readthrough 0.4.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.
Files changed (73) hide show
  1. readthrough/__init__.py +8 -0
  2. readthrough/__main__.py +3 -0
  3. readthrough/agents.py +344 -0
  4. readthrough/analyze.py +537 -0
  5. readthrough/assets/SKILL.md +86 -0
  6. readthrough/assets/defaults.toml +143 -0
  7. readthrough/assets/profile-reference.md +133 -0
  8. readthrough/assets/vendor/README.md +22 -0
  9. readthrough/assets/vendor/cose-base.js +3214 -0
  10. readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
  11. readthrough/assets/vendor/cytoscape.min.js +31 -0
  12. readthrough/assets/vendor/layout-base.js +5230 -0
  13. readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
  14. readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
  15. readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
  16. readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
  17. readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
  18. readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
  19. readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
  20. readthrough/assets/vendor/lucide-icons.js +36 -0
  21. readthrough/assets/vendor/marked.umd.js +82 -0
  22. readthrough/assets/vendor/purify.min.js +7 -0
  23. readthrough/assets/web/dashboard.css +202 -0
  24. readthrough/assets/web/dashboard.html +48 -0
  25. readthrough/assets/web/dashboard.js +937 -0
  26. readthrough/assets/web/setup.css +57 -0
  27. readthrough/assets/web/setup.html +28 -0
  28. readthrough/assets/web/setup.js +342 -0
  29. readthrough/assets/web/theme.css +36 -0
  30. readthrough/assistants.py +699 -0
  31. readthrough/brief.py +145 -0
  32. readthrough/build.py +616 -0
  33. readthrough/ci.py +107 -0
  34. readthrough/cli.py +958 -0
  35. readthrough/config.py +533 -0
  36. readthrough/contract.py +394 -0
  37. readthrough/engine.py +230 -0
  38. readthrough/faults.py +92 -0
  39. readthrough/files.py +110 -0
  40. readthrough/forges/__init__.py +614 -0
  41. readthrough/forges/azure_devops.py +658 -0
  42. readthrough/forges/forgejo.py +300 -0
  43. readthrough/forges/github.py +487 -0
  44. readthrough/forges/gitlab.py +335 -0
  45. readthrough/ledger.py +61 -0
  46. readthrough/limits.py +26 -0
  47. readthrough/logs.py +169 -0
  48. readthrough/membership.py +76 -0
  49. readthrough/model.py +177 -0
  50. readthrough/onboard.py +551 -0
  51. readthrough/onboard_model.py +319 -0
  52. readthrough/process.py +169 -0
  53. readthrough/profile.py +699 -0
  54. readthrough/py.typed +0 -0
  55. readthrough/registry.py +157 -0
  56. readthrough/review.py +394 -0
  57. readthrough/rules.py +111 -0
  58. readthrough/runtimes/__init__.py +297 -0
  59. readthrough/runtimes/anthropic.py +278 -0
  60. readthrough/runtimes/copilot.py +313 -0
  61. readthrough/runtimes/openai.py +307 -0
  62. readthrough/serve.py +817 -0
  63. readthrough/study.py +327 -0
  64. readthrough/system.py +205 -0
  65. readthrough/terminals.py +168 -0
  66. readthrough/tuning.py +266 -0
  67. readthrough/usage.py +169 -0
  68. readthrough/web_setup.py +635 -0
  69. readthrough-0.4.0.dist-info/METADATA +123 -0
  70. readthrough-0.4.0.dist-info/RECORD +73 -0
  71. readthrough-0.4.0.dist-info/WHEEL +4 -0
  72. readthrough-0.4.0.dist-info/entry_points.txt +2 -0
  73. readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,937 @@
1
+ let DATA = /*__READTHROUGH_DATA__*/null;
2
+ const LIVE = /*__READTHROUGH_LIVE__*/null;
3
+ const LANES = {ready:"Ready", approved:"Approved", waiting:"Waiting on author", blocked:"Blocked", draft:"Draft", mine:"Mine"};
4
+ const AUTHORS = {internal:"Internal", external:"External", bot:"Bots"};
5
+ // CI states, in order of urgency. Pills group them; badges and the table show the exact state.
6
+ const CI = {
7
+ failing: {group: "failing", icon: "✗", label: "failing (required)"},
8
+ "not-run": {group: "pending", icon: "∅", label: "required checks haven't run"},
9
+ "failing-optional": {group: "failing", icon: "!", label: "optional check failing"},
10
+ "failing-main": {group: "failing", icon: "✗", label: "failing, but also on main"},
11
+ pending: {group: "pending", icon: "…", label: "pending"},
12
+ passing: {group: "passing", icon: "✓", label: "passing"},
13
+ unknown: {group: "pending", icon: "?", label: "CI couldn't be read"},
14
+ none: {group: "none", icon: "–", label: "no CI"},
15
+ };
16
+ const CI_GROUPS = {passing: "CI passing", failing: "Failing", pending: "Pending", none: "No CI"};
17
+ const ciState = p => p.ci_state || "none";
18
+ const ciRank = p => Object.keys(CI).indexOf(ciState(p));
19
+
20
+
21
+ const UNDERSTOOD = ["understood","reviewed","commented","approved","changes-requested"];
22
+ const REVIEWED = ["reviewed","commented","approved","changes-requested"];
23
+ const STORE = "readthrough:" + (DATA.slug || DATA.repo);
24
+ const FORGE = DATA.forge || {name: "github", label: "GitHub", pr_noun: "pull request", url: ""};
25
+ const SLUG = DATA.slug || `${FORGE.name}/${DATA.repo}`;
26
+ const GROUPS = {lanes: LANES, authors: AUTHORS, cis: CI_GROUPS};
27
+ const HASH = new URLSearchParams(location.hash.slice(1).split("?")[1] || "");
28
+ const fromHash = (key, all) => { const v = HASH.get(key); const keep = v ? v.split(",").filter(k => k in all) : []; return new Set(keep.length ? keep : Object.keys(all)); };
29
+ const state = {
30
+ tab: location.hash.slice(1).split("?")[0] || "map", lanes: fromHash("lanes", LANES), authors: fromHash("authors", AUTHORS),
31
+ cis: fromHash("ci", CI_GROUPS), greenFirst: localStorage.getItem("readthrough:green-first") !== "0",
32
+ q: HASH.get("q") || "", comp: HASH.get("comp"), sel: null, dtab: "overview", srcOnly: true, overlapOnly: true,
33
+ drafts: JSON.parse(sessionStorage.getItem(STORE + ":drafts") || "{}"),
34
+ };
35
+ const saveDrafts = () => sessionStorage.setItem(STORE + ":drafts", JSON.stringify(state.drafts));
36
+ const study = {}; // pr -> {entries, summary, engine, pending}
37
+ let byNum, comps, LINKS, progress;
38
+ const $ = id => document.getElementById(id);
39
+ const icon = (name, cls = "ico") => `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true">${LUCIDE[name] || ""}</svg>`;
40
+ // The mark is a page being read: a highlight band steps down the lines, and two lines carry a note.
41
+ const LOGO = `<svg class="logo" viewBox="0 0 32 32" aria-hidden="true">
42
+ <rect x="5.5" y="3.5" width="21" height="25" rx="3" fill="none" stroke="currentColor" stroke-opacity=".35"/>
43
+ <g class="sweep"><rect x="7.5" y="7.25" width="17" height="5.5" rx="2.75" fill="currentColor" fill-opacity=".16"/></g>
44
+ <g stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-opacity=".45"><line x1="10" y1="10" x2="21" y2="10"/><line x1="10" y1="14.5" x2="18" y2="14.5"/><line x1="10" y1="19" x2="21" y2="19"/><line x1="10" y1="23.5" x2="16" y2="23.5"/></g>
45
+ <circle class="blip" cx="22.5" cy="14.5" r="1.8" fill="var(--ready)"/><circle class="blip b2" cx="20.5" cy="23.5" r="1.8" fill="var(--blocked)"/></svg>`;
46
+ // The tab icon is the same page, with a badge counting PRs that are waiting on you.
47
+ function favicon(count){
48
+ const acc = css("--acc") || "#0969da", bad = css("--bad") || "#d1242f";
49
+ const badge = count ? `<circle cx="47" cy="17" r="17" fill="${bad}"/><text x="47" y="24" text-anchor="middle" font-family="Segoe UI,Arial" font-weight="700" font-size="${count > 9 ? 18 : 22}" fill="#fff">${count > 99 ? "99+" : count}</text>` : "";
50
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="8" y="4" width="46" height="56" rx="7" fill="${acc}"/><rect x="14" y="24" width="34" height="12" rx="6" fill="#fff" fill-opacity=".3"/><g stroke="#fff" stroke-width="4.5" stroke-linecap="round" stroke-opacity=".85"><path d="M19 17h24"/><path d="M19 30h18"/><path d="M19 43h24"/><path d="M19 52h12"/></g>${badge}</svg>`;
51
+ $("favicon").href = "data:image/svg+xml," + encodeURIComponent(svg);
52
+ }
53
+ const EMPTY = msg => `<div class="empty-state"><svg viewBox="0 0 120 120" aria-hidden="true"><rect x="22" y="10" width="76" height="100" rx="9" fill="none" stroke="var(--line)" stroke-width="2"/><rect x="30" y="38" width="60" height="18" rx="9" fill="var(--acc)" fill-opacity=".12"/><g stroke="var(--line)" stroke-width="3" stroke-linecap="round" stroke-dasharray="4 5"><path d="M38 30h44"/><path d="M38 47h32"/><path d="M38 64h44"/><path d="M38 81h24"/></g><circle cx="38" cy="47" r="3.5" fill="var(--acc)"/><path d="M84 92 l6 6 m0 -6 l-6 6" stroke="var(--mut)" stroke-width="2" stroke-linecap="round"/></svg><div>${msg}</div></div>`;
54
+ const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
55
+ // A link a forge or a repo file supplied: only web URLs, and escaped for the attribute. Anything else links nowhere.
56
+ const safeUrl = u => /^https?:\/\//i.test(u || "") ? esc(u) : "";
57
+ const css = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
58
+ const laneColor = l => `var(--${l})`;
59
+ const lines = p => p.additions + p.deletions;
60
+ const authorGroup = p => p.author_group || (p.author_kind === "first-time" ? "external" : (p.author_kind || "external"));
61
+ const isFirst = p => p.author_kind === "first-time";
62
+ const isExt = p => authorGroup(p) === "external";
63
+ const kindBadge = k => (PROFILE.author_kinds?.[k]?.badge) || k || "";
64
+
65
+ let PROFILE, NON_SOURCE = [];
66
+ const layerColor = id => {
67
+ const layers = PROFILE.layers, layer = layers.find(l => l.id === id);
68
+ if (layer?.color) return layer.color;
69
+ if (layer && layer.source === false) return "var(--support)";
70
+ const i = layers.filter(l => l.source !== false).findIndex(l => l.id === id);
71
+ return `var(--l${Math.max(0, i) % 6})`;
72
+ };
73
+ function setData(d){
74
+ DATA = d;
75
+ PROFILE = DATA.profile;
76
+ NON_SOURCE = (PROFILE.overlap_non_source || []).map(p => new RegExp(p));
77
+ byNum = Object.fromEntries(DATA.prs.map(p => [p.number, p]));
78
+ comps = Object.fromEntries(DATA.components.map(c => [c.id, c]));
79
+ LINKS = DATA.links || {};
80
+ loadProgress();
81
+ }
82
+ // Live mode: the ledger is the only source of truth. Snapshot: this browser's checkmarks plus the ledger.
83
+ function loadProgress(){
84
+ progress = LIVE ? {} : JSON.parse(localStorage.getItem(STORE) || "{}");
85
+ for (const [num, e] of Object.entries(DATA.ledger || {})) {
86
+ const p = progress[num] ||= {};
87
+ if (UNDERSTOOD.includes(e.status)) p.understood = true;
88
+ if (REVIEWED.includes(e.status)) p.reviewed = true;
89
+ p.head = e.head || p.head; p.note = e.note; p.status = e.status;
90
+ }
91
+ }
92
+ setData(DATA);
93
+ if (state.comp && !comps[state.comp]) state.comp = null;
94
+ const save = () => { if (!LIVE) localStorage.setItem(STORE, JSON.stringify(progress)); };
95
+ const stale = n => progress[n]?.head && byNum[n] && progress[n].head !== byNum[n].head;
96
+
97
+ // ---- theme
98
+ const THEMES = ["auto", "light", "dark"];
99
+ let themePref = localStorage.getItem("readthrough:theme") || "auto";
100
+ const darkQuery = matchMedia("(prefers-color-scheme: dark)");
101
+ function applyTheme(){
102
+ const theme = themePref === "auto" ? (darkQuery.matches ? "dark" : "light") : themePref;
103
+ document.documentElement.dataset.theme = theme;
104
+ $("theme").innerHTML = icon({auto: "sun-moon", light: "sun", dark: "moon"}[themePref]);
105
+ $("theme").title = {auto: "Theme: follows your OS", light: "Theme: light", dark: "Theme: dark"}[themePref] + ". Click to change.";
106
+ $("theme").setAttribute("aria-label", $("theme").title);
107
+ favicon(needsYou());
108
+ if (cy) styleGraph();
109
+ }
110
+ darkQuery.addEventListener("change", applyTheme);
111
+
112
+ // ---- markdown, always sanitized (PR text is written by strangers)
113
+ DOMPurify.addHook("afterSanitizeAttributes", node => {
114
+ if (node.tagName === "A") { node.setAttribute("target", "_blank"); node.setAttribute("rel", "noopener noreferrer"); }
115
+ });
116
+ const PURIFY = {FORBID_TAGS: ["style", "form", "input", "button", "textarea", "select", "iframe"], FORBID_ATTR: ["style"], ALLOW_DATA_ATTR: false};
117
+ const safeHtml = html => DOMPurify.sanitize(html || "", PURIFY);
118
+ const md = text => safeHtml(marked.parse(text || "", {gfm: true, breaks: false}));
119
+ // What a model wrote never needs a picture, and an image URL is a way to send data out: no images in study
120
+ // text or the brief. A PR's own description keeps its screenshots.
121
+ const mdModel = text => DOMPurify.sanitize(marked.parse(text || "", {gfm: true, breaks: false}), {...PURIFY, FORBID_TAGS: [...PURIFY.FORBID_TAGS, "img", "picture", "source", "video", "audio"]});
122
+
123
+ function toast(msg){ const t = $("toast"); t.textContent = msg; t.classList.add("on"); clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove("on"), 2200); }
124
+ function copy(text, msg){ navigator.clipboard.writeText(text).then(() => toast(msg || "Copied")).catch(err => toast(`Couldn't copy: ${err.message}`)); }
125
+ const deepPrompt = n => `[readthrough:${SLUG}#${n}] Use the readthrough skill to run a deep review session for ${DATA.repo}#${n}. The study brief is at ${(LINKS.briefs_dir || "").replace(/\\/g, "/")}/pr-${n}.md`;
126
+ const reviewUrl = n => `readthrough://review/${SLUG}/${n}`;
127
+ // A session's editor link comes from the agent that owns it (Copilot sessions open in VS Code's agent window;
128
+ // Claude Code sessions have none), so the page never guesses one.
129
+ const vscodeUrl = n => {
130
+ const s = (byNum[n].sessions || []).find(s => s.editor_url);
131
+ if (s) return s.editor_url;
132
+ return `vscode://agents/new?prompt=${encodeURIComponent(deepPrompt(n))}` + (LINKS.clone_uri ? `&workspace=${encodeURIComponent(LINKS.clone_uri)}` : "");
133
+ };
134
+ const ago = ts => { const h = (Date.now() - ts) / 3.6e6; return h < 1 ? `${Math.max(1, Math.round(h * 60))} min ago` : h < 48 ? `${Math.round(h)} h ago` : `${Math.round(h / 24)} d ago`; };
135
+ const agentLabel = s => s.agent_label || "Copilot";
136
+ const sessDot = p => {
137
+ const all = p.sessions || (p.session?.exists ? [p.session] : []);
138
+ if (!all.length) return "";
139
+ const live = all.filter(s => s.active).length, latest = Math.max(...all.map(s => s.updated || 0));
140
+ const labels = [...new Set(all.map(agentLabel))].join(" and ");
141
+ const what = all.length > 1 ? `${all.length} ${labels} sessions` : `A ${labels} review session`;
142
+ return live ? `<span class="sess live" title="${esc(what)}; ${live} open right now"></span>`
143
+ : `<span class="sess" title="${esc(what)}, last active ${ago(latest * 1000)}"></span>`;
144
+ };
145
+ // `active` is true, false, or null: null means the agent leaves no trace of whether the session is open.
146
+ const activity = s => s.active ? "<b>open now</b>" : s.active === false ? ago(s.updated * 1000) : `last written ${ago(s.updated * 1000)}`;
147
+ function sessionList(n){
148
+ const all = byNum[n].sessions || [];
149
+ if (!all.length) return `<div class="hint">No review session yet. Starting one keeps it for this PR, so you can come back to it. Sessions started from VS Code, Claude Code, or a copied prompt show up here too.</div>`;
150
+ return `<div class="sessions">${all.map(s => `<div class="srow">${icon(s.where === "VS Code" ? "square-code" : "terminal", "ico sm")}
151
+ <span class="sname" title="${esc(s.id)}">${esc(s.name || s.id.slice(0, 8))}</span>
152
+ <span class="muted">${esc(agentLabel(s))} · ${esc(s.where)} · ${activity(s)}</span>
153
+ ${LIVE ? `<button class="btn small" data-review="${n}" data-session="${s.id}" title="Resume this session in a new terminal">terminal</button>` : ""}
154
+ ${s.editor_url ? `<a class="btn small" href="${esc(s.editor_url)}" title="Open this session in VS Code's agent window">VS Code</a>` : ""}</div>`).join("")}</div>`;
155
+ }
156
+ const whoBadge = p => {
157
+ const k = p.author_kind || "external";
158
+ const cls = isFirst(p) ? "first" : {internal: "int", external: "ext", bot: "bot"}[authorGroup(p)];
159
+ return `<span class="who ${cls}" title="${esc(FORGE.label)} association: ${esc(p.author_association || "?")}">${esc(kindBadge(k))}</span>`;
160
+ };
161
+ const scoreBadge = p => {
162
+ const s = p.study;
163
+ if (!s || !(s.assessed || s.predictions || s.teachback)) return "";
164
+ const q = s.assessed ? `quiz ${s.correct}/${s.assessed}` : "studying";
165
+ return `<span class="score" title="Study log: ${s.correct} correct, ${s.partial} partial, ${s.incorrect} incorrect; ${s.predictions} predictions; teach-back ${s.teachback || "not yet"}">${q}</span>`;
166
+ };
167
+ function reviewButton(n, cls = "btn small"){
168
+ const resume = byNum[n].session && byNum[n].session.exists;
169
+ const label = resume ? "resume" : "review", title = `${resume ? "Resume" : "Start"} the deep-review session for #${n} in a terminal`;
170
+ if (LIVE) return `<button class="${cls}" data-review="${n}" title="${title}">${label}</button>`;
171
+ if (LINKS.protocol) return `<a class="${cls}" href="${reviewUrl(n)}" title="${title}">${label}</a>`;
172
+ return `<button class="${cls}" data-copy="readthrough review ${n}" title="Copies the command. Run 'readthrough serve' (or 'readthrough install protocol') to make this one click.">${label}</button>`;
173
+ }
174
+ async function api(path, body, method = "POST"){
175
+ const opts = method === "GET" ? {cache: "no-store"} : {method, headers: {"Content-Type": "application/json", "X-Readthrough-Token": LIVE.token}, body: JSON.stringify(body || {})};
176
+ const resp = await fetch((LIVE.base || "") + path, opts);
177
+ const data = await resp.json().catch(() => ({}));
178
+ if (!resp.ok) throw new Error(data.error || resp.statusText);
179
+ return data;
180
+ }
181
+
182
+ // ---- filtering
183
+ function visible(p){
184
+ if (!state.lanes.has(p.lane) || !state.authors.has(authorGroup(p)) || !state.cis.has(CI[ciState(p)].group)) return false;
185
+ if (state.comp && !(state.comp in p.by_comp)) return false;
186
+ const q = state.q.trim().toLowerCase();
187
+ if (!q) return true;
188
+ return q.split(/\s+/).every(t => {
189
+ if (t.startsWith("@")) return p.author.toLowerCase().includes(t.slice(1));
190
+ if (t.startsWith("#")) return String(p.number).startsWith(t.slice(1));
191
+ if (t.startsWith("comp:")) return Object.keys(p.by_comp).some(c => c.startsWith(t.slice(5)));
192
+ if (t.startsWith("flag:")) return [...p.flags, ...p.smells].some(f => f.id.startsWith(t.slice(5)));
193
+ if (t.startsWith("is:")) return (p.author_kind || "").startsWith(t.slice(3)) || authorGroup(p).startsWith(t.slice(3));
194
+ if (t.startsWith("ci:")) { const v = t.slice(3); return v === "main" ? ciState(p) === "failing-main" : ciState(p).startsWith(v) || CI[ciState(p)].group.startsWith(v); }
195
+ return (p.title + " " + p.author + " " + p.files.map(f => f.path).join(" ")).toLowerCase().includes(t);
196
+ });
197
+ }
198
+
199
+ // ---- header
200
+ // "as of" in as few words as the moment allows: the time alone for today, the date too for anything older.
201
+ function when(ts){
202
+ const d = new Date(ts), now = new Date();
203
+ const time = d.toLocaleTimeString([], {hour: "numeric", minute: "2-digit"});
204
+ return d.toDateString() === now.toDateString() ? time : `${d.toLocaleDateString([], {month: "short", day: "numeric"})}, ${time}`;
205
+ }
206
+ function header(){
207
+ // The product first, the repo second, the small print third: readthrough / microsoft/vscode · 100 open · as of…
208
+ document.title = `${PROFILE.title} · readthrough`;
209
+ $("repos").innerHTML = LIVE
210
+ ? `<label class="switch" title="Switch repo (${esc(FORGE.label)})"><span class="switch-name">${esc(DATA.repo)}</span>${icon("chevron-down", "ico sm")}<select id="repoSwitch" aria-label="Switch repo">${LIVE.repos.map(r => `<option value="${esc(r.slug)}" ${r.slug === SLUG ? "selected" : ""}>${esc(r.name)}</option>`).join("")}<option value="__setup">+ Onboard a repo…</option></select></label>`
211
+ : `<span class="switch static" title="${esc(FORGE.label)}">${esc(DATA.repo)}</span>`;
212
+ $("tools").innerHTML = LIVE
213
+ ? `<a class="btn icon" href="/setup?repo=${encodeURIComponent(SLUG)}" title="Settings for ${esc(DATA.repo)}: account, clone, profile, authors" aria-label="Repo settings">${icon("settings")}</a>`
214
+ : "";
215
+ const shown = DATA.prs.length, open = DATA.stats?.open;
216
+ const openCount = open > shown
217
+ ? `<span title="Showing the ${shown} most recently active of ${open.toLocaleString()} open ${esc(FORGE.pr_noun)}s. Raise \`limit\` in this repo's settings to see more.">${shown} of ${open.toLocaleString()} open</span>`
218
+ : `${shown} open`;
219
+ $("meta").innerHTML = [openCount, `as of ${esc(when(DATA.generated))}`, DATA.viewer ? `@${esc(DATA.viewer)}` : ""].filter(Boolean).join(" · ");
220
+ $("logo").innerHTML ||= LOGO;
221
+ renderTabs();
222
+ const count = fn => DATA.prs.reduce((m, p) => (m[fn(p)] = (m[fn(p)] || 0) + 1, m), {});
223
+ const counts = {lanes: count(p => p.lane), authors: count(authorGroup), cis: count(p => CI[ciState(p)].group)};
224
+ const ciDot = {passing: "var(--good)", failing: "var(--bad)", pending: "var(--warn)", none: "var(--draft)"};
225
+ const dot = {lanes: laneColor, authors: k => k === "external" ? "var(--external)" : null, cis: k => ciDot[k]};
226
+ const attr = {lanes: "lane", authors: "author", cis: "ci"};
227
+ for (const [group, labels] of Object.entries(GROUPS)) {
228
+ const set = state[group], all = set.size === Object.keys(labels).length;
229
+ $(group).classList.toggle("filtered", !all);
230
+ $(group).innerHTML = Object.entries(labels).filter(([k]) => counts[group][k]).map(([k, l]) => {
231
+ const on = set.has(k), only = set.size === 1 && on, color = dot[group](k);
232
+ const tip = only ? `Showing only ${l}. Click to show everything again.` : `Click: show only ${l}. Ctrl-click: ${on ? "hide" : "add"} ${l}.`
233
+ + (k === "external" ? " Includes first-time contributors (hollow dot)." : "");
234
+ return `<button class="lane ${on ? "inc" : "off"}" data-${attr[group]}="${k}" aria-pressed="${on}" title="${tip}">${color ? `<i style="background:${color}"></i>` : ""}${l} ${counts[group][k]}</button>`;
235
+ }).join("");
236
+ }
237
+ const parts = Object.entries(GROUPS).filter(([g, labels]) => state[g].size !== Object.keys(labels).length)
238
+ .map(([g, labels]) => [...state[g]].map(k => labels[k]).join(" + "));
239
+ $("filtered").innerHTML = parts.length ? `<button class="clear" data-clear title="Show every lane, author, and CI state">${icon("filter-x")}Only ${esc(parts.join(" · "))} · show all</button>` : "";
240
+ const ready = DATA.prs.filter(p => !["draft","mine"].includes(p.lane));
241
+ const u = ready.filter(p => progress[p.number]?.understood && !stale(p.number)).length;
242
+ const r = ready.filter(p => progress[p.number]?.reviewed && !stale(p.number)).length;
243
+ $("progtext").textContent = `${r} reviewed · ${u} understood / ${ready.length}`;
244
+ $("progbar").innerHTML = `<span style="width:${100*r/ready.length}%;background:var(--ready)"></span><span style="width:${100*(u-r)/ready.length}%;background:color-mix(in srgb,var(--ready) 40%,transparent)"></span>`;
245
+ const building = !!LIVE?.status?.building;
246
+ $("refresh").innerHTML = LIVE
247
+ ? `${liveBadge()}<button class="btn icon ${building ? "busy" : ""}" data-refresh ${building ? "disabled" : ""} title="${building ? "Refreshing now" : "Fetch the latest PRs now"}" aria-label="Refresh">${icon("refresh-cw")}</button>`
248
+ : LINKS.protocol ? `<a class="btn icon" href="readthrough://refresh/${SLUG}" title="Refresh">${icon("refresh-cw")}</a>`
249
+ : `<button class="btn icon" data-copy="readthrough build --open" title="Copies the refresh command" aria-label="Copy refresh command">${icon("refresh-cw")}</button>`;
250
+ syncHash();
251
+ banners();
252
+ favicon(needsYou());
253
+ }
254
+ function dataFreshness(){
255
+ const ageH = (Date.now() - new Date(DATA.generated)) / 3.6e6;
256
+ const fresh = DATA.freshness || {stale_live_hours: 2, stale_snapshot_hours: 26};
257
+ return {hours: Math.round(ageH), stale: ageH > (LIVE ? fresh.stale_live_hours : fresh.stale_snapshot_hours)};
258
+ }
259
+ // Connection failures take precedence, but never hide the age of stale data.
260
+ function liveBadge(){
261
+ const s = LIVE.status || {}, age = dataFreshness();
262
+ const ageText = age.stale ? ` · ${age.hours} h` : "";
263
+ const ageDetail = age.stale ? ` Data is ${age.hours} hours old. Refresh, or check readthrough doctor.` : "";
264
+ const chip = (cls, text, title) => `<span class="live-status ${cls}" role="status" title="${esc(title + ageDetail)}"><span class="ping"></span>${esc(text + ageText)}</span>`;
265
+ if (LIVE.disconnected) return chip("off", "offline", "Lost the connection to readthrough serve. Retrying.");
266
+ if (s.building) return chip("busy", "refreshing", "Fetching the latest PRs now.");
267
+ if (s.error) { const e = typeof s.error === "object" ? `${s.error.message} [error ${s.error.id}]` : s.error;
268
+ return chip("err", "refresh failed", `The last refresh failed: ${e}. Showing the last good data; retrying automatically.`); }
269
+ const next = s.next_build ? ` Next check at ${new Date(s.next_build * 1000).toLocaleTimeString([], {hour: "numeric", minute: "2-digit"})}.` : "";
270
+ if (age.stale) return chip("stale", "stale", `Connected to readthrough serve.${next}`);
271
+ return chip("", "live", `Connected to readthrough serve; the page updates itself.${next}`);
272
+ }
273
+ const TABS = [["map", "Architecture map", "layers"], ["plan", "Burn-down plan", "list-checks"], ["overlap", "Overlap graph", "network"], ["table", "All PRs", "table-2"]];
274
+ function renderTabs(){
275
+ const nav = $("tabs");
276
+ if (!nav.childElementCount) nav.innerHTML = `<span class="tab-ind"></span>` + TABS.map(([k, l, ic]) => `<button class="tab" data-tab="${k}" title="${l}">${icon(ic)}<span class="tl" data-l="${l}">${l}</span></button>`).join("");
277
+ let on;
278
+ nav.querySelectorAll(".tab").forEach(t => { const yes = t.dataset.tab === state.tab; t.classList.toggle("on", yes); t.setAttribute("aria-current", yes ? "page" : "false"); if (yes) on = t; });
279
+ const ind = nav.querySelector(".tab-ind");
280
+ if (on) requestAnimationFrame(() => { ind.style.left = on.offsetLeft + "px"; ind.style.width = on.offsetWidth + "px"; });
281
+ }
282
+ // Filters live in the URL, so a view like "only my PRs" can be bookmarked.
283
+ function syncHash(){
284
+ const q = new URLSearchParams(), key = {lanes: "lanes", authors: "authors", cis: "ci"};
285
+ for (const [g, labels] of Object.entries(GROUPS)) if (state[g].size !== Object.keys(labels).length) q.set(key[g], [...state[g]].join(","));
286
+ if (state.q.trim()) q.set("q", state.q.trim());
287
+ if (state.comp) q.set("comp", state.comp);
288
+ const hash = "#" + state.tab + (q.size ? "?" + q.toString().replace(/%2C/g, ",") : "");
289
+ if (location.hash !== hash) history.replaceState(null, "", hash);
290
+ }
291
+ function pick(group, key, e){
292
+ const set = state[group], all = Object.keys(GROUPS[group]);
293
+ if (e.ctrlKey || e.metaKey || e.shiftKey) { set.has(key) ? set.delete(key) : set.add(key); if (!set.size) all.forEach(k => set.add(k)); }
294
+ else if (set.size === 1 && set.has(key)) all.forEach(k => set.add(k));
295
+ else { set.clear(); set.add(key); }
296
+ render();
297
+ }
298
+ const needsYou = () => DATA.prs.filter(p => p.flags.some(f => f.kind === "you") && !progress[p.number]?.reviewed).length;
299
+ // The explanation under a view's title, folded away once read; whether it's open is remembered across views and visits.
300
+ const legend = (title, html) => `<details class="legend" ${localStorage.getItem("readthrough:legend") === "open" ? "open" : ""}><summary>${title}</summary><p>${html}</p></details>`;
301
+ document.addEventListener("toggle", e => { if (e.target.matches?.("details.legend")) localStorage.setItem("readthrough:legend", e.target.open ? "open" : "closed"); }, true);
302
+ function banners(){
303
+ const out = [];
304
+ const age = dataFreshness();
305
+ if (!LIVE && age.stale) out.push(`<div class="banner warn stale-data"><b>This data is ${age.hours} hours old.</b><span class="muted">Refresh, or check <code>readthrough doctor</code>.</span></div>`);
306
+ const err = LIVE?.status?.error;
307
+ if (err && typeof err === "object") out.push(`<div class="banner warn"><b>The last refresh failed</b><span>during ${esc(err.step)}: ${esc(err.message)}</span><span class="muted">Showing the last good data. ${LIVE.status.consecutive_failures > 1 ? `${LIVE.status.consecutive_failures} failures in a row. ` : ""}Retrying automatically. Error <code>${esc(err.id)}</code> in readthrough.log.</span></div>`);
308
+ // The `limit` warning is a standing fact about a big repo, not news: the header's count carries it ("100 of 2,885 open").
309
+ for (const w of (DATA.warnings || []).filter(w => w.code !== "limit")) out.push(`<div class="banner warn"><b>${icon("info", "ico sm")}${esc(w.message)}</b>${w.details?.length ? `<details class="muted"><summary>${w.details.length} detail${w.details.length > 1 ? "s" : ""}</summary><ul>${w.details.map(d => `<li><code>${esc(d)}</code></li>`).join("")}</ul></details>` : ""}</div>`);
310
+ if (DATA.draft) out.push(`<div class="banner warn"><b>Onboarding preview.</b><span class="muted">This map comes from a draft profile. Edit it, then finish with <code>readthrough onboard ${esc(DATA.repo)} --accept</code>.</span></div>`);
311
+ if (DATA.drift) out.push(`<div class="banner warn"><b>The map is drifting:</b><span>only ${Math.round(DATA.drift.coverage * 100)}% of open-PR changes land in a known component.</span><span class="muted">Unmapped: ${DATA.drift.unmapped.map(([p, n]) => `<code>${esc(p)}</code> (${n})`).join(", ")}. Update it with <code>readthrough onboard ${esc(DATA.repo)} --update</code>.</span></div>`);
312
+ const nw = DATA.news || {};
313
+ if (nw.since){
314
+ const list = ns => ns.filter(n => byNum[n]).map(n => chip(byNum[n])).join(" ");
315
+ const parts = [];
316
+ if (nw.needs_you?.length) parts.push(`<span><b>Needs you:</b> ${list(nw.needs_you)}</span>`);
317
+ if (nw.changed_after_review?.length) parts.push(`<span><b>Changed since your review:</b> ${list(nw.changed_after_review)}</span>`);
318
+ if (nw.opened?.length) parts.push(`<span><b>New:</b> ${list(nw.opened)}</span>`);
319
+ if (nw.closed?.length) parts.push(`<span class="muted">Closed or merged: ${nw.closed.map(c => `<span title="${esc(c.title)}">#${c.number}</span>`).join(", ")}</span>`);
320
+ // Only when there is news: "nothing new" isn't worth a banner on every visit.
321
+ if (parts.length) out.push(`<div class="banner"><span class="muted">Since you last opened this (${esc(when(nw.since))}):</span>${parts.join("")}</div>`);
322
+ }
323
+ $("banners").innerHTML = out.join("");
324
+ }
325
+ function chip(p, comp){
326
+ const cls = ["chip", comp && p.primary === comp ? "pri" : "", (isFirst(p) ? "first" : isExt(p) ? "ext" : authorGroup(p) === "bot" ? "bot" : "")].join(" ");
327
+ const pad = Math.round(5 + Math.min(12, Math.log2(1 + lines(p))));
328
+ const who = kindBadge(p.author_kind);
329
+ return `<span class="${cls}" data-pr="${p.number}" style="background:${laneColor(p.lane)};padding-left:${pad}px;padding-right:${pad}px" title="#${p.number} ${esc(p.title)}\n@${esc(p.author)} (${esc(who)}) · ${LANES[p.lane]} · +${p.additions}/-${p.deletions}${comp ? ` · ${p.by_comp[comp]} lines here` : ""}">${p.number}</span>`;
330
+ }
331
+ // Every signal is worked out by a rule, never by a language model; DATA.rules says which rule.
332
+ const SOURCE = {forge: ["git-pull-request", `From ${FORGE.label}`], github: ["git-pull-request", "From GitHub"], profile: ["cog", "Rule in the repo's profile"], "built-in": ["cog", "readthrough check"]};
333
+ const ruleTip = id => { const r = DATA.rules?.[id]; return r ? `${SOURCE[r.source][1]}: ${r.how}` : ""; };
334
+ const ruleIcon = id => { const r = DATA.rules?.[id]; return r ? icon(SOURCE[r.source][0], "ico sm") : ""; };
335
+ function flagsHtml(p, kinds = ["blocker","you","risk","responsibility"]){
336
+ const fl = p.flags.filter(f => kinds.includes(f.kind)).map(f => `<span class="flag ${f.kind}" title="${esc(f.msg + "\n" + ruleTip(f.id))}">${esc(f.id)}</span>`);
337
+ const sm = [...new Set(p.smells.filter(s => s.kind === "responsibility").map(s => s.id))].map(id => `<span class="flag responsibility" title="${esc(p.smells.find(s => s.id === id).msg + "\n" + ruleTip(id))}">${esc(id)}</span>`);
338
+ return fl.concat(sm).join("");
339
+ }
340
+
341
+ // ---- architecture map
342
+ // Bar under each component: length = its changed lines vs. the busiest component; colors = how those lines split by lane.
343
+ function mixBar(prs, comp, total, max){
344
+ if (!total) return "";
345
+ const by = prs.reduce((m, p) => (m[p.lane] = (m[p.lane] || 0) + p.by_comp[comp], m), {});
346
+ const parts = Object.keys(LANES).filter(l => by[l]);
347
+ const tip = `${total} changed lines here (${Math.round(100 * total / max)}% of the busiest component): ` + parts.map(l => `${LANES[l]} ${by[l]}`).join(", ");
348
+ return `<div class="mix" style="width:${100 * total / max}%" title="${tip}">${parts.map(l => `<span style="flex:${by[l]};background:${laneColor(l)}"></span>`).join("")}</div>`;
349
+ }
350
+ function renderMap(){
351
+ const focusedComp = document.activeElement?.dataset?.comp;
352
+ const vis = DATA.prs.filter(visible);
353
+ const max = Math.max(1, ...DATA.components.map(c => vis.reduce((s,p) => s + (p.by_comp[c.id]||0), 0)));
354
+ let html = legend("How to read the map", `Each chip is a PR, colored by lane and sized by how much it changes. An outline marks the component where most of the change lives. An orange dot marks an external author, a hollow one a first-time contributor. Hover a chip to light up every component it touches; click a component to filter. The bar under a component shows how much is changing there compared with the busiest one, colored by lane. ${icon("cog", "ico sm")}Placement is by the profile's path patterns, not a language model. ${profileLine()}`);
355
+ if (!vis.length) html += `<p class="map-empty">No PRs match these filters.</p>`;
356
+ for (const {id: layer, label, flow} of PROFILE.layers){
357
+ const members = DATA.components.filter(c => c.layer === layer).map(c => ({
358
+ c, prs: vis.filter(p => c.id in p.by_comp).sort((a,b) => b.by_comp[c.id] - a.by_comp[c.id]),
359
+ }));
360
+ const bricks = members.filter(m => m.prs.length).map(({c, prs}, i) => {
361
+ const total = prs.reduce((s,p) => s + p.by_comp[c.id], 0);
362
+ const arrow = flow && i > 0 ? `<span class="arrow">→</span>` : "";
363
+ return `${arrow}<div class="brick ${state.comp===c.id?"sel":""}" data-comp="${esc(c.id)}" role="button" tabindex="0" aria-pressed="${state.comp === c.id}" title="${esc(c.contract?.responsibility || "")}">
364
+ <h3>${esc(c.label)} <span>${prs.length} PR · ${total} ln</span></h3>
365
+ <div class="chips">${prs.map(p => chip(p, c.id)).join("")}</div>
366
+ ${mixBar(prs, c.id, total, max)}</div>`;
367
+ }).join("");
368
+ const empty = members.filter(m => !m.prs.length).map(({c}) => `<button class="empty-component" data-comp="${esc(c.id)}" aria-pressed="${state.comp === c.id}" title="${esc([c.contract?.responsibility, "No PRs match these filters. Click to filter this component; click again to clear it."].filter(Boolean).join("\n"))}">${esc(c.label)}</button>`).join("");
369
+ html += `<div class="layer"><div class="layer-label" style="border-color:${esc(layerColor(layer))}">${esc(label)}</div><div class="layer-content">${bricks ? `<div class="bricks">${bricks}</div>` : ""}${empty ? `<div class="empty-components" role="group" aria-label="${esc(label)}: no matching PRs"><span>No matching PRs:</span>${empty}</div>` : ""}</div></div>`;
370
+ }
371
+ $("v-map").innerHTML = html;
372
+ if (focusedComp) $("v-map").querySelector(`[data-comp="${CSS.escape(focusedComp)}"]`)?.focus({preventScroll: true});
373
+ }
374
+
375
+ // ---- burn-down plan
376
+ const ciBadge = p => {
377
+ const s = ciState(p), c = CI[s], fails = (p.ci_checks?.failing || []);
378
+ const detail = fails.length ? "\n" + fails.slice(0, 8).map(f => `✗ ${f.name}${f.required ? " (required)" : ""}${f.on_main ? " (also on main)" : ""}`).join("\n") : "";
379
+ return `<span class="cib ${s}" title="${esc(`CI: ${c.label}${detail}`)}">${c.icon}</span>`;
380
+ };
381
+ const STATUSES = [["", "To do"], ["understood", "Understood"], ["reviewed", "Reviewed"], ["commented", "Commented"], ["approved", "Approved"], ["changes-requested", "Changes requested"], ["skipped", "Skipped"]];
382
+ const savingStatuses = new Set();
383
+ const statusOf = n => { const g = progress[n]; if (!g || stale(n)) return ""; return g.status || (g.reviewed ? "reviewed" : g.understood ? "understood" : ""); };
384
+ const statusSelect = n => { const cur = statusOf(n);
385
+ return `<select class="status s-${cur || "todo"}" data-status="${n}" ${savingStatuses.has(n) ? "disabled" : ""} aria-label="Your status for #${n}" title="What you've done with #${n}${LIVE ? ". Saved to the ledger; new commits reset it." : ". New commits reset it."}">${STATUSES.map(([v, l]) => `<option value="${v}" ${cur === v ? "selected" : ""}>${l}</option>`).join("")}</select>`; };
386
+ const statusPills = n => `<div class="status-pills" role="group" aria-label="Your status for #${n}" aria-busy="${savingStatuses.has(n)}">${STATUSES.map(([v, l]) => `<button class="status-pill s-${v || "todo"}" data-set-status="${n}" value="${v}" aria-pressed="${statusOf(n) === v}" aria-disabled="${savingStatuses.has(n)}">${l}</button>`).join("")}</div>`;
387
+ async function setStatus(n, value){
388
+ if (savingStatuses.has(n)) return;
389
+ const status = value || null;
390
+ if (LIVE) {
391
+ savingStatuses.add(n); render();
392
+ try { DATA.ledger = await api(`/api/ledger/${n}`, {status}); loadProgress(); }
393
+ catch (err) { toast(`Couldn't save your status: ${err.message}`); }
394
+ finally { savingStatuses.delete(n); render(); }
395
+ } else {
396
+ const g = progress[n] ||= {};
397
+ Object.assign(g, {status, understood: UNDERSTOOD.includes(status), reviewed: REVIEWED.includes(status), head: byNum[n].head});
398
+ save(); render();
399
+ }
400
+ }
401
+ function prRow(n){
402
+ const p = byNum[n]; if (!p || !visible(p)) return "";
403
+ const g = progress[n] || {}; const st = stale(n);
404
+ return `<div class="row ${g.reviewed && !st ? "done":""}">
405
+ ${statusSelect(n)}
406
+ <a href="${safeUrl(p.url)}" target="_blank" rel="noopener">#${n}</a>
407
+ <span class="t" data-open="${n}" title="${esc(p.title)}">${ciBadge(p)} ${esc(p.title)} <span class="muted">@${esc(p.author)}</span>${whoBadge(p)}${sessDot(p)}${scoreBadge(p)}${st?' <span class="flag blocker">changed since review</span>':""}</span>
408
+ <span>${flagsHtml(p)}</span>
409
+ <span class="muted">${p.minutes}m ${reviewButton(n)}</span></div>`;
410
+ }
411
+ function scatter(){
412
+ const pts = DATA.prs.filter(visible);
413
+ const W = 460, H = 300, P = 34;
414
+ const maxAge = Math.max(2, ...pts.map(p => p.age_days)), maxL = Math.max(10, ...pts.map(lines));
415
+ const x = a => P + (W-2*P) * Math.log1p(a)/Math.log1p(maxAge);
416
+ const y = l => H-P - (H-2*P) * Math.log1p(l)/Math.log1p(maxL);
417
+ const midX = Math.min(W-P, x(14)), midY = Math.max(P, y(200)); // clamped: with only young or small PRs the dividers fall off the plot
418
+ return `<svg width="100%" viewBox="0 0 ${W} ${H}">
419
+ <rect x="${P}" y="${midY}" width="${midX-P}" height="${H-P-midY}" style="fill:var(--good);opacity:.05"/>
420
+ <rect x="${midX}" y="${midY}" width="${W-P-midX}" height="${H-P-midY}" style="fill:var(--good);opacity:.11"/>
421
+ <rect x="${midX}" y="${P}" width="${W-P-midX}" height="${midY-P}" style="fill:var(--bad);opacity:.07"/>
422
+ <text x="${W-P-4}" y="${H-P-6}" text-anchor="end">quick wins: small and waiting</text>
423
+ <text x="${W-P-4}" y="${P+12}" text-anchor="end">big and old: schedule or ask to split</text>
424
+ <text x="${P+4}" y="${P+12}">big and new</text>
425
+ <line x1="${P}" y1="${H-P}" x2="${W-P}" y2="${H-P}" style="stroke:var(--line)"/><line x1="${P}" y1="${P}" x2="${P}" y2="${H-P}" style="stroke:var(--line)"/>
426
+ <text x="${W/2}" y="${H-8}" text-anchor="middle">age (days, log) →</text><text x="10" y="${H/2}" transform="rotate(-90 10 ${H/2})" text-anchor="middle">lines changed (log) →</text>
427
+ ${pts.map(p => `<circle cx="${x(p.age_days)}" cy="${y(lines(p))}" r="${progress[p.number]?.reviewed?3.5:5.5}" style="fill:${laneColor(p.lane)};stroke:${isExt(p) ? "var(--external)" : "var(--panel)"};stroke-width:${isExt(p) ? 2 : 1}" fill-opacity=".9" data-open="${p.number}" cursor="pointer"><title>#${p.number} ${esc(p.title)} (${lines(p)} ln, ${Math.round(p.age_days)}d, ${esc(kindBadge(p.author_kind))}, CI ${CI[ciState(p)].label})</title></circle>${["failing", "failing-optional"].includes(ciState(p)) ? `<text x="${x(p.age_days) + 6}" y="${y(lines(p)) - 5}" style="fill:var(--bad);font-size:11px;font-weight:700;pointer-events:none">✗</text>` : ""}`).join("")}
428
+ </svg>`;
429
+ }
430
+ function renderPlan(){
431
+ // "CI passing first": within each card, green PRs float up (stable, so priority order is kept otherwise).
432
+ const order = ns => state.greenFirst ? [...ns].sort((a, b) => (ciState(byNum[a]) === "passing" ? 0 : 1) - (ciState(byNum[b]) === "passing" ? 0 : 1)) : ns;
433
+ const sessions = DATA.sessions.map((s, i) => {
434
+ const rows = order(s.prs).map(prRow).join(""); if (!rows) return "";
435
+ const done = s.prs.filter(n => progress[n]?.reviewed && !stale(n)).length;
436
+ return `<div class="card"><h2>Session ${i+1} · ${esc(s.label)} <span>~${s.minutes} min · ${done}/${s.prs.length} done</span></h2>${rows}</div>`;
437
+ }).join("");
438
+ const lane = (l, note) => {
439
+ const ps = DATA.prs.filter(p => p.lane === l && visible(p)); if (!ps.length) return "";
440
+ return `<div class="card"><h2>${LANES[l]} <span>${note}</span></h2>${order(ps.sort((a,b)=>a.age_days-b.age_days).map(p => p.number)).map(prRow).join("")}</div>`;
441
+ };
442
+ $("v-plan").innerHTML = `<div class="grid2"><div>
443
+ <div class="card"><h2>Size vs. age <span>click a dot · orange ring = external author</span></h2>${scatter()}</div>
444
+ ${lane("approved","needs a merge or a final look")}
445
+ ${lane("waiting","changes requested; nothing to do until the author pushes")}
446
+ ${lane("blocked","conflicts or a required check failing; nudge the author")}
447
+ ${lane("mine","your PRs")}
448
+ ${lane("draft","not ready yet")}
449
+ </div><div>
450
+ ${legend("How sessions are packed", `Ready PRs are packed into sessions of about an hour, each in one component so you build context instead of switching it. Requested reviews and re-reviews come first, then quick wins, then the oldest. The menu on each row is your status (to do, understood, reviewed, and so on)${LIVE ? ", saved to the ledger the review sessions also write to" : ""}. New commits reset it. A <span class="sess"></span> means a review session exists; <span class="score">quiz 2/3</span> is your study-log score; <span class="cib passing">✓</span> <span class="cib failing">✗</span> <span class="cib failing-optional">!</span> show CI.`)}
451
+ <p style="margin-top:0"><label><input type="checkbox" id="greenFirst" ${state.greenFirst ? "checked" : ""}> CI passing first</label> <span class="muted">· a red check doesn't block review, but a green one means the PR is less likely to change under you.</span></p>
452
+ ${sessions || `<div class="card">${EMPTY("Nothing ready matches these filters.")}</div>`}
453
+ </div></div>`;
454
+ }
455
+
456
+ // ---- table
457
+ let sortKey = "priority", sortDir = -1;
458
+ function renderTable(){
459
+ const cols = [["number","#"],["title","Title"],["author","Author"],["author_kind","Who"],["lane","Lane"],["ci","CI"],["age_days","Age"],["idle_days","Idle"],["churn","±"],["changed_files","Files"],["primary","Primary"],["flags","Signals"],["minutes","Est"],["priority","Prio"]];
460
+ const numeric = ["number", "age_days", "idle_days", "churn", "changed_files", "minutes", "priority"];
461
+ // CI sorts by urgency, not alphabetically: ascending puts required failures first.
462
+ const val = (p,k) => k === "churn" ? lines(p) : k === "flags" ? p.flags.length + p.smells.length : k === "ci" ? ciRank(p) : p[k];
463
+ const rows = DATA.prs.filter(visible).sort((a,b) => { const x = val(a,sortKey), y = val(b,sortKey); return (x > y ? 1 : x < y ? -1 : 0) * sortDir; });
464
+ $("v-table").innerHTML = `<table><thead><tr>${cols.map(([k,l]) => `<th class="${numeric.includes(k) ? "num" : ""}" data-sort="${k}">${l}${sortKey===k?(sortDir>0?" ▲":" ▼"):""}</th>`).join("")}</tr></thead><tbody>
465
+ ${rows.map(p => `<tr><td class="num"><a href="${safeUrl(p.url)}" target="_blank" rel="noopener">${p.number}</a></td><td style="cursor:pointer" data-open="${p.number}">${esc(p.title)}${sessDot(p)}${scoreBadge(p)}</td><td>@${esc(p.author)}</td><td>${whoBadge(p)}</td>
466
+ <td><span class="pill" style="background:${laneColor(p.lane)}">${LANES[p.lane]}</span></td><td>${ciBadge(p)} <span class="muted">${CI[ciState(p)].label}</span></td><td class="num">${Math.round(p.age_days)}d</td><td class="num">${Math.round(p.idle_days)}d</td>
467
+ <td class="num"><span class="add">+${p.additions}</span> <span class="del">-${p.deletions}</span></td><td class="num">${p.changed_files}</td><td>${esc(comps[p.primary].label)}</td>
468
+ <td>${flagsHtml(p, ["blocker","you","risk","responsibility","convention","author"])}</td><td class="num">${p.minutes}m</td><td class="num">${p.priority}</td></tr>`).join("")}</tbody></table>`;
469
+ }
470
+
471
+ // ---- overlap graph (Cytoscape + fcose): PRs grouped by primary component, edges = shared files
472
+ let cy = null, cySig = "";
473
+ const keepFile = f => !state.srcOnly || !NON_SOURCE.some(r => r.test(f));
474
+ function overlapEdges(){
475
+ const vis = new Set(DATA.prs.filter(visible).map(p => p.number));
476
+ return DATA.overlaps.filter(e => vis.has(e.a) && vis.has(e.b)).map(e => ({...e, files: e.files.filter(keepFile)})).filter(e => e.files.length);
477
+ }
478
+ function renderOverlap(){
479
+ const edges = overlapEdges();
480
+ const connected = new Set(edges.flatMap(e => [e.a, e.b]));
481
+ const prs = DATA.prs.filter(visible).filter(p => !state.overlapOnly || connected.has(p.number));
482
+ const sig = JSON.stringify([DATA.generated, prs.map(p => p.number + p.lane), edges.length, state.srcOnly, state.overlapOnly]);
483
+ const view = $("v-overlap");
484
+ if (!view.querySelector("#cy")) {
485
+ view.innerHTML = `<div class="toolbar">
486
+ <label><input type="checkbox" id="srcOnly" ${state.srcOnly?"checked":""}> source files only</label>
487
+ <label><input type="checkbox" id="overlapOnly" ${state.overlapOnly?"checked":""}> only PRs that share files</label>
488
+ <button class="btn small" id="fit">fit</button>
489
+ <span>Edges join PRs that change the same files (thicker = more files). Boxes group PRs by their main component. Drag, scroll to zoom, hover for details.</span></div>
490
+ <div id="cy"></div><div class="card" style="margin-top:14px" id="hot"></div>`;
491
+ cySig = "";
492
+ }
493
+ renderHotFiles();
494
+ if (sig === cySig && cy) { cy.resize(); return; }
495
+ cySig = sig;
496
+ const groups = [...new Set(prs.map(p => p.primary))];
497
+ const elements = [
498
+ ...groups.map(g => ({data: {id: "c:" + g, label: comps[g].label, layer: comps[g].layer}, classes: "group"})),
499
+ ...prs.map(p => ({data: {id: "p:" + p.number, parent: "c:" + p.primary, label: String(p.number), pr: p.number, lane: p.lane, kind: p.author_kind, ext: isExt(p), first: isFirst(p), size: 34 + Math.min(30, Math.sqrt(lines(p)) * 1.2)}, classes: "pr"})),
500
+ ...edges.filter(e => prs.some(p => p.number === e.a) && prs.some(p => p.number === e.b))
501
+ .map(e => ({data: {id: `e:${e.a}-${e.b}`, source: "p:" + e.a, target: "p:" + e.b, weight: e.files.length, files: e.files}})),
502
+ ];
503
+ if (cy) cy.destroy();
504
+ cy = cytoscape({container: $("cy"), elements, wheelSensitivity: 0.3, minZoom: 0.2, maxZoom: 3});
505
+ styleGraph();
506
+ cy.layout({name: "fcose", quality: "proof", animate: false, randomize: true, nodeRepulsion: 22000, idealEdgeLength: e => 140 / Math.sqrt(e.data("weight")), edgeElasticity: 0.2, nodeSeparation: 90, nestingFactor: 0.5, gravity: 0.15, gravityRangeCompound: 1.6, packComponents: true, tilingPaddingVertical: 18, tilingPaddingHorizontal: 18, padding: 20}).run();
507
+ const tip = $("tip");
508
+ const showTip = (evt, html) => { tip.innerHTML = html; tip.style.display = "block"; const r = evt.originalEvent; tip.style.left = (r.clientX + 14) + "px"; tip.style.top = (r.clientY + 12) + "px"; };
509
+ cy.on("mouseover", "node.pr", evt => {
510
+ const p = byNum[evt.target.data("pr")];
511
+ cy.elements().addClass("faded"); evt.target.closedNeighborhood().removeClass("faded"); evt.target.ancestors().removeClass("faded");
512
+ showTip(evt, `<b>#${p.number}</b> ${esc(p.title)}<br><span class="muted">@${esc(p.author)} (${esc(kindBadge(p.author_kind))}) · ${LANES[p.lane]} · +${p.additions}/-${p.deletions}</span>`);
513
+ });
514
+ cy.on("mouseover", "edge", evt => {
515
+ const f = evt.target.data("files");
516
+ showTip(evt, `<b>#${evt.target.source().data("pr")} ↔ #${evt.target.target().data("pr")}</b>: ${f.length} shared file${f.length > 1 ? "s" : ""}<br><span class="mono">${f.slice(0, 10).map(esc).join("<br>")}</span>${f.length > 10 ? "<br>…" : ""}`);
517
+ });
518
+ cy.on("mousemove", evt => { if (tip.style.display === "block") { tip.style.left = (evt.originalEvent.clientX + 14) + "px"; tip.style.top = (evt.originalEvent.clientY + 12) + "px"; } });
519
+ cy.on("mouseout", "node.pr, edge", () => { tip.style.display = "none"; cy.elements().removeClass("faded"); });
520
+ cy.on("tap", "node.pr", evt => openDrawer(evt.target.data("pr")));
521
+ }
522
+ function styleGraph(){
523
+ const c = n => css(n);
524
+ cy.style([
525
+ {selector: "node.group", style: {"label": "data(label)", "text-valign": "top", "text-halign": "center", "font-size": 13, "font-weight": 600, "color": c("--mut"), "background-color": c("--subtle"), "background-opacity": 0.6, "border-width": 1, "border-color": c("--line"), "shape": "round-rectangle", "padding": 14, "text-margin-y": -4}},
526
+ {selector: "node.pr", style: {"label": "data(label)", "width": "data(size)", "height": "data(size)", "font-size": 12, "font-weight": 700, "text-valign": "center", "color": c("--chip-fg"), "border-width": 2, "border-color": c("--panel"), "text-outline-width": 0}},
527
+ ...Object.keys(LANES).map(l => ({selector: `node.pr[lane = "${l}"]`, style: {"background-color": c("--" + l)}})),
528
+ {selector: 'node.pr[?ext]', style: {"border-color": c("--external"), "border-width": 3}},
529
+ {selector: 'node.pr[?first]', style: {"border-style": "dashed"}},
530
+ {selector: "edge", style: {"width": e => Math.min(10, 0.8 + e.data("weight") * 1.3), "line-color": c("--line-strong"), "opacity": e => Math.min(0.85, 0.25 + e.data("weight") * 0.15), "curve-style": "haystack"}},
531
+ {selector: ".faded", style: {"opacity": 0.12}},
532
+ ]);
533
+ }
534
+ function renderHotFiles(){
535
+ const touch = {};
536
+ DATA.prs.filter(visible).forEach(p => p.files.forEach(f => { if (keepFile(f.path)) (touch[f.path] ||= []).push(p.number); }));
537
+ const hot = Object.entries(touch).filter(([, ns]) => ns.length >= 3).sort((a,b) => b[1].length - a[1].length).slice(0, 15);
538
+ $("hot").innerHTML = `<h2>Hot files <span>touched by 3+ open PRs: whichever merges first forces rebases on the others</span></h2>` +
539
+ (hot.map(([f, ns]) => `<div class="row" style="grid-template-columns:1fr auto"><code>${esc(f)}</code><span class="chips">${ns.map(n => chip(byNum[n])).join("")}</span></div>`).join("") || '<span class="muted">none</span>');
540
+ }
541
+
542
+ // ---- PR panel
543
+ const briefs = {};
544
+ const drawerBody = () => document.querySelector("#drawer .dbody");
545
+ function openDrawer(n, tab){
546
+ if (!byNum[n]) return closeDrawer();
547
+ const changed = state.sel !== n;
548
+ state.sel = n;
549
+ if (tab) state.dtab = tab;
550
+ document.body.classList.add("drawer-open");
551
+ renderDrawer({resetScroll: changed});
552
+ if (cy) setTimeout(() => cy.resize(), 0);
553
+ }
554
+ function closeDrawer(){
555
+ document.body.classList.remove("drawer-open"); state.sel = null;
556
+ sessionStorage.removeItem(STORE + ":panel");
557
+ if (cy) setTimeout(() => cy.resize(), 0);
558
+ }
559
+ // Whether the drawer body is scrolled to (or near) its end, so new study entries keep it there, like any chat.
560
+ const nearEnd = el => !!el && el.scrollHeight - el.scrollTop - el.clientHeight < 80;
561
+ function renderDrawer({resetScroll = false, follow = false} = {}){
562
+ const n = state.sel, p = byNum[n];
563
+ if (!p) return closeDrawer();
564
+ sessionStorage.setItem(STORE + ":panel", JSON.stringify({sel: n, dtab: state.dtab}));
565
+ const body = drawerBody();
566
+ const toEnd = state.dtab === "study" && (resetScroll || follow || nearEnd(body));
567
+ const scroll = resetScroll || !body ? 0 : body.scrollTop;
568
+ const active = document.activeElement?.dataset?.draft;
569
+ const caret = active ? document.activeElement.selectionStart : null;
570
+ const activeStatus = document.activeElement?.dataset?.setStatus === String(n) ? document.activeElement.value : null;
571
+ const menu = body?.querySelector(".action-menu"), menuOpen = menu?.open;
572
+ const menuFocus = menu?.contains(document.activeElement) ? [...menu.querySelectorAll("summary,button")].indexOf(document.activeElement) : -1;
573
+ const tabs = [["overview", "Overview"], ["study", "Study"], ["brief", "Brief"]];
574
+ $("dinner").innerHTML = `<div class="dhead"><span class="close" id="close" title="Close (Esc)">✕</span>
575
+ <div><span class="pill" style="background:${laneColor(p.lane)}">${LANES[p.lane]}</span> ${p.labels.map(l => `<span class="flag">${esc(l)}</span>`).join("")}</div>
576
+ <h2><a href="${safeUrl(p.url)}" target="_blank" rel="noopener">#${p.number}</a> ${esc(p.title)}</h2>
577
+ <div class="kv"><span>by <b>@${esc(p.author)}</b>${whoBadge(p)}</span><span>opened <b>${Math.round(p.age_days)}d</b> ago</span><span>idle <b>${Math.round(p.idle_days)}d</b></span>
578
+ <span><b class="add">+${p.additions}</b> <b class="del">-${p.deletions}</b> in <b>${p.changed_files}</b> files</span><span>CI <b>${CI[ciState(p)].label}</b></span><span>review <b>${p.review_decision}</b></span><span>est <b>${p.minutes} min</b></span></div>
579
+ <div class="dtabs">${tabs.map(([k, l]) => `<span class="dtab ${state.dtab === k ? "on" : ""}" data-dtab="${k}">${l}${k === "study" && p.study?.assessed ? ` <span class="score">${p.study.correct}/${p.study.assessed}</span>` : ""}</span>`).join("")}</div>
580
+ </div><div class="dbody">${state.dtab === "study" ? studyTab(n) : state.dtab === "brief" ? briefTab(n) : overviewTab(n)}</div>`;
581
+ document.querySelectorAll("#drawer [data-draft]").forEach(el => { el.value = state.drafts[`${n}:${el.dataset.draft}`] || ""; });
582
+ if (active) { const el = document.querySelector(`#drawer [data-draft="${CSS.escape(active)}"]`); if (el) { el.focus(); if (caret != null) el.setSelectionRange(caret, caret); } }
583
+ if (activeStatus !== null) document.querySelector(`#drawer [data-set-status="${n}"][value="${CSS.escape(activeStatus)}"]`)?.focus({preventScroll: true});
584
+ const fresh = drawerBody();
585
+ const freshMenu = fresh.querySelector(".action-menu");
586
+ if (freshMenu && !resetScroll) {
587
+ freshMenu.open = !!menuOpen;
588
+ if (menuFocus >= 0) freshMenu.querySelectorAll("summary,button")[menuFocus]?.focus({preventScroll: true});
589
+ }
590
+ fresh.scrollTop = toEnd ? fresh.scrollHeight : scroll;
591
+ }
592
+ function ciSection(p){
593
+ const c = p.ci_checks; if (!c) return "";
594
+ const rows = c.failing.map(f => `<div>${safeUrl(f.url) ? `<a href="${safeUrl(f.url)}" target="_blank" rel="noopener">${esc(f.name)}</a>` : esc(f.name)}
595
+ ${f.required ? '<span class="flag blocker">required</span>' : '<span class="flag">optional</span>'}${f.on_main ? '<span class="flag" title="This check fails on the default branch too">also failing on main</span>' : ""}</div>`).join("");
596
+ const summary = `${c.passed} passed · ${c.failing.length} failing · ${c.pending} pending${c.cancelled ? ` · ${c.cancelled} cancelled` : ""}` +
597
+ (c.required_missing.length ? ` · ${c.required_missing.length} required not reported` : "") + (c.required_known ? "" : " · required checks unknown");
598
+ return `<h4>CI ${ciBadge(p)}</h4><div class="hint" style="margin-top:0">${CI[ciState(p)].label}: ${summary}</div>${rows ? `<div class="checks">${rows}</div>` : ""}`;
599
+ }
600
+ function overviewTab(n){
601
+ const p = byNum[n], g = progress[n] || {};
602
+ const compRows = Object.entries(p.by_comp).sort((a,b) => b[1]-a[1]).map(([c, l]) => {
603
+ const k = comps[c]; const contract = k.contract?.does_not_own || (k.contract?.responsibility ? "Responsibility: " + k.contract.responsibility : "");
604
+ return `<div><b>${esc(k.label)}</b> <span class="muted">(${esc(k.layer)}, ${l} lines)</span>${contract ? `<div class="contract">${esc(contract.replace(/\*\*/g, ""))}</div>` : ""}</div>`;
605
+ }).join("");
606
+ const files = [...p.files].sort((a,b) => (b.add+b.del)-(a.add+a.del)).map(f => `<div><span class="mono" title="${esc(comps[f.comp].label)}">${esc(f.path)}</span><span class="mono"><span class="add">+${f.add}</span> <span class="del">-${f.del}</span></span></div>`).join("");
607
+ const smells = p.smells.map(s => `<div class="smell"><span class="flag ${s.kind}" title="${esc(ruleTip(s.id))}">${ruleIcon(s.id)}${s.kind}</span> <a href="${safeUrl(p.url + (FORGE.files_tab || "/files"))}" target="_blank" rel="noopener">${esc(s.path)}:${s.line}</a>: ${esc(s.msg)}<code>${esc(s.code)}</code></div>`).join("");
608
+ const threads = p.unresolved.map(t => `<div class="smell"><b>@${esc(t.author)}</b> on <span class="muted mono">${esc(t.path)}:${t.line ?? "?"}${t.outdated ? " (outdated)" : ""}</span><div class="md desc" style="max-height:220px;margin-top:4px">${t.body_html ? safeHtml(t.body_html) : md(t.body)}</div></div>`).join("");
609
+ const related = (p.related || []).map(r => byNum[r] ? chip(byNum[r]) : "").join("");
610
+ const rules = p.rules.map(r => { const ins = DATA.instructions.find(i => i.name === r); return `<a href="${safeUrl(ins?.url)}" target="_blank" rel="noopener">${esc(r)}</a>`; }).join(" · ");
611
+ const s = p.session;
612
+ return `<div class="actions review-actions">
613
+ ${reviewButton(n, "btn primary").replace(/>(review|resume)</, (m, w) => `>${w === "resume" ? "Resume" : "Start"} deep review<`)}
614
+ ${LIVE ? `<button class="btn" data-dtab="study" title="Predict, get quizzed, teach back; everything goes in this PR's study log">Study</button>` : ""}
615
+ <a class="btn" href="${esc(vscodeUrl(n))}" title="${byNum[n].sessions?.some(s => s.editor_url) ? "Open this PR's latest agent session in VS Code" : "Open a VS Code agent session with the prompt filled in; it'll be linked to this PR"}">Open in VS Code</a>
616
+ <details class="action-menu"><summary class="btn icon" aria-label="More review actions" title="More review actions"><span aria-hidden="true">&#8943;</span></summary>
617
+ <div class="action-items"><button data-deep="${n}">Copy prompt</button>
618
+ <button data-copy="readthrough worktree ${n}">Copy worktree cmd</button></div></details></div>
619
+ ${sessionList(n)}
620
+ <h4>Your status</h4>${statusPills(n)}
621
+ <h4>Signals</h4>${p.flags.map(f => `<span class="flag ${f.kind}" title="${esc(f.id + ": " + ruleTip(f.id))}">${ruleIcon(f.id)}${esc(f.msg)}</span>`).join(" ") || '<span class="muted">none</span>'}
622
+ ${ciSection(p)}
623
+ ${smells ? `<h4>Line heuristics (verify, not verdicts)</h4>${smells}` : ""}
624
+ <h4>Description</h4><div class="md desc">${p.body_html ? safeHtml(p.body_html) : md(p.body || "_No description._")}</div>
625
+ <h4>Architecture contracts touched</h4>${compRows}
626
+ <h4>Rules that apply</h4>${rules || '<span class="muted">none</span>'}
627
+ <h4>Related open PRs (shared files)</h4><div class="chips">${related || '<span class="muted">none; it can be reviewed on its own</span>'}</div>
628
+ ${threads ? `<h4>Unresolved threads (${p.unresolved.length})</h4>${threads}` : ""}
629
+ <h4>Files</h4><div class="files">${files}</div>
630
+ ${howItWorks()}`;
631
+ }
632
+ const profileLine = () => {
633
+ const pr = PROFILE, when = pr.onboarded ? new Date(pr.onboarded).toLocaleDateString() : null;
634
+ const drafted = pr.drafted_by === "model" ? ", first drafted by a model (the profile's header says which)" : pr.drafted_by === "readthrough" ? ", first drafted by readthrough from the file tree" : "";
635
+ return `The map comes from ${esc(pr.origin || "the repo's profile")}${drafted}${when ? `, accepted on ${when}` : ""}.`;
636
+ };
637
+ function howItWorks(){
638
+ return `<div class="how"><p>${icon("cog", "ico sm")}<b>Worked out by rules.</b> Lanes, CI, and review state come from ${esc(FORGE.label)}. Components come from the profile's path patterns, signals and line heuristics from its rules (hover one to see which), and the contracts are ${PROFILE.contracts_source ? `quoted from <code>${esc(PROFILE.contracts_source)}</code> in the repo` : "written in the profile"}. The plan, estimates, and related PRs are arithmetic. ${profileLine()}</p>
639
+ <p>${icon("sparkles", "ico sm")}<b>Written by a model:</b> only what's in the Study tab (each entry names the model), what review agents write in their sessions, and the profile itself if a model drafted it.</p></div>`;
640
+ }
641
+ function briefTab(n){
642
+ if (!LIVE) return `<p class="muted" style="margin-top:14px">The rendered brief is part of the live dashboard (<code>readthrough serve</code>). The file is at <code>${esc(LINKS.briefs_dir)}\\pr-${n}.md</code>. <button class="btn small" data-copy="${esc(LINKS.briefs_dir + "\\pr-" + n + ".md")}">copy path</button></p>`;
643
+ if (briefs[n] === undefined) {
644
+ briefs[n] = null;
645
+ api(`/api/brief/${n}`, null, "GET").then(r => { briefs[n] = r.markdown; if (state.sel === n && state.dtab === "brief") renderDrawer(); })
646
+ .catch(err => { briefs[n] = `_Couldn't load the brief: ${err.message}_`; renderDrawer(); });
647
+ }
648
+ return briefs[n] === null ? `<p class="muted">Loading…</p>` : `<div class="md" style="margin-top:12px">${mdModel(briefs[n])}</div>`;
649
+ }
650
+
651
+ // ---- panel resizing
652
+ (function setupGrip(){
653
+ const root = document.documentElement, grip = $("grip");
654
+ const clamp = w => Math.max(380, Math.min(w, Math.min(1400, innerWidth * 0.9)));
655
+ const setW = w => root.style.setProperty("--drawer-w", clamp(w) + "px");
656
+ setW(+localStorage.getItem("readthrough:drawer-w") || 560);
657
+ grip.addEventListener("pointerdown", e => {
658
+ grip.setPointerCapture(e.pointerId); grip.classList.add("on");
659
+ const move = ev => setW(innerWidth - ev.clientX);
660
+ const up = () => {
661
+ grip.classList.remove("on"); grip.removeEventListener("pointermove", move); grip.removeEventListener("pointerup", up);
662
+ localStorage.setItem("readthrough:drawer-w", parseInt(getComputedStyle(root).getPropertyValue("--drawer-w")));
663
+ if (cy) cy.resize();
664
+ };
665
+ grip.addEventListener("pointermove", move); grip.addEventListener("pointerup", up);
666
+ });
667
+ grip.addEventListener("dblclick", () => { setW(560); localStorage.removeItem("readthrough:drawer-w"); if (cy) cy.resize(); });
668
+ })();
669
+
670
+ // ---- study tab: predictions, Socratic quiz, teach-back, evidence. All of it appends to the study log.
671
+ function loadStudy(n){
672
+ if (!LIVE || study[n]?.loading) return;
673
+ study[n] = {...(study[n] || {}), loading: true};
674
+ api(`/api/study/${n}`, null, "GET").then(r => {
675
+ // The server says whether a turn is running. A reply bubble kept from before the fetch is only kept when it
676
+ // is: a `done` missed during a reconnect would otherwise leave the composer disabled for good.
677
+ study[n] = {...r, pending: r.engine.busy ? (study[n]?.pending || {text: "", tools: []}) : null};
678
+ if (byNum[n]) byNum[n].study = r.summary;
679
+ if (state.sel === n && state.dtab === "study") renderDrawer();
680
+ }).catch(err => { study[n] = {error: err.message}; renderDrawer(); });
681
+ }
682
+ // The composer's mode follows the log: predict first (or skip), answer an open question, otherwise talk.
683
+ function studyMode(entries){
684
+ const answered = new Set(entries.filter(e => e.kind === "answer").map(e => e.qid));
685
+ const openQ = [...entries].reverse().find(e => e.kind === "question" && !answered.has(e.qid));
686
+ if (openQ) return {mode: "answer", q: openQ};
687
+ if (!entries.some(e => e.kind === "prediction")) return {mode: "predict"};
688
+ return {mode: "chat"};
689
+ }
690
+ function watchList(p){
691
+ const items = [];
692
+ p.flags.filter(f => f.kind !== "info").forEach(f => items.push(`${ruleIcon(f.id)}${esc(f.msg)}`));
693
+ const smells = {}; p.smells.forEach(sm => (smells[sm.id] ||= []).push(sm));
694
+ Object.values(smells).forEach(list => items.push(`${ruleIcon(list[0].id)}${esc(list[0].msg)}: ${list.slice(0, 3).map(sm => `<code>${esc(sm.path.split("/").pop())}:${sm.line}</code>`).join(", ")}${list.length > 3 ? ` and ${list.length - 3} more` : ""}`));
695
+ const prim = comps[p.primary]?.contract?.does_not_own;
696
+ if (prim) items.push(`${icon("cog", "ico sm")}${esc(comps[p.primary].label)} doesn't own: ${esc(prim.replace(/\*\*/g, "").slice(0, 220))}`);
697
+ const big = [...p.files].sort((a, b) => (b.add + b.del) - (a.add + a.del)).slice(0, 3);
698
+ items.push(`${icon("cog", "ico sm")}Most changed: ${big.map(f => `<code>${esc(f.path.split("/").pop())}</code> (+${f.add}/-${f.del})`).join(", ")}`);
699
+ if (p.related?.length) items.push(`${icon("cog", "ico sm")}Shares files with ${p.related.slice(0, 5).map(r => `#${r}`).join(", ")}`);
700
+ return `<details class="watch"><summary>${icon("target", "ico sm")}What to look at <span class="muted">(worked out by rules, no model)</span></summary><ul>${items.map(i => `<li>${i}</li>`).join("")}</ul></details>`;
701
+ }
702
+ // Who wrote an entry, as precisely as the log knows: the model named on it, else the runtime that carried it,
703
+ // else the kind of author. Never the current configuration: switching runtimes must not relabel old entries.
704
+ const author = e => e.by === "you" ? "You" : e.by === "rules" ? `${icon("cog", "ico sm")}rules` : `${icon("sparkles", "ico sm")}${esc(e.model || e.runtime || "model")}`;
705
+ // What will answer next, from the engine: the configured model if the runtime names one, else the runtime.
706
+ const engineLabel = eng => eng.name === "rules" ? `${icon("cog", "ico sm")}rules` : `${icon("sparkles", "ico sm")}${esc(eng.model || eng.runtime || "model")}`;
707
+ function studyTab(n){
708
+ if (!LIVE) return `<p class="muted" style="margin-top:14px">Studying needs the live dashboard: run <code>readthrough serve</code> (or <code>readthrough install server</code>). In a terminal, <code>readthrough study ${n}</code> shows the evidence collected so far.</p>`;
709
+ const st = study[n];
710
+ if (!st || st.loading && !st.entries) { loadStudy(n); return `<p class="muted">Loading…</p>`; }
711
+ if (st.error) return `<p class="muted">Couldn't load the study log: ${esc(st.error)}</p>`;
712
+ const s = st.summary, entries = st.entries, busy = st.engine.busy || !!st.pending, ai = st.engine.available;
713
+ const p = byNum[n], dis = busy || !ai ? "disabled" : "";
714
+ const answers = {}, assessments = {}, pinned = new Set();
715
+ entries.forEach(e => { if (e.kind === "answer") answers[e.qid] = e; if (e.kind === "assessment") assessments[e.qid] = e; if (e.kind === "note" && e.pinned) pinned.add(e.pinned); });
716
+ const {mode, q: openQ} = studyMode(entries);
717
+ const pin = e => pinned.has(e.id) ? `<span class="pin on" title="Kept in the brief">${icon("pin", "ico sm")}pinned</span>`
718
+ : `<button class="pin" data-pin="${esc(e.id)}" title="Keep this in the brief's study log">${icon("pin", "ico sm")}pin</button>`;
719
+ const who = author;
720
+ const qcard = q => { const a = answers[q.qid], v = assessments[q.qid];
721
+ return `<div class="qcard ${q === openQ ? "open" : ""}"><div class="qhead"><b>${esc(q.qid)}</b><span>${esc(q.focus || "")}</span>${v ? `<span class="verdict ${esc(v.verdict)}">${esc(v.verdict)}</span>` : q === openQ ? `<span class="tag">answer below</span>` : ""}</div>
722
+ <div class="md">${mdModel(q.question)}</div>
723
+ ${a ? `<div class="answer md">${mdModel(a.text)}</div>` : ""}
724
+ ${v ? `<div class="md">${mdModel(v.feedback)}</div>${v.evidence?.length ? `<div class="hint">Evidence: ${v.evidence.map(x => `<code>${esc(x)}</code>`).join(" ")}</div>` : ""}` : ""}
725
+ ${a && q.expected_points?.length ? `<details class="hint"><summary>What a good answer covers</summary><ul>${q.expected_points.map(x => `<li>${esc(x)}</li>`).join("")}</ul></details>` : ""}</div>`; };
726
+ const timeline = entries.map(e => {
727
+ switch (e.kind) {
728
+ case "prediction": return e.skipped ? `<div class="event">You skipped the prediction.</div>`
729
+ : `<div class="bubble you"><div class="who-line">You <span class="tag">prediction</span></div><div class="md">${mdModel(e.text)}</div></div>`;
730
+ case "chat":
731
+ if (e.action === "brief") return `<div class="event">${icon("lightbulb", "ico sm")}You asked for a briefing.</div>`;
732
+ return `<div class="bubble ${esc(e.by)}"><div class="who-line">${who(e)} ${pin(e)}</div><div class="md">${mdModel(e.text)}</div></div>`;
733
+ case "question": return qcard(e);
734
+ case "teachback": return `<div class="bubble you"><div class="who-line">You <span class="tag">teach-back</span></div><div class="md">${mdModel(e.text)}</div></div>`;
735
+ case "reflection": return `<div class="bubble you"><div class="who-line">You <span class="tag">what I missed${e.qid ? ` on ${esc(e.qid)}` : ""}</span></div><div class="md">${mdModel(e.text)}</div></div>`;
736
+ case "teachback_assessment": return `<div class="qcard"><div class="qhead"><b>Teach-back</b><span class="verdict ${esc(e.verdict)}">${esc(e.verdict)}</span></div><div class="md">${mdModel(e.feedback)}</div>${e.gaps?.length ? `<ul>${e.gaps.map(g => `<li>${esc(g)}</li>`).join("")}</ul>` : ""}<div class="who-line">${pin({...e, text: e.feedback})}</div></div>`;
737
+ case "note": return `<div class="event">${icon("pin", "ico sm")}${e.pinned ? "Pinned" : e.by === "you" ? "Note" : `${esc(e.model || e.runtime || e.by)} added to the brief`}: <span class="md">${mdModel(e.text.length > 160 ? e.text.slice(0, 160) + "…" : e.text)}</span></div>`;
738
+ // A failure is named by the runtime, never a model: a model that never answered reached nothing.
739
+ case "failure": return `<div class="event warn">${icon("triangle-alert", "ico sm")}${esc(e.runtime ? `The ${e.runtime} runtime` : e.assistant === "rules" ? "The rules assistant" : "The assistant")} didn't answer: <code>${esc(e.text.length > 200 ? e.text.slice(0, 200) + "…" : e.text)}</code></div>`;
740
+ case "finding": return `<div class="event"><span class="flag ${e.severity === "blocker" ? "blocker" : "risk"}">${esc(e.severity)}</span> ${e.path ? `<code>${esc(e.path)}:${esc(e.line ?? "?")}</code> ` : ""}${esc(e.summary)} <span class="muted">(${esc(e.by)})</span></div>`;
741
+ default: return "";
742
+ }
743
+ }).join("");
744
+ const pending = st.pending ? `<div class="bubble model" id="pending"><div class="who-line">${engineLabel(st.engine)}</div><div class="md typing" id="pending-text">${mdModel(st.pending.text || "")}</div><div class="tools" id="pending-tools">${pendingTools(st.pending)}</div></div>` : "";
745
+ const step = (label, done, detail) => `<span class="step ${done ? "done" : ""}">${icon(done ? "circle-check" : "circle", "ico sm")}${label}${detail ? ` <span class="muted">${detail}</span>` : ""}</span>`;
746
+ const stepper = `<div class="stepper">${step("Predict", s.predictions || s.prediction_skipped, s.prediction_skipped && !s.predictions ? "skipped" : "")}<span class="line"></span>
747
+ ${step("Quiz", s.assessed, s.assessed ? `${s.correct}/${s.assessed} correct` : "")}<span class="line"></span>${step("Teach back", s.teachback, s.teachback || "")}</div>`;
748
+
749
+ const draft = mode === "answer" ? `answer:${openQ.qid}` : mode === "predict" ? "prediction" : "chat";
750
+ const placeholder = {predict: "Before reading the diff: which components will it touch, what's the riskiest part, and what test would you want to see?",
751
+ answer: `Your answer to ${openQ?.qid}. Think it through; it's fine to be wrong.`, chat: "Ask about the change, argue a point, or write your teach-back…"}[mode];
752
+ // The last verdict that wasn't "correct" is what a "what I missed" note is about; a teach-back's has no qid.
753
+ const missed = [...entries].reverse().find(e => (e.kind === "assessment" || e.kind === "teachback_assessment") && e.verdict !== "correct");
754
+ const reflect = missed ? `<button class="btn" data-study-add="reflection" data-qid="${esc(missed.qid || "")}" title="Save what's in the box as what you missed${missed.qid ? ` on ${esc(missed.qid)}` : ""}, in your own words. It goes in the brief.">What I missed</button>` : "";
755
+ const buttons = {
756
+ predict: `<button class="btn primary" data-study-add="prediction">Save prediction</button><button class="btn" data-skip-predict title="Go straight to the quiz or a briefing. The log notes that you skipped.">Skip</button>`,
757
+ answer: `<button class="btn primary" data-ask="answer" data-qid="${esc(openQ?.qid)}" ${dis}>Submit answer</button><button class="btn" data-ask="hint" data-qid="${esc(openQ?.qid)}" ${dis}>${icon("lightbulb", "ico sm")}Hint</button>`,
758
+ chat: `<button class="btn primary" data-ask="chat" ${dis} title="Send what's in the box">Send</button><button class="btn" data-ask="quiz" ${dis} title="One question at a time; you answer here and it's graded against the diff">${icon("graduation-cap", "ico sm")}${entries.some(e => e.kind === "question") ? "Next question" : "Quiz me"}</button><button class="btn" data-ask="brief" ${dis} title="A short summary and what to watch for. The log notes that you asked.">${icon("lightbulb", "ico sm")}Brief me</button><button class="btn" data-ask="teachback" ${dis} title="What's in the box is graded as your summary of the whole PR">Teach back</button>${reflect}`,
759
+ }[mode];
760
+ // What answers here, from the engine and never from an old entry: the model if the runtime names one up front,
761
+ // else the runtime (GitHub Copilot picks its model per call; each reply then names it).
762
+ const engineNote = ai ? (st.engine.name === "rules"
763
+ ? `Questions come from the repo's profile, not a model; nothing here is graded.`
764
+ : `Questions and grades come from <b title="${esc(st.engine.describe || "")}">${esc(st.engine.model || `the ${st.engine.runtime} runtime`)}</b>; each reply names the model that wrote it.`) : "";
765
+ return `${stepper}
766
+ ${ai ? "" : `<div class="banner warn">${esc(st.engine.reason)}</div>`}
767
+ ${mode === "predict" ? "" : watchList(p)}
768
+ <div class="transcript">${timeline || `<p class="hint">Write your prediction first: it's the cheapest way to find out what you don't know. Then ask for a question, or for a briefing.</p>`}${pending}</div>
769
+ <p class="hint">Everything here is appended to this PR's study log, which the brief and the terminal deep review read. ${engineNote} ${icon("sparkles", "ico sm")}marks what a model wrote; it can read the PR's code but can't change anything.</p>
770
+ <div class="composer">
771
+ <textarea data-draft="${esc(draft)}" placeholder="${esc(placeholder)}"></textarea>
772
+ <div class="actions">${buttons}<span class="hint">Ctrl+Enter ${mode === "predict" ? "saves" : mode === "answer" ? "submits" : "sends"}</span></div>
773
+ </div>`;
774
+ }
775
+ const pendingTools = pend => pend.tools.length ? "used " + [...new Set(pend.tools)].map(t => `<code>${esc(t)}</code>`).join(", ") : (pend.text ? "" : "thinking…");
776
+ async function studyPost(n, body){
777
+ try { await api(`/api/study/${n}`, body); loadStudy(n); } catch (err) { toast(err.message); }
778
+ }
779
+ async function studyAdd(n, kind, qid){
780
+ // A reflection is written in the chat box; the other kinds each have a box of their own.
781
+ const key = `${n}:${kind === "reflection" ? "chat" : kind}`, text = (state.drafts[key] || "").trim();
782
+ if (!text) return toast("Write something first");
783
+ try { await api(`/api/study/${n}`, {kind, text, ...(qid ? {qid} : {})}); state.drafts[key] = ""; saveDrafts(); renderDrawer({follow: true}); }
784
+ catch (err) { toast(err.message); }
785
+ }
786
+ async function studyAsk(n, action, qid){
787
+ const key = action === "answer" ? `${n}:answer:${qid}` : `${n}:chat`;
788
+ const text = ["chat", "answer", "teachback"].includes(action) ? (state.drafts[key] || "").trim() : "";
789
+ if (["chat", "answer", "teachback"].includes(action) && !text) return toast("Write something first");
790
+ try {
791
+ await api(`/api/study/${n}/ask`, {action, text, qid});
792
+ if (text) { state.drafts[key] = ""; saveDrafts(); }
793
+ study[n].pending = {text: "", tools: []};
794
+ renderDrawer({follow: true});
795
+ } catch (err) { toast(err.message); }
796
+ }
797
+ function onStudyEvent(ev){
798
+ const n = ev.pr, st = study[n];
799
+ if (ev.summary && byNum[n]) byNum[n].study = ev.summary;
800
+ if (!st || !st.entries) { if (ev.type === "entry" || ev.type === "reload") render(); return; }
801
+ const here = state.sel === n && state.dtab === "study";
802
+ if (ev.type === "start") { st.pending ||= {text: "", tools: []}; st.engine.busy = true; }
803
+ else if (ev.type === "delta") {
804
+ st.pending ||= {text: "", tools: []}; st.pending.text += ev.text;
805
+ const el = $("pending-text");
806
+ if (here && el) {
807
+ const body = drawerBody(), pinned = nearEnd(body);
808
+ el.innerHTML = mdModel(st.pending.text); $("pending-tools").innerHTML = pendingTools(st.pending);
809
+ if (pinned) body.scrollTop = body.scrollHeight;
810
+ return;
811
+ }
812
+ } else if (ev.type === "tool") {
813
+ st.pending ||= {text: "", tools: []}; st.pending.tools.push(ev.name);
814
+ if (here && $("pending-tools")) { $("pending-tools").innerHTML = pendingTools(st.pending); return; }
815
+ } else if (ev.type === "entry") {
816
+ if (!st.entries.some(e => e.id === ev.entry.id)) st.entries.push(ev.entry);
817
+ st.summary = ev.summary;
818
+ if (ev.entry.kind === "chat" && ev.entry.by !== "you") st.pending = null;
819
+ if (ev.entry.kind === "answer") { const q = st.entries.find(e => e.kind === "question" && e.qid === ev.entry.qid); if (q) loadStudy(n); }
820
+ } else if (ev.type === "done" || ev.type === "error") {
821
+ st.pending = null; st.engine.busy = false;
822
+ if (ev.type === "error") toast("Study: " + ev.message);
823
+ } else if (ev.type === "reload") { loadStudy(n); }
824
+ if (here) renderDrawer(); else if (ev.type === "entry") render();
825
+ }
826
+
827
+ // ---- render + events
828
+ function render(){
829
+ header();
830
+ document.querySelectorAll(".view").forEach(v => v.classList.toggle("on", v.id === "v-" + state.tab));
831
+ ({map: renderMap, plan: renderPlan, overlap: renderOverlap, table: renderTable})[state.tab]();
832
+ if (state.sel) renderDrawer();
833
+ }
834
+ document.addEventListener("click", e => {
835
+ const menu = document.querySelector(".action-menu[open]");
836
+ if (menu && (!menu.contains(e.target) || e.target.closest(".action-items button"))) {
837
+ menu.open = false;
838
+ if (menu.contains(e.target)) menu.querySelector("summary").focus();
839
+ }
840
+ const t = e.target.closest("[data-tab],[data-lane],[data-author],[data-ci],[data-clear],[data-open],[data-deep],[data-copy],[data-sort],[data-review],[data-refresh],[data-dtab],[data-ask],[data-study-add],[data-skip-predict],[data-pin],[data-set-status],[data-comp],.chip,#close,#fit,#theme");
841
+ if (!t) return;
842
+ if (t.id === "close") return closeDrawer();
843
+ if (t.id === "theme") { themePref = THEMES[(THEMES.indexOf(themePref) + 1) % THEMES.length]; localStorage.setItem("readthrough:theme", themePref); return applyTheme(); }
844
+ if (t.id === "fit") return cy && cy.fit(undefined, 24);
845
+ if (t.dataset.review) return startReview(+t.dataset.review, t);
846
+ if (t.hasAttribute("data-refresh")) return api("/api/refresh").then(() => toast("Refreshing…")).catch(err => toast(err.message));
847
+ if (t.dataset.dtab) { state.dtab = t.dataset.dtab; return renderDrawer({resetScroll: true}); }
848
+ if (t.dataset.ask) return studyAsk(state.sel, t.dataset.ask, t.dataset.qid);
849
+ if (t.dataset.studyAdd) return studyAdd(state.sel, t.dataset.studyAdd, t.dataset.qid || null);
850
+ if (t.hasAttribute("data-skip-predict")) return studyPost(state.sel, {kind: "prediction", skipped: true});
851
+ if (t.dataset.pin) { const e = study[state.sel]?.entries.find(x => x.id === +t.dataset.pin); if (e) return studyPost(state.sel, {kind: "note", text: e.text || e.feedback, pinned: e.id}); return; }
852
+ if (t.dataset.tab) { state.tab = t.dataset.tab; return render(); }
853
+ if (t.dataset.lane) return pick("lanes", t.dataset.lane, e);
854
+ if (t.dataset.author) return pick("authors", t.dataset.author, e);
855
+ if (t.dataset.ci) return pick("cis", t.dataset.ci, e);
856
+ if (t.hasAttribute("data-clear")) { for (const [g, labels] of Object.entries(GROUPS)) Object.keys(labels).forEach(k => state[g].add(k)); return render(); }
857
+ if (t.dataset.setStatus) return setStatus(+t.dataset.setStatus, t.value);
858
+ if (t.dataset.deep) return copy(deepPrompt(t.dataset.deep), "Prompt copied. Paste it into any agent chat (Copilot, Claude Code, VS Code)");
859
+ if (t.dataset.copy) return copy(t.dataset.copy);
860
+ if (t.dataset.sort) { sortDir = sortKey === t.dataset.sort ? -sortDir : (t.dataset.sort === "ci" ? 1 : -1); sortKey = t.dataset.sort; return render(); }
861
+ if (t.dataset.open || t.dataset.pr) return openDrawer(+(t.dataset.open || t.dataset.pr));
862
+ if (t.dataset.comp) { state.comp = state.comp === t.dataset.comp ? null : t.dataset.comp; return render(); }
863
+ });
864
+ document.addEventListener("input", e => { const d = e.target.dataset?.draft; if (d && state.sel) { state.drafts[`${state.sel}:${d}`] = e.target.value; saveDrafts(); } });
865
+ document.addEventListener("change", e => {
866
+ const t = e.target;
867
+ if (t.id === "repoSwitch") { location.href = t.value === "__setup" ? "/setup" : `/r/${encodeURI(t.value)}/`; return; }
868
+ if (t.id === "srcOnly") { state.srcOnly = t.checked; return render(); }
869
+ if (t.id === "overlapOnly") { state.overlapOnly = t.checked; return render(); }
870
+ if (t.id === "greenFirst") { state.greenFirst = t.checked; localStorage.setItem("readthrough:green-first", t.checked ? "1" : "0"); return render(); }
871
+ if (t.dataset.status) setStatus(+t.dataset.status, t.value);
872
+ });
873
+ document.addEventListener("mouseover", e => {
874
+ const c = e.target.closest(".chip[data-pr]"), map = $("v-map");
875
+ map.classList.toggle("dim", !!c && map.contains(c));
876
+ map.querySelectorAll(".chip.hl").forEach(x => x.classList.remove("hl"));
877
+ if (c && map.contains(c)) map.querySelectorAll(`.chip[data-pr="${c.dataset.pr}"]`).forEach(x => x.classList.add("hl"));
878
+ });
879
+ document.addEventListener("keydown", e => {
880
+ if (e.key === "Escape") {
881
+ const menu = document.querySelector(".action-menu[open]");
882
+ if (menu) { menu.open = false; menu.querySelector("summary").focus(); return; }
883
+ closeDrawer();
884
+ }
885
+ if (e.target.matches(".brick") && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); e.target.click(); return; }
886
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey) && e.target.dataset?.draft && state.sel) {
887
+ const d = e.target.dataset.draft;
888
+ if (d.startsWith("answer:")) studyAsk(state.sel, "answer", d.slice(7));
889
+ else if (d === "chat") studyAsk(state.sel, "chat");
890
+ else studyAdd(state.sel, d);
891
+ }
892
+ });
893
+ $("q").value = state.q;
894
+ $("q").addEventListener("input", e => { state.q = e.target.value; render(); });
895
+ new ResizeObserver(() => document.documentElement.style.setProperty("--hdr", document.querySelector("header").offsetHeight + "px")).observe(document.querySelector("header"));
896
+ addEventListener("resize", renderTabs);
897
+ async function startReview(n, button){
898
+ button.disabled = true;
899
+ try { const r = await api(`/api/review/${n}`, button.dataset.session ? {session: button.dataset.session} : {}); toast(r.resuming ? `Resuming the #${n} session in a new terminal` : `Starting a deep review of #${n} in a new terminal`); }
900
+ catch (err) { toast(err.message); }
901
+ finally { button.disabled = false; }
902
+ }
903
+ // Live mode: the server pushes changes. Re-render in place so tabs, filters, drafts, and the open panel survive.
904
+ // Events are notifications, not state (see contract.py): after any gap the page fetches everything it holds
905
+ // again rather than reasoning about what it missed.
906
+ function connectLive(){
907
+ const es = new EventSource((LIVE.base || "") + "/api/events");
908
+ // A restarted server has a new token; reload so the buttons keep working. Drafts survive in sessionStorage.
909
+ es.addEventListener("hello", e => { if (JSON.parse(e.data).instance !== LIVE.instance) { es.close(); location.reload(); } });
910
+ es.onopen = () => { if (LIVE.disconnected) { LIVE.disconnected = false; resync(); } header(); };
911
+ es.onerror = () => { LIVE.disconnected = true; header(); };
912
+ es.addEventListener("resync", () => resync());
913
+ es.addEventListener("status", e => { LIVE.status = JSON.parse(e.data); header(); });
914
+ es.addEventListener("data", () => reloadData(true));
915
+ es.addEventListener("ledger", e => { DATA.ledger = JSON.parse(e.data); loadProgress(); render(); });
916
+ es.addEventListener("sessions", e => { for (const [n, info] of Object.entries(JSON.parse(e.data))) if (byNum[n]) Object.assign(byNum[n], info); render(); });
917
+ es.addEventListener("study", e => onStudyEvent(JSON.parse(e.data)));
918
+ }
919
+ // Everything the page holds, fetched afresh: the payload, and the study log of every PR it has looked at.
920
+ async function resync(){
921
+ await reloadData();
922
+ for (const n of Object.keys(study).map(Number)) { delete study[n].loading; loadStudy(n); }
923
+ }
924
+ async function reloadData(announce){
925
+ const resp = await fetch((LIVE.base || "") + "/api/data", {cache: "no-store"});
926
+ if (!resp.ok) return;
927
+ const before = new Set(DATA.prs.map(p => p.number));
928
+ setData(await resp.json());
929
+ for (const k of Object.keys(briefs)) delete briefs[k];
930
+ render();
931
+ const added = DATA.prs.filter(p => !before.has(p.number)).length;
932
+ if (announce) toast(added ? `Updated: ${added} new PR${added > 1 ? "s" : ""}` : "Updated");
933
+ }
934
+ applyTheme();
935
+ render();
936
+ { const panel = JSON.parse(sessionStorage.getItem(STORE + ":panel") || "null"); if (panel && byNum[panel.sel]) openDrawer(panel.sel, panel.dtab); }
937
+ if (LIVE) connectLive();