create-pmos 0.261.0 → 0.263.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.261.0",
3
+ "version": "0.263.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@62b8a8e
1
+ kernel-source: pmos@3f8ffb3
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-18T07:07:07Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T08:08:29Z"}
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-18T07:07:07Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T08:08:29Z"}
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-18T07:07:07Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T08:08:29Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -94,7 +94,7 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
94
94
  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));
95
95
  /* I5 dashboards */
96
96
  const tabs = await p.evaluate(() => [...document.querySelectorAll('#dashTabs button')].map((b) => b.textContent + ':' + b.getAttribute('aria-pressed')));
97
- ok('I5 dashboards are the pillars the records name, all measures first', tabs.join() === 'All measures:true,Growth:false,Reliability:false', tabs.join());
97
+ ok('I5 dashboards: all measures first, then the saved ones (main marked), then the pillars the records name', tabs.join() === 'All measures:true,Weekly partner review · Main:false,Growth:false,Reliability:false', tabs.join());
98
98
  await p.click('#dashTabs [data-d="p:Reliability"]');
99
99
  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');
100
100
  await p.click('#dashTabs [data-d="all"]');
@@ -107,8 +107,8 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
107
107
  ok('I6 no sentence forecasts or gives a cause', !fd.some((x) => /forecast|will reach|because|caused|expected to/i.test(x)));
108
108
  /* I7 dialog */
109
109
  await p.locator('.nfd .nfr').first().click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(500);
110
- 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) }));
111
- 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));
110
+ 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, sw: [...document.querySelectorAll('#oMain [role=switch]')].map((b) => b.querySelector('b').textContent + ':' + b.getAttribute('aria-checked')).join(), inert: ['.rail', 'main.stage', '#dock'].every((s) => document.querySelector(s).inert) }));
111
+ ok('I7 a finding opens the standard dialog: the record\'s numbers, its readings with dates, its path, and only the dashboard switch as a 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 === 1 && dl.sw === 'Weekly partner review:true' && /Nothing here changes a record/.test(dl.hold) && dl.inert, JSON.stringify(dl));
112
112
  ok('I7 Escape closes it and focus returns', (await p.keyboard.press('Escape'), await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')))));
113
113
  await p.locator('#dashBody [data-open]').filter({ hasText: 'Details' }).first().click(); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(300);
114
114
  ok('I7 the Details link of a chart opens that chart\'s dialog', (await txt('#dTitle')) === 'Partner activation');
@@ -123,16 +123,16 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
123
123
  await R.ctx.close();
124
124
  }
125
125
  /* I8 reports */
126
- 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
+ const rp = await p.evaluate(() => ({ rows: [...document.querySelectorAll('#repDocs .dmr')].map((r) => r.querySelector('.dmn b').textContent + ' / ' + r.querySelector('.s').textContent), note: document.querySelector('#repBody .mhint').textContent, cap: document.querySelector('#repCap').textContent }));
127
127
  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));
128
- { 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
+ { const R = await open(); await R.page.locator('#repDocs .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(); }
129
129
  /* I9 labels */
130
130
  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')));
131
131
  ok('I9 the page makes no write request on its own', A.posts.length === 0, A.posts.join());
132
132
  /* I10 empty */
133
133
  {
134
134
  const R = await open({ model: mk({ outcomes: [] }) });
135
- 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
+ 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('#repDocs .dmr').length === 2 && document.querySelectorAll('#dashBody .mch').length === 0));
136
136
  await R.ctx.close();
137
137
  const R2 = await open({ model: mk({ reportsOk: false, reports: [], missing: ['reports'] }) });
138
138
  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)));
@@ -147,10 +147,68 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
147
147
  await c2.close();
148
148
  }
149
149
 
150
+ /* briefing-premium-reports: the dashboard store and the report presses (PRD D3 to D6, R2 to R4, R7) */
151
+ {
152
+ const R = await open(), q = R.page, sent = [];
153
+ let answer = (u, b) => ({ ok: true, dashboard: { id: b.id || 'pd-9' }, dashboards: [], drafted: { slot: '2026-10-23', path: 'planning/reports/release-readiness/2026-10-23.md' } });
154
+ await q.route(/\/api\/(premium-dashboards|report-setups)\//, (r) => { const u = new URL(r.request().url()).pathname, b = JSON.parse(r.request().postData() || '{}'); sent.push([u, b]); const a = answer(u, b); r.fulfill({ status: a.ok === false ? 409 : 200, contentType: 'application/json', body: JSON.stringify(a) }); });
155
+ const qt = (sel) => q.evaluate((x) => (document.querySelector(x) || {}).textContent || '', sel);
156
+ const last = () => sent[sent.length - 1] || [null, {}];
157
+ const dlgOn = () => until(() => q.evaluate(() => document.querySelector('#dlg').classList.contains('on')));
158
+ const shut = async () => { await q.keyboard.press('Escape'); await until(() => q.evaluate(() => !document.querySelector('#dlg').classList.contains('on'))); };
159
+ await q.click('#dashTabs [data-d="pd-1"]'); await sleep(200);
160
+ const sv = await q.evaluate(() => ({ tiles: [...document.querySelectorAll('#dashBody .mch .mlab')].map((e) => e.firstChild.textContent), gone: [...document.querySelectorAll('#dashBody .dplist .nempty')].map((e) => e.textContent.replace(/\s+/g, ' ')), bar: document.querySelector('#dashBar').textContent }));
161
+ ok('R1 a saved dashboard draws its charts in its order and says which chart is gone, in its place', sv.tiles.join() === 'Partner activation,Time to first call' && sv.gone.length === 1 && /krm-gone.*No KR metric record is called krm-gone/.test(sv.gone[0]) && /Main dashboard\..*Monday partner review/.test(sv.bar), JSON.stringify(sv));
162
+ await q.click('#pdEdit'); await dlgOn();
163
+ const ed = await q.evaluate(() => ({ n: document.querySelector('#pdN').value, rows: [...document.querySelectorAll('#pdList .pdrow b')].map((b) => b.textContent), main: document.querySelector('#pdMain').checked, note: document.querySelector('#oMain .addf .note').textContent }));
164
+ ok('R2 Edit opens the dialog with the name, Main and the charts in order, and says what Save changes', ed.n === 'Weekly partner review' && ed.rows.join() === 'Partner activation,Time to first call,krm-gone' && ed.main && /changes nothing else/.test(ed.note), JSON.stringify(ed));
165
+ await q.click('#pdList [data-mv="1:-1"]'); await q.click('#pdList [data-rm="2"]'); await q.selectOption('#pdAdd', 'krm-up'); await q.fill('#pdN', 'Monday review'); await q.click('#pdGo'); await sleep(400);
166
+ ok('R2 Save posts the dashboard with the new order, name and Main to the one save route', last()[0] === '/api/premium-dashboards/save' && JSON.stringify(last()[1]) === JSON.stringify({ ws: 'w1', board: 'w1', id: 'pd-1', name: 'Monday review', purpose: 'The measures the Monday partner review reads.', charts: ['krm-ttfc', 'krm-act', 'krm-up'], main: true }), JSON.stringify(last()));
167
+ await q.click('#pdNew'); await dlgOn(); await q.click('#pdGo'); await sleep(200);
168
+ ok('R2 a new dashboard without a name says so and posts nothing', /Give the dashboard a name/.test(await qt('#pdM')) && last()[1].id === 'pd-1');
169
+ answer = () => ({ ok: false, error: '“Weekly partner review” is already a dashboard on this board.' });
170
+ await q.fill('#pdN', 'Weekly partner review'); await q.fill('#pdP', 'x'); await q.click('#pdGo'); await sleep(300);
171
+ ok('R7 the server\'s refusal is shown in words and the dialog stays open', /already a dashboard on this board/.test(await qt('#pdM')) && await q.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !document.querySelector('#pdGo').disabled));
172
+ answer = (u, b) => ({ ok: true, dashboard: { id: b.id || 'pd-9' }, dashboards: [], setup: {}, drafted: { slot: '2026-10-23', path: 'planning/reports/release-readiness/2026-10-23.md' } });
173
+ await shut();
174
+ await q.click('#dashTabs [data-d="all"]'); await q.locator('#dashBody [data-open="ins:krm-up"]').click(); await dlgOn(); await q.click('#oMain [data-pdsw="pd-1"]'); await sleep(300);
175
+ ok('R3 the chart dialog\'s switch saves that dashboard with the chart added', last()[0] === '/api/premium-dashboards/save' && JSON.stringify(last()[1].charts) === JSON.stringify(['krm-act', 'krm-ttfc', 'krm-gone', 'krm-up']) && /Added to Weekly partner review/.test(await qt('#pdSwM')), JSON.stringify(last()));
176
+ await shut();
177
+ const groups = await q.evaluate(() => [...document.querySelectorAll('#repBody .ngrp > .label')].map((e) => e.textContent));
178
+ ok('R1 the Reports card lists your requests, what PMOS found, the set-up reports and the documents', groups.join() === 'Your requests · 2,Found in your work · 1,Set up · 1,Documents · 1 draft · 1 issued', groups.join());
179
+ await q.click('#repFound .dmo'); await dlgOn();
180
+ ok('R2 a finding opens with its proposal and what PMOS saw', /ScheduleWeekly, Thursdays 09:00/.test(await qt('#oMain .kv2')) && (await q.evaluate(() => document.querySelectorAll('#oMain .pdev li').length)) === 2);
181
+ const n0 = sent.length;
182
+ await q.click('#oMain [data-rx="no"]'); await sleep(300);
183
+ ok('R2 Not a report hides the row and waits; Undo sends nothing', (await q.evaluate(() => !document.querySelector('#repFound'))) && sent.length === n0 && (await q.click('#rxUndo'), await sleep(5400), sent.length === n0) && await q.evaluate(() => !!document.querySelector('#repFound')));
184
+ await q.click('#oMain [data-rx="no"]'); await sleep(5600);
185
+ ok('R2 without Undo, Not a report is sent after 5 seconds', last()[0] === '/api/report-setups/dismiss' && last()[1].finding === 'f-1' && last()[1].ws === 'w1', JSON.stringify(last()));
186
+ await until(() => q.evaluate(() => !document.querySelector('#dlg').classList.contains('on') || true)); if (await q.evaluate(() => document.querySelector('#dlg').classList.contains('on'))) await shut();
187
+ await q.click('#repFound .dmo'); await dlgOn(); await q.click('#oMain [data-rx="set"]'); await sleep(400);
188
+ ok('R2 Set it up posts the finding and says where the first draft is', last()[0] === '/api/report-setups/setup' && last()[1].finding === 'f-1' && /first draft is planning\/reports\/release-readiness\/2026-10-23\.md/.test(await qt('#toast')), JSON.stringify(last()));
189
+ await q.fill('#repAskIn', 'A weekly risk note'); await q.click('#repAskGo'); await sleep(300);
190
+ ok('R3 the Ask box posts the request and says it only proposes', last()[0] === '/api/report-setups/ask' && last()[1].text === 'A weekly risk note' && /Nothing is set up yet/.test(await qt('#toast')) && /only proposes/.test(await qt('#repBody .nask-n')), JSON.stringify(last()));
191
+ await q.click('#repAsks [data-ask="a-1"]'); await dlgOn(); await q.click('#oMain [data-rx="chg"]'); await sleep(100);
192
+ ok('R3 Change it needs words first', /Say what to change/.test(await qt('#rxM')));
193
+ await q.fill('#rxChg', 'quarterly'); await q.click('#oMain [data-rx="chg"]'); await sleep(300);
194
+ ok('R3 Change it posts the correction for that request', last()[0] === '/api/report-setups/change' && last()[1].id === 'a-1' && last()[1].text === 'quarterly', JSON.stringify(last()));
195
+ await q.click('#repAsks [data-ask="a-2"]'); await dlgOn();
196
+ ok('R3 a running request says it is working and offers only Cancel', /background run is working/.test(await qt('#oMain')) && (await q.evaluate(() => [...document.querySelectorAll('#oMain [data-rx]')].map((b) => b.dataset.rx).join())) === 'cancel');
197
+ await shut();
198
+ await q.click('#repSetups .dmo'); await dlgOn();
199
+ const su = await q.evaluate(() => ({ kv: document.querySelector('#oMain .kv2').textContent, acts: [...document.querySelectorAll('#oMain [data-rx]')].map((b) => b.dataset.rx).join() }));
200
+ ok('R4 a set-up report shows its schedule and next draft, with Draft it now and Pause', /ScheduleEvery other Monday at 09:00/.test(su.kv) && /Next draft26 Oct/.test(su.kv) && su.acts === 'draft,pause', JSON.stringify(su));
201
+ await q.click('#oMain [data-rx="pause"]'); await sleep(300);
202
+ ok('R4 Pause posts that report', last()[0] === '/api/report-setups/pause' && last()[1].id === 'partner-update', JSON.stringify(last()));
203
+ ok('R7 every press went to the dashboard save route or an existing report-setups route', R.posts.every((x) => /^POST \/api\/(premium-dashboards\/save|report-setups\/(ask|change|cancel|setup|dismiss|pause|resume|draft))$/.test(x)), R.posts.join());
204
+ ok('R6 the Reports card shows no demo row', !/demo/i.test(await qt('#repBody')));
205
+ await R.ctx.close();
206
+ }
207
+
150
208
  /* I11 floors */
151
209
  for (const theme of ['light', 'dark']) {
152
210
  const R = await open({ w: 390, h: 844, theme }), q = R.page;
153
- 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 }; });
211
+ const m = await q.evaluate(() => { const small = [...document.querySelectorAll('#dashTabs button, #dashBar button, #dashBody .lk, #dashBody .nfr, #repBody .dmo, #repBody .lk, #repBody input, #repAskGo, #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 }; });
154
212
  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));
155
213
  await q.locator('#dashBody .nfr').first().click(); await until(() => q.evaluate(() => document.querySelector('#dlg').classList.contains('on'))); await sleep(900);
156
214
  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 }; });
@@ -193,6 +251,17 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
193
251
  pg.on('pageerror', (e) => errs.push(String(e)));
194
252
  await pg.goto(base2 + '/premium-insights.html');
195
253
  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(' | '));
254
+ /* briefing-premium-reports against the real server: New dashboard, Save, the switch, then the ledger answers it back */
255
+ await pg.click('#pdNew'); await until(() => pg.evaluate(() => document.querySelector('#dlg').classList.contains('on')));
256
+ await pg.fill('#pdN', 'Partner review'); await pg.fill('#pdP', 'The Monday partner review.'); await pg.selectOption('#pdAdd', m.charts[0].id); await pg.check('#pdMain'); await pg.click('#pdGo');
257
+ ok('E8 a dashboard made on the real page is saved and drawn as the main one', await until(() => pg.evaluate(() => !document.querySelector('#dlg').classList.contains('on') && [...document.querySelectorAll('#dashTabs button')].some((b) => b.textContent === 'Partner review · Main' && b.getAttribute('aria-pressed') === 'true') && document.querySelectorAll('#dashBody .mch').length === 1), 10000), await pg.evaluate(() => (document.querySelector('#pdM') || {}).textContent + ' / ' + [...document.querySelectorAll('#dashTabs button')].map((b) => b.textContent).join()));
258
+ const j2 = await (await fetch(base2 + '/api/insights-premium')).json(), d2 = j2.model.dashboards.find((d) => d.saved);
259
+ ok('E8 the model reads it back from the ledger', !!d2 && d2.name === 'Partner review' && d2.main && d2.charts.join() === m.charts[0].id, JSON.stringify(d2));
260
+ const H = await T.pressHeaders(base2), body = JSON.stringify({ ws: m.board.ws, board: m.board.id, name: 'From an agent', purpose: 'x', charts: [] });
261
+ const asAgent = await fetch(base2 + '/api/premium-dashboards/save', { method: 'POST', headers: { ...H, 'x-pmos-session': 's1' }, body }).then((x) => x.status);
262
+ const noNonce = await fetch(base2 + '/api/premium-dashboards/save', { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: base2 }, body }).then((x) => x.status);
263
+ const unknown = await fetch(base2 + '/api/premium-dashboards/save', { method: 'POST', headers: H, body: JSON.stringify({ ws: m.board.ws, board: m.board.id, name: 'Other', purpose: 'x', charts: ['krm-none'] }) }).then((x) => x.status);
264
+ ok('E9 the real save route refuses an agent session (403), a press without the nonce (403) and a chart no record holds (400)', asAgent === 403 && noNonce === 403 && unknown === 400, [asAgent, noNonce, unknown].join());
196
265
  await ctx.close();
197
266
  }
198
267
 
@@ -78,6 +78,23 @@ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'br
78
78
  ok('R1 the console stays the default page', /id="c3-root"/.test(def) && !/class="rail/.test(def));
79
79
  { const tc = await p.evaluate(() => { const a = document.querySelector('#toConsole'); if (!a) return null; const r = a.getBoundingClientRect(); return { href: a.getAttribute('href'), label: a.getAttribute('aria-label'), w: Math.round(r.width), h: Math.round(r.height), tab: a.tabIndex }; }); ok('R1 the header links to the console (premium-console-link)', tc && tc.href === '/c3.html' && tc.label === 'Open the console' && tc.w >= 44 && tc.h >= 44 && tc.tab === 0, JSON.stringify(tc)); }
80
80
 
81
+ /* premium-settings: the dialog holds Workspaces and Connectors only; each press goes to its existing route */
82
+ { const bt = await p.evaluate(() => { const b = document.querySelector('#settingsBtn'); if (!b) return null; const r = b.getBoundingClientRect(); return { label: b.getAttribute('aria-label'), w: Math.round(r.width), h: Math.round(r.height) }; });
83
+ ok('S1 the header has a Settings button of at least 44 px', bt && bt.label === 'Settings' && bt.w >= 44 && bt.h >= 44, JSON.stringify(bt));
84
+ await p.click('#settingsBtn');
85
+ const drawn = await until(() => p.evaluate(() => document.querySelectorAll('#oMain .sr').length > 0), 8000);
86
+ const labs = await p.evaluate(() => [...document.querySelectorAll('#oMain .label')].map((x) => x.textContent));
87
+ ok('S2 the dialog has exactly two sections, Workspaces and Connectors', drawn && labs.join() === 'Workspaces,Connectors', labs.join());
88
+ const sw = await p.evaluate(() => { const b = document.querySelector('#oMain [data-src="mail"]'); return b ? b.getAttribute('aria-checked') : null; });
89
+ await p.click('#oMain [data-src="mail"]');
90
+ const flipped = await until(() => p.evaluate((v) => document.querySelector('#oMain [data-src="mail"]').getAttribute('aria-checked') !== v, sw), 6000);
91
+ ok('S3 a source switch saves through /api/proactive/settings and flips', flipped && A.reqs.includes('POST /api/proactive/settings'));
92
+ await p.click('#oMain [data-src="mail"]'); await until(() => p.evaluate((v) => document.querySelector('#oMain [data-src="mail"]').getAttribute('aria-checked') === v, sw), 6000);
93
+ const bare = await fetch(BASE + '/api/workspaces/forget', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: 'no-such' }) });
94
+ ok('S4 Remove is a page press: no nonce, no removal (403)', bare.status === 403, String(bare.status));
95
+ for (let i = A.reqs.length - 1; i >= 0; i--) if (/^POST \/api\/proactive\/settings$/.test(A.reqs[i])) A.reqs.splice(i, 1); // R10 below counts presses on a page where nothing was pressed
96
+ await p.keyboard.press('Escape'); }
97
+
81
98
  /* R2 */
82
99
  const hero = await p.evaluate(() => ({ text: document.querySelector('#brief').textContent, k: [...document.querySelectorAll('#brief .k')].map((x) => x.textContent) }));
83
100
  const want = MODEL.hero.map((s) => s.parts.map((x) => x.t).join('')).join(' ');
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
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
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. */
4
+ * The Activation series has a month with no reading in it, so the page must draw a gap and not a zero. The saved dashboard holds a chart id no record has. */
5
5
  const NOW = new Date(2026, 9, 18, 9, 0).getTime();
6
6
  const rd = (at, v) => ({ at, v });
7
7
  const OUTCOMES = [
@@ -20,11 +20,27 @@ const REPORTS = [
20
20
  { cadence: 'biweekly', slot: '2026-10-14', path: 'planning/reports/biweekly/2026-10-14.md', status: 'draft', bytes: 900, edited: false, issued: null },
21
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
22
  ];
23
+ // briefing-premium-reports: one saved dashboard (main) on the board, and the GET /api/report-setups answer with one setup, one finding and two asks.
24
+ const SAVED = [
25
+ { id: 'pd-1', board: 'w1', name: 'Weekly partner review', purpose: 'The measures the Monday partner review reads.', charts: ['krm-act', 'krm-ttfc', 'krm-gone'], main: true, at: '2026-10-17T09:00:00.000Z' },
26
+ ];
27
+ const SETUPS = {
28
+ setups: [{ id: 'partner-update', name: 'Partner update', purpose: 'What moved for partners this fortnight.', audience: 'Leadership', source: 'work', output: 'docx',
29
+ schedule: { cadence: 'bi-weekly', day: 'Mon', time: '09:00' }, label: 'Every other Monday at 09:00', next_draft: '2026-10-26T09:00:00.000Z', last_issued: '2026-10-14', status: 'active', cycles: 3,
30
+ copy: { kind: 'none', state: 'none', url: null }, structure: null, draft: null }],
31
+ findings: [{ id: 'f-1', name: 'Release readiness', why: 'You review the release measures before every release meeting.', evidence: [{ kind: 'calendar', text: 'Release review, 3 times in 6 weeks' }, { kind: 'drive', text: 'Release checklist doc' }],
32
+ confidence: 'likely', proposal: { name: 'Release readiness', purpose: 'Whether the measures are safe for the release.', audience: 'Leadership', source: 'work', output: 'pdf', schedule: { cadence: 'weekly', day: 'Thu', time: '09:00' } } }],
33
+ asks: [{ id: 'a-1', text: 'A monthly churn report for finance', state: 'ready', changed: false, error: null,
34
+ proposal: { name: 'Churn for finance', purpose: 'Monthly churn for the finance review.', audience: 'Finance', source: 'work', output: 'xlsx', schedule: { cadence: 'monthly', dayOfMonth: 1, time: '09:00' } } },
35
+ { id: 'a-2', text: 'A weekly uptime note', state: 'running', changed: false, error: null, proposal: null }],
36
+ finder: { cadence: 'weekly', sources: {}, last_run: null, next_run: null },
37
+ };
23
38
  function facts(o = {}) {
24
39
  return {
25
40
  now: NOW, pending: false, missing: [],
26
41
  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,
42
+ outcomes: OUTCOMES.map((x) => ({ ...x, readings: x.readings.map((r) => ({ ...r })) })), reports: REPORTS.map((r) => ({ ...r })), reportsOk: true,
43
+ saved: JSON.parse(JSON.stringify(SAVED)), setups: JSON.parse(JSON.stringify(SETUPS)), ...o,
28
44
  };
29
45
  }
30
- module.exports = { NOW, facts, OUTCOMES, REPORTS };
46
+ module.exports = { NOW, facts, OUTCOMES, REPORTS, SAVED, SETUPS };
@@ -13,6 +13,8 @@ A rail on the left names four places: Briefing, My work, Board and Insights. Eac
13
13
 
14
14
  Every premium page has an **Open the console** button beside the theme button. It opens the console at `/c3.html`, for the places premium does not have yet (agent sessions, Calendar, Settings). In the console, the More menu has **Open premium**, which opens this page.
15
15
 
16
+ Every premium page has a **Settings** button beside it. It opens one dialog with two sections. **Workspaces** lists the repositories PMOS works in, with Add (a folder path) and Remove; Remove forgets the address and never deletes the folder, and a refusal shows the server's reason. **Connectors** has an On/Off switch for each source the Briefing reads. Each press saves that one record. Every other setting runs on a default and stays in the console; the dialog links to it. Remove needs the page's launch nonce, so an agent session cannot call it.
17
+
16
18
  ## Products
17
19
 
18
20
  You work across products, and a conversation in email, the calendar or Confluence cannot be tied to one product. So the Briefing reads more than one workspace and merges what needs you into one list.
@@ -169,12 +171,16 @@ Not drawn, because PMOS holds no record for them: the mockup's demo tasks, its J
169
171
 
170
172
  ## Insights
171
173
 
172
- 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.
174
+ Insights is the fourth place on the rail, at `/premium-insights.html`. It reads the KR metric records of the board's workspace, your saved dashboards, and the report files and report setups the console's Reports tab lists. It writes only when you press a button: a dashboard goes to the workspace's state folder (`premium-dashboards.jsonl`), and a report press goes to the report ledger through the console's own report routes. An agent session cannot make either write.
173
175
 
174
176
  - **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.
175
- - **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.
177
+ - **Dashboards.** The switch lists All measures first, then your saved dashboards (the main one first, marked Main), then the pillars the metrics name. A saved dashboard draws its charts in the order you saved them. A chart whose record is gone, or that has fewer than two readings, is listed in its place with the reason and is not drawn.
178
+ - **Make or edit a dashboard.** Press **New dashboard**, or **Edit** on a saved one. Give it a name, say what it is for, choose its measures and their order, and decide whether it is the main dashboard. **Save** records it. **Remove the dashboard** asks once more and then removes it. The dialog says when a dashboard holds more than six charts, and it still saves. In a chart's dialog, **On your dashboards** has a switch for each saved dashboard, which adds the chart to it or takes it off.
176
179
  - **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.
177
180
  - **No series recorded.** A KR metric with one reading or none is listed with the reason and is not drawn.
178
- - **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.
181
+ - **Ask PMOS to set up a report.** Type what the report is for and press **Ask**. A background run proposes a report and does nothing else. The request is listed as Working, then Ready to review. A ready request opens with its proposal: **Set it up**, **Change it** (say what to change; the run revises it), or **Cancel**.
182
+ - **Found in your work.** Up to three reports PMOS found in your calendar, mail or documents, each with why and what it saw. **Set it up** records the report and drafts its first cycle as a file. **Not a report** hides it and records it after 5 seconds, unless you press **Undo**.
183
+ - **Set up.** Your recurring reports, with their schedule and next draft. A report opens with **Draft it now** (for a report drawn from your work) and **Pause** or **Resume**.
184
+ - **Documents.** 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.
179
185
 
180
- 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.
186
+ Not built: the Insight Studio (making a chart or a report by conversation), the report deck, present and print, tile sizes and free layout, the finder's settings, run-based charts such as corrections per 100 runs (they belong to the Board's Metrics card), and any measure no record holds. The console's own dashboards are separate and unchanged. KR metric records belong to a workspace, so every board of a workspace shows the same charts.
@@ -2,13 +2,15 @@
2
2
  /* lib/insights-premium.js — the premium Insights page's model, built from the KR metric records and the report files the console's Reports tab reads
3
3
  * (initiative briefing-premium-insights).
4
4
  *
5
- * build(facts) → model PURE. facts = { now, board, boards, outcomes, reports, reportsOk, missing[] }
5
+ * build(facts) → model PURE. facts = { now, board, boards, outcomes, reports, reportsOk, missing[], saved, setups }
6
6
  * peekModel() → the last model built, for the agent to find a chart in (null before the first)
7
7
  *
8
8
  * facts come from the routes of lib/routes-c3-strategy.js and lib/routes-reports.js:
9
9
  * board { ws, id, name } the board the page shows (KR metric records belong to its workspace, PRD D2)
10
10
  * outcomes GET /api/c3-strategy → .outcomes [{ id, name, pillar, unit, start (the baseline), target, by, now, expected, shortfall, status, pivot, reason, readings: [{ at, v }] }]
11
11
  * reports GET /api/report → .reports [{ cadence, slot, path, status, issued: { at, by } | null, edited }]
12
+ * saved lib/premium-dashboards.js list(root, board.id) → [{ id, name, purpose, charts: [KR metric id], main, at }] (briefing-premium-reports D1)
13
+ * setups GET /api/report-setups → { setups, findings, asks } | null when it could not be read (briefing-premium-reports R1)
12
14
  *
13
15
  * THE RULE THE FILE FOLLOWS (as the other premium models): a number, chip, line or date is made only from a field of a record. A measure with fewer than two
14
16
  * readings gets no chart and says why. The time between two readings is drawn as the time it is, so a gap in a series shows as a gap and never as a zero. No
@@ -99,6 +101,56 @@ function reportRows(reports) {
99
101
  });
100
102
  }
101
103
 
104
+ /** The board's saved dashboards (briefing-premium-reports D3/D5), main first as the ledger folds them. A chart id that has no record, or no series, stays
105
+ * in `charts` and is listed in `gone` with the reason, so the page can say so in its place. `checks` are the two advisory checks, never a refusal. */
106
+ function savedOf(saved, outcomes, charts) {
107
+ return (saved || []).map((d) => {
108
+ const ids = Array.isArray(d.charts) ? d.charts : [];
109
+ const L = ids.map((id) => charts.find((c) => c.id === id)).filter(Boolean);
110
+ const gone = ids.filter((id) => !charts.some((c) => c.id === id)).map((id) => {
111
+ const o = outcomes.find((x) => x.id === id);
112
+ return { id, title: o ? clip(o.name, 120) : id, why: o ? 'This measure has fewer than two readings, so it has no chart.' : 'No KR metric record is called ' + id + ' any more.' };
113
+ });
114
+ const checks = [];
115
+ if (ids.length > 6) checks.push('This dashboard holds ' + ids.length + ' charts. A dashboard that serves one routine usually holds six or fewer.');
116
+ if (new Set(ids).size !== ids.length) checks.push('The same measure is on this dashboard twice.');
117
+ const off = L.filter((c) => c.off).length;
118
+ return { id: d.id, name: clip(d.name, 60), purpose: clip(d.purpose, 200), saved: true, main: !!d.main, charts: ids.slice(), keys: L.map((c) => c.key), total: L.length, off,
119
+ chip: !L.length ? '' : off ? off + ' off its line' : 'On their lines', gone, checks, at: d.at || null };
120
+ });
121
+ }
122
+
123
+ /** The Reports card's setups, findings and asks from GET /api/report-setups (briefing-premium-reports R1–R4). Each field is the ledger's; an absent one is left out. */
124
+ function setupsOf(su, now) {
125
+ if (!su) return { setupsOk: false, setups: [], found: [], asks: [] };
126
+ const setups = (su.setups || []).map((s) => ({
127
+ id: s.id, name: clip(s.name, 120), purpose: clip(s.purpose, 240), audience: s.audience || '', source: s.source || '', output: s.output || '', label: s.label || '',
128
+ next: s.next_draft ? shortDate(s.next_draft) : '', lastIssued: s.last_issued ? shortDate(s.last_issued) : '', status: s.status || '', cycles: fin(s.cycles) ? s.cycles : 0,
129
+ paused: s.status === 'paused', fromWork: s.source === 'work', structured: !!(s.structure && s.structure.saved), drafting: !!(s.draft && s.draft.state === 'drafting'),
130
+ }));
131
+ const found = (su.findings || []).slice(0, 3).map((x) => ({
132
+ id: x.id, name: clip(x.name, 120), why: clip(x.why, 240), evidence: (x.evidence || []).map((e) => ({ kind: e.kind || '', text: clip(e.text, 240) })),
133
+ confidence: x.confidence === 'likely' ? 'Likely a report' : x.confidence === 'not-sure' ? 'Not sure' : '', proposal: proposalOf(x.proposal),
134
+ }));
135
+ const asks = (su.asks || []).filter((a) => a.state === 'running' || a.state === 'ready' || a.state === 'failed').map((a) => ({
136
+ id: a.id, text: clip(a.text, 240), state: a.state, changed: !!a.changed, error: a.error ? clip(a.error, 240) : '', proposal: proposalOf(a.proposal),
137
+ }));
138
+ return { setupsOk: true, setups, found, asks, findingsMore: Math.max(0, (su.findings || []).length - 3) };
139
+ }
140
+ function proposalOf(p) {
141
+ if (!p || typeof p !== 'object') return null;
142
+ const sc = p.schedule && typeof p.schedule === 'object' ? p.schedule : null;
143
+ const rows = [
144
+ p.name ? ['Name', clip(p.name, 120)] : null,
145
+ p.purpose ? ['Purpose', clip(p.purpose, 240)] : null,
146
+ p.audience ? ['Audience', clip(p.audience, 120)] : null,
147
+ sc && sc.cadence ? ['Schedule', require('./report-setups.js').scheduleLabel(sc)] : null,
148
+ p.source ? ['Source', p.source === 'work' ? 'Your work' : String(p.source)] : null,
149
+ p.output ? ['Output', String(p.output)] : null,
150
+ ].filter(Boolean);
151
+ return { name: p.name ? clip(p.name, 120) : '', rows };
152
+ }
153
+
102
154
  function build(facts) {
103
155
  const f = facts || {};
104
156
  const outcomes = f.outcomes || [], missing = (f.missing || []).slice();
@@ -110,7 +162,7 @@ function build(facts) {
110
162
  const pillars = [...new Set(charts.map((c) => c.pillar).filter(Boolean))];
111
163
  const offOf = (L) => L.filter((c) => c.off).length;
112
164
  const dash = (id, name, L) => ({ id, name, keys: L.map((c) => c.key), total: L.length, off: offOf(L), chip: !L.length ? '' : offOf(L) ? offOf(L) + ' off its line' : 'On their lines' });
113
- const dashboards = [dash('all', 'All measures', charts)].concat(pillars.length > 1 ? pillars.map((p) => dash('p:' + p, p, charts.filter((c) => c.pillar === p))) : []);
165
+ const dashboards = [dash('all', 'All measures', charts)].concat(savedOf(f.saved, outcomes, charts), pillars.length > 1 ? pillars.map((p) => dash('p:' + p, p, charts.filter((c) => c.pillar === p))) : []);
114
166
  const findings = findingsOf(charts);
115
167
  const rep = reportRows(f.reports);
116
168
  const off = offOf(charts);
@@ -121,7 +173,8 @@ function build(facts) {
121
173
  charts, noSeries, dashboards, rows: charts,
122
174
  findings: findings.length ? findings : [{ kind: 'calm', key: null, text: charts.length ? (charts.some((c) => c.target !== null) ? 'Nothing stands out. No measure moved much, and none is far behind its line.' : 'Nothing stands out. No measure here has a target, so the series can only be described.') : '' }],
123
175
  calm: !findings.length && charts.length > 0,
124
- reports: { rows: rep, ok: f.reportsOk !== false, counts: { draft: rep.filter((r) => r.state === 'draft').length, issued: rep.filter((r) => r.state === 'issued').length }, missing: f.reportsOk === false },
176
+ reports: Object.assign({ rows: rep, ok: f.reportsOk !== false, counts: { draft: rep.filter((r) => r.state === 'draft').length, issued: rep.filter((r) => r.state === 'issued').length }, missing: f.reportsOk === false }, setupsOf(f.setups, f.now)),
177
+ measures: outcomes.map((o) => ({ id: o.id, title: clip(o.name, 120), pillar: o.pillar || '', charted: charts.some((c) => c.id === o.id) })),
125
178
  empty: !outcomes.length ? 'No KR metric is recorded for this workspace, so there is nothing to chart. Add one where the KR metrics are kept.' : !charts.length ? 'No KR metric holds two readings yet, so nothing is drawn.' : '',
126
179
  dock: { needs: off, label: off === 1 ? 'measure off its line' : 'measures off their line', next: findings[0] && findings[0].chart ? (charts.find((c) => c.key === findings[0].chart) || {}).title || null : null },
127
180
  counts: { charts: charts.length, noSeries: noSeries.length, off, total: outcomes.length },
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+ /* premium-dashboards.js — the dashboards the PM makes on the premium Insights page (initiative briefing-premium-reports, PRD D1 and D2).
3
+ * THE ONE WRITER and THE ONE FOLD of <state>/premium-dashboards.jsonl.
4
+ *
5
+ * NAME_MAX · PURPOSE_MAX · CHARTS_MAX · ADVISED_MAX
6
+ * ledgerFile(root) · readLines(file)
7
+ * check(input) → { ok: true, value } | { ok: false, status, error } PURE: the shape only
8
+ * fold(lines) → { [board]: [{ id, board, name, purpose, charts, main, at }] } PURE
9
+ * list(root, board) → the dashboards of one board, the main one first, then in the order they were made
10
+ * save(root, input, actor, { now, known }) → { ok: true, dashboard, dashboards } | { ok: false, status, error }
11
+ *
12
+ * THE LEDGER. Lines { v: 1, ev: save | remove, id, board, name, purpose, charts, main, actor, at }. `board` is the board's id in the workspace whose
13
+ * state folder holds the file. `charts` is an ordered list of KR metric ids. The fold keeps the last save of each id and drops an id once it is removed.
14
+ * One dashboard per board is main: the latest save that says main wins, and the others read as not main. The file is never rewritten. A torn line, or one
15
+ * without an id and a board, is skipped. This store is the premium page's own: the console's dashboard layouts (lib/report-dashboards.js) are not touched.
16
+ */
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ const LEDGER = 'premium-dashboards.jsonl';
21
+ const NAME_MAX = 60;
22
+ const PURPOSE_MAX = 200;
23
+ const CHARTS_MAX = 24; // a hard limit on what one save may hold
24
+ const ADVISED_MAX = 6; // the Studio's check: a dashboard serves one routine and holds six charts or fewer (said, never enforced)
25
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/;
26
+
27
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
28
+ const refuse = (status, error) => ({ ok: false, status, error });
29
+ const tidy = (v) => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : '');
30
+ const norm = (t) => tidy(t).toLowerCase();
31
+
32
+ function ledgerFile(root) {
33
+ const abs = path.resolve(String(root));
34
+ return path.join(abs, require('./report-draft.js').stateRel(abs), LEDGER);
35
+ }
36
+ function readLines(file) {
37
+ let text = '';
38
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
39
+ const out = [];
40
+ for (const raw of text.split('\n')) {
41
+ if (!raw.trim()) continue;
42
+ try { const l = JSON.parse(raw); if (isObj(l) && (l.ev === 'save' || l.ev === 'remove') && typeof l.id === 'string' && typeof l.board === 'string') out.push(l); } catch { /* a torn line is skipped */ }
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** Check the fields of a save or a remove. Whether the board and the charts exist is the route's check (it passes `known`). */
48
+ function check(input) {
49
+ const i = isObj(input) ? input : {};
50
+ const board = typeof i.board === 'string' ? i.board : '';
51
+ if (!ID_RE.test(board)) return refuse(400, 'Name the board the dashboard belongs to.');
52
+ const id = i.id == null || i.id === '' ? null : i.id;
53
+ if (id !== null && (typeof id !== 'string' || !ID_RE.test(id))) return refuse(400, 'That dashboard id is not valid.');
54
+ if (i.remove === true) {
55
+ if (id === null) return refuse(400, 'Say which dashboard to remove.');
56
+ return { ok: true, value: { remove: true, id, board } };
57
+ }
58
+ const name = tidy(i.name);
59
+ if (!name) return refuse(400, 'Give the dashboard a name.');
60
+ if (name.length > NAME_MAX) return refuse(400, `The name can be at most ${NAME_MAX} characters.`);
61
+ const purpose = tidy(i.purpose);
62
+ if (!purpose) return refuse(400, 'Say what the dashboard is for, in one line.');
63
+ if (purpose.length > PURPOSE_MAX) return refuse(400, `The purpose can be at most ${PURPOSE_MAX} characters.`);
64
+ if (!Array.isArray(i.charts)) return refuse(400, 'charts must be a list of KR metric ids.');
65
+ if (i.charts.length > CHARTS_MAX) return refuse(400, `A dashboard can hold at most ${CHARTS_MAX} charts.`);
66
+ const charts = [];
67
+ for (const c of i.charts) {
68
+ if (typeof c !== 'string' || !ID_RE.test(c)) return refuse(400, 'Each chart must be a KR metric id.');
69
+ if (!charts.includes(c)) charts.push(c);
70
+ }
71
+ return { ok: true, value: { remove: false, id, board, name, purpose, charts, main: i.main === true } };
72
+ }
73
+
74
+ /** Every board's dashboards after the ledger's lines, in order. PURE. The main one of a board is the last one saved with main; a later save of that
75
+ * same dashboard without main, or its removal, leaves the board with none. */
76
+ function fold(lines) {
77
+ const byId = new Map(); // id → dashboard; `first` keeps the order they were first made
78
+ const mainOf = new Map(); // board → id
79
+ let made = 0;
80
+ for (const l of lines || []) {
81
+ const prev = byId.get(l.id);
82
+ if (prev && prev.board !== l.board) continue; // an id never moves between boards
83
+ if (l.ev === 'remove') { byId.delete(l.id); if (mainOf.get(l.board) === l.id) mainOf.delete(l.board); continue; }
84
+ byId.set(l.id, { id: l.id, board: l.board, name: tidy(l.name), purpose: tidy(l.purpose), charts: Array.isArray(l.charts) ? l.charts.filter((c) => typeof c === 'string') : [], at: l.at || null, first: prev ? prev.first : made++ });
85
+ if (l.main === true) mainOf.set(l.board, l.id); else if (mainOf.get(l.board) === l.id) mainOf.delete(l.board);
86
+ }
87
+ const out = {};
88
+ for (const d of byId.values()) (out[d.board] = out[d.board] || []).push(d);
89
+ for (const b of Object.keys(out)) {
90
+ out[b] = out[b].map((d) => Object.assign(d, { main: mainOf.get(b) === d.id }))
91
+ .sort((a, z) => (z.main - a.main) || (a.first - z.first))
92
+ .map(({ id, board, name, purpose, charts, main, at }) => ({ id, board, name, purpose, charts, main, at }));
93
+ }
94
+ return out;
95
+ }
96
+
97
+ const list = (root, board) => fold(readLines(ledgerFile(root)))[board] || [];
98
+
99
+ /** THE SINGLE WRITER of premium-dashboards.jsonl. `v`, `id` (for a new one) and `at` are set here.
100
+ * known = { charts: Set of KR metric ids of the workspace } — a chart outside it is refused. */
101
+ function save(root, input, actor, { now, known } = {}) {
102
+ const c = check(input);
103
+ if (!c.ok) return c;
104
+ const v = c.value;
105
+ const file = ledgerFile(root);
106
+ const have = list(root, v.board);
107
+ const t = now == null ? Date.now() : now;
108
+ let line;
109
+ if (v.remove) {
110
+ if (!have.some((d) => d.id === v.id)) return refuse(404, 'That dashboard is not on this board.');
111
+ line = { v: 1, ev: 'remove', id: v.id, board: v.board, actor: actor || null, at: new Date(t).toISOString() };
112
+ } else {
113
+ if (v.id !== null && !have.some((d) => d.id === v.id)) return refuse(404, 'That dashboard is not on this board.');
114
+ if (have.some((d) => d.id !== v.id && norm(d.name) === norm(v.name))) return refuse(409, `“${v.name}” is already a dashboard on this board.`);
115
+ const ks = known && known.charts;
116
+ const gone = ks ? v.charts.filter((x) => !ks.has(x)) : [];
117
+ if (gone.length) return refuse(400, `No KR metric record is called ${gone.map((x) => '“' + x + '”').join(', ')} in this workspace.`);
118
+ const id = v.id || 'pd-' + t.toString(36) + '-' + (readLines(file).length + 1);
119
+ line = { v: 1, ev: 'save', id, board: v.board, name: v.name, purpose: v.purpose, charts: v.charts, main: v.main, actor: actor || null, at: new Date(t).toISOString() };
120
+ }
121
+ fs.mkdirSync(path.dirname(file), { recursive: true });
122
+ fs.appendFileSync(file, JSON.stringify(line) + '\n');
123
+ const after = list(root, v.board);
124
+ return { ok: true, dashboard: v.remove ? null : after.find((d) => d.id === line.id) || null, dashboards: after };
125
+ }
126
+
127
+ module.exports = { NAME_MAX, PURPOSE_MAX, CHARTS_MAX, ADVISED_MAX, ledgerFile, readLines, check, fold, list, save };
@@ -82,6 +82,7 @@ const MODULES = Object.freeze([
82
82
  'routes-report-setups', // report-workspace: recurring reports, the Ask box, the finder, the report documents and their export (report-setups.jsonl)
83
83
  'routes-core-docs', // core-documents: the core documents of each level, Draft it (a core-doc run), Issue it and Drop (core-docs.jsonl)
84
84
  'routes-custom-docs', // briefing-premium-adddoc: the documents the PM adds beyond the core set, Add a document (custom-docs.jsonl)
85
+ 'routes-premium-dashboards', // briefing-premium-reports: the dashboards the PM makes on premium Insights (premium-dashboards.jsonl; page-press POST save)
85
86
  'routes-report-design', // report-design-studio: the design studio (describe, samples, turns, versions, This is it), cycle renders and decisions, speaker notes and pins
86
87
  'routes-report-structure', // report-structure: the structure step (turns, versions, Use this structure, sources and their checks, dry run) and the chart store (GET /api/charts)
87
88
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
@@ -4,13 +4,18 @@
4
4
  * 200 { ok, state: 'ready', model, as_of } | 500 { ok: false, state: 'error', error }
5
5
  * model is lib/insights-premium.js build(), made from what the console's Reports tab reads: /api/boards (the board list), the KR metric records of the
6
6
  * workspace with the line status the Calendar's Quarter pane computes from them (routes-c3-strategy.js outcomeOf; /api/c3-strategy itself drops the dated
7
- * readings, so the records are read here), and /api/report (the report files). None starts a cold repository read, so this route does not answer 202. Read-only: it writes nothing and the page posts nothing. */
7
+ * readings, so the records are read here), and /api/report (the report files). None starts a cold repository read, so this route does not answer 202.
8
+ * briefing-premium-reports adds the board's saved dashboards (lib/premium-dashboards.js list) and the workspace's GET /api/report-setups answer
9
+ * (setups, findings, asks). That GET is the console's own read: like the console, it may move old dashboard schedules into recurring reports once
10
+ * per repository. This route itself writes nothing. The page's presses post to /api/report-setups/* and /api/premium-dashboards/save. */
8
11
  const Insights = require('./insights-premium.js');
9
12
  const boards = require('./routes-boards.js');
10
13
  const strategy = require('./routes-c3-strategy.js');
11
14
  const { repoScript } = require('./repo-script.js');
12
15
  const { recordsDirFor } = require('./records-dir.js');
13
16
  const reports = require('./routes-reports.js');
17
+ const setups = require('./routes-report-setups.js');
18
+ const PD = require('./premium-dashboards.js');
14
19
 
15
20
  /** GET `pathAndQuery` from a route module's own handler, as the Board page's route does, and return { status, body }. */
16
21
  async function via(mod, pathAndQuery, req, ctx) {
@@ -42,9 +47,16 @@ module.exports = {
42
47
  outcomes = require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics').map((k) => strategy.outcomeOf(k, day));
43
48
  } catch (e) { return fail('the KR metric records could not be read: ' + ((e && e.message) || e)); }
44
49
  const reportsOk = !!(rp.body && rp.body.ok !== false);
50
+ const missing = reportsOk ? [] : ['reports'];
51
+ let saved = [];
52
+ if (pick && pick.id) { try { saved = PD.list(require('path').resolve(ctx.getWs(pick.ws).root), pick.id); } catch { missing.push('dashboards'); } }
53
+ const su = await via(setups, '/api/report-setups' + q, req, ctx).catch(() => ({ status: 500, body: null }));
54
+ const setupsOk = su.status === 200 && !!su.body && Array.isArray(su.body.setups);
55
+ if (!setupsOk) missing.push('report setups');
45
56
  const model = Insights.build({
46
57
  now: Date.now(), board: pick ? { ws: pick.ws, id: pick.id, name: pick.name } : { ws, id: null, name: 'Insights' }, boards: all.map((x) => ({ ws: x.ws, id: x.id, name: x.name })),
47
- outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing: reportsOk ? [] : ['reports'],
58
+ outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing, saved,
59
+ setups: setupsOk ? su.body : null,
48
60
  });
49
61
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
50
62
  return true;