the-high-council 0.6.0

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 (78) hide show
  1. package/.env.example +19 -0
  2. package/CONTRIBUTING.md +41 -0
  3. package/LICENSE +21 -0
  4. package/PERSONAS.md +51 -0
  5. package/README.md +499 -0
  6. package/TROUBLESHOOTING.md +45 -0
  7. package/chains/cheap.json +35 -0
  8. package/chains/gp-judge-v1.json +80 -0
  9. package/chains/idea-open-c2.json +106 -0
  10. package/chains/mock-budget.json +15 -0
  11. package/chains/mock-debate.json +59 -0
  12. package/chains/mock-external.json +59 -0
  13. package/chains/mock-open.json +60 -0
  14. package/chains/mock-proposals.json +57 -0
  15. package/chains/mock-questions-wait.json +63 -0
  16. package/chains/mock-questions.json +63 -0
  17. package/chains/mock-relay.json +42 -0
  18. package/chains/mock-unanimous.json +42 -0
  19. package/chains/mock.json +17 -0
  20. package/chains/plan-auto-mistral.json +101 -0
  21. package/chains/plan-auto.json +131 -0
  22. package/chains/plan-cheap.json +82 -0
  23. package/chains/plan-debate-c2.json +86 -0
  24. package/chains/plan-debate-open-c2.json +98 -0
  25. package/chains/plan-debate-roles-c1.json +149 -0
  26. package/chains/plan-debate.json +116 -0
  27. package/chains/plan-fast.json +66 -0
  28. package/chains/plan-proposals-best-of-5.json +98 -0
  29. package/chains/plan-proposals.json +96 -0
  30. package/chains/plan-relay.json +83 -0
  31. package/chains/plan-thorough.json +82 -0
  32. package/chains/plan-unanimous.json +82 -0
  33. package/chains/seven-cheap.json +67 -0
  34. package/chains/seven.json +60 -0
  35. package/chains/smo-v2-cheap.json +67 -0
  36. package/chains/smo.json +50 -0
  37. package/chains/verify.json +40 -0
  38. package/package.json +55 -0
  39. package/src/board-export.js +77 -0
  40. package/src/budget.js +126 -0
  41. package/src/buys.js +44 -0
  42. package/src/cache-integrity.js +38 -0
  43. package/src/chain-lint.js +107 -0
  44. package/src/chain.js +880 -0
  45. package/src/cli.js +1031 -0
  46. package/src/cost-forecast.js +70 -0
  47. package/src/cost.js +139 -0
  48. package/src/errors.js +82 -0
  49. package/src/http-server.js +349 -0
  50. package/src/integrity.js +48 -0
  51. package/src/key-redaction.js +97 -0
  52. package/src/mcp/server.js +319 -0
  53. package/src/name-lint.js +186 -0
  54. package/src/partial-deliverable.js +38 -0
  55. package/src/peer-claim.js +98 -0
  56. package/src/personas.js +54 -0
  57. package/src/preflight.js +84 -0
  58. package/src/pricing.json +120 -0
  59. package/src/providers.js +268 -0
  60. package/src/replay.js +40 -0
  61. package/src/resume-brief.js +114 -0
  62. package/src/role-diagnostics.js +181 -0
  63. package/src/roles.js +520 -0
  64. package/src/schema-version.js +39 -0
  65. package/src/scope-freeze.js +35 -0
  66. package/src/seat-role.js +96 -0
  67. package/src/shape-rounds.js +58 -0
  68. package/src/spend.js +193 -0
  69. package/src/stage-contract.js +223 -0
  70. package/src/stage-submission.js +53 -0
  71. package/src/tie-break.js +94 -0
  72. package/src/ui/app.js +139 -0
  73. package/src/ui/index.html +43 -0
  74. package/src/ui/parse.js +101 -0
  75. package/src/ui/server.js +117 -0
  76. package/src/ui/style.css +37 -0
  77. package/src/verdict-stats.js +267 -0
  78. package/src/withdrawal-ledger.js +47 -0
@@ -0,0 +1,94 @@
1
+ // v6 §4: weighted voting, 1.001 tiebreak, never silent (Muad's own decision -
2
+ // a deliberate tiebreaker, not a hierarchy: it decides only an exact
3
+ // deadlock and nothing else).
4
+ //
5
+ // Debate-stage votes are tallied twice, never once:
6
+ // 1. Unweighted tally first. Strictly more votes on one side wins outright
7
+ // - weighting is never consulted unless the unweighted count is tied.
8
+ // 2. Only on an exact tie, recompute with weights: seat #1 (the C&C seat,
9
+ // index 0) contributes 1.001; every other seat contributes 1.0. The
10
+ // epsilon (0.001) is smaller than any possible integer vote-count gap
11
+ // (the minimum non-tied gap is 1.0), so it can only ever matter when
12
+ // the unweighted count is exactly equal - it cannot silently tip a
13
+ // close-but-not-tied vote.
14
+ //
15
+ // The event this produces is meant for report.json's debate.tie_break -
16
+ // always present, never omitted, so its absence is never mistaken for
17
+ // "nothing to check" (the same silent-drop class of bug this project was
18
+ // burned by tonight with a dropped critic verdict under a false passed:true).
19
+
20
+ export const TIE_BREAK_SEAT_INDEX = 0;
21
+ export const TIE_BREAK_WEIGHT = 1.001;
22
+ export const DEFAULT_WEIGHT = 1.0;
23
+
24
+ // A tie_break object that is always safe to serialize when no vote was ever
25
+ // tallied this run - the field is present, occurred is false, nothing else
26
+ // is fabricated.
27
+ export const NO_TIE_BREAK = Object.freeze({ occurred: false });
28
+
29
+ /**
30
+ * Tally a list of votes ({ seat, vote: 'pass' | 'fail' }, `seat` the seat's
31
+ * index in the debate roster) and decide the outcome, weighting only on an
32
+ * exact tie. Never throws on an empty or malformed vote list - returns the
33
+ * unweighted result with occurred: false, same as any other non-tied vote.
34
+ *
35
+ * Returns { winner, tieBreak } where `winner` is 'pass' | 'fail' | null (null
36
+ * only for zero votes) and `tieBreak` is the object to store verbatim under
37
+ * report.json's debate.tie_break.
38
+ */
39
+ export function tallyVote(votes) {
40
+ // One vote per seat, last one wins if a caller ever passes a duplicate -
41
+ // two entries for the same seat must never double-count that seat's
42
+ // weight (bug-audit finding, 2026-09-13: unguarded, this would let one
43
+ // seat contribute the tiebreaker weight twice). No real call site
44
+ // constructs a votes array yet, so this is a guard against a future
45
+ // caller's bug, not a live one.
46
+ const bySeat = new Map();
47
+ for (const v of Array.isArray(votes) ? votes : []) {
48
+ if (v?.vote === 'pass' || v?.vote === 'fail') bySeat.set(v.seat, v);
49
+ }
50
+ const list = [...bySeat.values()];
51
+ const unweighted_tally = { pass: 0, fail: 0 };
52
+ for (const v of list) {
53
+ if (v.vote === 'pass') unweighted_tally.pass += 1;
54
+ else unweighted_tally.fail += 1;
55
+ }
56
+
57
+ if (unweighted_tally.pass === 0 && unweighted_tally.fail === 0) {
58
+ return { winner: null, tieBreak: NO_TIE_BREAK };
59
+ }
60
+
61
+ if (unweighted_tally.pass !== unweighted_tally.fail) {
62
+ const winner = unweighted_tally.pass > unweighted_tally.fail ? 'pass' : 'fail';
63
+ return { winner, tieBreak: NO_TIE_BREAK };
64
+ }
65
+
66
+ // Exact tie: only here does the tiebreaker seat's weight ever get
67
+ // consulted. Every other seat still contributes exactly 1.0, so the
68
+ // weighted tally can only differ from the unweighted one by the epsilon.
69
+ const weights = { [TIE_BREAK_SEAT_INDEX]: TIE_BREAK_WEIGHT };
70
+ const weighted_tally = { pass: 0, fail: 0 };
71
+ for (const v of list) {
72
+ if (v?.vote !== 'pass' && v?.vote !== 'fail') continue;
73
+ const w = v.seat === TIE_BREAK_SEAT_INDEX ? TIE_BREAK_WEIGHT : DEFAULT_WEIGHT;
74
+ weighted_tally[v.vote] += w;
75
+ }
76
+ const winner = weighted_tally.pass > weighted_tally.fail ? 'pass'
77
+ : weighted_tally.fail > weighted_tally.pass ? 'fail'
78
+ // The tiebreaker seat itself didn't vote at all - the tie survives even
79
+ // weighted. Not expected in practice (seat #1 is a debate participant
80
+ // like any other), but never silently pick a side that has no votes for it.
81
+ : null;
82
+
83
+ return {
84
+ winner,
85
+ tieBreak: {
86
+ occurred: true,
87
+ decided_by: 'seat_weights',
88
+ weights,
89
+ unweighted_tally,
90
+ weighted_tally,
91
+ outcome_changed: winner !== null,
92
+ },
93
+ };
94
+ }
package/src/ui/app.js ADDED
@@ -0,0 +1,139 @@
1
+ // The viewer's whole client. Fetches JSON from the local server, renders it.
2
+ const $ = s => document.querySelector(s);
3
+ const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
4
+ const usd = n => n == null ? '' : `$${n.toFixed(n < 1 ? 4 : 2)}`;
5
+ let run = null;
6
+
7
+ async function main() {
8
+ const runs = await (await fetch('/api/runs')).json();
9
+ const sel = $('#runs');
10
+ sel.innerHTML = runs.map(r => `<option value="${esc(r.id)}">${esc(r.id)} ${esc(r.chain)} ${esc(r.task.replace(/^tasks\//, ''))} ${r.finished ? (r.passed ? 'signed off' : 'open') : 'unfinished'} ${r.words ? r.words + 'w' : ''} ${usd(r.usd)}</option>`).join('');
11
+ sel.onchange = () => load(sel.value);
12
+ document.querySelectorAll('nav button').forEach(b => b.onclick = () => {
13
+ document.querySelectorAll('nav button, .tab').forEach(e => e.classList.remove('on'));
14
+ b.classList.add('on'); $(`#tab-${b.dataset.tab}`).classList.add('on');
15
+ });
16
+ const wanted = location.hash.slice(1);
17
+ if (runs.length) load(runs.find(r => r.id === wanted)?.id || runs[0].id);
18
+ }
19
+
20
+ async function load(id) {
21
+ $('#runs').value = id; location.hash = id;
22
+ run = await (await fetch(`/api/runs/${encodeURIComponent(id)}`)).json();
23
+ const rep = run.report;
24
+ $('#runmeta').textContent = rep
25
+ ? `${rep.chain} on ${rep.task} - ${rep.passed ? 'every lab signed off' : 'open objections'} - ${usd(rep.totals?.usd)} - ${run.drafts.length} draft(s)`
26
+ : `unfinished or crashed run - ${run.drafts.length} draft(s) on disk`;
27
+ renderOutline(); renderRevisions(); renderProposals(); renderPanel(); renderCost(); renderFiles();
28
+ }
29
+
30
+ // ---- Outline: last draft as a tree with word and volume bars ----
31
+ function renderOutline() {
32
+ const box = $('#outline');
33
+ const d = run.drafts[run.drafts.length - 1];
34
+ if (!d) { box.innerHTML = '<p class="hint">No draft in this run.</p>'; $('#reader').textContent = ''; return; }
35
+ const flat = flatten(d.tree);
36
+ const maxW = Math.max(1, ...flat.map(s => s.words));
37
+ const maxV = Math.max(1, ...flat.map(s => s.volume.score));
38
+ const opts = run.drafts.map(x => `<option value="${esc(x.label)}" ${x === d ? 'selected' : ''}>${esc(x.label)} (${x.words} words)</option>`).join('');
39
+ box.innerHTML = `<div class="small">Draft: <select id="draftpick">${opts}</select> - ${d.words} words, ${flat.length} sections.
40
+ Gold bar: words. Blue bar: build volume, a heuristic (files, scripts, code blocks, table rows, checklist items named).</div>
41
+ <div class="row l0"><span class="t small">section</span><span class="n small">words</span><span class="small">size / volume</span></div>` +
42
+ flat.map((s, i) => `<div class="row l${s.level}" data-i="${i}">
43
+ <span class="t" title="${esc(s.path)}">${esc(s.title)}</span>
44
+ <span class="n">${s.words}</span>
45
+ <span><div class="bar"><i style="width:${(100 * s.words / maxW).toFixed(1)}%"></i></div><div class="bar vol" style="margin-top:2px"><i style="width:${(100 * s.volume.score / maxV).toFixed(1)}%"></i></div></span>
46
+ </div>`).join('');
47
+ $('#draftpick').onchange = e => { run.drafts.push(run.drafts.splice(run.drafts.findIndex(x => x.label === e.target.value), 1)[0]); renderOutline(); };
48
+ box.querySelectorAll('.row[data-i]').forEach(r => r.onclick = () => {
49
+ box.querySelectorAll('.row').forEach(x => x.classList.remove('sel')); r.classList.add('sel');
50
+ const s = flat[Number(r.dataset.i)];
51
+ const v = s.volume;
52
+ $('#reader').innerHTML = `<div class="small" style="white-space:normal;font-family:system-ui">${esc(s.path)} - ${s.words} words (${s.ownWords} own)
53
+ <br>volume ${v.score}: ${v.files.length} file(s), ${v.scripts.length} script name(s), ${v.codeBlocks} code block(s), ${v.tableRows} table row(s), ${v.checklistItems} checklist item(s), ${v.numbers} unit-carrying number(s)
54
+ ${v.files.length ? `<br>files: ${v.files.map(esc).join(', ')}` : ''}${v.scripts.length ? `<br>scripts: ${v.scripts.map(esc).join(', ')}` : ''}</div><hr>` + esc(s.text);
55
+ });
56
+ }
57
+
58
+ function flatten(node, out = []) { if (node.level > 0) out.push(node); node.children.forEach(c => flatten(c, out)); return out; }
59
+
60
+ // ---- Revisions: every section across drafts, with deltas and the objections per round ----
61
+ function renderRevisions() {
62
+ const box = $('#revisions');
63
+ const labels = run.drafts.map(d => d.label);
64
+ if (labels.length < 1) { box.innerHTML = '<p class="hint">No drafts.</p>'; return; }
65
+ const rows = run.comparison.map(c => {
66
+ const cells = labels.map((l, i) => {
67
+ const cur = c.per[l]; const prev = i ? c.per[labels[i - 1]] : null;
68
+ if (!cur) return `<td class="n ${prev ? 'gone' : ''}">${prev ? 'gone' : ''}</td>`;
69
+ if (!prev) return `<td class="n ${i ? 'new' : ''}">${cur.words}${i ? ' new' : ''}</td>`;
70
+ const d = cur.words - prev.words;
71
+ return `<td class="n">${cur.words} <span class="${d > 0 ? 'up' : d < 0 ? 'down' : 'small'}">${d > 0 ? '+' : ''}${d || ''}</span></td>`;
72
+ }).join('');
73
+ return `<tr><td class="l${c.level}" style="padding-left:${8 + (c.level - 1) * 14}px">${esc(c.title)}</td>${cells}</tr>`;
74
+ }).join('');
75
+ const totals = `<tr><th>whole draft</th>${run.drafts.map(d => `<th class="n">${d.words}</th>`).join('')}</tr>`;
76
+ const rounds = Object.keys(run.panels).sort((a, b) => a - b).map(r => {
77
+ const items = run.panels[r].flatMap(p => (p.parsed?.failures || []).filter(f => f && f.criterion && !/^(none|n\/?a)$/i.test(f.criterion)).map(f => `<li><b>${esc(p.lab)}</b>: ${esc(f.problem || f.criterion)}</li>`));
78
+ const drove = run.drafts.some(d => d.label === `revise-${r}`) ? `drove revise-${r}` : 'left open (round cap reached, no further revision)';
79
+ return `<details class="card"><summary>Round ${r}: ${items.length} objection(s) ${drove}</summary><ul>${items.join('') || '<li class="small">none</li>'}</ul></details>`;
80
+ }).join('');
81
+ box.innerHTML = `<div class="legend">Words per section in each draft. Green and red are the change from the draft before. "new" and "gone" are sections that appeared or vanished. Below: which lab's objections drove each revision.</div>
82
+ <table><thead><tr><th>section</th>${labels.map(l => `<th class="n">${esc(l)}</th>`).join('')}</tr>${totals}</thead><tbody>${rows}</tbody></table>${rounds}`;
83
+ }
84
+
85
+ // ---- Proposals: per lab, with ledger status, scoreboard, and the dropped pool ----
86
+ function renderProposals() {
87
+ const box = $('#proposals');
88
+ const props = run.report?.proposals || [];
89
+ if (!props.length) { box.innerHTML = '<p class="hint">This run had no proposal stage.</p>'; return; }
90
+ const ledger = Object.fromEntries(run.ledger.map(l => [l.id, l]));
91
+ const byLab = {};
92
+ for (const p of props) (byLab[p.lab] ||= []).push(p);
93
+ const score = run.report.scoreboard?.labs || [];
94
+ const sb = `<table><thead><tr><th>lab</th><th>model</th><th class="n">proposed</th><th class="n">accepted</th><th class="n">cut</th><th class="n">unaccounted</th><th class="n">built</th></tr></thead><tbody>` +
95
+ score.map(l => `<tr><td>${esc(l.lab)}</td><td class="small">${esc(l.model)}</td><td class="n">${l.proposed}</td><td class="n">${l.accepted}</td><td class="n">${l.cut}</td><td class="n">${l.unaccounted}</td><td class="n small">${l.built ?? 'after the build'}</td></tr>`).join('') + '</tbody></table>';
96
+ const cards = Object.entries(byLab).map(([lab, list]) => `<div class="card"><h3>${esc(lab)} <span class="small">${esc(list[0].model)}</span></h3>` +
97
+ list.map(p => { const l = ledger[p.id]; const st = l?.status || 'unaccounted';
98
+ return `<details><summary><b>${esc(p.id)}</b> ${esc(p.title)} <span class="tag ${st}">${st}</span> <span class="small">${esc(l?.note || '')}</span></summary>
99
+ <div class="small">serves: ${esc(p.serves)}</div><p>${esc(p.what)}</p><p><i>${esc(p.why)}</i></p><p>${esc(p.how)}</p><p class="small">test: ${esc(p.acceptance_test)}</p></details>`; }).join('') + '</div>').join('');
100
+ const pool = run.texts['proposals-pool.md'] ? `<details class="card"><summary>Full pool, including dropped attempts (proposals-pool.md)</summary><pre class="reader">${esc(run.texts['proposals-pool.md'])}</pre></details>` : '';
101
+ box.innerHTML = `<div class="legend">Scoreboard from the plan's own scope ledger. "built" is filled by a human after a build session.</div>${sb}${cards}${pool}`;
102
+ }
103
+
104
+ // ---- Panel: verdicts per round per lab ----
105
+ function renderPanel() {
106
+ const box = $('#panel');
107
+ const rounds = Object.keys(run.panels).sort((a, b) => a - b);
108
+ if (!rounds.length) { box.innerHTML = '<p class="hint">No critic replies on disk.</p>'; return; }
109
+ const crit = run.report?.criteria || [];
110
+ box.innerHTML = (crit.length ? `<div class="card"><h3>Acceptance criteria</h3><ol>${crit.map(c => `<li>${esc(c)}</li>`).join('')}</ol></div>` : '') +
111
+ rounds.map(r => `<div class="card"><h3>Round ${r}</h3>` + run.panels[r].map(p => {
112
+ if (!p.parsed) return `<div><b>${esc(p.lab)}</b> <span class="tag abs">unreadable</span> <span class="small">${esc(p.file)}</span></div>`;
113
+ const fails = (p.parsed.failures || []).filter(f => f && f.criterion && !/^(none|n\/?a)$/i.test(f.criterion));
114
+ return `<details><summary><b>${esc(p.lab)}</b> <span class="tag ${fails.length ? 'bad' : 'ok'}">${fails.length ? fails.length + ' objection(s)' : 'signed off'}</span> <span class="small">${esc(p.parsed.verdict_line || '')}</span></summary>
115
+ <table><thead><tr><th>criterion</th><th>verdict</th><th>evidence</th></tr></thead><tbody>${(p.parsed.criteria || []).map(c => `<tr><td>${esc(c.criterion)}</td><td class="${/fail/i.test(c.verdict) ? 'down' : 'up'}">${esc(c.verdict)}</td><td class="small">${esc(c.evidence)}</td></tr>`).join('')}</tbody></table></details>`;
116
+ }).join('') + '</div>').join('');
117
+ }
118
+
119
+ // ---- Cost: per stage ----
120
+ function renderCost() {
121
+ const box = $('#cost');
122
+ const st = run.report?.stages || [];
123
+ if (!st.length) { box.innerHTML = '<p class="hint">No report.json yet (run unfinished).</p>'; return; }
124
+ const byProv = {};
125
+ for (const s of st) { const k = `${s.provider}/${s.model}`; byProv[k] = (byProv[k] || 0) + (s.usd || 0); }
126
+ box.innerHTML = `<div class="grid2"><div class="card"><h3>By seat</h3><table>${Object.entries(byProv).sort((a, b) => b[1] - a[1]).map(([k, v]) => `<tr><td>${esc(k)}</td><td class="n">${usd(v)}</td></tr>`).join('')}<tr><th>total</th><th class="n">${usd(run.report.totals.usd)}</th></tr></table></div>
127
+ <div class="card"><h3>By stage</h3><table><thead><tr><th>stage</th><th>seat</th><th class="n">in</th><th class="n">out</th><th class="n">thinking</th><th class="n">usd</th><th class="n">s</th></tr></thead><tbody>${st.map(s => `<tr><td>${esc(s.label)}</td><td class="small">${esc(s.provider)}/${esc(s.model)}</td><td class="n">${s.usage?.input ?? ''}</td><td class="n">${s.usage?.output ?? ''}</td><td class="n">${s.usage?.thinking || ''}</td><td class="n">${usd(s.usd)}</td><td class="n">${s.ms ? (s.ms / 1000).toFixed(0) : ''}</td></tr>`).join('')}</tbody></table></div></div>`;
128
+ }
129
+
130
+ // ---- Files: raw view of anything in the run folder ----
131
+ function renderFiles() {
132
+ const list = $('#filelist'), view = $('#fileview');
133
+ const names = Object.keys(run.texts);
134
+ list.innerHTML = names.map(n => `<div class="row" data-f="${esc(n)}"><span class="t">${esc(n)}</span><span class="n">${(run.texts[n] || '').length}</span><span></span></div>`).join('');
135
+ list.querySelectorAll('.row').forEach(r => r.onclick = () => { list.querySelectorAll('.row').forEach(x => x.classList.remove('sel')); r.classList.add('sel'); view.textContent = run.texts[r.dataset.f]; });
136
+ view.textContent = run.texts['run.log'] || '';
137
+ }
138
+
139
+ main();
@@ -0,0 +1,43 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>relay viewer</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+ <link rel="stylesheet" href="style.css">
8
+ </head>
9
+ <body>
10
+ <header>
11
+ <h1>relay</h1>
12
+ <select id="runs"></select>
13
+ <span id="runmeta" class="meta"></span>
14
+ <nav id="tabs">
15
+ <button data-tab="outline" class="on">Outline</button>
16
+ <button data-tab="revisions">Revisions</button>
17
+ <button data-tab="proposals">Proposals</button>
18
+ <button data-tab="panel">Panel</button>
19
+ <button data-tab="cost">Cost</button>
20
+ <button data-tab="files">Files</button>
21
+ </nav>
22
+ </header>
23
+ <main>
24
+ <section id="tab-outline" class="tab on">
25
+ <div class="split">
26
+ <div id="outline" class="pane"></div>
27
+ <div id="reader" class="pane reader"><p class="hint">Pick a section.</p></div>
28
+ </div>
29
+ </section>
30
+ <section id="tab-revisions" class="tab"><div id="revisions"></div></section>
31
+ <section id="tab-proposals" class="tab"><div id="proposals"></div></section>
32
+ <section id="tab-panel" class="tab"><div id="panel"></div></section>
33
+ <section id="tab-cost" class="tab"><div id="cost"></div></section>
34
+ <section id="tab-files" class="tab">
35
+ <div class="split">
36
+ <div id="filelist" class="pane"></div>
37
+ <div id="fileview" class="pane reader"></div>
38
+ </div>
39
+ </section>
40
+ </main>
41
+ <script src="app.js"></script>
42
+ </body>
43
+ </html>
@@ -0,0 +1,101 @@
1
+ // Turns a markdown plan into a section tree with sizes and a rough "build
2
+ // volume" estimate per section. Pure functions, no I/O, so the viewer's
3
+ // numbers can be checked from a script.
4
+ //
5
+ // Build volume is a heuristic and is labelled as one everywhere it is shown:
6
+ // a plan names files, scripts, code blocks and tables; a section that names
7
+ // many of them will cost more to build than one that names none. It is not
8
+ // a line count and never becomes one until a build session has run.
9
+
10
+ const FILE_RE = /`([A-Za-z0-9_./-]+\.(?:cs|js|ts|json|md|unity|prefab|asset|sh|py|css|html|yaml|yml|toml|cfg|txt))`/g;
11
+ const SCRIPT_RE = /\b([A-Z][A-Za-z0-9]+(?:Controller|Manager|Behaviour|Behavior|State|System|Config|Provider|Interaction|Visual|UI|Bootstrap|Assignment|Builder|Script))\b/g;
12
+
13
+ export function words(text) {
14
+ return (text.match(/\S+/g) || []).length;
15
+ }
16
+
17
+ export function parseSections(markdown) {
18
+ const lines = markdown.split('\n');
19
+ const root = { title: '(document)', level: 0, path: '', lines: [], children: [] };
20
+ const stack = [root];
21
+ let inFence = false;
22
+ for (const line of lines) {
23
+ if (/^```/.test(line)) inFence = !inFence;
24
+ const h = !inFence && line.match(/^(#{1,4})\s+(.*?)\s*#*\s*$/);
25
+ if (h) {
26
+ const level = h[1].length;
27
+ const node = { title: h[2].trim(), level, lines: [line], children: [] };
28
+ while (stack.length > 1 && stack[stack.length - 1].level >= level) stack.pop();
29
+ const parent = stack[stack.length - 1];
30
+ node.path = parent.path ? `${parent.path} > ${node.title}` : node.title;
31
+ parent.children.push(node);
32
+ stack.push(node);
33
+ } else {
34
+ stack[stack.length - 1].lines.push(line);
35
+ }
36
+ }
37
+ return finish(root);
38
+ }
39
+
40
+ function finish(node) {
41
+ node.ownText = node.lines.join('\n');
42
+ node.children.forEach(finish);
43
+ node.text = [node.ownText, ...node.children.map(c => c.text)].join('\n');
44
+ node.ownWords = words(node.ownText);
45
+ node.words = words(node.text);
46
+ node.volume = volumeOf(node.text);
47
+ delete node.lines;
48
+ return node;
49
+ }
50
+
51
+ export function volumeOf(text) {
52
+ const files = new Set([...text.matchAll(FILE_RE)].map(m => m[1]));
53
+ const scripts = new Set([...text.matchAll(SCRIPT_RE)].map(m => m[1]));
54
+ const fences = (text.match(/^```/gm) || []).length / 2 | 0;
55
+ const tableRows = (text.match(/^\|[^\n]*\|\s*$/gm) || []).length;
56
+ const numbers = (text.match(/\b\d+(?:\.\d+)?\s?(?:s|ms|m|m\/s|%|MB|KB|px|°|tokens?)\b/g) || []).length;
57
+ const checklist = (text.match(/^\s*(?:\d+\.|[-*]\s*\[[ x]\])\s/gm) || []).length;
58
+ return {
59
+ files: [...files].sort(),
60
+ scripts: [...scripts].sort(),
61
+ codeBlocks: fences,
62
+ tableRows,
63
+ numbers,
64
+ checklistItems: checklist,
65
+ // One number so bars can be drawn. Weights are arbitrary and stated.
66
+ score: files.size * 3 + scripts.size * 2 + fences * 4 + tableRows + checklist,
67
+ };
68
+ }
69
+
70
+ export function flatten(node, out = []) {
71
+ if (node.level > 0) out.push(node);
72
+ node.children.forEach(c => flatten(c, out));
73
+ return out;
74
+ }
75
+
76
+ // Section-by-section comparison across drafts, keyed by heading path.
77
+ export function compareDrafts(drafts) {
78
+ // drafts: [{ label, tree }]
79
+ const keys = new Map();
80
+ drafts.forEach((d, i) => {
81
+ for (const s of flatten(d.tree)) {
82
+ const key = s.path;
83
+ if (!keys.has(key)) keys.set(key, { path: key, title: s.title, level: s.level, first: i, per: {} });
84
+ keys.get(key).per[d.label] = { words: s.words, ownWords: s.ownWords, volume: s.volume.score };
85
+ }
86
+ });
87
+ return [...keys.values()];
88
+ }
89
+
90
+ // The plan's own scope ledger, if it wrote one.
91
+ export function parseLedger(markdown) {
92
+ // \Z is not a JS anchor; the section runs to the next heading or the end.
93
+ const m = markdown.match(/^#{1,4}\s+(?:\d+\.\s*)?Scope ledger\s*$([\s\S]*?)(?=^#{1,4}\s|$(?![\s\S]))/im);
94
+ if (!m) return [];
95
+ const rows = [];
96
+ for (const line of m[1].split('\n')) {
97
+ const r = line.match(/^[\s*_`-]*([A-Z0-9]+-\d+)[`*_]*\s*[-:–—]\s*\**(accepted|cut|withdrawn)\**\s*[-:–—]?\s*(.*)$/i);
98
+ if (r) rows.push({ id: r[1], status: r[2].toLowerCase(), note: r[3].trim() });
99
+ }
100
+ return rows;
101
+ }
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+ // Local viewer for relay runs. Serves the static page and a small JSON API
3
+ // over runs/. Nothing is written, nothing leaves the machine.
4
+ //
5
+ // npm run ui -> http://127.0.0.1:8787
6
+ // PORT=9000 npm run ui
7
+ import { createServer } from 'node:http';
8
+ import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';
9
+ import { join, dirname, resolve, extname } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { parseSections, compareDrafts, parseLedger, words } from './parse.js';
12
+
13
+ const here = dirname(fileURLToPath(import.meta.url));
14
+ const root = resolve(here, '../..');
15
+ const runsDir = join(root, 'runs');
16
+ const port = Number(process.env.PORT || 8787);
17
+
18
+ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8' };
19
+
20
+ function readJson(p) { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } }
21
+ function readText(p) { try { return readFileSync(p, 'utf8'); } catch { return null; } }
22
+
23
+ function listRuns() {
24
+ if (!existsSync(runsDir)) return [];
25
+ return readdirSync(runsDir)
26
+ .filter(id => statSync(join(runsDir, id)).isDirectory())
27
+ .sort()
28
+ .reverse()
29
+ .map(id => {
30
+ const report = readJson(join(runsDir, id, 'report.json'));
31
+ const deliverable = readText(join(runsDir, id, 'deliverable.md'));
32
+ const log = readText(join(runsDir, id, 'run.log')) || '';
33
+ const chain = report?.chain || (log.match(/^chain: (\S+)/m) || [])[1] || '?';
34
+ const task = report?.task || (log.match(/^task: +(\S+)/m) || [])[1] || '?';
35
+ return {
36
+ id, chain, task,
37
+ finished: !!report,
38
+ passed: report?.passed ?? null,
39
+ usd: report?.totals?.usd ?? null,
40
+ words: deliverable ? words(deliverable) : null,
41
+ proposals: report?.proposals?.length ?? 0,
42
+ };
43
+ });
44
+ }
45
+
46
+ // Drafts in the order they were written: build, revise-1, revise-2, ..., final.
47
+ function draftFiles(dir) {
48
+ const names = readdirSync(dir);
49
+ const order = n => n === 'build.md' ? 0 : n.startsWith('revise-') ? 1 + Number(n.match(/\d+/)[0]) : n === 'final.md' ? 900 : -1;
50
+ return names.filter(n => order(n) >= 0).sort((a, b) => order(a) - order(b));
51
+ }
52
+
53
+ function runDetail(id) {
54
+ const dir = join(runsDir, id);
55
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return null;
56
+ const report = readJson(join(dir, 'report.json'));
57
+ const files = readdirSync(dir).sort();
58
+ const drafts = draftFiles(dir).map(name => {
59
+ const text = readText(join(dir, name)) || '';
60
+ return { label: name.replace(/\.md$/, ''), name, words: words(text), tree: parseSections(text) };
61
+ });
62
+ const deliverable = readText(join(dir, 'deliverable.md'));
63
+ const texts = {};
64
+ for (const f of files) if (f.endsWith('.md') || f === 'run.log') texts[f] = readText(join(dir, f));
65
+ // Panel verdicts per round, from the saved critic replies.
66
+ const panels = {};
67
+ for (const f of files) {
68
+ const m = f.match(/^panel-(\d+)-([a-z0-9]+)\.md$/) || f.match(/^critique-(\d+)\.md$/);
69
+ if (!m) continue;
70
+ const round = m[1];
71
+ const lab = m[2] || 'critic';
72
+ let parsed = null;
73
+ try {
74
+ const t = texts[f];
75
+ const first = t.indexOf('{'), last = t.lastIndexOf('}');
76
+ parsed = JSON.parse(t.slice(first, last + 1));
77
+ } catch { /* unreadable, shown as such */ }
78
+ (panels[round] ||= []).push({ lab, file: f, parsed });
79
+ }
80
+ return {
81
+ id,
82
+ report,
83
+ files,
84
+ drafts: drafts.map(d => ({ label: d.label, name: d.name, words: d.words, tree: d.tree })),
85
+ comparison: compareDrafts(drafts),
86
+ ledger: deliverable ? parseLedger(deliverable) : [],
87
+ panels,
88
+ texts,
89
+ };
90
+ }
91
+
92
+ const server = createServer((req, res) => {
93
+ const url = new URL(req.url, `http://${req.headers.host}`);
94
+ const send = (code, body, type = 'application/json; charset=utf-8') => {
95
+ res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store' });
96
+ res.end(body);
97
+ };
98
+ try {
99
+ if (url.pathname === '/api/runs') return send(200, JSON.stringify(listRuns()));
100
+ const m = url.pathname.match(/^\/api\/runs\/([^/]+)$/);
101
+ if (m) {
102
+ const d = runDetail(decodeURIComponent(m[1]));
103
+ return d ? send(200, JSON.stringify(d)) : send(404, '{"error":"no such run"}');
104
+ }
105
+ const file = url.pathname === '/' ? 'index.html' : url.pathname.slice(1);
106
+ if (!/^[a-z0-9._-]+$/i.test(file)) return send(404, 'not found', 'text/plain');
107
+ const p = join(here, file);
108
+ if (!existsSync(p)) return send(404, 'not found', 'text/plain');
109
+ return send(200, readFileSync(p), MIME[extname(file)] || 'application/octet-stream');
110
+ } catch (err) {
111
+ return send(500, JSON.stringify({ error: String(err.message || err) }));
112
+ }
113
+ });
114
+
115
+ server.listen(port, '127.0.0.1', () => {
116
+ console.log(`relay viewer: http://127.0.0.1:${port} (runs from ${runsDir})`);
117
+ });
@@ -0,0 +1,37 @@
1
+ :root { --bg:#111; --bg2:#1a1a1a; --bg3:#232323; --fg:#e8e8e8; --dim:#9a9a9a; --gold:#d4a72c; --ok:#5cb85c; --bad:#d9534f; --mid:#6c8ebf; }
2
+ * { box-sizing: border-box; }
3
+ body { margin:0; background:var(--bg); color:var(--fg); font: 14px/1.45 system-ui, sans-serif; }
4
+ header { display:flex; gap:14px; align-items:center; padding:10px 16px; background:var(--bg2); border-bottom:1px solid #333; flex-wrap:wrap; }
5
+ h1 { font-size:16px; margin:0; color:var(--gold); letter-spacing:.04em; }
6
+ select { background:var(--bg3); color:var(--fg); border:1px solid #444; padding:4px 8px; max-width:60vw; }
7
+ .meta { color:var(--dim); font-size:12px; }
8
+ nav button { background:none; border:1px solid #444; color:var(--dim); padding:4px 10px; margin-left:4px; cursor:pointer; }
9
+ nav button.on { color:var(--fg); border-color:var(--gold); }
10
+ main { padding:12px 16px; }
11
+ .tab { display:none; } .tab.on { display:block; }
12
+ .split { display:grid; grid-template-columns: minmax(320px, 46%) 1fr; gap:16px; }
13
+ .pane { background:var(--bg2); border:1px solid #2c2c2c; padding:10px; max-height: calc(100vh - 90px); overflow:auto; }
14
+ .reader { white-space:pre-wrap; font-family: ui-monospace, monospace; font-size:12.5px; }
15
+ .hint { color:var(--dim); }
16
+ .row { display:grid; grid-template-columns: 1fr 64px 90px; gap:8px; align-items:center; padding:3px 4px; cursor:pointer; border-radius:3px; }
17
+ .row:hover, .row.sel { background:var(--bg3); }
18
+ .row .t { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
19
+ .row.l1 .t { font-weight:600; } .row.l2 .t { padding-left:14px; } .row.l3 .t { padding-left:28px; color:#cfcfcf; } .row.l4 .t { padding-left:42px; color:var(--dim); }
20
+ .n { text-align:right; color:var(--dim); font-variant-numeric: tabular-nums; }
21
+ .bar { height:8px; background:#2f2f2f; border-radius:2px; overflow:hidden; }
22
+ .bar i { display:block; height:100%; background:var(--gold); }
23
+ .bar.vol i { background:var(--mid); }
24
+ table { border-collapse:collapse; width:100%; font-size:13px; }
25
+ th, td { text-align:left; padding:5px 8px; border-bottom:1px solid #2a2a2a; vertical-align:top; }
26
+ th { color:var(--dim); font-weight:500; }
27
+ td.n, th.n { text-align:right; font-variant-numeric: tabular-nums; }
28
+ .up { color:var(--ok); } .down { color:var(--bad); } .new { color:var(--gold); } .gone { color:var(--bad); text-decoration: line-through; }
29
+ .card { background:var(--bg2); border:1px solid #2c2c2c; padding:10px 12px; margin:8px 0; }
30
+ .card h3 { margin:0 0 6px; font-size:14px; }
31
+ .tag { display:inline-block; padding:1px 7px; border-radius:10px; font-size:11px; background:#333; color:var(--fg); margin-left:6px; }
32
+ .tag.accepted { background:#254d25; } .tag.cut { background:#4d2525; } .tag.unaccounted { background:#4d4525; }
33
+ .tag.ok { background:#254d25; } .tag.bad { background:#4d2525; } .tag.abs { background:#4d4525; }
34
+ .small { color:var(--dim); font-size:12px; }
35
+ .grid2 { display:grid; grid-template-columns: 1fr 1fr; gap:12px; }
36
+ details summary { cursor:pointer; color:var(--dim); }
37
+ .legend { color:var(--dim); font-size:12px; margin:6px 0 12px; }