debrief-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
debrief/site/app.js ADDED
@@ -0,0 +1,1613 @@
1
+ "use strict";
2
+
3
+ // ---------- vocabulary ----------
4
+
5
+ const SIGNALS = {
6
+ correction: { label: "Said it was wrong", plural: "Said it was wrong", tip: "The person told the agent something it did or said was wrong." },
7
+ reversal: { label: "Had it redone", plural: "Had it redone", tip: "The person rejected an approach the agent had already built and asked for it to be redone." },
8
+ could_find: { label: "Agent overlooked", plural: "Agent overlooked", tip: "The person pointed the agent to information it already had access to but didn't find." },
9
+ defect: { label: "Caught a bug", plural: "Caught a bug", tip: "The person pointed out a bug or unwanted output in the agent's work." },
10
+ not_filed: { label: "Found, not filed", plural: "Found, not filed", tip: "The agent noticed a problem outside its task and left it." },
11
+ };
12
+ const SIG_ORDER = ["correction", "reversal", "could_find", "defect"];
13
+ // The three kinds of correction that make up "Agent corrected".
14
+ const CORRECTION_KINDS = ["correction", "reversal", "defect"];
15
+ const pctText = (rate) => (rate == null ? "—" : `${pct1(rate)}%`);
16
+ const SIG_FIELD = { correction: "corrections", reversal: "reversals", could_find: "could_find", defect: "defects" };
17
+ // A human message counts toward "Agent corrected" when it carries any of these.
18
+ const CORRECTING = ["correction", "reversal", "defect"];
19
+ // Glossary entry for each signal (method.js).
20
+ const LABEL_FIELD = { correction: "turn_kind", reversal: "design_reversal", could_find: "agent_could_have_found_it", defect: "human_caught_defect", not_filed: "found_not_filed" };
21
+ const OUTCOMES = { shipped_or_pr_ready: "Shipped", partial: "Partial", abandoned: "Abandoned", investigation_only: "Investigation", unclear: "Unclear" };
22
+ const TURN_KINDS = {
23
+ question_to_agent: "Question to agent", new_request: "New request", approval_or_go_ahead: "Approval / go ahead",
24
+ correction: "Correction", answer_to_agent_question: "Answer to agent", status_check: "Status check", other: "Other", unlabeled: "Unlabeled",
25
+ };
26
+ const PROMPT_STYLES = {
27
+ links_issue_or_pr: "Links issue or PR", detailed_instructions: "Detailed instructions", pasted_spec: "Pasted spec",
28
+ one_line_ask: "One-line ask", question: "Question", asks_for_plan_first: "Asks for a plan",
29
+ };
30
+ const CORRECTION_TYPES = {
31
+ scope: "Scope: too much or too little", wrong_assumption: "Wrong assumption", process: "Skipped a step",
32
+ missed_requirement: "Missed requirement", factual_error: "Factual error", style_or_convention: "Convention", unclassified: "Unclassified",
33
+ };
34
+ const CI_CLASSES = { infra_or_env: "Infra / env", test_regression: "Test regression", build_error: "Build error", flaky_test: "Flaky test", timeout: "Timeout", lint_or_format: "Lint / format", other: "Other", null: "Unlabeled" };
35
+ const HELD = { valid_and_fixed: "Valid, fixed", valid_open: "Valid, open", outdated: "Outdated", wrong: "Wrong", unclear: "Unclear", null: "Unlabeled" };
36
+ const HELD_COLOR = { valid_and_fixed: "var(--text-default)", valid_open: "var(--text-muted)", outdated: "var(--border-default)", wrong: "var(--destructive)", unclear: "var(--surface-selected)", null: "var(--surface-hover)" };
37
+ const PERIODS = { all: "All time", 30: "Last 30 days", 14: "Last 14 days" };
38
+ const DAY = 864e5;
39
+
40
+ const ICONS = {
41
+ overview: '<rect x="2" y="2" width="5" height="5" rx="1"/><rect x="9" y="2" width="5" height="5" rx="1"/><rect x="2" y="9" width="5" height="5" rx="1"/><rect x="9" y="9" width="5" height="5" rx="1"/>',
42
+ recs: '<path d="M2 4l1.5 1.5L6 3M2 10l1.5 1.5L6 9M8.5 4.5H14M8.5 10.5H14"/>',
43
+ corrections: '<path d="M8 2.2l6 10.8H2z"/><path d="M8 6.5v3M8 11.3v.2"/>',
44
+ adoption: '<circle cx="6" cy="5.5" r="2.5"/><path d="M1.5 13.5c.5-2.5 2.3-3.8 4.5-3.8s4 1.3 4.5 3.8M11 3.2a2.3 2.3 0 010 4.6M12.5 10c1.2.5 1.9 1.7 2 3.5"/>',
45
+ delivery: '<circle cx="4" cy="3.5" r="1.5"/><circle cx="4" cy="12.5" r="1.5"/><circle cx="12" cy="12.5" r="1.5"/><path d="M4 5v6M12 11V6.5a2 2 0 00-2-2H7M8.5 3L7 4.5 8.5 6"/>',
46
+ sessions: '<rect x="1.5" y="2.5" width="13" height="11" rx="1.5"/><path d="M4.5 6.5l2 1.5-2 1.5M8 9.5h3"/>',
47
+ method: '<path d="M3 2.5h7.5a2 2 0 012 2v9H5a2 2 0 01-2-2z"/><path d="M3 11.5a2 2 0 012-2h7.5M6 5.5h4"/>',
48
+ projects: '<path d="M1.5 4a1.5 1.5 0 011.5-1.5h3l1.5 2H13A1.5 1.5 0 0114.5 6v6a1.5 1.5 0 01-1.5 1.5H3A1.5 1.5 0 011.5 12z"/>',
49
+ settings: '<path d="M2 4.5h5M11 4.5h3M2 11.5h3M9 11.5h5"/><circle cx="9" cy="4.5" r="2"/><circle cx="7" cy="11.5" r="2"/>',
50
+ };
51
+ const PAGES = [
52
+ { id: "overview", label: "Overview" },
53
+ { id: "recs", label: "Ideas" },
54
+ { id: "corrections", label: "Corrections" },
55
+ { id: "adoption", label: "Adoption" },
56
+ { id: "delivery", label: "CI & review", needs: "github" },
57
+ { id: "sessions", label: "Sessions" },
58
+ { id: "method", label: "How it works", secondary: true },
59
+ { id: "projects", label: "Projects", secondary: true },
60
+ { id: "settings", label: "Settings", secondary: true },
61
+ ];
62
+
63
+ // ---------- state ----------
64
+
65
+ const state = {
66
+ data: null,
67
+ sessionsById: new Map(),
68
+ recsBySession: new Map(),
69
+ sessionCache: new Map(),
70
+ shardCache: new Map(),
71
+ memo: new Map(),
72
+ scope: { period: "all", agent: "", project: "" }, // project: a folder, NO_PROJECT, or "" for all
73
+ projects: [], // [folder, label, sessions], most sessions first
74
+ recFilter: { q: "", lever: "", sort: "sessions", dir: -1 },
75
+ correctionsFilter: { signal: "", ctype: "", dir: "" },
76
+ sessionFilter: { q: "", author: "", outcome: "", corrected: false, sort: "started", dir: -1 },
77
+ evTab: "all",
78
+ overviewGroup: "agent",
79
+ lastPage: null,
80
+ settings: null, // what GET api/settings returned, edited in place until saved
81
+ settingsMsg: null, // { at: "save" | "key", text, bad }
82
+ // The Projects page. settings: its own copy of GET api/settings, so a tick never saves the Settings
83
+ // page's unsaved edits. picked: what the boxes show. status: what GET api/run last said.
84
+ run: { settings: null, picked: [], status: null, est: null, stale: false, estimating: false, saves: 0, saveMsg: null, showAll: false, logOpen: false, refused: "", shownRun: null },
85
+ };
86
+
87
+
88
+ // ---------- helpers ----------
89
+
90
+ const $ = (sel, root = document) => root.querySelector(sel);
91
+ const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
92
+ // Not scrollIntoView: inside an iframe it also scrolls the page that embeds this one.
93
+ function scrollToEl(el, block = "start") {
94
+ if (!el) return;
95
+ const r = el.getBoundingClientRect();
96
+ const off = block === "center" ? (innerHeight - r.height) / 2 : parseFloat(getComputedStyle(el).scrollMarginTop) || 0;
97
+ window.scrollTo(0, scrollY + r.top - off);
98
+ }
99
+ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
100
+ const fmt = (n) => Number(n).toLocaleString("en-US");
101
+ const pct = (a, b) => (b ? Math.round((100 * a) / b) : 0);
102
+ const pct1 = (x) => (x == null ? "—" : `${(100 * x).toFixed(1)}`);
103
+ const sum = (xs, f = (x) => x) => xs.reduce((a, x) => a + (f(x) || 0), 0);
104
+ const groupBy = (xs, f) => xs.reduce((m, x) => { const k = f(x); (m.get(k) || m.set(k, []).get(k)).push(x); return m; }, new Map());
105
+ const short = (id) => String(id).slice(0, 8);
106
+ const time = (ts) => new Date(ts).getTime();
107
+ // A bare date like "2026-08-11" is a calendar day, so show it in UTC rather than shifting it a day west.
108
+ const day = (ts) => (ts ? new Date(ts).toLocaleDateString("en-US", { month: "short", day: "numeric", ...(/^\d{4}-\d{2}-\d{2}$/.test(ts) ? { timeZone: "UTC" } : {}) }) : "");
109
+ const dayTime = (ts) => (ts ? new Date(ts).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "");
110
+ const plural = (n, one, many = one + "s") => `${fmt(n)} ${n === 1 ? one : many}`;
111
+ const dirOf = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "(repo root)");
112
+ const DEF_BY_ID = new Map(DEFS.map((d) => [d.id, d]));
113
+ // Fill {placeholders} in glossary text from the data's meta block.
114
+ const fill = (text) => String(text || "").replace(/\{(\w+)\}/g, (_, k) => {
115
+ const d = state.data;
116
+ const v = { findings: d && Object.keys(d.findings).length, recommendations: d?.recommendations.length }[k] ?? d?.meta?.[k];
117
+ return v == null ? "?" : k === "from" || k === "to" ? day(v) : typeof v === "number" ? fmt(v) : v;
118
+ });
119
+ const defTip = (id) => fill(DEF_BY_ID.get(id)?.short);
120
+ // An ⓘ icon: hover for the short definition; with a glossary id, click to open the full entry.
121
+ function info(text, def) {
122
+ const tip = esc(fill(text || defTip(def)));
123
+ return def
124
+ ? `<a class="info" href="#method~${DEF_BY_ID.get(def)?.anchor || def}" data-tip="${tip}" aria-label="Definition: ${tip}">i</a>`
125
+ : `<span class="info" data-tip="${tip}" tabindex="0" aria-label="${tip}">i</span>`;
126
+ }
127
+ const glyph = (sig) => `<span class="glyph ${sig}" aria-hidden="true"></span>`;
128
+ const sigChip = (sig, extra = "") => `<span class="sig">${glyph(sig)}${esc(SIGNALS[sig].label)}${extra}</span>`;
129
+ const outcomeChip = (o) => (o ? `<span class="outcome ${esc(o)}">${esc(OUTCOMES[o] || o)}</span>` : `<span class="muted">—</span>`);
130
+ // Optional data (GitHub, people, checkpoints, projects, labels): the export says which exists, and
131
+ // pages, columns and tiles for the rest stay hidden.
132
+ const has = (k) => Boolean(state.data?.meta?.has?.[k]);
133
+ const pages = () => PAGES.filter((p) => !p.needs || has(p.needs));
134
+ // Lever keys and their descriptions come from the data. The label is the description up to its colon,
135
+ // or the key in words when there is no short one.
136
+ const lever = (k) => {
137
+ const desc = state.data.levers?.[k] || "";
138
+ const head = desc.split(":")[0];
139
+ return desc.includes(":") && head.length <= 32 ? head : String(k).replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase());
140
+ };
141
+ // A PR's key is "owner/name#12". The repo's name shows only when the report spans several repos.
142
+ const prLabel = (k) => { const [repo, n] = String(k).split("#"); return esc(state.data.meta.repo ? `#${n}` : `${repo.split("/").pop()}#${n}`); };
143
+ const prLink = (k) => { const url = state.data.prs[k]?.url; return url ? `<a href="${esc(url)}" target="_blank" rel="noopener">${prLabel(k)}</a>` : prLabel(k); };
144
+ // "3 of 40 messages", or "No messages" rather than "0 of 0".
145
+ const ofText = (a, b, unit) => (b ? `${fmt(a)} of ${fmt(b)} ${unit}` : `No ${unit}`);
146
+ const sessionHref = (id, idx) => `#session~${id}${idx != null ? "~" + idx : ""}`;
147
+ // Filter value for sessions whose harness didn't record who ran them.
148
+ const NO_PERSON = "(no person)";
149
+ const personLabel = (author, none = "Unknown") => (!author || author === NO_PERSON ? none : author);
150
+ // A session's project is the folder it ran in: show the last part, filter on the whole path.
151
+ const NO_PROJECT = "(no project)";
152
+ const pathTail = (p, n = 1) => String(p).replace(/[\\/]+$/, "").split(/[\\/]/).slice(-n).join("/") || p;
153
+ const projectName = (p) => (p ? state.projects.find((x) => x[0] === p)?.[1] || pathTail(p) : "Unknown");
154
+ // The side bar's picker sets state.scope.project, which scopes every page.
155
+ // The one name the page stores under and sends: storage keys and the token header (paths.py has its twin).
156
+ const APP = "debrief";
157
+ const PROJECT_KEY = `${APP}.project`;
158
+ const inProject = (s, p = state.scope.project) => !p || (p === NO_PROJECT ? !s.project : s.project === p);
159
+ const allSessions = () => state.data.sessions.filter((s) => inProject(s));
160
+ // An idea is about one project, or spans them (project null: prompting habits, and runs from before
161
+ // projects). A picked project shows its own ideas and the spanning ones whose evidence touches it.
162
+ const recsFor = (p) => state.data.recommendations.filter((r) => !p || (r.project ? r.project === p : r.sessions.some((id) => inProject(state.sessionsById.get(id) || {}, p))));
163
+ const allRecs = () => recsFor(state.scope.project);
164
+ const fromSessions = () => (state.scope.project ? `the ${plural(allSessions().length, "session")} in ${esc(workspaceLabel())}` : `all ${fmt(allSessions().length)} sessions`);
165
+ const ACROSS_TIP = "Built from more than one project; some of its evidence is from this one.";
166
+ const acrossPill = (r) => (state.scope.project && !r.project ? ` <span class="pill" data-tip="${ACROSS_TIP}">across projects</span>` : "");
167
+ function pickProject(p) {
168
+ state.scope.project = p;
169
+ try { localStorage.setItem(PROJECT_KEY, p); } catch { /* private window: the pick lasts until reload */ }
170
+ if ($("#project-pick")) $("#project-pick").value = p;
171
+ rerender();
172
+ }
173
+ // Who ran a session and with what, for a row's second line.
174
+ const ranBy = (s) => [has("people") && personLabel(s.author), s.agent].filter(Boolean).join(" · ");
175
+ // Shown in the intro, and in the side bar when there is one project: the picked project, the GitHub repo,
176
+ // the one project, or how many projects.
177
+ function workspaceLabel() {
178
+ const d = state.data;
179
+ if (state.scope.project) return projectName(state.scope.project === NO_PROJECT ? null : state.scope.project);
180
+ if (d.meta.repo) return d.meta.repo;
181
+ const projects = new Set(d.sessions.map((s) => s.project).filter(Boolean));
182
+ return projects.size === 1 ? projectName([...projects][0]) : projects.size ? plural(projects.size, "project") : "";
183
+ }
184
+ // A card that says what is missing and how to get it, in place of empty tables.
185
+ const notice = (title, text) => `<section class="card"><div class="card-body"><h2>${esc(title)}</h2><p>${text}</p></div></section>`;
186
+ const NOTICES = {
187
+ // The report holds picked projects only; index.json's projects lists the rest.
188
+ sessions: () => (state.data.projects?.length
189
+ ? notice("No project picked", `debrief found ${plural(state.data.projects.length, "project")} and analyses only the ones you pick. <a href="#projects">Pick projects and check them</a>. <code>debrief sync --project DIR</code> in a terminal also works.`)
190
+ : notice("No sessions yet", "debrief found no agent sessions to report on. Run <code>debrief sync</code> to import them.")),
191
+ labels: () => notice("Sessions imported, not analysed yet", `${plural(state.data.sessions.length, "session")} to <a href="#sessions">browse</a>, but none is labelled yet, so there are no correction rates or ideas. <a href="#projects">Check your data</a> to label them.`),
192
+ // A picked project can have none while the run has some.
193
+ ideas: () => (state.scope.project && state.data.recommendations.length
194
+ ? notice("No ideas for this project", `No idea in this run is about ${esc(workspaceLabel())} or cites its sessions.`)
195
+ : NOTICES.noIdeas()),
196
+ noIdeas: () => notice("No ideas yet", "The messages are labelled, but no findings or ideas have been written from them. <a href=\"#projects\">Check your data</a> to finish the analysis."),
197
+ };
198
+ const correctedTurns = (s) => s.friction.filter(([, sig]) => sig.some((x) => CORRECTING.includes(x))).length;
199
+
200
+ const agentKey = (agent) => ({ "Claude Code": "claude", Codex: "codex", Pi: "pi" }[agent] || "other");
201
+ const agentColor = (agent) => `var(--ag-${agentKey(agent)})`;
202
+ const agentChip = (a) => `<span class="agent-chip ${agentKey(a)}">${esc(a)}</span>`;
203
+
204
+ // Group key for a model: "[1m]" and the like only widen the context window, so they count with the base model.
205
+ const modelName = (m) => String(m || "").replace(/\[\d+[km]\]$/i, "").trim() || "Unknown model";
206
+ // Models with fewer sessions than this are left out of the model tables.
207
+ const MIN_RATED = 10;
208
+ // One row per model with enough sessions: metrics, the one-session check and sessions per harness, by sessions.
209
+ // `hidden` counts the models left out.
210
+ function modelRows(S) {
211
+ const all = [...groupBy(S, (s) => modelName(s.model))];
212
+ const rows = all.filter(([, ss]) => ss.length >= MIN_RATED)
213
+ .map(([name, ss]) => ({ name, mm: metrics(ss), one: restsOnOne(ss),
214
+ agents: [...groupBy(ss, (s) => s.agent)].map(([a, xs]) => [a, xs.length]).sort((x, y) => y[1] - x[1]) }))
215
+ .sort((x, y) => y.mm.sessions - x.mm.sessions);
216
+ return Object.assign(rows, { hidden: all.length - rows.length });
217
+ }
218
+ const hiddenNote = (rows) => (rows.hidden ? `${plural(rows.hidden, "model")} with fewer than ${MIN_RATED} sessions not shown.` : "");
219
+ const harnessDots = (agents) => `<span class="mini" data-tip="${esc(agents.map(([a, n]) => `${a}: ${n}`).join(", "))}" tabindex="0">${agents.map(([a]) => `<span class="dot" style="--c:${agentColor(a)}"></span>`).join("")}</span>`;
220
+
221
+ // One item per key in turn, so no single session crowds out the rest.
222
+ function interleave(xs, key) {
223
+ const queues = [...groupBy(xs, key).values()];
224
+ const out = [];
225
+ for (let i = 0; out.length < xs.length; i++) queues.forEach((q) => { if (q[i]) out.push(q[i]); });
226
+ return out;
227
+ }
228
+
229
+ // Minimal markdown: headings, fenced code, lists, paragraphs, inline code, bold, links. Escapes first.
230
+ function md(src) {
231
+ const out = [];
232
+ String(src || "").split(/```[\w-]*\n?/).forEach((part, i) => {
233
+ if (i % 2) { out.push(`<pre>${esc(part.replace(/\n$/, ""))}</pre>`); return; }
234
+ for (const block of part.split(/\n\s*\n/)) {
235
+ const lines = block.split("\n").filter((l) => l.trim());
236
+ if (lines.length && /^#{1,6}\s/.test(lines[0])) out.push(`<p><strong>${inline(lines.shift().replace(/^#+\s*/, ""))}</strong></p>`);
237
+ if (!lines.length) continue;
238
+ if (lines.every((l) => /^\s*([-*]|\d+[.)])\s+/.test(l))) {
239
+ const items = lines.map((l) => `<li>${inline(l.replace(/^\s*([-*]|\d+[.)])\s+/, ""))}</li>`).join("");
240
+ out.push(/^\s*\d/.test(lines[0]) ? `<ol>${items}</ol>` : `<ul>${items}</ul>`);
241
+ } else {
242
+ out.push(`<p>${lines.map(inline).join("<br>")}</p>`);
243
+ }
244
+ }
245
+ });
246
+ return out.join("");
247
+ }
248
+ function inline(s) {
249
+ return esc(s)
250
+ .replace(/`([^`]+)`/g, "<code>$1</code>")
251
+ .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
252
+ .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
253
+ }
254
+
255
+ // ---------- scope (global period + agent filter) ----------
256
+
257
+ function windowFor(offset) {
258
+ if (state.scope.period === "all") return offset ? null : [-Infinity, Infinity];
259
+ const end = time(state.data.meta.to) + DAY;
260
+ const len = Number(state.scope.period) * DAY;
261
+ return [end - len * (offset + 1), end - len * offset];
262
+ }
263
+
264
+ // When a session counts for periods and weeks: its start, or the window start if it began earlier.
265
+ const startedAt = (s) => Math.max(time(s.started), time(state.data.meta.from));
266
+
267
+ // Sessions and everything tied to them, for the current scope (offset 1 = the previous window).
268
+ function scoped(offset = 0) {
269
+ const key = `${state.scope.period}|${state.scope.agent}|${state.scope.project}|${offset}`;
270
+ if (state.memo.has(key)) return state.memo.get(key);
271
+ const w = windowFor(offset);
272
+ let out = null;
273
+ if (w) {
274
+ const d = state.data;
275
+ const S = d.sessions.filter((s) => inProject(s) && (!state.scope.agent || s.agent === state.scope.agent) && startedAt(s) >= w[0] && startedAt(s) < w[1]);
276
+ const ids = new Set(S.map((s) => s.id));
277
+ const prs = new Set(S.flatMap((s) => s.prs.map((p) => p.n)));
278
+ out = {
279
+ S, ids, prs, window: w,
280
+ flagged: d.flagged.filter((t) => ids.has(t.s)),
281
+ fails: d.ci.failures.filter((f) => prs.has(f.pr)),
282
+ reviews: d.reviews.filter((r) => prs.has(r.pr)),
283
+ skills: d.skills.filter((u) => ids.has(u.s)),
284
+ files: d.files.map((f) => ({ ...f, turns: f.turns.filter((t) => ids.has(t.s)) })).filter((f) => f.turns.length)
285
+ .map((f) => ({ ...f, sessions: [...new Set(f.turns.map((t) => t.s))] })),
286
+ };
287
+ }
288
+ state.memo.set(key, out);
289
+ return out;
290
+ }
291
+
292
+ function metrics(S) {
293
+ const turns = sum(S, (s) => s.human_turns);
294
+ const labeled = S.filter((s) => s.outcome);
295
+ const shipped = labeled.filter((s) => s.outcome === "shipped_or_pr_ready").length;
296
+ const corrected = sum(S, correctedTurns);
297
+ const m = {
298
+ sessions: S.length, people: new Set(S.map((s) => s.author).filter(Boolean)).size, turns, corrected,
299
+ labeled: labeled.length, shipped, shipRate: labeled.length ? shipped / labeled.length : null,
300
+ correctedRate: turns ? corrected / turns : null,
301
+ };
302
+ for (const g of SIG_ORDER) { m[g] = sum(S, (s) => s[SIG_FIELD[g]]); m[`${g}Rate`] = turns ? m[g] / turns : null; }
303
+ return m;
304
+ }
305
+
306
+ // Agent corrected without the one session that moves it most. Returns that session and the rate
307
+ // without it when dropping it shifts the rate by more than a third; null when the rate holds.
308
+ function restsOnOne(S) {
309
+ const turns = sum(S, (s) => s.human_turns);
310
+ const corrected = sum(S, correctedTurns);
311
+ if (!turns) return null;
312
+ const rate = corrected / turns;
313
+ let worst = null;
314
+ for (const s of S) {
315
+ const rest = turns - s.human_turns;
316
+ if (!rest) continue;
317
+ const r = (corrected - correctedTurns(s)) / rest;
318
+ if (!worst || Math.abs(r - rate) > Math.abs(worst.rate - rate)) worst = { s, rate: r };
319
+ }
320
+ return worst && Math.abs(worst.rate - rate) > rate / 3 ? worst : null;
321
+ }
322
+ const restsPill = (w) => (w ? ` <span class="pill" data-tip="Without its biggest session (${plural(w.s.human_turns, "message")}) this is ${pctText(w.rate)}.">rests on one session</span>` : "");
323
+
324
+ function weekStart(ts) {
325
+ const d = new Date(ts);
326
+ d.setUTCHours(0, 0, 0, 0);
327
+ d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 6) % 7));
328
+ return d.getTime();
329
+ }
330
+
331
+ // Every week in the scope, empty ones included, with metrics per week.
332
+ function weekly(S) {
333
+ if (!S.length) return [];
334
+ const by = groupBy(S, (s) => weekStart(startedAt(s)));
335
+ const first = Math.min(...by.keys());
336
+ const last = Math.max(...by.keys());
337
+ const out = [];
338
+ for (let w = first; w <= last; w += 7 * DAY) out.push({ week: w, S: by.get(w) || [], m: metrics(by.get(w) || []) });
339
+ return out;
340
+ }
341
+
342
+ // ---------- charts ----------
343
+
344
+ function spark(values) {
345
+ const pts = values.map((v, i) => [i, v]).filter(([, v]) => v != null);
346
+ if (pts.length < 2) return "";
347
+ const W = 84, H = 30, lo = Math.min(...pts.map((p) => p[1])), hi = Math.max(...pts.map((p) => p[1]));
348
+ const x = (i) => 2 + (i * (W - 4)) / (values.length - 1 || 1);
349
+ const y = (v) => H - 3 - ((v - lo) / (hi - lo || 1)) * (H - 6);
350
+ const line = pts.map(([i, v]) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");
351
+ const [li, lv] = pts[pts.length - 1];
352
+ return `<svg class="spark" viewBox="0 0 ${W} ${H}" aria-hidden="true">
353
+ <polygon points="${x(pts[0][0]).toFixed(1)},${H} ${line} ${x(li).toFixed(1)},${H}" fill="var(--surface-selected)"/>
354
+ <polyline points="${line}" fill="none" stroke="var(--text-muted)" stroke-width="1.5" stroke-linejoin="round"/>
355
+ <circle cx="${x(li).toFixed(1)}" cy="${y(lv).toFixed(1)}" r="2.5" fill="var(--text-muted)"/></svg>`;
356
+ }
357
+
358
+ // weeks: [{week, S, m}]; series: [{label, color, value: (week) => number|null}]
359
+ function lineChart(weeks, series, { fmtY = (v) => v.toFixed(1), unit = "" } = {}) {
360
+ if (weeks.length < 2) return `<div class="empty">Not enough weeks in this period for a trend.</div>`;
361
+ const W = 640, H = 200, L = 34, R = 10, T = 10, B = 24;
362
+ const vals = series.flatMap((s) => weeks.map(s.value)).filter((v) => v != null);
363
+ const step = niceStep(Math.max(...vals, 0.001) / 4);
364
+ const top = Math.ceil(Math.max(...vals, 0.001) / step) * step;
365
+ const x = (i) => L + (i * (W - L - R)) / (weeks.length - 1);
366
+ const y = (v) => T + (1 - v / top) * (H - T - B);
367
+ const grid = [];
368
+ for (let v = 0; v <= top + 1e-9; v += step) grid.push(`<line class="grid-line" x1="${L}" x2="${W - R}" y1="${y(v)}" y2="${y(v)}"/><text class="axis-text" x="${L - 6}" y="${y(v) + 4}" text-anchor="end">${fmtY(v)}</text>`);
369
+ const labelEvery = Math.ceil(weeks.length / 8);
370
+ const xl = weeks.map((w, i) => (i % labelEvery ? "" : `<text class="axis-text" x="${x(i)}" y="${H - 6}" text-anchor="middle">${day(w.week)}</text>`)).join("");
371
+ // A week still in progress at the end of the data, or with few sessions, isn't comparable: draw it dotted.
372
+ const dataEnd = time(state.data.meta.to);
373
+ const partial = (w) => w.week + 7 * DAY > dataEnd;
374
+ const weak = (w) => w.m.sessions < 5 || partial(w);
375
+ const lines = series.map((s) => {
376
+ const segs = weeks.slice(1).map((w, n) => {
377
+ const a = s.value(weeks[n]), b = s.value(w);
378
+ if (a == null || b == null) return "";
379
+ return `<path d="M${x(n).toFixed(1)},${y(a).toFixed(1)}L${x(n + 1).toFixed(1)},${y(b).toFixed(1)}" fill="none" stroke="${s.color}" stroke-width="2" stroke-linecap="round"${weak(weeks[n]) || weak(w) ? ' stroke-dasharray="2 4"' : ""}/>`;
380
+ }).join("");
381
+ const dots = weeks.map((w, i) => { const v = s.value(w); if (v == null) return ""; const thin = weak(w);
382
+ return `<circle cx="${x(i)}" cy="${y(v)}" r="${thin ? 3 : 3.5}" fill="var(--surface-floating)" stroke="${s.color}" stroke-width="${thin ? 1.5 : 2}"/>`; }).join("");
383
+ return `${segs}${dots}`;
384
+ }).join("");
385
+ const band = (W - L - R) / (weeks.length - 1);
386
+ const hover = weeks.map((w, i) => {
387
+ const tip = [`Week of ${day(w.week)} · ${plural(w.m.sessions, "session")}, ${plural(w.m.turns, "message")}`, ...series.map((s) => { const v = s.value(w); return `${s.label}: ${v == null ? "—" : fmtY(v) + unit}`; }), ...(partial(w) ? [`Partial week: data ends ${day(state.data.meta.to)}`] : w.m.sessions < 5 ? ["Few sessions: read as noise"] : [])].join("\n");
388
+ return `<g class="hover-band" data-tip="${esc(tip)}"><rect x="${x(i) - band / 2}" y="${T}" width="${band}" height="${H - T - B}" fill="transparent"/><line class="cross" x1="${x(i)}" x2="${x(i)}" y1="${T}" y2="${H - B}"/></g>`;
389
+ }).join("");
390
+ const note = weeks.some(weak) ? `<p class="note small">Dotted: a week that's only partly over or has fewer than 5 sessions.</p>` : "";
391
+ return `<div class="chart"><svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(series.map((s) => s.label).join(" and "))} by week">${grid.join("")}${xl}${lines}${hover}</svg>${note}</div>`;
392
+ }
393
+ function niceStep(raw) {
394
+ const p = 10 ** Math.floor(Math.log10(raw));
395
+ return [1, 2, 2.5, 5, 10].map((m) => m * p).find((s) => s >= raw) || raw;
396
+ }
397
+
398
+ // rows: [{label, value, valText?, color?, segs?: [{v, c, tip}], href?, tip?}]
399
+ function bars(rows, { max, labelWidth } = {}) {
400
+ if (!rows.length) return `<div class="empty">No data in this period.</div>`;
401
+ const top = max ?? Math.max(1, ...rows.map((r) => r.value));
402
+ const style = labelWidth ? ` style="grid-template-columns:${labelWidth} minmax(0,1fr) 72px"` : "";
403
+ return `<div class="bars">${rows.map((r) => {
404
+ const segs = r.segs || [{ v: r.value, c: r.color, tip: r.tip }];
405
+ const track = segs.filter((s) => s.v > 0).map((s) => `<span class="seg" style="width:${(100 * s.v) / top}%;${s.c ? `--c:${s.c}` : ""}" data-tip="${esc(s.tip || `${r.label}: ${fmt(s.v)}`)}"></span>`).join("");
406
+ const attrs = r.href ? ` class="bar-row link" data-href="${esc(r.href)}" role="link" tabindex="0"` : ` class="bar-row"`;
407
+ return `<div${attrs}${style}><span class="lab" title="${esc(r.label)}">${esc(r.label)}</span><span class="track">${track}</span><span class="val">${r.valText ?? fmt(r.value)}</span></div>`;
408
+ }).join("")}</div>`;
409
+ }
410
+ const legend = (items) => `<div class="legend">${items.map((i) => `<span>${i.glyph ? glyph(i.glyph) : `<span class="dot" style="--c:${i.c}"></span>`}${esc(i.label)}</span>`).join("")}</div>`;
411
+ const inlineBar = (value, max, color, text, tip) => `<div class="inline-bar"><span class="track"><span class="seg" style="width:${max ? (100 * value) / max : 0}%;--c:${color}" data-tip="${esc(tip || "")}"></span></span><span class="num" style="min-width:36px;text-align:right">${text}</span></div>`;
412
+
413
+ // ---------- building blocks ----------
414
+
415
+ function kpi({ label, tip, def, desc, value, unit = "", sub = "", sparkValues, delta, href }) {
416
+ // A div, not a link: the ⓘ inside is its own link, and links can't nest.
417
+ return `<div class="card kpi${href ? " link" : ""}"${href ? ` data-href="${href.slice(1)}" role="link" tabindex="0"` : ""}>
418
+ <div class="kpi-label"><span>${esc(label)}</span>${tip || def ? info(tip, def) : ""}</div>
419
+ <div class="kpi-row"><span class="kpi-value">${value}${unit ? `<small>${unit}</small>` : ""}</span>${sparkValues ? spark(sparkValues) : ""}</div>
420
+ ${desc ? `<div class="kpi-desc">${esc(desc)}</div>` : ""}
421
+ <div class="kpi-sub">${delta || ""}<span>${sub}</span></div>
422
+ </div>`;
423
+ }
424
+
425
+ // Change against the previous window; better = "up" | "down".
426
+ function delta(cur, prev, { better, pts = false }) {
427
+ if (cur == null || prev == null) return "";
428
+ const diff = pts ? 100 * (cur - prev) : prev ? (100 * (cur - prev)) / prev : null;
429
+ if (diff == null) return "";
430
+ const flat = Math.abs(diff) < (pts ? 0.5 : 5);
431
+ const good = better === "up" ? diff > 0 : diff < 0;
432
+ const cls = flat ? "flat" : good ? "good" : "bad";
433
+ const arrow = flat ? "→" : diff > 0 ? "▲" : "▼";
434
+ return `<span class="delta ${cls}" data-tip="vs previous ${state.scope.period} days">${arrow} ${Math.abs(diff).toFixed(1)}${pts ? " pts" : "%"}</span>`;
435
+ }
436
+
437
+ function card({ title, tip, def, aside = "", body, foot = "", flush = false, cls = "" }) {
438
+ return `<section class="card ${cls}"><div class="card-head"><h2>${esc(title)}${tip || def ? " " + info(tip, def) : ""}</h2>${aside ? `<div class="aside">${aside}</div>` : ""}</div>
439
+ <div class="card-body${flush ? " flush" : ""}">${body}</div>${foot ? `<div class="card-foot">${foot}</div>` : ""}</section>`;
440
+ }
441
+
442
+ // Recommendations are ordered by reach: sessions touched, then people. Ties keep the export's order.
443
+ // Ideas left with no supporting evidence (weak) sort last whatever the sort.
444
+ const REC_SORTS = {
445
+ sessions: (r) => r.sessions.length * 1e3 + r.people,
446
+ people: (r) => r.people * 1e3 + r.sessions.length,
447
+ };
448
+ const weakLast = (a, b) => Number(!!a.weak) - Number(!!b.weak);
449
+ const byReach = (a, b) => weakLast(a, b) || REC_SORTS.sessions(b) - REC_SORTS.sessions(a);
450
+ function sortRecs(recs, { sort, dir } = state.recFilter) {
451
+ return recs.slice().sort((a, b) => weakLast(a, b) || (REC_SORTS[sort](a) - REC_SORTS[sort](b)) * dir);
452
+ }
453
+ const WEAK_TIP = "A second model pass found none of this idea's cited items support it.";
454
+ const weakPill = (r) => (r.weak ? ` <span class="pill" data-tip="${WEAK_TIP}">weak evidence</span>` : "");
455
+
456
+ // sortable: headers become clickable and show the current sort (the Recommendations page).
457
+ function recTable(recs, { compact = false, sortable = false } = {}) {
458
+ if (!recs.length) return `<div class="empty">No ideas match.</div>`;
459
+ const f = state.recFilter;
460
+ const th = (k, label, cls = "") => (sortable
461
+ ? `<th class="sortable ${cls}" data-rec-sort="${k}" aria-sort="${f.sort === k ? (f.dir > 0 ? "ascending" : "descending") : "none"}">${label}${f.sort === k ? (f.dir > 0 ? " ↑" : " ↓") : ""}</th>`
462
+ : `<th class="${cls}">${label}</th>`);
463
+ return `<div class="table-wrap"><table><thead><tr><th>Idea</th><th>Type</th>
464
+ ${th("sessions", "Sessions", "r")}${has("people") ? th("people", "People", "r") : ""}</tr></thead>
465
+ <tbody>${recs.map((r) => `<tr class="click" data-href="rec~${r.id}">
466
+ <td style="min-width:260px"><div class="cell-title">${esc(r.title)}${weakPill(r)}${acrossPill(r)}</div>${!compact && r.target ? `<div class="cell-sub mono">${esc(r.target)}</div>` : ""}</td>
467
+ <td class="nowrap">${esc(lever(r.lever))}</td>
468
+ <td class="r">${r.sessions.length}</td>${has("people") ? `<td class="r">${r.people}</td>` : ""}</tr>`).join("")}</tbody></table></div>`;
469
+ }
470
+
471
+ function sessionRows(S) {
472
+ const col = { project: has("projects"), person: has("people"), pr: has("github") };
473
+ return S.map((s) => {
474
+ const c = Object.fromEntries(SIG_ORDER.map((g) => [g, s[SIG_FIELD[g]]]));
475
+ return `<tr class="click" data-href="session~${s.id}">
476
+ <td class="num nowrap">${day(s.started)}</td>
477
+ <td style="min-width:220px"><div class="cell-title">${esc(s.name || short(s.id))}</div><div class="cell-sub">${esc(s.prompt)}</div></td>
478
+ ${col.project ? `<td class="nowrap${s.project ? "" : " muted"}" style="max-width:220px;overflow:hidden;text-overflow:ellipsis" title="${esc(s.project || "")}">${esc(projectName(s.project))}</td>` : ""}
479
+ <td class="nowrap">${agentChip(s.agent)}<div class="cell-sub">${esc(s.model || "")}</div></td>
480
+ ${col.person ? `<td class="nowrap${s.author ? "" : " muted"}">${esc(personLabel(s.author))}</td>` : ""}
481
+ <td class="r">${s.human_turns}</td>
482
+ <td><span class="mini">${SIG_ORDER.filter((g) => c[g]).map((g) => `<span class="sig" data-tip="${c[g]} ${SIGNALS[g].plural.toLowerCase()}">${glyph(g)}${c[g]}</span>`).join("") || `<span class="muted">—</span>`}</span></td>
483
+ <td>${outcomeChip(s.outcome)}</td>${col.pr ? `<td class="nowrap">${s.prs.map((p) => `${prLink(p.n)} <span class="pr-state">${esc(p.state)}</span>`).join("<br>") || `<span class="muted">—</span>`}</td>` : ""}
484
+ </tr>`;
485
+ }).join("");
486
+ }
487
+
488
+ function turnRows(turns) {
489
+ return turns.map((t) => {
490
+ const s = state.sessionsById.get(t.s) || {};
491
+ return `<tr class="click" data-href="session~${t.s}~${t.i}">
492
+ <td class="num nowrap top">${day(t.ts || s.started)}</td>
493
+ <td class="top" style="min-width:180px"><div class="cell-title">${esc(s.name || short(t.s))}</div><div class="cell-sub">${esc(ranBy(s))}</div></td>
494
+ <td class="top"><div class="chips">${t.sig.map((g) => `<span class="sig">${glyph(g)}${esc(g === "correction" && t.ctype ? CORRECTION_TYPES[t.ctype] || t.ctype : SIGNALS[g].label)}</span>`).join("")}</div></td>
495
+ <td class="top" style="min-width:280px;color:var(--text-default);overflow-wrap:anywhere">${esc(t.text)}</td></tr>`;
496
+ }).join("");
497
+ }
498
+
499
+ // ---------- chrome ----------
500
+
501
+ function renderNav(active) {
502
+ const counts = { recs: allRecs().length, sessions: allSessions().length };
503
+ if ($("#foot-sessions")) $("#foot-sessions").textContent = fmt(counts.sessions);
504
+ $("#nav").innerHTML = pages().map((p, i, shown) => `${p.secondary && !shown[i - 1]?.secondary ? '<div class="nav-label">About</div>' : ""}<a href="#${p.id}"${p.id === active ? ' aria-current="page"' : ""}>
505
+ <svg viewBox="0 0 16 16" aria-hidden="true">${ICONS[p.id]}</svg><span>${esc(p.label)}</span>${counts[p.id] ? `<span class="count">${counts[p.id]}</span>` : ""}</a>`).join("");
506
+ }
507
+
508
+ function renderTopbar({ crumbs, scope = false, right = "" }) {
509
+ const m = state.data.meta;
510
+ const agents = [...new Set(state.data.sessions.map((s) => s.agent))].sort();
511
+ const trail = crumbs.map((c, i) => (i < crumbs.length - 1 ? `<a href="${c.href}">${esc(c.label)}</a><span class="sep">/</span>` : `<h1>${esc(c.label)}</h1>`)).join("");
512
+ const controls = scope ? `<label for="scope-period">Period <select id="scope-period">${Object.entries(PERIODS).map(([k, l]) => `<option value="${k}"${state.scope.period === k ? " selected" : ""}>${l}</option>`).join("")}</select></label>
513
+ <label for="scope-agent">Harness <select id="scope-agent"><option value="">All harnesses</option>${agents.map((a) => `<option${state.scope.agent === a ? " selected" : ""}>${esc(a)}</option>`).join("")}</select></label>` : "";
514
+ $("#topbar").innerHTML = `<nav class="crumbs" aria-label="Breadcrumb">${trail}</nav>${right}
515
+ <div class="scope">${controls}<span class="fresh" data-tip="Data exported ${esc(dayTime(m.generated))}. Analysis run ${esc(m.run_id)}."><span class="live"></span>Updated ${esc(day(m.generated))}</span></div>`;
516
+ $("#scope-period")?.addEventListener("change", (e) => { state.scope.period = e.target.value; rerender(); });
517
+ $("#scope-agent")?.addEventListener("change", (e) => { state.scope.agent = e.target.value; rerender(); });
518
+ }
519
+
520
+ function scopeLabel() {
521
+ const sc = scoped();
522
+ const w = sc.window;
523
+ const from = w[0] > time(state.data.meta.from) ? day(w[0]) : day(state.data.meta.from);
524
+ return `${from} – ${day(state.data.meta.to)} · ${state.scope.project ? `${esc(workspaceLabel())} · ` : ""}${plural(sc.S.length, "session")}${state.scope.agent ? ` · ${esc(state.scope.agent)}` : ""}`;
525
+ }
526
+
527
+ // ---------- routing ----------
528
+
529
+ function route() {
530
+ const [page, a, b] = (location.hash.slice(1) || "overview").split("~");
531
+ const views = { overview: viewOverview, recs: viewRecs, rec: () => viewRec(a), corrections: viewCorrections, adoption: viewAdoption,
532
+ delivery: viewDelivery, sessions: viewSessions, session: () => viewSession(a, b), method: () => viewMethod(a), projects: viewProjects, settings: viewSettings };
533
+ if (!has("github")) delete views.delivery;
534
+ // Nothing imported: every page would be empty tables, so say so once.
535
+ const view = state.data.sessions.length || page === "settings" || page === "projects" ? views[page] || viewOverview : () => { renderTopbar({ crumbs: [{ label: "Overview" }] }); return NOTICES.sessions(); };
536
+ renderNav(page === "rec" ? "recs" : page === "session" ? "sessions" : views[page] ? page : "overview");
537
+ $("#content").innerHTML = view();
538
+ const key = location.hash;
539
+ if (state.lastPage !== key && !((page === "session" || page === "method") && a)) window.scrollTo(0, 0);
540
+ state.lastPage = key;
541
+ }
542
+ function rerender() {
543
+ const y = window.scrollY;
544
+ const focusId = document.activeElement?.id;
545
+ const caret = document.activeElement?.selectionStart;
546
+ route();
547
+ window.scrollTo(0, y);
548
+ const el = focusId && document.getElementById(focusId);
549
+ if (el) { el.focus({ preventScroll: true }); if (caret != null && el.setSelectionRange) el.setSelectionRange(caret, caret); }
550
+ }
551
+
552
+ // ---------- Overview ----------
553
+
554
+ function viewOverview() {
555
+ renderTopbar({ crumbs: [{ label: "Overview" }], scope: has("labels") });
556
+ const d = state.data;
557
+ const sc = scoped();
558
+ const prev = scoped(1);
559
+ const m = metrics(sc.S);
560
+ const pm = prev && prev.S.length >= 5 ? metrics(prev.S) : null;
561
+ const wk = weekly(sc.S);
562
+ const recs = allRecs();
563
+ if (!has("labels")) return NOTICES.labels();
564
+
565
+ const kpis = [
566
+ kpi({ label: "Agent corrected", def: "correction_rate", desc: "Person said it was wrong, had it redo work, or caught a bug", value: pct1(m.correctedRate), unit: "%", sub: ofText(m.corrected, m.turns, "messages"), sparkValues: wk.map((w) => w.m.correctedRate), delta: pm && delta(m.correctedRate, pm.correctedRate, { better: "down", pts: true }), href: "#corrections" }),
567
+ kpi({ label: "Agent overlooked", def: "overlooked_info", desc: "Person pointed it to info it could have found itself", value: pct1(m.could_findRate), unit: "%", sub: ofText(m.could_find, m.turns, "messages"), sparkValues: wk.map((w) => w.m.could_findRate), delta: pm && delta(m.could_findRate, pm.could_findRate, { better: "down", pts: true }), href: "#corrections" }),
568
+ kpi({ label: "Shipped rate", def: "shipped_rate", desc: "Sessions that ended with a commit or a PR ready", value: m.shipRate == null ? "—" : Math.round(100 * m.shipRate), unit: "%", sub: m.labeled ? ofText(m.shipped, m.labeled, "sessions") : "No session outcomes labelled", sparkValues: wk.map((w) => w.m.shipRate), delta: pm && delta(m.shipRate, pm.shipRate, { better: "up", pts: true }), href: "#sessions" }),
569
+ ].join("");
570
+
571
+ const trend = card({
572
+ title: "Agent corrected and overlooked, by week", def: "correction_rate", tip: "Both as a share of human messages, by the week each session started. Dotted lines and hollow points mark a week that is only partly over or has fewer than 5 sessions.",
573
+ aside: legend([{ c: "var(--sig-corrected)", label: "Agent corrected (%)" }, { c: "var(--sig-could_find)", label: "Agent overlooked (%)" }]),
574
+ body: lineChart(wk, [
575
+ { label: "Agent corrected", color: "var(--sig-corrected)", value: (w) => (w.m.correctedRate == null ? null : 100 * w.m.correctedRate) },
576
+ { label: "Agent overlooked", color: "var(--sig-could_find)", value: (w) => (w.m.could_findRate == null ? null : 100 * w.m.could_findRate) },
577
+ ], { fmtY: (v) => v.toFixed(v < 10 && v % 1 ? 1 : 0), unit: "%" }),
578
+ });
579
+
580
+ const top = card({ title: "Top ideas", def: "reach", tip: "The ideas touching the most sessions. Built from every session in scope; the period filter does not apply.", flush: true,
581
+ body: recTable(recs.slice(0, 8), { compact: true }), foot: `<a href="#recs">View all ${recs.length} ideas →</a>` });
582
+
583
+ const agentRows = [...groupBy(sc.S, (s) => s.agent)].map(([a, ss]) => [a, metrics(ss), restsOnOne(ss)]).sort((x, y) => y[1].sessions - x[1].sessions);
584
+ const maxRate = Math.max(0.0001, ...agentRows.flatMap(([, mm]) => [mm.correctedRate || 0, mm.could_findRate || 0]));
585
+ const byModel = state.overviewGroup === "model";
586
+ const rateCells = (mm, max) => `<td>${inlineBar(mm.correctedRate || 0, max, "var(--sig-corrected)", pctText(mm.correctedRate), `${mm.corrected} of ${mm.turns} messages`)}</td>
587
+ <td>${inlineBar(mm.could_findRate || 0, max, "var(--sig-could_find)", pctText(mm.could_findRate), `${mm.could_find} of ${mm.turns} messages`)}</td>`;
588
+ const mRows = byModel ? modelRows(sc.S) : [];
589
+ const maxModelRate = Math.max(0.0001, ...mRows.flatMap((r) => [r.mm.correctedRate || 0, r.mm.could_findRate || 0]));
590
+ const rows = byModel
591
+ ? mRows.map((r) => `<tr class="click" data-href="corrections"><td class="nowrap"><span class="mono">${esc(r.name)}</span>${restsPill(r.one)}</td><td class="r">${r.mm.sessions}</td>
592
+ ${rateCells(r.mm, maxModelRate)}</tr>`)
593
+ : agentRows.map(([a, mm, one]) => `<tr class="click" data-href="corrections" data-agent="${esc(a)}"><td class="nowrap">${agentChip(a)}${restsPill(one)}</td><td class="r">${mm.sessions}</td>
594
+ ${rateCells(mm, maxRate)}</tr>`);
595
+ const groupTabs = `<div class="tabs" role="group" aria-label="Group by">${[["agent", "Harness"], ["model", "Model"]].map(([k, l]) => `<button type="button" data-ov-group="${k}" aria-pressed="${state.overviewGroup === k}">${l}</button>`).join("")}</div>`;
596
+ const byAgent = card({ title: byModel ? "By model" : "By harness", def: byModel ? "by_model" : "correction_rate", aside: groupTabs, flush: true,
597
+ foot: byModel && hiddenNote(mRows) ? `<span class="muted">${hiddenNote(mRows)}</span>` : "",
598
+ body: `<div class="table-wrap tight"><table><thead><tr><th>${byModel ? "Model" : "Harness"}</th><th class="r">Sessions</th><th>Agent corrected</th><th>Agent overlooked</th></tr></thead><tbody>
599
+ ${rows.join("") || `<tr><td colspan="4" class="empty">No sessions</td></tr>`}
600
+ </tbody></table></div>` });
601
+ setTimeout(() => $$("[data-ov-group]").forEach((b) => b.addEventListener("click", () => { state.overviewGroup = b.dataset.ovGroup; rerender(); })), 0);
602
+
603
+ const dirs = hotspotDirs(sc).slice(0, 6);
604
+ const hot = card({ title: "Where corrections happen", def: "hotspot", flush: true,
605
+ body: dirs.length ? `<div class="table-wrap"><table><thead><tr><th>Directory</th><th class="r">Sessions</th><th class="r">Flagged turns</th></tr></thead><tbody>
606
+ ${dirs.map((g) => `<tr class="click" data-dir="${esc(g.dir)}"><td class="mono">${esc(g.dir)}</td><td class="r">${g.sessions.size}</td><td class="r">${g.turns.size}</td></tr>`).join("")}</tbody></table></div>` : `<div class="empty">No hotspots in this period.</div>`,
607
+ foot: `<a href="#corrections">Open corrections →</a>` });
608
+
609
+ // All projects: one row each, biggest first; a row picks its project.
610
+ const byProject = state.scope.project || state.projects.length < 2 ? "" : card({ title: "By project", tip: "Each project's sessions in this period. Ideas are counted for the whole run. Pick a row to see only that project.", flush: true,
611
+ foot: state.projects.length > 8 ? `<span class="muted">The 8 projects with the most sessions. The picker in the side bar lists all ${state.projects.length}.</span>` : "",
612
+ body: `<div class="table-wrap tight"><table><thead><tr><th>Project</th><th class="r">Sessions</th><th class="r">Messages</th><th class="r">Agent corrected</th><th class="r">Ideas</th></tr></thead><tbody>
613
+ ${state.projects.map(([p, label]) => [p, label, metrics(sc.S.filter((s) => inProject(s, p)))]).filter(([, , mm]) => mm.sessions).slice(0, 8).map(([p, label, mm]) => `<tr class="click" data-project="${esc(p)}" tabindex="0" title="${esc(p)}"><td class="nowrap">${esc(label)}</td><td class="r">${mm.sessions}</td><td class="r">${fmt(mm.turns)}</td>
614
+ <td class="r" data-tip="${mm.corrected} of ${mm.turns} messages">${pctText(mm.correctedRate)}</td><td class="r">${d.recommendations.filter((r) => r.project === p).length}</td></tr>`).join("")}
615
+ </tbody></table></div>` });
616
+
617
+ const section = (title, sub) => `<div class="section-title"><h2>${esc(title)}</h2>${sub ? `<span>${sub}</span>` : ""}</div>`;
618
+ return `${intro()}
619
+ ${section("Statistics", scopeLabel())}
620
+ <div class="kpis cols-3">${kpis}</div>
621
+ <div class="grid"><div class="span-7">${trend}</div><div class="span-5">${byAgent}</div>${byProject ? `<div class="span-12">${byProject}</div>` : ""}</div>
622
+ ${section("Corrections", scopeLabel())}
623
+ <div class="grid"><div class="span-12">${hot}</div></div>
624
+ ${section("Ideas", `From ${fromSessions()}; the period and harness filters don't apply`)}
625
+ <div class="grid"><div class="span-12">${recs.length ? top : NOTICES.ideas()}</div></div>`;
626
+ }
627
+
628
+ // A backlog title names the fix ("Fix macOS path failure in …"); in a list, name the bug itself.
629
+ const bugName = (title) => title.replace(/^(check and file:\s*|(fix|track|make|reject|unify|validate)\s+(the\s+)?)/i, "");
630
+
631
+ // The first thing a new viewer reads: what this is, and three findings computed from all sessions.
632
+ function intro() {
633
+ const d = state.data;
634
+ const all = allSessions();
635
+ const recs = allRecs();
636
+ const m = metrics(all);
637
+ const prs = new Set(all.flatMap((s) => s.prs.filter((p) => p.state !== "open").map((p) => p.n))).size;
638
+ const people = has("people") ? ` from ${plural(recs[0]?.people, "person", "people")}` : "";
639
+ const stats = [`${fmt(all.length)} sessions`, has("people") && plural(m.people, "person", "people"), `${fmt(m.turns)} human messages`,
640
+ has("github") && `${fmt(prs)} merged or closed PRs with CI and review`, `${day(d.meta.from)} – ${day(d.meta.to)}`].filter(Boolean).join(" · ");
641
+
642
+ // Compare only harnesses with 20+ sessions whose rate doesn't rest on one session; name any
643
+ // harness left out for resting on one session when its rate sits outside the compared ones.
644
+ const agents = [...groupBy(all, (s) => s.agent)].filter(([, ss]) => ss.length >= 5)
645
+ .map(([a, ss]) => ({ a, n: ss.length, rate: metrics(ss).correctedRate, one: restsOnOne(ss) })).sort((x, y) => y.rate - x.rate);
646
+ const solid = agents.filter((x) => x.n >= 20 && !x.one);
647
+ const hi = solid[0];
648
+ const lo = solid[solid.length - 1];
649
+ const compared = hi && lo && hi !== lo ? `${esc(hi.a)} was corrected in ${pctText(hi.rate)} of messages, ${esc(lo.a)} in ${pctText(lo.rate)}.` : "";
650
+ const caveats = hi ? agents.filter((x) => x.one && (x.rate > hi.rate || x.rate < lo.rate))
651
+ .map((x) => `${esc(x.a)}'s ${x.rate > hi.rate ? "higher" : "lower"} rate comes mostly from one session.`) : [];
652
+ const agentLine = [compared, ...caveats].filter(Boolean).join(" ");
653
+
654
+ const top = recs[0];
655
+ // Bug ideas whose evidence held up; weak ones stay on the Ideas page but aren't counted here.
656
+ const bugs = recs.filter((r) => !r.weak && r.findings.some((i) => d.findings[i]?.kind === "found_not_filed"));
657
+
658
+ const findings = [
659
+ m.corrected && { big: `1 in ${Math.round(1 / m.correctedRate)}`, what: "messages people send an agent correct its work.", detail: agentLine, go: "See the messages", href: "#corrections" },
660
+ top && { eyebrow: "Top idea", title: top.title, detail: `Backed by ${plural(top.evidence.length, "cited item")} across ${plural(top.sessions.length, "session")}${people}.`, go: "See the change and evidence", href: `#rec~${top.id}` },
661
+ bugs.length && { big: fmt(bugs.length), what: "possible bugs agents flagged outside their task and left unfiled in the session.", detail: `For example: ${bugs.slice(0, 2).map((r) => `“${esc(bugName(r.title))}”`).join(" and ")}.`, go: "See the list", href: "#recs", lever: bugs[0]?.lever },
662
+ ].filter(Boolean);
663
+
664
+ return `<section class="card intro">
665
+ <div class="intro-head">
666
+ <h2>Session debrief</h2>
667
+ ${workspaceLabel() ? `<p class="intro-repo mono">${esc(workspaceLabel())}</p>` : ""}
668
+ <p class="intro-stats">${stats}</p>
669
+ </div>
670
+ <div class="findings">${findings.map((f) => `<div class="finding-cell">
671
+ ${f.eyebrow ? `<span class="finding-eyebrow">${esc(f.eyebrow)}</span><span class="finding-title">${esc(f.title)}</span>` : `<span class="finding-big num">${f.big}</span><span class="finding-title">${esc(f.what)}</span>`}
672
+ ${f.detail ? `<p class="finding-detail">${f.detail}</p>` : ""}
673
+ <a class="finding-go" href="${f.href}"${f.lever ? ` data-lever="${esc(f.lever)}"` : ""}>${esc(f.go)} →</a>
674
+ </div>`).join("")}</div>
675
+ </section>`;
676
+ }
677
+
678
+ function hotspotDirs(sc) {
679
+ const dirs = new Map();
680
+ for (const f of sc.files) {
681
+ const dir = dirOf(f.path);
682
+ const g = dirs.get(dir) || dirs.set(dir, { dir, sessions: new Set(), turns: new Set(), files: [] }).get(dir);
683
+ f.sessions.forEach((s) => g.sessions.add(s));
684
+ f.turns.forEach((t) => g.turns.add(`${t.s}~${t.i}`));
685
+ g.files.push(f);
686
+ }
687
+ return [...dirs.values()].sort((a, b) => b.sessions.size - a.sessions.size || b.turns.size - a.turns.size);
688
+ }
689
+
690
+ // ---------- Recommendations ----------
691
+
692
+ function filteredRecs() {
693
+ const f = state.recFilter;
694
+ const q = f.q.trim().toLowerCase();
695
+ return allRecs().filter((r) => (!f.lever || r.lever === f.lever) &&
696
+ (!q || `${r.title} ${r.target} ${r.problem}`.toLowerCase().includes(q)));
697
+ }
698
+
699
+ function viewRecs() {
700
+ const d = state.data;
701
+ renderTopbar({ crumbs: [{ label: "Ideas" }] });
702
+ const f = state.recFilter;
703
+ const recs = filteredRecs();
704
+ const all = allRecs();
705
+ if (!all.length) return has("labels") ? NOTICES.ideas() : NOTICES.labels();
706
+ const levers = [...new Set([...Object.keys(d.levers || {}), ...all.map((r) => r.lever)])];
707
+ const segs = [["", "All", all.length], ...levers.map((k) => [k, lever(k), all.filter((r) => r.lever === k).length]).filter(([, , n]) => n)];
708
+ // All projects: a table per project, biggest first, then the ideas that span projects.
709
+ // A run from before ideas had projects has no groups, so it stays one table.
710
+ const groups = state.scope.project ? [] : state.projects.map(([p, label]) => [label, recs.filter((r) => r.project === p)]).filter(([, rs]) => rs.length);
711
+ const tables = groups.length
712
+ ? [...groups, ["Across projects", recs.filter((r) => !r.project)]].filter(([, rs]) => rs.length).map(([label, rs]) => `<div class="group-head"><h3>${esc(label)}</h3><span class="muted small num">${plural(rs.length, "idea")}</span></div>${recTable(sortRecs(rs), { sortable: true })}`).join("")
713
+ : recTable(sortRecs(recs), { sortable: true });
714
+ return `<p class="page-sub">${all.length} ideas from ${fromSessions()}, sorted by how many sessions each touches. Each is a lead to check against its evidence, not a verdict.</p>
715
+ <section class="card">
716
+ <div class="toolbar">
717
+ <input type="search" id="rec-q" placeholder="Search ideas" value="${esc(f.q)}" aria-label="Search ideas">
718
+ <div class="seg-ctl" role="group" aria-label="Type">${segs.map(([k, l, n]) => `<button type="button" data-rec-lever="${esc(k)}" aria-pressed="${f.lever === k}">${esc(l)}<span class="n">${n}</span></button>`).join("")}</div>
719
+ <span class="spacer"></span><span class="muted small num">${recs.length} shown</span>
720
+ </div>
721
+ ${tables}
722
+ </section>`;
723
+ }
724
+
725
+ function viewRec(id) {
726
+ const d = state.data;
727
+ const r = d.recommendations.find((x) => String(x.id) === String(id));
728
+ if (!r) { renderTopbar({ crumbs: [{ label: "Ideas", href: "#recs" }, { label: "Not found" }] }); return `<div class="empty">This idea is not in the current run.</div>`; }
729
+ // Step through the picked project's ideas; an idea opened from outside it steps through all.
730
+ const order = sortRecs(allRecs().includes(r) ? allRecs() : d.recommendations);
731
+ const i = order.indexOf(r);
732
+ const pager = `<div class="pager"><a href="#rec~${order[i - 1]?.id}" aria-label="Previous idea" aria-disabled="${i === 0}">↑</a><a href="#rec~${order[i + 1]?.id}" aria-label="Next idea" aria-disabled="${i === order.length - 1}">↓</a></div>`;
733
+ renderTopbar({ crumbs: [{ label: "Ideas", href: "#recs" }, { label: r.title }], right: pager });
734
+
735
+ const ev = r.evidence.map((k) => d.refs[k]).filter((x) => x && x.type !== "missing");
736
+ const counts = { msg: ev.filter((x) => x.type === "msg").length, check: ev.filter((x) => x.type === "check").length, review: ev.filter((x) => x.type === "review").length };
737
+ const tabs = [["all", "All", ev.length], ["msg", "Messages", counts.msg], ["check", "CI runs", counts.check], ["review", "Review comments", counts.review]].filter(([, , n], j) => j === 0 || n);
738
+ if (!tabs.some(([k]) => k === state.evTab)) state.evTab = "all";
739
+ const shown = ev.filter((x) => state.evTab === "all" || x.type === state.evTab);
740
+
741
+ const main = `<div class="detail-main">
742
+ <section class="card"><div class="card-body" style="gap:14px">
743
+ <div class="issue-title">${esc(r.title)}</div>
744
+ ${r.impact ? `<div class="summary">${esc(r.impact)}</div>` : ""}
745
+ <div><h3 style="margin-bottom:6px">Problem</h3><div class="prose">${md(r.problem)}</div></div>
746
+ <div><div class="change-head" style="margin-bottom:6px"><h3>Suggested change</h3><button type="button" id="copy-change">Copy</button></div>
747
+ <div class="change-body" id="change-body">${md(r.change)}</div></div>
748
+ </div></section>
749
+ ${card({ title: "Evidence", aside: `<div class="tabs" role="group" aria-label="Evidence type">${tabs.map(([k, l, n]) => `<button type="button" data-ev-tab="${k}" aria-pressed="${state.evTab === k}">${l} <span class="num">${n}</span></button>`).join("")}</div>`, flush: true,
750
+ body: `<div class="evlist">${shown.map(evidenceItem).join("")}</div>` })}
751
+ </div>`;
752
+
753
+ const props = `<aside class="card props">
754
+ <dl>
755
+ <dt>Type</dt><dd>${esc(lever(r.lever))}</dd>
756
+ ${state.projects.length > 1 ? `<dt>Project</dt><dd${r.project ? ` title="${esc(r.project)}"` : ""}>${r.project ? esc(projectName(r.project)) : "Across projects"}</dd>` : ""}
757
+ ${r.target ? `<dt>Lands in</dt><dd class="mono small">${esc(r.target)}</dd>` : ""}
758
+ </dl>
759
+ <div class="section"><h3>Reach</h3>
760
+ <div class="num">${plural(r.sessions.length, "session")}${has("people") ? ` · ${plural(r.people, "person", "people")}` : ""}</div>
761
+ ${r.checked ? `<div class="small" data-tip="A second model pass checked each cited item against this idea; items that didn't support it are hidden and don't count toward reach.">${r.evidence.length} of ${plural(r.evidence_all, "cited item")} support this idea</div>` : ""}
762
+ ${ev.length ? `<div class="muted small">${[counts.msg && plural(counts.msg, "message"), counts.check && plural(counts.check, "CI run"), counts.review && plural(counts.review, "review comment")].filter(Boolean).join(" · ")}${r.checked ? "" : " cited"}</div>` : ""}
763
+ ${r.weak ? `<div class="small" style="color:var(--text-muted)">Weak evidence. ${WEAK_TIP}</div>` : r.sessions.length <= 1 ? `<div class="small" style="color:var(--text-muted)">Single session. Check the evidence before acting.</div>` : ""}
764
+ </div>
765
+ </aside>`;
766
+
767
+ setTimeout(() => wireRec(r), 0);
768
+ return `<div class="detail">${main}${props}</div>`;
769
+ }
770
+
771
+ function evidenceItem(x) {
772
+ if (x.type === "msg") {
773
+ const s = state.sessionsById.get(x.session_id) || {};
774
+ const who = x.role === "assistant" ? "Agent" : "Human";
775
+ const sigs = (x.signals || []).filter((g) => g !== "not_filed" || x.role === "assistant");
776
+ return `<a class="ev" href="${sessionHref(x.session_id, x.msg_idx)}">
777
+ <div class="ev-head"><span class="src">${esc(s.name || short(x.session_id))}</span><span>${esc(ranBy(s))} · turn ${x.msg_idx}</span></div>
778
+ <div class="quote${x.role === "assistant" ? " agent" : ""}"><span class="muted small">${who}: </span>${esc(x.role === "assistant" ? x.agent_before || x.text : x.text)}</div>
779
+ ${sigs.length ? `<div class="chips">${sigs.map((g) => sigChip(g, g === "correction" && x.correction_type ? ` · ${esc(CORRECTION_TYPES[x.correction_type] || x.correction_type)}` : "")).join("")}</div>` : ""}
780
+ </a>`;
781
+ }
782
+ if (x.type === "check") {
783
+ return `<div class="ev">
784
+ <div class="ev-head"><span class="src">CI · <span class="mono">${esc(x.name)}</span> failed</span><span>${esc(CI_CLASSES[x.failure_class] || "Unlabeled")} · ${dayTime(x.at)} · ${x.prs.map(prLink).join(", ") || "no PR"}${x.sessions.length ? ` · <a href="${sessionHref(x.sessions[0])}">session</a>` : ""}</span></div>
785
+ <details><summary>Log tail</summary><pre style="margin-top:6px">${esc(x.log)}</pre></details>
786
+ </div>`;
787
+ }
788
+ if (x.type === "review") {
789
+ const loc = x.path ? `${x.path}${x.line ? ":" + x.line : ""}` : "PR";
790
+ return `<div class="ev">
791
+ <div class="ev-head"><span class="src">Review · ${esc(x.author)}${x.is_bot ? " (bot)" : ""}</span><span><span class="mono">${esc(loc)}</span> · ${prLink(x.pr)} · ${esc(HELD[x.held_up] || "Unlabeled")} · thread ${x.resolved ? "resolved" : x.outdated ? "outdated" : "open"}</span></div>
792
+ <div class="quote agent">${esc(x.body)}</div>
793
+ </div>`;
794
+ }
795
+ return "";
796
+ }
797
+
798
+ function wireRec(r) {
799
+ $$("[data-ev-tab]").forEach((b) => b.addEventListener("click", () => { state.evTab = b.dataset.evTab; rerender(); }));
800
+ $("#copy-change")?.addEventListener("click", async (e) => {
801
+ try { await navigator.clipboard.writeText(r.change || ""); e.target.textContent = "Copied"; } catch {
802
+ const range = document.createRange();
803
+ range.selectNodeContents($("#change-body"));
804
+ getSelection().removeAllRanges();
805
+ getSelection().addRange(range);
806
+ e.target.textContent = "Selected";
807
+ }
808
+ setTimeout(() => { e.target.textContent = "Copy"; }, 2000);
809
+ });
810
+ }
811
+
812
+ // ---------- Corrections ----------
813
+
814
+ function viewCorrections() {
815
+ renderTopbar({ crumbs: [{ label: "Corrections" }], scope: has("labels") });
816
+ const sc = scoped();
817
+ const prev = scoped(1);
818
+ const m = metrics(sc.S);
819
+ const pm = prev && prev.S.length >= 5 ? metrics(prev.S) : null;
820
+ const wk = weekly(sc.S);
821
+ const f = state.correctionsFilter;
822
+ if (!has("labels")) return NOTICES.labels();
823
+
824
+ const headline = kpi({ label: "Agent corrected", def: "correction_rate", value: pct1(m.correctedRate), unit: "%", sub: ofText(m.corrected, m.turns, "messages"),
825
+ sparkValues: wk.map((w) => w.m.correctedRate), delta: pm && delta(m.correctedRate, pm.correctedRate, { better: "down", pts: true }) })
826
+ + kpi({ label: "Agent overlooked", def: "overlooked_info", value: pct1(m.could_findRate), unit: "%", sub: ofText(m.could_find, m.turns, "messages"),
827
+ sparkValues: wk.map((w) => w.m.could_findRate), delta: pm && delta(m.could_findRate, pm.could_findRate, { better: "down", pts: true }) });
828
+
829
+ const agentRows = [...groupBy(sc.S, (s) => s.agent)].map(([a, ss]) => ({ a, mm: metrics(ss), one: restsOnOne(ss), tools: sum(ss, (s) => s.tool_calls), err: sum(ss, (s) => s.tool_errors) }))
830
+ .sort((x, y) => y.mm.sessions - x.mm.sessions);
831
+ const cols = [
832
+ { label: "Agent corrected", rate: (mm) => mm.correctedRate, n: (mm) => mm.corrected, color: "var(--sig-corrected)" },
833
+ ...CORRECTION_KINDS.map((g) => ({ label: SIGNALS[g].plural, rate: (mm) => mm[`${g}Rate`], n: (mm) => mm[g], color: `var(--sig-${g})`, sub: true })),
834
+ { label: "Agent overlooked", rate: (mm) => mm.could_findRate, n: (mm) => mm.could_find, color: "var(--sig-could_find)" },
835
+ ];
836
+ const maxRate = Math.max(0.0001, ...agentRows.flatMap((r) => cols.map((c) => c.rate(r.mm) || 0)));
837
+ const byAgent = card({ title: "By harness", def: "correction_rate", tip: "Each as a share of the agent's human messages. The three middle columns break down Agent corrected; a message can count in more than one. Codex runs everything through one shell tool, so its failed-call rate includes test runs that fail on purpose.", flush: true,
838
+ body: `<div class="table-wrap"><table><thead><tr><th>Harness</th><th class="r">Sessions</th><th class="r">Human messages</th>${cols.map((c) => `<th${c.sub ? ' class="muted"' : ""}>${esc(c.label)}</th>`).join("")}<th class="r">Failed tool calls</th></tr></thead><tbody>
839
+ ${agentRows.map((r) => `<tr><td class="nowrap">${agentChip(r.a)}${r.mm.sessions < 10 ? ` <span class="pill" data-tip="Fewer than 10 sessions: treat the rates as anecdotes">low n</span>` : restsPill(r.one)}</td><td class="r">${r.mm.sessions}</td><td class="r">${fmt(r.mm.turns)}</td>
840
+ ${cols.map((c) => `<td>${inlineBar(c.rate(r.mm) || 0, maxRate, c.color, pctText(c.rate(r.mm)), `${r.a}: ${c.n(r.mm)} of ${r.mm.turns} messages`)}</td>`).join("")}
841
+ <td class="r">${r.tools ? `${pct(r.err, r.tools)}% <span class="muted">of ${fmt(r.tools)}</span>` : `<span class="muted">—</span>`}</td></tr>`).join("")}</tbody></table></div>` });
842
+
843
+ const mRows = modelRows(sc.S);
844
+ const maxModelRate = Math.max(0.0001, ...mRows.flatMap((r) => [r.mm.correctedRate || 0, r.mm.could_findRate || 0]));
845
+ const byModel = card({ title: "By model", def: "by_model", flush: true, foot: hiddenNote(mRows) && `<span class="muted">${hiddenNote(mRows)}</span>`,
846
+ body: `<div class="table-wrap"><table><thead><tr><th>Model</th><th>Harnesses</th><th class="r">Sessions</th><th class="r">Human messages</th><th>Agent corrected</th><th>Agent overlooked</th></tr></thead><tbody>
847
+ ${mRows.map((r) => `<tr><td class="nowrap"><span class="mono">${esc(r.name)}</span>${restsPill(r.one)}</td><td>${harnessDots(r.agents)}</td><td class="r">${r.mm.sessions}</td><td class="r">${fmt(r.mm.turns)}</td>
848
+ ${`<td>${inlineBar(r.mm.correctedRate || 0, maxModelRate, "var(--sig-corrected)", pctText(r.mm.correctedRate), `${r.name}: ${r.mm.corrected} of ${r.mm.turns} messages`)}</td>
849
+ <td>${inlineBar(r.mm.could_findRate || 0, maxModelRate, "var(--sig-could_find)", pctText(r.mm.could_findRate), `${r.name}: ${r.mm.could_find} of ${r.mm.turns} messages`)}</td>`}</tr>`).join("") || `<tr><td colspan="6" class="empty">No sessions</td></tr>`}</tbody></table></div>` });
850
+
851
+ const corrections = sc.flagged.filter((t) => t.sig.includes("correction"));
852
+ const types = [...groupBy(corrections, (t) => t.ctype || "unclassified")].sort((a, b) => b[1].length - a[1].length);
853
+ const typeCard = card({ title: "What the agent got wrong", def: "mistake_types", tip: "For messages that said the agent was wrong, what kind of mistake it was. Click a row to filter the messages below.",
854
+ aside: plural(corrections.length, "message"),
855
+ body: bars(types.map(([k, ts]) => ({ label: CORRECTION_TYPES[k] || k, value: ts.length, color: "var(--sig-corrected)", href: `corrections~ctype~${k}`, tip: `${ts.length} messages in ${new Set(ts.map((t) => t.s)).size} sessions` })), { labelWidth: "minmax(110px,190px)" }) });
856
+
857
+ const dirs = hotspotDirs(sc).slice(0, 10);
858
+ const dirCard = card({ title: "Where corrections happen", def: "hotspot", flush: true,
859
+ body: dirs.length ? `<div class="table-wrap"><table><thead><tr><th>Directory</th><th class="r">Sessions</th><th class="r">Flagged turns</th><th class="r">Files</th></tr></thead><tbody>
860
+ ${dirs.map((g) => `<tr class="click" data-dir="${esc(g.dir)}"${f.dir === g.dir ? ' style="background:var(--surface-selected)"' : ""}><td class="mono">${esc(g.dir)}</td><td class="r">${g.sessions.size}</td><td class="r">${g.turns.size}</td><td class="r">${g.files.length}</td></tr>`).join("")}</tbody></table></div>` : `<div class="empty">No hotspots in this period.</div>` });
861
+
862
+ // Flagged turns, filtered by signal, correction type or directory.
863
+ let turns = sc.flagged;
864
+ if (f.signal) turns = turns.filter((t) => t.sig.includes(f.signal));
865
+ if (f.ctype) turns = turns.filter((t) => t.sig.includes("correction") && (t.ctype || "unclassified") === f.ctype);
866
+ if (f.dir) {
867
+ const keys = new Set(sc.files.filter((x) => dirOf(x.path) === f.dir).flatMap((x) => x.turns.map((t) => `${t.s}~${t.i}`)));
868
+ turns = turns.filter((t) => keys.has(`${t.s}~${t.i}`));
869
+ }
870
+ turns = interleave(turns.slice().sort((a, b) => time(b.ts || 0) - time(a.ts || 0)), (t) => t.s);
871
+ const sigCounts = Object.fromEntries(SIG_ORDER.map((g) => [g, sc.flagged.filter((t) => t.sig.includes(g)).length]));
872
+ const active = [f.ctype && `Type: ${CORRECTION_TYPES[f.ctype] || f.ctype}`, f.dir && `Directory: ${f.dir}`].filter(Boolean);
873
+ const turnCard = `<section class="card">
874
+ <div class="card-head"><h2>Flagged messages ${info("Every human message that corrected the agent or pointed it to info it overlooked. Click a row to open the session at that message.")}</h2><span class="aside num">${plural(turns.length, "message")}</span></div>
875
+ <div class="toolbar">
876
+ <div class="seg-ctl" role="group" aria-label="Signal"><button type="button" data-signal="" aria-pressed="${!f.signal}">All<span class="n">${sc.flagged.length}</span></button>${SIG_ORDER.map((g) => `<button type="button" data-signal="${g}" aria-pressed="${f.signal === g}">${glyph(g)} ${SIGNALS[g].label}<span class="n">${sigCounts[g]}</span></button>`).join("")}</div>
877
+ ${active.map((a) => `<span class="pill accent">${esc(a)}</span>`).join("")}${active.length ? `<button type="button" class="linklike" id="clear-corrections">Clear</button>` : ""}
878
+ </div>
879
+ ${turns.length ? `<div class="table-wrap" style="max-height:560px;overflow-y:auto"><table><thead><tr><th>Date</th><th>Session</th><th>Signals</th><th>What the person said</th></tr></thead><tbody>${turnRows(turns.slice(0, 150))}</tbody></table></div>
880
+ ${turns.length > 150 ? `<div class="card-foot muted">Showing 150 of ${turns.length}. Narrow with the filters above.</div>` : ""}` : `<div class="empty">No turns match.</div>`}
881
+ </section>`;
882
+
883
+ setTimeout(wireCorrections, 0);
884
+ return `<p class="page-sub">${scopeLabel()} · ${fmt(m.turns)} human messages</p>
885
+ <div class="kpis cols-2">${headline}</div>
886
+ <div class="grid"><div class="span-12">${byAgent}</div><div class="span-12">${byModel}</div><div class="span-5">${typeCard}</div><div class="span-7">${dirCard}</div><div class="span-12" id="turns">${turnCard}</div></div>`;
887
+ }
888
+
889
+ function wireCorrections() {
890
+ const f = state.correctionsFilter;
891
+ $$("[data-signal]").forEach((b) => b.addEventListener("click", () => { f.signal = b.dataset.signal; rerender(); }));
892
+ $("#clear-corrections")?.addEventListener("click", () => { f.ctype = ""; f.dir = ""; if (location.hash === "#corrections") rerender(); else location.hash = "corrections"; });
893
+ }
894
+
895
+ // ---------- Adoption ----------
896
+
897
+ function viewAdoption() {
898
+ renderTopbar({ crumbs: [{ label: "Adoption" }], scope: true });
899
+ const sc = scoped();
900
+ const S = sc.S;
901
+ const all = allSessions();
902
+ const agents = [...new Set(all.map((s) => s.agent))].sort((a, b) => all.filter((s) => s.agent === b).length - all.filter((s) => s.agent === a).length);
903
+ const wk = weekly(S);
904
+ const labelled = has("labels");
905
+ const habits = habitCard(S, new Set(sc.skills.map((u) => u.s)));
906
+
907
+ const maxWeek = Math.max(1, ...wk.map((w) => w.S.length));
908
+ const weekChart = wk.length ? `<div class="col-chart"><div class="cols">${wk.map((w) => `<div class="col">${agents.map((a) => { const n = w.S.filter((s) => s.agent === a).length;
909
+ return n ? `<span class="seg" style="height:${(100 * n) / maxWeek}%;--c:${agentColor(a)}" data-tip="Week of ${day(w.week)}\n${a}: ${n}"></span>` : ""; }).join("")}</div>`).join("")}</div>
910
+ <div class="col-labels">${wk.map((w) => `<span>${day(w.week)}</span>`).join("")}</div></div>` : `<div class="empty">No sessions.</div>`;
911
+
912
+ const models = [...groupBy(S, (s) => `${s.agent}|${s.model || "unknown"}`)].sort((a, b) => b[1].length - a[1].length);
913
+ const moreModels = models.length - 10;
914
+ const people = [...groupBy(S.filter((s) => s.author), (s) => s.author)].sort((a, b) => b[1].length - a[1].length);
915
+ const nobody = S.filter((s) => !s.author);
916
+ if (nobody.length) people.push([NO_PERSON, nobody]);
917
+
918
+ const kinds = {};
919
+ S.forEach((s) => Object.entries(s.turn_kinds).forEach(([k, n]) => { kinds[k] = (kinds[k] || 0) + n; }));
920
+ const totalTurns = sum(Object.values(kinds));
921
+ const kindRows = Object.entries(kinds).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ label: TURN_KINDS[k] || k, value: n, valText: `${pct(n, totalTurns)}%`, color: k === "correction" ? "var(--sig-corrected)" : undefined, tip: `${fmt(n)} messages` }));
922
+
923
+ // Without GitHub no session has a settled PR, so compare all of them.
924
+ const settled = has("github") ? S.filter((s) => s.settled) : S;
925
+ const styles = [...groupBy(settled.filter((s) => s.prompt_style), (s) => s.prompt_style)].map(([k, ss]) => ({ k, n: ss.length, f: sum(ss, correctedTurns) / ss.length, shipped: ss.filter((s) => s.outcome === "shipped_or_pr_ready").length }))
926
+ .sort((a, b) => a.f - b.f);
927
+ const maxF = Math.max(0.0001, ...styles.map((r) => r.f));
928
+
929
+ const skills = [...groupBy(sc.skills, (u) => u.skill)].map(([k, us]) => ({ k, sessions: new Set(us.map((u) => u.s)).size, human: us.filter((u) => u.by === "human").length, agent: us.filter((u) => u.by === "agent").length }))
930
+ .sort((a, b) => b.sessions - a.sessions || b.human + b.agent - a.human - a.agent).slice(0, 12);
931
+
932
+ return `<p class="page-sub">${scopeLabel()}</p>
933
+ <div class="grid">
934
+ ${labelled ? `<div class="span-12">${habits}</div>` : ""}
935
+ <div class="span-8">${card({ title: "Sessions by week", def: "sessions", tip: "Sessions by the week they started.", aside: legend(agents.map((a) => ({ c: agentColor(a), label: a }))), body: weekChart })}</div>
936
+ <div class="span-4">${card({ title: "Harnesses and models", flush: true, foot: moreModels > 0 ? `<span class="muted">+${plural(moreModels, "more model")}</span>` : "",
937
+ body: `<div class="table-wrap"><table><thead><tr><th>Harness</th><th>Model</th><th class="r">Sessions</th></tr></thead><tbody>${models.slice(0, 10).map(([k, ss]) => { const [a, mo] = k.split("|"); return `<tr><td class="nowrap">${agentChip(a)}</td><td class="mono small">${esc(mo)}</td><td class="r">${ss.length}</td></tr>`; }).join("")}</tbody></table></div>` })}</div>
938
+ ${has("people") ? `<div class="span-6">${card({ title: "People", def: "per_person", tip: `${defTip("per_person")}${nobody.length ? ` ${plural(nobody.length, "session")} ha${nobody.length === 1 ? "s" : "ve"} no person: the harness didn't record who ran them.` : ""}`, flush: true,
939
+ body: `<div class="table-wrap"><table><thead><tr><th>Person</th><th class="r">Sessions</th><th>Harnesses</th><th class="r">Human messages</th><th>Last session</th></tr></thead><tbody>
940
+ ${people.map(([p, ss]) => `<tr class="click" data-href="sessions" data-author="${esc(p)}"><td${p === NO_PERSON ? ' class="muted"' : ""}>${esc(personLabel(p, "No person recorded"))}</td><td class="r">${ss.length}</td><td><span class="mini">${[...new Set(ss.map((s) => s.agent))].map((a) => `<span class="dot" style="--c:${agentColor(a)}" data-tip="${esc(a)}"></span>`).join("")}</span></td><td class="r">${fmt(sum(ss, (s) => s.human_turns))}</td><td class="num">${day(ss.reduce((x, s) => (time(s.started) > time(x) ? s.started : x), ss[0].started))}</td></tr>`).join("")}
941
+ </tbody></table></div>` })}</div>` : ""}
942
+ ${labelled ? `<div class="span-6">${card({ title: "How human messages are spent", def: "turn_kinds", aside: `${fmt(totalTurns)} messages`, body: bars(kindRows, { labelWidth: "minmax(120px,170px)" }) })}</div>
943
+ <div class="span-6">${card({ title: "Opening prompt vs corrections", def: "prompt_styles", tip: has("github") ? "" : "How the person opened the session. Small groups: read a gap as a lead, not proof.",
944
+ aside: `${has("github") ? "Sessions with a merged or closed PR" : "All sessions"} (${fmt(settled.length)})`, flush: true,
945
+ body: `<div class="table-wrap"><table><thead><tr><th>Opening prompt</th><th class="r">Sessions</th><th>Corrections / session</th><th class="r">Shipped</th></tr></thead><tbody>
946
+ ${styles.map((r) => `<tr><td>${esc(PROMPT_STYLES[r.k] || r.k)}</td><td class="r">${r.n}</td><td>${inlineBar(r.f, maxF, "var(--sig-corrected)", r.f.toFixed(2))}</td><td class="r">${pct(r.shipped, r.n)}%</td></tr>`).join("") || `<tr><td colspan="4" class="empty">No ${has("github") ? "settled sessions" : "sessions with a labelled opening prompt"} in this period.</td></tr>`}
947
+ </tbody></table></div>` })}</div>` : ""}
948
+ <div class="span-6">${card({ title: "Skills and slash commands", def: "skills_use", flush: true,
949
+ body: skills.length ? `<div class="table-wrap"><table><thead><tr><th>Skill</th><th class="r">Sessions</th><th class="r">Typed</th><th class="r">Auto-loaded</th></tr></thead><tbody>
950
+ ${skills.map((k) => `<tr><td class="mono small">${esc(k.k)}</td><td class="r">${k.sessions}</td><td class="r">${k.human}</td><td class="r">${k.agent}</td></tr>`).join("")}</tbody></table></div>` : `<div class="empty">No skill use in this period.</div>` })}</div>
951
+ </div>`;
952
+ }
953
+
954
+ // Agent corrected in sessions with each habit vs without. Sessions with no label for a habit sit out that row.
955
+ const HABITS = [
956
+ { label: "Agent planned before editing", has: (s) => (s.planned_first ? s.planned_first === "true" : null) },
957
+ { label: "Session changed tests", has: (s) => (s.tests_added ? s.tests_added === "true" : null) },
958
+ { label: "Used a skill or slash command", has: (s, skilled) => skilled.has(s.id) },
959
+ { label: "Opened with an issue or PR link", has: (s) => (s.prompt_style ? s.prompt_style === "links_issue_or_pr" : null) },
960
+ ];
961
+ function habitCard(S, skilled) {
962
+ const rows = HABITS.map((h) => {
963
+ const by = groupBy(S, (s) => h.has(s, skilled));
964
+ const yes = by.get(true) || [];
965
+ const no = by.get(false) || [];
966
+ return { label: h.label, yes: metrics(yes), no: metrics(no), yesOne: restsOnOne(yes), noOne: restsOnOne(no) };
967
+ });
968
+ const max = Math.max(0.0001, ...rows.flatMap((r) => [r.yes.correctedRate || 0, r.no.correctedRate || 0]));
969
+ const cell = (mm, one) => `<td>${inlineBar(mm.correctedRate || 0, max, "var(--sig-corrected)", pctText(mm.correctedRate), `${mm.corrected} of ${mm.turns} messages`)}<div class="cell-sub">${plural(mm.sessions, "session")}${restsPill(one)}</div></td>`;
970
+ // Under 2 points, or a side that rests on one session, is too close to call.
971
+ const diff = (r) => {
972
+ if (r.yes.sessions < 20 || r.no.sessions < 20) return `<span class="muted small">too few sessions</span>`;
973
+ const d = 100 * (r.yes.correctedRate - r.no.correctedRate);
974
+ if (Math.abs(d) < 2 || r.yesOne || r.noOne) {
975
+ return `<span class="muted small" data-tip="${Math.abs(d).toFixed(1)} pts ${d < 0 ? "fewer" : "more"} with the habit">no clear difference</span>`;
976
+ }
977
+ return `<span class="delta ${d < 0 ? "good" : "bad"}">${Math.abs(d).toFixed(1)} pts ${d < 0 ? "fewer" : "more"}</span>`;
978
+ };
979
+ return card({ title: "Habits and corrections", tip: "Share of human messages that corrected the agent, in sessions with and without each habit. A difference is a lead, not proof: harder tasks may draw both the habit and the corrections. Gaps under 2 points, or where one side rests on a single session, show as no clear difference.",
980
+ aside: `All sessions (${fmt(S.length)})`, flush: true,
981
+ body: `<div class="table-wrap"><table><thead><tr><th>Habit</th><th>With</th><th>Without</th><th class="r">Difference</th></tr></thead><tbody>
982
+ ${rows.map((r) => `<tr><td>${esc(r.label)}</td>${cell(r.yes, r.yesOne)}${cell(r.no, r.noOne)}<td class="r nowrap">${diff(r)}</td></tr>`).join("")}</tbody></table></div>` });
983
+ }
984
+
985
+ // ---------- CI & review ----------
986
+
987
+ function viewDelivery() {
988
+ renderTopbar({ crumbs: [{ label: "CI & review" }], scope: true });
989
+ const sc = scoped();
990
+ const fails = sc.fails;
991
+ const R = sc.reviews;
992
+ const bots = R.filter((r) => r.bot);
993
+ // Validity counts inline comments only: review summaries can't be right or wrong, and they repeat inline findings.
994
+ const inlineR = R.filter((r) => r.kind === "inline");
995
+ const botInline = inlineR.filter((r) => r.bot);
996
+ const botWrong = botInline.filter((r) => r.held === "wrong").length;
997
+ const heldTip = "Inline review comments only; review summaries can't be right or wrong.";
998
+ const infra = fails.filter((f) => f.class === "infra_or_env").length;
999
+ // Checks data holds only each check's latest attempt, so re-run passes show up only once data has retries.
1000
+ const reruns = fails.filter((f) => f.flaky).length;
1001
+ const rerunTip = "Seen, not judged: the same check failed, then passed later on the same commit. Flaky test is a cause read from the log, so the two counts needn't match.";
1002
+ const failNote = `${plural(fails.length, "failed run")} on merged or closed PRs in this window.${fails.length < state.data.meta.check_failures ? ` The rest of the ${fmt(state.data.meta.check_failures)} failed runs on record are on open PRs or an approval gate, or before the window.` : ""}`;
1003
+ // A share of nothing is a dash, not 0%.
1004
+ const share100 = (a, b) => (b ? pct(a, b) : "—");
1005
+ const unit = (b) => (b ? "%" : "");
1006
+
1007
+ const kpis = [
1008
+ kpi({ label: "Failures from infra", def: "ci_causes", tip: `Runner, network, setup or missing-secret failures: not the code's fault. ${failNote}`, value: share100(infra, fails.length), unit: unit(fails.length), sub: ofText(infra, fails.length, "failed runs") }),
1009
+ kpi({ label: "Review comments", def: "settled_pr", tip: "Top-level review comments on merged or closed PRs.", value: fmt(R.length), sub: R.length ? `${fmt(inlineR.length)} inline · ${pct(bots.length, R.length)}% from bots` : "" }),
1010
+ kpi({ label: "Bot comments valid", def: "held_up", tip: `Bot comments labeled valid (fixed or left open). ${heldTip}`, value: share100(botInline.filter((r) => r.held?.startsWith("valid")).length, botInline.length), unit: unit(botInline.length), sub: botInline.length ? `of ${botInline.length} inline` : "No inline bot comments" }),
1011
+ kpi({ label: "Bot comments wrong", def: "held_up", tip: `Bot comments where the thread shows the reviewer was wrong. Each one costs a human rebuttal. ${heldTip}`, value: share100(botWrong, botInline.length), unit: unit(botInline.length), sub: botInline.length ? plural(botWrong, "comment") : "No inline bot comments" }),
1012
+ ].join("");
1013
+
1014
+ const byClass = [...groupBy(fails, (f) => f.class)].sort((a, b) => b[1].length - a[1].length);
1015
+ const byCheck = [...groupBy(fails, (f) => f.name)].sort((a, b) => b[1].length - a[1].length).slice(0, 10);
1016
+ const heldOrder = ["valid_and_fixed", "valid_open", "outdated", "wrong", "unclear", null];
1017
+ const who = [["Bots", botInline], ["People", inlineR.filter((r) => !r.bot)]];
1018
+ const botRows = [...groupBy(botInline, (r) => r.author)].sort((a, b) => b[1].length - a[1].length);
1019
+ // Ideas that cite a CI run or a review comment.
1020
+ const related = allRecs().filter((r) => r.evidence.some((k) => ["check", "review"].includes(state.data.refs[k]?.type)));
1021
+ // Infra failures aren't the code's fault; a module-download error names whatever file did the import.
1022
+ const placed = fails.filter((f) => f.area && f.class !== "infra_or_env");
1023
+ const byArea = [...groupBy(placed, (f) => f.area)].sort((a, b) => b[1].length - a[1].length).slice(0, 10);
1024
+ const inline = R.filter((r) => r.path);
1025
+ const share = (rs, f) => rs.filter(f).length / rs.length;
1026
+ const isWrong = (r) => r.held === "wrong";
1027
+ const isValid = (r) => r.held === "valid_and_fixed" || r.held === "valid_open";
1028
+ const byDir = [...groupBy(inline, (r) => dirOf(r.path))].filter(([, rs]) => rs.length >= 5)
1029
+ .sort((a, b) => share(b[1], isWrong) - share(a[1], isWrong) || b[1].length - a[1].length);
1030
+ const extOf = (p) => /\.\w+$/.exec(p.slice(p.lastIndexOf("/") + 1))?.[0];
1031
+ const byExt = [...groupBy(inline.filter((r) => extOf(r.path)), (r) => extOf(r.path))].sort((a, b) => b[1].length - a[1].length).slice(0, 4);
1032
+ const otherExt = inline.length - byExt.reduce((n, [, rs]) => n + rs.length, 0);
1033
+ const extLine = [...byExt.map(([k, rs]) => `<span class="mono">${esc(k)}</span> ${rs.length}`), ...(otherExt ? [`other ${otherExt}`] : [])].join(" · ");
1034
+ // Up to three failing test names under the area; the rest in a tooltip.
1035
+ const areaTests = (fs) => {
1036
+ const names = [...new Set(fs.flatMap((f) => f.tests || []))];
1037
+ if (!names.length) return "";
1038
+ const more = names.length > 3 ? ` <span data-tip="${esc(names.slice(3).join(", "))}">+${names.length - 3} more</span>` : "";
1039
+ return `<div class="muted test-names">${names.slice(0, 3).map(esc).join("<br>")}${more}</div>`;
1040
+ };
1041
+
1042
+ return `<p class="page-sub">${scopeLabel()} · merged and closed PRs only</p>
1043
+ <div class="kpis cols-4">${kpis}</div>
1044
+ <div class="grid">
1045
+ <div class="span-5">${card({ title: "CI failures by cause", def: "ci_causes", aside: reruns ? `<span data-tip="${esc(rerunTip)}">${reruns} passed on re-run</span>` : "",
1046
+ body: bars(byClass.map(([k, fs]) => ({ label: CI_CLASSES[k] ?? k, value: fs.length,
1047
+ tip: `${fs.length} failures on ${new Set(fs.map((f) => f.pr)).size} PRs. Cause read from the log.${k === "flaky_test" ? " Passed on re-run counts what happened next instead." : ""}` }))),
1048
+ foot: `<span class="muted">${esc(failNote)}</span>` })}</div>
1049
+ <div class="span-7">${card({ title: "Failing checks", flush: true, body: byCheck.length ? `<div class="table-wrap"><table><thead><tr><th>Check</th><th class="r">Failures</th><th>Causes</th><th>PRs</th></tr></thead><tbody>
1050
+ ${byCheck.map(([k, fs]) => `<tr><td class="mono small">${esc(k)}</td><td class="r">${fs.length}</td><td class="small">${[...groupBy(fs, (f) => f.class)].map(([c, xs]) => `${esc(CI_CLASSES[c] ?? c)} ${xs.length}`).join(", ")}</td><td class="small">${[...new Set(fs.map((f) => f.pr))].map(prLink).join(", ")}</td></tr>`).join("")}</tbody></table></div>` : `<div class="empty">No CI failures in this period.</div>` })}</div>
1051
+ <div class="span-7">${card({ title: "Did review comments hold up?", def: "held_up", tip: `Validity from a classifier reading the thread. ${heldTip}`,
1052
+ aside: legend(heldOrder.map((k) => ({ c: HELD_COLOR[k], label: HELD[k] }))),
1053
+ body: bars(who.map(([k, rs]) => ({ label: `${k} · ${rs.length}`, value: rs.length, valText: `${pct(rs.filter((r) => r.held === "wrong").length, rs.length)}% wrong`,
1054
+ segs: heldOrder.map((h) => ({ v: rs.filter((r) => (r.held ?? null) === h).length, c: HELD_COLOR[h], tip: `${k}, ${HELD[h]}: ${rs.filter((r) => (r.held ?? null) === h).length}` })) })), { max: Math.max(1, ...who.map(([, rs]) => rs.length)) }) })}</div>
1055
+ <div class="span-5">${card({ title: "Review bots", tip: heldTip, flush: true, body: botRows.length ? `<div class="table-wrap"><table><thead><tr><th>Bot</th><th class="r">Comments</th><th class="r">Fixed</th><th class="r">Wrong</th></tr></thead><tbody>
1056
+ ${botRows.map(([k, rs]) => `<tr><td class="mono small">${esc(k)}</td><td class="r">${rs.length}</td><td class="r">${pct(rs.filter((r) => r.held === "valid_and_fixed").length, rs.length)}%</td><td class="r">${pct(rs.filter((r) => r.held === "wrong").length, rs.length)}%</td></tr>`).join("")}</tbody></table></div>` : `<div class="empty">No inline bot comments.</div>` })}</div>
1057
+ <div class="span-6">${card({ title: "Where CI fails", def: "ci_where", flush: true,
1058
+ body: byArea.length ? `<div class="table-wrap"><table><thead><tr><th>Area</th><th class="r">Failures</th><th>Causes</th>${reruns ? `<th class="r" data-tip="${esc(rerunTip)}">Passed on re-run</th>` : ""}</tr></thead><tbody>
1059
+ ${byArea.map(([k, fs]) => `<tr><td class="mono small">${esc(k)}${areaTests(fs)}</td><td class="r">${fs.length}</td><td class="small">${[...groupBy(fs, (f) => f.class)].map(([c, xs]) => `${esc(CI_CLASSES[c] ?? c)} ${xs.length}`).join(", ")}</td>${reruns ? `<td class="r">${fs.filter((f) => f.flaky).length}</td>` : ""}</tr>`).join("")}</tbody></table></div>` : `<div class="empty">No CI failures name a package or file in this period.</div>`,
1060
+ foot: `<span class="muted">${placed.length} of ${fails.length} failures placed by package or file. ${infra} infra failures are left out; the rest name no file.</span>` })}</div>
1061
+ <div class="span-6">${card({ title: "Where review comments land", def: "review_where", flush: true,
1062
+ body: inline.length ? `<div class="card-note">${extLine}</div>${byDir.length ? `<div class="table-wrap"><table><thead><tr><th>Directory</th><th class="r">Comments</th><th class="r">Valid</th><th class="r">Wrong</th></tr></thead><tbody>
1063
+ ${byDir.map(([k, rs]) => `<tr><td class="mono small">${esc(k)}</td><td class="r muted small">${rs.length}</td><td class="r">${Math.round(100 * share(rs, isValid))}%</td><td class="r">${Math.round(100 * share(rs, isWrong))}%</td></tr>`).join("")}</tbody></table></div>` : `<div class="empty">No directory has 5 or more comments in this period.</div>`}` : `<div class="empty">No inline review comments in this period.</div>`,
1064
+ foot: `<span class="muted">${inline.length} of ${R.length} comments point at a file; review bodies and PR-level comments don't.</span>` })}</div>
1065
+ <div class="span-12">${card({ title: "Related ideas", flush: true, body: recTable(related, { compact: true }) })}</div>
1066
+ </div>`;
1067
+ }
1068
+
1069
+ // ---------- Sessions ----------
1070
+
1071
+ function filteredSessions() {
1072
+ const f = state.sessionFilter;
1073
+ const q = f.q.trim().toLowerCase();
1074
+ const S = scoped().S.filter((s) => (!f.author || (f.author === NO_PERSON ? !s.author : s.author === f.author)) &&
1075
+ (!f.outcome || s.outcome === f.outcome) && (!f.corrected || correctedTurns(s) > 0) &&
1076
+ (!q || `${s.name} ${s.prompt} ${s.id} ${s.project || ""} ${s.prs.map((p) => p.n).join(" ")}`.toLowerCase().includes(q)));
1077
+ const key = { started: (s) => s.started, turns: (s) => s.human_turns, corrections: correctedTurns, name: (s) => (s.name || "").toLowerCase() }[f.sort];
1078
+ return S.slice().sort((a, b) => (key(a) > key(b) ? 1 : key(a) < key(b) ? -1 : 0) * f.dir);
1079
+ }
1080
+
1081
+ function viewSessions() {
1082
+ renderTopbar({ crumbs: [{ label: "Sessions" }], scope: true });
1083
+ const f = state.sessionFilter;
1084
+ const S = filteredSessions();
1085
+ const all = allSessions();
1086
+ const authors = [...new Set(all.map((s) => s.author).filter(Boolean))].sort((a, b) => a.localeCompare(b));
1087
+ const col = { project: has("projects"), person: has("people"), pr: has("github") };
1088
+ const th = (k, l, cls = "") => `<th class="sortable ${cls}" data-sort="${k}" aria-sort="${f.sort === k ? (f.dir > 0 ? "ascending" : "descending") : "none"}">${l}${f.sort === k ? (f.dir > 0 ? " ↑" : " ↓") : ""}</th>`;
1089
+ setTimeout(wireSessions, 0);
1090
+ return `<p class="page-sub">${scopeLabel()}</p>
1091
+ <section class="card">
1092
+ <div class="toolbar">
1093
+ <input type="search" id="s-q" placeholder="Search name${col.project ? ", project" : ""}${col.pr ? ", prompt or PR" : " or prompt"}" value="${esc(f.q)}" aria-label="Search sessions">
1094
+ ${col.person ? `<select id="s-author" aria-label="Person"><option value="">All people</option>${authors.map((a) => `<option${a === f.author ? " selected" : ""}>${esc(a)}</option>`).join("")}${all.some((s) => !s.author) ? `<option value="${esc(NO_PERSON)}"${f.author === NO_PERSON ? " selected" : ""}>Unknown</option>` : ""}</select>` : ""}
1095
+ <select id="s-outcome" aria-label="Outcome"><option value="">Any outcome</option>${Object.entries(OUTCOMES).map(([k, l]) => `<option value="${k}"${k === f.outcome ? " selected" : ""}>${l}</option>`).join("")}</select>
1096
+ <label class="check"><input type="checkbox" id="s-corrected"${f.corrected ? " checked" : ""}> Has corrections</label>
1097
+ <span class="spacer"></span><span class="muted small num">${S.length} of ${scoped().S.length}</span>
1098
+ </div>
1099
+ <div class="table-wrap"><table>
1100
+ <thead><tr>${th("started", "Started")}${th("name", "Session")}${col.project ? "<th>Project</th>" : ""}<th>Harness</th>${col.person ? "<th>Person</th>" : ""}${th("turns", "Messages", "r")}${th("corrections", "Signals")}<th>Outcome</th>${col.pr ? "<th>PR</th>" : ""}</tr></thead>
1101
+ <tbody>${sessionRows(S) || `<tr><td colspan="${6 + col.project + col.person + col.pr}" class="empty">No sessions match.</td></tr>`}</tbody>
1102
+ </table></div>
1103
+ </section>`;
1104
+ }
1105
+
1106
+ function wireSessions() {
1107
+ const f = state.sessionFilter;
1108
+ $("#s-q")?.addEventListener("input", (e) => { f.q = e.target.value; rerender(); });
1109
+ $("#s-author")?.addEventListener("change", (e) => { f.author = e.target.value; rerender(); });
1110
+ $("#s-outcome")?.addEventListener("change", (e) => { f.outcome = e.target.value; rerender(); });
1111
+ $("#s-corrected")?.addEventListener("change", (e) => { f.corrected = e.target.checked; rerender(); });
1112
+ $$("th[data-sort]").forEach((th) => th.addEventListener("click", () => { const k = th.dataset.sort; f.dir = f.sort === k ? -f.dir : -1; f.sort = k; rerender(); }));
1113
+ }
1114
+
1115
+ // ---------- Session detail ----------
1116
+
1117
+ // Transcripts ship in shard files of many sessions each; keep each shard's promise so
1118
+ // sessions from the same shard share one fetch.
1119
+ function loadShard(name) {
1120
+ let p = state.shardCache.get(name);
1121
+ if (!p) {
1122
+ p = fetch(`data/sessions/${name}.json`).then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); });
1123
+ p.catch(() => state.shardCache.delete(name));
1124
+ state.shardCache.set(name, p);
1125
+ }
1126
+ return p;
1127
+ }
1128
+
1129
+ function viewSession(id, focusIdx) {
1130
+ const s = state.sessionsById.get(id);
1131
+ if (!s) { renderTopbar({ crumbs: [{ label: "Sessions", href: "#sessions" }, { label: "Not found" }] }); return `<div class="empty">Session ${esc(id)} is not in this dataset.</div>`; }
1132
+ renderTopbar({ crumbs: [{ label: "Sessions", href: "#sessions" }, { label: s.name || short(s.id) }] });
1133
+ const cached = state.sessionCache.get(id);
1134
+ if (!cached) {
1135
+ loadShard(s.shard).then((shard) => {
1136
+ if (!shard[id]) throw new Error(`session ${id} missing from shard ${s.shard}`);
1137
+ state.sessionCache.set(id, shard[id]);
1138
+ if (location.hash.startsWith(`#session~${id}`)) route();
1139
+ }).catch(() => { const t = $("#transcript"); if (t) t.innerHTML = `<div class="empty">Could not load the transcript.</div>`; });
1140
+ }
1141
+ const focus = focusIdx != null ? Number(focusIdx) : null;
1142
+ const recs = state.recsBySession.get(id) || [];
1143
+ const dur = time(s.last) - time(s.started);
1144
+ const durText = Number.isNaN(dur) ? "—" : dur > DAY ? `${(dur / DAY).toFixed(1)} days` : `${Math.max(1, Math.round(dur / 36e5))} h`;
1145
+
1146
+ const main = `<section class="card">
1147
+ <div class="card-head"><h2>Transcript</h2></div>
1148
+ ${cached ? `<div class="strip-bar">${stripLegend(cached)}${strip(cached)}</div>` : ""}
1149
+ <div class="transcript" id="transcript">${cached ? transcript(cached, focus) : `<div class="empty">Loading transcript…</div>`}</div>
1150
+ </section>`;
1151
+
1152
+ const props = `<aside class="card props">
1153
+ <dl>
1154
+ <dt>Harness</dt><dd>${agentChip(s.agent)}</dd>
1155
+ <dt>Model</dt><dd class="mono small">${esc(s.model || "unknown")}</dd>
1156
+ ${s.project ? `<dt>Project</dt><dd class="mono small" title="${esc(s.project)}">${esc(projectName(s.project))}</dd>` : ""}
1157
+ ${has("people") ? `<dt>Person</dt><dd>${esc(personLabel(s.author))}</dd>` : ""}
1158
+ <dt>Started</dt><dd>${dayTime(s.started)}</dd>
1159
+ <dt>Duration</dt><dd class="num">${durText}</dd>
1160
+ <dt>Outcome</dt><dd>${outcomeChip(s.outcome)}</dd>
1161
+ <dt>Human turns</dt><dd class="num">${s.human_turns}</dd>
1162
+ <dt>Tool calls</dt><dd class="num">${fmt(s.tool_calls)} <span class="muted">(${fmt(s.tool_errors)} failed)</span></dd>
1163
+ ${has("checkpoints") ? `<dt>Checkpoints</dt><dd class="num">${s.checkpoints ?? "—"}</dd>` : ""}
1164
+ ${has("github") ? `<dt>PR</dt><dd>${s.prs.map((p) => `${prLink(p.n)} <span class="pr-state">${esc(p.state)}</span>`).join("<br>") || "—"}</dd>` : ""}
1165
+ </dl>
1166
+ <div class="section"><h3>Signals</h3><div class="chips">${SIG_ORDER.map((g) => `<span class="sig" data-tip="${esc(SIGNALS[g].tip)}">${glyph(g)}${s[SIG_FIELD[g]]} ${esc(SIGNALS[g].label.toLowerCase())}</span>`).join("")}</div>
1167
+ ${s.not_filed ? `<div class="small muted">${glyph("not_filed")} ${plural(s.not_filed, "problem")} found and left unfiled in the session</div>` : ""}</div>
1168
+ ${recs.length ? `<div class="section"><h3>Cited by</h3>${recs.map((r) => `<a href="#rec~${r.id}" class="small">${esc(r.title)}</a>`).join("")}</div>` : ""}
1169
+ </aside>`;
1170
+
1171
+ // A timeout, not requestAnimationFrame, which never fires in a background tab.
1172
+ if (cached) setTimeout(() => { const el = focus != null && document.getElementById(`m${focus}`); scrollToEl(el, "center"); }, 0);
1173
+ return `<div class="detail"><div class="detail-main">${main}</div>${props}</div>`;
1174
+ }
1175
+
1176
+ const STRIP_SIGS = [...SIG_ORDER, "not_filed"];
1177
+ function stripLegend(j) {
1178
+ const present = new Set(j.messages.flatMap((m) => m.sig || []));
1179
+ return legend(STRIP_SIGS.filter((g) => present.has(g)).map((g) => ({ glyph: g, label: SIGNALS[g].label })));
1180
+ }
1181
+ function strip(j) {
1182
+ const last = j.messages.length ? j.messages[j.messages.length - 1].i : 1;
1183
+ const marks = j.messages.filter((m) => (m.sig || []).length);
1184
+ if (!marks.length) return `<p class="muted small">Nothing flagged in this session.</p>`;
1185
+ return `<div class="strip">${marks.map((m) => {
1186
+ const g = STRIP_SIGS.find((x) => m.sig.includes(x));
1187
+ return `<button class="mark" type="button" style="left:${2 + (96 * m.i) / (last || 1)}%" data-jump="${m.i}" data-tip="Turn ${m.i}: ${m.sig.map((x) => SIGNALS[x].label).join(", ")}" aria-label="Jump to turn ${m.i}">${glyph(g)}</button>`;
1188
+ }).join("")}</div>`;
1189
+ }
1190
+
1191
+ function transcript(j, focus) {
1192
+ const out = [];
1193
+ let run = [];
1194
+ const flush = () => { if (run.length) out.push(agentRun(run, focus)); run = []; };
1195
+ for (const m of j.messages) {
1196
+ if (m.r === "user" && m.k === "human") { flush(); out.push(humanMsg(m, focus)); } else run.push(m);
1197
+ }
1198
+ flush();
1199
+ return out.join("");
1200
+ }
1201
+
1202
+ function humanMsg(m, focus) {
1203
+ const sigs = (m.sig || []).filter((g) => g !== "not_filed");
1204
+ const l = m.l || {};
1205
+ const extra = [l.turn_kind && `Turn: ${l.turn_kind[0].replace(/_/g, " ")}`, l.correction_type && sigs.includes("correction") && `Type: ${CORRECTION_TYPES[l.correction_type[0]] || l.correction_type[0]}`, l.resource_pointed_to && `Pointed to: ${l.resource_pointed_to[0].replace(/_/g, " ")}`].filter(Boolean);
1206
+ return `<div class="msg human${m.i === focus ? " focus" : ""}" id="m${m.i}">
1207
+ <div class="msg-head"><span class="who">Human · turn ${m.i}</span><span>${dayTime(m.ts)}</span></div>
1208
+ <div class="msg-body">${esc(m.t)}</div>
1209
+ ${sigs.length || extra.length ? `<div class="chips">${sigs.map((g) => sigChip(g, l[LABEL_FIELD[g]] ? ` <span class="muted num" data-tip="Classifier confidence">${l[LABEL_FIELD[g]][1]}</span>` : "")).join("")}${extra.map((x) => `<span class="pill">${esc(x)}</span>`).join("")}</div>` : ""}
1210
+ </div>`;
1211
+ }
1212
+
1213
+ function agentRun(msgs, focus) {
1214
+ const parts = [];
1215
+ let calls = [];
1216
+ const flushCalls = () => {
1217
+ if (!calls.length) return;
1218
+ const errs = calls.filter((c) => c.err).length;
1219
+ const byName = [...groupBy(calls, (c) => c.n)].map(([n, cs]) => `${n} ×${cs.length}`).join(" · ");
1220
+ parts.push(`<details class="tools"><summary>${calls.length} tool calls: ${esc(byName)}${errs ? ` · <span class="errtxt">${errs} failed</span>` : ""}</summary>
1221
+ <div class="table-wrap"><table><tbody>${calls.map((c) => `<tr${c.err ? ' class="err"' : ""}><td class="nowrap">${esc(c.n)}</td><td class="in">${esc(c.in)}${c.w ? `<div class="muted">wrote ${esc(c.w.join(", "))}</div>` : ""}${c.err ? `<pre style="margin-top:4px">${esc(c.err)}</pre>` : ""}</td></tr>`).join("")}</tbody></table></div></details>`);
1222
+ calls = [];
1223
+ };
1224
+ for (const m of msgs) {
1225
+ if (m.r === "user") {
1226
+ flushCalls();
1227
+ parts.push(`<div class="msg injected" id="m${m.i}">Injected context · turn ${m.i}: ${esc(m.t.slice(0, 200))}${m.t.length > 200 ? "…" : ""}</div>`);
1228
+ continue;
1229
+ }
1230
+ if ((m.t || "").trim()) {
1231
+ flushCalls();
1232
+ const clamp = m.t.length > 600 && m.i !== focus;
1233
+ const notFiled = (m.sig || []).includes("not_filed");
1234
+ parts.push(`<div class="msg agent${m.i === focus ? " focus" : ""}" id="m${m.i}">
1235
+ <div class="msg-head"><span class="who">Agent · turn ${m.i}</span><span>${dayTime(m.ts)}</span></div>
1236
+ ${notFiled ? `<div class="flagnote">${glyph("not_filed")} Noticed a problem outside its task and left it</div>` : ""}
1237
+ <div class="msg-body md${clamp ? " clamp" : ""}">${md(m.t)}</div>
1238
+ ${clamp ? `<button type="button" class="linklike small" data-unclamp>Show all</button>` : ""}
1239
+ </div>`);
1240
+ } else if (m.i === focus) {
1241
+ parts.push(`<div class="msg agent focus" id="m${m.i}"><div class="msg-head"><span class="who">Agent · turn ${m.i}</span></div><span class="muted">Tool calls only</span></div>`);
1242
+ }
1243
+ if (m.c) calls.push(...m.c);
1244
+ }
1245
+ flushCalls();
1246
+ return `<div class="agent-run">${parts.join("")}</div>`;
1247
+ }
1248
+
1249
+ // ---------- How it works ----------
1250
+
1251
+ function viewMethod(focus) {
1252
+ renderTopbar({ crumbs: [{ label: "How it works" }] });
1253
+ const better = { lower: "Lower is better", higher: "Higher is better" };
1254
+ const num = (v) => fill(v).replace(/^\d+$/, (n) => fmt(Number(n)));
1255
+ // Lines marked [github] in method.js describe steps that only run on GitHub data.
1256
+ const text = (t) => md(fill(has("github") ? t.replace(/\[github\] /g, "") : t.split("\n").filter((l) => !l.includes("[github]")).join("\n")));
1257
+ const glance = `<section class="card glance" aria-label="The method at a glance">${METHOD.steps.map((st, i) => `<a class="glance-step" href="#method~${st.id}">
1258
+ <span class="glance-name"><span class="step-n">${i + 1}</span>${esc(st.short)}</span>
1259
+ <span class="glance-num num">${esc(num(st.glance[0]))}</span><span class="glance-label">${esc(st.glance[1])}</span></a>`).join("")}</section>`;
1260
+ const steps = METHOD.steps.map((st, i) => `<section class="card step${st.id === focus ? " focus" : ""}" id="def-${st.id}">
1261
+ <div class="step-head"><span class="step-n">${i + 1}</span><h2>${esc(st.title)}</h2></div>
1262
+ <div class="step-body"><div class="step-lede">${text(st.lede)}</div>${st.text.map(text).join("")}
1263
+ ${st.facts?.length ? `<div class="facts">${st.facts.filter(([v]) => fill(v) !== "0").map(([v, l]) => `<span><b class="num">${esc(num(v))}</b>${esc(l)}</span>`).join("")}</div>` : ""}</div>
1264
+ </section>`).join("");
1265
+ const metrics = DEFS.filter((d) => d.page).map((d) => `<article class="def${d.id === focus ? " focus" : ""}" id="def-${d.id}">
1266
+ <div class="def-head"><h3>${esc(d.term)}</h3>${d.better ? `<span class="pill">${better[d.better]}</span>` : ""}</div>
1267
+ <p>${esc(fill(d.def))}</p>
1268
+ ${d.list ? `<dl class="def-list">${d.list.map(([k, v]) => `<dt>${esc(k)}</dt><dd>${esc(v)}</dd>`).join("")}</dl>` : ""}
1269
+ ${d.example ? `<p class="def-meta"><span>Example</span>${esc(d.example)}</p>` : ""}
1270
+ </article>`).join("");
1271
+ const toc = `<nav class="card toc" aria-label="On this page">
1272
+ <div class="toc-group"><div class="nav-label">Method</div>${METHOD.steps.map((st, i) => `<a href="#method~${st.id}"${st.id === focus ? ' aria-current="true"' : ""}>${i + 1}. ${esc(st.title)}</a>`).join("")}</div>
1273
+ <div class="toc-group"><div class="nav-label">Metrics</div>${DEFS.filter((d) => d.page).map((d) => `<a href="#method~${d.id}"${d.id === focus ? ' aria-current="true"' : ""}>${esc(d.term)}</a>`).join("")}</div></nav>`;
1274
+ if (focus) setTimeout(() => scrollToEl(document.getElementById(`def-${focus}`)), 0);
1275
+ return `<section class="card method-intro"><h2>How this analysis works</h2><p>${esc(fill(METHOD.question))}</p></section>
1276
+ ${glance}
1277
+ <div class="defs">${toc}<div class="defs-main">
1278
+ ${steps}
1279
+ ${card({ title: "The metrics", body: metrics })}
1280
+ </div></div>`;
1281
+ }
1282
+
1283
+ // ---------- Settings ----------
1284
+
1285
+ const STAGE_NAMES = { label: "Label", synthesize: "Synthesize", recommend: "Recommend", verify: "Verify" };
1286
+ const LLM_NAMES = { "claude-code": "Claude Code", openrouter: "OpenRouter" };
1287
+
1288
+ // Only `debrief open` has this API. Anything else answers with a 404 page or not at all: { error }.
1289
+ // `debrief open` puts a token for this run in the link it opens; writes are refused without it.
1290
+ const TOKEN_KEY = `${APP}-token`;
1291
+ const TOKEN = (() => {
1292
+ const url = new URL(location.href), t = url.searchParams.get("t");
1293
+ try {
1294
+ if (t) { sessionStorage.setItem(TOKEN_KEY, t); url.searchParams.delete("t"); history.replaceState(null, "", url); }
1295
+ return sessionStorage.getItem(TOKEN_KEY) || "";
1296
+ } catch {
1297
+ return t || "";
1298
+ }
1299
+ })();
1300
+
1301
+ async function settingsApi(method, path, body) {
1302
+ try {
1303
+ const r = await fetch(path, { method, headers: { "Content-Type": "application/json", [`X-${APP}-Token`]: TOKEN }, body: body && JSON.stringify(body) });
1304
+ const out = await r.json();
1305
+ return r.ok ? out : { ...out, error: out.error || `HTTP ${r.status}` };
1306
+ } catch {
1307
+ return { error: "" };
1308
+ }
1309
+ }
1310
+
1311
+ function viewSettings() {
1312
+ renderTopbar({ crumbs: [{ label: "Settings" }] });
1313
+ const s = state.settings;
1314
+ if (!s) {
1315
+ settingsApi("GET", "api/settings").then((r) => { state.settings = r; if (location.hash === "#settings") route(); });
1316
+ return '<p class="loading">Loading…</p>';
1317
+ }
1318
+ if (!s.stages) return notice("Settings need debrief running", `${s.error ? `${esc(s.error)}. ` : ""}This copy of the report cannot read or save settings. Run <code>debrief open</code> and use the page it opens.`);
1319
+ const msg = (at) => `<span role="status" class="${state.settingsMsg?.bad ? "bad" : "muted"}">${state.settingsMsg?.at === at ? esc(state.settingsMsg.text) : ""}</span>`;
1320
+ const rows = Object.entries(s.stages).map(([id, st]) => {
1321
+ const llms = Object.keys(st.defaults), name = STAGE_NAMES[id] || id, over = st.overrides[st.llm];
1322
+ return `<tr><td class="cell-title">${esc(name)}</td>
1323
+ <td>${llms.length > 1 ? `<select data-llm="${esc(id)}" aria-label="${esc(name)} provider">${llms.map((l) => `<option value="${esc(l)}"${l === st.llm ? " selected" : ""}>${esc(LLM_NAMES[l] || l)}</option>`).join("")}</select>` : esc(LLM_NAMES[st.llm] || st.llm)}</td>
1324
+ <td><input type="text" data-model="${esc(id)}" value="${esc(st.model)}" placeholder="${esc(st.defaults[st.llm])}" aria-label="${esc(name)} model" maxlength="100" spellcheck="false" autocomplete="off"></td>
1325
+ <td class="muted">${over ? `Overridden by <code>$${esc(over)}</code>` : ""}</td></tr>`;
1326
+ }).join("");
1327
+ const k = s.key;
1328
+ const keyState = !k.set ? "No key saved." : k.source === "env" ? `Set in your shell, ends in …${esc(k.last4)}. A key saved here would not be used.`
1329
+ : `Saved, ends in …${esc(k.last4)} <button type="button" class="linklike" id="key-remove">Remove</button>`;
1330
+ return `<section class="card settings"><div class="card-body">
1331
+ <form id="settings-form">
1332
+ <div class="table-wrap"><table><thead><tr><th>Stage</th><th>Provider</th><th>Model</th><th></th></tr></thead><tbody>${rows}</tbody></table></div>
1333
+ <label class="check"><input type="checkbox" id="set-github"${s.github ? " checked" : ""}> Look up pull requests, CI and review comments for my sessions (uses the <code>gh</code> CLI)</label>
1334
+ </form>
1335
+ <form id="key-form" class="key-row">
1336
+ <label for="key">OpenRouter key</label>
1337
+ <input type="password" id="key" placeholder="paste a key" required minlength="20" maxlength="200" autocomplete="off" spellcheck="false">
1338
+ <button>Save key</button><span>${keyState}</span>${msg("key")}
1339
+ </form>
1340
+ <p class="muted">Tip: Jev (provider OpenRouter) labels 2,774 items in about 3 min for about $0.37; Haiku takes 33 min.</p>
1341
+ </div><div class="card-foot key-row"><button class="primary" form="settings-form">Save</button><span class="muted">Changes apply on the next <code>debrief sync</code>.</span>${msg("save")}</div></section>`;
1342
+ }
1343
+
1344
+ // The key form sends only the key and takes back only the key's state, so unsaved model edits stay.
1345
+ async function settingsSend(at, method, path, body, done) {
1346
+ const r = await settingsApi(method, path, body);
1347
+ if (r.stages) Object.assign(state.settings, at === "key" ? { key: r.key } : r);
1348
+ state.settingsMsg = { at, text: r.stages ? done : r.error || "Could not reach debrief. Is `debrief open` still running?", bad: !r.stages };
1349
+ rerender();
1350
+ }
1351
+
1352
+ // ---------- Projects ----------
1353
+
1354
+ const RUN_STAGES = { ingest: "Reading logs", github: "Looking up pull requests", label: "Labeling", synthesize: "Finding patterns", recommend: "Writing ideas", export: "Building the report" };
1355
+ const VIA = { "claude-code": "your Claude subscription", openrouter: "OpenRouter, paid per use" };
1356
+ const GONE = "Could not reach debrief. Is `debrief open` still running?";
1357
+ const onProjects = () => location.hash === "#projects";
1358
+ const redraw = () => { if (onProjects()) rerender(); };
1359
+ // Screen readers hear #live; the page itself is redrawn too often to be a live region.
1360
+ const say = (text) => { $("#live").textContent = text; };
1361
+
1362
+ function viewProjects() {
1363
+ renderTopbar({ crumbs: [{ label: "Projects" }] });
1364
+ const r = state.run, s = r.settings;
1365
+ if (state.lastPage !== location.hash) projectsRefresh(); // on entering the page
1366
+ if (!s) return '<p class="loading">Loading…</p>';
1367
+ if (!s.stages) return notice("Projects need debrief running", `${s.error ? `${esc(s.error)}. ` : ""}This copy of the report cannot pick projects or check them. Run <code>debrief open</code> and use the page it opens.`);
1368
+ const st = r.status || {}, running = st.state === "running", all = state.data.projects || [];
1369
+ const picked = new Set(r.picked), nPicked = all.filter((p) => picked.has(p.path)).length;
1370
+ const shown = all.filter((p, i) => r.showAll || i < 8 || picked.has(p.path));
1371
+ const rows = shown.map((p) => `<tr><td><label class="check" title="${esc(p.path)}"><input type="checkbox" id="pick-${all.indexOf(p)}" data-pick="${esc(p.path)}"${picked.has(p.path) ? " checked" : ""}${running ? " disabled" : ""}> ${esc(p.name)}</label></td>
1372
+ <td class="r">${fmt(p.sessions)}</td><td class="r">${fmt(p.turns)}</td><td class="${p.analysed_at ? "" : "muted"}">${p.analysed_at ? esc(day(p.analysed_at)) : "never"}</td></tr>`).join("");
1373
+ const more = all.length - shown.length;
1374
+ const e = r.est;
1375
+ const estText = r.estimating ? "Estimating, about 20 seconds…" : !nPicked ? "" : !e ? "not estimated yet"
1376
+ : e.outdated ? "the last check changed what is left to label, so refresh the estimate"
1377
+ : e.error ? `the estimate failed (${esc(e.error)})`
1378
+ : `${e.items ? `${plural(e.items, "new item")} to label` : "nothing new to label"}${!e.items || e.minutes == null ? "" : e.minutes ? ` · about ${fmt(e.minutes)} min` : " · under a minute"}${r.stale ? " · from before your last change" : ""}`;
1379
+ const model = (id) => { const x = s.stages[id]; return x ? `<code>${esc(x.model || x.defaults[x.llm])}</code>` : "the default model"; };
1380
+ const via = (id) => VIA[s.stages[id]?.llm] || esc(s.stages[id]?.llm || "");
1381
+ const models = via("label") === via("synthesize") ? `Labeling uses ${model("label")} and findings use ${model("synthesize")}, through ${via("label")}.`
1382
+ : `Labeling uses ${model("label")} through ${via("label")}; findings use ${model("synthesize")} through ${via("synthesize")}.`;
1383
+ const why = running ? "A check is running." : r.estimating ? "Wait for the estimate to finish." : !nPicked ? "Pick at least one project first." : "";
1384
+ const save = r.saveMsg?.bad ? `<span class="bad">${esc(r.saveMsg.text)}</span>` : `<span class="muted">${r.saves ? "Saving…" : esc(r.saveMsg?.text || "")}</span>`;
1385
+ const log = (open) => (st.log?.length ? `<details id="run-log"${open || r.logOpen ? " open" : ""}><summary>Last lines of output</summary><pre>${esc(st.log.slice(open ? -12 : -8).join("\n"))}</pre></details>` : "");
1386
+ const stages = Object.keys(RUN_STAGES).filter((k) => k !== "github" || s.github), at = stages.indexOf(st.stage);
1387
+ const counted = st.total ? ` ${fmt(st.done)} of ${fmt(st.total)}` : "";
1388
+ const box = running ? `<div class="run-row"><span><strong>Running</strong> · ${esc(RUN_STAGES[st.stage] || "Starting")}${counted}</span><button type="button" id="run-cancel">Cancel</button></div>
1389
+ <div class="run-row"><progress id="run-bar" aria-label="Progress of the check" max="1" value="${at < 0 ? 0 : ((at + (st.total ? st.done / st.total : 0)) / stages.length).toFixed(3)}"></progress>${at < 0 ? "" : `<span class="muted">stage ${at + 1} of ${stages.length}</span>`}</div>${log(false)}`
1390
+ : st.state === "done" ? `<p>Finished ${esc(dayTime(st.ended))}. Every page now shows the new report. <a href="#overview">Read it</a></p>${log(false)}`
1391
+ : st.state === "failed" ? `<p class="bad">The check failed (exit code ${esc(st.exit_code)}). Its last lines:</p>${log(true)}`
1392
+ : st.state === "cancelled" ? `<p>Cancelled. Labels made so far are saved, so the next check continues from there.</p>${log(false)}`
1393
+ : st.error != null ? `<p class="bad">${esc(st.error || GONE)}</p>` : "";
1394
+ return `<section class="card projects"><div class="card-body">
1395
+ <div class="table-wrap"><table><thead><tr><th>Project</th><th class="r">Sessions</th><th class="r">Turns</th><th>Last checked</th></tr></thead><tbody>${rows}</tbody></table></div>
1396
+ ${more > 0 ? `<p class="muted">… ${fmt(more)} more <button type="button" class="linklike" id="projects-all">show all</button></p>` : ""}
1397
+ <div class="run-row"><span>${fmt(nPicked)} picked${estText ? ` · ${estText}` : ""} ${save}</span>
1398
+ <button type="button" id="est-refresh"${running || r.estimating || !nPicked ? " disabled" : ""}>Refresh estimate</button></div>
1399
+ <p class="muted">${models} <a href="#settings">Change</a></p>
1400
+ <div class="run-row start"><button type="button" class="primary" id="run-start"${why ? ' disabled aria-describedby="run-why"' : ""}>Check my data now</button><span class="muted" id="run-why">${why}</span>${r.refused ? `<span class="bad">${esc(r.refused)}</span>` : ""}</div>
1401
+ ${box ? `<div class="run-box">${box}</div>` : ""}
1402
+ </div></section>`;
1403
+ }
1404
+
1405
+ async function projectsRefresh() {
1406
+ const r = state.run;
1407
+ const [s, st] = await Promise.all([settingsApi("GET", "api/settings"), settingsApi("GET", "api/run")]);
1408
+ r.settings = s;
1409
+ if (!r.saves && s.projects) r.picked = s.projects;
1410
+ if (s.stages) await runSeen(st); else redraw();
1411
+ }
1412
+
1413
+ // Saves go one at a time, each sending the boxes as they are when it is sent, so two quick ticks
1414
+ // cannot overwrite each other. A refused save puts its box back.
1415
+ let saveQueue = Promise.resolve();
1416
+ function togglePick(path, on) {
1417
+ const r = state.run, set = (yes) => { r.picked = r.picked.filter((p) => p !== path).concat(yes ? [path] : []); };
1418
+ set(on);
1419
+ r.saves++;
1420
+ r.saveMsg = null;
1421
+ saveQueue = saveQueue.then(async () => {
1422
+ let s = await settingsApi("GET", "api/settings");
1423
+ if (s.stages) s = await settingsApi("POST", "api/settings", { github: s.github, projects: r.picked, stages: Object.fromEntries(Object.entries(s.stages).map(([id, x]) => [id, { llm: x.llm, model: x.model }])) });
1424
+ r.saves--;
1425
+ if (s.stages) { r.settings = s; r.stale = Boolean(r.est); r.saveMsg = { text: "Saved." }; }
1426
+ else { set(!on); r.saveMsg = { bad: true, text: `Not saved: ${s.error || GONE}` }; say(r.saveMsg.text); }
1427
+ redraw();
1428
+ });
1429
+ redraw();
1430
+ }
1431
+
1432
+ // An estimate counts what was unlabelled when it was made. A check that ended since (done, failed
1433
+ // or cancelled) has labelled some of that, so the numbers go. `after` is the `ended` of the last
1434
+ // check the estimate knew about.
1435
+ function estimateAfter(est, st) {
1436
+ return est && st.state !== "running" && st.ended && st.ended !== est.after ? { outdated: true } : est;
1437
+ }
1438
+
1439
+ async function estimate() {
1440
+ const r = state.run;
1441
+ r.estimating = true;
1442
+ redraw();
1443
+ const e = await settingsApi("POST", "api/estimate");
1444
+ Object.assign(r, { estimating: false, stale: false, est: { ...(e.error == null ? e : { error: e.lines?.length ? e.lines.slice(-3).join(" / ") : e.error || GONE }), after: r.status?.ended ?? null } });
1445
+ // The estimate read the logs again and rebuilt the pages.
1446
+ if (e.error == null) await load().catch(() => {});
1447
+ say(r.est.error ? "The estimate failed." : "Estimate ready.");
1448
+ redraw();
1449
+ }
1450
+
1451
+ // Every answer about the run comes through here. While it runs, ask again every 2 s, on any page,
1452
+ // so the report reloads when it ends; a hidden tab waits until it is shown again.
1453
+ let runTimer;
1454
+ async function runSeen(st) {
1455
+ const r = state.run, was = r.status || {};
1456
+ r.status = st;
1457
+ r.est = estimateAfter(r.est, st);
1458
+ clearTimeout(runTimer);
1459
+ if (st.state === "running") {
1460
+ runTimer = setTimeout(runPoll, 2000);
1461
+ if (st.stage !== was.stage || was.state !== "running") say(`Running: ${RUN_STAGES[st.stage] || "starting"}.`);
1462
+ } else if (st.state === "done" && st.ended !== r.shownRun) {
1463
+ // Also true for a run that another tab started and that ended before this one looked.
1464
+ r.shownRun = st.ended;
1465
+ const ok = await load().then(() => true, () => false);
1466
+ say(ok ? "Finished. Every page now shows the new report." : "Finished. Reload this page to see the new report.");
1467
+ } else if (was.state === "running") {
1468
+ say(st.state === "cancelled" ? "Cancelled. Labels made so far are saved." : st.state === "failed" ? `The check failed with exit code ${st.exit_code}.` : GONE);
1469
+ }
1470
+ redraw();
1471
+ }
1472
+ async function runPoll() {
1473
+ clearTimeout(runTimer);
1474
+ if (!document.hidden) await runSeen(await settingsApi("GET", "api/run"));
1475
+ }
1476
+ async function runSend(method) {
1477
+ const st = await settingsApi(method, "api/run");
1478
+ // A refusal (another tab got there first) is not news about the run: say it and look again.
1479
+ state.run.refused = st.state ? "" : st.error || GONE;
1480
+ if (!st.state) { say(state.run.refused); return runPoll(); }
1481
+ await runSeen(st);
1482
+ }
1483
+
1484
+ // ---------- global events ----------
1485
+
1486
+ function correctionsFromHash() {
1487
+ const [page, key, val] = location.hash.slice(1).split("~");
1488
+ if (page !== "corrections") return false;
1489
+ if (key === "ctype") state.correctionsFilter = { ...state.correctionsFilter, ctype: val, dir: "" };
1490
+ if (key === "dir") state.correctionsFilter = { ...state.correctionsFilter, dir: decodeURIComponent(val), ctype: "" };
1491
+ return Boolean(key);
1492
+ }
1493
+
1494
+ function initEvents() {
1495
+ const tip = $("#tip");
1496
+ const show = (t) => { tip.textContent = t.dataset.tip; tip.hidden = false; };
1497
+ document.addEventListener("pointerover", (e) => { const t = e.target.closest("[data-tip]"); if (t) show(t); else tip.hidden = true; });
1498
+ document.addEventListener("focusin", (e) => { const t = e.target.closest?.("[data-tip]"); if (t) { show(t); const r = t.getBoundingClientRect(); tip.style.left = `${r.left}px`; tip.style.top = `${r.bottom + 6}px`; } });
1499
+ document.addEventListener("focusout", () => { tip.hidden = true; });
1500
+ document.addEventListener("pointermove", (e) => {
1501
+ if (tip.hidden) return;
1502
+ tip.style.left = `${Math.max(8, Math.min(e.clientX + 14, window.innerWidth - tip.offsetWidth - 8))}px`;
1503
+ tip.style.top = `${e.clientY + 18 + tip.offsetHeight > window.innerHeight ? e.clientY - tip.offsetHeight - 10 : e.clientY + 18}px`;
1504
+ });
1505
+
1506
+ document.addEventListener("click", (e) => {
1507
+ // Rows and links that carry a filter set it before navigating.
1508
+ const el = e.target.closest("[data-lever],[data-agent],[data-author],[data-dir]");
1509
+ if (el) {
1510
+ if (el.dataset.lever) state.recFilter = { ...state.recFilter, lever: el.dataset.lever };
1511
+ if (el.dataset.agent) { state.scope.agent = el.dataset.agent; }
1512
+ if (el.dataset.author) state.sessionFilter.author = el.dataset.author;
1513
+ if (el.dataset.dir) { location.hash = `corrections~dir~${encodeURIComponent(el.dataset.dir)}`; return; }
1514
+ }
1515
+ const pick = e.target.closest("[data-project]");
1516
+ if (pick) { pickProject(pick.dataset.project); window.scrollTo(0, 0); return; }
1517
+ const row = e.target.closest("[data-href]");
1518
+ if (row && !e.target.closest("a,button,select,input")) location.hash = row.dataset.href;
1519
+ const jump = e.target.closest("[data-jump]");
1520
+ if (jump) {
1521
+ $$(".msg.focus").forEach((x) => x.classList.remove("focus"));
1522
+ const m = document.getElementById(`m${jump.dataset.jump}`);
1523
+ if (m) { m.classList.add("focus"); scrollToEl(m, "center"); /* instant: a smooth scroll across a long transcript is slow */ }
1524
+ }
1525
+ const un = e.target.closest("[data-unclamp]");
1526
+ if (un) { un.previousElementSibling.classList.remove("clamp"); un.remove(); }
1527
+ const rsort = e.target.closest("[data-rec-sort]");
1528
+ if (rsort) {
1529
+ const f = state.recFilter;
1530
+ const k = rsort.dataset.recSort;
1531
+ f.dir = f.sort === k ? -f.dir : -1;
1532
+ f.sort = k;
1533
+ rerender();
1534
+ }
1535
+ const rl = e.target.closest("[data-rec-lever]");
1536
+ if (rl) { state.recFilter.lever = rl.dataset.recLever; rerender(); }
1537
+ });
1538
+ document.addEventListener("keydown", (e) => {
1539
+ const row = e.target.closest?.("[data-href],[data-project]");
1540
+ if (row && row === e.target && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); row.click(); }
1541
+ });
1542
+ document.addEventListener("input", (e) => { if (e.target.id === "rec-q") { state.recFilter.q = e.target.value; rerender(); } });
1543
+ document.addEventListener("change", (e) => {
1544
+ const t = e.target, stages = state.settings?.stages;
1545
+ if (!stages || !t.closest(".settings")) return;
1546
+ // A model belongs to its provider, so a new provider starts from its default.
1547
+ if (t.dataset.llm) { Object.assign(stages[t.dataset.llm], { llm: t.value, model: "" }); rerender(); }
1548
+ else if (t.dataset.model) stages[t.dataset.model].model = t.value.trim();
1549
+ else if (t.id === "set-github") state.settings.github = t.checked;
1550
+ });
1551
+ document.addEventListener("submit", (e) => {
1552
+ const s = state.settings;
1553
+ if (!e.target.closest(".settings")) return;
1554
+ e.preventDefault();
1555
+ if (e.target.id === "key-form") settingsSend("key", "POST", "api/key", { key: $("#key").value.trim() }, "Key saved.");
1556
+ else settingsSend("save", "POST", "api/settings", { github: s.github, stages: Object.fromEntries(Object.entries(s.stages).map(([id, st]) => [id, { llm: st.llm, model: st.model }])) }, "Saved.");
1557
+ });
1558
+ document.addEventListener("click", (e) => { if (e.target.id === "key-remove") settingsSend("key", "DELETE", "api/key", undefined, "Key removed."); });
1559
+ document.addEventListener("change", (e) => { if (e.target.dataset.pick) togglePick(e.target.dataset.pick, e.target.checked); });
1560
+ document.addEventListener("click", (e) => {
1561
+ const act = { "projects-all": () => { state.run.showAll = true; rerender(); }, "est-refresh": estimate, "run-start": () => runSend("POST"), "run-cancel": () => runSend("DELETE") }[e.target.id];
1562
+ if (act && !e.target.disabled) act();
1563
+ });
1564
+ // toggle does not bubble, so catch it on the way down: the page is redrawn every 2 s and must keep the log open.
1565
+ document.addEventListener("toggle", (e) => { if (e.target.id === "run-log") state.run.logOpen = e.target.open; }, true);
1566
+ document.addEventListener("visibilitychange", () => { if (!document.hidden && state.run.status?.state === "running") runPoll(); });
1567
+ window.addEventListener("hashchange", () => {
1568
+ const deep = correctionsFromHash();
1569
+ route();
1570
+ if (deep) setTimeout(() => scrollToEl($("#turns")), 0);
1571
+ });
1572
+ }
1573
+
1574
+ // ---------- boot ----------
1575
+
1576
+ // Read the report and draw it. Called again when a check or an estimate has rebuilt it.
1577
+ async function load() {
1578
+ const d = await fetch("data/index.json", { cache: "no-store" }).then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); });
1579
+ state.data = d;
1580
+ for (const m of [state.sessionsById, state.recsBySession, state.sessionCache, state.shardCache, state.memo]) m.clear();
1581
+ d.recommendations.sort(byReach);
1582
+ for (const s of d.sessions) state.sessionsById.set(s.id, s);
1583
+ for (const r of d.recommendations) for (const sid of r.sessions) (state.recsBySession.get(sid) || state.recsBySession.set(sid, []).get(sid)).push(r);
1584
+ // Projects by session count. Two folders with the same name show their parent too, so they stay distinct.
1585
+ const byProject = groupBy(d.sessions, (s) => s.project || NO_PROJECT);
1586
+ const sameName = groupBy([...byProject.keys()], (p) => pathTail(p));
1587
+ state.projects = [...byProject].map(([p, ss]) => [p, p === NO_PROJECT ? "Unknown" : pathTail(p, sameName.get(pathTail(p)).length > 1 ? 2 : 1), ss.length])
1588
+ .sort((a, b) => b[2] - a[2] || a[1].localeCompare(b[1]));
1589
+ if (!byProject.has(state.scope.project)) state.scope.project = "";
1590
+ const m = d.meta;
1591
+ const picker = state.projects.length > 1;
1592
+ $("#workspace").classList.toggle("pick", picker);
1593
+ $("#workspace").innerHTML = picker
1594
+ ? `<select id="project-pick" aria-label="Project"><option value="">All projects</option>${state.projects.map(([p, label, n]) => `<option value="${esc(p)}" title="${esc(p)}"${p === state.scope.project ? " selected" : ""}>${esc(label)} (${n})</option>`).join("")}</select>`
1595
+ : `<span>${esc(workspaceLabel())}</span>`;
1596
+ $("#project-pick")?.addEventListener("change", (e) => pickProject(e.target.value));
1597
+ $("#side-foot").innerHTML = `<div class="row"><span>Sessions</span><span id="foot-sessions"></span></div>
1598
+ ${m.to ? `<div class="row"><span>Window</span><span>${esc(day(m.from))} – ${esc(day(m.to))}</span></div>` : ""}
1599
+ <div class="row"><span>Label confidence</span><span>≥ ${m.min_conf}</span></div>`;
1600
+ route();
1601
+ }
1602
+
1603
+ async function boot() {
1604
+ initEvents();
1605
+ try { state.scope.project = localStorage.getItem(PROJECT_KEY) || ""; } catch { /* no storage: start on all projects */ }
1606
+ correctionsFromHash();
1607
+ try {
1608
+ await load();
1609
+ } catch (e) {
1610
+ $("#content").innerHTML = `<section class="card"><div class="card-body"><h2>No data</h2><p>Could not load data/index.json (${esc(e.message)}). Run <code>debrief sync</code> to build it, and open this page over http, not as a file.</p></div></section>`;
1611
+ }
1612
+ }
1613
+ boot();