create-pmos 0.679.0 → 0.681.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.679.0",
3
+ "version": "0.681.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -33,6 +33,25 @@
33
33
  "audit"
34
34
  ],
35
35
  "pmosChanges": [
36
+ {
37
+ "v": "0.681.0",
38
+ "at": "2026-11-22T07:52:20.147Z",
39
+ "f": 4,
40
+ "prs": [
41
+ {
42
+ "n": 1488,
43
+ "t": "Read a document as a CFO, an engineer and a sceptic (A110)",
44
+ "s": "Read a document as a CFO, an engineer and a sceptic (A110)",
45
+ "k": "new"
46
+ },
47
+ {
48
+ "n": 1487,
49
+ "t": "Design drift guard counts token bypasses, with a ratchet",
50
+ "s": "Design drift guard counts token bypasses, with a ratchet",
51
+ "k": "new"
52
+ }
53
+ ]
54
+ },
36
55
  {
37
56
  "v": "0.679.0",
38
57
  "at": "2026-11-22T06:54:44.843Z",
@@ -363,19 +382,6 @@
363
382
  "k": "new"
364
383
  }
365
384
  ]
366
- },
367
- {
368
- "v": "0.646.0",
369
- "at": "2026-11-20T03:32:31.987Z",
370
- "f": 4,
371
- "prs": [
372
- {
373
- "n": 1428,
374
- "t": "Today is built from the design system's blocks",
375
- "s": "Today is built from the design system's blocks",
376
- "k": "new"
377
- }
378
- ]
379
385
  }
380
386
  ]
381
387
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@29ab82b1
1
+ kernel-source: pmos@ee3639a5
2
2
  assembled: 2026-11-22
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-11-22T06:54:41Z"}
5
+ generated: {by: process:create-pmos, at: "2026-11-22T07:52:17Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-11-22T06:54:41Z"}
5
+ generated: {by: process:create-pmos, at: "2026-11-22T07:52:17Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-11-22T06:54:41Z"}
5
+ generated: {by: process:create-pmos, at: "2026-11-22T07:52:17Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -1,4 +1,23 @@
1
1
  [
2
+ {
3
+ "v": "0.681.0",
4
+ "at": "2026-11-22T07:52:20.147Z",
5
+ "f": 4,
6
+ "prs": [
7
+ {
8
+ "n": 1488,
9
+ "t": "Read a document as a CFO, an engineer and a sceptic (A110)",
10
+ "s": "Read a document as a CFO, an engineer and a sceptic (A110)",
11
+ "k": "new"
12
+ },
13
+ {
14
+ "n": 1487,
15
+ "t": "Design drift guard counts token bypasses, with a ratchet",
16
+ "s": "Design drift guard counts token bypasses, with a ratchet",
17
+ "k": "new"
18
+ }
19
+ ]
20
+ },
2
21
  {
3
22
  "v": "0.679.0",
4
23
  "at": "2026-11-22T06:54:44.843Z",
@@ -237,7 +237,7 @@ What each part does:
237
237
  - **What the canvas can do.** The prototype runs in a sandboxed frame. It cannot reach PMOS. The canvas talks to it only to show a screen, point, pin, play and apply your edits.
238
238
  - **Your prototype rules.** After a version renders and before it opens, PMOS checks it against your prototype rules: no device or browser frame, no instructions on the screen, no sample copy, and each rule PMOS learns from your corrections. When a correction is true of every prototype (for example "no device frame"), the chat adds it as a rule (`pmos lab rule add`). PMOS keeps a rule only when it fails a bad example and passes a good one, so a button such as "See the week" is never read as an instruction. A change to one version ("make the alert orange") or a taste ("calmer") never becomes a rule. A version that breaks a rule gets one fix run, given only the lines that broke it. You see only the fixed version, with one quiet line: "PMOS fixed 3 things before showing you this." When the fix does not reach a rule, the version still opens and the line names the rule it breaks. When nothing was fixed, there is no line. Settings › Prototype rules lists the rules with Undo.
239
239
  - **The design critic.** After the prototype rules, a separate read-only session reads the version's desk and phone screenshots and its page against every standing design rule of your product. Each rule is a named check: each numbered principle in your design principles and each rule in your `design-rules.json`. A finding must name the rule it breaks, so the critic reports broken rules, not taste. Its findings go into the same one fix run. After the fix it reads only those rules again, so "PMOS fixed n things" is never claimed unchecked. A critic that cannot run never holds the version. `pmos lab critic` runs it on any screenshots, and `PMOS_CRITIC=off` turns it off.
240
- - **The sceptical reviewer.** Before you share a document, the chat's agent runs `pmos critic <file>`: a separate read-only session reads it as a sceptical reviewer and lists at most 3 hard questions. Each names its lens, quotes the document and gives the smallest fix; a question whose quote is not in the document is dropped. `pmos critic stats` shows how many you called real, and the gaps that repeat across documents.
240
+ - **The sceptical reviewer.** Before you share a document, the chat's agent runs `pmos critic <file>`: a separate read-only session reads it as a sceptical reviewer and lists at most 3 hard questions. Each names its lens, quotes the document and gives the smallest fix; a question whose quote is not in the document is dropped. For a report or an update that goes to leadership, it runs `pmos critic <file> --as all`: the same pass reads it as the CFO (cost, return, the cost of a slip), the engineering lead (can it be built as written, what it waits on, who builds it) and the sceptic, at most 2 questions each. `pmos critic stats` shows how many you called real, for each reader, and the gaps that repeat across documents.
241
241
  - **No time limit.** A version takes as long as the ask needs. While PMOS makes it, the Viewer shows what it is doing now (for example "Building screen 3 of 7"), the steps done, a progress bar and the time so far, with a Stop press. A run that writes nothing for 10 minutes is stuck: PMOS stops it. A version that does not render, that is stuck or that you stop is "not made" with the reason, and the chat says so. The Viewer still opens it: it says why and shows the version it was made from. While a version is being made, a new ask on the same initiative waits: PMOS says what is running.
242
242
  - **Lessons.** Each change sentence, ✓ and ✕ is a Lessons line of the experiment (`pmos artefacts show`). Each version that rendered is a Specimens line. The one you keep is the kept specimen.
243
243
  - **The grill runs after the session, not during it.** When you keep a version, the grill runs once on the kept specimen, as the Review step. Its findings wait under the ✦ (D60 as amended on 2026-11-17).
@@ -188,11 +188,12 @@ PMOS's grill run files with these commands, which refuse outside that run:
188
188
 
189
189
  Before you share a spec, a strategy, a roadmap or a report, PMOS reads it as a sceptical reviewer would and lists the hardest questions that reviewer would ask. Each question names its lens (evidence, outcome, trade-off, scope, risk, owner, contradiction or unverified claim), quotes the words of the document it rests on, and gives the smallest fix. A question whose quote is not in the document is dropped. The chat's agent runs it when you say you are about to share a document. Nothing is sent and the document is not changed.
190
190
 
191
- - `pmos critic <file> [--ws <id>]`: one pass on a markdown, text or HTML document. It prints at most 3 questions, the hardest first. The running PMOS server starts one read-only session.
191
+ - `pmos critic <file> [--as <readers>] [--ws <id>]`: one pass on a markdown, text or HTML document. It prints at most 3 questions, the hardest first. The running PMOS server starts one read-only session.
192
+ - `--as cfo,engineer,sceptic` (or `--as all`) reads the document as those readers in the same pass. Each reader asks at most 2 questions, and each question shows its reader, for example `[cfo · cost-of-delay]`. The CFO asks about cost, return and the cost of a slip. The engineering lead asks if it can be built as written, what it waits on, and who builds it. The sceptic asks the base questions. With no `--as`, the sceptic reads alone. Use `--as all` for a report or an update that goes to leadership.
192
193
  - `pmos critic show <file> [--ws <id>]`: the newest pass on that file, and whether the file changed since.
193
- - `pmos critic lenses [--root <dir>]`: the lenses. Add your product's own reviewer questions in `pmos/review-questions.json` (or `okf/products/<slug>/references/review-questions.json`): `{ "questions": [{ "id", "title", "rule" }] }`. An id that is a base lens replaces it. No server is needed.
194
+ - `pmos critic lenses [--as <readers>] [--root <dir>]`: the lenses. Add your product's own reviewer questions in `pmos/review-questions.json` (or `okf/products/<slug>/references/review-questions.json`): `{ "questions": [{ "id", "title", "rule", "reader" }] }`. `reader` is `cfo`, `engineer` or `sceptic` (none: the sceptic). An id that is a PMOS lens replaces it. `--as` lists those readers' lenses. No server is needed.
194
195
  - `pmos critic label <run> <n> real|noise`: your word on question `n` of a run.
195
- - `pmos critic stats`: the runs, the questions, how many you called real or noise, how many were dropped for a quote not in the document, and the gaps that repeat across documents. When the same gap is in several documents, fix the template or the generator that makes them.
196
+ - `pmos critic stats`: the runs, the questions, how many you called real or noise, how many were dropped for a quote not in the document, the same counts for each reader, and the gaps that repeat across documents. When the same gap is in several documents, fix the template or the generator that makes them.
196
197
 
197
198
  `PMOS_CRITIC=off` turns this critic and the design critic off.
198
199
 
@@ -319,12 +320,16 @@ Only PMOS's impact run uses these. The server pins each run to your ledger. Outs
319
320
  - `pmos drift replay`: the replay of the last four weeks of this repository.
320
321
  - `pmos drift status`: the last weekly result and the replays on record.
321
322
 
322
- ### pmos design drift: pages that drift from the design system
323
+ ### pmos design drift: places that do not read a design token
323
324
 
324
- - `pmos design drift`: for each page, the share of its classes that your design system defines, its own CSS rules, the system parts it draws again, and its raw colours. It ends with the pages to rebuild next, lowest share first. It reads git only.
325
- - `--base <ref>` compares with an earlier commit and marks each page drift, rebuilt, not rebuilt or unchanged. `--base week` uses the last commit a week earlier.
326
- - `--weeks <n>` adds the mean share at the end of each of the last n weeks. `--write` writes the report to `planning/reports/`. `--gate` exits 1 when a page drifts.
327
- - A product names its pages and system sheets in `design-drift.json` in its design-system folder, for example `{ "pages": ["web/*.html"], "assetBase": "web", "systemSheets": ["ds.css"] }`.
325
+ The aim: change one token and every page follows. Each place this command counts is a place a token change does not reach.
326
+
327
+ - `pmos design drift`: counts every literal colour, text size, corner, spacing and shadow outside the system sheets, every token defined outside the system, every inline style value, and every class the system does not define. It says how many have a token with the same value. It reads git only.
328
+ - `--base <ref>` compares with an earlier commit. For each file whose count of a kind rose, it lists the added lines and the token each one should read. `--base week` uses the last commit a week earlier.
329
+ - `--gate` exits 1 when a count rose against `--base`. `--github` prints each new place as a GitHub warning on its line. CI runs it on every pull request, as a warning only.
330
+ - `--weeks <n>` adds the total at the end of each of the last n weeks. `--write` writes the report to `planning/reports/`.
331
+ - `--pages` shows the older measure instead: for each page, the share of its classes that the system defines and its own CSS rules.
332
+ - A product sets the files to count and its system sheets in `design-drift.json` in its design-system folder, for example `{ "scan": ["web/**/*.css"], "systemSheets": ["ds.css"] }`.
328
333
 
329
334
  ## Initiatives and the Board
330
335
 
@@ -2,10 +2,12 @@
2
2
  /* critic-cli.js — `pmos critic`: before you share a document, the hardest questions a sceptical reviewer would ask (initiative spec-critic;
3
3
  * lib/spec-critic.js, POST and GET /api/spec-critic in lib/routes-spec-critic.js).
4
4
  *
5
- * pmos critic <file> [--ws <id>] one pass through the running server: at most 3 questions, each with its lens, the quoted words and
6
- * the smallest fix. The chat's agent runs it when the PM says they are about to share a document.
5
+ * pmos critic <file> [--as <readers>] [--ws <id>] one pass through the running server: at most 3 questions, each with its lens, the
6
+ * quoted words and the smallest fix. The chat's agent runs it when the PM says they are about to share
7
+ * a document. --as cfo,engineer,sceptic (or all) reads it as those readers, at most 2 questions each
8
+ * (initiative review-lenses-cfo-engineer-sceptic, bet A110); none: the sceptic alone.
7
9
  * pmos critic show <file> [--ws <id>] the newest pass on that file, and whether the file changed since (through the server)
8
- * pmos critic lenses [--root <dir>] the lenses: the base set plus the product's review-questions.json (no server)
10
+ * pmos critic lenses [--as <readers>] [--root <dir>] the lenses: the readers' sets plus the product's review-questions.json (no server)
9
11
  * pmos critic label <run> <n> real|noise the PM's word on question n of a run (no server)
10
12
  * pmos critic stats runs, questions, real, noise, dropped for a missing quote, and the gaps that repeat across documents
11
13
  *
@@ -16,9 +18,10 @@ const SC = require('./spec-critic.js');
16
18
  const COMMANDS = { critic: ['show', 'lenses', 'label', 'stats'] };
17
19
  const USAGE = [
18
20
  'usage: pmos critic <file> [--ws <id>] — before you share a document, the hardest questions a sceptical reviewer would ask',
19
- ' pmos critic <file> [--ws <id>] a markdown, text or HTML document: at most 3 questions, each quoting the document, with the smallest fix',
21
+ ' pmos critic <file> [--as <readers>] [--ws <id>] a markdown, text or HTML document: at most 3 questions, each quoting the document, with the smallest fix',
22
+ ' --as cfo,engineer,sceptic (or all): read it as those readers, at most 2 questions each. None: the sceptic alone.',
20
23
  ' pmos critic show <file> [--ws <id>] the newest pass on that file, and whether the file changed since',
21
- ' pmos critic lenses [--root <dir>] the lenses the critic asks through: the base set plus the product\'s review-questions.json',
24
+ ' pmos critic lenses [--as <readers>] [--root <dir>] the lenses the critic asks through: each reader\'s set plus the product\'s review-questions.json',
22
25
  ' pmos critic label <run> <n> real|noise your word on question n of a run',
23
26
  ' pmos critic stats runs, questions, real, noise, and the gaps that repeat across documents',
24
27
  'A question whose quote is not in the document is dropped. Nothing is sent. PMOS_CRITIC=off turns the critic off.',
@@ -26,12 +29,18 @@ const USAGE = [
26
29
  const flag = (args, k) => { const i = args.indexOf('--' + k); return i >= 0 ? (args[i + 1] === undefined || args[i + 1].startsWith('--') ? true : args[i + 1]) : undefined; };
27
30
  const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
28
31
  const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
29
- const fileArg = (args, from) => { for (let i = from; i < args.length; i++) { if (args[i] === '--ws' || args[i] === '--root') { i++; continue; } if (!args[i].startsWith('--')) return args[i]; } return ''; };
32
+ const fileArg = (args, from) => { for (let i = from; i < args.length; i++) { if (args[i] === '--ws' || args[i] === '--root' || args[i] === '--as') { i++; continue; } if (!args[i].startsWith('--')) return args[i]; } return ''; };
30
33
  const pathFor = (f) => (path.isAbsolute(f) ? f : path.resolve(f));
31
34
 
32
- function printQuestions(say, qs) {
35
+ const tag = (q, named) => (named && q.reader ? `${q.reader} · ${q.lens}` : q.lens);
36
+ /** Readers are named on each question when someone other than the sceptic alone read it. */
37
+ const named = (readers) => Array.isArray(readers) && !(readers.length === 1 && readers[0] === 'sceptic') && readers.length > 0;
38
+ const asOf = (args) => { const a = flag(args, 'as'); return a === true ? { ok: false, error: '--as needs readers: ' + SC.READER_IDS.join(', ') + ' (or all)' } : SC.readersOf(a); };
39
+
40
+ function printQuestions(say, qs, readers) {
41
+ const n = named(readers);
33
42
  qs.forEach((q, i) => {
34
- say(` ${i + 1}. [${q.lens}] ${q.question}`);
43
+ say(` ${i + 1}. [${tag(q, n)}] ${q.question}`);
35
44
  say(` quotes: "${one(q.quote, 200)}"`);
36
45
  if (q.why) say(` why it is hard: ${q.why}`);
37
46
  if (q.fix) say(` fix before sharing: ${q.fix}`);
@@ -44,16 +53,24 @@ async function run(argv, { say = (s) => console.log(s), call = null, env = proce
44
53
  if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 2; }
45
54
  const rt = () => require('./state-root.js').defaultRoot({ env });
46
55
 
56
+ const rd = asOf(args);
57
+ if (!rd.ok) { say('✗ ' + rd.error); return 2; }
47
58
  if (sub === 'lenses') {
48
59
  const root = typeof flag(args, 'root') === 'string' ? path.resolve(flag(args, 'root')) : process.cwd();
49
- const K = SC.lensesFor(root);
50
- say(K.added ? `${K.lenses.length} lenses: the base set and ${plural(K.added, 'question')} from ${K.from.join(' and ')}` : `${K.lenses.length} base lenses (add your own in pmos/review-questions.json):`);
51
- for (const l of K.lenses) say(` [${l.id}] ${l.title} ${one(l.rule, 160)}`);
60
+ const K = SC.lensesFor(root, { as: rd.readers });
61
+ const n = named(K.readers);
62
+ const whose = n ? ` for ${SC.readerList(K.readers)}` : '';
63
+ say(K.added ? `${K.lenses.length} lenses${whose}: ${n ? 'the PMOS set' : 'the base set'} and ${plural(K.added, 'question')} from ${K.from.join(' and ')}`
64
+ : n ? `${K.lenses.length} lenses${whose} (add your own in pmos/review-questions.json):` : `${K.lenses.length} base lenses (add your own in pmos/review-questions.json):`);
65
+ for (const l of K.lenses) say(` [${n ? l.reader + ' · ' : ''}${l.id}] ${l.title} ${one(l.rule, 160)}`);
52
66
  return 0;
53
67
  }
54
68
  if (sub === 'stats') {
55
69
  const st = SC.stats(rt());
56
70
  say(`${plural(st.runs, 'critic run')}${st.notRun ? ` (${st.notRun} did not run)` : ''} on ${plural(st.files, 'document')} · ${plural(st.questions, 'question')}: ${st.real} real, ${st.noise} noise, ${st.unlabelled} not labelled · ${st.dropped} dropped for a quote not in the document`);
71
+ if (Object.keys(st.byReader).some((r) => r !== 'sceptic')) {
72
+ for (const r of SC.READER_IDS) { const b = st.byReader[r]; if (b) say(` ${SC.READERS[r].name}: ${plural(b.questions, 'question')}, ${b.real} real, ${b.noise} noise, ${b.unlabelled} not labelled`); }
73
+ }
57
74
  for (const r of st.repeats) say(` the same gap in ${r.files.length} documents: [${r.lens}] ${r.files.map((f) => path.basename(f)).join(', ')}. Fix the template or the generator that makes them.`);
58
75
  return 0;
59
76
  }
@@ -79,19 +96,21 @@ async function run(argv, { say = (s) => console.log(s), call = null, env = proce
79
96
  const x = r.run;
80
97
  say(`${x.at.slice(0, 16).replace('T', ' ')} · run ${x.id}${r.changed ? ' · the document changed since: run it again before you share' : ''}`);
81
98
  if (!x.ok) { say('✗ it did not run: ' + (x.why || 'no answer')); return 0; }
82
- if (!x.questions.length) say('✓ no hard question'); else printQuestions(say, x.questions);
99
+ if (!x.questions.length) say('✓ no hard question'); else printQuestions(say, x.questions, x.readers);
83
100
  return 0;
84
101
  }
85
102
  const f = fileArg(args, 0);
86
103
  if (!f) { for (const l of USAGE) say(l); return 2; }
87
104
  if (typeof call !== 'function') { say('✗ no PMOS server answers: start PMOS, then ask again'); return 1; }
88
- let r = null; try { r = await call('POST', '/api/spec-critic', { path: pathFor(f), ...(wsq ? { ws: wsq } : {}) }); } catch { r = null; }
105
+ const asked = flag(args, 'as') !== undefined;
106
+ let r = null; try { r = await call('POST', '/api/spec-critic', { path: pathFor(f), ...(wsq ? { ws: wsq } : {}), ...(asked ? { as: rd.readers } : {}) }); } catch { r = null; }
89
107
  if (!r) { say('✗ no PMOS server answers: start PMOS, then ask again'); return 1; }
90
108
  if (!r.ok) { say('✗ ' + (r.error || 'the critic did not run')); return 1; }
109
+ const who = named(r.readers) ? SC.readerList(r.readers) : 'a sceptical reviewer';
91
110
  say(r.questions.length
92
- ? `${plural(r.questions.length, 'hard question')} a sceptical reviewer would ask of ${path.basename(r.file)} · run ${r.run}`
111
+ ? `${plural(r.questions.length, 'hard question')} ${who} would ask of ${path.basename(r.file)} · run ${r.run}`
93
112
  : `✓ no hard question on ${path.basename(r.file)} (${r.lenses} lenses) · run ${r.run}`);
94
- printQuestions(say, r.questions);
113
+ printQuestions(say, r.questions, r.readers);
95
114
  if (r.questions.length) say(`Label each: pmos critic label ${r.run} <n> real|noise`);
96
115
  return 0;
97
116
  }
@@ -1,34 +1,40 @@
1
1
  'use strict';
2
- /* design-cli.js — `pmos design drift`: which pages are built from this product's design system, and which drift from it (initiative
3
- * design-drift-guard; lib/design-drift.js does the measuring).
2
+ /* design-cli.js — `pmos design drift`: every place this product's styles and scripts do not read a design token, and a ratchet so a pull
3
+ * request may lower that count but never raise it (initiative design-token-ratchet, the rescope of design-drift-guard). lib/design-drift.js
4
+ * does the counting. Wawan, 2026-11-22: a design system is reusable templates; changing one token must change every page, with no page rewritten.
4
5
  *
5
- * pmos design drift [--ref <ref>] [--base <ref>|week] [--weeks <n>] [--json] [--write] [--gate]
6
- * --ref the commit to measure (default HEAD). WORKTREE measures the files on disk, saved or not.
7
- * --base compare with this commit. `week` is the last commit a week before --ref. Without --base, the pages are only listed.
8
- * --weeks add the mean system share at the end of each of the last n weeks (1 to 12)
9
- * --json print the rows as JSON
10
- * --write write the report to planning/reports/design-drift-<date>.md (the only write this command makes)
11
- * --gate exit 1 when a page drifts against --base (for a CI step later; no CI runs it today)
6
+ * pmos design drift [--ref <ref>] [--base <ref>|week] [--weeks <n>] [--json] [--write] [--gate] [--github] [--pages]
7
+ * --ref the commit to count (default HEAD). WORKTREE counts the files on disk, saved or not.
8
+ * --base compare with this commit: each file whose count of a kind rose, with the added lines and the token each should read.
9
+ * `week` is the last commit a week before --ref.
10
+ * --weeks add the total at the end of each of the last n weeks (1 to 12)
11
+ * --json print the result as JSON
12
+ * --write write the report to planning/reports/ (the only write this command makes)
13
+ * --gate exit 1 when a count rose against --base
14
+ * --github print each new bypass as a GitHub warning on its file and line (the CI step uses it)
15
+ * --pages the older view instead: each page's share of system classes and its own CSS (a measure only)
12
16
  *
13
- * Run it in the product's repository. It reads git only and changes nothing else. Exit codes: 0 done, 1 a page drifts (only with --gate)
14
- * or the refs cannot be read, 2 usage. */
17
+ * Run it in the product's repository. It reads git only and changes nothing else. Exit codes: 0 done, 1 a count rose (only with --gate) or
18
+ * the refs cannot be read, 2 usage. */
15
19
  const fs = require('fs');
16
20
  const path = require('path');
17
21
  const D = require('./design-drift.js');
18
22
 
19
23
  const COMMANDS = { design: ['drift'] };
20
24
  const USAGE = [
21
- 'usage: pmos design drift — which pages are built from this product\'s design system, and which drift from it',
22
- ' pmos design drift [--ref <ref>] [--base <ref>|week] [--weeks <n>] [--json] [--write] [--gate]',
23
- ' --ref <ref> the commit to measure (default HEAD; WORKTREE reads the files on disk)',
24
- ' --base <ref> compare with this commit; "week" is the last commit a week earlier',
25
- ' --weeks <n> the mean system share at the end of each of the last n weeks (1 to 12)',
26
- ' --write write the report to planning/reports/design-drift-<date>.md',
27
- ' --gate exit 1 when a page drifts against --base',
28
- 'It reads git only. A product sets its pages and system sheets in design-drift.json in its design-system folder.',
25
+ 'usage: pmos design drift — every place your styles and scripts do not read a design token, and which ones a change adds',
26
+ ' pmos design drift [--ref <ref>] [--base <ref>|week] [--weeks <n>] [--json] [--write] [--gate] [--github] [--pages]',
27
+ ' --ref <ref> the commit to count (default HEAD; WORKTREE reads the files on disk)',
28
+ ' --base <ref> compare with this commit and name each added line that bypasses a token; "week" is the last commit a week earlier',
29
+ ' --weeks <n> the total at the end of each of the last n weeks (1 to 12)',
30
+ ' --write write the report to planning/reports/',
31
+ ' --gate exit 1 when a count rose against --base',
32
+ ' --github print each new bypass as a GitHub warning on its line',
33
+ ' --pages each page\'s share of system classes instead (a measure only)',
34
+ 'It reads git only. A product sets its files and system sheets in design-drift.json in its design-system folder.',
29
35
  ];
30
- const FLAGS = new Set(['ref', 'base', 'weeks', 'json', 'write', 'gate', 'repo']);
31
- const BOOL = new Set(['json', 'write', 'gate']);
36
+ const FLAGS = new Set(['ref', 'base', 'weeks', 'json', 'write', 'gate', 'repo', 'github', 'pages']);
37
+ const BOOL = new Set(['json', 'write', 'gate', 'github', 'pages']);
32
38
 
33
39
  function parse(args) {
34
40
  const pos = [], flags = {};
@@ -59,7 +65,8 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), now
59
65
  for (const k of ['ref', 'base', 'weeks', 'repo']) if (k in flags && !flags[k]) { say(`✗ --${k} needs a value`); return 2; }
60
66
  const weeks = flags.weeks === undefined ? 0 : Number(flags.weeks);
61
67
  if (!Number.isInteger(weeks) || weeks < 0 || weeks > 12) { say('✗ --weeks is a whole number from 1 to 12'); return 2; }
62
- if (flags.gate && !flags.base) { say('✗ --gate needs --base: it fails only a page that drifts against an earlier commit'); return 2; }
68
+ if (flags.gate && !flags.base) { say('✗ --gate needs --base: it fails only a count that rose against an earlier commit'); return 2; }
69
+ if (flags.github && !flags.base) { say('✗ --github needs --base: it marks only the lines a change added'); return 2; }
63
70
 
64
71
  const repo = repoRoot(flags.repo ? path.resolve(cwd, flags.repo) : cwd);
65
72
  if (!repo) { say('✗ this is not a git repository. Run pmos design drift in your product\'s repository.'); return 1; }
@@ -75,6 +82,8 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), now
75
82
  }
76
83
  if (base && !D.gitOut(repo, ['rev-parse', '--verify', '--quiet', base + '^{commit}'])) { say(`✗ no commit "${base}" in this repository`); return 1; }
77
84
 
85
+ if (!flags.pages) return tokens({ repo, ref, base, worktree, weeks, flags, say, now });
86
+
78
87
  const head = D.measure(repo, ref);
79
88
  if (head.config.error) { say('✗ ' + head.config.error); return 1; }
80
89
  const before = base ? D.measure(repo, base) : null;
@@ -99,7 +108,7 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), now
99
108
  }
100
109
  say(`shared code: ${head.shared.files.length} files · ${pct(head.shared.share)} from the system · ${head.shared.ownRules} own CSS rules`);
101
110
  const q = D.queue(rows);
102
- if (q.length) say('Rebuild next, one pull request each: ' + q.map((r) => `${short(r.page)} ${pct(r.share)}`).join(', '));
111
+ if (q.length) say('Lowest system share: ' + q.map((r) => `${short(r.page)} ${pct(r.share)}`).join(', '));
103
112
  }
104
113
  if (trend) say('Mean share by week: ' + trend.map((t) => `${t.week} ${t.share == null ? '–' : pct(t.share)}`).join(' · '));
105
114
  }
@@ -112,4 +121,47 @@ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), now
112
121
  return flags.gate && drifting.length ? 1 : 0;
113
122
  }
114
123
 
124
+ const n = (x) => Number(x).toLocaleString('en-US');
125
+
126
+ /** The default view: token bypasses, and with --base the ratchet. */
127
+ function tokens({ repo, ref, base, worktree, weeks, flags, say, now }) {
128
+ const head = D.bypasses(repo, ref);
129
+ if (head.config.error) { say('✗ ' + head.config.error); return 1; }
130
+ const before = base ? D.bypasses(repo, base) : null;
131
+ const findings = before ? D.ratchet(repo, before, head) : null;
132
+ const trend = weeks ? D.tokenTrend(repo, worktree ? 'HEAD' : ref, weeks, { now: worktree ? now : Date.parse(D.gitOut(repo, ['show', '-s', '--format=%cI', ref]).trim()) }) : null;
133
+ const date = new Date(now).toISOString().slice(0, 10);
134
+ const cmd = `pmos design drift --ref ${ref}${base ? ` --base ${base}` : ''}${weeks ? ` --weeks ${weeks}` : ''} --write`;
135
+ const bypass = head.total - head.totals.pageClass;
136
+ if (flags.json) {
137
+ say(JSON.stringify({ ok: true, ref, commit: head.commit, base, baseCommit: before && before.commit, config: head.config.from, tokens: head.tokens, totals: head.totals, total: head.total, swaps: head.swaps,
138
+ files: head.files.map((f) => ({ file: f.file, counts: f.counts })), findings: findings && findings.map((g) => ({ ...g, lines: g.lines.map((x) => ({ ...x, say: D.findingSay(x) })) })), trend }));
139
+ } else if (!flags.github) {
140
+ say(`${n(bypass)} places do not read a design token, ${n(head.swaps)} of them with a same-value token; ${n(head.totals.pageClass)} page-only classes (${head.commit}; config: ${head.config.from})`);
141
+ say(D.KINDS.filter((k) => k !== 'pageClass').map((k) => `${D.KIND_LABEL[k]} ${n(head.totals[k])}`).join(' · '));
142
+ if (findings) {
143
+ say(findings.length ? `${findings.length} count${findings.length === 1 ? '' : 's'} rose against ${before.commit}:` : `No count rose against ${before.commit}.`);
144
+ for (const g of findings) {
145
+ say(` ${g.file} · ${D.KIND_LABEL[g.kind]} ${g.before} → ${g.after}`);
146
+ for (const x of g.lines.slice(0, 10)) say(` line ${x.line}: ${D.findingSay(x)}`);
147
+ }
148
+ }
149
+ if (trend) say('By week: ' + trend.map((t) => `${t.week} ${t.total == null ? '–' : n(t.total)}`).join(' · '));
150
+ }
151
+ if (flags.github && findings) {
152
+ for (const g of findings) {
153
+ if (!g.lines.length) { say(`::warning file=${g.file},title=Design tokens::${D.KIND_LABEL[g.kind]} count ${g.before} → ${g.after}`); continue; }
154
+ for (const x of g.lines) say(`::warning file=${g.file},line=${x.line},title=Design tokens::${D.findingSay(x).replace(/[\r\n%]/g, ' ')}`);
155
+ }
156
+ if (!findings.length) say(`No new token bypasses against ${before.commit}.`);
157
+ }
158
+ if (flags.write) {
159
+ const file = path.join(repo, 'planning', 'reports', `design-drift-${date}-tokens.md`);
160
+ fs.mkdirSync(path.dirname(file), { recursive: true });
161
+ fs.writeFileSync(file, D.tokensMd({ date, ref, now: head, base, baseCommit: before && before.commit, findings, trend, cmd }));
162
+ if (!flags.json && !flags.github) say('Report: ' + path.relative(repo, file));
163
+ }
164
+ return flags.gate && findings && findings.length ? 1 : 0;
165
+ }
166
+
115
167
  module.exports = { run, COMMANDS, USAGE };
@@ -16,10 +16,10 @@
16
16
  * out of each page, so every page's number is about that page. Two pages built from one script read the same.
17
17
  *
18
18
  * COMPARE two commits, per page:
19
- * drift own rules grew, or the share fell by more than half a point. (More restyled parts is shown, not failed: a page rebuilt
19
+ * drift own rules grew, or the share fell by more than half a point. (More restyled parts is shown, not failed: a page moved
20
20
  * from the parts often adds a few layout rules around them.)
21
- * rebuilt the share rose 10 points or more and own rules shrank 20% or more
22
- * not rebuilt changed, but not enough to count as rebuilt
21
+ * moved the share rose 10 points or more and own rules shrank 20% or more
22
+ * partly moved changed, but not enough to count as moved
23
23
  * unchanged the same numbers
24
24
  * new · gone the page exists on one side only
25
25
  *
@@ -43,6 +43,10 @@ const DEFAULTS = Object.freeze({
43
43
  systemSheets: ['brand.css', 'charts.css', 'komorebi.css', 'documents.css', 'slides.css'],
44
44
  // the old shared shell and the bridge from its tokens: loaded by many pages, owned by none
45
45
  shellSheets: ['cozy.css', 'components.css', 'ds-bridge.css'],
46
+ // the token-bypass count (design-token-ratchet): every stylesheet, script and page here, except the system's own files and vendor code
47
+ scan: ['workspace/public/**/*.css', 'workspace/public/**/*.js', 'workspace/public/**/*.html'],
48
+ ignore: ['workspace/public/vendor/**'],
49
+ systemScripts: ['komorebi.js'],
46
50
  });
47
51
  const CONFIG_PLACES = ['pmos/design-system/design-drift.json', 'design-system/design-drift.json', 'workspace/design-system/design-drift.json'];
48
52
  const REBUILT_SHARE = 0.10;
@@ -301,9 +305,9 @@ function compare(base, head) {
301
305
  let status;
302
306
  if (!b) status = 'new';
303
307
  else if (h.ownRules > b.ownRules || h.share < b.share - SHARE_SLACK) status = 'drift';
304
- else if (h.share - b.share >= REBUILT_SHARE && h.ownRules <= b.ownRules * REBUILT_SHRINK) status = 'rebuilt';
308
+ else if (h.share - b.share >= REBUILT_SHARE && h.ownRules <= b.ownRules * REBUILT_SHRINK) status = 'moved';
305
309
  else if (h.ownRules === b.ownRules && h.classes === b.classes && h.system === b.system && h.restyled === b.restyled) status = 'unchanged';
306
- else status = 'not rebuilt';
310
+ else status = 'partly moved';
307
311
  const why = [];
308
312
  if (b && status === 'drift') {
309
313
  if (h.ownRules > b.ownRules) why.push(`own CSS +${h.ownRules - b.ownRules} rules`);
@@ -315,7 +319,7 @@ function compare(base, head) {
315
319
  return out;
316
320
  }
317
321
 
318
- /** The pages to rebuild next: lowest system share first, then the most own CSS. Pages with almost no markup are left out. */
322
+ /** The pages with the lowest system share first, then the most own CSS. Pages with almost no markup are left out. */
319
323
  function queue(pages, n = 5) {
320
324
  return pages.filter((r) => r.classes >= 20 && r.status !== 'gone').sort((a, b) => a.share - b.share || b.ownRules - a.ownRules).slice(0, n);
321
325
  }
@@ -344,7 +348,7 @@ function summary(rows, { compared = true } = {}) {
344
348
  if (!rows.length) return 'No pages found. Set "pages" in design-drift.json in your design-system folder.';
345
349
  if (!compared) return `${rows.length} pages · mean system share ${pct(meanShare(rows))}%.`;
346
350
  const n = (s) => rows.filter((r) => r.status === s).length;
347
- const parts = [`${n('drift')} drifting`, `${n('rebuilt')} rebuilt`, `${n('not rebuilt')} not rebuilt`, `${n('unchanged')} unchanged`];
351
+ const parts = [`${n('drift')} drifting`, `${n('moved')} moved`, `${n('partly moved')} partly moved`, `${n('unchanged')} unchanged`];
348
352
  if (n('new')) parts.push(`${n('new')} new`);
349
353
  if (n('gone')) parts.push(`${n('gone')} gone`);
350
354
  return `${rows.length} pages: ${parts.join(', ')}.`;
@@ -376,8 +380,8 @@ function reportMd(view) {
376
380
  }
377
381
  L.push('');
378
382
  const q = queue(rows);
379
- L.push('## Rebuild next', '');
380
- L.push(q.length ? 'One pull request per page, lowest system share first:' : 'Nothing to rebuild.', '');
383
+ L.push('## Lowest system share', '');
384
+ L.push(q.length ? 'A measure, not a work list: a page moves to the system by reading its tokens and blocks, never by being redrawn.' : 'No page has enough markup to rank.', '');
381
385
  q.forEach((r, i) => L.push(`${i + 1}. **${name(r.page)}**: ${pct(r.share)}% from the system, ${r.ownRules} own CSS rules${r.parts.length ? `; restyles ${r.parts.map((p) => `\`${p.part}\` (${p.rules})`).join(', ')}` : ''}.`));
382
386
  L.push('');
383
387
  if (view.shared && view.shared.files && view.shared.files.length) {
@@ -392,15 +396,272 @@ function reportMd(view) {
392
396
  }
393
397
  L.push('## How to read it', '',
394
398
  '- **drift**: own CSS grew, or the system share fell.',
395
- '- **rebuilt**: the system share rose 10 points or more and own CSS shrank 20% or more.',
396
- '- **not rebuilt**: the page changed, but not enough to count as rebuilt (for example, system classes added while its own CSS stayed).',
397
- '- The numbers count source, not the rendered page, so they differ from a pixel audit. A page can raise its share by adding system classes without deleting its own CSS; that is why "rebuilt" also needs its own CSS to shrink.', '');
399
+ '- **moved**: the system share rose 10 points or more and own CSS shrank 20% or more.',
400
+ '- **partly moved**: the page changed, but not enough to count as moved (for example, system classes added while its own CSS stayed).',
401
+ '- The numbers count source, not the rendered page, so they differ from a pixel audit. A page can raise its share by adding system classes without deleting its own CSS; that is why "moved" also needs its own CSS to shrink.', '');
398
402
  return L.join('\n');
399
403
  }
400
- function order(s) { return ['drift', 'not rebuilt', 'new', 'rebuilt', 'unchanged', 'gone'].indexOf(s); }
404
+ function order(s) { return ['drift', 'partly moved', 'new', 'moved', 'unchanged', 'gone'].indexOf(s); }
405
+
406
+
407
+ // ── token bypasses (initiative design-token-ratchet) ────────────────────────────────────────────────────────────────────────────────
408
+ // Wawan, 2026-11-22: a design system is reusable templates; changing one token must change every page without rewriting a page. So the
409
+ // guard counts every place that does not read a token, and a pull request may lower that count but never raise it.
410
+
411
+ const KINDS = ['colour', 'size', 'corner', 'spacing', 'shadow', 'tokenDef', 'inline', 'pageClass'];
412
+ const KIND_LABEL = { colour: 'literal colour', size: 'literal text size', corner: 'literal corner', spacing: 'literal spacing', shadow: 'literal shadow',
413
+ tokenDef: 'token defined outside the system', inline: 'inline style value', pageClass: 'page-only class' };
414
+ const COLOUR = /#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?)\([^()]*\)/g;
415
+ const LENGTH = /(?<![\w.#/-])(-?\d*\.?\d+)(px|rem|em)\b/g;
416
+ const RADIUS_PROP = /^border(?:-[a-z]+)*-radius$/;
417
+ const SPACE_PROP = /^(?:(?:padding|margin)(?:-(?:top|right|bottom|left|inline|block)(?:-(?:start|end))?)?|(?:row-|column-)?gap)$/;
418
+
419
+ /** Text with var(...) removed, nested parentheses included: a literal inside var(--token, fallback) reads the token. */
420
+ function dropVars(v) {
421
+ let out = String(v); let guard = 0;
422
+ while (/var\(/.test(out) && guard++ < 50) {
423
+ const i = out.indexOf('var(');
424
+ let depth = 0; let j = i + 3;
425
+ for (; j < out.length; j++) { if (out[j] === '(') depth++; else if (out[j] === ')' && --depth === 0) break; }
426
+ out = out.slice(0, i) + out.slice(j + 1);
427
+ }
428
+ return out;
429
+ }
430
+ const normColour = (c) => {
431
+ let x = String(c).toLowerCase().replace(/\s+/g, '');
432
+ if (/^#[0-9a-f]{3}$/.test(x)) x = '#' + x.slice(1).split('').map((d) => d + d).join('');
433
+ return x;
434
+ };
435
+ const normSpace = (v) => String(v).replace(/\s+/g, ' ').replace(/\s*,\s*/g, ', ').trim().toLowerCase();
436
+ const pxOf = (n, unit) => (unit === 'px' ? Number(n) : Number(n) * 16);
437
+
438
+ /** The system's tokens from its sheets: the first value of each custom property that is a literal (not an alias). */
439
+ function tokensOf(sheets) {
440
+ const t = new Map();
441
+ for (const css of sheets) {
442
+ for (const m of String(css).replace(/\/\*[\s\S]*?\*\//g, '').matchAll(/(--[a-zA-Z0-9-]+)\s*:\s*([^;{}]+)/g)) {
443
+ const name = m[1]; const val = m[2].trim();
444
+ if (!t.has(name) && !/var\(/.test(val)) t.set(name, val);
445
+ }
446
+ }
447
+ return t;
448
+ }
449
+
450
+ /** The token a literal should read: { token, same } — same means the token has exactly this value (a swap, no change in the light theme). */
451
+ function tokenFor(kind, literal, tokens) {
452
+ const all = [...tokens.entries()];
453
+ if (kind === 'colour') {
454
+ const hit = all.find(([, v]) => normColour(v) === normColour(literal));
455
+ return hit ? { token: hit[0], same: true } : { token: null, same: false };
456
+ }
457
+ if (kind === 'shadow') {
458
+ const hit = all.find(([n, v]) => /shadow|lift|raise|glow/.test(n) && normSpace(v) === normSpace(literal));
459
+ return hit ? { token: hit[0], same: true } : { token: null, same: false };
460
+ }
461
+ const family = kind === 'corner' ? /^--radius-/ : kind === 'spacing' ? /^--space-/ : kind === 'size' ? /^--(?:type|fs|font-size)-/ : null;
462
+ if (!family) return { token: null, same: false };
463
+ const px = []; for (const m of String(literal).matchAll(LENGTH)) px.push(pxOf(m[1], m[2]));
464
+ const cands = all.filter(([n, v]) => family.test(n) && /^-?\d*\.?\d+(px|rem)$/.test(v.trim())).map(([n, v]) => { const m = v.trim().match(/^(-?\d*\.?\d+)(px|rem)$/); return [n, pxOf(m[1], m[2])]; });
465
+ if (!cands.length || !px.length) return { token: null, same: false };
466
+ // each length on its own: a same-value token replaces it, 0 stays; `fix` is the value with every same-value length swapped
467
+ let same = true; const near = [];
468
+ const fix = String(literal).replace(LENGTH, (m, n, u) => {
469
+ const p = pxOf(n, u);
470
+ if (p === 0) return m;
471
+ const exact = cands.find(([, v]) => v === Math.abs(p));
472
+ if (exact) return p < 0 ? `calc(-1 * var(${exact[0]}))` : `var(${exact[0]})`;
473
+ same = false;
474
+ near.push(`${m} → ${cands.slice().sort((x, y) => Math.abs(x[1] - Math.abs(p)) - Math.abs(y[1] - Math.abs(p)))[0][0]}`);
475
+ return m;
476
+ }).trim();
477
+ return { token: same ? fix : near.join(', '), same };
478
+ }
479
+
480
+ /** Bypasses in one stylesheet's text: [{ kind, line, prop, value, token, same }]. PURE. */
481
+ function cssBypasses(css, tokens) {
482
+ const out = [];
483
+ const lines = String(css || '').replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' ')).split('\n');
484
+ lines.forEach((text, i) => {
485
+ for (const m of text.matchAll(/(?:^|[{;\s])(--[a-zA-Z0-9-]+|[a-z][a-z-]*)\s*:\s*([^;{}]+)/g)) {
486
+ const prop = m[1]; const raw = m[2].trim();
487
+ if (!raw) continue; // a selector's pseudo-class (a:hover {) reads as a property no kind uses, so it never counts
488
+ const line = i + 1;
489
+ if (prop.startsWith('--')) { out.push({ kind: 'tokenDef', line, prop, value: raw, token: null, same: false }); continue; }
490
+ const v = dropVars(raw);
491
+ for (const c of v.matchAll(COLOUR)) { if (prop === 'box-shadow' || prop === 'text-shadow') break; const t = tokenFor('colour', c[0], tokens); out.push({ kind: 'colour', line, prop, value: c[0], ...t }); }
492
+ const hasLen = () => [...v.matchAll(LENGTH)].some((x) => Number(x[1]) !== 0);
493
+ if ((prop === 'font-size' || prop === 'font') && hasLen()) out.push({ kind: 'size', line, prop, value: v.trim(), ...tokenFor('size', v, tokens) });
494
+ else if (RADIUS_PROP.test(prop) && hasLen()) out.push({ kind: 'corner', line, prop, value: v.trim(), ...tokenFor('corner', v, tokens) });
495
+ else if (SPACE_PROP.test(prop) && hasLen()) out.push({ kind: 'spacing', line, prop, value: v.trim(), ...tokenFor('spacing', v, tokens) });
496
+ else if ((prop === 'box-shadow' || prop === 'text-shadow') && /\d/.test(v) && !/^\s*(none|0)\s*$/.test(v)) out.push({ kind: 'shadow', line, prop, value: v.trim(), ...tokenFor('shadow', raw, tokens) });
497
+ }
498
+ });
499
+ return out;
500
+ }
501
+
502
+ const INLINE = [/\bstyle\s*=\s*"([^"]*)"/g, /\bstyle\s*=\s*'([^']*)'/g, /\.style\.[a-zA-Z]+\s*=\s*["'`]([^"'`]*)["'`]/g, /\bcssText\s*[+]?=\s*["'`]([^"'`]*)["'`]/g,
503
+ /\bstyle\s*:\s*["'`]([^"'`]*)["'`]/g, /\.setProperty\(\s*["'][^"']+["']\s*,\s*["'`]([^"'`]*)["'`]/g];
504
+ /** Bypasses in one script or page: inline style values with a literal, and page-only classes. PURE. */
505
+ function scriptBypasses(src, systemAll) {
506
+ const out = [];
507
+ String(src || '').split('\n').forEach((text, i) => {
508
+ const line = i + 1;
509
+ for (const re of INLINE) for (const m of text.matchAll(re)) {
510
+ const v = dropVars(m[1].replace(/\$\{[^}]*\}/g, ''));
511
+ if (COLOUR.test(v) || [...v.matchAll(LENGTH)].some((x) => Number(x[1]) !== 0)) out.push({ kind: 'inline', line, prop: 'style', value: m[1].trim().slice(0, 80), token: null, same: false });
512
+ COLOUR.lastIndex = 0;
513
+ }
514
+ for (const c of classesOf(text)) if (!systemAll.has(c)) out.push({ kind: 'pageClass', line, prop: 'class', value: c, token: null, same: false });
515
+ });
516
+ return out;
517
+ }
518
+
519
+ /** Every class a system sheet names anywhere (parts, states, scopes). */
520
+ function systemClassesAll(sheets) {
521
+ const all = new Set();
522
+ for (const css of sheets) for (const r of rulesOf(css)) for (const c of selectorClasses(r.selector)) all.add(c);
523
+ return all;
524
+ }
525
+
526
+ /** Read many files of one commit in one git call (or from disk for WORKTREE). → Map path → text */
527
+ function readMany(repo, ref, paths) {
528
+ const out = new Map();
529
+ if (!paths.length) return out;
530
+ if (isWorktree(ref)) { for (const p of paths) { try { out.set(p, fs.readFileSync(path.join(repo, p), 'utf8')); } catch { /* gone */ } } return out; }
531
+ const { spawnSync } = require('child_process');
532
+ const r = spawnSync('git', ['-C', repo, 'cat-file', '--batch'], { input: paths.map((p) => `${ref}:${p}`).join('\n') + '\n', maxBuffer: 1 << 30 });
533
+ const buf = r.stdout || Buffer.alloc(0);
534
+ let pos = 0;
535
+ for (const p of paths) {
536
+ const nl = buf.indexOf(10, pos); if (nl < 0) break;
537
+ const head = buf.slice(pos, nl).toString();
538
+ pos = nl + 1;
539
+ if (/ missing$/.test(head)) continue;
540
+ const size = Number(head.split(' ')[2]);
541
+ out.set(p, buf.slice(pos, pos + size).toString('utf8'));
542
+ pos += size + 1;
543
+ }
544
+ return out;
545
+ }
546
+
547
+ /** Count the token bypasses of every scanned file at one commit. → { ref, commit, config, files: [{ file, counts, findings }], totals, swaps } */
548
+ function bypasses(repo, ref, { files: given } = {}) {
549
+ const R = given ? null : readerOf(repo, ref);
550
+ const all = given ? Object.keys(given) : R.list();
551
+ const read1 = given ? (p) => (p in given ? given[p] : null) : R.read;
552
+ const cfg = configAt(read1);
553
+ const isSystem = endsWithName(cfg.systemSheets);
554
+ const isSysJs = endsWithName(cfg.systemScripts || []);
555
+ const scan = (cfg.scan || []).map(globRe); const ignore = (cfg.ignore || []).map(globRe);
556
+ const sysPaths = all.filter((p) => /\.css$/i.test(p) && isSystem(p));
557
+ const targets = all.filter((p) => /\.(css|m?js|html?)$/i.test(p) && scan.some((re) => re.test(p)) && !ignore.some((re) => re.test(p)) && !isSystem(p) && !isSysJs(p)).sort();
558
+ const texts = given ? new Map([...sysPaths, ...targets].map((p) => [p, given[p]])) : readMany(repo, ref, [...sysPaths, ...targets]);
559
+ const sysTexts = sysPaths.map((p) => texts.get(p)).filter((t) => t != null);
560
+ const tokens = tokensOf(sysTexts);
561
+ const sysAll = systemClassesAll(sysTexts);
562
+ const files = [];
563
+ const totals = Object.fromEntries(KINDS.map((k) => [k, 0]));
564
+ let swaps = 0;
565
+ for (const f of targets) {
566
+ const text = texts.get(f);
567
+ if (text == null) continue;
568
+ let findings;
569
+ if (/\.css$/i.test(f)) findings = cssBypasses(text, tokens);
570
+ else if (/\.html?$/i.test(f)) {
571
+ const styles = [...text.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)];
572
+ findings = scriptBypasses(text.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, (b) => b.replace(/[^\n]/g, ' ')), sysAll);
573
+ for (const st of styles) { const off = text.slice(0, st.index).split('\n').length - 1; for (const x of cssBypasses(st[1], tokens)) findings.push({ ...x, line: x.line + off }); }
574
+ } else findings = scriptBypasses(text, sysAll);
575
+ const counts = Object.fromEntries(KINDS.map((k) => [k, 0]));
576
+ for (const x of findings) { counts[x.kind]++; totals[x.kind]++; if (x.same) swaps++; }
577
+ files.push({ file: f, counts, findings });
578
+ }
579
+ const commit = given ? null : (isWorktree(ref) ? 'WORKTREE' : (gitOut(repo, ['rev-parse', '--short', ref]) || '').trim() || null);
580
+ return { ref: isWorktree(ref) ? 'WORKTREE' : ref, commit, config: cfg, tokens: tokens.size, files, totals, total: Object.values(totals).reduce((a, b) => a + b, 0), swaps };
581
+ }
582
+
583
+ /** The lines a commit range added to one file (base → head; head WORKTREE compares with the files on disk). */
584
+ function addedLines(repo, base, head, file) {
585
+ const args = isWorktree(head) ? ['diff', '-U0', base, '--', file] : ['diff', '-U0', base, head, '--', file];
586
+ const out = gitOut(repo, args) || '';
587
+ const lines = new Set();
588
+ for (const m of out.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) { const a = Number(m[1]); const n = m[2] === undefined ? 1 : Number(m[2]); for (let i = 0; i < n; i++) lines.add(a + i); }
589
+ return lines;
590
+ }
591
+
592
+ /** The ratchet: every file whose count of a kind rose from base to head. → [{ file, kind, before, after, lines: [finding] }] */
593
+ function ratchet(repo, base, head, { addedOf = addedLines } = {}) {
594
+ const before = new Map(base.files.map((f) => [f.file, f.counts]));
595
+ const out = [];
596
+ for (const f of head.files) {
597
+ const b = before.get(f.file) || Object.fromEntries(KINDS.map((k) => [k, 0]));
598
+ const rose = KINDS.filter((k) => f.counts[k] > b[k]);
599
+ if (!rose.length) continue;
600
+ const added = before.has(f.file) ? addedOf(repo, base.ref, head.ref, f.file) : null;
601
+ for (const k of rose) out.push({ file: f.file, kind: k, before: b[k], after: f.counts[k], lines: f.findings.filter((x) => x.kind === k && (!added || added.has(x.line))) });
602
+ }
603
+ return out;
604
+ }
605
+
606
+ /** One line for a finding: what bypasses which token. */
607
+ function findingSay(x) {
608
+ const what = `${KIND_LABEL[x.kind]} ${x.kind === 'pageClass' ? '.' + x.value : x.value}`;
609
+ if (x.kind === 'tokenDef') return `${what}: define tokens in the design system only`;
610
+ if (x.kind === 'pageClass') return `${what}: use a system part`;
611
+ if (x.kind === 'inline') return `${what}: use a class that reads the tokens`;
612
+ if (x.token && x.same) return `${what}: use ${/^--/.test(x.token) ? `var(${x.token})` : x.token} (same value)`;
613
+ if (x.token) return `${what}: nearest token ${x.token}`;
614
+ return `${what}: the system has no token for this yet`;
615
+ }
616
+
617
+ /** The token report as markdown. view = { date, ref, commit, now: bypasses(), base, baseCommit, findings, trend, cmd } */
618
+ function tokensMd(view) {
619
+ const { date, now } = view;
620
+ const L = [];
621
+ L.push('---', 'type: Reference', `title: "Design token bypasses ${date}"`, `timestamp: ${date}`, '---', '');
622
+ L.push(`# Design token bypasses, ${date}`, '');
623
+ L.push(`**${(now.total - now.totals.pageClass).toLocaleString('en-US')} places do not read a design token. ${now.swaps.toLocaleString('en-US')} of them have a token with the same value, so swapping them changes nothing in the light theme. ${now.totals.pageClass.toLocaleString('en-US')} classes are page-only: the system does not define them.**`, '');
624
+ L.push(`Goal (Wawan, 2026-11-22): change one token and every page follows, with no page rewritten. Each place counted here is a place a token change does not reach. Made by \`${view.cmd}\` at \`${now.commit}\` (initiative design-token-ratchet). Config: ${now.config.from}. ${now.tokens} tokens read from the system sheets.`, '');
625
+ L.push('## By kind', '', '| Kind | Count | Same-value swaps |', '|---|---|---|');
626
+ for (const k of KINDS) L.push(`| ${KIND_LABEL[k]} | ${now.totals[k].toLocaleString('en-US')} | ${now.files.reduce((n, f) => n + f.findings.filter((x) => x.kind === k && x.same).length, 0).toLocaleString('en-US')} |`);
627
+ L.push('');
628
+ const top = now.files.map((f) => ({ f, n: KINDS.filter((k) => k !== 'pageClass').reduce((a, k) => a + f.counts[k], 0) })).filter((x) => x.n).sort((a, b) => b.n - a.n).slice(0, 15);
629
+ L.push('## Files with the most bypasses', '', 'Page-only classes left out of this ranking.', '', '| File | Colours | Sizes | Corners | Spacing | Shadows | Tokens defined | Inline |', '|---|---|---|---|---|---|---|---|');
630
+ for (const { f } of top) L.push(`| ${f.file.replace(/^workspace\/public\//, '')} | ${f.counts.colour} | ${f.counts.size} | ${f.counts.corner} | ${f.counts.spacing} | ${f.counts.shadow} | ${f.counts.tokenDef} | ${f.counts.inline} |`);
631
+ L.push('');
632
+ if (view.findings) {
633
+ L.push('## New bypasses against the base', '', view.findings.length ? `Compared with \`${view.baseCommit}\`:` : `None against \`${view.baseCommit}\`.`, '');
634
+ for (const g of view.findings) { L.push(`- \`${g.file}\` ${KIND_LABEL[g.kind]}: ${g.before} → ${g.after}`); for (const x of g.lines.slice(0, 10)) L.push(` - line ${x.line}: ${findingSay(x)}`); }
635
+ L.push('');
636
+ }
637
+ if (view.trend && view.trend.length) {
638
+ L.push('## Trend', '', 'Total bypasses at the last commit of each week (page-only classes counted separately):', '', '| Week ending | Commit | Bypasses | Page-only classes |', '|---|---|---|---|');
639
+ for (const t of view.trend) L.push(`| ${t.week} | ${t.commit ? '`' + t.commit + '`' : 'none'} | ${t.total == null ? '' : t.total.toLocaleString('en-US')} | ${t.pageClass == null ? '' : t.pageClass.toLocaleString('en-US')} |`);
640
+ L.push('');
641
+ }
642
+ L.push('## How it is used', '',
643
+ '- On every pull request, CI compares each file with the base. A count may fall, never rise. A rise names the line and the token it should read. CI only warns until Wawan decides to block (reminder 2026-11-29).',
644
+ '- The only changes this check proposes are same-value swaps: a literal replaced by the token that has that value. It never rewrites a page.',
645
+ '- A literal inside `var(--token, fallback)` reads the token and is not counted. A colour swap is the same in the light theme; in the dark theme the line then follows the token, as every other line does.', '');
646
+ return L.join('\n');
647
+ }
648
+
649
+ /** Totals per week from the commit at the end of each week, oldest first. */
650
+ function tokenTrend(repo, ref, weeks, { now = Date.now() } = {}) {
651
+ const out = [];
652
+ for (let i = weeks - 1; i >= 0; i--) {
653
+ const end = new Date(now - i * 7 * 86400000);
654
+ const sha = (gitOut(repo, ['rev-list', '-1', `--before=${end.toISOString()}`, ref]) || '').trim();
655
+ if (!sha) { out.push({ week: end.toISOString().slice(0, 10), commit: null, total: null, pageClass: null }); continue; }
656
+ const b = bypasses(repo, sha);
657
+ out.push({ week: end.toISOString().slice(0, 10), commit: sha.slice(0, 8), total: b.total - b.totals.pageClass, pageClass: b.totals.pageClass });
658
+ }
659
+ return out;
660
+ }
401
661
 
402
662
  module.exports = {
403
663
  DEFAULTS, CONFIG_PLACES, REBUILT_SHARE, REBUILT_SHRINK,
404
664
  rulesOf, selectorClasses, splitSelectors, compoundsOf, systemOf, classesOf, importsOf, colourCount, globRe, resolveRef,
665
+ KINDS, KIND_LABEL, dropVars, tokensOf, tokenFor, cssBypasses, scriptBypasses, systemClassesAll, readMany, bypasses, addedLines, ratchet, findingSay, tokensMd, tokenTrend,
405
666
  configAt, readerOf, measure, compare, queue, meanShare, trend, summary, reportMd, gitOut,
406
667
  };
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
  /* routes-spec-critic.js — the sceptical reviewer's routes (initiative spec-critic; lib/spec-critic.js).
3
3
  *
4
- * POST /api/spec-critic { path, ws? } → { ok, run, file, questions, dropped, lenses, added } | { ok: false, error }
4
+ * POST /api/spec-critic { path, ws?, as? } → { ok, run, file, readers, questions, dropped, lenses, added } | { ok: false, error }
5
+ * as: who reads it, 'cfo,engineer,sceptic' | 'all' | a list (none: the sceptic alone); an unknown reader is a 400.
5
6
  * one critic pass on a markdown, text or HTML document: a path relative to the workspace (it must stay inside it) or a full path.
6
7
  * `pmos critic <file>` reaches it with no Origin (D98, like `pmos lab critic`); from a page it needs a page press.
7
8
  * GET /api/spec-critic?path=&ws= → { ok, run: <the newest run on that file> | null, changed } a read; changed: the file differs from
@@ -40,16 +41,18 @@ async function run(ctx, res, b) {
40
41
  const w = wsOf(ctx, typeof b.ws === 'string' && b.ws ? b.ws : null);
41
42
  const d = docOf(w, b.path);
42
43
  if (!d.ok) return fail(ctx, res, d.status, d.error);
44
+ const rd = SC.readersOf(b.as);
45
+ if (!rd.ok) return fail(ctx, res, 400, rd.error);
43
46
  if (SC.off(process.env)) return fail(ctx, res, 409, 'the critic is off (PMOS_CRITIC=off)');
44
47
  let raw = ''; try { raw = fs.readFileSync(d.abs, 'utf8'); } catch { return fail(ctx, res, 400, 'the document could not be read'); }
45
- const K = SC.lensesFor(w ? w.root : '');
48
+ const K = SC.lensesFor(w ? w.root : '', { as: rd.readers });
46
49
  const text = SC.textOf(raw, d.abs);
47
50
  const ask = typeof ctx.specCritic === 'function' ? ctx.specCritic : SC.askVia(ctx.spawnSession);
48
51
  const r = await SC.critique(ask, { lenses: K.lenses, text: raw, file: d.abs });
49
52
  const id = ctx.runtimeDir ? SC.record(ctx.runtimeDir, { from: String(b.from || 'cli'), ws: w ? w.id : '', file: d.abs, sha: SC.sha(text), chars: text.length,
50
- lenses: r.lenses || [], ok: r.ok, why: r.why, questions: r.questions, dropped: r.dropped, ms: r.ms }) : null;
53
+ lenses: r.lenses || [], readers: K.readers, ok: r.ok, why: r.why, questions: r.questions, dropped: r.dropped, ms: r.ms }) : null;
51
54
  if (!r.ok) return fail(ctx, res, r.off ? 409 : 502, r.why);
52
- ctx.json(res, { ok: true, run: id, file: d.abs, questions: r.questions, dropped: r.dropped, lenses: r.lenses.length, added: K.added, from: K.from });
55
+ ctx.json(res, { ok: true, run: id, file: d.abs, readers: K.readers, questions: r.questions, dropped: r.dropped, lenses: r.lenses.length, added: K.added, from: K.from });
53
56
  return true;
54
57
  }
55
58
 
@@ -11,6 +11,12 @@
11
11
  * parse() keeps a question only when it names a known lens AND its quote is found in the document (case, whitespace, quote marks and
12
12
  * markdown emphasis ignored), so the PM never prepares for a question about words the document does not hold. At most 3 (MAX_QUESTIONS).
13
13
  *
14
+ * READERS (initiative review-lenses-cfo-engineer-sceptic, bet A110: a CFO, engineer and sceptic read of 5 real reports on 2 products left
15
+ * unanswered questions in all 15 reader reviews). The PM chooses who reads: `--as cfo,engineer,sceptic` or `--as all`. Each lens belongs
16
+ * to one reader: the CFO (cost, return, cost-of-delay), the engineering lead (feasibility, dependency, capacity), the sceptic (the base
17
+ * lenses). A product question joins a reader with "reader": "<id>" (none: the sceptic). With no reader given, the sceptic reads alone, as
18
+ * before. One run reads for every chosen reader; each reader keeps at most PER_READER (2) questions when several read, 3 when one reads.
19
+ *
14
20
  * THE RUN. One read-only session through the design critic's ask path (lib/design-critic.js askVia, origin `briefing-ask:spec-critic:<key>`,
15
21
  * kind `ask`). The document's text is in the prompt, so the run needs no file. A run that cannot start, times out or answers nonsense
16
22
  * files no questions, and the ledger says it did not run. PMOS_CRITIC=off runs none (the same switch as the design critic).
@@ -19,12 +25,13 @@
19
25
  * it when the PM says they are about to share a document. GET /api/spec-critic gives a page the latest run on a file.
20
26
  *
21
27
  * THE LEDGER. <runtime>/spec-critic.jsonl, append-only: { kind: 'run', id, at, from, ws?, file, sha, chars, lenses, ok, why?,
22
- * questions: [{ lens, title, question, quote, why, fix }], dropped, ms } and { kind: 'label', run, n, label: real | noise, by, at } (the PM's
23
- * word on question n, 1-based; the newest label wins). stats() counts them, and lists a lens flagged in 2 or more documents as a repeat:
28
+ * readers?, questions: [{ reader?, lens, title, question, quote, why, fix }], dropped, ms } and { kind: 'label', run, n, label: real | noise, by, at } (the PM's
29
+ * word on question n, 1-based; the newest label wins). stats() counts them (byReader: each reader's questions, real, noise), and lists a lens flagged in 2 or more documents as a repeat:
24
30
  * the same gap in several documents points at the template or generator that made them.
25
31
  *
26
32
  * BASE · ORIGIN · MAX_QUESTIONS · MAX_CHARS · DOC_RE · off(env)
27
- * questionsOf(json, rel) PURE → [lens] · lensesFor(root) → { lenses, from, added }
33
+ * READERS · readersOf(as) PURE → { ok, readers } | { ok: false, error } · readerList(ids) PURE → 'a CFO and a sceptic'
34
+ * questionsOf(json, rel) PURE → [lens] · lensesFor(root, { as? }) → { lenses, from, added, readers }
28
35
  * textOf(raw, file) PURE → the text the critic reads (HTML without its tags) · norm(s) PURE · sha(text) PURE
29
36
  * promptOf({ lenses, text, file, product? }) PURE → string
30
37
  * parse(answer, lenses, text) PURE → { questions, dropped } | null (null: the answer could not be read)
@@ -38,13 +45,44 @@ const DC = require('./design-critic.js');
38
45
 
39
46
  const FILE = 'spec-critic.jsonl';
40
47
  const ORIGIN = 'briefing-ask:spec-critic:';
41
- const MAX_QUESTIONS = 3, MAX_CHARS = 80000, MAX_RULE = 500, MIN_QUOTE = 6;
48
+ const MAX_QUESTIONS = 3, PER_READER = 2, MAX_ALL = 6, MAX_CHARS = 80000, MAX_RULE = 500, MIN_QUOTE = 6;
42
49
  const DOC_RE = /\.(md|markdown|txt|html?)$/i;
43
50
  const ID_RE = /^[a-z0-9][a-z0-9-]{0,59}$/;
44
51
  const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
45
52
  const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
46
53
  const off = (env) => DC.off(env);
47
54
 
55
+ /* ── the readers: who reads the document before it is shared ── */
56
+ const READERS = Object.freeze({
57
+ cfo: Object.freeze({ id: 'cfo', name: 'CFO', article: 'a', who: 'the CFO or finance partner who has to fund it and answer for what it costs' }),
58
+ engineer: Object.freeze({ id: 'engineer', name: 'engineering lead', article: 'an', who: 'the engineering lead who has to build it, run it and commit a team to it' }),
59
+ sceptic: Object.freeze({ id: 'sceptic', name: 'sceptic', article: 'a', who: 'the most sceptical senior reader in the room, who has to say yes' }),
60
+ });
61
+ const READER_IDS = Object.freeze(Object.keys(READERS));
62
+ const DEFAULT_READERS = Object.freeze(['sceptic']);
63
+ /** 'all' | 'cfo,engineer' | ['cfo'] | empty → { ok, readers (in reader order) } | { ok: false, error }. Empty: the sceptic alone. */
64
+ function readersOf(as) {
65
+ const given = (Array.isArray(as) ? as : String(as == null ? '' : as).split(',')).map((x) => String(x).trim().toLowerCase()).filter(Boolean);
66
+ if (!given.length) return { ok: true, readers: [...DEFAULT_READERS] };
67
+ if (given.includes('all')) return { ok: true, readers: [...READER_IDS] };
68
+ const unknown = given.filter((x) => !READERS[x]);
69
+ if (unknown.length) return { ok: false, error: `no reader ${unknown.map((x) => one(x, 30)).join(', ')}: the readers are ${READER_IDS.join(', ')} (or all)` };
70
+ return { ok: true, readers: READER_IDS.filter((r) => given.includes(r)) };
71
+ }
72
+ const readerList = (ids) => { const n = ids.map((r) => `${READERS[r].article} ${READERS[r].name}`); return n.length < 2 ? n.join('') : n.slice(0, -1).join(', ') + ' and ' + n[n.length - 1]; };
73
+
74
+ /* ── the CFO's and the engineering lead's lenses ── */
75
+ const CFO = [
76
+ { id: 'cost', title: 'What does it cost?', rule: 'No cost, budget, price, headcount or effort is stated, or a cost is left out on purpose, so the money asked for cannot be judged.' },
77
+ { id: 'return', title: 'What do we get back?', rule: 'No revenue, saving, retention or other value is tied to the cost, or the return has no number and no date.' },
78
+ { id: 'cost-of-delay', title: 'What does a slip cost?', rule: 'A date or a choice between dates is given with no cost of delay, no money at risk and no fallback if it slips.' },
79
+ ].map((c) => ({ ...c, reader: 'cfo', source: 'PMOS reader lenses' }));
80
+ const ENGINEER = [
81
+ { id: 'feasibility', title: 'Can it be built as written?', rule: 'A date, estimate or scope comes before the work it depends on (tests, sign-off, design), or no approach, stack or estimate is named.' },
82
+ { id: 'dependency', title: 'What does it wait on?', rule: 'A team, system, vendor, contract, data or decision the work needs is not named, not confirmed, or has no date.' },
83
+ { id: 'capacity', title: 'Who builds it, with what?', rule: 'No named team, people or effort for the build, or the work is called small or easy with nothing to show it.' },
84
+ ].map((c) => ({ ...c, reader: 'engineer', source: 'PMOS reader lenses' }));
85
+
48
86
  /* ── the base lenses: what a sceptical reviewer asks of any spec, strategy, roadmap or report ── */
49
87
  const BASE = Object.freeze([
50
88
  { id: 'evidence', title: 'What is the evidence?', rule: 'A claim, number, need or user problem stated with no source, data or example behind it.' },
@@ -55,7 +93,8 @@ const BASE = Object.freeze([
55
93
  { id: 'owner', title: 'Who decides, and by when?', rule: 'No owner, no date, or no clear decision or action asked of the reader.' },
56
94
  { id: 'contradiction', title: 'Which part is true?', rule: 'Two parts of the document disagree, or a summary says something its own detail contradicts.' },
57
95
  { id: 'unverified', title: 'Is it real yet?', rule: 'A status, delivery or result is claimed but marked unverified, assumed, or never checked.' },
58
- ].map((c) => Object.freeze({ ...c, source: 'PMOS base lenses' })));
96
+ ].map((c) => Object.freeze({ ...c, reader: 'sceptic', source: 'PMOS base lenses' })));
97
+ const ALL = Object.freeze([...CFO.map((c) => Object.freeze(c)), ...ENGINEER.map((c) => Object.freeze(c)), ...BASE]);
59
98
 
60
99
  /* ── the product's own reviewer questions ── */
61
100
  function questionsOf(json, rel = 'review-questions.json') {
@@ -65,16 +104,21 @@ function questionsOf(json, rel = 'review-questions.json') {
65
104
  const out = [], seen = new Set();
66
105
  for (const q of list) {
67
106
  if (!isObj(q) || !ID_RE.test(String(q.id || '')) || !one(q.title, 120) || !one(q.rule, MAX_RULE) || seen.has(q.id)) continue;
107
+ const reader = q.reader == null || q.reader === '' ? null : String(q.reader).trim().toLowerCase();
108
+ if (reader && !READERS[reader]) continue;
68
109
  seen.add(q.id);
69
- out.push({ id: q.id, title: one(q.title, 120), rule: one(q.rule, MAX_RULE), source: one([q.source, q.date].filter(Boolean).join(', ') || rel, 160) });
110
+ out.push({ id: q.id, title: one(q.title, 120), rule: one(q.rule, MAX_RULE), ...(reader ? { reader } : {}), source: one([q.source, q.date].filter(Boolean).join(', ') || rel, 160) });
70
111
  }
71
112
  return out;
72
113
  }
73
114
  const readOr = (abs) => { try { return fs.readFileSync(abs, 'utf8'); } catch { return null; } };
74
- /** The base lenses plus the product's own reviewer questions (an id that is a base lens replaces it). */
75
- function lensesFor(root) {
115
+ /** The chosen readers' lenses plus the product's own reviewer questions for them (an id that is a PMOS lens replaces it; a product
116
+ * question with no reader keeps the reader of the lens it replaces, else joins the sceptic). No reader given: the sceptic alone. */
117
+ function lensesFor(root, { as } = {}) {
76
118
  const R = String(root || '');
77
- let lenses = BASE.map((c) => ({ ...c }));
119
+ const rd = readersOf(as);
120
+ const readers = rd.ok ? rd.readers : [...DEFAULT_READERS];
121
+ let lenses = ALL.map((c) => ({ ...c }));
78
122
  const from = [];
79
123
  let added = 0;
80
124
  if (R) {
@@ -84,13 +128,21 @@ function lensesFor(root) {
84
128
  const t = readOr(path.join(R, rel)); if (t == null) continue;
85
129
  const qs = questionsOf(t, rel);
86
130
  if (!qs.length) continue;
87
- for (const q of qs) { const i = lenses.findIndex((l) => l.id === q.id); if (i >= 0) lenses[i] = q; else lenses.push(q); added++; }
131
+ for (const q of qs) {
132
+ const i = lenses.findIndex((l) => l.id === q.id);
133
+ const lens = { ...q, reader: q.reader || (i >= 0 ? lenses[i].reader : 'sceptic') };
134
+ if (i >= 0) lenses[i] = lens; else lenses.push(lens);
135
+ if (readers.includes(lens.reader)) added++;
136
+ }
88
137
  from.push(rel);
89
138
  break;
90
139
  }
91
140
  }
92
- return { lenses, from, added };
141
+ lenses = lenses.filter((l) => readers.includes(l.reader));
142
+ return { lenses, from: added ? from : [], added, readers };
93
143
  }
144
+ const readersIn = (lenses) => READER_IDS.filter((r) => lenses.some((l) => (l.reader || 'sceptic') === r));
145
+ const capOf = (readers) => (readers.length > 1 ? PER_READER : MAX_QUESTIONS);
94
146
 
95
147
  /* ── the text ── */
96
148
  /** What the critic reads: an HTML page without its scripts, styles and tags; any other document as it is. At most MAX_CHARS. */
@@ -112,10 +164,23 @@ const sha = (text) => crypto.createHash('sha1').update(String(text || '')).diges
112
164
 
113
165
  /* ── the run ── */
114
166
  function promptOf({ lenses, text, file = '', product = '' }) {
167
+ const readers = readersIn(lenses);
168
+ const about = `${product ? ' about ' + one(product, 80) : ''}${file ? ' (' + one(path.basename(file), 120) + ')' : ''}`;
169
+ const solo = readers.length < 2 ? (readers[0] || 'sceptic') : null;
170
+ const open = solo === 'sceptic'
171
+ ? `You are PMOS's sceptical reviewer. The user is about to share this document${about}. Read it as the most sceptical senior reader in the room would: an executive, an engineering lead, or a finance partner who has to say yes. List the hardest questions that reader would ask, so the user can answer them before sharing. Do not write or change anything.`
172
+ : solo
173
+ ? `You are PMOS's ${READERS[solo].name} reviewer. The user is about to share this document${about}. Read it as ${READERS[solo].who} would. List the hardest questions that reader would ask, so the user can answer them before sharing. Do not write or change anything.`
174
+ : `You are PMOS's review panel. The user is about to share this document${about}. Read it ${readers.length} times, once as each of these readers, and list the hardest questions each would ask, so the user can answer them before sharing. Do not write or change anything.\n` + readers.map((r) => `- ${READERS[r].name}: ${READERS[r].who}.`).join('\n');
175
+ const lensLine = (l) => `[${l.id}] ${l.title} ${l.rule}`;
176
+ const lensBlock = solo
177
+ ? 'The lenses. Each question must name exactly one of these ids:\n' + lenses.map(lensLine).join('\n')
178
+ : 'The lenses, by reader. Each question must name exactly one of these ids; the id says which reader asks it:\n' + readers.map((r) => `${READERS[r].name}:\n` + lenses.filter((l) => (l.reader || 'sceptic') === r).map(lensLine).join('\n')).join('\n');
179
+ const cap = solo ? `At most ${MAX_QUESTIONS} questions, the hardest first.` : `At most ${PER_READER} questions for each reader, the hardest first; a reader with nothing hard asks nothing.`;
115
180
  return [
116
- `You are PMOS's sceptical reviewer. The user is about to share this document${product ? ' about ' + one(product, 80) : ''}${file ? ' (' + one(path.basename(file), 120) + ')' : ''}. Read it as the most sceptical senior reader in the room would: an executive, an engineering lead, or a finance partner who has to say yes. List the hardest questions that reader would ask, so the user can answer them before sharing. Do not write or change anything.`,
117
- 'The lenses. Each question must name exactly one of these ids:\n' + lenses.map((l) => `[${l.id}] ${l.title} ${l.rule}`).join('\n'),
118
- `Rules. At most ${MAX_QUESTIONS} questions, the hardest first. Each question quotes the document's own words it rests on, copied exactly (a few words to one sentence). For something missing, quote the heading or sentence where it should be. A question whose quote is not in the document is thrown away. Give the smallest fix the user can make before sharing, in one line. No praise, no style or grammar notes, no question the document already answers. If a strong reader would ask nothing hard, answer an empty list.`,
181
+ open,
182
+ lensBlock,
183
+ `Rules. ${cap} Each question quotes the document's own words it rests on, copied exactly (a few words to one sentence). For something missing, quote the heading or sentence where it should be. A question whose quote is not in the document is thrown away. Give the smallest fix the user can make before sharing, in one line. No praise, no style or grammar notes, no question the document already answers. If a strong reader would ask nothing hard, answer an empty list.`,
119
184
  'The document:\n<<<DOCUMENT\n' + text + '\nDOCUMENT>>>',
120
185
  'Answer with JSON only: {"questions":[{"lens":"<id>","question":"<the question, as the reviewer would ask it>","quote":"<the exact words>","why":"<why it is hard, one line>","fix":"<the smallest fix>"}]}',
121
186
  ].join('\n\n');
@@ -132,6 +197,8 @@ function parse(answer, lenses, text) {
132
197
  }
133
198
  if (!isObj(o) || !Array.isArray(o.questions)) return null;
134
199
  const byId = new Map(lenses.map((l) => [l.id, l]));
200
+ const cap = capOf(readersIn(lenses));
201
+ const per = {};
135
202
  const doc = norm(text);
136
203
  const out = [], seen = new Set();
137
204
  let dropped = 0;
@@ -145,7 +212,8 @@ function parse(answer, lenses, text) {
145
212
  const k = l.id + '|' + nq;
146
213
  if (seen.has(k)) continue;
147
214
  seen.add(k);
148
- if (out.length < MAX_QUESTIONS) out.push({ lens: l.id, title: l.title, question, quote, why: one(q.why, 240), fix: one(q.fix, 240) });
215
+ const reader = l.reader || 'sceptic';
216
+ if ((per[reader] || 0) < cap) { per[reader] = (per[reader] || 0) + 1; out.push({ reader, lens: l.id, title: l.title, question, quote, why: one(q.why, 240), fix: one(q.fix, 240) }); }
149
217
  }
150
218
  return { questions: out, dropped };
151
219
  }
@@ -164,7 +232,7 @@ async function critique(ask, { root = '', lenses = null, text = '', file = '', p
164
232
  if (answer == null) return { ok: false, why: 'the critic session did not answer', ms };
165
233
  const p = parse(answer, L, T);
166
234
  if (!p) return { ok: false, why: 'the critic\'s answer could not be read', ms };
167
- return { ok: true, questions: p.questions, dropped: p.dropped, lenses: L.map((l) => l.id), ms };
235
+ return { ok: true, questions: p.questions, dropped: p.dropped, lenses: L.map((l) => l.id), readers: readersIn(L), ms };
168
236
  }
169
237
  /** The design critic's ask path with this critic's origin: a read-only `briefing-ask:` run (kind ask). */
170
238
  const askVia = (spawnSession, { timeoutMs } = {}) => DC.askVia(spawnSession, { name: 'spec critic', origin: ORIGIN, ...(timeoutMs ? { timeoutMs } : {}) });
@@ -180,8 +248,9 @@ function record(rt, run = {}) {
180
248
  const id = 'sc-' + Date.now().toString(36) + crypto.randomBytes(3).toString('hex');
181
249
  append(rt, { kind: 'run', id, at: new Date().toISOString(), from: one(run.from || 'cli', 40), ...(run.ws ? { ws: one(run.ws, 80) } : {}),
182
250
  file: one(run.file, 400), sha: one(run.sha, 16), chars: Number.isFinite(run.chars) ? run.chars : null, lenses: (run.lenses || []).slice(0, 40),
251
+ ...(Array.isArray(run.readers) && run.readers.length ? { readers: run.readers.filter((r) => READERS[r]) } : {}),
183
252
  ok: !!run.ok, ...(run.why ? { why: one(run.why, 200) } : {}),
184
- questions: (run.questions || []).slice(0, MAX_QUESTIONS).map((q) => ({ lens: q.lens, title: one(q.title, 120), question: one(q.question, 300), quote: one(q.quote, 400), why: one(q.why, 240), fix: one(q.fix, 240) })),
253
+ questions: (run.questions || []).slice(0, MAX_ALL).map((q) => ({ ...(READERS[q.reader] ? { reader: q.reader } : {}), lens: q.lens, title: one(q.title, 120), question: one(q.question, 300), quote: one(q.quote, 400), why: one(q.why, 240), fix: one(q.fix, 240) })),
185
254
  dropped: Number.isInteger(run.dropped) ? run.dropped : 0, ms: Number.isFinite(run.ms) ? run.ms : null });
186
255
  return id;
187
256
  }
@@ -218,7 +287,7 @@ function label(rt, run, n, lab, { by = 'pm:cli' } = {}) {
218
287
  /** The counts the Checker reads, and the lenses that repeat across documents (the newest run per file counts for repeats). */
219
288
  function stats(rt) {
220
289
  const R = read(rt);
221
- const s = { runs: R.length, notRun: 0, files: 0, questions: 0, real: 0, noise: 0, unlabelled: 0, dropped: 0, byLens: {}, repeats: [] };
290
+ const s = { runs: R.length, notRun: 0, files: 0, questions: 0, real: 0, noise: 0, unlabelled: 0, dropped: 0, byLens: {}, byReader: {}, repeats: [] };
222
291
  const newest = new Map();
223
292
  for (const r of R) {
224
293
  if (!r.ok) { s.notRun++; continue; }
@@ -227,8 +296,10 @@ function stats(rt) {
227
296
  r.questions.forEach((q, i) => {
228
297
  s.questions++;
229
298
  s.byLens[q.lens] = (s.byLens[q.lens] || 0) + 1;
299
+ const b = s.byReader[q.reader || 'sceptic'] = s.byReader[q.reader || 'sceptic'] || { questions: 0, real: 0, noise: 0, unlabelled: 0 };
300
+ b.questions++;
230
301
  const l = r.labels[i + 1];
231
- if (l === 'real') s.real++; else if (l === 'noise') s.noise++; else s.unlabelled++;
302
+ if (l === 'real') { s.real++; b.real++; } else if (l === 'noise') { s.noise++; b.noise++; } else { s.unlabelled++; b.unlabelled++; }
232
303
  });
233
304
  }
234
305
  s.files = newest.size;
@@ -238,4 +309,4 @@ function stats(rt) {
238
309
  return s;
239
310
  }
240
311
 
241
- module.exports = { FILE, BASE, ORIGIN, MAX_QUESTIONS, MAX_CHARS, DOC_RE, off, questionsOf, lensesFor, textOf, norm, sha, promptOf, parse, critique, askVia, file, record, read, latest, label, stats };
312
+ module.exports = { FILE, BASE, READERS, READER_IDS, ORIGIN, MAX_QUESTIONS, PER_READER, MAX_ALL, readersOf, readerList, MAX_CHARS, DOC_RE, off, questionsOf, lensesFor, textOf, norm, sha, promptOf, parse, critique, askVia, file, record, read, latest, label, stats };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.679.0",
3
+ "version": "0.681.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.679.0",
9
+ "version": "0.681.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.679.0",
3
+ "version": "0.681.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",
@@ -1,5 +1,5 @@
1
1
  {
2
- "_comment": "design-drift-guard: the design drift guard. Which pages are built from the product's design system and which drift from it, read from git only: the measure and compare (lib/design-drift.js), pmos design drift (lib/design-cli.js), on a scratch git repository. No server, no network, no model.",
2
+ "_comment": "design-drift-guard and design-token-ratchet: every place the product's styles and scripts do not read a design token, the ratchet that lets a change lower that count but never raise it, and the older page-share measure (--pages). Read from git only (lib/design-drift.js, lib/design-cli.js), on scratch git repositories. No server, no network, no model.",
3
3
  "modules": ["design-drift.test.js"],
4
- "seconds": { "design-drift.test.js": 3 }
4
+ "seconds": { "design-drift.test.js": 4 }
5
5
  }
@@ -1,7 +1,11 @@
1
1
  {
2
- "_comment": "Sceptical spec critic (initiative spec-critic, bet A330 of the factory line): before a PM shares a document, at most 3 hard questions a sceptical reviewer would ask, each naming its lens and quoting the document (a question whose quote is not in the document is dropped); the product's own review-questions.json; ledger with the PM's real/noise labels and the gaps that repeat across documents (lib/spec-critic.js, lib/routes-spec-critic.js /api/spec-critic, lib/critic-cli.js `pmos critic`). Backend only.",
2
+ "_comment": "Sceptical spec critic (initiative spec-critic, bet A330 of the factory line): before a PM shares a document, at most 3 hard questions a sceptical reviewer would ask, each naming its lens and quoting the document (a question whose quote is not in the document is dropped); the product's own review-questions.json; ledger with the PM's real/noise labels and the gaps that repeat across documents (lib/spec-critic.js, lib/routes-spec-critic.js /api/spec-critic, lib/critic-cli.js `pmos critic`). Backend only. Reader roles (initiative review-lenses-cfo-engineer-sceptic, bet A110): --as cfo,engineer,sceptic, lenses per reader, per-reader caps and stats.",
3
3
  "modules": [
4
- "spec-critic.test.js"
4
+ "spec-critic.test.js",
5
+ "spec-critic-readers.test.js"
5
6
  ],
6
- "seconds": { "spec-critic.test.js": 1 }
7
+ "seconds": {
8
+ "spec-critic.test.js": 1,
9
+ "spec-critic-readers.test.js": 1
10
+ }
7
11
  }