create-pmos 0.659.0 → 0.660.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.659.0",
3
+ "version": "0.660.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": {
@@ -34,8 +34,8 @@
34
34
  ],
35
35
  "pmosChanges": [
36
36
  {
37
- "v": "0.659.0",
38
- "at": "2026-11-22T03:48:36.791Z",
37
+ "v": "0.660.0",
38
+ "at": "2026-11-22T03:56:11.761Z",
39
39
  "f": 4,
40
40
  "prs": [
41
41
  {
@@ -43,6 +43,31 @@
43
43
  "t": "Library is built from the design system's blocks",
44
44
  "s": "Library is built from the design system's blocks",
45
45
  "k": "new"
46
+ },
47
+ {
48
+ "n": 1445,
49
+ "t": "Pmos design drift, the design drift guard",
50
+ "s": "Pmos design drift, the design drift guard",
51
+ "k": "new"
52
+ }
53
+ ]
54
+ },
55
+ {
56
+ "v": "0.658.0",
57
+ "at": "2026-11-22T03:38:17.292Z",
58
+ "f": 4,
59
+ "prs": [
60
+ {
61
+ "n": 1441,
62
+ "t": "Goals is built from the design system's blocks",
63
+ "s": "Goals is built from the design system's blocks",
64
+ "k": "new"
65
+ },
66
+ {
67
+ "n": 1443,
68
+ "t": "Events is built from the design system's blocks",
69
+ "s": "Events is built from the design system's blocks",
70
+ "k": "new"
46
71
  }
47
72
  ]
48
73
  },
@@ -303,19 +328,6 @@
303
328
  "k": "new"
304
329
  }
305
330
  ]
306
- },
307
- {
308
- "v": "0.632.0",
309
- "at": "2026-11-19T11:23:46.354Z",
310
- "f": 4,
311
- "prs": [
312
- {
313
- "n": 1414,
314
- "t": "Set up the Meet panel from Settings › Connectors › Google Meet",
315
- "s": "Set up the Meet panel from Settings › Connectors › Google Meet",
316
- "k": "new"
317
- }
318
- ]
319
331
  }
320
332
  ]
321
333
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@d9579e83
1
+ kernel-source: pmos@58c68d24
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-22T03:48:33Z"}
5
+ generated: {by: process:create-pmos, at: "2026-11-22T03:56:08Z"}
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-22T03:48:33Z"}
5
+ generated: {by: process:create-pmos, at: "2026-11-22T03:56:08Z"}
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-22T03:48:33Z"}
5
+ generated: {by: process:create-pmos, at: "2026-11-22T03:56:08Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -1,7 +1,7 @@
1
1
  [
2
2
  {
3
- "v": "0.659.0",
4
- "at": "2026-11-22T03:48:36.791Z",
3
+ "v": "0.660.0",
4
+ "at": "2026-11-22T03:56:11.761Z",
5
5
  "f": 4,
6
6
  "prs": [
7
7
  {
@@ -9,6 +9,31 @@
9
9
  "t": "Library is built from the design system's blocks",
10
10
  "s": "Library is built from the design system's blocks",
11
11
  "k": "new"
12
+ },
13
+ {
14
+ "n": 1445,
15
+ "t": "Pmos design drift, the design drift guard",
16
+ "s": "Pmos design drift, the design drift guard",
17
+ "k": "new"
18
+ }
19
+ ]
20
+ },
21
+ {
22
+ "v": "0.658.0",
23
+ "at": "2026-11-22T03:38:17.292Z",
24
+ "f": 4,
25
+ "prs": [
26
+ {
27
+ "n": 1441,
28
+ "t": "Goals is built from the design system's blocks",
29
+ "s": "Goals is built from the design system's blocks",
30
+ "k": "new"
31
+ },
32
+ {
33
+ "n": 1443,
34
+ "t": "Events is built from the design system's blocks",
35
+ "s": "Events is built from the design system's blocks",
36
+ "k": "new"
12
37
  }
13
38
  ]
14
39
  },
@@ -304,6 +304,13 @@ Only PMOS's impact run uses these. The server pins each run to your ledger. Outs
304
304
  - `pmos drift replay`: the replay of the last four weeks of this repository.
305
305
  - `pmos drift status`: the last weekly result and the replays on record.
306
306
 
307
+ ### pmos design drift: pages that drift from the design system
308
+
309
+ - `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.
310
+ - `--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.
311
+ - `--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.
312
+ - 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"] }`.
313
+
307
314
  ## Initiatives and the Board
308
315
 
309
316
  ### pmos initiative
@@ -0,0 +1,115 @@
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).
4
+ *
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)
12
+ *
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. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const D = require('./design-drift.js');
18
+
19
+ const COMMANDS = { design: ['drift'] };
20
+ 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.',
29
+ ];
30
+ const FLAGS = new Set(['ref', 'base', 'weeks', 'json', 'write', 'gate', 'repo']);
31
+ const BOOL = new Set(['json', 'write', 'gate']);
32
+
33
+ function parse(args) {
34
+ const pos = [], flags = {};
35
+ for (let i = 0; i < args.length; i++) {
36
+ const a = args[i];
37
+ if (!a.startsWith('--')) { pos.push(a); continue; }
38
+ const k = a.slice(2);
39
+ if (BOOL.has(k)) flags[k] = true;
40
+ else flags[k] = args[i + 1] !== undefined && !String(args[i + 1]).startsWith('--') ? args[++i] : '';
41
+ }
42
+ return { pos, flags };
43
+ }
44
+ function repoRoot(cwd) {
45
+ const out = D.gitOut(cwd, ['rev-parse', '--show-toplevel']);
46
+ return out ? out.trim() : null;
47
+ }
48
+ const pct = (x) => Math.round(100 * x) + '%';
49
+ const short = (p) => p.replace(/^.*\//, '').replace(/\.html?$/i, '');
50
+
51
+ async function run(argv, { say = (s) => console.log(s), cwd = process.cwd(), now = Date.now() } = {}) {
52
+ const args = argv[0] === 'design' ? argv.slice(1) : argv.slice();
53
+ const sub = args[0];
54
+ if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 2; }
55
+ if (!COMMANDS.design.includes(sub)) { say(`unknown design command "${sub}". Use one of: ${COMMANDS.design.join(', ')}`); return 2; }
56
+ const { pos, flags } = parse(args.slice(1));
57
+ if (pos.length) { say(`✗ pmos design ${sub} takes no argument`); return 2; }
58
+ for (const k of Object.keys(flags)) if (!FLAGS.has(k)) { say(`✗ --${k} is not an option of pmos design drift`); return 2; }
59
+ for (const k of ['ref', 'base', 'weeks', 'repo']) if (k in flags && !flags[k]) { say(`✗ --${k} needs a value`); return 2; }
60
+ const weeks = flags.weeks === undefined ? 0 : Number(flags.weeks);
61
+ 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; }
63
+
64
+ const repo = repoRoot(flags.repo ? path.resolve(cwd, flags.repo) : cwd);
65
+ if (!repo) { say('✗ this is not a git repository. Run pmos design drift in your product\'s repository.'); return 1; }
66
+ const ref = flags.ref || 'HEAD';
67
+ const worktree = ref === 'WORKTREE';
68
+ if (!worktree && !D.gitOut(repo, ['rev-parse', '--verify', '--quiet', ref + '^{commit}'])) { say(`✗ no commit "${ref}" in this repository`); return 1; }
69
+ let base = flags.base || null;
70
+ if (base === 'week') {
71
+ const when = worktree ? new Date(now) : new Date(D.gitOut(repo, ['show', '-s', '--format=%cI', ref]).trim());
72
+ const sha = (D.gitOut(repo, ['rev-list', '-1', `--before=${new Date(when.getTime() - 7 * 86400000).toISOString()}`, worktree ? 'HEAD' : ref]) || '').trim();
73
+ if (!sha) { say('✗ no commit a week before ' + ref); return 1; }
74
+ base = sha.slice(0, 8);
75
+ }
76
+ if (base && !D.gitOut(repo, ['rev-parse', '--verify', '--quiet', base + '^{commit}'])) { say(`✗ no commit "${base}" in this repository`); return 1; }
77
+
78
+ const head = D.measure(repo, ref);
79
+ if (head.config.error) { say('✗ ' + head.config.error); return 1; }
80
+ const before = base ? D.measure(repo, base) : null;
81
+ const rows = before ? D.compare(before, head) : head.pages;
82
+ const trend = weeks ? D.trend(repo, worktree ? 'HEAD' : ref, weeks, { now: worktree ? now : Date.parse(D.gitOut(repo, ['show', '-s', '--format=%cI', ref]).trim()) }) : null;
83
+ const date = new Date(now).toISOString().slice(0, 10);
84
+ const view = { date, ref, commit: head.commit, base, baseCommit: before && before.commit, rows, compared: !!before, trend, config: head.config, shared: head.shared };
85
+ const drifting = rows.filter((r) => r.status === 'drift');
86
+
87
+ if (flags.json) {
88
+ say(JSON.stringify({ ok: true, ref, commit: head.commit, base, baseCommit: view.baseCommit, config: head.config.from, summary: D.summary(rows, { compared: !!before }),
89
+ pages: rows, shared: { ...head.shared, files: head.shared.files.length }, queue: D.queue(rows).map((r) => r.page), trend }));
90
+ } else {
91
+ say(D.summary(rows, { compared: !!before }) + ` (${head.commit}${before ? ' against ' + before.commit : ''}; config: ${head.config.from})`);
92
+ if (rows.length) {
93
+ say('page share own rules restyled colours ' + (before ? 'status' : ''));
94
+ for (const r of [...rows].sort((a, b) => (a.share || 0) - (b.share || 0))) {
95
+ const b = r.before;
96
+ const two = (x, y, f = String) => (b ? `${f(x)} → ${f(y)}` : f(y));
97
+ if (r.status === 'gone') { say(`${short(r.page).padEnd(26)}(gone)`); continue; }
98
+ say(`${short(r.page).padEnd(26)}${two(b && b.share, r.share, pct).padEnd(14)}${two(b && b.ownRules, r.ownRules).padEnd(15)}${String(r.restyled).padEnd(10)}${String(r.colours).padEnd(9)}${before ? r.status + (r.why && r.why.length ? ' (' + r.why.join('; ') + ')' : '') : ''}`);
99
+ }
100
+ say(`shared code: ${head.shared.files.length} files · ${pct(head.shared.share)} from the system · ${head.shared.ownRules} own CSS rules`);
101
+ 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(', '));
103
+ }
104
+ if (trend) say('Mean share by week: ' + trend.map((t) => `${t.week} ${t.share == null ? '–' : pct(t.share)}`).join(' · '));
105
+ }
106
+ if (flags.write) {
107
+ const file = path.join(repo, 'planning', 'reports', `design-drift-${date}.md`);
108
+ fs.mkdirSync(path.dirname(file), { recursive: true });
109
+ fs.writeFileSync(file, D.reportMd(view));
110
+ if (!flags.json) say('Report: ' + path.relative(repo, file));
111
+ }
112
+ return flags.gate && drifting.length ? 1 : 0;
113
+ }
114
+
115
+ module.exports = { run, COMMANDS, USAGE };
@@ -0,0 +1,406 @@
1
+ 'use strict';
2
+ /* design-drift.js — the design drift guard (initiative design-drift-guard, bet 5 / A2): which pages are built from the product's design system,
3
+ * and which only changed colour. It reads git only: no checkout, no build, no browser, no model. lib/design-cli.js is `pmos design drift`.
4
+ *
5
+ * WHAT IS MEASURED, per page (an HTML file):
6
+ * own sheets the stylesheets the page links that are neither the system's nor the old shared shell's
7
+ * own rules style rules in those sheets (a rule inside @media counts; @media, @keyframes and @font-face themselves do not)
8
+ * restyled own rules whose selector names a system class: a system part drawn again by the page
9
+ * colours raw colour literals (#hex, rgb(), hsl()) in own sheets, outside a var(--token, fallback)
10
+ * system share of the class names in the page's markup and in the scripts it loads (followed through their imports), the share that the
11
+ * system sheets define. A class the system sheets do not define does not count, whatever its prefix.
12
+ * The system's parts come from the system sheets themselves, so this works for any product's design system: a part is the first class after
13
+ * the scope in a system selector (pm-row in `.pm-ds .pm-row .on`). A class that leads at least half of a sheet's selectors is its scope
14
+ * (pm-ds): it is left out, so putting the scope on <body> does not raise the share.
15
+ * shared a sheet or script that half of the pages or more load (the nav, the popup) is measured once, as `shared`, and left
16
+ * out of each page, so every page's number is about that page. Two pages built from one script read the same.
17
+ *
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
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
23
+ * unchanged the same numbers
24
+ * new · gone the page exists on one side only
25
+ *
26
+ * WHICH PAGES, WHICH SHEETS. PMOS-self's defaults are DEFAULTS. A product sets its own in design-drift.json in its design-system folder
27
+ * (pmos/design-system/, design-system/ or workspace/design-system/), read at the commit measured:
28
+ * { "pages": ["web/*.html"], "assetBase": "web", "systemSheets": ["ds.css"], "shellSheets": ["legacy.css"] }
29
+ * pages are globs from the repository root (* inside one folder, ** across folders). Sheet names match the end of the path.
30
+ *
31
+ * configAt(read, ref) → config · measure(repo, ref, opts) → { ref, commit, config, pages: [row] } · compare(base, head) → [row + status]
32
+ * trend(repo, ref, weeks, opts) → [{ week, commit, share, pages }] · queue(pages, n) · summary(rows) · reportMd(view) PURE
33
+ * rulesOf(css) PURE · classesOf(src) PURE · importsOf(js) PURE · colourCount(css) PURE · globRe(glob) PURE
34
+ * ref null or 'WORKTREE' reads the files on disk (git ls-files for the list). Every other ref reads `git show <ref>:<path>`. Nothing is written.
35
+ */
36
+ const fs = require('fs');
37
+ const path = require('path');
38
+ const { execFileSync } = require('child_process');
39
+
40
+ const DEFAULTS = Object.freeze({
41
+ pages: ['workspace/public/*.html'],
42
+ assetBase: 'workspace/public',
43
+ systemSheets: ['brand.css', 'charts.css', 'komorebi.css', 'documents.css', 'slides.css'],
44
+ // the old shared shell and the bridge from its tokens: loaded by many pages, owned by none
45
+ shellSheets: ['cozy.css', 'components.css', 'ds-bridge.css'],
46
+ });
47
+ const CONFIG_PLACES = ['pmos/design-system/design-drift.json', 'design-system/design-drift.json', 'workspace/design-system/design-drift.json'];
48
+ const REBUILT_SHARE = 0.10;
49
+ const REBUILT_SHRINK = 0.8;
50
+ const SHARE_SLACK = 0.005;
51
+
52
+ // ── pure parts ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
53
+
54
+ /** Style rules of a sheet: [{ selector }]. Container at-rules (@media, @supports, @layer, @container) are walked into; @keyframes,
55
+ * @font-face and other at-rule blocks are skipped whole. */
56
+ function rulesOf(css) {
57
+ const src = String(css || '').replace(/\/\*[\s\S]*?\*\//g, '');
58
+ const out = [];
59
+ const stack = []; // 'container' | 'rule' | 'skip'
60
+ let buf = '';
61
+ let quote = null;
62
+ for (let i = 0; i < src.length; i++) {
63
+ const ch = src[i];
64
+ if (quote) { if (ch === quote && src[i - 1] !== '\\') quote = null; buf += ch; continue; }
65
+ if (ch === '"' || ch === "'") { quote = ch; buf += ch; continue; }
66
+ if (ch === '{') {
67
+ const pre = buf.trim(); buf = '';
68
+ const inSkip = stack.includes('skip') || stack[stack.length - 1] === 'rule';
69
+ if (inSkip) stack.push('skip');
70
+ else if (pre.startsWith('@')) stack.push(/^@(media|supports|layer|container|document)\b/i.test(pre) ? 'container' : 'skip');
71
+ else { stack.push('rule'); out.push({ selector: pre }); }
72
+ continue;
73
+ }
74
+ if (ch === '}') { stack.pop(); buf = ''; continue; }
75
+ if (ch === ';' && !stack.length) { buf = ''; continue; } // @import, @charset
76
+ buf += ch;
77
+ }
78
+ return out;
79
+ }
80
+
81
+ const CLASS_NAME = /^-?[_a-zA-Z][_a-zA-Z0-9-]*$/;
82
+ /** Class names a selector names. */
83
+ function selectorClasses(sel) {
84
+ const out = [];
85
+ for (const m of String(sel).replace(/\[[^\]]*\]/g, '').replace(/"[^"]*"|'[^']*'/g, '').matchAll(/\.(-?[_a-zA-Z][_a-zA-Z0-9-]*)/g)) out.push(m[1]);
86
+ return out;
87
+ }
88
+
89
+ /** Selector list split at top-level commas (not the commas inside :is(), :not() and friends). */
90
+ function splitSelectors(sel) {
91
+ const out = []; let depth = 0; let cur = '';
92
+ for (const ch of String(sel)) {
93
+ if (ch === '(') depth++;
94
+ if (ch === ')') depth--;
95
+ if (ch === ',' && depth === 0) { out.push(cur); cur = ''; } else cur += ch;
96
+ }
97
+ out.push(cur);
98
+ return out.map((s) => s.trim()).filter(Boolean);
99
+ }
100
+
101
+ /** A selector's compounds, split at combinators outside parentheses: '.a.b > .c :is(.d .e)' → ['.a.b', '.c', ':is(.d .e)']. */
102
+ function compoundsOf(sel) {
103
+ const out = []; let depth = 0; let cur = '';
104
+ for (const ch of String(sel)) {
105
+ if (ch === '(' || ch === '[') depth++;
106
+ if (ch === ')' || ch === ']') depth--;
107
+ if (depth === 0 && /[\s>+~]/.test(ch)) { if (cur) out.push(cur); cur = ''; } else cur += ch;
108
+ }
109
+ if (cur) out.push(cur);
110
+ return out;
111
+ }
112
+
113
+ /** The system's parts from its sheets' text: { classes: Set, scopes: Set }. A class that leads at least half of a sheet's selectors is a
114
+ * scope (pm-ds). A PART is the first class after the scopes in a selector: `.pm-ds .pm-row .on` makes pm-row a part, and `on` only a
115
+ * state inside it, so a page's own `on` neither counts as the system nor as a restyled part. */
116
+ function systemOf(sheets) {
117
+ const classes = new Set(); const scopes = new Set();
118
+ const all = sheets.map(rulesOf);
119
+ for (const rules of all) {
120
+ const count = new Map();
121
+ for (const r of rules) { const lead = new Set(splitSelectors(r.selector).map((one) => selectorClasses(one)[0]).filter(Boolean)); for (const c of lead) count.set(c, (count.get(c) || 0) + 1); }
122
+ for (const [c, n] of count) if (rules.length >= 4 && n * 2 >= rules.length) scopes.add(c);
123
+ }
124
+ for (const rules of all) for (const r of rules) for (const one of splitSelectors(r.selector)) {
125
+ // the compound that holds a scope (.pm-ds.dark, :is(.pm-ds,.pmd-ds)) is the root with its theme states, and what comes before it
126
+ // (html.dark) is outside the system: a part can only come after the root
127
+ const comps = compoundsOf(one).map(selectorClasses);
128
+ let root = -1;
129
+ comps.forEach((cls, i) => { if (cls.some((c) => scopes.has(c))) root = i; });
130
+ const first = comps.slice(root + 1).find((cls) => cls.length);
131
+ if (first) classes.add(first[0]);
132
+ }
133
+ return { classes, scopes };
134
+ }
135
+
136
+ /** Class names written in markup or script: class="…", className = '…', class: '…', classList.add/toggle/remove('…', …). */
137
+ function classesOf(src) {
138
+ const out = [];
139
+ const text = String(src || '');
140
+ for (const m of text.matchAll(/\bclass(?:Name)?\s*(?:=|:)\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`)/g)) out.push(...(m[1] ?? m[2] ?? m[3]).split(/\s+/));
141
+ for (const m of text.matchAll(/classList\.(?:add|toggle|remove)\(([^)]*)\)/g)) for (const q of m[1].matchAll(/["']([^"']+)["']/g)) out.push(q[1]);
142
+ return out.filter((c) => CLASS_NAME.test(c));
143
+ }
144
+
145
+ /** Module specifiers a script loads: static imports, re-exports and import('…') with a literal. */
146
+ function importsOf(js) {
147
+ const out = [];
148
+ const text = String(js || '');
149
+ for (const m of text.matchAll(/(?:^|[;\n])\s*(?:import|export)\s+(?:[^'"`;]*?\s+from\s+)?["']([^"']+)["']/g)) out.push(m[1]);
150
+ for (const m of text.matchAll(/\bimport\(\s*["']([^"']+)["']\s*\)/g)) out.push(m[1]);
151
+ return out;
152
+ }
153
+
154
+ /** Raw colour literals outside var(--token, fallback). */
155
+ function colourCount(css) {
156
+ let s = String(css || '').replace(/\/\*[\s\S]*?\*\//g, '');
157
+ for (let guard = 0; guard < 50 && /var\(/.test(s); guard++) s = s.replace(/var\([^()]*(?:\([^()]*\)[^()]*)*\)/g, '');
158
+ const hex = (s.match(/#[0-9a-fA-F]{3,8}\b/g) || []).length;
159
+ const fn = (s.match(/\b(?:rgba?|hsla?|oklch|oklab|lab|lch)\(/g) || []).length;
160
+ return hex + fn;
161
+ }
162
+
163
+ /** A glob from the repository root as a RegExp: ** crosses folders, * stays inside one. */
164
+ function globRe(glob) {
165
+ let re = '';
166
+ const g = String(glob).replace(/^\.?\//, '');
167
+ for (let i = 0; i < g.length; i++) {
168
+ const ch = g[i];
169
+ if (ch === '*' && g[i + 1] === '*') { re += g[i + 2] === '/' ? '(?:.*/)?' : '.*'; i += g[i + 2] === '/' ? 2 : 1; }
170
+ else if (ch === '*') re += '[^/]*';
171
+ else if (ch === '?') re += '[^/]';
172
+ else re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
173
+ }
174
+ return new RegExp('^' + re + '$');
175
+ }
176
+
177
+ const endsWithName = (list) => (p) => list.some((n) => p === n || p.endsWith('/' + n));
178
+ const pct = (x) => Math.round(100 * x);
179
+
180
+ // ── reading a commit ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
181
+
182
+ function gitOut(repo, args) {
183
+ try { return execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'ignore'] }); } catch { return null; }
184
+ }
185
+ const isWorktree = (ref) => ref == null || ref === 'WORKTREE';
186
+
187
+ /** A cached reader of one commit (or the files on disk). */
188
+ function readerOf(repo, ref) {
189
+ const cache = new Map();
190
+ const read = (p) => {
191
+ if (cache.has(p)) return cache.get(p);
192
+ let text = null;
193
+ if (isWorktree(ref)) { try { text = fs.readFileSync(path.join(repo, p), 'utf8'); } catch { text = null; } }
194
+ else text = gitOut(repo, ['show', `${ref}:${p}`]);
195
+ cache.set(p, text);
196
+ return text;
197
+ };
198
+ const list = () => {
199
+ const out = isWorktree(ref) ? gitOut(repo, ['ls-files', '--cached', '--others', '--exclude-standard']) : gitOut(repo, ['ls-tree', '-r', '--name-only', ref]);
200
+ return (out || '').split('\n').filter(Boolean);
201
+ };
202
+ return { read, list };
203
+ }
204
+
205
+ /** The config at a commit: the product's design-drift.json over the defaults. */
206
+ function configAt(read) {
207
+ for (const p of CONFIG_PLACES) {
208
+ const text = read(p);
209
+ if (text == null) continue;
210
+ let own;
211
+ try { own = JSON.parse(text); } catch { return { ...DEFAULTS, from: p, error: `${p} is not valid JSON` }; }
212
+ const cfg = { ...DEFAULTS, from: p };
213
+ for (const k of Object.keys(DEFAULTS)) if (k in own) cfg[k] = k === 'assetBase' ? String(own[k] || '') : [].concat(own[k] || []).map(String);
214
+ return cfg;
215
+ }
216
+ return { ...DEFAULTS, from: 'defaults' };
217
+ }
218
+
219
+ /** A reference in a page or a script, as a repository path; null for a URL elsewhere. */
220
+ function resolveRef(ref, fromFile, assetBase) {
221
+ const clean = String(ref).split(/[?#]/)[0];
222
+ if (!clean || /^[a-z]+:|^\/\//i.test(clean)) return null;
223
+ if (clean.startsWith('/')) return path.posix.normalize(path.posix.join(assetBase || '', clean.slice(1)));
224
+ return path.posix.normalize(path.posix.join(path.posix.dirname(fromFile), clean));
225
+ }
226
+
227
+ /** Measure every page at one commit. */
228
+ function measure(repo, ref, { files } = {}) {
229
+ const R = readerOf(repo, ref);
230
+ const read = files ? (p) => (p in files ? files[p] : null) : R.read;
231
+ const all = files ? Object.keys(files) : R.list();
232
+ const cfg = configAt(read);
233
+ const isSystem = endsWithName(cfg.systemSheets);
234
+ const isShell = endsWithName(cfg.shellSheets);
235
+ const pageRes = cfg.pages.map(globRe);
236
+ const pages = all.filter((p) => /\.html?$/i.test(p) && pageRes.some((re) => re.test(p))).sort();
237
+ // the system: every system sheet in the commit, whichever page loads it
238
+ const sysTexts = all.filter((p) => /\.css$/i.test(p) && isSystem(p)).map(read).filter((t) => t != null);
239
+ const sys = systemOf(sysTexts);
240
+ const commit = files ? null : (isWorktree(ref) ? 'WORKTREE' : (gitOut(repo, ['rev-parse', '--short', ref]) || '').trim() || null);
241
+
242
+ // what each page loads: its sheets, and its scripts followed through their imports
243
+ const loads = pages.map((page) => {
244
+ const html = read(page) || '';
245
+ const sheets = [...html.matchAll(/<link\b[^>]*\bhref\s*=\s*["']([^"']+\.css(?:[?#][^"']*)?)["'][^>]*>/gi)].map((m) => resolveRef(m[1], page, cfg.assetBase)).filter(Boolean);
246
+ const own = [...new Set(sheets.filter((s) => !isSystem(s) && !isShell(s)))];
247
+ const seen = new Set();
248
+ const todo = [...html.matchAll(/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/gi)].map((m) => resolveRef(m[1], page, cfg.assetBase)).filter(Boolean);
249
+ for (const m of html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)) for (const spec of importsOf(m[1])) { const r = resolveRef(spec, page, cfg.assetBase); if (r) todo.push(r); }
250
+ while (todo.length) {
251
+ const js = todo.shift();
252
+ if (seen.has(js)) continue;
253
+ seen.add(js);
254
+ const text = read(js);
255
+ if (text == null) continue;
256
+ for (const spec of importsOf(text)) { if (!/^[./]/.test(spec)) continue; const r = resolveRef(spec, js, cfg.assetBase); if (r && !seen.has(r)) todo.push(r); }
257
+ }
258
+ return { page, html, own, scripts: [...seen] };
259
+ });
260
+ // SHARED CODE: a sheet or script that at least half of the pages load (with 4 pages or more) is the shell (the nav, the popup, the viewer).
261
+ // It is measured once, as `shared`, so it does not blur every page's own number the same way.
262
+ const used = new Map();
263
+ for (const l of loads) for (const f of [...l.own, ...l.scripts]) used.set(f, (used.get(f) || 0) + 1);
264
+ const isShared = (f) => pages.length >= 4 && used.get(f) * 2 >= pages.length;
265
+
266
+ const measureOf = (sheets, scripts, html) => {
267
+ let ownRules = 0; let restyled = 0; let colours = 0; const restyledParts = new Map();
268
+ for (const s of sheets) {
269
+ const css = read(s);
270
+ if (css == null) continue;
271
+ const rules = rulesOf(css);
272
+ ownRules += rules.length;
273
+ colours += colourCount(css);
274
+ for (const r of rules) {
275
+ const hit = selectorClasses(r.selector).filter((c) => sys.classes.has(c));
276
+ if (hit.length) { restyled++; for (const c of new Set(hit)) restyledParts.set(c, (restyledParts.get(c) || 0) + 1); }
277
+ }
278
+ }
279
+ let names = html ? classesOf(html.replace(/<style[\s\S]*?<\/style>/gi, '')) : [];
280
+ for (const js of scripts) { const text = read(js); if (text != null) names = names.concat(classesOf(text)); }
281
+ const counted = names.filter((c) => !sys.scopes.has(c));
282
+ const system = counted.filter((c) => sys.classes.has(c)).length;
283
+ return {
284
+ ownSheets: sheets.length, ownRules, restyled, colours, scripts: scripts.length,
285
+ classes: counted.length, system, share: counted.length ? system / counted.length : 0,
286
+ parts: [...restyledParts.entries()].sort((x, y) => y[1] - x[1]).slice(0, 5).map(([c, n]) => ({ part: c, rules: n })),
287
+ };
288
+ };
289
+ const rows = loads.map((l) => ({ page: l.page, ...measureOf(l.own.filter((f) => !isShared(f)), l.scripts.filter((f) => !isShared(f)), l.html) }));
290
+ const sharedFiles = [...used.keys()].filter(isShared).sort();
291
+ const shared = { ...measureOf(sharedFiles.filter((f) => /\.css$/i.test(f)), sharedFiles.filter((f) => !/\.css$/i.test(f)), ''), files: sharedFiles };
292
+ return { ref: isWorktree(ref) ? 'WORKTREE' : ref, commit, config: cfg, systemClasses: sys.classes.size, pages: rows, shared };
293
+ }
294
+
295
+ /** Compare two measures, page by page. */
296
+ function compare(base, head) {
297
+ const before = new Map((base ? base.pages : []).map((r) => [r.page, r]));
298
+ const out = [];
299
+ for (const h of head.pages) {
300
+ const b = before.get(h.page);
301
+ let status;
302
+ if (!b) status = 'new';
303
+ 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';
305
+ 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';
307
+ const why = [];
308
+ if (b && status === 'drift') {
309
+ if (h.ownRules > b.ownRules) why.push(`own CSS +${h.ownRules - b.ownRules} rules`);
310
+ if (h.share < b.share - SHARE_SLACK) why.push(`share ${pct(b.share)}% → ${pct(h.share)}%`);
311
+ }
312
+ out.push({ ...h, before: b ? { ownRules: b.ownRules, share: b.share, restyled: b.restyled, colours: b.colours } : null, status, why });
313
+ }
314
+ for (const [page, b] of before) if (!head.pages.some((h) => h.page === page)) out.push({ page, before: { ownRules: b.ownRules, share: b.share, restyled: b.restyled, colours: b.colours }, status: 'gone', why: [] });
315
+ return out;
316
+ }
317
+
318
+ /** The pages to rebuild next: lowest system share first, then the most own CSS. Pages with almost no markup are left out. */
319
+ function queue(pages, n = 5) {
320
+ 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
+ }
322
+
323
+ /** Mean system share over the pages that have markup. */
324
+ function meanShare(pages) {
325
+ const live = pages.filter((r) => r.classes > 0);
326
+ return live.length ? live.reduce((n, r) => n + r.share, 0) / live.length : 0;
327
+ }
328
+
329
+ /** The commit at the end of each of the last n weeks (oldest first), and its mean share. `now` is the end of the newest week. */
330
+ function trend(repo, ref, weeks, { now = Date.now() } = {}) {
331
+ const out = [];
332
+ for (let i = weeks - 1; i >= 0; i--) {
333
+ const end = new Date(now - i * 7 * 86400000);
334
+ const sha = (gitOut(repo, ['rev-list', '-1', `--before=${end.toISOString()}`, ref]) || '').trim();
335
+ if (!sha) { out.push({ week: end.toISOString().slice(0, 10), commit: null, share: null, pages: 0 }); continue; }
336
+ const m = measure(repo, sha);
337
+ out.push({ week: end.toISOString().slice(0, 10), commit: sha.slice(0, 8), share: meanShare(m.pages), pages: m.pages.length });
338
+ }
339
+ return out;
340
+ }
341
+
342
+ /** One-line summary of a compare (or of a single measure). */
343
+ function summary(rows, { compared = true } = {}) {
344
+ if (!rows.length) return 'No pages found. Set "pages" in design-drift.json in your design-system folder.';
345
+ if (!compared) return `${rows.length} pages · mean system share ${pct(meanShare(rows))}%.`;
346
+ 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`];
348
+ if (n('new')) parts.push(`${n('new')} new`);
349
+ if (n('gone')) parts.push(`${n('gone')} gone`);
350
+ return `${rows.length} pages: ${parts.join(', ')}.`;
351
+ }
352
+
353
+ const name = (page) => page.replace(/^.*\//, '').replace(/\.html?$/i, '');
354
+
355
+ /** The report as markdown (a tracked Reference: type, title, timestamp; Report is not in the frontmatter registry). view = { date, ref, commit, base, baseCommit, rows, compared, trend, config }. */
356
+ function reportMd(view) {
357
+ const { date, rows, compared } = view;
358
+ const L = [];
359
+ L.push('---', 'type: Reference', `title: "Design drift report ${date}"`, `timestamp: ${date}`, '---', '');
360
+ L.push(`# Design drift report, ${date}`, '');
361
+ L.push(`**${summary(rows, { compared })}**`, '');
362
+ L.push(`Made by \`pmos design drift${view.base ? ` --base ${view.base}` : ''} --ref ${view.ref}${view.trend ? ` --weeks ${view.trend.length}` : ''} --write\` (initiative design-drift-guard). ` +
363
+ `Commit measured: \`${view.commit}\`${view.base ? `, compared with \`${view.baseCommit}\`` : ''}. Config: ${view.config.from}. ` +
364
+ 'It reads git only. The system share is the share of a page\'s class names (markup and the scripts it loads) that the system sheets define.', '');
365
+ L.push('## Pages', '');
366
+ if (compared) {
367
+ L.push('| Page | Status | System share | Own CSS rules | System parts restyled | Raw colours | Why |', '|---|---|---|---|---|---|---|');
368
+ for (const r of [...rows].sort((a, b) => order(a.status) - order(b.status) || a.share - b.share)) {
369
+ const b = r.before;
370
+ const arrow = (x, y, f = String) => (b && x !== y ? `${f(x)} → ${f(y)}` : f(y));
371
+ L.push(`| ${name(r.page)} | ${r.status} | ${r.status === 'gone' ? '' : arrow(b && b.share, r.share, (v) => pct(v) + '%')} | ${r.status === 'gone' ? '' : arrow(b && b.ownRules, r.ownRules)} | ${r.status === 'gone' ? '' : arrow(b && b.restyled, r.restyled)} | ${r.status === 'gone' ? '' : arrow(b && b.colours, r.colours)} | ${(r.why || []).join('; ')} |`);
372
+ }
373
+ } else {
374
+ L.push('| Page | System share | Own CSS rules | System parts restyled | Raw colours |', '|---|---|---|---|---|');
375
+ for (const r of [...rows].sort((a, b) => a.share - b.share)) L.push(`| ${name(r.page)} | ${pct(r.share)}% | ${r.ownRules} | ${r.restyled} | ${r.colours} |`);
376
+ }
377
+ L.push('');
378
+ 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.', '');
381
+ 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
+ L.push('');
383
+ if (view.shared && view.shared.files && view.shared.files.length) {
384
+ const sh = view.shared;
385
+ L.push('## Shared code', '', `${sh.files.length} files that half of the pages or more load (the shell: nav, popups, viewer) are measured once here and left out of each page: ` +
386
+ `${pct(sh.share)}% from the system, ${sh.ownRules} own CSS rules, ${sh.restyled} restyle a system part.`, '');
387
+ }
388
+ if (view.trend && view.trend.length) {
389
+ L.push('## Trend', '', 'Mean system share over the pages, at the last commit of each week:', '', '| Week ending | Commit | Mean share |', '|---|---|---|');
390
+ for (const t of view.trend) L.push(`| ${t.week} | ${t.commit ? '`' + t.commit + '`' : 'none'} | ${t.share == null ? '' : pct(t.share) + '%'} |`);
391
+ L.push('');
392
+ }
393
+ L.push('## How to read it', '',
394
+ '- **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.', '');
398
+ return L.join('\n');
399
+ }
400
+ function order(s) { return ['drift', 'not rebuilt', 'new', 'rebuilt', 'unchanged', 'gone'].indexOf(s); }
401
+
402
+ module.exports = {
403
+ DEFAULTS, CONFIG_PLACES, REBUILT_SHARE, REBUILT_SHRINK,
404
+ rulesOf, selectorClasses, splitSelectors, compoundsOf, systemOf, classesOf, importsOf, colourCount, globRe, resolveRef,
405
+ configAt, readerOf, measure, compare, queue, meanShare, trend, summary, reportMd, gitOut,
406
+ };
@@ -118,6 +118,9 @@ const VERBS = Object.freeze({
118
118
  // Not a pm-os-absorb verb (run: null): initiative weekly-drift-check added it through the same table.
119
119
  drift: Object.freeze({ module: 'drift-cli.js', run: null, guide: 'cli.md',
120
120
  help: 'pmos drift show|replay|status — the weekly check for quiet drift: what it would show, its replay on your real records, and its last result (pmos drift help)' }),
121
+ // Not a pm-os-absorb verb (run: null): initiative design-drift-guard added it through the same table.
122
+ design: Object.freeze({ module: 'design-cli.js', run: null, guide: 'cli.md',
123
+ help: 'pmos design drift — which pages are built from your design system and which drift from it, read from git (pmos design help)' }),
121
124
  // Not a pm-os-absorb verb (run: null): initiative outcome-for-every-initiative added it through the same table.
122
125
  outcomes: Object.freeze({ module: 'outcomes-cli.js', run: null, guide: 'cli.md',
123
126
  help: 'pmos outcomes list|propose|declare|record — every initiative\'s expected outcome and check date: Claude\'s cited drafts, the PM\'s yes, and the verdict when a check is due (pmos outcomes help)' }),
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.659.0",
3
+ "version": "0.660.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.659.0",
9
+ "version": "0.660.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.659.0",
3
+ "version": "0.660.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",
@@ -0,0 +1,5 @@
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.",
3
+ "modules": ["design-drift.test.js"],
4
+ "seconds": { "design-drift.test.js": 3 }
5
+ }