P3: personalization core — event log + taste engine + section engine + agent pass + API + frontend

- db.py: guarded P3 tables (swipe_events/sections/section_items/taste_profile/
  agent_runs), one-time event seeding from swipes, append_event round math
- taste.py: deterministic taste engine (action x round x recency weights,
  n/(n+3) shrink, ramp w=min(.85,N/60), percentile norm, agent adjustments
  +/-10, points + source-labeled breakdown + tank bands)
- sections.py: compose/read/exhaust/forge — 2 wildcards + <=5 returns
  (<=2 nopes, surprising only) + remainder new, <=4/family, >=3 price
  bands w/ repair, returns maybe>like>nope, last-two-section exclusion,
  ondemand/strict modes
- agentpass.py: mock (deterministic) / live (OpenRouter, one retry) /
  fallback; strict payload schema; --print-summary/--dry-run
- api.py: GET /api/section, POST /api/section/forge, GET /api/trends,
  POST /api/agent/run, POST /api/prefs; P3 payload fields (points, tank,
  slot, round_next, points_breakdown); events stamped with section_id
- frontend: section buffer + progress pill, report screen + forge + mode
  toggle, WILDCARD/SECOND LOOK bands, tank gauges (list + dossier), dossier
  Why-this-rank, real Trends tab, /api/deck fallback for pre-P3 API, sw v2
- selfcheck: 9 new P3 checks (25/25 green)
This commit is contained in:
Torres
2026-11-10 23:16:32 -04:00
parent 8060852b83
commit 04463cadcd
8 changed files with 2504 additions and 26 deletions

View File

@@ -133,17 +133,80 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
.search::placeholder{color:#6f6f7a}
.toast{position:fixed;left:50%;bottom:150px;transform:translateX(-50%);background:#1d1d24;border:1px solid #2a2a33;color:#fff;padding:10px 16px;border-radius:12px;font-size:13px;z-index:80;opacity:0;transition:opacity .25s;pointer-events:none;white-space:nowrap;max-width:92vw;overflow:hidden;text-overflow:ellipsis}
.toast.on{opacity:1}
/* P3 additions */
.sect{margin-left:4px;font-size:12px;font-weight:650;color:var(--mut);white-space:nowrap}
.sect.hot{color:var(--accent1)}
.band{position:absolute;top:12px;left:12px;z-index:4;max-width:78%;font-size:11px;font-weight:650;letter-spacing:.4px;border-radius:999px;padding:4px 9px;pointer-events:none;line-height:1.35;user-select:none}
.band.wild{color:#ffb43a;background:rgba(255,180,58,.14);border:1px solid rgba(255,180,58,.35)}
.band.sl{color:rgba(255,255,255,.85);background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.22)}
.report{position:absolute;inset:6px 14px 2px;display:none;flex-direction:column;align-items:center;justify-content:center;gap:8px;border:1px dashed #2a2a33;border-radius:18px;color:var(--mut);text-align:center;padding:24px;font-size:13.5px;z-index:3}
.report.on{display:flex}
.report b{color:#fff;font-size:16px}
.rforge{margin-top:10px;border:0;border-radius:14px;background:linear-gradient(135deg,var(--accent1),var(--accent2));color:#fff;font-size:15px;font-weight:700;padding:12px 22px;cursor:pointer;box-shadow:0 8px 22px rgba(253,38,125,.3)}
.rforge:disabled{background:#23232b;color:#6f6f7a;box-shadow:none;cursor:default}
.rstatus{font-size:12.5px;min-height:16px}
.rmode{display:flex;align-items:center;gap:7px;font-size:12px;margin-top:6px;flex-wrap:wrap;justify-content:center}
.rmode .ron{color:#fff;border-bottom:1px solid #fff}
.rmode span{cursor:pointer;color:var(--mut)}
.rmode .sep{color:#4a4a55;cursor:default}
.rcap{flex-basis:100%;color:var(--mut);font-size:12px}
/* tank gauge (non-numeric) */
.tank{width:18px;height:22px;flex:none;display:block}
.tank.big{width:28px;height:34px}
.tank .tf{transition:y .25s ease,height .25s ease}
.rpt{display:flex;align-items:center;gap:7px}
/* dossier why-this-rank */
.drank{display:flex;gap:12px;align-items:flex-start;margin-top:10px;padding:10px;background:#15151b;border-radius:12px}
.drank .tankwrap{flex:none;padding-top:2px}
.dpts{font-size:17px;font-weight:700}
.dlines{font-size:12.5px;color:var(--mut);line-height:1.55}
.dlines .pos{color:#9ee8a8}
.dlines .neg{color:#f0a5ab}
.dfoot{margin-top:6px;font-size:11.5px;color:#7b7b88}
/* trends screen */
.trends{position:absolute;inset:0;display:none;flex-direction:column;background:var(--bg);z-index:50;padding-bottom:68px;overflow-y:auto}
.trends.on{display:flex}
.tsec{font-size:11px;font-weight:700;letter-spacing:1.2px;text-transform:uppercase;color:#7b7b88;margin:16px 18px 6px}
.tlead{font-size:18px;font-weight:700;margin:0 18px;line-height:1.35}
.tsub{font-size:12.5px;color:var(--mut);margin:4px 18px 0}
.tbullets{margin:0 18px;font-size:14px;color:#d7d7dd;line-height:1.6}
.tminis{display:flex;gap:10px;margin:0 18px}
.tmini{flex:1;background:#141419;border:1px solid #1f1f27;border-radius:12px;padding:12px 10px;text-align:center}
.tmv{font-size:19px;font-weight:800}
.tmk{font-size:10.5px;color:var(--mut);margin-top:4px;letter-spacing:.3px;text-transform:uppercase}
.tacts{margin:8px 18px 0;display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.tstatus{font-size:12.5px;color:var(--mut)}
.trow{display:flex;align-items:center;gap:8px;margin:12px 18px 0;font-size:13px;color:var(--mut)}
.trow .on{color:#fff;border-bottom:1px solid #fff}
.trow span{cursor:pointer}
.trow i{color:#4a4a55;font-style:normal;cursor:default}
.tmuted{font-size:12px;color:#6f6f7a;margin:10px 18px 20px}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand"><span class="flame"></span>Bike-Tinder</div>
<div class="pill" id="pill">—</div>
<div style="display:flex;align-items:center">
<div class="pill" id="pill">—</div>
<div class="sect" id="sect"></div>
</div>
</header>
<div class="stage" id="stage">
<div class="empty" id="empty"><b>You're all caught up.</b>New bikes arrive nightly — next import 08:30.<br>↺ brings the last card back.</div>
<div class="report" id="report">
<b>Section complete.</b>
<div id="repCounts"></div>
<div id="repSub">The file is digesting your strikes.</div>
<div id="repLine2"></div>
<button class="rforge" id="btnForge">Forge next 25</button>
<div class="rstatus" id="forgeStatus"></div>
<div class="rmode" id="modeRow">
<span id="modeOnd" class="on">on demand</span><i class="sep">⇄</i><span id="modeStr">strict</span>
<div class="rcap" id="strictCap" style="display:none">Waiting for the nightly read — next section after the agent runs.</div>
</div>
</div>
</div>
<div class="actions" id="actions">
@@ -169,6 +232,14 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
<div class="dtitle" id="dtitle"></div>
<div class="drow"><div class="dprice" id="dprice"></div><div class="dsub" id="dsub"></div></div>
<div class="dchips" id="dchips"></div>
<div class="drank" id="drank" style="display:none">
<div class="tankwrap" id="drankTank"></div>
<div style="flex:1;min-width:0">
<div class="dpts" id="dpts"></div>
<div class="dlines" id="dlines"></div>
<div class="dfoot" id="dfoot"></div>
</div>
</div>
<div class="dsec">The machine</div>
<div class="specs" id="dspecs"></div>
<div class="dsec">Seller's notes</div>
@@ -203,7 +274,30 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
<div class="mempty" id="mempty">No likes yet — swipe right on the deck.</div>
</div>
<div class="stub" id="stubTrends"><b>Trends — Phase 3</b>The deck learns your taste as you swipe.</div>
<div class="trends" id="trendsScreen">
<div class="lhead"><h1>Trends</h1></div>
<div class="tsec">Your read</div>
<div class="tlead" id="tLead">—</div>
<div class="tsub" id="tReadAt"></div>
<div class="tsub" id="tCold" style="display:none">Swipe ~10 more and the read sharpens.</div>
<div class="tsec" id="tLeanSec" style="display:none">Leanings</div>
<div class="tbullets" id="tLeanings"></div>
<div class="tsec">Stats</div>
<div class="tminis">
<div class="tmini"><div class="tmv" id="tmHit">—</div><div class="tmk">Hit rate</div></div>
<div class="tmini"><div class="tmv" id="tmRet">—</div><div class="tmk">Returns re-struck</div></div>
<div class="tmini"><div class="tmv" id="tmWild">—</div><div class="tmk">Wildcards hit</div></div>
</div>
<div class="tsec" id="tSinceSec" style="display:none">Since last read</div>
<div class="tsub" id="tSince" style="display:none"></div>
<div class="tsec">Actions</div>
<div class="tacts">
<button class="rforge" id="btnRunAgent" style="margin-top:0">Run agent now</button>
<div class="tstatus" id="runStatus"></div>
</div>
<div class="trow"><span>Forge:</span><span id="tOnd" class="on">on demand</span><i>⇄</i><span id="tStr">strict</span></div>
<div class="tmuted" id="tLastRun"></div>
</div>
</div>
<div class="toast" id="toast"></div>
@@ -216,8 +310,11 @@ const SC=.026, TY=16, DIM=.08; // per-depth step: scale, y-offset, dimming
let pile=[]; // top-first [{d,el}] — every card its own swipable object
let hist=[]; // undo history: full payloads
let dragEl=null, sx=0, sy=0, dx=0, dy=0, moved=false;
let buffer=[]; // deck feed from GET /api/deck (payloads)
let buffer=[]; // deck feed (payloads, pinned section order in P3)
let deckCursor=null, deckLoaded=false, deckLoading=false;
let section=null; // P3: latest GET /api/section body
let legacyMode=false; // true when the API has no /api/section (P2 API)
let forgeBusy=false, runBusy=false;
/* ---------- production wiring: API + retry queue + toast ---------- */
let toastTimer=null;
@@ -235,10 +332,10 @@ async function getJSON(url){
/* swipe persistence: optimistic, never waits; failures retry 2s/5s/10s then
every 15s while the tab lives. Last write per listing wins; the queue runs
serially so reorderings can't land out of sequence. */
const pend=new Map(); // listing_id -> {act, fails, warned}
const pend=new Map(); // listing_id -> {act, secId, fails, warned}
let qRunning=false, qTimer=null, qWarned=false;
function enqueue(listingId, act){ // act: 'like'|'nope'|'maybe'|null (delete)
pend.set(listingId,{act,fails:0});
function enqueue(listingId, act, secId=null){ // act: 'like'|'nope'|'maybe'|null (delete)
pend.set(listingId,{act,secId,fails:0});
scheduleQueue();
}
function queDelay(op){ return op.fails===1?2000:op.fails===2?5000:op.fails===3?10000:15000; }
@@ -258,7 +355,7 @@ async function runQueue(){
try{
const res= p.act==null
? await fetch('/api/swipe/'+id,{method:'DELETE'})
: await fetch('/api/swipe',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({listing_id:id,action:p.act})});
: await fetch('/api/swipe',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(p.secId?{listing_id:id,action:p.act,section_id:p.secId}:{listing_id:id,action:p.act})});
if(res.ok){ pend.delete(id); }
else { p.fails++; if(!qWarned){ qWarned=true; toast("Couldn't save — retrying"); } minDelay=Math.max(minDelay,queDelay(p)); }
}catch(e){
@@ -270,9 +367,9 @@ async function runQueue(){
if(pend.size){ qTimer=setTimeout(runQueue,Math.max(minDelay||15000,1000)); }
}
/* optimistic decision set for list/matches + deck commits share this */
function setDecision(id, act){
function setDecision(id, act, secId=null){
updateRowDecision(id, act); // optimistic paint
enqueue(id, act);
enqueue(id, act, secId);
}
/* ---------- payload -> display helpers ---------- */
@@ -305,6 +402,31 @@ function relSeen(fs){
const days=Math.floor((now-d)/86400000);
return days<=0?'Today':(days===1?'1 day ago':days+' days ago');
}
function relTime(ts){
if(!ts) return '—';
const d=new Date(ts), now=new Date();
if(isNaN(d)) return '—';
const sec=Math.max(0,Math.floor((now-d)/1000));
if(sec<60) return 'just now';
const min=Math.floor(sec/60);
if(min<60) return min+'m ago';
const hr=Math.floor(min/60);
if(hr<24) return hr+'h ago';
const days=Math.floor(hr/24);
return days===1?'1 day ago':days+' days ago';
}
/* P3: non-numeric tank gauge (filled per points, colored per band) */
const TANK_COLORS={like:'var(--like)',maybe:'var(--maybe)',nope:'var(--nope)'};
function tankSVG(tank,big){
const v= tank&&tank.value!=null?Math.max(0,Math.min(100,tank.value)):0;
const color= TANK_COLORS[tank&&tank.band]||'var(--maybe)';
const fillH=13.5*v/100, y=18-fillH;
return `<svg class="tank${big?' big':''}" viewBox="0 0 18 22" aria-hidden="true">`+
`<rect x="5" y="4.5" width="8" height="13.5" rx="4" fill="rgba(255,255,255,.12)"/>`+
`<rect x="7.4" y="5.6" width="3.2" height="2.2" rx="1.1" fill="rgba(255,255,255,.28)"/>`+
`<rect class="tf" x="6.4" y="${y}" width="5.2" height="${fillH}" rx="2.2" fill="${color}"/>`+
`</svg>`;
}
function ccFrom(it){
const m=((it.title||'')+' '+((it.desc||'').split(' [also listed:')[0])).match(/(\d[\d,]*)\s*cc/i);
return m?(fmtNum(m[1].replace(/,/g,''))+' cc'):null;
@@ -323,11 +445,20 @@ function setStamps(el,a,b,c){
el.querySelector('.stamp.nope').style.opacity=b;
el.querySelector('.stamp.maybe').style.opacity=c;
}
function bandHTML(item){ // P3 system bands — the ONLY card-face additions
if(item.slot==='wildcard') return `<div class="band wild">WILDCARD · maybe you&rsquo;ll like this one instead</div>`;
if(item.slot==='return'){
const verb= item.decision==='like'?'liked':item.decision==='maybe'?'maybed':item.decision==='nope'?'noped':'seen';
return `<div class="band sl">SECOND LOOK — you ${verb} this</div>`;
}
return '';
}
function cardNode(item){
const el=document.createElement('div');
el.className='card';
el.innerHTML=`${item.img?`<img class="photo" src="${item.img}" alt="" draggable="false">`:`<div class="nophoto">Photo pending — thumbnail backfill queued</div>`}
<div class="grad"></div>
${bandHTML(item)}
<div class="stamp like">LIKE</div>
<div class="stamp nope">NOPE</div>
<div class="stamp maybe">MAYBE</div>
@@ -376,8 +507,8 @@ function fillPile(){
}
relayer();
}
/* deck feed: cursor pages of 40; refill whenever the buffer thins */
async function loadDeck(){
/* deck feed: P3 sections (pinned order) with a legacy /api/deck fallback */
async function loadDeck(){ // legacy cursor feed (pre-P3 API)
if(deckLoading||deckLoaded) return;
deckLoading=true;
try{
@@ -390,10 +521,48 @@ async function loadDeck(){
deckCursor=res.next_cursor||null;
if(!deckCursor) deckLoaded=true;
}finally{ deckLoading=false; }
maybeRefill();
}
async function loadSection(){
if(deckLoading) return;
deckLoading=true;
try{
const res=await fetch('/api/section');
if(res.status===404){ // pre-P3 server: fall back to the deck feed
legacyMode=true;
deckLoading=false;
loadDeck();
return;
}
if(!res.ok){ setTimeout(()=>loadSection(),15000); return; }
const body=await res.json();
section=body;
const live=new Set([...pile.map(c=>c.d.id),...hist.map(h=>h.id),...buffer.map(b=>b.id)]);
const fresh=(body.items||[]).filter(it=>it.decision===null&&!live.has(it.id));
buffer.push(...fresh);
fillPile();
updateSectionUI(body);
}catch(e){ setTimeout(()=>loadSection(),15000); }
finally{ deckLoading=false; }
maybeRefill();
}
function maybeRefill(){
if(buffer.length<DEPTH&&deckCursor&&!deckLoaded) loadDeck();
if(!pile.length&&!buffer.length&&(deckLoaded||(!deckCursor&&!deckLoading))) $('empty').classList.add('on');
if(legacyMode){
if(buffer.length<DEPTH&&deckCursor&&!deckLoaded) loadDeck();
if(!pile.length&&!buffer.length&&(deckLoaded||(!deckCursor&&!deckLoading))) $('empty').classList.add('on');
return;
}
if(!pile.length&&!buffer.length&&!deckLoading){
if(section&&(section.exhausted||(section.progress&&section.progress.undecided===0))){
$('report').classList.add('on');
$('empty').classList.remove('on');
}else if(section){
$('empty').classList.remove('on'); $('report').classList.remove('on');
}
}else{
$('empty').classList.remove('on');
$('report').classList.remove('on');
}
}
/* ---------- docs/mockup core: commit / fly / undo — no lock ---------- */
@@ -401,7 +570,10 @@ function commit(el,dir){
if(!isTop(el)) return;
const t=pile.shift();
hist.push(t.d);
setDecision(t.d.id, dir==='maybe'?'maybe':dir); // optimistic persist
const act= dir==='maybe'?'maybe':dir;
setDecision(t.d.id, act, (!legacyMode&&section&&!section.exhausted)?section.section.id:null);
sectDecided++;
paintSect();
flyOut(el,dir);
fillPile(); relayer();
maybeRefill();
@@ -422,6 +594,8 @@ function undo(){
if(!hist.length) return;
const item=hist.pop();
setDecision(item.id, null); // DELETE through the queue
sectDecided=Math.max(0,sectDecided-1);
paintSect();
const entry=cardNode(item);
entry.el.style.transition='none';
entry.el.style.transform='translateY(-46px) scale(1.02)';
@@ -432,6 +606,7 @@ function undo(){
void entry.el.offsetWidth;
relayer();
$('empty').classList.remove('on');
$('report').classList.remove('on');
}
$('btnLike').onclick=()=>{ if(pile[0]) commit(pile[0].el,'like'); };
$('btnNope').onclick=()=>{ if(pile[0]) commit(pile[0].el,'nope'); };
@@ -493,9 +668,35 @@ function openDetail(data,ctx){
$('dspecs').innerHTML=rows.map(r=>`<div class="spec"><span class="k">${r[0]}</span><span class="v${(!r[1]||r[1]==='—')?' z':''}">${r[1]||'—'}</span></div>`).join('');
$('dnotes').textContent=(data.desc||'').split(' [also listed:')[0]||'';
$('dopen').href=data.url||'#';
fillRank(data); // P3 "Why this rank" (may be progressive)
$('detail').classList.add('on'); $('dback').classList.add('on');
$('dbody').scrollTop=0;
}
/* P3 dossier rank block: gauge + points + strongest ± lines + audit footer */
function fillRank(data){
if(!data||data.tank==null||data.tank.value==null){
$('drank').style.display='none';
return;
}
$('drank').style.display='flex';
$('drankTank').innerHTML=tankSVG(data.tank,true);
$('dpts').textContent=data.tank.value+'/100';
const lines=(data.points_breakdown||[]).slice()
.sort((a,b)=>Math.abs(b.value)-Math.abs(a.value)).slice(0,4);
$('dlines').innerHTML=lines.map(l=>{
const lbl= l.source==='agent'?('agent: '+l.label):l.label;
const n= l.value>=0?(' +'+l.value):(' '+l.value);
return `<div class="${l.value>=0?'pos':'neg'}">· ${lbl}${n}</div>`;
}).join('');
const ri= section&&section.read_info;
$('dfoot').textContent= ri?`from ${ri.events} strikes · read ${relTime(ri.profile_at)}`:'';
// list/matches payloads carry no breakdown — fill it on the quiet
if(!data.points_breakdown&&data.id&&!legacyMode){
getJSON('/api/listing/'+data.id).then(full=>{
if(full&&full.points_breakdown&&dCtx) fillRank(full);
});
}
}
function closeDetail(){ const d=$('detail'); d.style.transition=''; d.style.transform=''; d.classList.remove('on'); $('dback').classList.remove('on'); dCtx=null; }
$('dclose').onclick=closeDetail;
$('dclose').addEventListener('pointerdown',e=>e.stopPropagation());
@@ -547,7 +748,7 @@ function rowHTML(it){
<div class="row" data-i="${it.id}">
${thumbFor(it)}
<div class="rmain"><div class="rtitle"></div><div class="rsub"></div></div>
<div class="rright"><div class="rprice"></div>
<div class="rright"><div class="rpt">${it.tank?tankSVG(it.tank):''}<div class="rprice"></div></div>
<div class="rc" data-i="${it.id}">
<button class="rbtn like${on('like')?' on':''}" data-s="like">♥</button>
<button class="rbtn maybe${on('maybe')?' on':''}" data-s="maybe">★</button>
@@ -700,15 +901,122 @@ async function loadStats(){
}
}
/* ---------- P3 section UI: progress pill + report + forge + modes ---------- */
let sectDecided=0, sectTotal=0;
function paintSect(){
const t=$('sect');
if(legacyMode||!section){ t.textContent=''; return; }
t.textContent=`${sectDecided}/${sectTotal}`;
t.classList.toggle('hot',sectDecided>=sectTotal);
}
function paintMode(){
const m= section?section.mode:'ondemand';
$('modeOnd').classList.toggle('on',m==='ondemand');
$('modeStr').classList.toggle('on',m==='strict');
$('tOnd').classList.toggle('on',m==='ondemand');
$('tStr').classList.toggle('on',m==='strict');
$('strictCap').style.display= m==='strict'?'':'none';
const btn=$('btnForge');
if(m==='strict'){ btn.disabled=true; }
else if(!forgeBusy) btn.disabled=false;
}
function updateSectionUI(body){
sectDecided=body.progress.decided; sectTotal=body.progress.total;
paintSect();
paintMode();
const c=body.counts||{};
$('repCounts').innerHTML=`♥ ${c.likes||0} · ★ ${c.maybes||0} · ✕ ${c.nopes||0}`;
const hits=[];
if(c.restruck>0) hits.push('Second looks re-struck: '+c.restruck);
if(c.wildcard_hits>0) hits.push('Wildcards that hit: '+c.wildcard_hits);
$('repLine2').textContent=hits.join(' · ');
}
async function setMode(m){
const res=await fetch('/api/prefs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({key:'forge_mode',value:m})}).catch(()=>null);
if(res&&res.ok){ if(section) section.mode=m; paintMode(); }
}
$('modeOnd').onclick=()=>setMode('ondemand');
$('modeStr').onclick=()=>setMode('strict');
$('btnForge').onclick=async()=>{
if(forgeBusy||!section) return;
forgeBusy=true;
const btn=$('btnForge'); btn.disabled=true;
$('forgeStatus').textContent='The agent is reading your strikes…';
try{
const res=await fetch('/api/section/forge',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});
const body=await res.json();
if(res.ok){
$('forgeStatus').textContent= body.note&&body.note.indexOf('fallback')>=0
?'Agent offline — forging on the last read.':'';
section=body;
buffer.length=0;
const fresh=(body.items||[]).filter(it=>it.decision===null);
buffer.push(...fresh);
fillPile();
updateSectionUI(body);
if(pile.length){ $('report').classList.remove('on'); }
}else{
$('forgeStatus').textContent= body.detail||'Forge failed';
paintMode();
}
}catch(e){ $('forgeStatus').textContent='Offline — retrying'; }
forgeBusy=false;
paintMode();
};
/* ---------- P3 trends tab ---------- */
function fmtPct(f){ return f==null?'—':((Math.round(f*1000)/10)+'%'); }
async function fetchTrends(){
const t=await getJSON('/api/trends');
if(!t) return;
const p=t.profile;
$('tLead').textContent= p?p.lead:'—';
$('tReadAt').textContent= p?('updated '+relTime(p.created_at)):'';
$('tCold').style.display= p?'none':'';
$('tLeanSec').style.display= p&&p.leanings&&p.leanings.length?'':'none';
$('tLeanings').innerHTML= ((p&&p.leanings)||[]).map(x=>`<div>· ${x}</div>`).join('');
const s=t.stats||{};
$('tmHit').textContent= fmtPct(s.hit_rate);
$('tmRet').textContent= s.returns_re_struck??'0';
$('tmWild').textContent= s.wildcards_hit??'0';
const since= (p&&p.changes&&p.changes[0])||null;
$('tSinceSec').style.display= since?'':'none';
$('tSince').style.display= since?'':'none';
$('tSince').textContent= since||'';
const lr=t.last_run;
$('tLastRun').textContent= lr&&lr.ok
?`Last read ${relTime(lr.finished_at)} · ${lr.model||'—'}`
:(lr?`Last run failed (${lr.source||'?'}) — will retry`:'Last read —');
if(section) section.mode=t.forge_mode;
paintMode();
}
$('btnRunAgent').onclick=async()=>{
if(runBusy) return;
runBusy=true;
$('runStatus').textContent='Reading your strikes…';
const res=await fetch('/api/agent/run',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'}).catch(()=>null);
if(res&&res.ok){
const b=await res.json();
$('runStatus').textContent= b.source==='fallback'?'Agent offline — ran on the last read':'Done — the next read uses it.';
}else{
$('runStatus').textContent="Couldn't run — see the read above.";
}
runBusy=false;
fetchTrends();
};
$('tOnd').onclick=()=>setMode('ondemand');
$('tStr').onclick=()=>setMode('strict');
/* ---------- tabs ---------- */
document.querySelectorAll('.tab').forEach(t=>t.onclick=()=>{
const name=t.dataset.tab;
document.querySelectorAll('.tab').forEach(x=>x.classList.toggle('on',x===t));
$('listScreen').classList.toggle('on',name==='list');
$('matchesScreen').classList.toggle('on',name==='matches');
$('stubTrends').classList.toggle('on',name==='trends');
$('trendsScreen').classList.toggle('on',name==='trends');
if(name==='list') fetchList(); // fresh decisions every visit
else if(name==='matches') fetchMatches();
else if(name==='trends') fetchTrends();
});
/* ---------- desktop keyboard arrows (DESIGN.md: v1 frontend) ---------- */
@@ -722,7 +1030,7 @@ document.addEventListener('keydown',e=>{
/* ---------- boot ---------- */
loadStats();
loadDeck();
loadSection();
/* PWA */
if('serviceWorker' in navigator && (location.protocol==='https:'||location.hostname==='localhost'||location.hostname==='127.0.0.1')){

View File

@@ -6,7 +6,7 @@
offline once seen).
- Everything else (shell/navigation): network-first, fall back to cache.
*/
const VERSION = 'bike-tinder-v1';
const VERSION = 'bike-tinder-v2';
const SHELL = [
'/',
'/manifest.json',