create-pmos 0.257.0 → 0.259.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.
Files changed (35) hide show
  1. package/package.json +1 -1
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-adddoc-test.js +171 -0
  7. package/workspace/briefing-premium-initiative-test.js +1 -1
  8. package/workspace/briefing-premium-insights-test.js +228 -0
  9. package/workspace/fixtures/insights-premium-facts.js +30 -0
  10. package/workspace/guide/briefing-premium.md +14 -2
  11. package/workspace/lib/board-premium.js +8 -5
  12. package/workspace/lib/briefing-premium-agent.js +2 -2
  13. package/workspace/lib/custom-docs.js +107 -0
  14. package/workspace/lib/initiative-premium.js +9 -4
  15. package/workspace/lib/insights-premium.js +133 -0
  16. package/workspace/lib/route-modules.js +2 -0
  17. package/workspace/lib/routes-board-premium.js +5 -1
  18. package/workspace/lib/routes-briefing-premium.js +2 -1
  19. package/workspace/lib/routes-custom-docs.js +62 -0
  20. package/workspace/lib/routes-initiative-premium.js +4 -1
  21. package/workspace/lib/routes-insights-premium.js +53 -0
  22. package/workspace/package-lock.json +2 -2
  23. package/workspace/package.json +1 -1
  24. package/workspace/public/pm/premium-board.js +7 -4
  25. package/workspace/public/pm/premium-initiative.js +8 -7
  26. package/workspace/public/pm/premium-insights.css +143 -0
  27. package/workspace/public/pm/premium-insights.js +143 -0
  28. package/workspace/public/pm/premium-shell.js +31 -2
  29. package/workspace/public/pm/premium.css +3 -1
  30. package/workspace/public/premium-board.html +2 -2
  31. package/workspace/public/premium-initiative.html +1 -1
  32. package/workspace/public/premium-insights.html +61 -0
  33. package/workspace/server.js +2 -2
  34. package/workspace/test-files.json +4 -0
  35. package/workspace/test-lists/briefing-premium.json +4 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.257.0",
3
+ "version": "0.259.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": {
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@97ec1d5
1
+ kernel-source: pmos@538d51d
2
2
  assembled: 2026-10-18
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-10-18T01:44:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:26:53Z"}
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-10-18T01:44:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:26:53Z"}
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-10-18T01:44:16Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:26:53Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* briefing-premium-adddoc-test.js — Add a document on the premium Board and initiative page (initiative briefing-premium-adddoc; planning/prd/briefing-premium-adddoc-prd.md A1 to A8).
4
+ * Serves the real pages from the real server. The model routes and the add route are answered from fixtures, so nothing is written to this repository; the real
5
+ * route is checked only for its refusals. A1 dialog · A3 the press · A4 messages · A5 rows · A7 labels · A8 floors and fidelity */
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { spawn } = require('child_process');
9
+ const { findBrowser } = require('./lib/find-browser');
10
+ const T = require('./test-run').configure({ name: 'briefing-premium-adddoc' });
11
+ const BP = require('./lib/board-premium.js');
12
+ const IP = require('./lib/initiative-premium.js');
13
+ const BF = require('./fixtures/board-premium-facts.js');
14
+ const IF = require('./fixtures/initiative-premium-facts.js');
15
+
16
+ const BASE = T.BASE;
17
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
+ const until = async (fn, ms = 10000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
19
+ const results = [];
20
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + extra : ''}`); };
21
+ let srv = null; let browser = null;
22
+ const finish = async (code) => {
23
+ if (browser) await browser.close().catch(() => {});
24
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
25
+ T.killTmux();
26
+ const bad = results.filter((x) => !x.cond).length;
27
+ console.log(`\n${results.length - bad}/${results.length} briefing-premium-adddoc assertions passed`);
28
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
29
+ };
30
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
31
+
32
+ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'briefing-artifact.html');
33
+ const CUSTOM = [
34
+ { id: 'cd-1', scope: 'board:w1', title: 'UAT plan', writer: 'you', phase: null, link: null, at: '2026-10-18T09:00:00.000Z' },
35
+ { id: 'cd-2', scope: 'board:w1', title: 'Contract', writer: 'drafts', phase: null, link: { kind: 'Confluence', url: 'https://example.atlassian.net/wiki/spaces/X/pages/1' }, at: '2026-10-18T09:05:00.000Z' },
36
+ ];
37
+ const PAGES = {
38
+ board: { file: '/premium-board.html', api: '**/api/board-premium*', scope: 'board:w1', mk: (custom) => BP.build(BF.facts({ custom })), ready: '#ibBody .ini2', btn: '#addDoc', qs: '?theme=' },
39
+ initiative: { file: '/premium-initiative.html', api: '**/api/initiative-premium*', scope: 'initiative:self-serve-v2', mk: (custom) => IP.build(IF.facts({ custom })), ready: '#cIniTk', btn: '[data-adddoc]', qs: '?id=self-serve-v2&ws=w1&board=w1&theme=' },
40
+ };
41
+
42
+ (async () => {
43
+ const exe = findBrowser();
44
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
45
+ let chromium;
46
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
47
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PMOS_SELF_ROOT: path.resolve(__dirname, '..') }) });
48
+ await T.waitForServer(BASE);
49
+ browser = await chromium.launch({ executablePath: exe });
50
+
51
+ const open = async (kind, { w = 1280, h = 900, theme = 'light', custom = [], add = { status: 200, body: { ok: true } } } = {}) => {
52
+ const P = PAGES[kind];
53
+ const ctx = await browser.newContext({ viewport: { width: w, height: h } });
54
+ if (kind === 'board') await ctx.addInitScript(() => { try { localStorage.setItem('pmos.premium.openAs', 'popup'); } catch { /* none */ } });
55
+ const page = await ctx.newPage();
56
+ let current = custom, calls = 0, reply = add; const errors = [], posts = [];
57
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
58
+ await page.route(P.api, (r) => { calls++; return r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model: P.mk(current), as_of: Date.now() }) }); });
59
+ await page.route('**/api/custom-docs/**', (r) => { const rq = r.request(); posts.push({ path: new URL(rq.url()).pathname, body: JSON.parse(rq.postData() || '{}'), headers: rq.headers() }); r.fulfill({ status: reply.status, contentType: 'application/json', body: JSON.stringify(reply.body) }); });
60
+ await page.route('**/api/briefing-premium/**', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, turns: [], working: false }) }));
61
+ await page.goto(BASE + P.file + P.qs + theme);
62
+ const up = await until(() => page.evaluate((s) => !!document.querySelector(s), P.ready), 20000);
63
+ return { ctx, page, errors, posts, up, calls: () => calls, setCustom: (c) => { current = c; }, reply: (a) => { reply = a; } };
64
+ };
65
+ const txt = (p, s) => p.evaluate((q) => (document.querySelector(q) || {}).textContent || '', s);
66
+
67
+ for (const kind of ['board', 'initiative']) {
68
+ const P = PAGES[kind], ini = kind === 'initiative';
69
+ const A = await open(kind), p = A.page;
70
+ ok(`${kind} 0 the page draws`, A.up);
71
+ if (!A.up) return finish(1);
72
+ ok(`${kind} A1 the Core documents card has an Add a document button`, await p.evaluate((s) => { const b = document.querySelector(s); return !!b && /Add a document/.test(b.textContent) && !b.hidden; }, P.btn));
73
+ await p.click(P.btn); await sleep(250);
74
+ const form = await p.evaluate(() => ({ open: document.querySelector('#dlg').classList.contains('on'), title: document.querySelector('#dTitle').textContent, t: !!document.querySelector('#adT'), phase: !!document.querySelector('#adC'), seg: [...document.querySelectorAll('#adW button')].map((b) => b.textContent), kinds: [...document.querySelectorAll('#adK option')].map((o) => o.textContent), uOff: document.querySelector('#adU').disabled, note: document.querySelector('.addf .note').textContent }));
75
+ ok(`${kind} A1 the dialog has the mockup's fields`, form.open && form.title === 'Add a document' && form.t && form.phase === ini && form.seg.join() === 'PMOS drafts it,I write it' && form.kinds.join() === 'In PMOS,Confluence,Google Docs,Google Slides' && form.uOff, JSON.stringify(form));
76
+ ok(`${kind} A7 the dialog says the document is saved and the linked page is not read`, /saved on the (board|initiative)'s record/.test(form.note) && /does not read or sync/.test(form.note), form.note);
77
+ await p.click('#adGo'); await sleep(120);
78
+ ok(`${kind} A4 an empty title is refused in the dialog and posts nothing`, /Give the document a title/.test(await txt(p, '#adM')) && A.posts.length === 0);
79
+ await p.fill('#adT', 'UAT plan'); await p.selectOption('#adK', 'Confluence'); await sleep(100);
80
+ ok(`${kind} A1 the address field opens for a link kind`, await p.evaluate(() => !document.querySelector('#adU').disabled));
81
+ await p.click('#adGo'); await sleep(120);
82
+ ok(`${kind} A4 a link kind with no address is refused in the dialog and posts nothing`, /Paste the address of the Confluence page/.test(await txt(p, '#adM')) && A.posts.length === 0);
83
+ A.reply({ status: 409, body: { ok: false, error: '“UAT plan” is already on this ' + (ini ? 'initiative' : 'board') + '.' } });
84
+ await p.fill('#adU', 'https://example.atlassian.net/wiki/x'); await p.click('#adGo'); await sleep(250);
85
+ ok(`${kind} A4 a refusal from the route is shown in the dialog, which stays open`, /already on this/.test(await txt(p, '#adM')) && await p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !document.querySelector('#adGo').disabled));
86
+ A.reply({ status: 200, body: { ok: true } }); const calls0 = A.calls();
87
+ await p.click('[data-w="you"]'); if (ini) await p.selectOption('#adC', 'Plan');
88
+ await p.click('#adGo'); await sleep(500);
89
+ const last = A.posts[A.posts.length - 1], mint = await T.nonce(BASE);
90
+ const want = { ws: ini ? 'w1' : 'w1', scope: P.scope, title: 'UAT plan', writer: 'you', kind: 'Confluence', url: 'https://example.atlassian.net/wiki/x' };
91
+ if (ini) want.phase = 'Plan';
92
+ ok(`${kind} A3 the press posts the entered fields to the one route, with the launch nonce and no writer field`, last && last.path === '/api/custom-docs/add' && JSON.stringify(Object.keys(last.body).sort()) === JSON.stringify(Object.keys(want).sort()) && Object.keys(want).every((k) => last.body[k] === want[k] || k === 'ws') && !!mint && last.headers['x-pmos-nonce'] === mint && !['by', 'via', 'at', 'actor', 'pm', 'nonce'].some((k) => k in last.body), JSON.stringify(last && last.body));
93
+ ok(`${kind} A3 nothing else was posted`, A.posts.every((x) => x.path === '/api/custom-docs/add'));
94
+ ok(`${kind} A1 the dialog closes, the page reads again and focus returns to the button`, A.calls() > calls0 && await p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')) && await p.evaluate((s) => document.activeElement === document.querySelector(s), P.btn));
95
+ A.setCustom(CUSTOM.map((d) => Object.assign({}, d, { scope: P.scope }))); await p.reload(); await until(() => p.evaluate((s) => !!document.querySelector(s), P.ready), 20000); await sleep(400);
96
+ const sel = ini ? '#cIniDoc' : '#cDocs';
97
+ const rows = await p.evaluate((s) => [...document.querySelectorAll(s + ' .dmr')].map((r) => ({ t: r.querySelector('b').textContent, s: r.querySelector('.dmm .s').textContent.trim(), small: r.querySelector('.dmn>small').textContent, meta: r.querySelector('.dmm').textContent, btn: r.querySelectorAll('button').length })), sel);
98
+ const uat = rows.find((r) => r.t === 'UAT plan'), con = rows.find((r) => r.t === 'Contract');
99
+ ok(`${kind} A5 an unlinked document reads Not started with the date it was added and no press`, uat && uat.s === 'Not started' && /added 18 Oct/.test(uat.meta) && /You write it/.test(uat.meta) && uat.btn === 0, JSON.stringify(uat));
100
+ ok(`${kind} A5 a linked document reads Linked, shows its address as text and has no press`, con && con.s === 'Linked' && /Confluence: https:\/\/example\.atlassian\.net/.test(con.small) && con.btn === 0 && !/Up to date/.test(con.s), JSON.stringify(con));
101
+ const sum = await txt(p, sel + ' .dsum');
102
+ ok(`${kind} A5 the summary counts one linked and the total counts both`, /1\s*linked/.test(sum) && /up to date/.test(sum), sum);
103
+ ok(`${kind} A5 the filter chips keep their four and a linked document is under All only`, await p.evaluate((s) => { const b = [...document.querySelectorAll(s + ' #dmF button')]; return b.length === 4 && /Linked/.test(b.map((x) => x.textContent).join('')) === false; }, sel));
104
+ await p.click(P.btn); await sleep(250);
105
+ const floors = await p.evaluate(() => { const h = (s) => Math.round(document.querySelector(s).getBoundingClientRect().height); return { go: h('#adGo'), no: h('#adNo'), t: h('#adT'), k: h('#adK'), w: Math.round(document.querySelector('#adW button').getBoundingClientRect().height), add: h('.dmadd2') }; });
106
+ ok(`${kind} A8 the buttons are at least 44 px (the fields and the switch keep the mockup's own size)`, [floors.go, floors.no, floors.add].every((v) => v >= 44), JSON.stringify(floors));
107
+ await p.keyboard.press('Escape'); await sleep(250);
108
+ ok(`${kind} A8 Escape closes the dialog`, await p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
109
+ ok(`${kind} no page error`, A.errors.length === 0, A.errors.join(' | '));
110
+ await A.ctx.close();
111
+ const N = await open(kind, { w: 390, h: 844 }); await N.page.click(P.btn); await sleep(300);
112
+ ok(`${kind} A8 no sideways scroll at 390 px with the dialog open`, await N.page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1 && document.querySelector('#dlg').getBoundingClientRect().right <= innerWidth + 1));
113
+ await N.ctx.close();
114
+ }
115
+
116
+ /* the real route: refusals only, so nothing is written to this repository */
117
+ {
118
+ const H = await T.pressHeaders(BASE);
119
+ const send = (body, headers) => fetch(BASE + '/api/custom-docs/add', { method: 'POST', headers, body: JSON.stringify(body) }).then(async (r) => ({ status: r.status, body: await r.json().catch(() => null) }));
120
+ const noNonce = await send({ scope: 'board:nope', title: 'A' }, { 'Content-Type': 'application/json' });
121
+ ok('A3 a request without the page headers is refused with 403', noNonce.status === 403, JSON.stringify(noNonce));
122
+ const agent = await send({ scope: 'board:nope', title: 'A' }, Object.assign({}, H, { 'x-pmos-session': 'abc' }));
123
+ ok('A3 an agent session is refused with 403', agent.status === 403, JSON.stringify(agent));
124
+ const empty = await send({ scope: 'board:nope', title: ' ' }, H);
125
+ ok('A4 an empty title is refused with 400 and a reason', empty.status === 400 && /title/.test(empty.body.error), JSON.stringify(empty));
126
+ const orphan = await send({ scope: 'board:no-such-board-xyz', title: 'A' }, H);
127
+ ok('A4 a board this workspace does not hold is refused', orphan.status !== 200 && orphan.body && orphan.body.ok === false, JSON.stringify(orphan));
128
+ const get = await fetch(BASE + '/api/custom-docs?scope=board:no-such-board-xyz').then(async (r) => ({ status: r.status, body: await r.json() }));
129
+ ok('A2 the list answers an empty set for a scope with no document', get.status === 200 && Array.isArray(get.body.docs) && get.body.docs.length === 0, JSON.stringify(get));
130
+ const badScope = await fetch(BASE + '/api/custom-docs?scope=portfolio').then((r) => r.status);
131
+ ok('A2 a scope that is not a board or initiative is refused', badScope === 400);
132
+ const wrong = await fetch(BASE + '/api/custom-docs/add').then((r) => r.status);
133
+ ok('A3 the add route takes POST only', wrong === 405);
134
+ }
135
+
136
+ /* A8 fidelity against the mockup's own dialog */
137
+ if (!fs.existsSync(MOCKUP)) ok('A8 the mockup is in the repository', false, MOCKUP);
138
+ else {
139
+ const PAIRS = [['ttl', '#dTitle'], ['note', '.addf .note'], ['lbl', '.addf label'], ['inp', '#adT'], ['phase', '#adC'], ['seg', '#adW'], ['segb', '#adW button'], ['kind', '#adK'], ['url', '#adU'], ['msg', '#adM'], ['go', '#adGo'], ['no', '#adNo'], ['pane', '#oMain'], ['paper', '#oMain .paper']];
140
+ const PROPS = ['fontSize', 'fontWeight', 'fontFamily', 'color', 'backgroundColor', 'borderRadius', 'paddingTop', 'paddingLeft', 'letterSpacing', 'lineHeight', 'borderTopColor', 'minHeight'];
141
+ const grab = (pg) => pg.evaluate(([pairs, props]) => { const o = {}; for (const [n, s] of pairs) { const e = document.querySelector(s); if (!e) { o[n] = null; continue; } const cs = getComputedStyle(e), r = e.getBoundingClientRect(), v = { width: e.offsetWidth, height: e.offsetHeight, cw: e.clientWidth, sh: e.scrollHeight }; props.forEach((k) => { v[k] = cs[k]; }); o[n] = v; } return o; }, [PAIRS, PROPS]);
142
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const th of ['light', 'dark']) {
143
+ const m = await (await browser.newContext({ viewport: { width: w, height: h } })).newPage();
144
+ await m.goto('file://' + MOCKUP);
145
+ await until(() => m.evaluate(() => document.querySelectorAll('#rank .rr').length > 0));
146
+ await m.evaluate((t) => { document.documentElement.dataset.theme = t; document.querySelector('.pl[data-p="init"]').click(); }, th);
147
+ await until(() => m.evaluate(() => document.querySelectorAll('#ibBody .ini2').length > 0)); await sleep(500);
148
+ await m.evaluate(() => { showInit('initiative', 'pmos', 0); });
149
+ await until(() => m.evaluate(() => !!document.querySelector('#cIniDoc .dmr'))); await sleep(800);
150
+ const mBtn = await m.evaluate(() => { const b = document.querySelector('#cIniDoc .dmadd2'), cs = getComputedStyle(b), r = b.getBoundingClientRect(); return { fs: cs.fontSize, fw: cs.fontWeight, bg: cs.backgroundColor, c: cs.color, br: cs.borderRadius, h: Math.round(r.height) }; });
151
+ await m.click('#cIniDoc .dmadd2'); await sleep(500);
152
+ const a = await grab(m);
153
+ const R = await open('initiative', { w, h, theme: th }); await sleep(400);
154
+ const rBtn = await R.page.evaluate(() => { const b = document.querySelector('[data-adddoc]'), cs = getComputedStyle(b), r = b.getBoundingClientRect(); return { fs: cs.fontSize, fw: cs.fontWeight, bg: cs.backgroundColor, c: cs.color, br: cs.borderRadius, h: Math.round(r.height) }; });
155
+ await R.page.click('[data-adddoc]'); await sleep(500);
156
+ const c = await grab(R.page), diffs = [];
157
+ for (const k of Object.keys(mBtn)) if (k !== 'h' && mBtn[k] !== rBtn[k]) diffs.push(`btn.${k} ${mBtn[k]} | ${rBtn[k]}`); // the height is the 44 px floor the earlier slices keep (the mockup draws 36)
158
+ for (const [n] of PAIRS) {
159
+ if (!a[n] || !c[n]) { diffs.push(n + ' missing'); continue; }
160
+ for (const k of Object.keys(a[n])) {
161
+ if (k === 'cw' || k === 'sh' || ((n === 'ttl' || n === 'pane' || n === 'paper') && (k === 'width' || k === 'height'))) continue; // the dialog's columns size to the conversation beside the form, which differs
162
+ const geom = k === 'width' || k === 'height';
163
+ if (geom ? Math.abs(a[n][k] - c[n][k]) > 14 : a[n][k] !== c[n][k]) diffs.push(`${n}.${k} ${a[n][k]} | ${c[n][k]}`);
164
+ }
165
+ }
166
+ ok(`A8 the button and the dialog match the mockup at ${w} px, ${th}`, diffs.length === 0, diffs.join(' ; '));
167
+ await m.context().close(); await R.ctx.close();
168
+ }
169
+ }
170
+ return finish();
171
+ })().catch((e) => { console.error(e); finish(1); });
@@ -147,7 +147,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
147
147
  const mint0 = await T.nonce(BASE);
148
148
  ok('I10 both task presses carried the launch nonce and no writer field', !!mint0 && A.posts.filter((x) => /^\/api\/boards\/tasks\//.test(x.path)).every((x) => x.headers['x-pmos-nonce'] === mint0 && !['by', 'via', 'at', 'actor', 'pm', 'nonce'].some((k) => k in x.body)));
149
149
  await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
150
- ok('I6 there is no Add a document: no store for it exists', !(await p.evaluate(() => /Add a document/.test(document.body.textContent))));
150
+ ok('I6 Add a document is the one button of the Core documents card that adds (its own suite is briefing-premium-adddoc-test.js)', await p.evaluate(() => document.querySelectorAll('[data-adddoc]').length === 1 && /Add a document/.test(document.querySelector('#cIniDoc .ch').textContent)));
151
151
 
152
152
  /* I7 documents, I11 one count */
153
153
  ok('I7 the counts agree: caption, summary, filter and bar', await p.evaluate(() => { const s = document.querySelector('.dsum').textContent.replace(/\s+/g, ' '); const f = [...document.querySelectorAll('#dmF button')].map((b) => b.textContent.replace(/\s+/g, '')).join(','); return document.querySelector('#hDoc + small').textContent === '5' && /1 draft to review/.test(s) && /3 not started/.test(s) && /1 up to date/.test(s) && f === 'All5,Notstarted3,Draft1,Uptodate1' && document.querySelectorAll('.dprog i').length === 5; }));
@@ -0,0 +1,228 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* briefing-premium-insights-test.js — the premium Insights page (initiative briefing-premium-insights; planning/prd/briefing-premium-insights-prd.md I1 to I11).
4
+ * Serves the real page from the real server. Most checks answer GET /api/insights-premium with the model lib/insights-premium.js builds from a fixture
5
+ * (fixtures/insights-premium-facts.js); the last blocks read a scratch repository's KR metric records through the real route, and compare the page with the mockup.
6
+ * I1 place · I2 reading · I3 charts · I4 no series · I5 dashboards · I6 what stands out · I7 dialog · I8 reports · I9 labels · I10 empty · I11 floors and fidelity */
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const { spawn } = require('child_process');
11
+ const { findBrowser } = require('./lib/find-browser');
12
+ const T = require('./test-run').configure({ name: 'briefing-premium-insights' });
13
+ const IP = require('./lib/insights-premium.js');
14
+ const F = require('./fixtures/insights-premium-facts.js');
15
+
16
+ const BASE = T.BASE;
17
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
+ const until = async (fn, ms = 10000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
19
+ const results = [];
20
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + extra : ''}`); };
21
+ let srv = null, srv2 = null, browser = null;
22
+ const finish = async (code) => {
23
+ if (browser) await browser.close().catch(() => {});
24
+ for (const s of [srv, srv2]) if (s) { try { s.kill('SIGKILL'); } catch { /* gone */ } }
25
+ T.killTmux();
26
+ const bad = results.filter((x) => !x.cond).length;
27
+ console.log(`\n${results.length - bad}/${results.length} briefing-premium-insights assertions passed`);
28
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
29
+ };
30
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
31
+
32
+ const mk = (o) => IP.build(F.facts(o));
33
+ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'briefing-artifact.html');
34
+
35
+ (async () => {
36
+ const exe = findBrowser();
37
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
38
+ let chromium;
39
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
40
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PMOS_SELF_ROOT: path.resolve(__dirname, '..') }) });
41
+ await T.waitForServer(BASE);
42
+ browser = await chromium.launch({ executablePath: exe });
43
+
44
+ const open = async ({ w = 1280, h = 900, theme = 'light', model = mk(), answers = null } = {}) => {
45
+ const ctx = await browser.newContext({ viewport: { width: w, height: h } });
46
+ const page = await ctx.newPage();
47
+ let current = model, calls = 0; const errors = [], posts = []; let thread = { ok: true, turns: [], working: false };
48
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
49
+ page.on('request', (rq) => { if (rq.method() !== 'GET') posts.push(rq.method() + ' ' + new URL(rq.url()).pathname); });
50
+ await page.route('**/api/insights-premium*', (r) => { calls++; if (answers) { const a = answers(calls); return r.fulfill({ status: a.status, contentType: 'application/json', body: JSON.stringify(a.body) }); } return r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model: current, as_of: 1 }) }); });
51
+ await page.route('**/api/briefing-premium/**', (r) => { const rq = r.request(); if (rq.method() === 'GET') return r.fulfill({ contentType: 'application/json', body: JSON.stringify(thread) }); return r.fulfill({ contentType: 'application/json', body: '{"ok":true}' }); });
52
+ await page.goto(BASE + '/premium-insights.html?theme=' + theme);
53
+ const up = await until(() => page.evaluate(() => document.querySelectorAll('#dashBody .mch').length > 0 || /could not be read/.test(document.querySelector('#snap').textContent) || document.querySelectorAll('#dashBody .nempty').length > 0), 20000);
54
+ return { ctx, page, errors, posts, up, calls: () => calls, setModel: (m) => { current = m; }, setThread: (t) => { thread = t; } };
55
+ };
56
+
57
+ const A = await open();
58
+ ok('0 the page draws the charts', A.up);
59
+ if (!A.up) return finish(1);
60
+ const p = A.page, M = mk();
61
+ const txt = (s) => p.evaluate((q) => (document.querySelector(q) || {}).textContent || '', s);
62
+
63
+ /* I1 */
64
+ const rail = await p.evaluate(() => ({ names: [...document.querySelectorAll('.rail .pl')].map((b) => b.textContent.trim()), cur: document.querySelector('.rail [aria-current="page"]').textContent.trim(), pi: getComputedStyle(document.querySelector('.rail')).getPropertyValue('--pi').trim(), title: document.title, name: document.querySelector('#crBoard').textContent, sw: document.querySelector('#crSw').hidden }));
65
+ ok('I1 the rail names four places, Insights is current, the board is named and has no switcher for one board', rail.names.join() === 'Briefing,My work,Board,Insights' && rail.cur === 'Insights' && rail.pi === '3' && rail.name === 'pmos' && rail.sw, JSON.stringify(rail));
66
+ ok('I1 the page is served at /premium-insights and /premium-insights.html', (await fetch(BASE + '/premium-insights')).status === 200 && (await fetch(BASE + '/premium-insights.html')).status === 200);
67
+ for (const [go, re] of [['brief', /\/premium\.html$/], ['work', /\/premium-work\.html$/], ['init', /\/premium-board\.html$/]]) {
68
+ const r2 = await open(); await r2.page.locator(`.rail [data-go="${go}"]`).click();
69
+ ok(`I1 the ${go} button opens its premium page`, await until(() => re.test(r2.page.url()), 5000), r2.page.url());
70
+ await r2.ctx.close();
71
+ }
72
+ { const r2 = await open(); const before = r2.page.url(); await r2.page.locator('.rail [data-go="rep"]').click(); await sleep(300); ok('I1 the Insights button opens nothing else: it is the page already', r2.page.url() === before); await r2.ctx.close(); }
73
+
74
+ /* I3 charts */
75
+ const ch = await p.evaluate(() => ({ n: document.querySelectorAll('#dashBody .mch').length, tiles: [...document.querySelectorAll('#dashBody .mch')].map((t) => ({ lab: t.querySelector('.mlab').firstChild.textContent, chip: t.querySelector('.mchip').textContent, val: t.querySelector('.mval').textContent, cap: t.querySelector('.mwk').textContent, tg: !!t.querySelector('.tg'), foot: t.querySelector('.mfoot').textContent, pts: t.querySelector('.ln2').getAttribute('d').split('L').length, off: t.classList.contains('off') })) }));
76
+ ok('I3 one chart for each KR metric with two or more readings, with its latest value, chip and target', ch.n === 3 && ch.tiles[0].lab === 'Partner activation' && ch.tiles[0].val === '28%' && ch.tiles[0].chip === 'Behind its line' && /target 50%/.test(ch.tiles[0].cap) && ch.tiles[0].tg && ch.tiles[1].chip === 'On its line' && !ch.tiles[1].off && ch.tiles[2].val === '9 days', JSON.stringify(ch.tiles[0]));
77
+ ok('I3 the line has exactly as many points as the record has readings (a gap is not filled)', ch.tiles[0].pts === 4 && ch.tiles[1].pts === 4);
78
+ ok('I3 the foot names the first and last date and says the dashed line is the target', /1 Jul/.test(ch.tiles[0].foot) && /15 Oct/.test(ch.tiles[0].foot) && /dashed line is the target/.test(ch.tiles[0].foot), ch.tiles[0].foot);
79
+ {
80
+ const gap = await p.evaluate(() => { const t = document.querySelector('#dashBody .mch'); const d = t.querySelector('.ln2').getAttribute('d').split('L').map((s) => parseFloat(s.replace('M', ''))); return d; });
81
+ ok('I3 the x position follows the date: the long wait between 1 Aug and 1 Oct is the widest step', (gap[2] - gap[1]) > 1.9 * (gap[1] - gap[0]) && (gap[3] - gap[2]) < (gap[1] - gap[0]) / 2, JSON.stringify(gap));
82
+ }
83
+ // hover and keys move the reading
84
+ {
85
+ const t = p.locator('#dashBody .mch').first(); await t.focus(); await p.keyboard.press('ArrowLeft');
86
+ const a = await p.evaluate(() => { const t = document.querySelector('#dashBody .mch'); return { v: t.querySelector('.mval').textContent, c: t.querySelector('.mwk').textContent, hv: t.classList.contains('hv') }; });
87
+ ok('I3 the left arrow reads the reading before the last, with its date', a.v === '30%' && /1 Oct/.test(a.c) && a.hv, JSON.stringify(a));
88
+ await p.keyboard.press('ArrowRight');
89
+ ok('I3 the right arrow returns to the latest reading', (await txt('#dashBody .mch .mval')) === '28%');
90
+ }
91
+ /* I4 no series */
92
+ const ns = await p.evaluate(() => [...document.querySelectorAll('#dashBody .ngl, #dashBody .dplist .nempty')].map((e) => e.textContent.replace(/\s+/g, ' ').trim()));
93
+ ok('I4 a measure with one reading or none is listed with the record\'s reason and not drawn', ns[0] === 'No series recorded · 2' && /Partner NPS.*Only one reading is recorded\. It is not drawn\./.test(ns[1]) && /Monthly churn.*No reading is recorded yet\./.test(ns[2]), JSON.stringify(ns));
94
+ /* I5 dashboards */
95
+ const tabs = await p.evaluate(() => [...document.querySelectorAll('#dashTabs button')].map((b) => b.textContent + ':' + b.getAttribute('aria-pressed')));
96
+ ok('I5 dashboards are the pillars the records name, all measures first', tabs.join() === 'All measures:true,Growth:false,Reliability:false', tabs.join());
97
+ await p.click('#dashTabs [data-d="p:Reliability"]');
98
+ ok('I5 choosing a pillar shows only its charts and one count', (await p.evaluate(() => document.querySelectorAll('#dashBody .mch').length)) === 1 && /1 of 1.*on their line/.test(await txt('#dashBody .mhint')) && (await p.evaluate(() => document.querySelector('#dashBody .mprog').getAttribute('aria-valuenow'))) === '1');
99
+ await p.click('#dashTabs [data-d="all"]');
100
+ const hint = await txt('#dashBody .mhint');
101
+ ok('I5 the card counts the measures behind their line from the records: 1 of 3 on their line', /1 of 3 on their line\. 2 are behind it\./.test(hint.replace(/\s+/g, ' ')), hint);
102
+ ok('I5 the dock counts the same two', (await txt('#dN')) === '2' && /measures off their line/.test(await txt('#dLab')) && /First Time to first call/.test(await txt('#dNext')));
103
+ /* I6 */
104
+ const fd = await p.evaluate(() => [...document.querySelectorAll('.nfd li')].map((li) => li.className + ': ' + li.textContent.replace(/\s+/g, ' ').trim()));
105
+ ok('I6 what stands out is up to three plain sentences with numbers from the series', fd.length >= 1 && fd.length <= 3 && /^stuck: Time to first call has been behind its line at three readings in a row/.test(fd[0]) && fd.some((x) => /from 30% to 28%/.test(x)), JSON.stringify(fd));
106
+ ok('I6 no sentence forecasts or gives a cause', !fd.some((x) => /forecast|will reach|because|caused|expected to/i.test(x)));
107
+ /* I7 dialog */
108
+ await p.locator('.nfd .nfr').first().click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(500);
109
+ const dl = await p.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, eye: document.querySelector('#dEye').textContent, kv: [...document.querySelectorAll('#oMain .kv2')].map((k) => k.textContent.replace(/\s+/g, ' ')).join(' | '), path: document.querySelector('#oMain .dpath').textContent, btn: document.querySelectorAll('#oMain button').length, hold: document.querySelector('#holdWhy').textContent, inert: ['.rail', 'main.stage', '#dock'].every((s) => document.querySelector(s).inert) }));
110
+ ok('I7 a finding opens the standard dialog: the record\'s numbers, its readings with dates, its path, no press', dl.title === 'Time to first call' && /real data/.test(dl.eye) && /Target3 days by 31 Dec/.test(dl.kv) && /15 Oct9 days/.test(dl.kv) && dl.path === 'planning/records/kr-metrics.jsonl' && dl.btn === 0 && /Nothing here changes a record/.test(dl.hold) && dl.inert, JSON.stringify(dl));
111
+ ok('I7 Escape closes it and focus returns', (await p.keyboard.press('Escape'), await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')))));
112
+ await p.locator('#dashBody [data-open]').filter({ hasText: 'Details' }).first().click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(300);
113
+ ok('I7 the Details link of a chart opens that chart\'s dialog', (await txt('#dTitle')) === 'Partner activation');
114
+ await p.keyboard.press('Escape'); await sleep(300);
115
+ /* the agent is the read-only one: a question goes to the briefing route and nothing else posts */
116
+ {
117
+ const R = await open(); const posts = [];
118
+ await R.page.route('**/api/briefing-premium/ask', (r) => { posts.push(JSON.parse(r.request().postData() || '{}')); r.fulfill({ contentType: 'application/json', body: '{"ok":true,"id":"bq-1","state":"working"}' }); });
119
+ await R.page.locator('#dashBody [data-open]').filter({ hasText: 'Details' }).first().click(); await until(() => R.page.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(400);
120
+ await R.page.fill('#askIn', 'Why is this behind?'); await R.page.keyboard.press('Enter'); await sleep(500);
121
+ ok('I7 a question goes to the read-only agent with the chart\'s key, and the page posts nothing else', posts.length === 1 && posts[0].key === 'ins:krm-act' && R.posts.every((x) => /briefing-premium\/ask$/.test(x)), JSON.stringify([posts, R.posts]));
122
+ await R.ctx.close();
123
+ }
124
+ /* I8 reports */
125
+ const rp = await p.evaluate(() => ({ rows: [...document.querySelectorAll('#repBody .dmr')].map((r) => r.querySelector('.dmn b').textContent + ' / ' + r.querySelector('.s').textContent), note: document.querySelector('#repBody .mhint').textContent, cap: document.querySelector('#repCap').textContent }));
126
+ ok('I8 the Reports card lists the report files: cadence, slot, draft or issued', rp.rows.join() === 'biweekly · 14 Oct / Draft,monthly · 30 Sep / Issued 1 Oct' && /Nothing is sent from here/.test(rp.note) && rp.cap === '2', JSON.stringify(rp));
127
+ { const R = await open(); await R.page.locator('#repBody .dmo').first().click(); ok('I8 a report opens the console\'s Reports tab to read it', await until(() => /\/c3\.html\?tab=rep/.test(R.page.url()), 5000), R.page.url()); await R.ctx.close(); }
128
+ /* I9 labels */
129
+ ok('I9 no demo label, and the foot says what is left out', !(await p.evaluate(() => /demo/i.test(document.querySelector('main.stage').textContent))) && /Left out: the Insight Studio/.test(await txt('#foot')) && /Real data/.test(await txt('#snap')));
130
+ ok('I9 the page makes no write request on its own', A.posts.length === 0, A.posts.join());
131
+ /* I10 empty */
132
+ {
133
+ const R = await open({ model: mk({ outcomes: [] }) });
134
+ ok('I10 with no KR metric the page says so in one sentence and the Reports card still lists its files', await R.page.evaluate(() => /No KR metric is recorded/.test(document.querySelector('#brief').textContent) && /No KR metric is recorded for this workspace/.test(document.querySelector('#dashBody').textContent) && document.querySelectorAll('#repBody .dmr').length === 2 && document.querySelectorAll('#dashBody .mch').length === 0));
135
+ await R.ctx.close();
136
+ const R2 = await open({ model: mk({ reportsOk: false, reports: [], missing: ['reports'] }) });
137
+ ok('I10 reports that could not be read are said to be unread, not empty', await R2.page.evaluate(() => /report files could not be read/.test(document.querySelector('#repBody').textContent) && /not read: reports/.test(document.querySelector('#snap').textContent)));
138
+ await R2.ctx.close();
139
+ }
140
+ /* I2 failed read */
141
+ {
142
+ const c2 = await browser.newContext({ viewport: { width: 1280, height: 900 } }), p2 = await c2.newPage();
143
+ await p2.route('**/api/insights-premium*', (r) => r.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ ok: false, state: 'error', error: 'the KR metric records could not be read: boom' }) }));
144
+ await p2.goto(BASE + '/premium-insights.html');
145
+ ok('I2 a failed read says why and draws nothing', await until(() => p2.evaluate(() => /The reason: the KR metric records could not be read: boom/.test(document.querySelector('#brief').textContent) && document.querySelectorAll('#dashBody .mch').length === 0), 4000));
146
+ await c2.close();
147
+ }
148
+
149
+ /* I11 floors */
150
+ for (const theme of ['light', 'dark']) {
151
+ const R = await open({ w: 390, h: 844, theme }), q = R.page;
152
+ const m = await q.evaluate(() => { const small = [...document.querySelectorAll('#dashTabs button, #dashBody .lk, #dashBody .nfr, #repBody .dmo, #repBody .lk, #crSw')].filter((b) => !b.closest('[hidden]') && b.getBoundingClientRect().height > 0 && b.getBoundingClientRect().height < 44).map((b) => b.className + ':' + Math.round(b.getBoundingClientRect().height)); return { over: document.documentElement.scrollWidth > innerWidth + 1, small }; });
153
+ ok(`I11 at 390 px (${theme}) the page has no sideways scroll and every control is 44 px`, !m.over && m.small.length === 0, JSON.stringify(m));
154
+ await q.locator('#dashBody .nfr').first().click(); await until(() => q.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(900);
155
+ const g = await q.evaluate(() => { const r = document.querySelector('#dlg').getBoundingClientRect(); return { l: Math.round(r.left), w: Math.round(r.width), vw: innerWidth, tabs: getComputedStyle(document.querySelector('#dTabs')).display }; });
156
+ ok(`I11 at 390 px (${theme}) the dialog is full width and its tab strip is hidden`, g.l === 0 && g.w === g.vw && g.tabs === 'none', JSON.stringify(g));
157
+ await R.ctx.close();
158
+ }
159
+ {
160
+ const R = await open(); await R.page.locator('#dashBody .lk').first().focus(); await R.page.keyboard.press('Enter'); await until(() => R.page.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(500);
161
+ ok('I11 the page behind a dialog is inert, Escape closes it and focus returns to the link', await R.page.evaluate(() => ['.rail', 'main.stage', '#dock'].every((s) => document.querySelector(s).inert)) && (await R.page.keyboard.press('Escape'), await until(() => R.page.evaluate(() => !document.querySelector('#dlg').classList.contains('on') && document.activeElement.classList.contains('lk')))));
162
+ await R.ctx.close();
163
+ }
164
+
165
+ /* the real routes: this repository holds no KR metric record, and a scratch repository holds one with a gap */
166
+ {
167
+ const r = await fetch(BASE + '/api/insights-premium'); const j = await r.json();
168
+ ok('E1 the real route answers ready for this repository, with no demo data', r.status === 200 && j.ok && j.state === 'ready' && !/demo/i.test(JSON.stringify(j.model.header)), JSON.stringify(j).slice(0, 200));
169
+ ok('E2 this repository holds no KR metric record, so the model draws nothing and says so', j.model.charts.length === 0 && j.model.counts.total === 0 && /^No KR metric is recorded/.test(j.model.empty), JSON.stringify(j.model.counts));
170
+ const post = await fetch(BASE + '/api/insights-premium', { method: 'POST', headers: await T.pressHeaders(BASE), body: '{}' }).then((x) => x.status);
171
+ ok('E3 the model route is read-only', post === 405, String(post));
172
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }), pg = await ctx.newPage(), errs = [];
173
+ pg.on('pageerror', (e) => errs.push(String(e)));
174
+ await pg.goto(BASE + '/premium-insights.html');
175
+ ok('E4 the real page says there is nothing to chart, and has no script error', await until(() => pg.evaluate(() => /No KR metric is recorded/.test(document.querySelector('#dashBody').textContent)), 20000) && errs.length === 0, errs.join(' | '));
176
+ await ctx.close();
177
+ }
178
+ {
179
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-repo-'));
180
+ fs.mkdirSync(path.join(dir, 'planning', 'records'), { recursive: true });
181
+ const L = [{ id: '1', kind: 'add', rid: 'krm-a', fields: { metric: 'Partner activation', baseline: 20, target: 50, by: '2026-12-31', pillar: 'Growth', unit: '%' } },
182
+ { id: '2', kind: 'reading', rid: 'krm-a', fields: { at: '2026-07-01', value: 20 } }, { id: '3', kind: 'reading', rid: 'krm-a', fields: { at: '2026-08-01', value: 24 } }, { id: '4', kind: 'reading', rid: 'krm-a', fields: { at: '2026-10-01', value: 30 } },
183
+ { id: '5', kind: 'add', rid: 'krm-b', fields: { metric: 'Lonely', baseline: 1, target: 2, by: '2026-12-31' } }, { id: '6', kind: 'reading', rid: 'krm-b', fields: { at: '2026-10-01', value: 1 } }];
184
+ fs.writeFileSync(path.join(dir, 'planning', 'records', 'kr-metrics.jsonl'), L.map((x) => JSON.stringify(x)).join('\n') + '\n');
185
+ const port2 = T.port(), base2 = `http://${require('./test-run').HOST}:${port2}`;
186
+ srv2 = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(port2), PMOS_SELF_ROOT: dir, PMOS_STATE_DIR: fs.mkdtempSync(path.join(os.tmpdir(), 'ins-state-')) }) });
187
+ await T.waitForServer(base2);
188
+ const j = await (await fetch(base2 + '/api/insights-premium')).json(); const m = j.model;
189
+ ok('E5 a scratch repository\'s KR metric records reach the page model: one chart of three readings, one measure without a series', !!m && m.charts.length === 1 && m.charts[0].pts.length === 3 && m.charts[0].v === '30%' && m.noSeries.length === 1 && m.noSeries[0].why === 'Only one reading is recorded.', JSON.stringify(m && m.counts));
190
+ ok('E6 the real model keeps the gap: the 1 Aug to 1 Oct step is wider than 1 Jul to 1 Aug', !!m && m.charts[0].pts[2].fx - m.charts[0].pts[1].fx > 1.9 * (m.charts[0].pts[1].fx - m.charts[0].pts[0].fx));
191
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }), pg = await ctx.newPage(), errs = [];
192
+ pg.on('pageerror', (e) => errs.push(String(e)));
193
+ await pg.goto(base2 + '/premium-insights.html');
194
+ ok('E7 the real page draws that chart with the record\'s numbers and no script error', await until(() => pg.evaluate(() => { const t = document.querySelector('#dashBody .mch'); return !!t && t.querySelector('.mval').textContent === '30%' && /Partner activation/.test(t.textContent); }), 20000) && errs.length === 0, errs.join(' | '));
195
+ await ctx.close();
196
+ }
197
+
198
+ /* I11 fidelity against the mockup */
199
+ if (!fs.existsSync(MOCKUP)) ok('I11 the mockup is in the repository', false, MOCKUP);
200
+ else {
201
+ const PAIRS = [['rail', '.rail', '.rail'], ['card', '.nlc .card', '.nlc .card'], ['heading', '#hNd', '#hDash'], ['band', '.nfd', '.nfd'], ['bandlabel', '.nfd .label', '.nfd .label'], ['finding', '.nfd .nfr', '.nfd .nfr'], ['findtext', '.nfd .nft', '.nfd .nft'], ['dot', '.nfd .nfdot', '.nfd .nfdot'],
202
+ ['hint', '.mhint', '.mhint'], ['grid', '.ngrid', '.ngrid'], ['tile', '.ngrid .mt1', '.ngrid .mt1'], ['tlabel', '.ngrid .mlab', '.ngrid .mlab'], ['chip', '.ngrid .mchip', '.ngrid .mchip'], ['value', '.ngrid .mval', '.ngrid .mval'], ['caption', '.ngrid .mwk', '.ngrid .mwk'],
203
+ ['foot', '.ngrid .mfoot', '.ngrid .mfoot'], ['link', '.ntf .lk', '.ntf .lk'], ['repcard', '.nlr .card', '.nlr .card'], ['dock', '.dock', '.dock']];
204
+ const SKIP_W = ['card', 'band', 'bandlabel', 'finding', 'findtext', 'hint', 'tile', 'tlabel', 'chip', 'value', 'caption', 'foot', 'link', 'heading', 'repcard', 'grid'];
205
+ const PROPS = ['fontSize', 'fontWeight', 'fontFamily', 'color', 'backgroundColor', 'borderRadius', 'paddingTop', 'paddingLeft', 'letterSpacing', 'lineHeight', 'boxShadow', 'backdropFilter', 'borderTopColor'];
206
+ const grab = (pg, which) => pg.evaluate(([pairs, props, idx]) => { const o = {}; for (const pr of pairs) { const n = pr[0], s0 = pr[idx]; const s = (n === 'rail' || n === 'dock') ? s0 : 'main.stage:not([hidden]) ' + s0; const e = document.querySelector(s); if (!e) { o[n] = null; continue; } const cs = getComputedStyle(e), r = e.getBoundingClientRect(), v = { left: Math.round(r.left), width: Math.round(r.width) }; props.forEach((k) => { v[k] = cs[k]; }); o[n] = v; } return o; }, [PAIRS, PROPS, which]);
207
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const th of ['light', 'dark']) {
208
+ const m = await (await browser.newContext({ viewport: { width: w, height: h } })).newPage();
209
+ await m.goto('file://' + MOCKUP);
210
+ await until(() => m.evaluate(() => document.querySelectorAll('#rank .rr').length > 0));
211
+ await m.evaluate((t) => { document.documentElement.dataset.theme = t; document.querySelector('.pl[data-p="ins"]').click(); }, th);
212
+ await until(() => m.evaluate(() => document.querySelectorAll('#nMain .mt1').length > 0)); await sleep(900);
213
+ const R = await open({ w, h, theme: th }); await sleep(500);
214
+ const a = await grab(m, 1), c = await grab(R.page, 2), diffs = [];
215
+ for (const [n] of PAIRS) {
216
+ if (!a[n] || !c[n]) { diffs.push(n + ' missing'); continue; }
217
+ for (const k of Object.keys(a[n])) {
218
+ const geom = k === 'left' || k === 'width';
219
+ if (geom && (SKIP_W.includes(n) && k === 'width' || ['findtext', 'tlabel', 'chip', 'value', 'caption', 'foot', 'link', 'dot', 'finding', 'hint', 'heading'].includes(n) && k === 'left')) continue;
220
+ if (geom ? Math.abs(a[n][k] - c[n][k]) > 2 : a[n][k] !== c[n][k]) diffs.push(`${n}.${k} ${a[n][k]} | ${c[n][k]}`);
221
+ }
222
+ }
223
+ ok(`I11 styles and geometry match the mockup at ${w} px, ${th}`, diffs.length === 0, diffs.join(' ; '));
224
+ await m.context().close(); await R.ctx.close();
225
+ }
226
+ }
227
+ return finish();
228
+ })().catch((e) => { console.error(e); finish(1); });
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+ /* fixtures/insights-premium-facts.js — the facts lib/insights-premium.js builds from, for a plausible workspace on 18 Oct 2026. Shapes follow the answers of
3
+ * lib/routes-c3-strategy.js (outcomes) and lib/routes-reports.js (reports). Five KR metrics: three with a series, one with a single reading, one with none.
4
+ * The Activation series has a month with no reading in it, so the page must draw a gap and not a zero. */
5
+ const NOW = new Date(2026, 9, 18, 9, 0).getTime();
6
+ const rd = (at, v) => ({ at, v });
7
+ const OUTCOMES = [
8
+ { id: 'krm-act', name: 'Partner activation', pillar: 'Growth', unit: '%', start: 20, target: 50, by: '2026-12-31', now: 28, expected: 38, shortfall: 0.33, status: 'drift', pivot: false, reason: '',
9
+ readings: [rd('2026-07-01', 20), rd('2026-08-01', 24), rd('2026-10-01', 30), rd('2026-10-15', 28)] },
10
+ { id: 'krm-up', name: 'Partner uptime', pillar: 'Reliability', unit: '%', start: 99, target: 99.9, by: '2026-12-31', now: 99.6, expected: 99.5, shortfall: -0.1, status: 'ok', pivot: false, reason: '',
11
+ readings: [rd('2026-09-01', 99.2), rd('2026-09-15', 99.4), rd('2026-10-01', 99.5), rd('2026-10-15', 99.6)] },
12
+ { id: 'krm-ttfc', name: 'Time to first call', pillar: 'Growth', unit: 'days', start: 10, target: 3, by: '2026-12-31', now: 9, expected: 6, shortfall: 0.43, status: 'drift', pivot: true, reason: '',
13
+ readings: [rd('2026-09-01', 8), rd('2026-09-15', 8.5), rd('2026-10-01', 8.8), rd('2026-10-15', 9)] },
14
+ { id: 'krm-nps', name: 'Partner NPS', pillar: 'Growth', unit: '', start: 10, target: 40, by: '2026-12-31', now: 12, expected: 30, shortfall: 0.6, status: 'off', pivot: false, reason: '',
15
+ readings: [rd('2026-10-01', 12)] },
16
+ { id: 'krm-churn', name: 'Monthly churn', pillar: 'Reliability', unit: '%', start: 4, target: 2, by: '2026-12-31', now: null, expected: null, status: 'unscored', pivot: false, reason: 'No reading is recorded yet.',
17
+ readings: [] },
18
+ ];
19
+ const REPORTS = [
20
+ { cadence: 'biweekly', slot: '2026-10-14', path: 'planning/reports/biweekly/2026-10-14.md', status: 'draft', bytes: 900, edited: false, issued: null },
21
+ { cadence: 'monthly', slot: '2026-09-30', path: 'planning/reports/monthly/2026-09-30.md', status: null, bytes: 1200, edited: false, issued: { at: '2026-10-01T09:00:00Z', by: 'wawan', via: 'ui', sha: 'a'.repeat(40) } },
22
+ ];
23
+ function facts(o = {}) {
24
+ return {
25
+ now: NOW, pending: false, missing: [],
26
+ board: { ws: 'w1', id: 'w1', name: 'pmos' }, boards: [{ ws: 'w1', id: 'w1', name: 'pmos' }],
27
+ outcomes: OUTCOMES.map((x) => ({ ...x, readings: x.readings.map((r) => ({ ...r })) })), reports: REPORTS.map((r) => ({ ...r })), reportsOk: true, ...o,
28
+ };
29
+ }
30
+ module.exports = { NOW, facts, OUTCOMES, REPORTS };
@@ -144,7 +144,7 @@ Board is the third place on the rail, at `/premium-board.html`. It reads what th
144
144
  - **Sprint** appears when an agent session has read Jira for the board. Otherwise it says there is none. **Coming up** shows the next release, from the releases ledger.
145
145
  - **Metrics** appears above the Initiatives card on the board of any workspace except the home one (PMOS itself), and counts from that workspace's own repository. It has four tiles. **Corrections per 100 runs** is the corrections logged on the week's runs in `planning/runs/agent-runs.jsonl`; a week with fewer than 10 runs is left blank. **Merged a week** counts the commits on the first-parent line of the trunk. **Blocked** and **Idle for a month** come from the workflow engine and keep no history, so they have no chart. Move over a chart, or use the arrow keys, to read a week. A tile that cannot be counted says **Not read** and why. Press a tile for its definition and values, with the read-only agent beside it. There are no targets, and Day and Month are off. It was tested only on made-up repositories, not on a real IDPF or microsite repository.
146
146
  - **The crumb** at the top names the board. With more than one board a menu switches between them, and the sparkle opens the board in the dialog with the read-only agent.
147
- - **Core documents** lists the board's documents with their state, cadence and writer, a summary (drafts to review, not started, up to date), a progress bar, a filter and a search. **Draft it** starts the existing read-only run that writes a draft and sends nothing; **Draft the N not started** does that for each document that can be drafted. **Set it up** and **Open** go to the console. Issue, Drop and Add a document are not on this page.
147
+ - **Core documents** lists the board's documents with their state, cadence and writer, a summary (drafts to review, not started, up to date), a progress bar, a filter and a search. **Draft it** starts the existing read-only run that writes a draft and sends nothing; **Draft the N not started** does that for each document that can be drafted. **Set it up** and **Open** go to the console. **Add a document** opens a form (title, who writes it, where it lives) and saves a document the core set does not cover on the board's record, in `custom-docs.jsonl`. A document with no link reads "Not started". A document with a link to Confluence or Google Docs reads "Linked" and shows its address. PMOS does not read or sync the linked page, so a linked document is never counted as up to date. Issue and Drop are not on this page.
148
148
  - **Opening an initiative.** A click on an initiative opens its page (see "Initiative page"). The **Page / Popup** switch in the header changes that: Popup opens the initiative's dialog instead, which shows its record as a grid and the path of its file, with the read-only agent beside it. The choice is kept in this browser. The dialog holds no press: moving an initiative or starting work on it is not built here.
149
149
 
150
150
  Not drawn, because PMOS holds no record for them: the Metrics card on the PMOS board, the mockup's demo measures (Activation, Partner uptime, API p95), targets, and the mockup's demo boards.
@@ -158,8 +158,20 @@ The initiative page is at `/premium-initiative.html?id=<initiative>`. A click on
158
158
  - **The header** shows a status chip, the owner and the planned finish. Each appears only when a record holds it. Under it, the stage strip shows how far through the board's workflow the initiative is.
159
159
  - **Overview** shows the description (the part of the record's title after " — "), then the next step with its reason, its action and what happens if you wait, as the workflow engine states them, and who it waits on. **PMOS can help** offers up to three presses that do something real: a draft of the first core document not started (the existing read-only run) and a question for the read-only agent. The health reasons and the board's warnings are shown as written.
160
160
  - **Checks** lists the engine's six steps (spec, contract, build, quality, review, accept) with their state and the evidence each states, and marks the next one. "All N workflow steps" lists every step.
161
- - **Tasks** lists the PRD requirements and the board's tracker items for this initiative. The repository records no result for each requirement, so a requirement says "No result" and is never drawn as done or open. **By stage** groups them by state. **Timeline** draws a bar for each task that has both a start and a due date, and lists the rest. Press a task to read its record; for a PMOS task you can change its status. **Add a task** writes a PMOS task to the board's own record; with no dates the board plans it from tomorrow for a week. Jira tickets stay read-only. There is no Add a document: nothing stores a document you add.
161
+ - **Tasks** lists the PRD requirements and the board's tracker items for this initiative. The repository records no result for each requirement, so a requirement says "No result" and is never drawn as done or open. **By stage** groups them by state. **Timeline** draws a bar for each task that has both a start and a due date, and lists the rest. Press a task to read its record; for a PMOS task you can change its status. **Add a task** writes a PMOS task to the board's own record; with no dates the board plans it from tomorrow for a week. Jira tickets stay read-only. **Add a document** works as on the Board, with a phase as well, and saves on the initiative's record.
162
162
  - **Core documents** has the same counts, filter and search as the Board's card, for this initiative. **Draft it** starts the existing read-only run that writes a draft and sends nothing. Technical documents (the record, the rubric, the stories, the review and the explainer) are grouped and not counted.
163
163
  - **The document sheet.** A document that has a file opens in a dialog with **Read** (the file's text, its front matter as a grid and an outline), **Edit** (the file as plain Markdown, a reason, and **Save**), **Proposals** (**Ask the agent**, the open proposals with **Accept** and **Reject**, and the closed ones), **Edit log** (the revisions and other entries of the document sheet) and **Health** (the document-health checks; a check with no input is not counted). The file changes only when you press Save or Accept, and every change is kept in the Edit log with its reason. Save and Reject need a reason. A proposal made on text that has since changed shows which sections are out of date and cannot take them. The agent beside the sheet still only reads. Bold and undo buttons, Issue and Drop are not built on this page.
164
164
 
165
165
  Not drawn, because PMOS holds no record for them: the mockup's demo tasks, its Jira data, and the owner "Agents" on a requirement.
166
+
167
+ ## Insights
168
+
169
+ Insights is the fourth place on the rail, at `/premium-insights.html`. It reads the KR metric records of the board's workspace and the report files the console's Reports tab lists. It presses nothing and writes nothing.
170
+
171
+ - **Charts.** One chart for each KR metric that holds at least two readings. The line runs through the readings at their dates, so a month with no reading is a gap and not a zero. The dashed line is the metric's target. The chip is the record's own line status: on its line, behind it, or well behind it. Pressing a chart, or its Details link, opens the metric's record in the dialog with the read-only agent beside it.
172
+ - **Dashboards.** The records hold no dashboard, so the groups are the pillars the metrics name, with all measures first. The switch shows only when there is more than one pillar.
173
+ - **What stands out.** Up to three plain sentences taken from the series: behind its line for three readings in a row, behind and still moving away from the target, closing in, slipped, reached its target, or a large one-step move. There is no forecast and no cause.
174
+ - **No series recorded.** A KR metric with one reading or none is listed with the reason and is not drawn.
175
+ - **Reports.** The report files of the workspace, with cadence, slot and whether each is a draft or issued. Pressing one opens the console's Reports tab, where it is read, edited or issued. Nothing is sent from this page.
176
+
177
+ Not built: the Insight Studio (making your own chart, dashboard or report by conversation), run-based charts such as corrections per 100 runs (they belong to the Board's Metrics card), saved dashboards and their layout, and any measure no record holds. KR metric records belong to a workspace, so every board of a workspace shows the same charts.
@@ -19,6 +19,7 @@
19
19
 
20
20
  const pad = (n) => String(n).padStart(2, '0');
21
21
  const hhmm = (ms) => { const d = new Date(ms); return pad(d.getHours()) + ':' + pad(d.getMinutes()); };
22
+ const Custom = require('./custom-docs.js');
22
23
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
23
24
  const isoDay = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null; };
24
25
  const shortDate = (v) => { const d = isoDay(v); return d ? d.getDate() + ' ' + MON[d.getMonth()] : ''; };
@@ -100,15 +101,17 @@ function build(f) {
100
101
  : { cap: 'none', why: 'No release is planned for this board.' };
101
102
 
102
103
  const dd = f.docs || null;
104
+ const custom = (f.custom || []).map((d) => Object.assign(Custom.rowOf(d), { added: shortDate(d.at) }));
105
+ const nLinked = custom.filter((d) => d.st === 'linked').length, nCustomNone = custom.length - nLinked;
103
106
  const docs = dd ? {
104
- cap: dd.summary ? [dd.summary.missing ? dd.summary.missing + ' not started' : null, dd.summary.draft ? dd.summary.draft + ' ' + plural(dd.summary.draft, 'draft', 'drafts') : null, dd.summary.stale ? dd.summary.stale + ' stale' : null, dd.summary.due ? dd.summary.due + ' due' : null].filter(Boolean).join(' · ') || 'all up to date' : '',
107
+ cap: dd.summary ? [(dd.summary.missing + nCustomNone) ? (dd.summary.missing + nCustomNone) + ' not started' : null, dd.summary.draft ? dd.summary.draft + ' ' + plural(dd.summary.draft, 'draft', 'drafts') : null, dd.summary.stale ? dd.summary.stale + ' stale' : null, dd.summary.due ? dd.summary.due + ' due' : null].concat(nLinked ? [nLinked + ' linked'] : []).filter(Boolean).join(' · ') || 'all up to date' : '',
105
108
  scope: dd.scope || null,
106
109
  counts: null,
107
110
  rows: (dd.docs || []).map((d) => ({ key: d.key, title: d.title, what: d.for || '', state: d.kind === 'live' ? 'Live' : DOC_STATE[d.st] || d.st || '', st: d.st, cadence: d.cadence || '', by: BY[d.by] || d.by || '', running: !!d.running,
108
- act: d.act && d.act.do === 'draft' ? { kind: 'draft', label: d.running ? 'Drafting' : d.act.label || 'Draft it' } : d.act && d.act.go ? { kind: 'go', label: d.act.label || 'Open', tab: GO[d.act.go] || 'init' } : d.open && d.open.tab ? { kind: 'go', label: 'Open', tab: GO[d.open.tab] || 'init' } : null })),
109
- } : { cap: '', rows: [], missing: true };
110
- if (dd) docs.counts = { all: docs.rows.length, none: docs.rows.filter((d) => d.st === 'missing').length, draft: docs.rows.filter((d) => d.st === 'draft').length, ok: docs.rows.filter((d) => d.st === 'ok').length };
111
- else docs.counts = { all: 0, none: 0, draft: 0, ok: 0 };
111
+ act: d.act && d.act.do === 'draft' ? { kind: 'draft', label: d.running ? 'Drafting' : d.act.label || 'Draft it' } : d.act && d.act.go ? { kind: 'go', label: d.act.label || 'Open', tab: GO[d.act.go] || 'init' } : d.open && d.open.tab ? { kind: 'go', label: 'Open', tab: GO[d.open.tab] || 'init' } : null })).concat(custom),
112
+ } : { cap: '', rows: custom, missing: true, scope: board.id ? 'board:' + board.id : null };
113
+ docs.counts = dd || custom.length ? { all: docs.rows.length, none: docs.rows.filter((d) => d.st === 'missing').length, draft: docs.rows.filter((d) => d.st === 'draft').length, ok: docs.rows.filter((d) => d.st === 'ok').length } : { all: 0, none: 0, draft: 0, ok: 0 };
114
+ if (nLinked) docs.counts.linked = nLinked; // a key only when an added document is linked
112
115
  if (!dd && !missing.includes('core documents')) missing.push('core documents');
113
116
 
114
117
  const model = {