create-pmos 0.849.0 → 0.850.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,130 @@
1
+ 'use strict';
2
+ /* routes-spec-drift.js — Library › Drift: "Spec and code no longer match" over HTTP (initiative spec-code-drift, idea A495; lib/spec-code-drift.js).
3
+ * lib/routes-drift.js hands it every /api/spec-drift request, so the route table does not change.
4
+ *
5
+ * GET /api/spec-drift → { ok, on, specs, compared, drifted, rows, running } this week's mismatches of every open
6
+ * product. rows is [] when nothing differs (zero is silence). A product with no result for
7
+ * this week starts its check in the background (a worker thread: the page never waits on git)
8
+ * and `running` names how many are being read; the next open shows them.
9
+ * POST /api/spec-drift/act { ws, id, what } → { ok, task } what: 'code' (fix the code) or 'spec' (update the spec). A work item is added
10
+ * to the spec's initiative by the boards' own Add a task, and the row says so.
11
+ * POST /api/spec-drift/undo { ws, id } → { ok } the work item is removed again (the boards' own delete) and the row is open again.
12
+ *
13
+ * ONCE A WEEK. The check of a product runs at most once in a week (the Monday that starts it, local time): a second open in the same week
14
+ * reads the ledger. `pmos drift spec --now` runs it again by hand. THE SWITCH: PMOS_SPEC_DRIFT=off answers { ok, on: false } and every POST
15
+ * 409. WHO WRITES: a POST with an agent session header is refused (403; the chat uses `pmos drift spec fix|update|undo`); pm-guard
16
+ * requirePagePress checks the page. Nothing is sent outside. */
17
+ const path = require('path');
18
+ const { Worker } = require('worker_threads');
19
+ const guard = require('./pm-guard.js');
20
+ const S = require('./spec-code-drift.js');
21
+
22
+ const prefixes = ['/api/spec-drift'];
23
+ const running = new Set();
24
+ const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
25
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
26
+ const nowMs = (ctx) => { const t = Date.parse((ctx.env || process.env).PMOS_SPEC_DRIFT_NOW || ''); return Number.isFinite(t) ? t : Date.now(); };
27
+ const wsKey = (root) => require('./driver.js').wsIdOf(root);
28
+
29
+ /** The check of one repository in a worker thread of this process, so the server never blocks on git. It calls the same
30
+ * check() export in-process; no new program is started. Tests replace runner.run. */
31
+ const WORKER_SRC = `
32
+ const { parentPort, workerData } = require('worker_threads');
33
+ let out;
34
+ try { out = require(workerData.mod).check(workerData.root); } catch (e) { out = { ok: false, error: String((e && e.message) || e).slice(0, 200) }; }
35
+ parentPort.postMessage(out);
36
+ `;
37
+ const runner = {
38
+ run: (root) => new Promise((resolve) => {
39
+ let done = false;
40
+ const end = (r) => { if (!done) { done = true; clearTimeout(timer); resolve(r); } };
41
+ let w;
42
+ try { w = new Worker(WORKER_SRC, { eval: true, workerData: { mod: path.join(__dirname, 'spec-code-drift.js'), root } }); } catch (e) { end({ ok: false, error: 'the check could not start' }); return; }
43
+ const timer = setTimeout(() => { end({ ok: false, error: 'the check took too long' }); w.terminate(); }, 10 * 60 * 1000);
44
+ if (timer.unref) timer.unref();
45
+ w.once('message', (r) => end(r && typeof r === 'object' ? r : { ok: false, error: 'the check did not answer' }));
46
+ w.once('error', (e) => end({ ok: false, error: String((e && e.message) || e).slice(0, 200) }));
47
+ w.once('exit', () => end({ ok: false, error: 'the check did not answer' }));
48
+ }),
49
+ };
50
+
51
+ function products(ctx) {
52
+ const out = [], seen = new Set();
53
+ for (const w of (ctx.workspaceList ? ctx.workspaceList() : []) || []) {
54
+ if (!w || !w.root || seen.has(path.resolve(w.root))) continue;
55
+ seen.add(path.resolve(w.root));
56
+ out.push({ w, key: wsKey(w.root) });
57
+ }
58
+ return out;
59
+ }
60
+
61
+ /** Start this week's check of a product unless it has one or one is running. Its only write is the week line. */
62
+ function startWeek(ctx, dir, p, week) {
63
+ if (running.has(p.key)) return null;
64
+ running.add(p.key);
65
+ const t0 = Date.now();
66
+ return Promise.resolve(runner.run(p.w.root)).then((r) => {
67
+ if (r && r.ok) {
68
+ S.append(dir, { kind: 'week', ws: p.key, week, specs: r.specs, compared: r.compared, items: r.items }, new Date(nowMs(ctx)).toISOString());
69
+ console.log(`${S.TAG} week ws=${p.key} specs=${r.specs} compared=${r.compared} items=${r.items.length} ms=${Date.now() - t0}`);
70
+ } else console.warn(`${S.TAG} check failed ws=${p.key}: ${(r && r.error) || 'no answer'}`);
71
+ }).catch((e) => console.warn(`${S.TAG} check failed ws=${p.key}: ${(e && e.message) || e}`)).finally(() => running.delete(p.key));
72
+ }
73
+
74
+ async function handle(req, res, url, ctx) {
75
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
76
+ const what = url.pathname.replace(/^\/api\/spec-drift\/?/, '');
77
+ const env = ctx.env || process.env;
78
+ const dir = S.dirOf(ctx.runtimeDir);
79
+ const on = !flagOff(env.PMOS_SPEC_DRIFT);
80
+ if (what === '') {
81
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
82
+ if (!on || !dir) return send({ status: 200, body: { ok: true, on: false } });
83
+ const F = S.read(dir), week = S.weekOf(nowMs(ctx));
84
+ const out = { ok: true, on: true, week, specs: 0, compared: 0, drifted: 0, rows: [], running: 0 };
85
+ for (const p of products(ctx)) {
86
+ const v = S.view(F, p.key);
87
+ if (v.week !== week) startWeek(ctx, dir, p, week);
88
+ if (!v.week) continue;
89
+ out.specs += v.specs; out.compared += v.compared; out.drifted += v.drifted;
90
+ for (const r of v.rows) out.rows.push({ ...r, ws: p.w.id, product: p.w.name || p.w.id });
91
+ }
92
+ out.running = products(ctx).filter((p) => running.has(p.key)).length;
93
+ return send({ status: 200, body: out });
94
+ }
95
+ if (what !== 'act' && what !== 'undo') return send(bad(404, 'no such spec-drift route'));
96
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
97
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'The chat uses pmos drift spec fix, update or undo.'));
98
+ const rd = await ctx.readJson(req);
99
+ if (!rd.ok) return send(bad(400, 'the body is not JSON'));
100
+ const body = rd.body || {};
101
+ const g = guard.requirePagePress(req, body);
102
+ if (!g.ok) return send(bad(g.status, g.error));
103
+ if (!on || !dir) return send(bad(409, 'The weekly spec check is off.'));
104
+ const p = products(ctx).find((x) => x.w.id === body.ws);
105
+ if (!p) return send(bad(404, 'no such product'));
106
+ const F = S.read(dir), v = S.view(F, p.key);
107
+ const row = v.rows.find((r) => r.id === body.id);
108
+ const item = row && (F.weeks.get(p.key).items || []).find((it) => it.id === body.id);
109
+ if (!item) return send(bad(404, 'There is no such row this week.'));
110
+ const at = new Date(nowMs(ctx)).toISOString();
111
+ const CF = require('./capture-file.js');
112
+ if (what === 'act') {
113
+ if (body.what !== 'code' && body.what !== 'spec') return send(bad(400, "what is 'code' (fix the code) or 'spec' (update the spec)"));
114
+ if (row.act) return send(bad(409, 'This row already has a work item.'));
115
+ const work = S.workOf(item, body.what);
116
+ const r = CF.file(ctx, { ws: p.w.id, ini: item.ini, title: work.title, bullet: 'task' }, g);
117
+ if (!r.ok || !r.filed.task) return send(bad(r.status || 409, r.error || 'The initiative has no board to add the task to.'));
118
+ S.append(dir, { kind: 'act', ws: p.key, id: item.id, what: body.what, task: { ws: r.filed.ws, board: r.filed.board, ini: r.filed.ini, task: r.filed.task, title: work.title } }, at);
119
+ console.log(`${S.TAG} act ws=${p.key} id=${item.id} what=${body.what} task=${r.filed.task}`);
120
+ return send({ status: 200, body: { ok: true, task: { id: r.filed.task, title: work.title, initiative: item.ini } } });
121
+ }
122
+ const a = F.acts.get(p.key + '|' + item.id);
123
+ if (!a) return send(bad(409, 'This row has no work item to take back.'));
124
+ if (a.task) CF.unfile(ctx, a.task, g);
125
+ S.append(dir, { kind: 'undo', ws: p.key, id: item.id }, at);
126
+ console.log(`${S.TAG} undo ws=${p.key} id=${item.id}`);
127
+ return send({ status: 200, body: { ok: true } });
128
+ }
129
+
130
+ module.exports = { prefixes, handle, runner, running };
@@ -0,0 +1,334 @@
1
+ 'use strict';
2
+ /* spec-code-drift.js — "Spec and code no longer match" (initiative spec-code-drift, idea A495): once a week, every merged spec (each
3
+ * initiative's done test) is compared with the code as it is now. THE PURE CORE, THE GIT READ and THE ONE WRITER of
4
+ * <runtime>/spec-drift/spec-drift.jsonl. lib/routes-spec-drift.js shows it in Library › Drift; `pmos drift spec` (lib/drift-cli.js) reads
5
+ * and writes the same ledger.
6
+ *
7
+ * WHAT IS COMPARED (structured, no model). A spec is a done test in markdown whose rows name the files that prove them (`x.test.js`
8
+ * "R2", `lib/y.js`). For each row it reads the repository twice from git: THEN, when the spec landed (the commit that added it, or the
9
+ * first later commit that touched the named file, for a build that landed after its spec), and NOW (HEAD). A mismatch is one of:
10
+ * test-gone the test file that proved the rows is gone, and no file with the same name proves them now
11
+ * test-dropped the test file is still there, but it no longer names the row (the case that proved it was taken out)
12
+ * test-changed the test still names the row, but a line that proved it when the spec landed is not there any more (it was rewritten:
13
+ * the spec, or the code, may say something else now). Lines added beside it and comments do not count.
14
+ * file-gone a code file the spec names is gone, and no file with the same name exists now
15
+ * A row that never had its proof (THEN) is not a mismatch: that is the build's gap, not drift. A moved file (same name elsewhere) is not
16
+ * a mismatch. Markdown files are documents, not code: they are not compared. One item per spec, kind and file, with every row it holds.
17
+ *
18
+ * specsOf(root) → [{ ini, title, path }] every markdown done test: initiative records' done_test_path
19
+ * (planning/initiatives, pmos/state/initiatives, state/initiatives, .pmos/initiatives) and the
20
+ * files in planning/done-tests with an `initiative:` line
21
+ * refsOf(rows) PURE → [{ id, check, files: [path] }] the files each row names ("Same file" takes the row above's)
22
+ * compare(specs, git) PURE over a git reader → { specs, compared, items }
23
+ * check(root, { now }) → { ok, specs, compared, items, at } the git read of one repository (git only, writes nothing)
24
+ * dirOf(runtime) · read(dir) · append(dir, line, at) · fold(lines) · weekOf(ms) · view(F, ws, week)
25
+ *
26
+ * THE LEDGER (PRIVATE, in the per-user runtime folder). One line per event, { at, kind, ... }:
27
+ * week { ws, week, specs, compared, items } the week's result for one product (an empty list is a quiet week: nothing shows)
28
+ * act { ws, id, what: 'code'|'spec', task: { ws, board, ini, task, title } } a work item was added for the row (fix the code / update the spec)
29
+ * undo { ws, id } the work item taken back (the task is removed again)
30
+ * Every log line carries [spec-drift]. It calls no model and sends nothing. */
31
+ const fs = require('fs');
32
+ const path = require('path');
33
+ const crypto = require('crypto');
34
+ const { execFileSync } = require('child_process');
35
+
36
+ const TAG = '[spec-drift]';
37
+ const LEDGER = 'spec-drift.jsonl';
38
+ const LINES = new Set(['week', 'act', 'undo']);
39
+ const KINDS = ['test-gone', 'test-dropped', 'test-changed', 'file-gone'];
40
+ const RECORD_DIRS = [['planning', 'initiatives'], ['pmos', 'state', 'initiatives'], ['state', 'initiatives'], ['.pmos', 'initiatives']];
41
+ const DONE_DIR = ['planning', 'done-tests'];
42
+ const ROW_ID = /^[A-Z]{1,3}\d{1,3}[a-z]?$/;
43
+ const TEST_FILE = [/(^|\/)(tests?|__tests__)\//i, /\.(test|spec)\.[^/]+$/i];
44
+ const PATH_RE = /(?:^|[\s`'"(\[])((?:[\w@.-]+\/)*[\w@.-]+\.(?:js|mjs|cjs|ts|tsx|jsx|py|sh|rb|go|rs|java|kt|swift|json|css|html|yml|yaml))(?=$|[\s`'"),.:;\]])/g;
45
+ const SAME = /^\s*(same|the same) (file|test|suite|test file)\b/i;
46
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
47
+
48
+ const isTest = (f) => TEST_FILE.some((re) => re.test(f));
49
+ const names = (text, id) => new RegExp(`(^|[^\\w])${id}([^\\w]|$)`).test(String(text || ''));
50
+ const COMMENT = /^\s*(\/\/|\/\*|\*|#|<!--)/;
51
+ /** The lines of a test file that name the row and are not a comment, spaces folded: what proves the row. */
52
+ const proofLines = (text, id) => (text == null ? [] : String(text).split('\n').filter((l) => !COMMENT.test(l) && names(l, id)).map((l) => l.replace(/\s+/g, ' ').trim()));
53
+ const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/[`*]/g, '').replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
54
+ const short = (day) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(day || '')); return m ? Number(m[3]) + ' ' + MON[Number(m[2]) - 1] : ''; };
55
+ const idOf = (spec, kind, file) => crypto.createHash('sha1').update(spec + '|' + kind + '|' + file).digest('hex').slice(0, 12);
56
+
57
+ /* ── the specs ──────────────────────────────────────────────────────────────────────────────────────────────── */
58
+ function front(text) {
59
+ const m = /^---\n([\s\S]*?)\n---/.exec(String(text || ''));
60
+ const out = {};
61
+ if (!m) return out;
62
+ for (const l of m[1].split('\n')) { const kv = /^([a-z_]+):\s*(.*)$/.exec(l); if (kv) out[kv[1]] = kv[2].replace(/^["']|["']$/g, '').trim(); }
63
+ return out;
64
+ }
65
+ function specsOf(root) {
66
+ const out = new Map();
67
+ for (const rel of RECORD_DIRS) {
68
+ const dir = path.join(root, ...rel);
69
+ let files = [];
70
+ try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')); } catch { continue; }
71
+ for (const f of files) {
72
+ let fm;
73
+ try { fm = front(fs.readFileSync(path.join(dir, f), 'utf8')); } catch { continue; }
74
+ const p = String(fm.done_test_path || '').replace(/^\.?\//, '');
75
+ if (!/\.(md|markdown)$/i.test(p) || out.has(p)) continue;
76
+ out.set(p, { ini: fm.id || f.replace(/\.md$/, ''), title: fm.title || fm.id || f.replace(/\.md$/, ''), path: p });
77
+ }
78
+ }
79
+ const dd = path.join(root, ...DONE_DIR);
80
+ let files = [];
81
+ try { files = fs.readdirSync(dd).filter((f) => f.endsWith('.md')); } catch { files = []; }
82
+ for (const f of files) {
83
+ const p = DONE_DIR.join('/') + '/' + f;
84
+ if (out.has(p)) continue;
85
+ let fm;
86
+ try { fm = front(fs.readFileSync(path.join(dd, f), 'utf8')); } catch { continue; }
87
+ if (fm.initiative) out.set(p, { ini: fm.initiative, title: fm.title ? fm.title.replace(/^Done test\s*[—:-]\s*/i, '') : fm.initiative, path: p });
88
+ }
89
+ return [...out.values()].sort((a, b) => a.path.localeCompare(b.path));
90
+ }
91
+
92
+ /* ── the rows and the files they name ───────────────────────────────────────────────────────────────────────── */
93
+ function rowsOf(text) {
94
+ const out = [];
95
+ for (const line of String(text || '').split('\n')) {
96
+ if (!/^\s*\|/.test(line)) continue;
97
+ const cells = line.trim().replace(/^\||(?<!\\)\|$/g, '').split(/(?<!\\)\|/).map((c) => c.trim().replace(/^\*\*|\*\*$/g, ''));
98
+ if (!ROW_ID.test(cells[0] || '')) continue;
99
+ out.push({ id: cells[0], check: cells[1] || '', how: cells.slice(2).join(' | ') });
100
+ }
101
+ return out;
102
+ }
103
+ function pathsIn(text) {
104
+ const out = [];
105
+ let m;
106
+ PATH_RE.lastIndex = 0;
107
+ while ((m = PATH_RE.exec(String(text || '')))) { const p = m[1].replace(/^\.\//, ''); if (p.includes('/') || /\.(test|spec)\./.test(p)) out.push(p); }
108
+ return out;
109
+ }
110
+ /** PURE. Each row with the files it names: its how-to-check first ("Same file" takes the row above's), then its check. */
111
+ function refsOf(rows) {
112
+ const out = [];
113
+ let prev = [];
114
+ for (const r of rows || []) {
115
+ let files = pathsIn(r.how).concat(pathsIn(r.check));
116
+ if (!pathsIn(r.how).length && SAME.test(r.how)) files = prev.concat(files);
117
+ files = [...new Set(files)].filter((f) => !/\.(md|markdown)$/i.test(f));
118
+ if (files.length) prev = files.filter(isTest).length ? files.filter(isTest) : prev;
119
+ out.push({ id: r.id, check: r.check, files });
120
+ }
121
+ return out;
122
+ }
123
+
124
+ /* ── the comparison (pure over a git reader) ────────────────────────────────────────────────────────────────── */
125
+ /**
126
+ * git: { added(spec) → { sha, day } | null, resolve(file, sha) → path | null (the path that exists at sha: as written, or under a top
127
+ * folder), at(sha, file) → text | null, head(file) → text | null, firstAfter(sha, file) → { sha, day } | null,
128
+ * lastTouch(file) → { sha, day } | null, moved(file) → [path at HEAD with the same name] }
129
+ * specs: [{ ini, title, path, text }]
130
+ */
131
+ function compare(specs, git) {
132
+ const items = [];
133
+ let compared = 0;
134
+ for (const s of specs || []) {
135
+ const add = git.added(s.path);
136
+ if (!add) continue; // not merged: nothing to compare yet
137
+ const refs = refsOf(rowsOf(s.text)).filter((r) => r.files.length);
138
+ if (!refs.length) continue;
139
+ compared += 1;
140
+ const found = new Map(); // kind|file → item
141
+ const put = (kind, file, row, codeDay) => {
142
+ const key = kind + '|' + file;
143
+ if (!found.has(key)) found.set(key, { id: idOf(s.path, kind, file), ws: '', ini: s.ini, title: s.title, spec: s.path, kind, file, rows: [], says: row.check, specDay: add.day, codeDay: codeDay || '' });
144
+ const it = found.get(key);
145
+ if (!it.rows.includes(row.id)) it.rows.push(row.id);
146
+ };
147
+ for (const r of refs) {
148
+ for (const f of r.files) {
149
+ const thenPath = git.resolve(f, add.sha);
150
+ let then = thenPath ? git.at(add.sha, thenPath) : null;
151
+ let p = thenPath;
152
+ if (isTest(f)) {
153
+ // the build may have landed after its spec: THEN is the first commit after the spec that touched the file
154
+ if (!proofLines(then, r.id).length) {
155
+ const cand = p || git.resolve(f, 'HEAD') || f;
156
+ const nx = git.firstAfter(add.sha, cand);
157
+ const t2 = nx ? git.at(nx.sha, cand) : null;
158
+ if (t2 != null) { then = t2; p = cand; }
159
+ }
160
+ const was = proofLines(then, r.id);
161
+ if (!was.length) continue; // never proved: the build's gap, not drift
162
+ const now = git.head(p);
163
+ if (now == null) {
164
+ if (!git.moved(p).some((m) => proofLines(git.head(m), r.id).length)) put('test-gone', p, r, (git.lastTouch(p) || {}).day);
165
+ continue;
166
+ }
167
+ const is = new Set(proofLines(now, r.id));
168
+ if (!is.size) put('test-dropped', p, r, (git.lastTouch(p) || {}).day);
169
+ else if (was.some((l) => !is.has(l))) put('test-changed', p, r, (git.lastTouch(p) || {}).day);
170
+ } else {
171
+ if (then == null) continue; // the spec named a file that did not exist yet: nothing to compare
172
+ if (git.head(p) == null && !git.moved(p).length) put('file-gone', p, r, (git.lastTouch(p) || {}).day);
173
+ }
174
+ }
175
+ }
176
+ items.push(...found.values());
177
+ }
178
+ items.sort((a, b) => String(b.codeDay).localeCompare(String(a.codeDay)) || a.spec.localeCompare(b.spec));
179
+ return { specs: (specs || []).length, compared, items };
180
+ }
181
+
182
+ /** The row's one line: "<initiative>: spec says "<check>", <what the code does>". */
183
+ function lineOf(it) {
184
+ const base = path.basename(it.file);
185
+ const code = it.kind === 'test-dropped' ? `code: ${base} no longer checks ${it.rows.join(', ')}`
186
+ : it.kind === 'test-changed' ? `code: the check for ${it.rows.join(', ')} in ${base} was rewritten` : `code: ${base} is gone`;
187
+ return `${clip(it.title, 48)}: spec says "${clip(it.says, 90)}", ${code}`;
188
+ }
189
+ const datesOf = (it) => 'spec ' + short(it.specDay) + (it.codeDay ? ' · code ' + short(it.codeDay) : '');
190
+
191
+ /* ── the git read of one repository ─────────────────────────────────────────────────────────────────────────── */
192
+ function gitIn(root) {
193
+ const run = (args, input) => execFileSync('git', args, { cwd: root, encoding: 'utf8', input, maxBuffer: 512 * 1024 * 1024, stdio: ['pipe', 'pipe', 'ignore'] });
194
+ const cache = new Map();
195
+ /** many `<rev>:<path>` reads in one process; a missing object is null */
196
+ function batch(keys) {
197
+ const want = [...new Set(keys)].filter((k) => !cache.has(k));
198
+ if (!want.length) return;
199
+ const buf = execFileSync('git', ['cat-file', '--batch'], { cwd: root, input: want.join('\n') + '\n', maxBuffer: 1024 * 1024 * 1024, stdio: ['pipe', 'pipe', 'ignore'] });
200
+ let i = 0;
201
+ for (const k of want) {
202
+ const nl = buf.indexOf(10, i);
203
+ const head = buf.slice(i, nl).toString('utf8');
204
+ i = nl + 1;
205
+ const m = /^\S+ (\w+) (\d+)$/.exec(head);
206
+ if (!m) { cache.set(k, null); continue; }
207
+ const n = Number(m[2]);
208
+ cache.set(k, m[1] === 'blob' ? buf.slice(i, i + n).toString('utf8') : null);
209
+ i += n + 1;
210
+ }
211
+ }
212
+ return { run, batch, cache, get: (k) => (cache.has(k) ? cache.get(k) : (batch([k]), cache.get(k))) };
213
+ }
214
+
215
+ function check(root, { specs: given } = {}) {
216
+ const G = gitIn(root);
217
+ const specs = (given || specsOf(root)).map((s) => ({ ...s, text: (() => { try { return fs.readFileSync(path.join(root, s.path), 'utf8'); } catch { return ''; } })() }));
218
+ // when each spec landed: the commit that added it (oldest first)
219
+ const added = new Map();
220
+ if (specs.length) {
221
+ const out = G.run(['log', '--diff-filter=A', '--format=@%H %cs', '--name-only', '--no-renames', 'HEAD', '--', ...new Set(specs.map((s) => path.dirname(s.path)))]);
222
+ let cur = null;
223
+ for (const l of out.split('\n')) {
224
+ if (l.startsWith('@')) { const [sha, day] = l.slice(1).split(' '); cur = { sha, day }; }
225
+ else if (l.trim() && cur) added.set(l.trim(), cur); // newest first: the last write is the oldest add
226
+ }
227
+ }
228
+ const files = G.run(['ls-tree', '-r', '--name-only', 'HEAD']).split('\n').filter(Boolean);
229
+ const headSet = new Set(files);
230
+ const byBase = new Map();
231
+ for (const f of files) { const b = path.basename(f); if (!byBase.has(b)) byBase.set(b, []); byBase.get(b).push(f); }
232
+ // every path the history has held, by name, so a short path in a spec ("pm/x.js", "x.test.js") finds its full path
233
+ const ever = new Map();
234
+ for (const f of G.run(['log', '--format=', '--name-only', '--no-renames', 'HEAD']).split('\n').concat(files)) {
235
+ if (!f) continue;
236
+ const b = path.basename(f);
237
+ if (!ever.has(b)) ever.set(b, new Set());
238
+ ever.get(b).add(f);
239
+ }
240
+ const refs = specs.map((s) => ({ s, add: added.get(s.path), refs: refsOf(rowsOf(s.text)).filter((r) => r.files.length) })).filter((x) => x.add && x.refs.length);
241
+ const candOf = (f) => [...(ever.get(path.basename(f)) || [])].filter((c) => c === f || c.endsWith('/' + f)).sort((a, b) => a.length - b.length);
242
+ const checkKeys = [];
243
+ for (const x of refs) for (const r of x.refs) for (const f of r.files) for (const c of candOf(f)) checkKeys.push(x.add.sha + ':' + c);
244
+ // existence in one --batch-check
245
+ const exists = new Set();
246
+ const uniq = [...new Set(checkKeys)];
247
+ if (uniq.length) {
248
+ const out = execFileSync('git', ['cat-file', '--batch-check'], { cwd: root, input: uniq.join('\n') + '\n', encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['pipe', 'pipe', 'ignore'] }).split('\n');
249
+ uniq.forEach((k, i) => { if (/ blob \d+$/.test(out[i] || '')) exists.add(k); });
250
+ }
251
+ // the touches of every named file since the oldest spec: first after a commit, and the last
252
+ const named = new Set();
253
+ for (const x of refs) for (const r of x.refs) for (const f of r.files) for (const c of candOf(f)) if (exists.has(x.add.sha + ':' + c) || headSet.has(c)) named.add(c);
254
+ const touches = new Map(); // file → [{ sha, day, t }] oldest first
255
+ let order = new Map(); // sha → its place in history (0 = oldest)
256
+ if (named.size) {
257
+ order = new Map(G.run(['log', '--format=%H', '--reverse', 'HEAD']).split('\n').filter(Boolean).map((s, i) => [s, i]));
258
+ const hist = G.run(['log', '--format=@%H %cs', '--name-only', '--no-renames', '--reverse', 'HEAD', '--', ...named]);
259
+ let cur = null;
260
+ for (const l of hist.split('\n')) {
261
+ if (l.startsWith('@')) { const [sha, day] = l.slice(1).split(' '); cur = { sha, day, t: order.has(sha) ? order.get(sha) : -1 }; }
262
+ else if (l.trim() && cur && named.has(l.trim())) { if (!touches.has(l.trim())) touches.set(l.trim(), []); touches.get(l.trim()).push(cur); }
263
+ }
264
+ }
265
+ const git = {
266
+ added: (p) => added.get(p) || null,
267
+ resolve: (f, sha) => (sha === 'HEAD' ? candOf(f).find((c) => headSet.has(c)) || null : candOf(f).find((c) => exists.has(sha + ':' + c)) || null),
268
+ at: (sha, f) => G.get(sha + ':' + f),
269
+ head: (f) => (headSet.has(f) ? G.get('HEAD:' + f) : null),
270
+ firstAfter: (sha, f) => { const t = order.has(sha) ? order.get(sha) : -1; return (touches.get(f) || []).find((c) => c.t > t) || null; },
271
+ lastTouch: (f) => { const l = touches.get(f) || []; return l[l.length - 1] || null; },
272
+ moved: (f) => (byBase.get(path.basename(f)) || []).filter((x) => x !== f),
273
+ };
274
+ const r = compare(specs, git);
275
+ return { ok: true, ...r };
276
+ }
277
+
278
+ /* ── the ledger ─────────────────────────────────────────────────────────────────────────────────────────────── */
279
+ const pad = (n) => String(n).padStart(2, '0');
280
+ const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); };
281
+ /** The Monday (local) that starts the week of ms. */
282
+ function weekOf(ms) { const d = new Date(ms); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() - ((d.getDay() + 6) % 7)); return localDay(d.getTime()); }
283
+ const dirOf = (runtime) => (runtime ? path.join(runtime, 'spec-drift') : null);
284
+ const ledgerFile = (dir) => path.join(dir, LEDGER);
285
+ function fold(lines) {
286
+ const F = { weeks: new Map(), acts: new Map() }; // ws → latest week · ws|id → act
287
+ for (const l of lines || []) {
288
+ if (!l || typeof l.ws !== 'string') continue;
289
+ if (l.kind === 'week' && typeof l.week === 'string') F.weeks.set(l.ws, { week: l.week, at: l.at, specs: l.specs || 0, compared: l.compared || 0, items: Array.isArray(l.items) ? l.items : [] });
290
+ else if (l.kind === 'act' && typeof l.id === 'string') F.acts.set(l.ws + '|' + l.id, { what: l.what, task: l.task || null, at: l.at });
291
+ else if (l.kind === 'undo' && typeof l.id === 'string') F.acts.delete(l.ws + '|' + l.id);
292
+ }
293
+ return F;
294
+ }
295
+ function read(dir) {
296
+ if (!dir) return fold([]);
297
+ let text = '';
298
+ try { text = fs.readFileSync(ledgerFile(dir), 'utf8'); } catch { return fold([]); }
299
+ const out = [];
300
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const o = JSON.parse(raw); if (o && LINES.has(o.kind)) out.push(o); } catch { /* a torn line has no effect */ } }
301
+ return fold(out);
302
+ }
303
+ function append(dir, line, at) {
304
+ if (!dir || !line || !LINES.has(line.kind)) throw new Error('not a spec-drift ledger line');
305
+ fs.mkdirSync(dir, { recursive: true });
306
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify({ at: at || new Date().toISOString(), ...line }) + '\n', { mode: 0o600 });
307
+ }
308
+ /** The week's result for one product as the page and the chat show it. Zero is silence: rows is [] when nothing differs. */
309
+ function view(F, ws) {
310
+ const w = F.weeks.get(ws);
311
+ if (!w) return { week: null, specs: 0, compared: 0, drifted: 0, rows: [] };
312
+ const rows = w.items.map((it) => {
313
+ const a = F.acts.get(ws + '|' + it.id) || null;
314
+ return { id: it.id, ini: it.ini, kind: it.kind, file: it.file, rows: it.rows, says: it.says, spec: it.spec, specDay: it.specDay, codeDay: it.codeDay, line: lineOf(it), dates: datesOf(it), act: a ? { what: a.what, task: a.task && a.task.task } : null };
315
+ });
316
+ return { week: w.week, at: w.at, specs: w.specs, compared: w.compared, drifted: new Set(w.items.map((it) => it.spec)).size, rows };
317
+ }
318
+ /** The work item's title and notes: fix the code, or update the spec. */
319
+ function workOf(it, what) {
320
+ const base = path.basename(it.file);
321
+ const title = what === 'code'
322
+ ? `Fix the code to match the spec: ${it.rows.join(', ')} (${base})`
323
+ : `Update the spec: ${it.rows.join(', ')} no longer matches the code (${base})`;
324
+ return { title: clip(title, 200), notes: `${it.spec}: "${clip(it.says, 160)}". ${lineOf(it).split(', code: ')[1] ? 'Code: ' + lineOf(it).split(', code: ')[1] : ''}. Found by the weekly spec check (pmos drift spec).` };
325
+ }
326
+
327
+ module.exports = { TAG, proofLines, KINDS, LEDGER, specsOf, rowsOf, refsOf, pathsIn, compare, check, lineOf, datesOf, weekOf, dirOf, read, append, fold, view, workOf, isTest };
328
+
329
+ // `node lib/spec-code-drift.js <repository>`: the check of one repository as JSON (lib/routes-spec-drift.js calls check() in a worker thread).
330
+ if (require.main === module) {
331
+ let out;
332
+ try { out = check(path.resolve(process.argv[2] || process.cwd())); } catch (e) { out = { ok: false, error: String((e && e.message) || e).slice(0, 200) }; }
333
+ process.stdout.write(JSON.stringify(out));
334
+ }
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+ /* spec-drift-cli.js — `pmos drift spec`: Library › Drift (spec and code no longer match) from a terminal and the chat (initiative
3
+ * spec-code-drift, idea A495; lib/spec-code-drift.js). It reads and writes the same ledger as the page, <runtime>/spec-drift/spec-drift.jsonl,
4
+ * so what the chat does shows in Library at once.
5
+ *
6
+ * pmos drift spec [--now] [--json] this week's rows for this repository. With no result for this week, or with --now, it runs the
7
+ * check (git only) and writes the week's result.
8
+ * pmos drift spec fix <row> [--json] adds the work item "fix the code to match the spec" to the spec's initiative (pmos task add)
9
+ * pmos drift spec update <row> [--json] adds the work item "update the spec" instead
10
+ * pmos drift spec undo <row> [--json] removes that work item again (pmos task remove) and opens the row
11
+ * <row> is the row id the list prints. Exit codes: 0 done, 1 refused, 2 usage. Nothing is sent outside. */
12
+ const path = require('path');
13
+ const { execFileSync } = require('child_process');
14
+ const S = require('./spec-code-drift.js');
15
+
16
+ const USAGE = [
17
+ 'usage: pmos drift spec [fix|update|undo <row>] — specs and code that no longer match (Library › Drift)',
18
+ ' pmos drift spec [--now] [--json] this week\'s rows; runs the check when this week has none, or with --now',
19
+ ' pmos drift spec fix <row> add the work item "fix the code to match the spec" to the spec\'s initiative',
20
+ ' pmos drift spec update <row> add the work item "update the spec" instead',
21
+ ' pmos drift spec undo <row> remove that work item again',
22
+ ];
23
+ function repoRoot(cwd) {
24
+ try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; } catch { return cwd; }
25
+ }
26
+
27
+ async function run(args, { say = (s) => console.log(s), env = process.env, cwd = process.cwd(), now = Date.now(), runtime, isTTY } = {}) {
28
+ const pos = [], flags = {};
29
+ for (const a of args) { if (a.startsWith('--')) flags[a.slice(2)] = true; else pos.push(a); }
30
+ for (const k of Object.keys(flags)) if (!['json', 'now', 'help'].includes(k)) { say(`✗ --${k} is not an option of pmos drift spec`); return 2; }
31
+ if (flags.help || pos[0] === 'help') { for (const l of USAGE) say(l); return 0; }
32
+ const verb = pos[0] || 'show';
33
+ if (!['show', 'fix', 'update', 'undo'].includes(verb)) { say(`unknown drift spec command "${verb}". Use fix, update or undo, or no command to list`); return 2; }
34
+ if (verb === 'show' ? pos.length > 1 : pos.length !== 2) { for (const l of USAGE) say(l); return 2; }
35
+ if (/^(off|0|false|no)$/i.test(String(env.PMOS_SPEC_DRIFT || ''))) { say('✗ the weekly spec check is off (PMOS_SPEC_DRIFT=off)'); return 1; }
36
+ const dir = S.dirOf(runtime || require('./state-root.js').defaultRoot({ env }));
37
+ const root = repoRoot(cwd);
38
+ const ws = require('./driver.js').wsIdOf(root);
39
+ const at = new Date(now).toISOString();
40
+
41
+ if (verb === 'show') {
42
+ const week = S.weekOf(now);
43
+ let v = S.view(S.read(dir), ws);
44
+ if (flags.now || v.week !== week) {
45
+ const r = S.check(root);
46
+ if (!r.ok) { say('✗ the check could not read this repository: ' + (r.error || 'git failed')); return 1; }
47
+ S.append(dir, { kind: 'week', ws, week, specs: r.specs, compared: r.compared, items: r.items }, at);
48
+ console.error(`${S.TAG} week ws=${ws} specs=${r.specs} compared=${r.compared} items=${r.items.length} by=cli`);
49
+ v = S.view(S.read(dir), ws);
50
+ }
51
+ if (flags.json) { say(JSON.stringify({ ok: true, week: v.week, specs: v.specs, compared: v.compared, drifted: v.drifted, rows: v.rows })); return 0; }
52
+ if (!v.rows.length) { say(`Spec and code match: ${v.compared} specs compared, week of ${v.week}.`); return 0; }
53
+ say(`This week: ${v.drifted} of ${v.compared} specs no longer match the code (week of ${v.week}).`);
54
+ for (const r of v.rows) say(` ${r.id} ${r.line}\n ${r.dates}${r.act ? ` · work item ${r.act.task} (${r.act.what === 'code' ? 'fix the code' : 'update the spec'})` : ''}`);
55
+ say('Add a work item: pmos drift spec fix <row> (fix the code) or pmos drift spec update <row> (update the spec).');
56
+ return 0;
57
+ }
58
+
59
+ const id = pos[1];
60
+ const F = S.read(dir), w = F.weeks.get(ws);
61
+ const item = w && w.items.find((it) => it.id === id);
62
+ if (!item) { say(`✗ no row ${id} this week: pmos drift spec lists them`); return 1; }
63
+ const act = F.acts.get(ws + '|' + id);
64
+ const TC = require('./task-cli.js');
65
+ const out = [];
66
+ if (verb === 'undo') {
67
+ if (!act) { say(`✗ row ${id} has no work item to take back`); return 1; }
68
+ const code = act.task && act.task.task ? await TC.run(['task', 'remove', act.task.task, '--why', 'taken back from Library › Drift', '--json'], { say: (s) => out.push(s), cwd: root, isTTY, env }) : 0;
69
+ if (code !== 0) { say('✗ the work item could not be removed: ' + out.join(' ')); return 1; }
70
+ S.append(dir, { kind: 'undo', ws, id }, at);
71
+ console.error(`${S.TAG} undo ws=${ws} id=${id} by=cli`);
72
+ say(flags.json ? JSON.stringify({ ok: true }) : `✓ the work item for row ${id} was removed. The row is open again in Library › Drift.`);
73
+ return 0;
74
+ }
75
+ if (act) { say(`✗ row ${id} already has a work item (${act.task && act.task.task}); pmos drift spec undo ${id} takes it back`); return 1; }
76
+ const what = verb === 'fix' ? 'code' : 'spec';
77
+ const work = S.workOf(item, what);
78
+ const code = await TC.run(['task', 'add', item.ini, work.title, '--notes', work.notes, '--json'], { say: (s) => out.push(s), cwd: root, isTTY, env });
79
+ let task = null;
80
+ try { task = JSON.parse(out[out.length - 1]).task; } catch { task = null; }
81
+ if (code !== 0 || !task) { say('✗ the work item could not be added: ' + out.join(' ')); return 1; }
82
+ S.append(dir, { kind: 'act', ws, id, what, task: { ws, board: task.board || '', ini: item.ini, task: task.id, title: work.title } }, at);
83
+ console.error(`${S.TAG} act ws=${ws} id=${id} what=${what} task=${task.id} by=cli`);
84
+ say(flags.json ? JSON.stringify({ ok: true, task: { id: task.id, title: work.title, initiative: item.ini } })
85
+ : `✓ added ${task.id} to ${item.ini}: ${work.title}. Undo: pmos drift spec undo ${id}`);
86
+ return 0;
87
+ }
88
+
89
+ module.exports = { run, USAGE };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.849.0",
3
+ "version": "0.850.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.849.0",
9
+ "version": "0.850.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.849.0",
3
+ "version": "0.850.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",
@@ -90,6 +90,7 @@ body.bd-page.bk-on .bd-hd .bd-tools { margin-left: auto; }
90
90
  .bk-bar button { all: unset; cursor: pointer; height: 34px; padding: 0 14px; border-radius: var(--radius-pill); background: rgba(255, 255, 255, .12); font-size: var(--fs-row); white-space: nowrap; display: inline-flex; align-items: center; gap: 6px; }
91
91
  .bk-bar button.pm { background: var(--cz-blue); }
92
92
  .bk-bar button.x { width: 34px; padding: 0; justify-content: center; background: none; }
93
+ .bk-bar button.bk-cmp { width: 34px; padding: 0; justify-content: center; } /* Compare, icon only, with exactly two ticked (pm/compare-items.js) */
93
94
  .bk-bar button.x svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; }
94
95
 
95
96
  /* small popovers: a pick list, a date, the tune panel, the kind of work */
@@ -28,6 +28,7 @@ import * as LV from './line-view.js'; // quiet-rows slice B: the Line tab, eve
28
28
  import * as FV from './factory.js'; // Work › Factory (factory-page-ui): the stations and the work they make, from GET /api/factory
29
29
  import * as IC from './initiative-cost.js'; // Work › Cost (initiative-cost, A17): what the factory spent per initiative, from GET /api/initiative-cost
30
30
  import * as LB from './list-balance.js'; // the balance meter under the Backlog header (bet A448, board BalanceDS) // quiet-rows slice B: the Line tab, every initiative by station (GET /api/line)
31
+ import * as CMP from './compare-items.js'; // exactly two ticked: Compare opens them side by side in one panel (A421, board CompareDS)
31
32
  import * as BD from './bd-backlog-ds.js'; // the Backlog from the system's parts (WorkBacklogDS) // the sprint overview while "This sprint" is on (initiative sprint-overview)
32
33
 
33
34
  const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
@@ -573,6 +574,7 @@ function drawBar() {
573
574
  bar.innerHTML = `<span class="c">${n} selected</span><button type="button" class="pm" data-bkb="give">${SPARK} Give to PMOS</button><button type="button" data-bkb="person">Give to a person</button>`
574
575
  + `<button type="button" data-bkb="ini">Move to initiative</button><button type="button" data-bkb="parent">Under a parent</button><button type="button" data-bkb="section">Stage</button><button type="button" data-bkb="date">Set date</button><button type="button" data-bkb="shift">Move dates</button>`
575
576
  + `<button type="button" data-bkb="done">Done</button><button type="button" data-bkb="archive">Archive</button>`
577
+ + CMP.barPressHtml(n)
576
578
  + `<button type="button" class="x" data-bkb="clear" aria-label="Clear the ticks" title="Clear">${SV(I.x)}</button>`;
577
579
  }
578
580
  const picked = () => DATA.tasks.filter((t) => SEL.has(uidOf(t)));
@@ -580,6 +582,7 @@ async function barPress(e) {
580
582
  const b = e.target.closest('[data-bkb]'); if (!b) return;
581
583
  const k = b.dataset.bkb, T = picked();
582
584
  if (k === 'clear') { SEL.clear(); draw(); return; }
585
+ if (k === 'compare') { if (CMP.canCompare(T.length)) CMP.openCompare(CMP.taskSide(T[0], (at) => AP().openTask(T[0], at)), CMP.taskSide(T[1], (at) => AP().openTask(T[1], at))); return; }
583
586
  if (k === 'give') { await giveTo(T); return; }
584
587
  if (k === 'person') { pickPop(b, 'Give to a person', people(), async (who) => { await editMany(T, { owner: who }, 'Given to ' + who); }, { free: 'A name' }); return; }
585
588
  if (k === 'ini') { pickPop(b, 'Move to initiative', inisFor(T).map((x) => [x.id, x.title]), async (id) => { await moveMany(T, id); }); return; }