create-pmos 0.659.0 → 0.661.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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)' }),
@@ -84,7 +84,7 @@ const ROWS = [
84
84
  await page.route('**/api/metric-drafts?*', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify(DRAFTS(rows)) }));
85
85
  for (const k of ['keep', 'keep-all', 'drop', 'edit', 'undo', 'start']) await page.route('**/api/metric-drafts/' + k, (r) => { posts.push({ path: '/api/metric-drafts/' + k, body: JSON.parse(r.request().postData() || '{}') }); r.fulfill({ contentType: 'application/json', body: JSON.stringify(k === 'keep' ? { ok: true, rid: 'r1' } : { ok: true, kept: 3 }) }); });
86
86
  await page.route('**/api/goals/notify', (r) => { posts.push({ path: '/api/goals/notify', body: JSON.parse(r.request().postData() || '{}') }); r.fulfill({ contentType: 'application/json', body: '{"ok":true}' }); });
87
- await page.goto(BASE + '/premium-intelligence.html?theme=' + theme);
87
+ await page.goto(BASE + '/premium-intelligence.html?theme=' + theme + '&tab=goals'); // key results live on Goals: ?tab=goals shows them here (intelligence-ds-page)
88
88
  await until(() => page.evaluate(() => document.querySelectorAll('#goalTbl .ins-row').length > 0), 20000);
89
89
  await until(() => page.evaluate(() => !!document.querySelector('#goalTbl .okr-dr')), 6000);
90
90
  return { ctx, page, errors, posts };
@@ -104,7 +104,7 @@ const ROWS = [
104
104
  const wt = await p.evaluate(() => { const W = document.querySelector('#waitList'); return { shown: !!W && !W.hidden, churn: !!(W && W.querySelector('[data-goal="krm-churn"]')), head: ((W && W.querySelector('h2')) || {}).textContent || '' }; });
105
105
  ok('L4 a goal with no reading is not a table row; it waits in Waiting on a source', !churn.id && wt.shown && wt.churn && wt.head === 'Waiting on a source', JSON.stringify([churn, wt]));
106
106
  const ns = await txt(p, '#nsRow .ins-nsc');
107
- ok('L6 the North Star is its own card with its number, its change and its line', /North Star Partner uptime/.test(ns) && /99\.6%/.test(ns) && !!(await p.$('#nsRow .ins-nsch')), ns);
107
+ ok('L6 the North Star is its own card with its number, its change and its line', /North Star · Partner uptime/.test(ns) && /99\.6%/.test(ns) && !!(await p.$('#nsRow .ins-nsch')), ns);
108
108
  await shot(p, 'okr-desktop-light');
109
109
 
110
110
  /* D · drafts */
@@ -149,7 +149,7 @@ const ROWS = [
149
149
 
150
150
  /* M · ⋯ (re-pointed, U3): Reports and dashboards and Export CSV only; the table is the metric list, so ⋯ › Metrics is gone */
151
151
  await p.click('#moreB'); await sleep(80);
152
- ok('M1 ⋯ holds Reports and dashboards and Export only', (await p.evaluate(() => [...document.querySelectorAll('#moreMenu [data-more]')].map((b) => b.dataset.more).join())) === 'library,export');
152
+ ok('M1 ⋯ holds Reports and dashboards, Key results here and Export only', (await p.evaluate(() => [...document.querySelectorAll('#moreMenu [data-more]')].map((b) => b.dataset.more).join())) === 'library,krs,export');
153
153
  await p.keyboard.press('Escape');
154
154
  ok('M4 no script error on the page', !R.errors.length, R.errors.join(' | '));
155
155
  await R.ctx.close();
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.659.0",
3
+ "version": "0.661.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.661.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.661.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",
@@ -428,7 +428,7 @@ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
428
428
  ok('0 no page error with the chat at 1920', Dw.errors.length === 0, Dw.errors.join(' | '));
429
429
  await Dw.close();
430
430
  // Intelligence: a goal row opens a split; ⌘-click opens beside
431
- const In = await open({ at: '/premium-intelligence.html', ready: () => !!window.czPanels && document.querySelectorAll('#goalTbl .ins-row[data-goal]').length > 1 });
431
+ const In = await open({ at: '/premium-intelligence.html?tab=goals', ready: () => !!window.czPanels && document.querySelectorAll('#goalTbl .ins-row[data-goal]').length > 1 });
432
432
  ok('P9 Intelligence draws its goal rows and window.czPanels', !!In.up);
433
433
  const G = await In.page.evaluate(() => [...document.querySelectorAll('#goalTbl .ins-row[data-goal]')].map((r) => r.dataset.goal));
434
434
  await In.page.click(`#goalTbl .ins-row[data-goal="${G[0]}"]`);
@@ -441,7 +441,7 @@ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
441
441
  ok('0 no page error on Intelligence', In.errors.length === 0, In.errors.join(' | '));
442
442
  await In.close();
443
443
  // a phone: the page as today
444
- for (const [at, ready, row] of [['/premium-board.html', boardReady, '.ini2[data-key]:not(.bd-bc)'], ['/premium-intelligence.html', () => !!window.czPanels && document.querySelectorAll('[data-goal]').length > 1, '#goalCards .ins-card[data-goal]']]) {
444
+ for (const [at, ready, row] of [['/premium-board.html', boardReady, '.ini2[data-key]:not(.bd-bc)'], ['/premium-intelligence.html?tab=goals', () => !!window.czPanels && document.querySelectorAll('[data-goal]').length > 1, '#goalCards .ins-card[data-goal]']]) {
445
445
  const Q = await open({ w: 390, h: 844, at, ready });
446
446
  await Q.page.evaluate((s) => { const b = document.querySelector(s); if (b) b.click(); }, row);
447
447
  await until(() => Q.page.evaluate(() => !!document.querySelector('#czViewer:not([hidden])')), 5000);