create-pmos 0.256.0 → 0.258.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.256.0",
3
+ "version": "0.258.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@f4eae68
1
+ kernel-source: pmos@d223785
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:25:47Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:00:03Z"}
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:25:47Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:00:03Z"}
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:25:47Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:00:03Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* briefing-premium-doc-edit-test.js — the premium sheet's Edit and Proposals tabs (initiative briefing-premium-doc-edit; planning/prd/briefing-premium-doc-edit-prd.md E1 to E8).
4
+ * Serves the real page from the real server. The initiative model and the /api/doc-sheet routes are answered by a small stateful stand-in, so each press can be
5
+ * read off the request the page sent. The routes' own behaviour (the file, the log, stale, 403) is in briefing-premium-doc-edit.test.js, on a scratch repository.
6
+ * E1 tabs · E2 edit · E3 ask · E4 proposals · E5 after a write · E6 held · E7 honesty · E8 fidelity and floors */
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { spawn } = require('child_process');
10
+ const { findBrowser } = require('./lib/find-browser');
11
+ const T = require('./test-run').configure({ name: 'briefing-premium-doc-edit' });
12
+ const IP = require('./lib/initiative-premium.js');
13
+ const F = require('./fixtures/initiative-premium-facts.js');
14
+
15
+ const BASE = T.BASE;
16
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
17
+ 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); } };
18
+ const results = [];
19
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + extra : ''}`); };
20
+ let srv = null; let browser = null;
21
+ const finish = async (code) => {
22
+ if (browser) await browser.close().catch(() => {});
23
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
24
+ T.killTmux();
25
+ const bad = results.filter((x) => !x.cond).length;
26
+ console.log(`\n${results.length - bad}/${results.length} briefing-premium-doc-edit assertions passed`);
27
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
28
+ };
29
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
30
+
31
+ const MOCKUP = fs.readFileSync(path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'briefing-artifact.html'), 'utf8');
32
+ const CSS = fs.readFileSync(path.join(__dirname, 'public', 'pm', 'premium.css'), 'utf8');
33
+ const PATH = 'planning/prd/self-serve-v2-prd.md';
34
+ const TEXT = '---\ntype: PRD\ntitle: "Self-serve onboarding v2"\n---\n\n# PRD: Self-serve onboarding v2\n\n## Problem\n\nA partner waits for a person.\n\n## Goal\n\n- a first call without help\n\n## Requirements\n\nR1 a first call\n';
35
+ const prop = (o) => Object.assign({ id: 'prop-a', state: 'proposed', prompt: 'add a one-paragraph summary', at: '2026-10-18T01:00:00Z', hash: 'ha', by: 'agent', why: null, sections: [
36
+ { name: 'Summary', kind: 'added', before: '', after: 'Partners reach a first call without help.', current: null, stale: false },
37
+ { name: 'Goal', kind: 'changed', before: 'x', after: 'y', current: 'z', stale: true }] }, o || {});
38
+
39
+ (async () => {
40
+ const exe = findBrowser();
41
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
42
+ let chromium;
43
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
44
+ 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, '..') }) });
45
+ await T.waitForServer(BASE);
46
+ browser = await chromium.launch({ executablePath: exe });
47
+
48
+ const open = async ({ w = 1280, h = 900, theme = 'light', props = [prop()], post = null } = {}) => {
49
+ const ctx = await browser.newContext({ viewport: { width: w, height: h } });
50
+ const page = await ctx.newPage();
51
+ const S = { text: TEXT, revs: [{ rev: 1, why: '', by: 'baseline', at: '2026-10-16T08:00:00Z' }], props, ask: null, errors: [], posts: [], gets: [] };
52
+ page.on('pageerror', (e) => S.errors.push(String((e && e.message) || e)));
53
+ await page.route('**/api/initiative-premium*', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model: IP.build(F.facts()), as_of: F.NOW }) }));
54
+ await page.route('**/api/doc-health/check', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, health: { passed: 1, total: 1, checks: [{ id: 'fresh', pass: true, reason: 'ok' }] } }) }));
55
+ await page.route('**/api/briefing-premium/**', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, turns: [], working: false }) }));
56
+ await page.route('**/api/doc-sheet/**', (r) => {
57
+ const rq = r.request(), u = new URL(rq.url()), route = u.pathname.replace('/api/doc-sheet/', ''), send = (b, status = 200) => r.fulfill({ status, contentType: 'application/json', body: JSON.stringify(b) });
58
+ if (rq.method() === 'GET') {
59
+ S.gets.push({ route, query: u.search });
60
+ if (route === 'log') return send({ ok: true, path: PATH, revisions: S.revs, events: [] });
61
+ if (route === 'at') return send({ ok: true, path: PATH, rev: S.revs.length, text: S.text });
62
+ if (route === 'proposals') return send({ ok: true, path: PATH, proposals: S.props });
63
+ if (route === 'ask') return send(S.ask || { ok: true, id: 'ask-1', state: 'working' });
64
+ return send({ ok: false, error: 'not in this test' }, 404);
65
+ }
66
+ const body = JSON.parse(rq.postData() || '{}'); S.posts.push({ route, query: u.search, body, headers: rq.headers() });
67
+ if (post) { const a = post(route, body, S); if (a) return send(a.body, a.status || 200); }
68
+ if (route === 'edit') { S.text = body.text; S.revs.push({ rev: S.revs.length + 1, why: body.why, by: 'pm', at: '2026-10-18T02:00:00Z' }); return send({ ok: true }); }
69
+ if (route === 'accept') { S.props = S.props.map((p) => (p.id === body.id ? Object.assign({}, p, { state: 'accepted' }) : p)); S.revs.push({ rev: S.revs.length + 1, why: 'add a one-paragraph summary', by: 'pm', at: '2026-10-18T02:00:00Z' }); return send({ ok: true }); }
70
+ if (route === 'reject') { S.props = S.props.map((p) => (p.id === body.id ? Object.assign({}, p, { state: 'rejected', why: body.why }) : p)); return send({ ok: true }); }
71
+ if (route === 'ask') { S.ask = { ok: true, id: 'ask-1', state: 'working' }; return send({ ok: true, id: 'ask-1', state: 'working' }); }
72
+ return send({ ok: false, error: 'not in this test' }, 404);
73
+ });
74
+ await page.goto(BASE + '/premium-initiative.html?id=self-serve-v2&ws=w1&board=w1&theme=' + theme);
75
+ await until(() => page.evaluate(() => document.querySelector('#cIniDoc')));
76
+ await page.locator('#dmList .dmo[data-doc="prd"]').click();
77
+ await until(() => page.evaluate(() => document.querySelector('#oMain .dsbody')));
78
+ return { ctx, page, S };
79
+ };
80
+ const txt = (p, q) => p.evaluate((s) => (document.querySelector(s) || {}).textContent || '', q);
81
+ const tab = async (p, k) => { await p.click(`#shT [data-sh="${k}"]`); await sleep(150); };
82
+
83
+ const A = await open(); const p = A.page;
84
+ ok('0 the sheet opens', !!(await p.evaluate(() => document.querySelector('#shT'))));
85
+ /* E1 tabs */
86
+ ok('E1 the sheet has Read, Edit, Proposals, Edit log and Health, with the open count on Proposals', await p.evaluate(() => [...document.querySelectorAll('#shT button')].map((b) => b.textContent.replace(/\s+/g, ' ').trim()).join('|') === 'Read|Edit|Proposals 1|Edit log|Health'));
87
+ ok('E1 the Read outline marks only a heading an open proposal names', await p.evaluate(() => { const b = [...document.querySelectorAll('.dso button')]; return b.length === 0 || b.every((x) => !x.querySelector('i') === !/Goal|Summary/.test(x.textContent)); }));
88
+ ok('E7 the footnote no longer says read-only', !/Read-only/.test(await txt(p, '#oMain .xn')) && /only when you press Save or Accept/.test(await txt(p, '#oMain .xn')));
89
+
90
+ /* E2 edit */
91
+ await tab(p, 'edit');
92
+ ok('E2 the Edit tab holds the file as text, Save is off, and the note says no changes', await p.evaluate((t) => document.querySelector('#dsEd').value === t && document.querySelector('#dsSave').disabled && /No changes yet/.test(document.querySelector('#dsNote').textContent), TEXT));
93
+ await p.fill('#dsEd', TEXT + '\nMore.\n');
94
+ ok('E2 a change turns Save on and the note says changed', await p.evaluate(() => !document.querySelector('#dsSave').disabled && /Changed/.test(document.querySelector('#dsNote').textContent)));
95
+ await p.click('#dsSave');
96
+ ok('E2 Save with no reason posts nothing and says why', await p.evaluate(() => /Say why the document changes/.test(document.querySelector('#dsErr').textContent)) && A.S.posts.length === 0);
97
+ ok('E2 the text typed is still there after the refusal', (await p.inputValue('#dsEd')) === TEXT + '\nMore.\n');
98
+ await tab(p, 'read'); await tab(p, 'edit');
99
+ ok('E2 the draft survives a tab switch', (await p.inputValue('#dsEd')) === TEXT + '\nMore.\n');
100
+ await p.fill('#dsWhy', 'add the missing line'); await p.click('#dsSave');
101
+ await until(() => A.S.posts.length);
102
+ const e1 = A.S.posts[0];
103
+ ok('E2 Save posts path, text and why to /api/doc-sheet/edit with the launch headers and the workspace', e1 && e1.route === 'edit' && Object.keys(e1.body).sort().join() === 'path,text,why' && e1.body.path === PATH && e1.body.why === 'add the missing line' && e1.body.text.endsWith('More.\n') && /ws=w1/.test(e1.query) && e1.headers.origin === BASE, JSON.stringify(e1 && { r: e1.route, q: e1.query }));
104
+ /* E5 after a write */
105
+ await until(() => p.evaluate(() => /No changes yet/.test((document.querySelector('#dsNote') || {}).textContent || '')));
106
+ ok('E5 after Save the text is read again from the route and the note says no changes', (await p.inputValue('#dsEd')).endsWith('More.\n') && await p.evaluate(() => document.querySelector('#dsSave').disabled));
107
+ await tab(p, 'log');
108
+ ok('E5 the Edit log shows the new revision with its reason', await until(() => p.evaluate(() => /v2 add the missing line/.test((document.querySelector('#oMain .evl') || {}).textContent || ''))));
109
+
110
+ /* E3 + E4 proposals */
111
+ await tab(p, 'props');
112
+ const pv = await until(() => p.evaluate(() => document.querySelector('.dsp') && { n: document.querySelectorAll('.dsp').length, t: document.querySelector('.dsp').textContent.replace(/\s+/g, ' '), acc: !!document.querySelector('[data-ds^="acc:"]'), rej: !!document.querySelector('[data-ds^="rej:"]'), stale: /Changed since this was proposed/.test(document.querySelector('.dsp').textContent), head: document.querySelector('#oMain .label:nth-of-type(2)') ? '' : '' }));
113
+ ok('E4 an open proposal names who, the request, the added text, and a stale section says so', pv && /The agent/.test(pv.t) && /add a one-paragraph summary/.test(pv.t) && /\+ Partners reach a first call/.test(pv.t) && pv.stale && pv.acc && pv.rej, JSON.stringify(pv));
114
+ ok('E4 the lists say how many are open and closed', await p.evaluate(() => /Open proposals · 1/.test(document.querySelector('#oMain').textContent) && !/Closed ·/.test(document.querySelector('#oMain').textContent)));
115
+ const nAcc = A.S.posts.length;
116
+ await p.click('[data-ds^="acc:"]');
117
+ await until(() => A.S.posts.length > nAcc);
118
+ const ac = A.S.posts[A.S.posts.length - 1];
119
+ ok('E4 Accept posts path, id, hash and only the sections still current', ac.route === 'accept' && Object.keys(ac.body).sort().join() === 'hash,id,path,sections' && ac.body.hash === 'ha' && ac.body.sections.join() === 'Summary', JSON.stringify(ac.body));
120
+ await until(() => p.evaluate(() => /Closed · 1/.test(document.querySelector('#oMain').textContent)));
121
+ ok('E5 after Accept the proposal is listed as closed and accepted, and none is open', await p.evaluate(() => /Open proposals · 0/.test(document.querySelector('#oMain').textContent) && /Accepted/.test(document.querySelector('.dsp.accepted').textContent) && /No open proposals/.test(document.querySelector('#oMain').textContent)));
122
+ ok('E5 the Proposals count is gone from the tab once none is open', await p.evaluate(() => document.querySelector('#shT [data-sh="props"]').textContent.trim() === 'Proposals'));
123
+ await A.ctx.close();
124
+
125
+ /* E4 stale-all, reject, ask */
126
+ {
127
+ const B = await open({ props: [prop({ sections: [{ name: 'Goal', kind: 'changed', before: 'x', after: 'y', current: 'z', stale: true }] }), prop({ id: 'prop-b', hash: 'hb', prompt: 'drop the code block', sections: [{ name: 'Requirements', kind: 'removed', before: 'R1', after: '', current: 'R1', stale: false }] })] });
128
+ const q = B.page; await tab(q, 'props');
129
+ ok('E4 a proposal whose every section is stale has no Accept and says so', await q.evaluate(() => { const d = [...document.querySelectorAll('.dsp')].find((x) => /add a one-paragraph summary/.test(x.textContent)); return d && !d.querySelector('[data-ds^="acc:"]') && !!d.querySelector('[data-ds^="rej:"]') && /cannot be accepted/.test(d.textContent); }));
130
+ ok('E4 a removed section says it removes', await q.evaluate(() => /Removes this section/.test(document.querySelector('#oMain').textContent)));
131
+ await q.click('[data-ds="rej:prop-b"]');
132
+ ok('E4 Reject asks for a reason first and posts nothing yet', await q.evaluate(() => !!document.querySelector('#dsRj')) && B.S.posts.length === 0);
133
+ await q.click('[data-ds="rejgo:prop-b"]');
134
+ ok('E4 Reject with no reason is refused with no post', await q.evaluate(() => /Say why you are rejecting it/.test(document.querySelector('#dsErr').textContent)) && B.S.posts.length === 0);
135
+ await q.fill('#dsRj', 'not needed'); await q.click('[data-ds="rejgo:prop-b"]'); await until(() => B.S.posts.length);
136
+ ok('E4 Reject posts path, id and why only', B.S.posts[0].route === 'reject' && Object.keys(B.S.posts[0].body).sort().join() === 'id,path,why' && B.S.posts[0].body.why === 'not needed');
137
+ await until(() => q.evaluate(() => /Closed · 1/.test(document.querySelector('#oMain').textContent)));
138
+ ok('E5 the rejected proposal is closed with its reason', await q.evaluate(() => /Rejected/.test(document.querySelector('.dsp.rejected').textContent) && /not needed/.test(document.querySelector('.dsp.rejected').textContent)));
139
+ /* ask */
140
+ await q.fill('#dsAsk', 'tighten the goal'); await q.click('[data-ds="ask"]'); await until(() => B.S.posts.length > 1);
141
+ const ak = B.S.posts[1];
142
+ ok('E3 Ask posts path and prompt to /api/doc-sheet/ask', ak.route === 'ask' && Object.keys(ak.body).sort().join() === 'path,prompt' && ak.body.prompt === 'tighten the goal' && /ws=w1/.test(ak.query));
143
+ ok('E3 while it works the tab says the agent can only read, and the button is off', await until(() => q.evaluate(() => /The agent is reading the document/.test(document.querySelector('#oMain').textContent) && document.querySelector('[data-ds="ask"]').disabled)));
144
+ ok('E3 the page polls the ask by id', await until(() => B.S.gets.some((g) => g.route === 'ask' && /id=ask-1/.test(g.query)), 8000));
145
+ B.S.ask = { ok: true, id: 'ask-1', state: 'failed', error: 'The run ended without an answer. Ask again.' };
146
+ ok('E3 a failed ask shows the route\'s own error', await until(() => q.evaluate(() => /The run ended without an answer/.test(document.querySelector('#oMain').textContent)), 8000));
147
+ ok('0 no page error', B.S.errors.length === 0, B.S.errors.join(' | '));
148
+ await B.ctx.close();
149
+ }
150
+ /* E5/E4 a refused accept shows the route's reason and reads again */
151
+ {
152
+ const C = await open({ post: (route) => (route === 'accept' ? { status: 409, body: { ok: false, error: 'stale: Summary changed since this proposal was made', reason: 'stale' } } : null) });
153
+ await tab(C.page, 'props'); await C.page.click('[data-ds^="acc:"]');
154
+ ok('E4 a refused Accept shows the route\'s reason and the proposal stays open', await until(() => C.page.evaluate(() => /stale: Summary changed since this proposal was made/.test((document.querySelector('#dsErr') || {}).textContent || '') && /Open proposals · 1/.test(document.querySelector('#oMain').textContent))));
155
+ await C.ctx.close();
156
+ }
157
+ /* the mockup's .dsed carries a toolbar above it (radius 0 0 14px 14px); this build leaves the toolbar out, so the box keeps the full 14px radius */
158
+ /* E8 fidelity: the page's rules for the new elements equal the mockup's last rule for each class */
159
+ const rule = (src, sel) => { const m = [...src.matchAll(new RegExp('(?:^|[}\\n])\\s*' + sel.replace(/[.#]/g, (c) => '\\' + c) + '\\{([^}]*)\\}', 'g'))].filter((x) => sel !== '.dsfoot' || /justify-content/.test(x[1])); return m.length ? m[m.length - 1][1].replace('border-radius:0 0 14px 14px', 'border-radius:14px').replace(/#6d3fd1/g, 'rgb(109,63,209)').replace(/\s+/g, '') : null; };
160
+ for (const sel of ['.dsed', '.dsy', '.dsfoot', '.dsdf', '#dsAsk']) {
161
+ const a = rule(MOCKUP, sel), b = rule(CSS, sel);
162
+ ok(`E8 ${sel} has the mockup's declarations`, a && b && b.replace(/;$/, '') === a.replace(/;$/, ''), JSON.stringify({ a, b }));
163
+ }
164
+ for (const [w, h, theme] of [[1280, 900, 'light'], [1280, 900, 'dark'], [390, 844, 'light'], [390, 844, 'dark']]) {
165
+ const R = await open({ w, h, theme });
166
+ for (const t of ['edit', 'props']) {
167
+ await tab(R.page, t);
168
+ const f = await R.page.evaluate(() => { const bad = []; for (const e of document.querySelectorAll('#oMain button,#oMain input:not([type=checkbox]),#oMain textarea')) { const r = e.getBoundingClientRect(); if (r.width && r.height && r.height < 32) bad.push(e.textContent.trim() || e.id); } return { sx: document.documentElement.scrollWidth - innerWidth, bad, out: [...document.querySelectorAll('#oMain textarea,#oMain .dsp,#oMain .dsask2')].filter((e) => e.getBoundingClientRect().right > innerWidth + 1).length }; });
169
+ ok(`E8 ${t} tab at ${w} px ${theme}: no sideways scroll, no tiny target, nothing past the edge`, f.sx <= 0 && f.bad.length === 0 && f.out === 0, JSON.stringify(f));
170
+ }
171
+ const cs = await R.page.evaluate(() => { const e = document.querySelector('#dsAsk'); const c = getComputedStyle(e); return { r: c.borderRadius, fs: c.fontSize }; });
172
+ ok(`E8 the ask box is 14px rounded, 15px type at ${w} px ${theme}`, cs.r === '14px' && cs.fs === '15px', JSON.stringify(cs));
173
+ await R.ctx.close();
174
+ }
175
+ finish();
176
+ })();
@@ -181,7 +181,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
181
181
  const nPost0 = A.posts.length;
182
182
  await p.locator('#dmList .dmo[data-doc="prd"]').click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && /Self-serve onboarding v2/.test(document.querySelector('#oMain').textContent) && document.querySelector('#oMain .dsbody'))); await sleep(500);
183
183
  const sh = await p.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, path: document.querySelector('#oMain .dpath').textContent, tabs: [...document.querySelectorAll('#shT button')].map((b) => b.textContent).join(','), fm: [...document.querySelectorAll('#oMain .kv2 span')].map((s) => s.textContent).join('|'), heads: [...document.querySelectorAll('#oMain h3.d2')].map((h) => h.textContent).join('|'), outline: [...document.querySelectorAll('#oMain .dso button')].map((b) => b.textContent).join('|'), pre: [...document.querySelectorAll('#oMain pre')].map((e) => e.textContent).join('|'), li: document.querySelectorAll('#oMain li').length }));
184
- ok('I8 Read shows the file\'s path, its front matter as a grid, its headings, list and code', sh.title === 'PRD' && sh.path === 'planning/prd/self-serve-v2-prd.md' && sh.tabs === 'Read,Edit log,Health' && /type\|PRD\|title\|Self-serve onboarding v2/.test(sh.fm) && sh.heads === 'PRD: Self-serve onboarding v2|Problem|Goal|Requirements' && sh.li === 2 && /R1 a first call/.test(sh.pre), JSON.stringify(sh));
184
+ ok('I8 Read shows the file\'s path, its front matter as a grid, its headings, list and code', sh.title === 'PRD' && sh.path === 'planning/prd/self-serve-v2-prd.md' && sh.tabs === 'Read,Edit,Proposals,Edit log,Health' && /type\|PRD\|title\|Self-serve onboarding v2/.test(sh.fm) && sh.heads === 'PRD: Self-serve onboarding v2|Problem|Goal|Requirements' && sh.li === 2 && /R1 a first call/.test(sh.pre), JSON.stringify(sh));
185
185
  ok('I8 Read asked for the log and the last revision, by GET, for this path', A.gets.some((g) => g.path === '/api/doc-sheet/log' && /path=planning%2Fprd%2Fself-serve-v2-prd.md/.test(g.query)) && A.gets.some((g) => g.path === '/api/doc-sheet/at' && /rev=2/.test(g.query)));
186
186
  await p.click('#shT [data-sh="log"]');
187
187
  const lg = await until(() => p.evaluate(() => document.querySelector('#oMain .hsr') && [...document.querySelectorAll('#oMain .hsr')].map((r) => r.textContent.replace(/\s+/g, ' ').trim())));
@@ -191,7 +191,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
191
191
  ok('I8 Health shows each check as passed, not passed or no input, and says no input is not counted', hl && /1 of 2 checks/.test(hl.note) && hl.rows.join() === 'ckr done:Passed,ckr blocked:Not passed,ckr skipped:No input', JSON.stringify(hl));
192
192
  ok('I8 the health check posts the path and the workspace only', A.posts.some((x) => x.path === '/api/doc-health/check' && Object.keys(x.body).sort().join() === 'path,ws' && x.body.ws === 'w1'));
193
193
  ok('I8 the sheet wrote nothing: no edit, propose, accept, reject, why, mark or ask post went out', !A.posts.slice(nPost0).some((x) => /doc-sheet/.test(x.path)) && !A.posts.some((x) => /^\/api\/doc-sheet\/(edit|propose|accept|reject|why|mark-current|ask)/.test(x.path)));
194
- ok('I8 the sheet says it is read-only', /Read-only/.test(await txt('#oMain .xn')));
194
+ ok('I8 the sheet says the file changes only on Save or Accept', /only when you press Save or Accept/.test(await txt('#oMain .xn')));
195
195
  A.setThread({ ok: true, working: false, turns: [] });
196
196
  await p.fill('#askIn', 'What is missing?'); const nA = A.posts.length; await p.press('#askIn', 'Enter');
197
197
  ok('I8 a question posts the document key and the text', await until(() => A.posts.length > nA && A.posts[A.posts.length - 1].path === '/api/briefing-premium/ask' && A.posts[A.posts.length - 1].body.key === 'doc:self-serve-v2:prd' && A.posts[A.posts.length - 1].body.text === 'What is missing?'));
@@ -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 };
@@ -160,6 +160,18 @@ The initiative page is at `/premium-initiative.html?id=<initiative>`. A click on
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
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.
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
- - **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 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 read-only agent sits beside it and starts from the file. The sheet writes nothing: editing, accepting a proposal, Issue and Drop are not built on this page.
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.
@@ -16,7 +16,7 @@ const crypto = require('crypto');
16
16
  const headless = require('./headless.js');
17
17
 
18
18
  const THREADS = 'briefing-premium-threads.jsonl';
19
- const KEY_RE = /^(decision|blocked|waited|src|ev|work|board|init|doc):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/;
19
+ const KEY_RE = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/;
20
20
  const MAX_Q = 2000, MAX_A = 6000, MAX_QUESTIONS = 40, PROMPT_TURNS = 8;
21
21
  const fail = (status, error) => ({ status, body: { ok: false, error } });
22
22
  const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s; };
@@ -49,7 +49,7 @@ function threadOf(runtimeDir, key, now = Date.now()) {
49
49
  /** The row as the server's own model has it, plus the files an answer should start from. null when the key names no row on the page. */
50
50
  function rowFor(model, key) {
51
51
  if (!model || !KEY_RE.test(String(key || ''))) return null;
52
- if (/^(work|board|init|doc):/.test(key)) { // a My work item, a Board initiative, an initiative page or one of its documents: the item's own record is the context
52
+ if (/^(work|board|init|doc|ins):/.test(key)) { // a My work item, a Board initiative, an Insights measure, an initiative page or one of its documents: the item's own record is the context
53
53
  const w = (model.rows || []).find((r) => r.key === key); if (!w) return null;
54
54
  const d = w.dialog || {};
55
55
  return { title: clip(w.title, 160), subject: clip(w.sub, 240), say: clip(d.say, 600), facts: (d.facts || []).slice(0, 12).map(([a, b]) => clip(a, 40) + ': ' + clip(b, 240)), files: (d.files || []).filter((f) => SAFE_PATH.test(f) && !f.includes('..')).slice(0, 4) };