Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files80 unmodified lines81828384858687888927 unmodified lines1171181191201211226 unmodified lines1291301311321331341351367 unmodified lines14414514614714814915013 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871886 unmodified lines19519619719819920020117 unmodified lines2192202212222232242253 unmodified lines2292302312322332342358 unmodified lines24424524624724824925013 unmodified lines26426526626726826984 unmodified lines3543553563573583593609 unmodified lines37037137237337437537619 unmodified lines39639739839940040140240340440540640740840963 unmodified lines47347447547647747847948048148248348448548612 unmodified lines49950050150250350450523 unmodified lines52953053153253353453527 unmodified lines5635645655665675685695705 unmodified lines57657757857958058158258358483 unmodified lines66866967067167267367467567667767867968016 unmodified lines69769869970070170270368 unmodified lines77277377477577677777877978078178278378478578678778878979079179279379479519 unmodified lines81581681781881982010 unmodified lines8318328338348358368373 unmodified lines8418428438448458468471 unmodified line8498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878 unmodified lines8968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509512 unmodified lines9549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210236 unmodified lines1030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210532 unmodified lines1056105710581059106010611062106310641065106610671068106910701071107210731074107510761 unmodified line1078107910801081108210831084108510861087108843 unmodified lines113211331134113511361137113898 unmodified lines12371238123912401241124212434 unmodified lines124812491250125112521253125480 unmodified linesfont-family: inherit; font-size: 0.78rem; font-weight: 600;color: var(--text-dim); background: transparent; cursor: pointer;transition: all 0.2s;}.tab-btn:hover { color: var(--text); }.tab-btn.active { background: var(--indigo); color: #fff; box-shadow: 0 2px 12px var(--indigo-glow); }.tab-content { display: none; }.tab-content.active { display: block; }27 unmodified lines.stat-label { font-size: 0.6rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px; color: var(--text-dim); margin-bottom: 4px; }.stat-value { font-size: 1.5rem; font-weight: 800; }/* ββ Toast ββ */.toast-container { position: fixed; bottom: 20px; right: 20px; z-index: 1000; display: flex; flex-direction: column; gap: 6px; }.toast {6 unmodified lines@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }/* ββββββββββββββββββββββββ ARENA TAB ββββββββββββββββββββββββ *//* Agent icons */.agent-icon {width: 48px; height: 48px; border-radius: 14px;display: grid; place-items: center; font-size: 22px;7 unmodified lines.agent-label.investigator { color: var(--indigo); }.agent-label.auditor { color: var(--amber); }/* Phase bar */.phase-bar {display: flex; align-items: center; gap: 0; margin-bottom: 20px;background: var(--surface); border: 1px solid var(--border);13 unmodified lines.phase-step.done-phase { color: var(--text-dim); }.phase-arrow { color: var(--text-muted); font-size: 0.7rem; margin: 0 4px; }/* Arena controls */.arena-controls {display: flex; gap: 10px; margin-bottom: 18px; flex-wrap: wrap; align-items: center;}3 unmodified linesborder: 1px solid rgba(148,163,184,0.35);}.arena-controls select option { background: #0f172a; color: #f1f5f9; }/* Arena stats */.arena-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; margin-bottom: 18px; }/* Arena main grid */.arena-main { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; margin-bottom: 16px; }@media (max-width: 1024px) { .arena-main { grid-template-columns: 1fr; } }/* Agent panel header */.agent-hdr { display: flex; align-items: center; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--border); }.agent-hdr-info { flex: 1; }.agent-name { font-size: 0.85rem; font-weight: 700; }6 unmodified lines.reward-badge.neg { background: var(--red-glow); color: var(--red); }.reward-badge.zero { background: var(--surface); color: var(--text-dim); border: 1px solid var(--border); }/* Timeline / trace */.trace-timeline {max-height: 320px; overflow-y: auto; padding: 12px 16px;font-size: 0.72rem;17 unmodified lines.trace-reward.pos { color: var(--green); }.trace-reward.neg { color: var(--red); }/* Reward chart */.chart-container {background: var(--surface); border: 1px solid var(--border);border-radius: var(--radius); padding: 16px 20px; margin-bottom: 16px;3 unmodified lines.chart-legend-item { display: flex; align-items: center; gap: 6px; font-size: 0.65rem; color: var(--text-dim); }.chart-legend-dot { width: 8px; height: 8px; border-radius: 2px; }/* Queue visualization */.queue-grid { display: flex; flex-wrap: wrap; gap: 6px; }.q-chip {padding: 6px 12px; border-radius: 6px; font-size: 0.7rem; font-weight: 600;8 unmodified lines.q-chip.proposed { border-color: var(--amber); color: var(--amber); }.q-dot { width: 6px; height: 6px; border-radius: 50%; }/* Audit report */.audit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }@media (max-width: 768px) { .audit-grid { grid-template-columns: 1fr; } }.flag-entry {13 unmodified lines.severity-fill.med { background: var(--amber); }.severity-fill.high { background: var(--red); }/* ββββββββββββββββββββββββ PLAYGROUND TAB ββββββββββββββββββββββββ */.pg-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; margin-bottom: 16px; }.pg-grid { display: grid; grid-template-columns: 1fr 360px; gap: 16px; }84 unmodified lines.score-pill.mid { background: var(--amber-glow); color: var(--amber); }.score-pill.low { background: var(--red-glow); color: var(--red); }/* Architecture diagram */.arch-diagram {display: flex; align-items: center; justify-content: center; gap: 24px;padding: 28px 20px; flex-wrap: wrap;9 unmodified lines.arch-node-name { font-size: 0.75rem; font-weight: 700; }.arch-node-desc { font-size: 0.6rem; color: var(--text-dim); line-height: 1.3; }/* Footer */footer {margin-top: 28px; text-align: center; padding: 16px;font-size: 0.65rem; color: var(--text-muted); border-top: 1px solid var(--border);19 unmodified lines</header><div class="tab-bar"><button class="tab-btn active" data-tab="arena">⚔ Arena</button><button class="tab-btn" data-tab="playground">🔍 Playground</button><button class="tab-btn" data-tab="results">📈 Results</button></div><!-- ββββββββββββββββββββββββ ARENA TAB ββββββββββββββββββββββββ --><div class="tab-content active" id="tab-arena"><!-- Architecture overview --><div class="panel" style="margin-bottom:18px"><div class="panel-body">63 unmodified lines<div class="stat-card"><div class="stat-label">End Reason</div><div class="stat-value" id="ar-reason" style="font-size:0.85rem;color:var(--text-dim)">-</div></div></div><!-- Reward chart --><div class="chart-container"><div class="chart-title">Agent Reward Trajectories</div><div id="arena-chart" style="width:100%;height:160px;"></div><div class="chart-legend"><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--red)"></div>Fraudster</div><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--indigo)"></div>Investigator</div><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--amber)"></div>Auditor</div></div></div>12 unmodified lines<div class="reward-badge zero" id="ar-f-reward">0.00</div></div><div class="panel-body"><div id="ar-f-actions" style="font-size:0.72rem;color:var(--text-dim)">Run a match to see fraudster actions.</div></div></div>23 unmodified lines<div class="reward-badge zero" id="ar-i-reward">0.00</div></div><div class="panel-body"><div id="ar-i-actions" style="font-size:0.72rem;color:var(--text-dim)">Run a match to see investigator actions.</div></div></div></div>27 unmodified lines<!-- ββββββββββββββββββββββββ PLAYGROUND TAB ββββββββββββββββββββββββ --><div class="tab-content" id="tab-playground"><div style="margin-bottom:16px;padding:14px 18px;border-radius:var(--radius);background:linear-gradient(135deg,rgba(99,102,241,0.06),rgba(6,182,212,0.04));border:1px solid rgba(99,102,241,0.2);font-size:0.78rem;line-height:1.5;color:var(--text-dim)"><strong style="color:var(--text)">Single-agent investigator playground.</strong> Choose a task, reset, then investigate ads and render verdicts under an action budget. This is the original Round 1 interface.</div><div class="pg-stats">5 unmodified lines<div class="stat-card"><div class="stat-label">Cum. reward</div><div class="stat-value" id="st-cum">-</div></div></div><div class="chart-container" style="margin-bottom:16px"><div class="chart-title">Cumulative Reward</div><div id="pg-chart" style="width:100%;height:100px;"></div></div><div style="display:flex;gap:10px;margin-bottom:18px;flex-wrap:wrap;align-items:center">83 unmodified lines<!-- ββββββββββββββββββββββββ RESULTS TAB ββββββββββββββββββββββββ --><div class="tab-content" id="tab-results"><div style="margin-bottom:20px;padding:16px 20px;border-radius:var(--radius);background:linear-gradient(135deg,rgba(34,197,94,0.06),rgba(6,182,212,0.04));border:1px solid rgba(34,197,94,0.2);font-size:0.8rem;line-height:1.6;color:var(--text-dim)"><strong style="color:var(--text)">Training overview.</strong>CounterFeint trains a small <code style="color:var(--cyan)">Qwen3-0.6B</code> Investigator via <strong style="color:var(--green)">GRPO</strong> (Group Relative Policy Optimization) against a frozen <code style="color:var(--red)">llama3.1:8b</code> Fraudster β a <strong>13×</strong> parameter asymmetry. The Auditor is deterministic (rule-based scorecards) to keep the reward signal reproducible.</div><div class="results-grid"><!-- Baseline table --><div class="panel"><div class="panel-hdr"><span class="panel-title">Baseline Scores (pre-training)</span></div><div class="panel-body">16 unmodified lines</div></div><!-- Reward design --><div class="panel"><div class="panel-hdr"><span class="panel-title">Reward Design</span></div><div class="panel-body">68 unmodified lines</div></div><!-- Run a live demo to see results --><div class="panel" style="margin-top:16px"><div class="panel-hdr"><span class="panel-title">📈 Live Match Reward Curves</span><button class="btn btn-primary" id="btn-results-demo" style="padding:6px 14px;font-size:0.68rem">Run Demo Match</button></div><div class="panel-body"><div id="results-chart" style="width:100%;height:180px;margin-bottom:12px"><div style="color:var(--text-dim);font-size:0.78rem;text-align:center;padding:40px">Click "Run Demo Match" to generate live reward curves.</div></div><div class="chart-legend" id="results-legend" style="display:none"><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--red)"></div>Fraudster</div><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--indigo)"></div>Investigator</div><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--amber)"></div>Auditor</div></div><div id="results-summary" style="margin-top:14px"></div></div></div></div><footer>19 unmodified linesc.appendChild(t);setTimeout(() => t.remove(), 3200);}/* βββββββββββββββββββ Tab switching βββββββββββββββββββ */document.querySelectorAll('.tab-btn').forEach(btn => {10 unmodified linesconst el = typeof container === 'string' ? document.getElementById(container) : container;const w = options.width || el.clientWidth || 600;const h = options.height || el.clientHeight || 160;const pad = { t: 16, r: 16, b: 24, l: 44 };const cw = w - pad.l - pad.r;const ch = h - pad.t - pad.b;3 unmodified lineslet mn = Math.min(0, ...allVals), mx = Math.max(0, ...allVals);if (mn === mx) { mn -= 0.1; mx += 0.1; }const maxLen = Math.max(...datasets.map(ds => ds.data.length));function sx(i) { return pad.l + (maxLen <= 1 ? cw / 2 : (i / (maxLen - 1)) * cw); }function sy(v) { return pad.t + ch - ((v - mn) / (mx - mn)) * ch; }1 unmodified linelet svg = `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" preserveAspectRatio="xMidYMid meet" style="display:block;width:100%;height:100%">`;svg += `<rect width="${w}" height="${h}" fill="rgba(0,0,0,0.2)" rx="8"/>`;const gridLines = 4;for (let g = 0; g <= gridLines; g++) {const yy = pad.t + (g / gridLines) * ch;const val = mx - (g / gridLines) * (mx - mn);svg += `<line x1="${pad.l}" y1="${yy}" x2="${w - pad.r}" y2="${yy}" stroke="rgba(255,255,255,0.06)" stroke-width="1"/>`;svg += `<text x="${pad.l - 6}" y="${yy + 3}" fill="rgba(255,255,255,0.25)" font-size="9" text-anchor="end" font-family="Inter,sans-serif">${val.toFixed(2)}</text>`;}const zeroY = sy(0);if (zeroY > pad.t && zeroY < h - pad.b) {svg += `<line x1="${pad.l}" y1="${zeroY}" x2="${w - pad.r}" y2="${zeroY}" stroke="rgba(255,255,255,0.12)" stroke-width="1" stroke-dasharray="4,3"/>`;}datasets.forEach(ds => {if (!ds.data.length) return;const pts = ds.data.map((v, i) => `${sx(i)},${sy(v)}`).join(' ');const gradId = 'g' + Math.random().toString(36).slice(2, 8);const lastY = sy(ds.data[ds.data.length - 1]);svg += `<defs><linearGradient id="${gradId}" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="${ds.color}" stop-opacity="0.25"/><stop offset="100%" stop-color="${ds.color}" stop-opacity="0"/></linearGradient></defs>`;const areaPath = `M${sx(0)},${sy(ds.data[0])} ` + ds.data.map((v, i) => `L${sx(i)},${sy(v)}`).join(' ') + ` L${sx(ds.data.length - 1)},${h - pad.b} L${sx(0)},${h - pad.b} Z`;svg += `<path d="${areaPath}" fill="url(#${gradId})"/>`;svg += `<polyline fill="none" stroke="${ds.color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" points="${pts}"/>`;svg += `<circle cx="${sx(ds.data.length - 1)}" cy="${lastY}" r="3.5" fill="${ds.color}"/>`;svg += `<text x="${sx(ds.data.length - 1) + 6}" y="${lastY + 3}" fill="${ds.color}" font-size="9" font-weight="700" font-family="Inter,sans-serif">${ds.data[ds.data.length - 1].toFixed(2)}</text>`;});svg += `<text x="${w / 2}" y="${h - 4}" fill="rgba(255,255,255,0.2)" font-size="9" text-anchor="middle" font-family="Inter,sans-serif">steps</text>`;svg += '</svg>';el.innerHTML = svg;}/* βββββββββββββββββββ ARENA TAB βββββββββββββββββββ */let arenaData = null;function updatePhaseBar(phase) {['ph-fraudster','ph-investigator','ph-auditor','ph-done'].forEach(id => {8 unmodified linesif (map[phase]) document.getElementById(map[phase]).classList.add('active');}function rewardBadge(value) {const cls = value > 0.001 ? 'pos' : value < -0.001 ? 'neg' : 'zero';return `<div class="reward-badge ${cls}">${value >= 0 ? '+' : ''}${value.toFixed(2)}</div>`;}function renderArenaMatch(data) {arenaData = data;const fs = data.final_state;const trace = data.trace;document.getElementById('ar-round').textContent = fs.round_number || '-';document.getElementById('ar-steps').textContent = data.total_steps;document.getElementById('ar-proposals').textContent = fs.proposals_used || 0;document.getElementById('ar-grader').textContent = fs.grader_score != null ? fs.grader_score.toFixed(3) : '-';document.getElementById('ar-reason').textContent = fs.end_reason || '-';document.getElementById('ar-f-reward').outerHTML = rewardBadge(data.final_rewards.fraudster);document.getElementById('ar-i-reward').outerHTML = rewardBadge(data.final_rewards.investigator);document.getElementById('ar-a-reward').outerHTML = rewardBadge(data.final_rewards.auditor);updatePhaseBar('done');const fActions = trace.filter(t => t.role === 'fraudster');const iActions = trace.filter(t => t.role === 'investigator');const aActions = trace.filter(t => t.role === 'auditor');function renderActionList(actions, container, color) {const el = document.getElementById(container);if (!actions.length) { el.innerHTML = '<span style="color:var(--text-dim)">No actions.</span>'; return; }el.innerHTML = actions.map(a => {const rCls = a.reward > 0 ? 'color:var(--green)' : a.reward < 0 ? 'color:var(--red)' : 'color:var(--text-muted)';return `<div style="padding:6px 0;border-bottom:1px solid var(--border);font-size:0.72rem"><span style="color:${color};font-weight:600">${esc(a.action_type)}</span> <span style="color:var(--text-dim)">${esc(a.detail)}</span> <span style="${rCls};font-weight:600;float:right">${a.reward >= 0 ? '+' : ''}${a.reward.toFixed(3)}</span></div>`;}).join('');}renderActionList(fActions, 'ar-f-actions', 'var(--red)');renderActionList(iActions, 'ar-i-actions', 'var(--indigo)');// Queueconst verdictMap = {};const proposedAds = new Set();trace.forEach(t => {if (t.role === 'investigator' && t.action_type === 'verdict') {const m = t.detail.match(/Verdict on (ad_\d+): (\w+)/);if (m) verdictMap[m[1]] = m[2];}if (t.role === 'fraudster' && t.action_type === 'propose_ad') {const m = t.feedback.match(/ad_id=(ad_\d+)/);if (m) proposedAds.add(m[1]);}});const allAds = [...new Set([...Object.keys(verdictMap), ...proposedAds])].sort();const qEl = document.getElementById('ar-queue');if (allAds.length) {2 unmodified linesconst isProp = proposedAds.has(id);const cls = v === 'approve' ? 'approved' : v === 'reject' ? 'rejected' : v === 'escalate' ? 'escalated' : isProp ? 'proposed' : 'pending';const dotColor = cls === 'approved' ? 'var(--green)' : cls === 'rejected' ? 'var(--red)' : cls === 'escalated' ? 'var(--cyan)' : cls === 'proposed' ? 'var(--amber)' : 'var(--text-muted)';return `<div class="q-chip ${cls}"><span class="q-dot" style="background:${dotColor}"></span>${id}${isProp ? ' β ' : ''}</div>`;}).join('');document.getElementById('ar-q-count').textContent = allAds.length + ' ads';}// Auditorconst auditBody = document.getElementById('ar-audit-body');if (fs.audit_report) {const ar = fs.audit_report;const ta = ar.track_a_flags || [];const tb = ar.track_b_flags || [];let html = '<div class="audit-grid">';html += '<div>';html += `<div style="font-size:0.65rem;font-weight:700;text-transform:uppercase;color:var(--indigo);margin-bottom:8px">Track A β Investigator Audit (score: ${(ar.investigator_audit_score || 0).toFixed(2)})</div>`;if (ta.length) {ta.forEach(f => {const sev = f.severity || 0.5;const sevCls = sev >= 0.7 ? 'high' : sev >= 0.4 ? 'med' : 'low';html += `<div class="flag-entry track-a"><div class="flag-type">${esc(f.flag_type || 'flag')} ${f.target_ad_id ? '(' + esc(f.target_ad_id) + ')' : ''}</div><div style="font-size:0.65rem;color:var(--text-dim);margin-top:2px">${esc((f.note || '').slice(0, 100))}</div><div class="severity-bar"><div class="severity-fill ${sevCls}" style="width:${sev * 100}%"></div></div></div>`;});} else {html += '<div style="font-size:0.72rem;color:var(--text-dim)">No Track A flags.</div>';}html += '</div><div>';html += `<div style="font-size:0.65rem;font-weight:700;text-transform:uppercase;color:var(--amber);margin-bottom:8px">Track B β Fraudster Plausibility (score: ${(ar.fraudster_plausibility_score || 0).toFixed(2)})</div>`;if (tb.length) {tb.forEach(f => {const sev = f.severity || 0.5;const sevCls = sev >= 0.7 ? 'high' : sev >= 0.4 ? 'med' : 'low';html += `<div class="flag-entry track-b"><div class="flag-type">${esc(f.flag_type || 'flag')} ${f.target_ad_id ? '(' + esc(f.target_ad_id) + ')' : ''}</div><div style="font-size:0.65rem;color:var(--text-dim);margin-top:2px">${esc((f.note || '').slice(0, 100))}</div><div class="severity-bar"><div class="severity-fill ${sevCls}" style="width:${sev * 100}%"></div></div></div>`;});} else {html += '<div style="font-size:0.72rem;color:var(--text-dim)">No Track B flags.</div>';}html += '</div></div>';auditBody.innerHTML = html;}// Timelineconst timeline = document.getElementById('ar-timeline');timeline.innerHTML = '';trace.forEach(t => {const rCls = t.reward > 0 ? 'pos' : t.reward < 0 ? 'neg' : '';const entry = document.createElement('div');entry.className = 'trace-entry';entry.innerHTML = `<div class="trace-dot ${t.role}"></div><div class="trace-text"><strong>${t.role}</strong> ${esc(t.detail)}</div><div class="trace-reward ${rCls}">${t.reward >= 0 ? '+' : ''}${t.reward.toFixed(3)}</div>`;timeline.appendChild(entry);});document.getElementById('ar-trace-count').textContent = trace.length + ' events';// Reward chartconst traj = data.reward_trajectories;renderMultiChart('arena-chart', [{ data: traj.fraudster || [], color: '#ef4444', label: 'Fraudster' },{ data: traj.investigator || [], color: '#6366f1', label: 'Investigator' },{ data: traj.auditor || [], color: '#f59e0b', label: 'Auditor' },]);}document.getElementById('btn-auto').onclick = async () => {const btn = document.getElementById('btn-auto');const status = document.getElementById('arena-status');btn.disabled = true;status.textContent = 'Running match...';status.style.color = 'var(--amber)';try {6 unmodified lines});const data = await res.json();if (!res.ok) throw new Error(data.detail || res.statusText);renderArenaMatch(data);status.textContent = `Match complete β ${data.total_steps} steps`;status.style.color = 'var(--green)';toast('Match completed successfully', 'success');} catch (e) {status.textContent = 'Error: ' + e.message;status.style.color = 'var(--red)';toast(e.message, 'error');} finally {btn.disabled = false;}};/* Results tab demo */document.getElementById('btn-results-demo').onclick = async () => {const btn = document.getElementById('btn-results-demo');btn.disabled = true;btn.textContent = 'Running...';try {const res = await fetch(API + '/arena/api/auto', {method: 'POST',2 unmodified lines});const data = await res.json();if (!res.ok) throw new Error(data.detail || res.statusText);const traj = data.reward_trajectories;renderMultiChart('results-chart', [{ data: traj.fraudster || [], color: '#ef4444' },{ data: traj.investigator || [], color: '#6366f1' },{ data: traj.auditor || [], color: '#f59e0b' },], { height: 180 });document.getElementById('results-legend').style.display = 'flex';const fs = data.final_state;document.getElementById('results-summary').innerHTML = `<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px"><div class="stat-card"><div class="stat-label">Grader Score</div><div class="stat-value" style="color:var(--green)">${fs.grader_score != null ? fs.grader_score.toFixed(3) : '-'}</div></div><div class="stat-card"><div class="stat-label">Fraudster Reward</div><div class="stat-value" style="color:var(--red)">${data.final_rewards.fraudster.toFixed(3)}</div></div><div class="stat-card"><div class="stat-label">Investigator Reward</div><div class="stat-value" style="color:var(--indigo)">${data.final_rewards.investigator.toFixed(3)}</div></div><div class="stat-card"><div class="stat-label">Auditor Reward</div><div class="stat-value" style="color:var(--amber)">${data.final_rewards.auditor.toFixed(3)}</div></div><div class="stat-card"><div class="stat-label">Total Steps</div><div class="stat-value">${data.total_steps}</div></div><div class="stat-card"><div class="stat-label">End Reason</div><div class="stat-value" style="font-size:0.85rem;color:var(--text-dim)">${fs.end_reason || '-'}</div></div></div>`;1 unmodified line} catch (e) {toast(e.message, 'error');} finally {btn.disabled = false;btn.textContent = 'Run Demo Match';}};/* βββββββββββββββββββ PLAYGROUND TAB βββββββββββββββββββ */const TARGETS = ['advertiser_history','landing_page','payment_method','targeting_overlap','campaign_structure','policy_classifier'];43 unmodified linesreturn;}const col = pgCumHistory[pgCumHistory.length - 1] >= 0 ? '#22c55e' : '#ef4444';renderMultiChart('pg-chart', [{ data: pgCumHistory, color: col }], { height: 100 });}function renderPgQueue(obs) {const ads = obs.available_ads || [];98 unmodified lines};document.getElementById('btn-step').onclick = async () => {if (pgDone) { toast('Episode finished β reset first', 'error'); return; }const t = document.getElementById('act-type').value;const ad = document.getElementById('act-ad').value;const body = { action_type: t, ad_id: ad };4 unmodified linespgVerdicts[ad] = { verdict: body.verdict, confidence: body.confidence };} else if (t === 'link_accounts') {body.linked_ad_id = document.getElementById('act-linked').value;body.link_reason = document.getElementById('act-reason').value.trim() || 'β';}try {const res = await fetch(API + '/investigate/api/step', {80 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611727 unmodified lines1451461471481491501511521531541551561571581591601616 unmodified lines1681691701711721737 unmodified lines18118218318418518613 unmodified lines2002012022032042053 unmodified lines2092102112122132142152162172186 unmodified lines22522622722822923017 unmodified lines2482492502512522533 unmodified lines2572582592602612628 unmodified lines27127227327427527613 unmodified lines29029129229329429529629729884 unmodified lines3833843853863873889 unmodified lines39839940040140240319 unmodified lines42342442542642742842943043143243343443543643743843944044144263 unmodified lines50650750850951051151251351451551651751812 unmodified lines53153253353453553653723 unmodified lines56156256356456556656727 unmodified lines5955965975985996006016026036045 unmodified lines61061161261361461561661761883 unmodified lines70270370470570670770870971071171271371416 unmodified lines73173273373473573668 unmodified lines80580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684719 unmodified lines86786886987087187287310 unmodified lines8848858868878888898903 unmodified lines8948958968978988999009019029031 unmodified line9059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529538 unmodified lines96296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110122 unmodified lines101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111426 unmodified lines11491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011912 unmodified lines1194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261 unmodified line1228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127143 unmodified lines131513161317131813191320132198 unmodified lines14201421142214231424142514264 unmodified lines143114321433143414351436143780 unmodified linesfont-family: inherit; font-size: 0.78rem; font-weight: 600;color: var(--text-dim); background: transparent; cursor: pointer;transition: all 0.2s;position: relative;}.tab-btn:hover { color: var(--text); }.tab-btn.active { background: var(--indigo); color: #fff; box-shadow: 0 2px 12px var(--indigo-glow); }/* Tab tooltips */.tab-btn[data-tooltip]::after {content: attr(data-tooltip);position: absolute;bottom: calc(100% + 10px);left: 50%;transform: translateX(-50%);padding: 10px 16px;background: rgba(15,23,42,0.96);border: 1px solid rgba(255,255,255,0.1);border-radius: 10px;font-size: 0.68rem;font-weight: 400;color: var(--text-dim);white-space: normal;width: 240px;text-align: center;line-height: 1.5;pointer-events: none;opacity: 0;transition: opacity 0.2s ease;z-index: 100;box-shadow: 0 8px 24px rgba(0,0,0,0.4);}.tab-btn[data-tooltip]:hover::after { opacity: 1; }.tab-content { display: none; }.tab-content.active { display: block; }27 unmodified lines.stat-label { font-size: 0.6rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.8px; color: var(--text-dim); margin-bottom: 4px; }.stat-value { font-size: 1.5rem; font-weight: 800; }/* Guidance banners */.guide-banner {margin-bottom: 18px; padding: 14px 20px; border-radius: var(--radius);font-size: 0.78rem; line-height: 1.6; color: var(--text-dim);}.guide-banner strong { color: var(--text); }.guide-banner code { color: var(--cyan); font-size: 0.74rem; }.guide-banner.arena { background: linear-gradient(135deg,rgba(239,68,68,0.04),rgba(99,102,241,0.05)); border: 1px solid rgba(99,102,241,0.15); }.guide-banner.playground { background: linear-gradient(135deg,rgba(99,102,241,0.06),rgba(6,182,212,0.04)); border: 1px solid rgba(99,102,241,0.2); }.guide-banner.results { background: linear-gradient(135deg,rgba(34,197,94,0.06),rgba(6,182,212,0.04)); border: 1px solid rgba(34,197,94,0.2); }/* ββ Toast ββ */.toast-container { position: fixed; bottom: 20px; right: 20px; z-index: 1000; display: flex; flex-direction: column; gap: 6px; }.toast {6 unmodified lines@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }/* ββββββββββββββββββββββββ ARENA TAB ββββββββββββββββββββββββ */.agent-icon {width: 48px; height: 48px; border-radius: 14px;display: grid; place-items: center; font-size: 22px;7 unmodified lines.agent-label.investigator { color: var(--indigo); }.agent-label.auditor { color: var(--amber); }.phase-bar {display: flex; align-items: center; gap: 0; margin-bottom: 20px;background: var(--surface); border: 1px solid var(--border);13 unmodified lines.phase-step.done-phase { color: var(--text-dim); }.phase-arrow { color: var(--text-muted); font-size: 0.7rem; margin: 0 4px; }.arena-controls {display: flex; gap: 10px; margin-bottom: 18px; flex-wrap: wrap; align-items: center;}3 unmodified linesborder: 1px solid rgba(148,163,184,0.35);}.arena-controls select option { background: #0f172a; color: #f1f5f9; }.arena-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; margin-bottom: 18px; }.arena-main { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; margin-bottom: 16px; }@media (max-width: 1024px) { .arena-main { grid-template-columns: 1fr; } }.agent-hdr { display: flex; align-items: center; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--border); }.agent-hdr-info { flex: 1; }.agent-name { font-size: 0.85rem; font-weight: 700; }6 unmodified lines.reward-badge.neg { background: var(--red-glow); color: var(--red); }.reward-badge.zero { background: var(--surface); color: var(--text-dim); border: 1px solid var(--border); }.trace-timeline {max-height: 320px; overflow-y: auto; padding: 12px 16px;font-size: 0.72rem;17 unmodified lines.trace-reward.pos { color: var(--green); }.trace-reward.neg { color: var(--red); }.chart-container {background: var(--surface); border: 1px solid var(--border);border-radius: var(--radius); padding: 16px 20px; margin-bottom: 16px;3 unmodified lines.chart-legend-item { display: flex; align-items: center; gap: 6px; font-size: 0.65rem; color: var(--text-dim); }.chart-legend-dot { width: 8px; height: 8px; border-radius: 2px; }.queue-grid { display: flex; flex-wrap: wrap; gap: 6px; }.q-chip {padding: 6px 12px; border-radius: 6px; font-size: 0.7rem; font-weight: 600;8 unmodified lines.q-chip.proposed { border-color: var(--amber); color: var(--amber); }.q-dot { width: 6px; height: 6px; border-radius: 50%; }.audit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }@media (max-width: 768px) { .audit-grid { grid-template-columns: 1fr; } }.flag-entry {13 unmodified lines.severity-fill.med { background: var(--amber); }.severity-fill.high { background: var(--red); }/* Arena agent action scrollable area */.agent-actions-scroll { max-height: 220px; overflow-y: auto; }/* ββββββββββββββββββββββββ PLAYGROUND TAB ββββββββββββββββββββββββ */.pg-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; margin-bottom: 16px; }.pg-grid { display: grid; grid-template-columns: 1fr 360px; gap: 16px; }84 unmodified lines.score-pill.mid { background: var(--amber-glow); color: var(--amber); }.score-pill.low { background: var(--red-glow); color: var(--red); }.arch-diagram {display: flex; align-items: center; justify-content: center; gap: 24px;padding: 28px 20px; flex-wrap: wrap;9 unmodified lines.arch-node-name { font-size: 0.75rem; font-weight: 700; }.arch-node-desc { font-size: 0.6rem; color: var(--text-dim); line-height: 1.3; }footer {margin-top: 28px; text-align: center; padding: 16px;font-size: 0.65rem; color: var(--text-muted); border-top: 1px solid var(--border);19 unmodified lines</header><div class="tab-bar"><button class="tab-btn active" data-tab="arena" data-tooltip="Watch agents compete in real-time. Fraudster vs Investigator with live reward tracking and step-by-step replay.">⚔ Arena</button><button class="tab-btn" data-tab="playground" data-tooltip="Hands-on single-agent mode. Investigate ads yourself, render verdicts, and earn rewards under an action budget.">🔍 Playground</button><button class="tab-btn" data-tab="results" data-tooltip="Training overview, baseline scores, reward design details, and animated model comparison reward curves.">📈 Results</button></div><!-- ββββββββββββββββββββββββ ARENA TAB ββββββββββββββββββββββββ --><div class="tab-content active" id="tab-arena"><div class="guide-banner arena"><strong>Welcome to the CounterFeint Arena!</strong>Click <strong>Run Auto Match</strong> to watch a live simulation. The Fraudster agent crafts deceptive ads while the Investigator reviews each one.Watch the reward curves evolve in real-time as agents compete. Adjust the task difficulty and random seed for different scenarios.</div><!-- Architecture overview --><div class="panel" style="margin-bottom:18px"><div class="panel-body">63 unmodified lines<div class="stat-card"><div class="stat-label">End Reason</div><div class="stat-value" id="ar-reason" style="font-size:0.85rem;color:var(--text-dim)">-</div></div></div><!-- Reward chart (Fraudster + Investigator only) --><div class="chart-container"><div class="chart-title">Agent Reward Trajectories</div><div id="arena-chart" style="width:100%;height:220px;"></div><div class="chart-legend"><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--red)"></div>Fraudster</div><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--indigo)"></div>Investigator</div></div></div>12 unmodified lines<div class="reward-badge zero" id="ar-f-reward">0.00</div></div><div class="panel-body"><div class="agent-actions-scroll" id="ar-f-actions"><span class="ph-text" style="color:var(--text-dim);font-size:0.72rem">Run a match to see fraudster actions.</span></div></div></div>23 unmodified lines<div class="reward-badge zero" id="ar-i-reward">0.00</div></div><div class="panel-body"><div class="agent-actions-scroll" id="ar-i-actions"><span class="ph-text" style="color:var(--text-dim);font-size:0.72rem">Run a match to see investigator actions.</span></div></div></div></div>27 unmodified lines<!-- ββββββββββββββββββββββββ PLAYGROUND TAB ββββββββββββββββββββββββ --><div class="tab-content" id="tab-playground"><div class="guide-banner playground"><strong>Step into the Investigator's shoes!</strong>Select a task difficulty below, click <strong>Reset environment</strong> to begin, then investigate ads by examining advertiser histories, landing pages, and payment methods.Render your verdict (approve, reject, or escalate) on each ad. Every investigation costs budget — balance thoroughness against efficiency to maximize your cumulative reward.</div><div class="pg-stats">5 unmodified lines<div class="stat-card"><div class="stat-label">Cum. reward</div><div class="stat-value" id="st-cum">-</div></div></div><div class="chart-container" style="margin-bottom:16px;width:55%;min-width:380px;"><div class="chart-title">Cumulative Reward</div><div id="pg-chart" style="width:100%;height:300px;"></div></div><div style="display:flex;gap:10px;margin-bottom:18px;flex-wrap:wrap;align-items:center">83 unmodified lines<!-- ββββββββββββββββββββββββ RESULTS TAB ββββββββββββββββββββββββ --><div class="tab-content" id="tab-results"><div class="guide-banner results"><strong>Training overview & model comparison.</strong>Explore baseline scores, reward design, and the GRPO training pipeline below.Use <strong>Run Demo Match</strong> to see a live animated simulation. Model comparison curves will be updated as new models are trained and evaluated.</div><div class="results-grid"><div class="panel"><div class="panel-hdr"><span class="panel-title">Baseline Scores (pre-training)</span></div><div class="panel-body">16 unmodified lines</div></div><div class="panel"><div class="panel-hdr"><span class="panel-title">Reward Design</span></div><div class="panel-body">68 unmodified lines</div></div><!-- Live demo match (animated like arena) --><div class="panel" style="margin-top:16px"><div class="panel-hdr"><span class="panel-title">📈 Live Match Reward Curves</span><button class="btn btn-primary" id="btn-results-demo" style="padding:6px 14px;font-size:0.68rem">Run Demo Match</button></div><div class="panel-body"><div id="results-chart" style="width:100%;height:220px;margin-bottom:12px"><div style="color:var(--text-dim);font-size:0.78rem;text-align:center;padding:50px 20px">Click “Run Demo Match” to generate animated reward curves from a live simulation.</div></div><div class="chart-legend" id="results-legend" style="display:none"><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--red)"></div>Fraudster</div><div class="chart-legend-item"><div class="chart-legend-dot" style="background:var(--indigo)"></div>Investigator</div></div><div id="results-summary" style="margin-top:14px"></div></div></div><!-- Model comparison (placeholder β data to be added) --><div class="panel" style="margin-top:16px"><div class="panel-hdr"><span class="panel-title">🧠 Model Comparison β Investigator Reward Curves</span><button class="btn btn-green" id="btn-model-compare" style="padding:6px 14px;font-size:0.68rem" disabled>Play Comparison</button></div><div class="panel-body"><div id="model-chart" style="width:100%;height:220px;margin-bottom:12px"><div style="color:var(--text-dim);font-size:0.78rem;text-align:center;padding:50px 20px;line-height:1.7">Model comparison curves will appear here as training progresses.<br/><span style="font-size:0.68rem;color:var(--text-muted)">Planned models: Untrained Qwen3.5-0.8B, Fine-tuned Qwen3.5-0.8B, and more.</span></div></div><div class="chart-legend" id="model-legend" style="display:none"><div class="chart-legend-item"><div class="chart-legend-dot" style="background:#94a3b8"></div>Untrained Qwen3.5-0.8B</div><div class="chart-legend-item"><div class="chart-legend-dot" style="background:#22c55e"></div>Fine-tuned Qwen3.5-0.8B</div></div></div></div></div><footer>19 unmodified linesc.appendChild(t);setTimeout(() => t.remove(), 3200);}function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }/* βββββββββββββββββββ Tab switching βββββββββββββββββββ */document.querySelectorAll('.tab-btn').forEach(btn => {10 unmodified linesconst el = typeof container === 'string' ? document.getElementById(container) : container;const w = options.width || el.clientWidth || 600;const h = options.height || el.clientHeight || 160;const pad = { t: 20, r: 52, b: 28, l: 52 };const cw = w - pad.l - pad.r;const ch = h - pad.t - pad.b;3 unmodified lineslet mn = Math.min(0, ...allVals), mx = Math.max(0, ...allVals);if (mn === mx) { mn -= 0.1; mx += 0.1; }const range = mx - mn;mn -= range * 0.05;mx += range * 0.05;const maxLen = options.totalSteps || Math.max(...datasets.map(ds => ds.data.length));function sx(i) { return pad.l + (maxLen <= 1 ? cw / 2 : (i / (maxLen - 1)) * cw); }function sy(v) { return pad.t + ch - ((v - mn) / (mx - mn)) * ch; }1 unmodified linelet svg = `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" preserveAspectRatio="xMidYMid meet" style="display:block;width:100%;height:100%">`;svg += `<rect width="${w}" height="${h}" fill="rgba(0,0,0,0.2)" rx="8"/>`;const gridLines = 5;for (let g = 0; g <= gridLines; g++) {const yy = pad.t + (g / gridLines) * ch;const val = mx - (g / gridLines) * (mx - mn);svg += `<line x1="${pad.l}" y1="${yy}" x2="${w - pad.r}" y2="${yy}" stroke="rgba(255,255,255,0.06)" stroke-width="1"/>`;svg += `<text x="${pad.l - 8}" y="${yy + 4}" fill="rgba(255,255,255,0.55)" font-size="11" text-anchor="end" font-family="Inter,sans-serif" font-weight="500">${val.toFixed(2)}</text>`;}const zeroY = sy(0);if (zeroY > pad.t + 2 && zeroY < h - pad.b - 2) {svg += `<line x1="${pad.l}" y1="${zeroY}" x2="${w - pad.r}" y2="${zeroY}" stroke="rgba(255,255,255,0.15)" stroke-width="1" stroke-dasharray="4,3"/>`;svg += `<text x="${pad.l - 8}" y="${zeroY + 4}" fill="rgba(255,255,255,0.5)" font-size="10" text-anchor="end" font-family="Inter,sans-serif" font-weight="600">0</text>`;}datasets.forEach(ds => {if (!ds.data.length) return;const pts = ds.data.map((v, i) => `${sx(i)},${sy(v)}`).join(' ');const gradId = 'g' + Math.random().toString(36).slice(2, 8);const lastX = sx(ds.data.length - 1);const lastY = sy(ds.data[ds.data.length - 1]);svg += `<defs><linearGradient id="${gradId}" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="${ds.color}" stop-opacity="0.25"/><stop offset="100%" stop-color="${ds.color}" stop-opacity="0"/></linearGradient></defs>`;const areaPath = `M${sx(0)},${sy(ds.data[0])} ` + ds.data.map((v, i) => `L${sx(i)},${sy(v)}`).join(' ') + ` L${lastX},${h - pad.b} L${sx(0)},${h - pad.b} Z`;svg += `<path d="${areaPath}" fill="url(#${gradId})"/>`;svg += `<polyline fill="none" stroke="${ds.color}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" points="${pts}"/>`;svg += `<circle cx="${lastX}" cy="${lastY}" r="4" fill="${ds.color}" stroke="rgba(0,0,0,0.3)" stroke-width="1"/>`;const labelX = lastX + 8;const labelVal = ds.data[ds.data.length - 1].toFixed(2);svg += `<text x="${labelX}" y="${lastY + 4}" fill="${ds.color}" font-size="12" font-weight="700" font-family="Inter,sans-serif">${labelVal}</text>`;});const stepLabels = [0, Math.floor(maxLen / 2), maxLen - 1];stepLabels.forEach(i => {if (i < 0 || maxLen <= 0) return;svg += `<text x="${sx(i)}" y="${h - 6}" fill="rgba(255,255,255,0.4)" font-size="10" text-anchor="middle" font-family="Inter,sans-serif">${i}</text>`;});svg += `<text x="${w / 2}" y="${h - 6}" fill="rgba(255,255,255,0.25)" font-size="9" text-anchor="middle" font-family="Inter,sans-serif"></text>`;svg += '</svg>';el.innerHTML = svg;}/* βββββββββββββββββββ ARENA TAB βββββββββββββββββββ */let arenaAnimating = false;let arenaAbort = false;function updatePhaseBar(phase) {['ph-fraudster','ph-investigator','ph-auditor','ph-done'].forEach(id => {8 unmodified linesif (map[phase]) document.getElementById(map[phase]).classList.add('active');}function updateRewardBadge(id, value) {const el = document.getElementById(id);if (!el) return;const cls = value > 0.001 ? 'pos' : value < -0.001 ? 'neg' : 'zero';el.className = 'reward-badge ' + cls;el.textContent = (value >= 0 ? '+' : '') + value.toFixed(2);}function appendActionEntry(containerId, entry, color) {const el = document.getElementById(containerId);const ph = el.querySelector('.ph-text');if (ph) ph.remove();const div = document.createElement('div');div.style.cssText = 'padding:6px 0;border-bottom:1px solid var(--border);font-size:0.72rem;animation:fadeIn 0.3s ease';const rStyle = entry.reward > 0 ? 'color:var(--green)' : entry.reward < 0 ? 'color:var(--red)' : 'color:var(--text-muted)';div.innerHTML = `<span style="color:${color};font-weight:600">${esc(entry.action_type)}</span> <span style="color:var(--text-dim)">${esc(entry.detail)}</span> <span style="${rStyle};font-weight:600;float:right">${entry.reward >= 0 ? '+' : ''}${entry.reward.toFixed(3)}</span>`;el.appendChild(div);el.scrollTop = el.scrollHeight;}function appendTimelineEntry(entry) {const timeline = document.getElementById('ar-timeline');const rCls = entry.reward > 0 ? 'pos' : entry.reward < 0 ? 'neg' : '';const div = document.createElement('div');div.className = 'trace-entry';div.innerHTML = `<div class="trace-dot ${entry.role}"></div><div class="trace-text"><strong>${entry.role}</strong> ${esc(entry.detail)}</div><div class="trace-reward ${rCls}">${entry.reward >= 0 ? '+' : ''}${entry.reward.toFixed(3)}</div>`;timeline.appendChild(div);timeline.scrollTop = timeline.scrollHeight;document.getElementById('ar-trace-count').textContent = timeline.children.length + ' events';}function updateArenaQueue(trace, upToIdx) {const verdictMap = {};const proposedAds = new Set();for (let i = 0; i <= upToIdx; i++) {const t = trace[i];if (t.role === 'investigator' && t.action_type === 'verdict') {const m = t.detail.match(/Verdict on (ad_\d+): (\w+)/);if (m) verdictMap[m[1]] = m[2];}if (t.role === 'fraudster' && t.action_type === 'propose_ad') {const m = (t.feedback || '').match(/ad_id=(ad_\d+)/);if (m) proposedAds.add(m[1]);}}const allAds = [...new Set([...Object.keys(verdictMap), ...proposedAds])].sort();const qEl = document.getElementById('ar-queue');if (allAds.length) {2 unmodified linesconst isProp = proposedAds.has(id);const cls = v === 'approve' ? 'approved' : v === 'reject' ? 'rejected' : v === 'escalate' ? 'escalated' : isProp ? 'proposed' : 'pending';const dotColor = cls === 'approved' ? 'var(--green)' : cls === 'rejected' ? 'var(--red)' : cls === 'escalated' ? 'var(--cyan)' : cls === 'proposed' ? 'var(--amber)' : 'var(--text-muted)';return `<div class="q-chip ${cls}"><span class="q-dot" style="background:${dotColor}"></span>${id}${isProp ? ' \u2605' : ''}</div>`;}).join('');document.getElementById('ar-q-count').textContent = allAds.length + ' ads';}}function renderAuditorPanel(data) {const fs = data.final_state;updateRewardBadge('ar-a-reward', data.final_rewards.auditor);const auditBody = document.getElementById('ar-audit-body');if (fs.audit_report) {const ar = fs.audit_report;const ta = ar.track_a_flags || [];const tb = ar.track_b_flags || [];let html = '<div class="audit-grid"><div>';html += `<div style="font-size:0.65rem;font-weight:700;text-transform:uppercase;color:var(--indigo);margin-bottom:8px">Track A \u2014 Investigator Audit (score: ${(ar.investigator_audit_score || 0).toFixed(2)})</div>`;if (ta.length) {ta.forEach(f => {const sev = f.severity || 0.5;const sevCls = sev >= 0.7 ? 'high' : sev >= 0.4 ? 'med' : 'low';html += `<div class="flag-entry track-a"><div class="flag-type">${esc(f.flag_type || 'flag')} ${f.target_ad_id ? '(' + esc(f.target_ad_id) + ')' : ''}</div><div style="font-size:0.65rem;color:var(--text-dim);margin-top:2px">${esc((f.note || '').slice(0, 100))}</div><div class="severity-bar"><div class="severity-fill ${sevCls}" style="width:${sev * 100}%"></div></div></div>`;});} else { html += '<div style="font-size:0.72rem;color:var(--text-dim)">No Track A flags.</div>'; }html += '</div><div>';html += `<div style="font-size:0.65rem;font-weight:700;text-transform:uppercase;color:var(--amber);margin-bottom:8px">Track B \u2014 Fraudster Plausibility (score: ${(ar.fraudster_plausibility_score || 0).toFixed(2)})</div>`;if (tb.length) {tb.forEach(f => {const sev = f.severity || 0.5;const sevCls = sev >= 0.7 ? 'high' : sev >= 0.4 ? 'med' : 'low';html += `<div class="flag-entry track-b"><div class="flag-type">${esc(f.flag_type || 'flag')} ${f.target_ad_id ? '(' + esc(f.target_ad_id) + ')' : ''}</div><div style="font-size:0.65rem;color:var(--text-dim);margin-top:2px">${esc((f.note || '').slice(0, 100))}</div><div class="severity-bar"><div class="severity-fill ${sevCls}" style="width:${sev * 100}%"></div></div></div>`;});} else { html += '<div style="font-size:0.72rem;color:var(--text-dim)">No Track B flags.</div>'; }html += '</div></div>';auditBody.innerHTML = html;}}function resetArenaUI() {document.getElementById('ar-f-actions').innerHTML = '<span class="ph-text" style="color:var(--text-dim);font-size:0.72rem">Waiting...</span>';document.getElementById('ar-i-actions').innerHTML = '<span class="ph-text" style="color:var(--text-dim);font-size:0.72rem">Waiting...</span>';document.getElementById('ar-timeline').innerHTML = '';document.getElementById('ar-queue').innerHTML = '<span style="color:var(--text-dim);font-size:0.75rem">Waiting for match...</span>';document.getElementById('ar-q-count').textContent = '0 ads';document.getElementById('ar-trace-count').textContent = '0 events';updateRewardBadge('ar-f-reward', 0);updateRewardBadge('ar-i-reward', 0);updateRewardBadge('ar-a-reward', 0);document.getElementById('ar-round').textContent = '-';document.getElementById('ar-steps').textContent = '0';document.getElementById('ar-proposals').textContent = '0';document.getElementById('ar-grader').textContent = '-';document.getElementById('ar-reason').textContent = 'Running...';document.getElementById('ar-audit-body').innerHTML = '<div style="font-size:0.72rem;color:var(--text-dim)">Auditor will act after match concludes...</div>';document.getElementById('arena-chart').innerHTML = '';updatePhaseBar('');}async function animateArenaMatch(data) {const trace = data.trace;const fs = data.final_state;const totalSteps = trace.length;let cumF = 0, cumI = 0;const chartDataF = [], chartDataI = [];trace.forEach(t => {if (t.role === 'fraudster') cumF += t.reward;else if (t.role === 'investigator') cumI += t.reward;chartDataF.push(cumF);chartDataI.push(cumI);});for (let i = 0; i < totalSteps; i++) {if (arenaAbort) return;const entry = trace[i];if (entry.role === 'fraudster') updatePhaseBar('fraudster_turn');else if (entry.role === 'investigator') updatePhaseBar('investigator_turn');else if (entry.role === 'auditor') updatePhaseBar('audit_phase');updateRewardBadge('ar-f-reward', chartDataF[i]);updateRewardBadge('ar-i-reward', chartDataI[i]);if (entry.role === 'fraudster') appendActionEntry('ar-f-actions', entry, 'var(--red)');else if (entry.role === 'investigator') appendActionEntry('ar-i-actions', entry, 'var(--indigo)');updateArenaQueue(trace, i);appendTimelineEntry(entry);document.getElementById('ar-steps').textContent = i + 1;renderMultiChart('arena-chart', [{ data: chartDataF.slice(0, i + 1), color: '#ef4444', label: 'Fraudster' },{ data: chartDataI.slice(0, i + 1), color: '#6366f1', label: 'Investigator' },], { height: 220, totalSteps: totalSteps });await sleep(600);}updatePhaseBar('done');document.getElementById('ar-round').textContent = fs.round_number || '-';document.getElementById('ar-proposals').textContent = fs.proposals_used || 0;document.getElementById('ar-grader').textContent = fs.grader_score != null ? fs.grader_score.toFixed(3) : '-';document.getElementById('ar-reason').textContent = fs.end_reason || '-';await sleep(400);renderAuditorPanel(data);}document.getElementById('btn-auto').onclick = async () => {if (arenaAnimating) {arenaAbort = true;return;}const btn = document.getElementById('btn-auto');const status = document.getElementById('arena-status');btn.innerHTML = '■ Stop';btn.className = 'btn btn-red';btn.disabled = false;arenaAnimating = true;arenaAbort = false;status.textContent = 'Fetching match data...';status.style.color = 'var(--amber)';try {6 unmodified lines});const data = await res.json();if (!res.ok) throw new Error(data.detail || res.statusText);resetArenaUI();status.textContent = `Animating match (${data.total_steps} steps)...`;await animateArenaMatch(data);if (!arenaAbort) {status.textContent = `Match complete \u2014 ${data.total_steps} steps`;status.style.color = 'var(--green)';toast('Match completed successfully', 'success');} else {status.textContent = 'Stopped';status.style.color = 'var(--text-dim)';}} catch (e) {status.textContent = 'Error: ' + e.message;status.style.color = 'var(--red)';toast(e.message, 'error');} finally {arenaAnimating = false;arenaAbort = false;btn.innerHTML = '▶ Run Auto Match';btn.className = 'btn btn-primary';}};/* βββββββββββββββββββ RESULTS TAB βββββββββββββββββββ *//* Live Demo */let resultsDemoRunning = false;document.getElementById('btn-results-demo').onclick = async () => {if (resultsDemoRunning) return;const btn = document.getElementById('btn-results-demo');btn.disabled = true;btn.textContent = 'Running...';resultsDemoRunning = true;try {const res = await fetch(API + '/arena/api/auto', {method: 'POST',2 unmodified lines});const data = await res.json();if (!res.ok) throw new Error(data.detail || res.statusText);const trace = data.trace;let cumF = 0, cumI = 0;const cF = [], cI = [];trace.forEach(t => {if (t.role === 'fraudster') cumF += t.reward;else if (t.role === 'investigator') cumI += t.reward;cF.push(cumF);cI.push(cumI);});document.getElementById('results-legend').style.display = 'flex';for (let i = 0; i < trace.length; i++) {renderMultiChart('results-chart', [{ data: cF.slice(0, i + 1), color: '#ef4444' },{ data: cI.slice(0, i + 1), color: '#6366f1' },], { height: 220, totalSteps: trace.length });await sleep(600);}const fs = data.final_state;document.getElementById('results-summary').innerHTML = `<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px"><div class="stat-card"><div class="stat-label">Grader Score</div><div class="stat-value" style="color:var(--green)">${fs.grader_score != null ? fs.grader_score.toFixed(3) : '-'}</div></div><div class="stat-card"><div class="stat-label">Fraudster Reward</div><div class="stat-value" style="color:var(--red)">${data.final_rewards.fraudster.toFixed(3)}</div></div><div class="stat-card"><div class="stat-label">Investigator Reward</div><div class="stat-value" style="color:var(--indigo)">${data.final_rewards.investigator.toFixed(3)}</div></div><div class="stat-card"><div class="stat-label">Total Steps</div><div class="stat-value">${data.total_steps}</div></div><div class="stat-card"><div class="stat-label">End Reason</div><div class="stat-value" style="font-size:0.85rem;color:var(--text-dim)">${fs.end_reason || '-'}</div></div></div>`;1 unmodified line} catch (e) {toast(e.message, 'error');} finally {resultsDemoRunning = false;btn.disabled = false;btn.textContent = 'Run Demo Match';}};/** Model comparison data placeholder.* To add model curves, populate the `data` arrays with cumulative reward* values (one per match step) and set `ready: true`.*/const MODEL_CURVES = [{ name: 'Untrained Qwen3.5-0.8B', color: '#94a3b8', data: [], ready: false },{ name: 'Fine-tuned Qwen3.5-0.8B', color: '#22c55e', data: [], ready: false },];document.getElementById('btn-model-compare').onclick = async () => {const ready = MODEL_CURVES.filter(m => m.ready && m.data.length);if (!ready.length) { toast('No model data available yet', 'info'); return; }const btn = document.getElementById('btn-model-compare');btn.disabled = true;btn.textContent = 'Playing...';document.getElementById('model-legend').style.display = 'flex';const totalSteps = Math.max(...ready.map(m => m.data.length));for (let i = 0; i < totalSteps; i++) {renderMultiChart('model-chart',ready.map(m => ({ data: m.data.slice(0, i + 1), color: m.color })),{ height: 220, totalSteps: totalSteps });await sleep(600);}btn.disabled = false;btn.textContent = 'Play Comparison';};/* βββββββββββββββββββ PLAYGROUND TAB βββββββββββββββββββ */const TARGETS = ['advertiser_history','landing_page','payment_method','targeting_overlap','campaign_structure','policy_classifier'];43 unmodified linesreturn;}const col = pgCumHistory[pgCumHistory.length - 1] >= 0 ? '#22c55e' : '#ef4444';renderMultiChart('pg-chart', [{ data: pgCumHistory, color: col }], { height: 300 });}function renderPgQueue(obs) {const ads = obs.available_ads || [];98 unmodified lines};document.getElementById('btn-step').onclick = async () => {if (pgDone) { toast('Episode finished \u2014 reset first', 'error'); return; }const t = document.getElementById('act-type').value;const ad = document.getElementById('act-ad').value;const body = { action_type: t, ad_id: ad };4 unmodified linespgVerdicts[ad] = { verdict: body.verdict, confidence: body.confidence };} else if (t === 'link_accounts') {body.linked_ad_id = document.getElementById('act-linked').value;body.link_reason = document.getElementById('act-reason').value.trim() || '\u2014';}try {const res = await fetch(API + '/investigate/api/step', {
server/static/investigate_hq.html+314-131