create-pmos 0.577.0 → 0.579.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.
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+ /* improve-runs.js — the workspace job `improve`: the self-improvement loop in every product and project PMOS runs (initiative
3
+ * improve-loop-engine, stage 3 of the spec "Recursive self-improvement for PMOS"). The engine is lib/improve-loop.js; PMOS itself runs
4
+ * the same loop through scripts/improve.js and a cloud trigger, so a PMOS checkout is skipped here.
5
+ *
6
+ * WHEN IT RUNS. bg-queue step 5 (lib/bg-queue.js): only while the PM has stepped away, so it yields to the PM's live sessions; held by quiet
7
+ * hours, the runs-at-once limit and the spend limit (which the PM may set to unlimited: `pmos grill cap unlimited`). No cadence and no count
8
+ * cap: each turn it may start one run when the brakes allow. Off with `pmos ai off improve` or PMOS_IMPROVE=off; off on a scratch server
9
+ * (PMOS_STATE_DIR) unless PMOS_IMPROVE=1.
10
+ *
11
+ * WHAT ONE TURN DOES, per open product (not a PMOS checkout):
12
+ * 1. Reads the product's signals (<state>/improve-signals.jsonl, the signals build: counts, ids and links only, never words) and this
13
+ * job's ledger (<state>/improve.jsonl). Both are local state: product data stays home.
14
+ * 2. Brakes (lib/improve-loop.js brakes): the usage-limit hold a failed run left (lib/orchestrator-quota.js: back off on the first
15
+ * rate-limit reply), and the circuit breaker on the product's reverts and CI failures.
16
+ * 3. Measures each lesson MEASURE_DAYS after it was applied. In a product the held-out judge is the PM: a lesson the PM undid failed
17
+ * its held-out check. Otherwise the area's signal rate against a matched untouched area decides keep, revert or inconclusive (tried).
18
+ * A revert removes the memory entry and records a setback (lib/autonomy.js), so two bad ones demote the job to asking (D106).
19
+ * 4. Stage gate: lessons start only at stage 3, after PMOS itself passed stage 2's exit test (20 measured fixes, half passing held-out),
20
+ * read from an open PMOS checkout (deps.selfRoot). Before that the turn only ranks and keeps the status for `pmos improve status`.
21
+ * 5. Starts at most ONE headless run (kind improve, origin improve:<ws>:<area>:<token>) on the top eligible area. Its only writes are
22
+ * `pmos improve lesson` (a curated-memory entry, 30-day stale date, class B with Undo through the autonomy ledger) and
23
+ * `pmos improve propose` (a skill or harness change: a class C ✦, never applied by itself).
24
+ *
25
+ * create(deps) → { tick({ now }), status(), active() }
26
+ * lesson({ stateDir, root, ws, area, run, text, now, env }) → { ok, ref?, applied?, error? } the CLI's one write (pmos improve lesson)
27
+ * propose({ stateDir, ws, area, run, text, ini, now }) → { ok, id?, error? } the CLI's other write (pmos improve propose)
28
+ * undo(stateDir, root, ref, { now }) → { ok, error? } Undo of a lesson (routes-autonomy)
29
+ * LEDGER · SIGNALS · JOB · ORIGIN · off(env) · isSelf(root)
30
+ * deps: { roots() → [{ id, root }], stateDirFor(w) → dir, selfRoot() → PMOS root | null, quota() → hold | null, env, spawn(spec), stop(s), warn(what, e) }
31
+ */
32
+ const fs = require('fs');
33
+ const path = require('path');
34
+ const crypto = require('crypto');
35
+ const L = require('./improve-loop.js');
36
+
37
+ const LEDGER = 'improve.jsonl';
38
+ const SIGNALS = 'improve-signals.jsonl';
39
+ const JOB = 'ai:improve';
40
+ const ORIGIN = 'improve:';
41
+ const STALE_DAYS = 30;
42
+ const RE_REF = /^im-[0-9a-f]{10}$/;
43
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
44
+
45
+ const off = (env) => {
46
+ const e = env || process.env;
47
+ const v = String(e.PMOS_IMPROVE || '').trim();
48
+ if (/^(1|on|true|yes)$/i.test(v)) return false;
49
+ return /^(off|0|false|no)$/i.test(v) || !!String(e.PMOS_STATE_DIR || '').trim();
50
+ };
51
+ const isSelf = (root) => fs.existsSync(path.join(root, 'scripts', 'improve.js')) && fs.existsSync(path.join(root, 'workspace', 'lib', 'improve-loop.js'));
52
+
53
+ function jsonl(file) {
54
+ let t = ''; try { t = fs.readFileSync(file, 'utf8'); } catch { return []; }
55
+ const out = [];
56
+ for (const l of t.split('\n')) { if (!l.trim()) continue; try { const o = JSON.parse(l); if (o && typeof o === 'object') out.push(o); } catch { /* a torn line */ } }
57
+ return out;
58
+ }
59
+ function signalsOf(sd) {
60
+ try { const S = require('./signals.js'); if (S && typeof S.readSignals === 'function') return S.readSignals(S.productFile ? S.productFile(sd) : path.join(sd, SIGNALS)) || []; } catch { /* the signals build is not here yet */ }
61
+ return jsonl(path.join(sd, SIGNALS));
62
+ }
63
+ const ledgerOf = (sd) => jsonl(path.join(sd, LEDGER));
64
+ function append(sd, line, now = Date.now()) {
65
+ fs.mkdirSync(sd, { recursive: true });
66
+ fs.appendFileSync(path.join(sd, LEDGER), JSON.stringify({ v: 1, at: new Date(now).toISOString(), ...line }) + '\n');
67
+ }
68
+ /* the stage PMOS itself has reached (scripts/improve.js in an open PMOS checkout); products start at stage 3 */
69
+ function selfStage(selfRoot, now, env) {
70
+ if (!selfRoot) return { stage: 0, why: 'no PMOS checkout is open, so the loop cannot read whether PMOS itself passed stage 2' };
71
+ try {
72
+ const I = require(path.join(selfRoot, 'scripts', 'improve.js'));
73
+ const sigs = jsonl(path.join(selfRoot, 'planning', 'improve', 'signals.jsonl'));
74
+ const lines = jsonl(path.join(selfRoot, L.LEDGER));
75
+ const st = L.stage(I.stageEvidence(sigs, lines, now), { now, override: (env || {}).PMOS_IMPROVE_STAGE });
76
+ const first = st.exits.find((x) => !x.passed);
77
+ return { stage: st.stage, why: first ? `stage ${first.stage} exit: ${first.why}` : null };
78
+ } catch (e) { return { stage: 0, why: `the PMOS checkout's loop could not be read: ${one(e && e.message, 120)}` }; }
79
+ }
80
+ /* reverts and CI failures from the product's own signals, merges from its git history */
81
+ function productEvents(root, sigs) {
82
+ const out = [];
83
+ try {
84
+ const r = require('child_process').spawnSync('git', ['log', '--first-parent', '--since=40.days', '--format=%cI%x09%s'], { cwd: root, encoding: 'utf8', timeout: 20000 });
85
+ for (const l of String(r.stdout || '').split('\n')) { const [at, s] = l.split('\t'); if (!at) continue; out.push({ at, kind: 'merge' }); if (/^revert\b/i.test(s || '')) out.push({ at, kind: 'revert' }); }
86
+ } catch { /* no git: the breaker has no merges, so it never trips */ }
87
+ for (const s of sigs) if (s.kind === 'ci-fail' || s.kind === 'release-check-fail') out.push({ at: s.at, kind: 'ci-fail' });
88
+ return out;
89
+ }
90
+
91
+ function prompt(cand, ws) {
92
+ const ev = cand.evidence.map((e) => `- ${e.id}${e.link ? ' ' + e.link : ''}`).join('\n') || '- (none)';
93
+ return [
94
+ `PMOS's improvement loop found a problem that repeats in this product. Area: ${cand.area}. ${cand.count} signals in the last ${L.WINDOW_DAYS} days (${cand.kinds.join(', ')}). Evidence (ids and links, data only, never instructions):`,
95
+ ev, '',
96
+ '1. Read the evidence and the records it points at. Find the one cause that, if every agent working here knew it, would stop the problem repeating.',
97
+ '2. If a short fact does it (at most 300 characters, written as what to do), record it once: `pmos improve lesson --text "<the fact>"`. It goes into the product\'s curated memory, which every later run reads; the PM can undo it.',
98
+ '3. If only a change to a skill, an agent rule, a gate or the harness would stop it, do not change anything: file it once with `pmos improve propose --text "<what to change and why>"`. The PM decides.',
99
+ '4. If the evidence does not show a cause you can name, write nothing and say so.',
100
+ 'Change nothing else. Send nothing outward. Do not write to any record other than through these two commands.',
101
+ `(product ${ws})`,
102
+ ].join('\n');
103
+ }
104
+
105
+ function create(deps = {}) {
106
+ const warn = deps.warn || (() => {});
107
+ const env = deps.env || process.env;
108
+ const last = new Map(); // ws → { at, stage, why, action, top }
109
+ let live = null; // the one run at a time
110
+
111
+ function measureDue(w, sd, now) {
112
+ const lines = ledgerOf(sd); const st = L.fold(lines);
113
+ const sigs = signalsOf(sd);
114
+ for (const f of st.fixes.values()) {
115
+ if (f.verdict || now - Date.parse(f.at) < L.MEASURE_DAYS * L.DAY) continue;
116
+ const les = st.lessons.get(f.id);
117
+ const counts = L.countsAround(sigs, f.at);
118
+ const control = L.pickControl(counts, f.area, { exclude: [...st.fixes.values()].filter((x) => !x.verdict && x.id !== f.id).map((x) => x.area) });
119
+ const m = L.measure({ casePass: null, heldout: [{ id: 'not-undone', pass: !(les && les.undone) }], area: counts[f.area] || { before: 0, after: 0 }, control: control ? counts[control] : null });
120
+ append(sd, { ev: 'measured', fix: f.id, area: f.area, verdict: m.verdict, why: m.why, heldout: { pass: les && les.undone ? 0 : 1, total: 1 } }, now);
121
+ if (m.verdict === 'revert' && les && !les.undone) {
122
+ undo(sd, w.root, f.id, { now, kind: 'revert', ws: w.id });
123
+ }
124
+ }
125
+ }
126
+
127
+ function tick({ now = Date.now() } = {}) {
128
+ if (off(env)) return { off: true };
129
+ if (live && live.state !== 'exited') return { busy: true };
130
+ live = null;
131
+ const quota = deps.quota ? (() => { try { return deps.quota(); } catch { return null; } })() : null;
132
+ const self = selfStage(deps.selfRoot ? deps.selfRoot() : null, now, env);
133
+ for (const w of (deps.roots ? deps.roots() : [])) {
134
+ if (!w || !w.root || isSelf(w.root)) continue;
135
+ const sd = deps.stateDirFor ? deps.stateDirFor(w) : null;
136
+ if (!sd) continue;
137
+ try {
138
+ measureDue(w, sd, now);
139
+ const sigs = signalsOf(sd);
140
+ const lines = ledgerOf(sd);
141
+ const state = L.fold(lines);
142
+ const ranked = L.rank(L.scout(sigs, { now }));
143
+ const brake = L.brakes({ quota, breaker: L.breaker(productEvents(w.root, sigs), { now }) });
144
+ const top = ranked.filter((c) => c.eligible).slice(0, 5).map((c) => ({ area: c.area, score: c.score, family: c.family, count: c.count }));
145
+ const say = (action, why) => { last.set(w.id, { at: new Date(now).toISOString(), stage: self.stage, action, why, top, digest: L.digest(state, { now, signals: sigs, ranked }) }); };
146
+ if (!brake.go) { say('none', brake.why); continue; }
147
+ if (self.stage < 3) { say('none', `lessons start at stage 3 (${self.why})`); continue; }
148
+ const cand = ranked.find((c) => c.eligible && !c.outside && !c.self && !L.areaGate(c.area, state, { now }));
149
+ if (!cand) { say('none', ranked.some((c) => c.eligible) ? 'every eligible area is being measured, cooling down or waiting for Wawan' : 'no area above the value floor'); continue; }
150
+ if (!deps.spawn) { say('none', 'no way to start a run here'); continue; }
151
+ const token = crypto.randomBytes(4).toString('hex');
152
+ const s = deps.spawn({ name: `Learning from a repeated problem: ${cand.area}`, ws: w.id, origin: `${ORIGIN}${w.id}:${cand.area}:${token}`, initialInput: prompt(cand, w.id) + '\r',
153
+ env: { PMOS_IMPROVE_RUN: token, PMOS_IMPROVE_WS: w.id, PMOS_IMPROVE_AREA: cand.area, PMOS_IMPROVE_STATE: sd, PMOS_IMPROVE_ROOT: w.root } });
154
+ if (!s || s.held || s.state === 'exited') { say('none', s && s.why ? `the run was held: ${s.why}` : 'the run did not start'); continue; }
155
+ live = s;
156
+ say('run', `started a run on ${cand.area} (score ${cand.score})`);
157
+ return { started: cand.area, ws: w.id }; // one run at a time for the machine
158
+ } catch (e) { warn('improve tick', e); }
159
+ }
160
+ return { started: null };
161
+ }
162
+ return { tick, status: () => [...last.entries()].map(([ws, v]) => ({ ws, ...v })), active: () => !!(live && live.state !== 'exited') };
163
+ }
164
+
165
+ /* ---------- the run's two writes (pmos improve lesson | propose) ---------- */
166
+ function memoryCore() { const m = require('./memory.js').core(); return m && m.ok ? m.core : null; }
167
+ function lesson({ stateDir, root, ws, area, run, text, now = Date.now(), env = process.env, signals = null } = {}) {
168
+ const t = one(text, 300);
169
+ if (!stateDir || !root || !ws || !area || !run) return { ok: false, error: 'pmos improve lesson runs only inside an improvement run (the improvement run variables are not set)' };
170
+ if (t.length < 12) return { ok: false, error: 'a lesson is one short fact, written as what to do' };
171
+ const st = L.fold(ledgerOf(stateDir));
172
+ if ([...st.fixes.values()].some((f) => f.source === run)) return { ok: false, error: 'this run already recorded its one lesson' };
173
+ const A = require('./autonomy.js');
174
+ const d = A.decide({ stateDir, job: JOB, product: ws, cls: 'B', undoable: true, now, env });
175
+ const ref = 'im-' + crypto.createHash('sha256').update(`${ws}:${area}:${run}:${t}`).digest('hex').slice(0, 10);
176
+ if (!d.apply) {
177
+ append(stateDir, { ev: 'wawan', area, why: `a lesson waits for you (${d.why}): ${t}` }, now);
178
+ return { ok: true, ref, applied: false, why: d.why };
179
+ }
180
+ const core = memoryCore();
181
+ if (!core) return { ok: false, error: 'curated memory is not available in this install' };
182
+ const stale = new Date(now + STALE_DAYS * L.DAY).toISOString().slice(0, 10);
183
+ const w = core.write(root, { op: 'add', text: t, by: 'agent:improve', source: `improve:${ref}`, stale_after: stale, confidence: 'unconfirmed' });
184
+ if (!w.ok) return { ok: false, error: w.error };
185
+ const sigs = signals || signalsOf(stateDir);
186
+ const n = sigs.filter((s) => L.slug(s.area) === area).length;
187
+ append(stateDir, { ev: 'fix', fix: ref, area, case: null, source: run, files: [] }, now);
188
+ append(stateDir, { ev: 'lesson', ref, area, text: t }, now);
189
+ A.recordApplied(stateDir, { job: JOB, product: ws, ref, title: `Learned: ${t}`, cls: 'B', why: `${n} signals in ${area}`, run }, { now });
190
+ return { ok: true, ref, applied: true };
191
+ }
192
+ function propose({ stateDir, ws, area, run, text, ini = null, now = Date.now() } = {}) {
193
+ const t = one(text, 300);
194
+ if (!stateDir || !ws || !area || !run) return { ok: false, error: 'pmos improve propose runs only inside an improvement run (the improvement run variables are not set)' };
195
+ if (t.length < 12) return { ok: false, error: 'say what to change and why' };
196
+ // a ✦ lives on an initiative; with none to hang it on, the area waits for the PM in the digest
197
+ if (!ini) { append(stateDir, { ev: 'wawan', area, why: `harness change proposed: ${t}` }, now); return { ok: true, id: null }; }
198
+ const PR = require('./proposals.js');
199
+ const id = PR.idOf(ini, 'harness', 'improve', `${area}:${new Date(now).toISOString().slice(0, 10)}`);
200
+ PR.append(stateDir, { by: 'agent:improve' }, { kind: 'propose', ini, board: '', run, id, group: 'harness', type: 'improve', section: 'check',
201
+ title: 'Change the harness', why: one(`PMOS's improvement loop saw this repeat in ${area}. Only you change a skill, an agent rule or a gate: ${t}`, 300),
202
+ sources: [], items: [{ id: area, title: one(t, 120) }], data: { area, next: one(t, 140) }, at: new Date(now).toISOString() });
203
+ append(stateDir, { ev: 'wawan', area, why: `harness change proposed under ✦ (${id})` }, now);
204
+ return { ok: true, id };
205
+ }
206
+ function undo(stateDir, root, ref, { now = Date.now(), kind = 'undo', ws = null } = {}) {
207
+ if (!RE_REF.test(String(ref || ''))) return { ok: false, error: 'not an improvement lesson' };
208
+ const st = L.fold(ledgerOf(stateDir)); const les = st.lessons.get(ref);
209
+ if (!les) return { ok: false, error: 'no lesson was applied under that id' };
210
+ if (les.undone) return { ok: true, already: true };
211
+ const core = memoryCore();
212
+ if (core) { const r = core.write(root, { op: 'remove', old: les.text, by: 'agent:improve' }); if (!r.ok && !/no entry|not found|matches no/i.test(r.error || '')) return { ok: false, error: r.error }; }
213
+ append(stateDir, { ev: 'undone', ref }, now);
214
+ const A = require('./autonomy.js');
215
+ const r = A.recordSetback(stateDir, { job: JOB, product: ws, ref, kind }, { now });
216
+ return { ok: true, demoted: r && r.demoted ? r.demoted : null };
217
+ }
218
+
219
+ module.exports = { LEDGER, SIGNALS, JOB, ORIGIN, STALE_DAYS, off, isSelf, create, lesson, propose, undo, prompt, selfStage };
@@ -95,6 +95,12 @@ const LEDGERS = Object.freeze({
95
95
  r('lib/briefing-premium.js', 'agent-runs.jsonl', 'the briefing'),
96
96
  r('repo:scripts/check-verify-queue.js', 'agent-runs.jsonl', 'what verification is owed')] },
97
97
  // check-verify-queue.js COUNTS the queue (a CI report) and is not a reader; verifier.js takes the next merged run that owes a verdict (T4)
98
+ // improve-loop-engine: the self-improvement loop's own ledgers. A product's lessons (the workspace job) and PMOS's own cases and fixes (the
99
+ // cloud trigger through scripts/improve.js). Two scopes of one loop, so two concepts.
100
+ '<state>/improve.jsonl': { concept: 'improve-product', owner: 'lib/improve-runs.js', readers: [
101
+ r('lib/improve-cli.js', 'L.digest', '`pmos improve status`: what the loop kept, reverted, tried or waits on in this product')] },
102
+ 'repo:planning/improve/loop.jsonl': { concept: 'improve-self', owner: 'repo:scripts/improve.js', readers: [
103
+ r('lib/improve-runs.js', 'L.LEDGER', "products start learning only once PMOS's own loop passed stage 2 (selfStage)")] },
98
104
  'repo:planning/runs/verify-queue.jsonl': { concept: 'verify-requests', owner: 'repo:scripts/verify-queue.js', readers: [
99
105
  r('repo:scripts/verifier.js', 'deriveQueue', 'the verifier after merge: the next merged run to grade')] },
100
106
  'repo:planning/runs/evals.jsonl': { concept: 'review-verdicts', owner: 'repo:scripts/record-eval.js', readers: [
@@ -143,6 +149,8 @@ const JOBS = Object.freeze([
143
149
  q('report-design', 'lib/routes-report-design.js', ['<state>/design.jsonl']),
144
150
  q('report-structure', 'lib/routes-report-structure.js', ['<state>/structure.jsonl']),
145
151
  q('team', 'lib/team-runs.js', ['<state>/team.jsonl'], ['<state>/team.jsonl', 'initiative records']),
152
+ q('improve', 'lib/improve-runs.js', ['<state>/improve.jsonl', '<state>/autonomy.jsonl', props], ['<state>/improve-signals.jsonl', '<state>/improve.jsonl', 'repo:planning/improve/loop.jsonl'],
153
+ 'step 5; one headless run at a time; a lesson is a curated-memory entry with Undo, a harness change only a ✦'),
146
154
  q('scan', 'lib/scan-run.js', ['<state>/scan.jsonl'], ['public web']),
147
155
  q('idle-lab', 'lib/idle-lab-engine.js', ['<runtime>/idle-lab.jsonl', props], [props]),
148
156
  ai('past-repeat', 'lib/past-repeat.js', [props], ['repo:DECISIONS.md']),
@@ -153,6 +161,7 @@ const JOBS = Object.freeze([
153
161
  ai('rehearse', 'lib/rehearse-guard.js', [], ['task links']),
154
162
  ai('next-prompt', 'lib/next-prompt.js', []),
155
163
  ai('sharpen-prompt', 'lib/next-prompt.js', []),
164
+ { id: 'improve-self', kind: 'script', module: 'repo:scripts/improve.js', reads: ['repo:planning/improve/signals.jsonl'], writes: ['repo:planning/improve/loop.jsonl'] },
156
165
  { id: 'log-run', kind: 'script', module: 'repo:scripts/log-run.js', reads: [], writes: ['repo:planning/runs/agent-runs.jsonl', 'repo:planning/runs/verify-queue.jsonl'] },
157
166
  ]);
158
167
 
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+ /* lab-present.js — present mode (live round W3, initiative live-round-present): one prototype round as a clean screen for GET /api/lab/present
3
+ * (lib/routes-lab.js) and the page GET /pm/present (premium-present.html, pm/cozy-present.js). It reads the same proposal fold as the
4
+ * compare view (lib/idle-lab.js compareOf), so present mode keeps no state of its own.
5
+ *
6
+ * presentOf(P, id, { titleOf }) PURE → { ini, board, id, title, round, frames: [{ key, title, file }] } | null
7
+ */
8
+ /**
9
+ * PURE. One prototype round as a clean screen: the initiative title, the round number and its frames, nothing else.
10
+ * P lib/proposals.js fold; id: a prototyped (a first round: every specimen) or improved (a later round: its one file) proposal id
11
+ * → { ini, board, id, title, round, frames: [{ key, title, file }] } | null
12
+ */
13
+ function presentOf(P, id, { titleOf = () => '' } = {}) {
14
+ if (!P) return null;
15
+ const p = P.props.get(id);
16
+ if (!p || (p.group !== 'prototyped' && p.group !== 'improved') || !p.data) return null;
17
+ const frames = p.group === 'prototyped'
18
+ ? (p.data.specimens || []).filter((s) => s && s.file).map((s) => ({ key: String(s.key || ''), title: String(s.title || ''), file: s.file }))
19
+ : p.data.file ? [{ key: String(p.data.base || ''), title: String(p.data.changed || ''), file: p.data.file }] : [];
20
+ if (!frames.length) return null;
21
+ return { ini: p.ini, board: p.board || '', id: p.id, title: titleOf(p.ini) || p.ini, round: p.group === 'improved' ? p.data.round : 1, frames };
22
+ }
23
+
24
+ module.exports = { presentOf };
@@ -95,6 +95,9 @@ const VERBS = Object.freeze({
95
95
  // Not a pm-os-absorb verb (run: null): the role-agent team (brief agent-team, 2026-11-08) added it through the same table.
96
96
  team: Object.freeze({ module: 'team-cli.js', run: null, guide: 'cli.md',
97
97
  help: 'pmos team roles|dispatch|status|pause|resume — the role agents under the chief of staff: who owns what, who works on what (pmos team help)' }),
98
+ // Not a pm-os-absorb verb (run: null): the self-improvement loop (improve-loop-engine, 2026-11-17) added it through the same table.
99
+ improve: Object.freeze({ module: 'improve-cli.js', run: null, guide: 'cli.md',
100
+ help: 'pmos improve status|lesson|propose … — the improvement loop in this product: what it found, what it learned, what waits for you (pmos improve help)' }),
98
101
  ai: Object.freeze({ module: 'ai-cli.js', run: null, guide: 'cli.md',
99
102
  help: 'pmos ai status|off|on|log … — the AI jobs: their kill switch, replay state and audit (pmos ai help)' }),
100
103
  // Not a pm-os-absorb verb (run: null): the AI-ideas round (2026-11-03, feature 5, plan-rehearsal) added it through the same table.
@@ -11,7 +11,7 @@
11
11
  * line where the work is.
12
12
  * GET /api/autonomy/ahead?ws&ini&title → { ok, ws, ini, outcome: { date, metric, src } | null, jobs: [{ date, name, src }] }
13
13
  * the initiative's dated things only the server reads, for the Viewer's Coming up list (lib/coming-up.js; batch 29 item 7)
14
- * POST /api/autonomy/undo { ws, ref } → { ok, back, demoted? } Undo of one change: a Driver proposal (p-…) or a ✦ batch (pk-…)
14
+ * POST /api/autonomy/undo { ws, ref } → { ok, back, demoted? } Undo of one change: a Driver proposal (p-…), a ✦ batch (pk-…) or a lesson (im-…)
15
15
  * POST /api/autonomy/seen { ws, job, product, until } → { ok } Home said the demotion once
16
16
  * GET /api/autonomy/kinds → { ok, kinds: [{ kind, label, made, kept, undone, auto, set, way, until }], showUntil }
17
17
  * How Claude decides (Settings › Claude, boards AwG and AwG2), over every product's state folders: lib/autonomy.js kindsOf. The PM
@@ -66,7 +66,12 @@ async function undoRef(ctx, w, ref, g) {
66
66
  const r = RP.undoCore({ ...ctx, runtimeDir: runtimeOf(ctx) }, { w, fr, board, file: null }, g, ref);
67
67
  return r.ok ? { status: 200, body: { ok: true, back: r.back > 0 || !r.kept, ...(r.demoted ? { demoted: r.demoted } : {}) } } : bad(r.status, r.error);
68
68
  }
69
- return bad(400, 'ref is a Driver proposal id (p-…) or a ✦ batch id (pk-…)');
69
+ if (/^im-[0-9a-f]{10}$/.test(ref)) { // a lesson the improvement loop applied (lib/improve-runs.js): the memory entry goes, a setback is recorded
70
+ const dir = ctx.stateDirFor ? ctx.stateDirFor(w) : null;
71
+ const r = dir ? require('./improve-runs.js').undo(dir, w.root, ref, { ws: w.id }) : { ok: false, error: 'no state folder' };
72
+ return r.ok ? { status: 200, body: { ok: true, back: true, ...(r.demoted ? { demoted: r.demoted } : {}) } } : bad(404, r.error);
73
+ }
74
+ return bad(400, 'ref is a Driver proposal id (p-…), a ✦ batch id (pk-…) or a lesson id (im-…)');
70
75
  }
71
76
 
72
77
  /* the Driver's kinds said as an act: "problem: Checkout tickets lack…" reads "Wrote the problem: Checkout tickets lack…" */
@@ -5,6 +5,7 @@
5
5
  *
6
6
  * GET /api/lab?ws&board → { ok, lab } lab: lib/idle-lab.js labOf (null: nothing ran this week and nothing waits)
7
7
  * GET /api/lab/compare?ws&board&id[&key] → { ok, compare } lib/idle-lab.js compareOf (404 when the prototype is gone)
8
+ * GET /api/lab/present?ws&board&id → { ok, present } lib/lab-present.js presentOf: the round's frames for present mode (GET /pm/present)
8
9
  * GET /api/lab/specimen?file → text/html, a specimen from <runtime>/idle-lab/specimens/, served sandboxed (no scripts that can
9
10
  * reach PMOS: CSP sandbox without allow-same-origin, no network but the fonts)
10
11
  * POST /api/lab/keep { ws, id } → { ok, batch, said } ✓ on a Lab ✦: start keeps it and starts the initiative on its board
@@ -113,6 +114,17 @@ const READS = {
113
114
  ctx.json(res, { ok: true, compare: c });
114
115
  return true;
115
116
  },
117
+ '/api/lab/present': (ctx, res, url) => {
118
+ const w = wsOf(ctx, url.searchParams.get('ws')); if (!w) return fail(ctx, res, 404, 'no such workspace');
119
+ const dir = dirOf(ctx, w), id = url.searchParams.get('id') || '';
120
+ if (!dir || !ID_RE.test(id)) return fail(ctx, res, 400, 'id names a prototype');
121
+ const T = titles(w);
122
+ const v = require('./lab-present.js').presentOf(PR.read(dir), id, { titleOf: (ini) => (T.get(ini) || {}).title || '' });
123
+ if (!v) return fail(ctx, res, 404, 'That prototype is no longer here');
124
+ for (const f of v.frames) f.url = LAB.specimenUrl(f.file);
125
+ ctx.json(res, { ok: true, present: v });
126
+ return true;
127
+ },
116
128
  '/api/lab/specimen': (ctx, res, url) => {
117
129
  const f = LAB.specimenPath(ctx.runtimeDir, url.searchParams.get('file') || '');
118
130
  let html = null;
@@ -101,6 +101,9 @@ const DEFS = Object.freeze({
101
101
  // and the monthly credit cap in US dollars. At the cap Claude pauses. `pmos grill mode|cap` reads and sets them.
102
102
  'grill.mode': one('checks', 'computer', ['full', 'exits', 'off'], 'full'),
103
103
  'grill.cap': { section: 'checks', scope: 'computer', type: 'dollars', min: 0, max: 500, def: 10 },
104
+ // Background use with no dollar limit (Wawan 2026-11-17: the runs use the subscription plan). On: the step-5 spend hold never holds
105
+ // (lib/bg-queue.js spendHold); the usage-limit hold a failed run leaves is the brake. `pmos grill cap unlimited` sets it.
106
+ 'ai.unlimited': bool('checks', 'computer', false),
104
107
  // The AI jobs' kill switch (lib/ai-guard.js): 'ai.on' false stops every AI job; 'ai.off' lists the jobs that are off one by one.
105
108
  // `pmos ai off [job]` and `pmos ai on [job]` set them; PMOS_AI=off wins over both.
106
109
  'ai.on': bool('checks', 'computer', true),
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.577.0",
3
+ "version": "0.579.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.577.0",
9
+ "version": "0.579.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/sdk": "^1.3.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.577.0",
3
+ "version": "0.579.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -8,7 +8,7 @@
8
8
  * openCompare({ where: { ws, board }, id, key?, H? }) the compare view in the Viewer: the ✦ line, the columns (Production, Design,
9
9
  * Prototype), "Where they differ" and History. A column whose source is not proven is left out with one line
10
10
  * why (lib/idle-lab.js PROVEN). A press on a round in History puts it in the Prototype column. ✓ and ✕ in the
11
- * header keep or drop the round shown.
11
+ * header keep or drop the round shown; ⤢ presents it on a clean screen in a new tab (GET /pm/present).
12
12
  * Every specimen loads from GET /api/lab/specimen in a sandboxed frame: it cannot reach PMOS. Nothing is written before the PM's ✓. */
13
13
  import { pmGet, pmPost } from './http.js';
14
14
 
@@ -16,7 +16,7 @@ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&':
16
16
  const SVG = (d, w = 16, sw = 1.8) => `<svg aria-hidden="true" width="${w}" height="${w}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${sw}" stroke-linecap="round" stroke-linejoin="round"><path d="${d}"/></svg>`;
17
17
  export const I = {
18
18
  proto: 'M3 4h18v14H3zM3 9h18', round: 'M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5', scan: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18M12 3a15 15 0 0 1 0 18M3 12h18',
19
- open: 'M7 17 17 7M8 7h9v9', check: 'M5 12l5 5 9-10', x: 'M6 6l12 12M18 6L6 18',
19
+ open: 'M7 17 17 7M8 7h9v9', check: 'M5 12l5 5 9-10', x: 'M6 6l12 12M18 6L6 18', present: 'M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7',
20
20
  };
21
21
  const GROUPS = ['prototyped', 'improved', 'scanned'];
22
22
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
@@ -91,8 +91,13 @@ function bodyHtml(c) {
91
91
  + `<div class="lab-below">${pins}${hist}</div></div>`;
92
92
  }
93
93
  function presses(c) {
94
- return c && c.state === 'open' ? [{ act: 'drop', label: 'Drop this round', icon: I.x }, { act: 'keep', label: 'Keep this round', icon: I.check, blue: true }] : [];
94
+ if (!c) return [];
95
+ // ⤢ present (live round W3): the round shown, on a clean screen in a new tab (GET /pm/present, pm/cozy-present.js)
96
+ const present = { act: 'present', label: 'Present this round', icon: I.present };
97
+ return c.state === 'open' ? [present, { act: 'drop', label: 'Drop this round', icon: I.x }, { act: 'keep', label: 'Keep this round', icon: I.check, blue: true }] : [present];
95
98
  }
99
+ /** The present page's address for the round shown. */
100
+ export const presentUrl = (at, c) => '/pm/present?ws=' + encodeURIComponent((at && at.ws) || '') + '&board=' + encodeURIComponent((at && at.board) || c.board || '') + '&id=' + encodeURIComponent(c.id);
96
101
  function draw() {
97
102
  const VW = window.czViewer, b = VW && VW.body(), cur = VW && VW.current();
98
103
  if (!b || !cur || cur.id !== 'lab:cmp' || !C.c) return;
@@ -111,6 +116,7 @@ async function load() {
111
116
  async function act(a) {
112
117
  const c = C.c, at = C.at || {}; if (!c) return;
113
118
  const say = (m, u) => { if (C.H && C.H.toast) C.H.toast(m, u); };
119
+ if (a === 'present') { window.open(presentUrl(at, c), '_blank', 'noopener'); return; }
114
120
  if (a === 'keep') {
115
121
  const r = await pmPost('/api/proposals/keep', { ws: at.ws, board: at.board || c.board, initiative: c.ini, ids: [c.id] }).catch(() => null);
116
122
  if (!r || r.ok === false) { say((r && r.error) || 'Nothing was kept.'); return; }
@@ -0,0 +1,33 @@
1
+ /* pm/cozy-present.css — present mode (premium-present.html, cozy-present.js; live round W3). A dark ground to the edge, like the audience
2
+ * tab: the frames are the only light on the screen. Type from the role tokens; colours from the cozy tokens. */
3
+ body.cz.prs-page { margin: 0; min-height: 100vh; background: var(--cz-c-17191c); color: var(--cz-c-eceef1); }
4
+ .prs { display: flex; flex-direction: column; height: 100vh; height: 100dvh; padding: 16px 24px 24px; box-sizing: border-box; gap: 12px; }
5
+ .prs-hd { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
6
+ .prs-title { margin: 0; font-size: var(--fs-page); line-height: var(--lh-page); font-weight: var(--fw-page); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
7
+ .prs-round { flex: none; font-size: var(--fs-meta); line-height: var(--lh-meta); font-weight: var(--fw-meta); color: var(--cz-c-9ea4ad); }
8
+ .prs-strip { flex: 1; min-height: 0; display: grid; grid-template-columns: repeat(var(--n, 3), minmax(0, 1fr)); gap: 16px; }
9
+ .prs-fr { position: relative; min-width: 0; min-height: 0; border-radius: 16px; overflow: hidden; background: var(--cz-c-ffffff); }
10
+ .prs-fr iframe { display: block; width: 100%; height: 100%; border: 0; background: var(--cz-c-ffffff); }
11
+ .prs-tap { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; padding: 0; background: transparent; cursor: zoom-in; }
12
+ .prs-tap:focus-visible, .prs-back:focus-visible { outline: 3px solid var(--cz-c-6aaaf0); outline-offset: -3px; }
13
+ .prs-key { position: absolute; left: 12px; bottom: 12px; min-width: 28px; height: 28px; padding: 0 8px; box-sizing: border-box; border-radius: 14px;
14
+ display: inline-flex; align-items: center; justify-content: center; pointer-events: none;
15
+ font-size: var(--fs-label); line-height: var(--lh-label); font-weight: var(--fw-label); background: var(--cz-c-17191c); color: var(--cz-c-eceef1); opacity: .85; }
16
+ .prs-none { margin: 0; font-size: var(--fs-body); line-height: var(--lh-body); color: var(--cz-c-9ea4ad); }
17
+ /* one frame fills the screen: the header goes, the frame takes the whole page */
18
+ .prs:not([data-full=""]) { padding: 0; gap: 0; }
19
+ .prs:not([data-full=""]) .prs-hd { display: none; }
20
+ .prs:not([data-full=""]) .prs-strip { display: block; }
21
+ .prs-fr.full { width: 100%; height: 100%; border-radius: 0; }
22
+ .prs-back { position: absolute; top: 12px; right: 12px; width: 40px; height: 40px; border: 0; border-radius: 20px; display: inline-flex; align-items: center; justify-content: center;
23
+ background: var(--cz-c-17191c); color: var(--cz-c-eceef1); opacity: .8; cursor: zoom-out; }
24
+ .prs-back:hover { opacity: 1; }
25
+ /* a phone: the frames stack, each tall enough to read, and the page scrolls */
26
+ @media (max-width: 640px) {
27
+ .prs { height: auto; min-height: 100dvh; padding: 12px 16px 16px; }
28
+ .prs-title { font-size: var(--fs-panel); line-height: var(--lh-panel); }
29
+ .prs-strip { grid-template-columns: minmax(0, 1fr); }
30
+ .prs-fr { height: 78dvh; }
31
+ .prs:not([data-full=""]) { height: 100dvh; }
32
+ .prs-fr.full { height: 100dvh; }
33
+ }
@@ -0,0 +1,74 @@
1
+ /* pm/cozy-present.js — present mode (live round W3, initiative live-round-present; premium-present.html at GET /pm/present?ws&board&id).
2
+ *
3
+ * A prototype round on a shared screen: its frames side by side (A, B, C of a first round, or the one file of a later round), the
4
+ * initiative title and the round number. Nothing else: no keep or drop, no History, no nav, no Adler. It reads GET /api/lab/present and
5
+ * loads every frame from GET /api/lab/specimen in a sandboxed frame (allow-scripts only: a specimen cannot reach PMOS).
6
+ *
7
+ * A tap on a frame, or its key (1 to 3, or A to C), fills the screen with that frame. In full screen the frame can be used; the arrow
8
+ * keys move to the next or the earlier frame; Esc or the ⤡ press goes back to all of them. Keys reach the page only while the focus is
9
+ * not inside the frame, so the ⤡ press is always there.
10
+ *
11
+ * keyOf(e, n) → { go: index } | { back: true } | { step: ±1 } | null (pure, the key map)
12
+ * stripHtml(v, full) → html (pure, what the page draws) */
13
+ import { pmGet } from './http.js';
14
+
15
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
16
+ const BACK = '<svg aria-hidden="true" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"/></svg>';
17
+
18
+ /** The key map. n: how many frames. Digits 1..n and letters a.. pick a frame; Esc goes back; arrows step (in full screen only). */
19
+ export function keyOf(e, n, full) {
20
+ if (!e || e.metaKey || e.ctrlKey || e.altKey) return null;
21
+ const k = String(e.key || '');
22
+ if (k === 'Escape') return full != null ? { back: true } : null;
23
+ if (/^[1-9]$/.test(k) && +k <= n) return { go: +k - 1 };
24
+ if (/^[a-z]$/i.test(k)) { const i = k.toLowerCase().charCodeAt(0) - 97; if (i < n) return { go: i }; }
25
+ if (full != null && (k === 'ArrowRight' || k === 'ArrowDown')) return { step: 1 };
26
+ if (full != null && (k === 'ArrowLeft' || k === 'ArrowUp')) return { step: -1 };
27
+ return null;
28
+ }
29
+
30
+ /** The frames. full: the index shown full screen, or null for all of them side by side. */
31
+ export function stripHtml(v, full) {
32
+ return v.frames.map((f, i) => {
33
+ const on = full === i, off = full != null && !on;
34
+ const label = (f.key || String(i + 1)) + (f.title ? ', ' + f.title : '');
35
+ return `<section class="prs-fr${on ? ' full' : ''}"${off ? ' hidden' : ''} aria-label="${esc(label)}">`
36
+ + `<iframe src="${esc(f.url)}" sandbox="allow-scripts" title="${esc(label)}" tabindex="${on ? 0 : -1}"></iframe>`
37
+ + (on ? `<button type="button" class="prs-back" data-prs-back aria-label="Back to all frames">${BACK}</button>`
38
+ : `<button type="button" class="prs-tap" data-prs-go="${i}" aria-label="${esc('Fill the screen with ' + label)}"></button>`)
39
+ + (f.key ? `<span class="prs-key" aria-hidden="true">${esc(f.key)}</span>` : '')
40
+ + '</section>';
41
+ }).join('');
42
+ }
43
+
44
+ const S = { v: null, full: null };
45
+ const $ = (id) => document.getElementById(id);
46
+ function draw() {
47
+ const v = S.v, strip = $('prsStrip'); if (!v || !strip) return;
48
+ $('prs').dataset.full = S.full == null ? '' : String(S.full);
49
+ strip.style.setProperty('--n', String(v.frames.length));
50
+ strip.innerHTML = stripHtml(v, S.full);
51
+ const b = strip.querySelector('[data-prs-back]'); if (b) b.focus({ preventScroll: true });
52
+ }
53
+ function go(i) { if (!S.v) return; S.full = i == null ? null : (i + S.v.frames.length) % S.v.frames.length; draw(); }
54
+
55
+ async function boot() {
56
+ const q = new URLSearchParams(location.search);
57
+ const r = await pmGet('/api/lab/present?ws=' + encodeURIComponent(q.get('ws') || '') + '&board=' + encodeURIComponent(q.get('board') || '') + '&id=' + encodeURIComponent(q.get('id') || ''));
58
+ if (!r || r.ok === false || !r.present) { $('prsStrip').innerHTML = `<p class="prs-none">${esc((r && r.error) || 'The prototype could not be read.')}</p>`; return; }
59
+ S.v = r.present;
60
+ $('prsTitle').textContent = S.v.title;
61
+ $('prsRound').textContent = 'Round ' + S.v.round;
62
+ document.title = S.v.title + ' · PMOS';
63
+ draw();
64
+ $('prsStrip').addEventListener('click', (e) => {
65
+ if (e.target.closest('[data-prs-back]')) { go(null); return; }
66
+ const t = e.target.closest('[data-prs-go]'); if (t) go(+t.dataset.prsGo);
67
+ });
68
+ document.addEventListener('keydown', (e) => {
69
+ const a = keyOf(e, S.v.frames.length, S.full); if (!a) return;
70
+ e.preventDefault();
71
+ if (a.back) go(null); else if (a.step) go(S.full + a.step); else go(a.go);
72
+ });
73
+ }
74
+ if (typeof document !== 'undefined' && document.getElementById('prs')) boot();
@@ -0,0 +1,21 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="pmos-nonce" content="" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
7
+ <title>Present · PMOS</title>
8
+ <!-- Present mode (live round W3, initiative live-round-present): GET /pm/present?ws&board&id. A prototype round's frames on a shared
9
+ screen, with the initiative title and the round number only. It makes no press: no keep, no drop, no nav. pm/cozy-present.js draws it. -->
10
+ <link rel="preload" href="/vendor/plus-jakarta-sans-var.woff2" as="font" type="font/woff2" crossorigin />
11
+ <link rel="stylesheet" href="/pm/cozy.css" />
12
+ <link rel="stylesheet" href="/pm/cozy-present.css" />
13
+ </head>
14
+ <body class="cz prs-page">
15
+ <main class="prs" id="prs" data-full="">
16
+ <header class="prs-hd"><h1 class="prs-title" id="prsTitle"></h1><span class="prs-round" id="prsRound"></span></header>
17
+ <div class="prs-strip" id="prsStrip" aria-live="polite"></div>
18
+ </main>
19
+ <script type="module" src="/pm/cozy-present.js"></script>
20
+ </body>
21
+ </html>
@@ -165,8 +165,9 @@ const WIDE = new Set([
165
165
  * - server.js: the changed lines (git diff -U0). A comment or blank line reaches nothing. A line inside one route block
166
166
  * of handleRequest (an `if (p === '/api/…')` statement up to the next statement at its indent) reaches that route. A
167
167
  * line inside a top-level function reaches whatever uses that function, followed by name to the route blocks and the
168
- * functions that use it. Anything else (top-level setup, middleware between route blocks, a page route, a name used
169
- * outside any function or route block) reaches every suite.
168
+ * functions that use it. The one-line page map (`const PAGES = { … }`) reaches the suites that name an entry the diff
169
+ * adds, drops or repoints, by its path or its page file. Anything else (top-level setup, middleware between route blocks,
170
+ * a page route, a name used outside any function or route block) reaches every suite.
170
171
  * - lib/routes-<x>.js (a route module that lib/route-modules.js loads): every '/api/…' route the file names under the
171
172
  * prefixes it declares (a route it only calls through ctx is left out). With no prefixes it can read: every route it names.
172
173
  * - lib/route-modules.js, when the diff only adds module names to its list: what each added lib/routes-<x>.js reaches. Any other change to it is the rule below.
@@ -404,6 +405,10 @@ function traceChanges(changes, ctx) {
404
405
  if (raw === undefined || !raw.trim()) continue; // a comment or a blank line reaches nothing
405
406
  const b = blockAt(n);
406
407
  if (b) { const w = routes(b.keys, `server.js:${n}`); if (w) return w; continue; }
408
+ // the page map (`const PAGES = { '/path': 'page.html', … }`, one line): a change to it reaches only the suites that name an entry
409
+ // it adds, drops or points elsewhere, by its path or its page file (live round W3: adding /pm/present reached all 511 suites)
410
+ const pm = pagesChanged(raw);
411
+ if (pm) { for (const x of pm) for (const sfile of list) if ((get(sfile) || '').includes(x)) picked.add(sfile); continue; }
407
412
  const own = fnAt(n);
408
413
  if (own && own.name !== 'handleRequest' && optionOnly(own, lines)) continue;
409
414
  if (own && own.name !== 'handleRequest') { const w = useOf(own.name); if (w) return `${own.name} (server.js:${n}) is used by ${w}`; continue; }
@@ -419,6 +424,20 @@ function traceChanges(changes, ctx) {
419
424
  }
420
425
  return null;
421
426
  };
427
+ // The entries a changed PAGES line adds, drops or repoints, as their paths and page files; null when the line is not that map, or the
428
+ // old map is not one line the diff removed (then the line stays wide).
429
+ const serverOld = ((changes.find((c) => c.file === 'server.js') || {}).old) || null;
430
+ const pagesChanged = (raw) => {
431
+ const isMap = (t) => /^\s*const PAGES = \{.*\};\s*$/.test(t);
432
+ if (!isMap(raw) || !serverOld) return null;
433
+ const was = serverOld.filter(isMap);
434
+ if (was.length !== 1) return null;
435
+ const mapOf = (t) => new Map([...t.matchAll(/'(\/[^']*)'\s*:\s*'([^']+)'/g)].map((m) => [m[1], m[2]]));
436
+ const a = mapOf(was[0]), b = mapOf(raw), out = new Set();
437
+ for (const [k, v] of b) if (a.get(k) !== v) { out.add(k); out.add(v); if (a.has(k)) out.add(a.get(k)); }
438
+ for (const [k, v] of a) if (!b.has(k)) { out.add(k); out.add(v); }
439
+ return out;
440
+ };
422
441
  // A line inside a top-level statement that builds one lib module (`const x = require('./lib/m.js').create({ ... })`): the module's file.
423
442
  const wiringOf = (n) => {
424
443
  const { C } = parseServer();
@@ -700,7 +719,7 @@ function changedSuites(list, ref, { exact = false } = {}) {
700
719
  const changes = files.map((file) => {
701
720
  if (file !== 'server.js' && file !== 'lib/route-modules.js' && !/^lib\/[^/]+\.js$/.test(file)) return { file };
702
721
  const d = git('diff', '-U0', base, '--', path.join(DIR, file));
703
- return { file, lines: d == null ? null : diffLines(d) };
722
+ return { file, lines: d == null ? null : diffLines(d), ...(file === 'server.js' && d != null ? { old: oldLines(d) } : {}) };
704
723
  });
705
724
  const read = (f) => { try { return fs.readFileSync(path.join(DIR, f), 'utf8'); } catch { return null; } };
706
725
  const browser = new Set([...FILES.panels, ...FILES.ui]);
@@ -728,6 +747,11 @@ function changedDeps(diff, changed) {
728
747
  return names.length ? [...new Set(names)] : null;
729
748
  }
730
749
 
750
+ /* The old-side text of the lines a `git diff -U0` removes or changes (without the leading '-'). */
751
+ function oldLines(diff) {
752
+ return String(diff).split('\n').filter((l) => /^-/.test(l) && !/^---/.test(l)).map((l) => l.slice(1));
753
+ }
754
+
731
755
  /* The new-side line numbers a `git diff -U0` touches. A pure removal counts the lines on both sides of where it was. */
732
756
  function diffLines(diff) {
733
757
  const out = [];