create-pmos 0.258.0 → 0.259.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.258.0",
3
+ "version": "0.259.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@d223785
1
+ kernel-source: pmos@538d51d
2
2
  assembled: 2026-10-18
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-10-18T02:00:03Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:26:53Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-10-18T02:00:03Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:26:53Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-10-18T02:00:03Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-18T02:26:53Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* briefing-premium-adddoc-test.js — Add a document on the premium Board and initiative page (initiative briefing-premium-adddoc; planning/prd/briefing-premium-adddoc-prd.md A1 to A8).
4
+ * Serves the real pages from the real server. The model routes and the add route are answered from fixtures, so nothing is written to this repository; the real
5
+ * route is checked only for its refusals. A1 dialog · A3 the press · A4 messages · A5 rows · A7 labels · A8 floors and fidelity */
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { spawn } = require('child_process');
9
+ const { findBrowser } = require('./lib/find-browser');
10
+ const T = require('./test-run').configure({ name: 'briefing-premium-adddoc' });
11
+ const BP = require('./lib/board-premium.js');
12
+ const IP = require('./lib/initiative-premium.js');
13
+ const BF = require('./fixtures/board-premium-facts.js');
14
+ const IF = require('./fixtures/initiative-premium-facts.js');
15
+
16
+ const BASE = T.BASE;
17
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
+ const until = async (fn, ms = 10000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
19
+ const results = [];
20
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + extra : ''}`); };
21
+ let srv = null; let browser = null;
22
+ const finish = async (code) => {
23
+ if (browser) await browser.close().catch(() => {});
24
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
25
+ T.killTmux();
26
+ const bad = results.filter((x) => !x.cond).length;
27
+ console.log(`\n${results.length - bad}/${results.length} briefing-premium-adddoc assertions passed`);
28
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
29
+ };
30
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
31
+
32
+ const MOCKUP = path.join(__dirname, '..', 'prototype', 'premium-ux-concept', 'briefing-artifact.html');
33
+ const CUSTOM = [
34
+ { id: 'cd-1', scope: 'board:w1', title: 'UAT plan', writer: 'you', phase: null, link: null, at: '2026-10-18T09:00:00.000Z' },
35
+ { id: 'cd-2', scope: 'board:w1', title: 'Contract', writer: 'drafts', phase: null, link: { kind: 'Confluence', url: 'https://example.atlassian.net/wiki/spaces/X/pages/1' }, at: '2026-10-18T09:05:00.000Z' },
36
+ ];
37
+ const PAGES = {
38
+ board: { file: '/premium-board.html', api: '**/api/board-premium*', scope: 'board:w1', mk: (custom) => BP.build(BF.facts({ custom })), ready: '#ibBody .ini2', btn: '#addDoc', qs: '?theme=' },
39
+ initiative: { file: '/premium-initiative.html', api: '**/api/initiative-premium*', scope: 'initiative:self-serve-v2', mk: (custom) => IP.build(IF.facts({ custom })), ready: '#cIniTk', btn: '[data-adddoc]', qs: '?id=self-serve-v2&ws=w1&board=w1&theme=' },
40
+ };
41
+
42
+ (async () => {
43
+ const exe = findBrowser();
44
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
45
+ let chromium;
46
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
47
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT), PMOS_SELF_ROOT: path.resolve(__dirname, '..') }) });
48
+ await T.waitForServer(BASE);
49
+ browser = await chromium.launch({ executablePath: exe });
50
+
51
+ const open = async (kind, { w = 1280, h = 900, theme = 'light', custom = [], add = { status: 200, body: { ok: true } } } = {}) => {
52
+ const P = PAGES[kind];
53
+ const ctx = await browser.newContext({ viewport: { width: w, height: h } });
54
+ if (kind === 'board') await ctx.addInitScript(() => { try { localStorage.setItem('pmos.premium.openAs', 'popup'); } catch { /* none */ } });
55
+ const page = await ctx.newPage();
56
+ let current = custom, calls = 0, reply = add; const errors = [], posts = [];
57
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
58
+ await page.route(P.api, (r) => { calls++; return r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, state: 'ready', model: P.mk(current), as_of: Date.now() }) }); });
59
+ await page.route('**/api/custom-docs/**', (r) => { const rq = r.request(); posts.push({ path: new URL(rq.url()).pathname, body: JSON.parse(rq.postData() || '{}'), headers: rq.headers() }); r.fulfill({ status: reply.status, contentType: 'application/json', body: JSON.stringify(reply.body) }); });
60
+ await page.route('**/api/briefing-premium/**', (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, turns: [], working: false }) }));
61
+ await page.goto(BASE + P.file + P.qs + theme);
62
+ const up = await until(() => page.evaluate((s) => !!document.querySelector(s), P.ready), 20000);
63
+ return { ctx, page, errors, posts, up, calls: () => calls, setCustom: (c) => { current = c; }, reply: (a) => { reply = a; } };
64
+ };
65
+ const txt = (p, s) => p.evaluate((q) => (document.querySelector(q) || {}).textContent || '', s);
66
+
67
+ for (const kind of ['board', 'initiative']) {
68
+ const P = PAGES[kind], ini = kind === 'initiative';
69
+ const A = await open(kind), p = A.page;
70
+ ok(`${kind} 0 the page draws`, A.up);
71
+ if (!A.up) return finish(1);
72
+ ok(`${kind} A1 the Core documents card has an Add a document button`, await p.evaluate((s) => { const b = document.querySelector(s); return !!b && /Add a document/.test(b.textContent) && !b.hidden; }, P.btn));
73
+ await p.click(P.btn); await sleep(250);
74
+ const form = await p.evaluate(() => ({ open: document.querySelector('#dlg').classList.contains('on'), title: document.querySelector('#dTitle').textContent, t: !!document.querySelector('#adT'), phase: !!document.querySelector('#adC'), seg: [...document.querySelectorAll('#adW button')].map((b) => b.textContent), kinds: [...document.querySelectorAll('#adK option')].map((o) => o.textContent), uOff: document.querySelector('#adU').disabled, note: document.querySelector('.addf .note').textContent }));
75
+ ok(`${kind} A1 the dialog has the mockup's fields`, form.open && form.title === 'Add a document' && form.t && form.phase === ini && form.seg.join() === 'PMOS drafts it,I write it' && form.kinds.join() === 'In PMOS,Confluence,Google Docs,Google Slides' && form.uOff, JSON.stringify(form));
76
+ ok(`${kind} A7 the dialog says the document is saved and the linked page is not read`, /saved on the (board|initiative)'s record/.test(form.note) && /does not read or sync/.test(form.note), form.note);
77
+ await p.click('#adGo'); await sleep(120);
78
+ ok(`${kind} A4 an empty title is refused in the dialog and posts nothing`, /Give the document a title/.test(await txt(p, '#adM')) && A.posts.length === 0);
79
+ await p.fill('#adT', 'UAT plan'); await p.selectOption('#adK', 'Confluence'); await sleep(100);
80
+ ok(`${kind} A1 the address field opens for a link kind`, await p.evaluate(() => !document.querySelector('#adU').disabled));
81
+ await p.click('#adGo'); await sleep(120);
82
+ ok(`${kind} A4 a link kind with no address is refused in the dialog and posts nothing`, /Paste the address of the Confluence page/.test(await txt(p, '#adM')) && A.posts.length === 0);
83
+ A.reply({ status: 409, body: { ok: false, error: '“UAT plan” is already on this ' + (ini ? 'initiative' : 'board') + '.' } });
84
+ await p.fill('#adU', 'https://example.atlassian.net/wiki/x'); await p.click('#adGo'); await sleep(250);
85
+ ok(`${kind} A4 a refusal from the route is shown in the dialog, which stays open`, /already on this/.test(await txt(p, '#adM')) && await p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !document.querySelector('#adGo').disabled));
86
+ A.reply({ status: 200, body: { ok: true } }); const calls0 = A.calls();
87
+ await p.click('[data-w="you"]'); if (ini) await p.selectOption('#adC', 'Plan');
88
+ await p.click('#adGo'); await sleep(500);
89
+ const last = A.posts[A.posts.length - 1], mint = await T.nonce(BASE);
90
+ const want = { ws: ini ? 'w1' : 'w1', scope: P.scope, title: 'UAT plan', writer: 'you', kind: 'Confluence', url: 'https://example.atlassian.net/wiki/x' };
91
+ if (ini) want.phase = 'Plan';
92
+ ok(`${kind} A3 the press posts the entered fields to the one route, with the launch nonce and no writer field`, last && last.path === '/api/custom-docs/add' && JSON.stringify(Object.keys(last.body).sort()) === JSON.stringify(Object.keys(want).sort()) && Object.keys(want).every((k) => last.body[k] === want[k] || k === 'ws') && !!mint && last.headers['x-pmos-nonce'] === mint && !['by', 'via', 'at', 'actor', 'pm', 'nonce'].some((k) => k in last.body), JSON.stringify(last && last.body));
93
+ ok(`${kind} A3 nothing else was posted`, A.posts.every((x) => x.path === '/api/custom-docs/add'));
94
+ ok(`${kind} A1 the dialog closes, the page reads again and focus returns to the button`, A.calls() > calls0 && await p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')) && await p.evaluate((s) => document.activeElement === document.querySelector(s), P.btn));
95
+ A.setCustom(CUSTOM.map((d) => Object.assign({}, d, { scope: P.scope }))); await p.reload(); await until(() => p.evaluate((s) => !!document.querySelector(s), P.ready), 20000); await sleep(400);
96
+ const sel = ini ? '#cIniDoc' : '#cDocs';
97
+ const rows = await p.evaluate((s) => [...document.querySelectorAll(s + ' .dmr')].map((r) => ({ t: r.querySelector('b').textContent, s: r.querySelector('.dmm .s').textContent.trim(), small: r.querySelector('.dmn>small').textContent, meta: r.querySelector('.dmm').textContent, btn: r.querySelectorAll('button').length })), sel);
98
+ const uat = rows.find((r) => r.t === 'UAT plan'), con = rows.find((r) => r.t === 'Contract');
99
+ ok(`${kind} A5 an unlinked document reads Not started with the date it was added and no press`, uat && uat.s === 'Not started' && /added 18 Oct/.test(uat.meta) && /You write it/.test(uat.meta) && uat.btn === 0, JSON.stringify(uat));
100
+ ok(`${kind} A5 a linked document reads Linked, shows its address as text and has no press`, con && con.s === 'Linked' && /Confluence: https:\/\/example\.atlassian\.net/.test(con.small) && con.btn === 0 && !/Up to date/.test(con.s), JSON.stringify(con));
101
+ const sum = await txt(p, sel + ' .dsum');
102
+ ok(`${kind} A5 the summary counts one linked and the total counts both`, /1\s*linked/.test(sum) && /up to date/.test(sum), sum);
103
+ ok(`${kind} A5 the filter chips keep their four and a linked document is under All only`, await p.evaluate((s) => { const b = [...document.querySelectorAll(s + ' #dmF button')]; return b.length === 4 && /Linked/.test(b.map((x) => x.textContent).join('')) === false; }, sel));
104
+ await p.click(P.btn); await sleep(250);
105
+ const floors = await p.evaluate(() => { const h = (s) => Math.round(document.querySelector(s).getBoundingClientRect().height); return { go: h('#adGo'), no: h('#adNo'), t: h('#adT'), k: h('#adK'), w: Math.round(document.querySelector('#adW button').getBoundingClientRect().height), add: h('.dmadd2') }; });
106
+ ok(`${kind} A8 the buttons are at least 44 px (the fields and the switch keep the mockup's own size)`, [floors.go, floors.no, floors.add].every((v) => v >= 44), JSON.stringify(floors));
107
+ await p.keyboard.press('Escape'); await sleep(250);
108
+ ok(`${kind} A8 Escape closes the dialog`, await p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
109
+ ok(`${kind} no page error`, A.errors.length === 0, A.errors.join(' | '));
110
+ await A.ctx.close();
111
+ const N = await open(kind, { w: 390, h: 844 }); await N.page.click(P.btn); await sleep(300);
112
+ ok(`${kind} A8 no sideways scroll at 390 px with the dialog open`, await N.page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1 && document.querySelector('#dlg').getBoundingClientRect().right <= innerWidth + 1));
113
+ await N.ctx.close();
114
+ }
115
+
116
+ /* the real route: refusals only, so nothing is written to this repository */
117
+ {
118
+ const H = await T.pressHeaders(BASE);
119
+ const send = (body, headers) => fetch(BASE + '/api/custom-docs/add', { method: 'POST', headers, body: JSON.stringify(body) }).then(async (r) => ({ status: r.status, body: await r.json().catch(() => null) }));
120
+ const noNonce = await send({ scope: 'board:nope', title: 'A' }, { 'Content-Type': 'application/json' });
121
+ ok('A3 a request without the page headers is refused with 403', noNonce.status === 403, JSON.stringify(noNonce));
122
+ const agent = await send({ scope: 'board:nope', title: 'A' }, Object.assign({}, H, { 'x-pmos-session': 'abc' }));
123
+ ok('A3 an agent session is refused with 403', agent.status === 403, JSON.stringify(agent));
124
+ const empty = await send({ scope: 'board:nope', title: ' ' }, H);
125
+ ok('A4 an empty title is refused with 400 and a reason', empty.status === 400 && /title/.test(empty.body.error), JSON.stringify(empty));
126
+ const orphan = await send({ scope: 'board:no-such-board-xyz', title: 'A' }, H);
127
+ ok('A4 a board this workspace does not hold is refused', orphan.status !== 200 && orphan.body && orphan.body.ok === false, JSON.stringify(orphan));
128
+ const get = await fetch(BASE + '/api/custom-docs?scope=board:no-such-board-xyz').then(async (r) => ({ status: r.status, body: await r.json() }));
129
+ ok('A2 the list answers an empty set for a scope with no document', get.status === 200 && Array.isArray(get.body.docs) && get.body.docs.length === 0, JSON.stringify(get));
130
+ const badScope = await fetch(BASE + '/api/custom-docs?scope=portfolio').then((r) => r.status);
131
+ ok('A2 a scope that is not a board or initiative is refused', badScope === 400);
132
+ const wrong = await fetch(BASE + '/api/custom-docs/add').then((r) => r.status);
133
+ ok('A3 the add route takes POST only', wrong === 405);
134
+ }
135
+
136
+ /* A8 fidelity against the mockup's own dialog */
137
+ if (!fs.existsSync(MOCKUP)) ok('A8 the mockup is in the repository', false, MOCKUP);
138
+ else {
139
+ const PAIRS = [['ttl', '#dTitle'], ['note', '.addf .note'], ['lbl', '.addf label'], ['inp', '#adT'], ['phase', '#adC'], ['seg', '#adW'], ['segb', '#adW button'], ['kind', '#adK'], ['url', '#adU'], ['msg', '#adM'], ['go', '#adGo'], ['no', '#adNo'], ['pane', '#oMain'], ['paper', '#oMain .paper']];
140
+ const PROPS = ['fontSize', 'fontWeight', 'fontFamily', 'color', 'backgroundColor', 'borderRadius', 'paddingTop', 'paddingLeft', 'letterSpacing', 'lineHeight', 'borderTopColor', 'minHeight'];
141
+ const grab = (pg) => pg.evaluate(([pairs, props]) => { const o = {}; for (const [n, s] of pairs) { const e = document.querySelector(s); if (!e) { o[n] = null; continue; } const cs = getComputedStyle(e), r = e.getBoundingClientRect(), v = { width: e.offsetWidth, height: e.offsetHeight, cw: e.clientWidth, sh: e.scrollHeight }; props.forEach((k) => { v[k] = cs[k]; }); o[n] = v; } return o; }, [PAIRS, PROPS]);
142
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const th of ['light', 'dark']) {
143
+ const m = await (await browser.newContext({ viewport: { width: w, height: h } })).newPage();
144
+ await m.goto('file://' + MOCKUP);
145
+ await until(() => m.evaluate(() => document.querySelectorAll('#rank .rr').length > 0));
146
+ await m.evaluate((t) => { document.documentElement.dataset.theme = t; document.querySelector('.pl[data-p="init"]').click(); }, th);
147
+ await until(() => m.evaluate(() => document.querySelectorAll('#ibBody .ini2').length > 0)); await sleep(500);
148
+ await m.evaluate(() => { showInit('initiative', 'pmos', 0); });
149
+ await until(() => m.evaluate(() => !!document.querySelector('#cIniDoc .dmr'))); await sleep(800);
150
+ const mBtn = await m.evaluate(() => { const b = document.querySelector('#cIniDoc .dmadd2'), cs = getComputedStyle(b), r = b.getBoundingClientRect(); return { fs: cs.fontSize, fw: cs.fontWeight, bg: cs.backgroundColor, c: cs.color, br: cs.borderRadius, h: Math.round(r.height) }; });
151
+ await m.click('#cIniDoc .dmadd2'); await sleep(500);
152
+ const a = await grab(m);
153
+ const R = await open('initiative', { w, h, theme: th }); await sleep(400);
154
+ const rBtn = await R.page.evaluate(() => { const b = document.querySelector('[data-adddoc]'), cs = getComputedStyle(b), r = b.getBoundingClientRect(); return { fs: cs.fontSize, fw: cs.fontWeight, bg: cs.backgroundColor, c: cs.color, br: cs.borderRadius, h: Math.round(r.height) }; });
155
+ await R.page.click('[data-adddoc]'); await sleep(500);
156
+ const c = await grab(R.page), diffs = [];
157
+ for (const k of Object.keys(mBtn)) if (k !== 'h' && mBtn[k] !== rBtn[k]) diffs.push(`btn.${k} ${mBtn[k]} | ${rBtn[k]}`); // the height is the 44 px floor the earlier slices keep (the mockup draws 36)
158
+ for (const [n] of PAIRS) {
159
+ if (!a[n] || !c[n]) { diffs.push(n + ' missing'); continue; }
160
+ for (const k of Object.keys(a[n])) {
161
+ if (k === 'cw' || k === 'sh' || ((n === 'ttl' || n === 'pane' || n === 'paper') && (k === 'width' || k === 'height'))) continue; // the dialog's columns size to the conversation beside the form, which differs
162
+ const geom = k === 'width' || k === 'height';
163
+ if (geom ? Math.abs(a[n][k] - c[n][k]) > 14 : a[n][k] !== c[n][k]) diffs.push(`${n}.${k} ${a[n][k]} | ${c[n][k]}`);
164
+ }
165
+ }
166
+ ok(`A8 the button and the dialog match the mockup at ${w} px, ${th}`, diffs.length === 0, diffs.join(' ; '));
167
+ await m.context().close(); await R.ctx.close();
168
+ }
169
+ }
170
+ return finish();
171
+ })().catch((e) => { console.error(e); finish(1); });
@@ -147,7 +147,7 @@ const HEALTH = { ok: true, path: 'planning/prd/self-serve-v2-prd.md', health: {
147
147
  const mint0 = await T.nonce(BASE);
148
148
  ok('I10 both task presses carried the launch nonce and no writer field', !!mint0 && A.posts.filter((x) => /^\/api\/boards\/tasks\//.test(x.path)).every((x) => x.headers['x-pmos-nonce'] === mint0 && !['by', 'via', 'at', 'actor', 'pm', 'nonce'].some((k) => k in x.body)));
149
149
  await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on')));
150
- ok('I6 there is no Add a document: no store for it exists', !(await p.evaluate(() => /Add a document/.test(document.body.textContent))));
150
+ ok('I6 Add a document is the one button of the Core documents card that adds (its own suite is briefing-premium-adddoc-test.js)', await p.evaluate(() => document.querySelectorAll('[data-adddoc]').length === 1 && /Add a document/.test(document.querySelector('#cIniDoc .ch').textContent)));
151
151
 
152
152
  /* I7 documents, I11 one count */
153
153
  ok('I7 the counts agree: caption, summary, filter and bar', await p.evaluate(() => { const s = document.querySelector('.dsum').textContent.replace(/\s+/g, ' '); const f = [...document.querySelectorAll('#dmF button')].map((b) => b.textContent.replace(/\s+/g, '')).join(','); return document.querySelector('#hDoc + small').textContent === '5' && /1 draft to review/.test(s) && /3 not started/.test(s) && /1 up to date/.test(s) && f === 'All5,Notstarted3,Draft1,Uptodate1' && document.querySelectorAll('.dprog i').length === 5; }));
@@ -144,7 +144,7 @@ Board is the third place on the rail, at `/premium-board.html`. It reads what th
144
144
  - **Sprint** appears when an agent session has read Jira for the board. Otherwise it says there is none. **Coming up** shows the next release, from the releases ledger.
145
145
  - **Metrics** appears above the Initiatives card on the board of any workspace except the home one (PMOS itself), and counts from that workspace's own repository. It has four tiles. **Corrections per 100 runs** is the corrections logged on the week's runs in `planning/runs/agent-runs.jsonl`; a week with fewer than 10 runs is left blank. **Merged a week** counts the commits on the first-parent line of the trunk. **Blocked** and **Idle for a month** come from the workflow engine and keep no history, so they have no chart. Move over a chart, or use the arrow keys, to read a week. A tile that cannot be counted says **Not read** and why. Press a tile for its definition and values, with the read-only agent beside it. There are no targets, and Day and Month are off. It was tested only on made-up repositories, not on a real IDPF or microsite repository.
146
146
  - **The crumb** at the top names the board. With more than one board a menu switches between them, and the sparkle opens the board in the dialog with the read-only agent.
147
- - **Core documents** lists the board's documents with their state, cadence and writer, a summary (drafts to review, not started, up to date), a progress bar, a filter and a search. **Draft it** starts the existing read-only run that writes a draft and sends nothing; **Draft the N not started** does that for each document that can be drafted. **Set it up** and **Open** go to the console. Issue, Drop and Add a document are not on this page.
147
+ - **Core documents** lists the board's documents with their state, cadence and writer, a summary (drafts to review, not started, up to date), a progress bar, a filter and a search. **Draft it** starts the existing read-only run that writes a draft and sends nothing; **Draft the N not started** does that for each document that can be drafted. **Set it up** and **Open** go to the console. **Add a document** opens a form (title, who writes it, where it lives) and saves a document the core set does not cover on the board's record, in `custom-docs.jsonl`. A document with no link reads "Not started". A document with a link to Confluence or Google Docs reads "Linked" and shows its address. PMOS does not read or sync the linked page, so a linked document is never counted as up to date. Issue and Drop are not on this page.
148
148
  - **Opening an initiative.** A click on an initiative opens its page (see "Initiative page"). The **Page / Popup** switch in the header changes that: Popup opens the initiative's dialog instead, which shows its record as a grid and the path of its file, with the read-only agent beside it. The choice is kept in this browser. The dialog holds no press: moving an initiative or starting work on it is not built here.
149
149
 
150
150
  Not drawn, because PMOS holds no record for them: the Metrics card on the PMOS board, the mockup's demo measures (Activation, Partner uptime, API p95), targets, and the mockup's demo boards.
@@ -158,7 +158,7 @@ The initiative page is at `/premium-initiative.html?id=<initiative>`. A click on
158
158
  - **The header** shows a status chip, the owner and the planned finish. Each appears only when a record holds it. Under it, the stage strip shows how far through the board's workflow the initiative is.
159
159
  - **Overview** shows the description (the part of the record's title after " — "), then the next step with its reason, its action and what happens if you wait, as the workflow engine states them, and who it waits on. **PMOS can help** offers up to three presses that do something real: a draft of the first core document not started (the existing read-only run) and a question for the read-only agent. The health reasons and the board's warnings are shown as written.
160
160
  - **Checks** lists the engine's six steps (spec, contract, build, quality, review, accept) with their state and the evidence each states, and marks the next one. "All N workflow steps" lists every step.
161
- - **Tasks** lists the PRD requirements and the board's tracker items for this initiative. The repository records no result for each requirement, so a requirement says "No result" and is never drawn as done or open. **By stage** groups them by state. **Timeline** draws a bar for each task that has both a start and a due date, and lists the rest. Press a task to read its record; for a PMOS task you can change its status. **Add a task** writes a PMOS task to the board's own record; with no dates the board plans it from tomorrow for a week. Jira tickets stay read-only. There is no Add a document: nothing stores a document you add.
161
+ - **Tasks** lists the PRD requirements and the board's tracker items for this initiative. The repository records no result for each requirement, so a requirement says "No result" and is never drawn as done or open. **By stage** groups them by state. **Timeline** draws a bar for each task that has both a start and a due date, and lists the rest. Press a task to read its record; for a PMOS task you can change its status. **Add a task** writes a PMOS task to the board's own record; with no dates the board plans it from tomorrow for a week. Jira tickets stay read-only. **Add a document** works as on the Board, with a phase as well, and saves on the initiative's record.
162
162
  - **Core documents** has the same counts, filter and search as the Board's card, for this initiative. **Draft it** starts the existing read-only run that writes a draft and sends nothing. Technical documents (the record, the rubric, the stories, the review and the explainer) are grouped and not counted.
163
163
  - **The document sheet.** A document that has a file opens in a dialog with **Read** (the file's text, its front matter as a grid and an outline), **Edit** (the file as plain Markdown, a reason, and **Save**), **Proposals** (**Ask the agent**, the open proposals with **Accept** and **Reject**, and the closed ones), **Edit log** (the revisions and other entries of the document sheet) and **Health** (the document-health checks; a check with no input is not counted). The file changes only when you press Save or Accept, and every change is kept in the Edit log with its reason. Save and Reject need a reason. A proposal made on text that has since changed shows which sections are out of date and cannot take them. The agent beside the sheet still only reads. Bold and undo buttons, Issue and Drop are not built on this page.
164
164
 
@@ -19,6 +19,7 @@
19
19
 
20
20
  const pad = (n) => String(n).padStart(2, '0');
21
21
  const hhmm = (ms) => { const d = new Date(ms); return pad(d.getHours()) + ':' + pad(d.getMinutes()); };
22
+ const Custom = require('./custom-docs.js');
22
23
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
23
24
  const isoDay = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null; };
24
25
  const shortDate = (v) => { const d = isoDay(v); return d ? d.getDate() + ' ' + MON[d.getMonth()] : ''; };
@@ -100,15 +101,17 @@ function build(f) {
100
101
  : { cap: 'none', why: 'No release is planned for this board.' };
101
102
 
102
103
  const dd = f.docs || null;
104
+ const custom = (f.custom || []).map((d) => Object.assign(Custom.rowOf(d), { added: shortDate(d.at) }));
105
+ const nLinked = custom.filter((d) => d.st === 'linked').length, nCustomNone = custom.length - nLinked;
103
106
  const docs = dd ? {
104
- cap: dd.summary ? [dd.summary.missing ? dd.summary.missing + ' not started' : null, dd.summary.draft ? dd.summary.draft + ' ' + plural(dd.summary.draft, 'draft', 'drafts') : null, dd.summary.stale ? dd.summary.stale + ' stale' : null, dd.summary.due ? dd.summary.due + ' due' : null].filter(Boolean).join(' · ') || 'all up to date' : '',
107
+ cap: dd.summary ? [(dd.summary.missing + nCustomNone) ? (dd.summary.missing + nCustomNone) + ' not started' : null, dd.summary.draft ? dd.summary.draft + ' ' + plural(dd.summary.draft, 'draft', 'drafts') : null, dd.summary.stale ? dd.summary.stale + ' stale' : null, dd.summary.due ? dd.summary.due + ' due' : null].concat(nLinked ? [nLinked + ' linked'] : []).filter(Boolean).join(' · ') || 'all up to date' : '',
105
108
  scope: dd.scope || null,
106
109
  counts: null,
107
110
  rows: (dd.docs || []).map((d) => ({ key: d.key, title: d.title, what: d.for || '', state: d.kind === 'live' ? 'Live' : DOC_STATE[d.st] || d.st || '', st: d.st, cadence: d.cadence || '', by: BY[d.by] || d.by || '', running: !!d.running,
108
- act: d.act && d.act.do === 'draft' ? { kind: 'draft', label: d.running ? 'Drafting' : d.act.label || 'Draft it' } : d.act && d.act.go ? { kind: 'go', label: d.act.label || 'Open', tab: GO[d.act.go] || 'init' } : d.open && d.open.tab ? { kind: 'go', label: 'Open', tab: GO[d.open.tab] || 'init' } : null })),
109
- } : { cap: '', rows: [], missing: true };
110
- if (dd) docs.counts = { all: docs.rows.length, none: docs.rows.filter((d) => d.st === 'missing').length, draft: docs.rows.filter((d) => d.st === 'draft').length, ok: docs.rows.filter((d) => d.st === 'ok').length };
111
- else docs.counts = { all: 0, none: 0, draft: 0, ok: 0 };
111
+ act: d.act && d.act.do === 'draft' ? { kind: 'draft', label: d.running ? 'Drafting' : d.act.label || 'Draft it' } : d.act && d.act.go ? { kind: 'go', label: d.act.label || 'Open', tab: GO[d.act.go] || 'init' } : d.open && d.open.tab ? { kind: 'go', label: 'Open', tab: GO[d.open.tab] || 'init' } : null })).concat(custom),
112
+ } : { cap: '', rows: custom, missing: true, scope: board.id ? 'board:' + board.id : null };
113
+ docs.counts = dd || custom.length ? { all: docs.rows.length, none: docs.rows.filter((d) => d.st === 'missing').length, draft: docs.rows.filter((d) => d.st === 'draft').length, ok: docs.rows.filter((d) => d.st === 'ok').length } : { all: 0, none: 0, draft: 0, ok: 0 };
114
+ if (nLinked) docs.counts.linked = nLinked; // a key only when an added document is linked
112
115
  if (!dd && !missing.includes('core documents')) missing.push('core documents');
113
116
 
114
117
  const model = {
@@ -0,0 +1,107 @@
1
+ 'use strict';
2
+ /* custom-docs.js — the documents the PM adds to a board or an initiative, beyond the core set (initiative briefing-premium-adddoc).
3
+ * THE ONE WRITER and THE ONE FOLD of <state>/custom-docs.jsonl.
4
+ *
5
+ * KINDS · PHASES · WRITERS · TITLE_MAX · URL_MAX
6
+ * ledgerFile(root) · readLines(file)
7
+ * check(input) → { ok: true, value } | { ok: false, status, error } PURE
8
+ * list(root, scope) → [{ id, scope, title, writer, phase, link, at }] in the order they were added
9
+ * add(root, input, actor, { now }) → { ok: true, doc } | { ok: false, status, error }
10
+ *
11
+ * THE LEDGER. Lines { v: 1, ev: 'add', id, scope, title, writer, phase, link, actor, at }. `scope` is board:<id> or initiative:<id>. `writer` is
12
+ * drafts | you. `phase` is a phase name for an initiative and null for a board. `link` is { kind, url } or null. `actor` is the actor of the call
13
+ * path (lib/actor.js), never an argument. Nothing here reads or syncs a linked page: the record holds the address and the date it was added.
14
+ * The file is never rewritten. A line that does not parse, or has no title, is skipped.
15
+ */
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ const LEDGER = 'custom-docs.jsonl';
20
+ const KINDS = Object.freeze(['Confluence', 'Google Docs', 'Google Slides']);
21
+ const PHASES = Object.freeze(['Discover', 'Plan', 'Build', 'Evaluate']);
22
+ const WRITERS = Object.freeze(['drafts', 'you']);
23
+ const TITLE_MAX = 80;
24
+ const URL_MAX = 300;
25
+ const SCOPE_RE = /^(board|initiative):[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 norm = (t) => String(t).trim().replace(/\s+/g, ' ').toLowerCase();
30
+
31
+ function ledgerFile(root) {
32
+ const abs = path.resolve(String(root));
33
+ return path.join(abs, require('./report-draft.js').stateRel(abs), LEDGER);
34
+ }
35
+ function readLines(file) {
36
+ let text = '';
37
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
38
+ const out = [];
39
+ for (const raw of text.split('\n')) {
40
+ if (!raw.trim()) continue;
41
+ try { const l = JSON.parse(raw); if (isObj(l) && l.ev === 'add' && typeof l.scope === 'string' && typeof l.title === 'string' && l.title && typeof l.id === 'string') out.push(l); } catch { /* a torn line is skipped */ }
42
+ }
43
+ return out;
44
+ }
45
+
46
+ /** Check the fields of an add. The scope's existence is the route's check; this one is about the shape. */
47
+ function check(input) {
48
+ const i = isObj(input) ? input : {};
49
+ const scope = typeof i.scope === 'string' ? i.scope : '';
50
+ if (!SCOPE_RE.test(scope)) return refuse(400, 'scope must be board:<id> or initiative:<id>');
51
+ const level = scope.slice(0, scope.indexOf(':'));
52
+ const title = typeof i.title === 'string' ? i.title.trim().replace(/\s+/g, ' ') : '';
53
+ if (!title) return refuse(400, 'Give the document a title.');
54
+ if (title.length > TITLE_MAX) return refuse(400, `The title can be at most ${TITLE_MAX} characters.`);
55
+ const writer = i.writer == null || i.writer === '' ? 'drafts' : i.writer;
56
+ if (!WRITERS.includes(writer)) return refuse(400, 'Say who writes it: PMOS drafts it, or you write it.');
57
+ let phase = null;
58
+ if (level === 'initiative') {
59
+ phase = i.phase == null || i.phase === '' ? null : i.phase;
60
+ if (phase != null && !PHASES.includes(phase)) return refuse(400, 'The phase must be Discover, Plan, Build or Evaluate.');
61
+ }
62
+ let link = null;
63
+ const kind = i.kind == null || i.kind === '' ? null : i.kind;
64
+ if (kind != null) {
65
+ if (!KINDS.includes(kind)) return refuse(400, `Where it lives must be In PMOS, ${KINDS.join(', ')}.`);
66
+ const url = typeof i.url === 'string' ? i.url.trim() : '';
67
+ if (!url) return refuse(400, `Paste the address of the ${kind} page, or choose In PMOS.`);
68
+ if (url.length > URL_MAX) return refuse(400, `The address can be at most ${URL_MAX} characters.`);
69
+ let u = null; try { u = new URL(url); } catch { u = null; }
70
+ if (!u || (u.protocol !== 'https:' && u.protocol !== 'http:') || !u.hostname || u.username || u.password) return refuse(400, 'The address must be a web address that starts with http:// or https://.');
71
+ link = { kind, url };
72
+ }
73
+ return { ok: true, value: { scope, title, writer, phase, link } };
74
+ }
75
+
76
+ /** The documents of one scope, oldest first. */
77
+ function list(root, scope) {
78
+ return readLines(ledgerFile(root)).filter((l) => l.scope === scope).map((l) => ({
79
+ id: l.id, scope: l.scope, title: l.title, writer: WRITERS.includes(l.writer) ? l.writer : null, phase: PHASES.includes(l.phase) ? l.phase : null,
80
+ link: isObj(l.link) && KINDS.includes(l.link.kind) && typeof l.link.url === 'string' ? { kind: l.link.kind, url: l.link.url } : null, at: l.at || null,
81
+ }));
82
+ }
83
+
84
+ /** THE SINGLE WRITER of custom-docs.jsonl. `v`, `id` and `at` are set here. */
85
+ function add(root, input, actor, { now } = {}) {
86
+ const c = check(input);
87
+ if (!c.ok) return c;
88
+ const v = c.value;
89
+ const file = ledgerFile(root);
90
+ const have = readLines(file).filter((l) => l.scope === v.scope);
91
+ if (have.some((l) => norm(l.title) === norm(v.title))) return refuse(409, `“${v.title}” is already on this ${v.scope.startsWith('board:') ? 'board' : 'initiative'}.`);
92
+ const t = now == null ? Date.now() : now;
93
+ const line = { v: 1, ev: 'add', id: 'cd-' + t.toString(36) + '-' + (have.length + 1), scope: v.scope, title: v.title, writer: v.writer, phase: v.phase, link: v.link, actor: actor || null, at: new Date(t).toISOString() };
94
+ fs.mkdirSync(path.dirname(file), { recursive: true });
95
+ fs.appendFileSync(file, JSON.stringify(line) + '\n');
96
+ return { ok: true, doc: { id: line.id, scope: line.scope, title: line.title, writer: line.writer, phase: line.phase, link: line.link, at: line.at } };
97
+ }
98
+
99
+ /** One added document as a row of the Core documents card. PURE. `st` is `missing` (no link) or `linked`; never `ok`: PMOS cannot read a linked page.
100
+ * `added` is the day it was added (YYYY-MM-DD) and the only date the row holds. */
101
+ function rowOf(d) {
102
+ const linked = !!d.link;
103
+ return { key: 'custom:' + d.id, title: d.title, what: linked ? 'Lives in ' + d.link.kind + ': ' + d.link.url : 'Added by you.', st: linked ? 'linked' : 'missing', state: linked ? 'Linked' : 'Not started',
104
+ by: d.writer === 'you' ? 'You write it' : d.writer === 'drafts' ? 'PMOS drafts it' : '', cat: d.phase || null, link: d.link, added: d.at ? String(d.at).slice(0, 10) : '', custom: true, act: null };
105
+ }
106
+
107
+ module.exports = { rowOf, KINDS, PHASES, WRITERS, TITLE_MAX, URL_MAX, ledgerFile, readLines, check, list, add };
@@ -18,6 +18,7 @@
18
18
 
19
19
  const pad = (n) => String(n).padStart(2, '0');
20
20
  const hhmm = (ms) => { const d = new Date(ms); return pad(d.getHours()) + ':' + pad(d.getMinutes()); };
21
+ const Custom = require('./custom-docs.js');
21
22
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
22
23
  const isoDay = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null; };
23
24
  const shortDate = (v) => { const d = isoDay(v); return d ? d.getDate() + ' ' + MON[d.getMonth()] : ''; };
@@ -105,11 +106,15 @@ function build(f) {
105
106
  when: d.when ? shortDate(d.when) : '', cat: d.cat === 'Do' ? 'Build' : d.cat === 'Learn' ? 'Evaluate' : d.cat || 'Board', path: d.open && d.open.path ? d.open.path : null, running: !!d.running, tech: TECH.has(d.key),
106
107
  act: d.act && d.act.do === 'draft' ? { kind: 'draft', label: d.running ? 'Drafting' : d.act.label || 'Draft it' } : null,
107
108
  })) : [];
108
- const core = all.filter((d) => !d.tech);
109
+ const custom = (f.custom || []).map((d) => Object.assign(Custom.rowOf(d), { added: shortDate(d.at), cat: d.phase || 'Board' }));
110
+ const rows = all.concat(custom);
111
+ const core = rows.filter((d) => !d.tech);
109
112
  const cnt = { all: core.length, none: core.filter((d) => d.st === 'missing').length, draft: core.filter((d) => d.st === 'draft').length, ok: core.filter((d) => d.st === 'ok' || d.st === 'live').length };
110
- const docs = dd ? { rows: all, counts: cnt, techCount: all.length - core.length,
111
- cap: core.length ? [cnt.draft ? cnt.draft + ' ' + plural(cnt.draft, 'draft', 'drafts') + ' to review' : '', cnt.none ? cnt.none + ' not started' : '', cnt.ok ? cnt.ok + ' up to date' : ''].filter(Boolean).join(' · ') : '',
112
- scope: dd.scope || 'initiative:' + id } : { rows: [], counts: { all: 0, none: 0, draft: 0, ok: 0 }, techCount: 0, cap: '', missing: true };
113
+ const nLinked = core.filter((d) => d.st === 'linked').length;
114
+ if (nLinked) cnt.linked = nLinked; // a key only when an added document is linked
115
+ const docs = dd || custom.length ? { rows, counts: cnt, techCount: rows.length - core.length,
116
+ cap: core.length ? [cnt.draft ? cnt.draft + ' ' + plural(cnt.draft, 'draft', 'drafts') + ' to review' : '', cnt.none ? cnt.none + ' not started' : '', cnt.ok ? cnt.ok + ' up to date' : '', nLinked ? nLinked + ' linked' : ''].filter(Boolean).join(' · ') : '',
117
+ scope: (dd && dd.scope) || 'initiative:' + id, missing: !dd } : { rows: [], counts: { all: 0, none: 0, draft: 0, ok: 0 }, techCount: 0, cap: '', missing: true };
113
118
  if (!dd && !missing.includes('core documents')) missing.push('core documents');
114
119
 
115
120
  // ── PMOS can help: only things a press can really do. A draft of a core document the initiative has not started (the existing read-only draft run), and a question for the read-only agent ──
@@ -81,6 +81,7 @@ const MODULES = Object.freeze([
81
81
  'routes-scan', // horizon-scan-portfolio: one scan for the workspace: the watch list and setting, Scan now and Stop, report documents and their proposals (approve, change, dismiss, undo), plus the first scan's per-board and Briefing reads (scan.jsonl)
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
+ 'routes-custom-docs', // briefing-premium-adddoc: the documents the PM adds beyond the core set, Add a document (custom-docs.jsonl)
84
85
  'routes-report-design', // report-design-studio: the design studio (describe, samples, turns, versions, This is it), cycle renders and decisions, speaker notes and pins
85
86
  '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)
86
87
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
@@ -10,6 +10,7 @@ const BoardPremium = require('./board-premium.js');
10
10
  const BoardP = BoardPremium;
11
11
  const boards = require('./routes-boards.js');
12
12
  const coreDocs = require('./routes-core-docs.js');
13
+ const Custom = require('./custom-docs.js');
13
14
  const path = require('path');
14
15
  const fs = require('fs');
15
16
  const Metrics = require('./board-metrics-premium.js');
@@ -73,10 +74,13 @@ module.exports = {
73
74
  ]);
74
75
  const ok = (r, name) => { if (r.status === 202 || !r.body || r.body.ok === false || r.body.pending) { missing.push(name); return null; } return r.body; };
75
76
  const rk = ok(risk, 'initiatives'), nw = ok(now, 'initiatives'), c = ok(cols, 'stages'), s = ok(spr, 'sprints'), d = ok(docs, 'core documents');
77
+ // the documents the PM added (lib/custom-docs.js): one file read, no route
78
+ let custom = [];
79
+ try { const w = ctx.getWs ? ctx.getWs(pick.ws) : null; custom = w ? Custom.list(w.root, 'board:' + pick.id) : []; } catch { custom = []; missing.push('added documents'); }
76
80
  const model = BoardPremium.build({
77
81
  now: Date.now(), pending: false, missing: missing.filter((m) => m !== 'core documents'), boards: all.map((x) => ({ ws: x.ws, id: x.id, name: x.name })),
78
82
  board: head.body.board, counts: head.body.counts, nextRelease: head.body.nextRelease || null,
79
- rows: listOf(rk, nw), columns: c ? c.columns : [], sprints: s || { source: 'none', sprints: [] }, docs: d,
83
+ rows: listOf(rk, nw), columns: c ? c.columns : [], sprints: s || { source: 'none', sprints: [] }, docs: d, custom,
80
84
  });
81
85
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
82
86
  return true;
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+ /* routes-custom-docs.js — the documents the PM adds beyond the core set (initiative briefing-premium-adddoc).
3
+ *
4
+ * GET /api/custom-docs?ws&scope → { ok, scope, docs: [{ id, title, writer, phase, link, at }] }
5
+ * POST /api/custom-docs/add { ws, scope, title, writer, phase, kind, url } → { ok, doc } one `add` line in custom-docs.jsonl
6
+ *
7
+ * WHO WRITES. The POST refuses a request that carries an agent session header (403), as routes-core-docs.js does, and passes pm-guard
8
+ * requirePagePress: the launch nonce and the page's origin. The scope must be a board or an initiative the workspace knows (lib/core-docs.js
9
+ * gather). The route stores what the PM typed and nothing else: it never reads a linked page. */
10
+ const guard = require('./pm-guard.js');
11
+ const CD = require('./core-docs.js');
12
+ const Custom = require('./custom-docs.js');
13
+
14
+ const text = (v) => (typeof v === 'string' ? v : '');
15
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
16
+
17
+ function wsOf(ctx, id) {
18
+ const w = ctx.getWs(id || null);
19
+ return w && (!id || w.id === id) ? w : null;
20
+ }
21
+ /** The scope must name a board or an initiative this workspace holds. → null | refusal */
22
+ function known(ctx, w, scope) {
23
+ const p = CD.parseScope(scope);
24
+ if (!p || p.level === 'portfolio') return bad(400, 'scope must be board:<id> or initiative:<id>');
25
+ const g = CD.gather(ctx, w, { level: p.level, board: p.level === 'board' ? p.id : null, id: p.level === 'initiative' ? p.id : null, now: Date.now() });
26
+ if (g.pending) return bad(202, 'The initiatives are being read. Ask again in a few seconds.');
27
+ if (!g.ok) return bad(g.status || 404, g.error || 'no such board or initiative');
28
+ return null;
29
+ }
30
+
31
+ async function handle(req, res, url, ctx) {
32
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
33
+ const sub = url.pathname.replace(/^\/api\/custom-docs\/?/, '');
34
+ if (sub === '') {
35
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
36
+ const w = wsOf(ctx, url.searchParams.get('ws'));
37
+ if (!w) return send(bad(404, 'no such workspace'));
38
+ const scope = text(url.searchParams.get('scope'));
39
+ if (!Custom.check({ scope, title: 'x' }).ok) return send(bad(400, 'scope must be board:<id> or initiative:<id>'));
40
+ return send({ status: 200, body: { ok: true, scope, docs: Custom.list(w.root, scope) } });
41
+ }
42
+ if (sub !== 'add') return send(bad(404, 'no such custom-docs route'));
43
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
44
+ const read = await ctx.readJson(req);
45
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
46
+ const body = read.body || {};
47
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'an agent session cannot add a document. Only a press on the page does'));
48
+ const g = guard.requirePagePress(req, body);
49
+ if (!g.ok) return send(bad(g.status, g.error));
50
+ const w = wsOf(ctx, text(body.ws));
51
+ if (!w) return send(bad(404, 'no such workspace'));
52
+ const c = Custom.check(body);
53
+ if (!c.ok) return send(bad(c.status, c.error));
54
+ const miss = known(ctx, w, c.value.scope);
55
+ if (miss) return send(miss);
56
+ const r = Custom.add(w.root, body, g.actor, { now: Date.now() });
57
+ if (!r.ok) return send(bad(r.status, r.error));
58
+ try { if (ctx.invalidateNeedsAgg) ctx.invalidateNeedsAgg(w.id); } catch { /* the next poll recounts */ }
59
+ return send({ status: 200, body: { ok: true, doc: r.doc } });
60
+ }
61
+
62
+ module.exports = { prefixes: ['/api/custom-docs'], handle };
@@ -10,6 +10,7 @@ const InitPremium = require('./initiative-premium.js');
10
10
  const boards = require('./routes-boards.js');
11
11
  const initiatives = require('./routes-initiatives.js');
12
12
  const coreDocs = require('./routes-core-docs.js');
13
+ const Custom = require('./custom-docs.js');
13
14
 
14
15
  /** GET `pathAndQuery` from a route module's own handler, as the Work page's route does, and return { status, body }. */
15
16
  async function via(mod, pathAndQuery, req, ctx) {
@@ -55,10 +56,12 @@ module.exports = {
55
56
  let lad = null;
56
57
  try { const w = ctx.getWs ? ctx.getWs(pick.ws) : null; const r = w && ctx.consoleState && ctx.consoleState.ladder ? ctx.consoleState.ladder({ root: w.root, id }) : null; lad = r && r.ok && r.row ? r.row : null; } catch { lad = null; }
57
58
  if (!lad) missing.push('workflow steps');
59
+ let custom = [];
60
+ try { const w = ctx.getWs ? ctx.getWs(pick.ws) : null; custom = w ? Custom.list(w.root, 'initiative:' + id) : []; } catch { custom = []; missing.push('added documents'); }
58
61
  const model = InitPremium.build({
59
62
  now: Date.now(), pending: false, missing: missing.filter((m) => m !== 'core documents'),
60
63
  board: { ws: own.ws || pick.ws, id: own.id, name: own.name, workflow: own.workflow },
61
- row: head.body.row, sheet: sh, items: it ? it.items : [], docs: dd, ladder: lad,
64
+ row: head.body.row, sheet: sh, items: it ? it.items : [], docs: dd, custom, ladder: lad,
62
65
  boards: all.map((x) => ({ ws: x.ws, id: x.id, name: x.name })), siblings: it ? (it.initiatives || []).map((x) => ({ id: x.id, title: x.title })) : [],
63
66
  });
64
67
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.258.0",
3
+ "version": "0.259.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.258.0",
9
+ "version": "0.259.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.258.0",
3
+ "version": "0.259.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -3,7 +3,7 @@
3
3
  * Coming up cards, Core documents, the dock and the standard dialog. The one press is Draft it on a core document, through POST /api/core-docs/draft.
4
4
  * Nothing here moves an initiative or issues a document. */
5
5
  import { pmPost } from './http.js';
6
- import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, store, crumbHtml, wireCrumb, kv, H } from './premium-shell.js';
6
+ import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, store, crumbHtml, wireCrumb, kv, H, openAddDoc } from './premium-shell.js';
7
7
 
8
8
  const MODE_KEY = 'pmos.premium.openAs';
9
9
  let M = null; // the model
@@ -13,7 +13,7 @@ let readTimer = null;
13
13
  wireRail('init');
14
14
  const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
15
15
  const DOCI = '<path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 13h6M9 17h4"/>';
16
- const STATE_ICO = { Live: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>', 'Up to date': '<path d="M5 12.5l4.5 4.5L19 7.5"/>', Draft: '<path d="M4 20l4-1 11-11-3-3L5 16z"/>', 'Not started': '<circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16.5v.5"/>', Stale: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>', Due: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>' };
16
+ const STATE_ICO = { Linked: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>', Live: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>', 'Up to date': '<path d="M5 12.5l4.5 4.5L19 7.5"/>', Draft: '<path d="M4 20l4-1 11-11-3-3L5 16z"/>', 'Not started': '<circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16.5v.5"/>', Stale: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>', Due: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>' };
17
17
 
18
18
  /* ── header ───────────────────────────────────────────────────────────────────────────────────────────── */
19
19
  let crumbed = false;
@@ -89,7 +89,7 @@ function drawSide() {
89
89
  }
90
90
  function docRow(d) {
91
91
  const act = !d.act ? '' : d.act.kind === 'draft' ? `<button class="dmcta alt" data-draft="${esc(d.key)}"${d.running ? ' disabled' : ''}>${d.running ? '<span class="spin"></span>' : ICO('<path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/>')}${esc(d.act.label)}</button>` : `<button class="dmcta alt" data-tab="${esc(d.act.tab)}">${esc(d.act.label)}</button>`;
92
- return `<div class="dmr" role="listitem"><span class="dmo"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(d.title)}</b><small>${esc(d.what)}</small><span class="dmm"><span class="s ${esc(d.st || 'live')}">${ICO(STATE_ICO[d.state] || STATE_ICO['Not started'])}${esc(d.state)}</span>${d.cadence ? `<span>${ICO('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>')}${esc(d.cadence)}</span>` : ''}${d.by ? `<span>${ICO('<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>')}${esc(d.by)}</span>` : ''}</span></span></span><span class="dmq">${act}</span></div>`;
92
+ return `<div class="dmr" role="listitem"><span class="dmo"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(d.title)}</b><small>${esc(d.what)}</small><span class="dmm"><span class="s ${esc(d.st || 'live')}">${ICO(STATE_ICO[d.state] || STATE_ICO['Not started'])}${esc(d.state)}</span>${d.added ? `<span>${ICO('<rect x="3" y="5" width="18" height="16" rx="3"/><path d="M3 10h18M8 3v4M16 3v4"/>')}added ${esc(d.added)}</span>` : ''}${d.cadence ? `<span>${ICO('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>')}${esc(d.cadence)}</span>` : ''}${d.by ? `<span>${ICO('<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>')}${esc(d.by)}</span>` : ''}</span></span></span><span class="dmq">${act}</span></div>`;
93
93
  }
94
94
  let docFilter = 'all', docQuery = '';
95
95
  const draftable = () => (M.docs.rows || []).filter((d) => d.st === 'missing' && d.act && d.act.kind === 'draft' && !d.running);
@@ -101,11 +101,12 @@ function drawDocList() {
101
101
  }
102
102
  function drawDocs() {
103
103
  const D = M.docs, c = D.counts;
104
+ $('#addDoc').hidden = !D.scope;
104
105
  $('#docCap').textContent = D.rows.length ? String(c.all) : '';
105
106
  if (!D.rows.length) { $('#docTop').innerHTML = ''; $('#docBody').innerHTML = `<p class="empty3 plain">${D.missing ? 'The core documents could not be read, so none is shown.' : 'No core documents are on record for this board.'}</p>`; $('#docNote').textContent = ''; return; }
106
107
  const dot = { ok: 'ok', draft: 'warn', missing: 'mut' };
107
108
  const hadQ = $('#dmQ') && document.activeElement === $('#dmQ');
108
- $('#docTop').innerHTML = `<p class="dsum"><span><b>${c.draft}</b> ${c.draft === 1 ? 'draft' : 'drafts'} to review</span><span><b>${c.none}</b> not started</span><span><b>${c.ok}</b> up to date</span>${draftable().length > 1 ? `<button class="dlink" data-draftall="1">${ICO('<path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/>')}Draft the ${draftable().length} not started</button>` : ''}</p>
109
+ $('#docTop').innerHTML = `<p class="dsum"><span><b>${c.draft}</b> ${c.draft === 1 ? 'draft' : 'drafts'} to review</span><span><b>${c.none}</b> not started</span><span><b>${c.ok}</b> up to date</span>${c.linked ? `<span><b>${c.linked}</b> linked</span>` : ''}${draftable().length > 1 ? `<button class="dlink" data-draftall="1">${ICO('<path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/>')}Draft the ${draftable().length} not started</button>` : ''}</p>
109
110
  <div class="dprog" role="img" aria-label="${c.ok} of ${c.all} up to date">${D.rows.map((d) => `<i class="${dot[d.st] || (d.st === 'live' ? 'ok' : 'mut')}"></i>`).join('')}</div>
110
111
  <div class="dtool"><div class="seg" id="dmF" role="group" aria-label="Filter documents"><i class="pill"></i>${[['all', 'All', c.all], ['none', 'Not started', c.none], ['draft', 'Draft', c.draft], ['ok', 'Up to date', c.ok]].map(([k, l, n]) => `<button data-dmf="${k}" aria-pressed="${docFilter === k}">${l}<em>${n}</em></button>`).join('')}</div>
111
112
  <label class="dmsr">${ICO('<circle cx="11" cy="11" r="6.5"/><path d="m20 20-4-4"/>')}<input id="dmQ" type="search" placeholder="Find a document" aria-label="Find a document" value="${esc(docQuery)}"></label></div>`;
@@ -134,6 +135,8 @@ $('#docBody').addEventListener('click', async (e) => {
134
135
  await load();
135
136
  });
136
137
 
138
+ $('#addDoc').onclick = () => openAddDoc({ ws: M.board.ws, scope: M.docs.scope, sub: M.board.name, onAdded: load });
139
+
137
140
  /* ── dock ───────────────────────────────────────────────────────────────────────────────────────────────── */
138
141
  function drawDock() { $('#dN').textContent = M.dock.needs; $('#dLab').textContent = M.dock.label; $('#dNext').innerHTML = M.dock.next ? `<i></i>First <b>${esc(M.dock.next)}</b>` : 'Nothing is late or at risk'; }
139
142
 
@@ -5,7 +5,7 @@
5
5
  * existing /api/doc-sheet routes, initiative briefing-premium-doc-edit), Add a task and a task's status. Nothing here issues a document or moves an initiative. */
6
6
  import { pmPost } from './http.js';
7
7
  import { proposalsModel, editBody, acceptBody, rejectBody, askBody, askLine } from './premium-doc-edit.js';
8
- import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, crumbHtml, wireCrumb, AI } from './premium-shell.js';
8
+ import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, crumbHtml, wireCrumb, AI, openAddDoc } from './premium-shell.js';
9
9
 
10
10
  let M = null; // the model
11
11
  let taskView = 'list';
@@ -16,7 +16,7 @@ wireRail('init');
16
16
  const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
17
17
  const DOCI = '<path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 13h6M9 17h4"/>';
18
18
  const SPARK = '<path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/>';
19
- const STATE_ICO = { Live: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>', 'Up to date': '<path d="M5 12.5l4.5 4.5L19 7.5"/>', Draft: '<path d="M4 20l4-1 11-11-3-3L5 16z"/>', 'Not started': '<circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16.5v.5"/>', Stale: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>', Due: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>' };
19
+ const STATE_ICO = { Linked: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>', Live: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>', 'Up to date': '<path d="M5 12.5l4.5 4.5L19 7.5"/>', Draft: '<path d="M4 20l4-1 11-11-3-3L5 16z"/>', 'Not started': '<circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16.5v.5"/>', Stale: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>', Due: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>' };
20
20
  const TKI = { jira: '<rect x="4" y="5" width="16" height="14" rx="3"/><path d="m8.5 12 2.5 2.5 4.5-5"/>', task: '<path d="M6 4v16M6 5h11l-2.5 4L17 13H6"/>', req: '<path d="M6 3h9l4 4v14H6z"/><path d="M9 12h6M9 16h4"/>' };
21
21
  const TONE = { Done: 'ok', 'In progress': 'wip', 'In review': 'wip', 'To do': 'mut' };
22
22
 
@@ -103,6 +103,7 @@ function tasksHtml() {
103
103
  $('#iMain').addEventListener('click', (e) => {
104
104
  const v = e.target.closest('#tkTabs [data-v]'); if (v) { taskView = v.dataset.v; $('#tkBody').innerHTML = tasksBody(); $$('#tkTabs button').forEach((b) => b.setAttribute('aria-pressed', b.dataset.v === taskView)); pillOf($('#tkTabs')); return; }
105
105
  if (e.target.closest('[data-tkadd]')) { openAddTask(); return; }
106
+ if (e.target.closest('[data-adddoc]')) { openAddDoc({ ws: M.board.ws, scope: M.docs.scope, sub: M.title, onAdded: async () => { await load(); const b = $('[data-adddoc]'); if (b) b.focus(); } }); return; }
106
107
  const t = e.target.closest('[data-task]'); if (t) { openTask(M.tasks.rows.find((x) => x.key === t.dataset.task)); return; }
107
108
  const f = e.target.closest('[data-dmf]'); if (f) { docFilter = f.dataset.dmf; drawDocList(); return; }
108
109
  const d = e.target.closest('[data-draft]'); if (d && !d.disabled) { draft(d); return; }
@@ -153,7 +154,7 @@ function openAddTask() {
153
154
  /* ── documents ──────────────────────────────────────────────────────────────────────────────────────────── */
154
155
  function docRow(d) {
155
156
  const act = d.act && d.act.kind === 'draft' ? `<button class="dmcta alt" data-draft="${esc(d.key)}"${d.running ? ' disabled' : ''}>${d.running ? '<span class="spin"></span>' : ICO(SPARK)}${esc(d.act.label)}</button>` : d.path ? `<button class="dmcta alt" data-doc="${esc(d.key)}">Read</button>` : '';
156
- const inner = `<span class="dmi c-${esc(d.cat || 'Board')}">${ICO(DOCI)}</span><span class="dmn"><b>${esc(d.title)}</b><small>${esc(d.what)}</small><span class="dmm"><span class="s ${esc(d.st || 'live')}">${ICO(STATE_ICO[d.state] || STATE_ICO['Not started'])}${esc(d.state)}</span>${d.when ? `<span>${ICO('<rect x="3" y="5" width="18" height="16" rx="3"/><path d="M3 10h18M8 3v4M16 3v4"/>')}updated ${esc(d.when)}</span>` : ''}${d.by ? `<span>${ICO('<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>')}${esc(d.by)}</span>` : ''}</span></span>`;
157
+ const inner = `<span class="dmi c-${esc(d.cat || 'Board')}">${ICO(DOCI)}</span><span class="dmn"><b>${esc(d.title)}</b><small>${esc(d.what)}</small><span class="dmm"><span class="s ${esc(d.st || 'live')}">${ICO(STATE_ICO[d.state] || STATE_ICO['Not started'])}${esc(d.state)}</span>${d.when ? `<span>${ICO('<rect x="3" y="5" width="18" height="16" rx="3"/><path d="M3 10h18M8 3v4M16 3v4"/>')}updated ${esc(d.when)}</span>` : ''}${d.added ? `<span>${ICO('<rect x="3" y="5" width="18" height="16" rx="3"/><path d="M3 10h18M8 3v4M16 3v4"/>')}added ${esc(d.added)}</span>` : ''}${d.by ? `<span>${ICO('<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>')}${esc(d.by)}</span>` : ''}</span></span>`;
157
158
  return `<div class="dmr ${esc(d.st || '')}" role="listitem">${d.path ? `<button class="dmo" data-doc="${esc(d.key)}" aria-haspopup="dialog">${inner}</button>` : `<span class="dmo">${inner}</span>`}<span class="dmq">${act}</span></div>`;
158
159
  }
159
160
  const matches = (d) => (docFilter === 'all' || (docFilter === 'none' ? d.st === 'missing' : docFilter === 'draft' ? d.st === 'draft' : (d.st === 'ok' || d.st === 'live'))) && (!docQuery.trim() || (d.title + ' ' + d.what).toLowerCase().includes(docQuery.trim().toLowerCase()));
@@ -166,16 +167,16 @@ function drawDocList() {
166
167
  }
167
168
  function docsHtml() {
168
169
  const D = M.docs, c = D.counts;
169
- if (!D.rows.length) return `<section class="card rise ifull" style="--d:6" id="cIniDoc" aria-labelledby="hDoc"><div class="ch"><span class="ic">${ICO(DOCI)}</span><h2 id="hDoc">Core documents</h2></div><p class="empty3 plain">${D.missing ? 'The core documents could not be read, so none is shown.' : 'No core documents are on record for this initiative.'}</p></section>`;
170
+ if (!D.rows.length) return `<section class="card rise ifull" style="--d:6" id="cIniDoc" aria-labelledby="hDoc"><div class="ch"><span class="ic">${ICO(DOCI)}</span><h2 id="hDoc">Core documents</h2><button class="fold alt dmadd2" data-adddoc="1" type="button">Add a document</button></div><p class="empty3 plain">${D.missing ? 'The core documents could not be read, so none is shown.' : 'No core documents are on record for this initiative.'}</p></section>`;
170
171
  const dot = { ok: 'ok', draft: 'warn', missing: 'mut' };
171
172
  const core = D.rows.filter((d) => !d.tech);
172
- return `<section class="card rise ifull" style="--d:6" id="cIniDoc" aria-labelledby="hDoc"><div class="ch"><span class="ic">${ICO(DOCI)}</span><h2 id="hDoc">Core documents</h2><small>${c.all}</small></div>
173
- <p class="dsum"><span><b>${c.draft}</b> ${c.draft === 1 ? 'draft' : 'drafts'} to review</span><span><b>${c.none}</b> not started</span><span><b>${c.ok}</b> up to date</span>${draftable().length > 1 ? `<button class="dlink" data-draftall="1">${ICO(SPARK)}Draft the ${draftable().length} not started</button>` : ''}</p>
173
+ return `<section class="card rise ifull" style="--d:6" id="cIniDoc" aria-labelledby="hDoc"><div class="ch"><span class="ic">${ICO(DOCI)}</span><h2 id="hDoc">Core documents</h2><small>${c.all}</small><button class="fold alt dmadd2" data-adddoc="1" type="button">Add a document</button></div>
174
+ <p class="dsum"><span><b>${c.draft}</b> ${c.draft === 1 ? 'draft' : 'drafts'} to review</span><span><b>${c.none}</b> not started</span><span><b>${c.ok}</b> up to date</span>${c.linked ? `<span><b>${c.linked}</b> linked</span>` : ''}${draftable().length > 1 ? `<button class="dlink" data-draftall="1">${ICO(SPARK)}Draft the ${draftable().length} not started</button>` : ''}</p>
174
175
  <div class="dprog" role="img" aria-label="${c.ok} of ${c.all} up to date">${core.map((d) => `<i class="${dot[d.st] || (d.st === 'live' ? 'ok' : 'mut')}"></i>`).join('')}</div>
175
176
  <div class="dtool"><div class="seg" id="dmF" role="group" aria-label="Filter documents"><i class="pill"></i>${[['all', 'All', c.all], ['none', 'Not started', c.none], ['draft', 'Draft', c.draft], ['ok', 'Up to date', c.ok]].map(([k, l, n]) => `<button data-dmf="${k}" aria-pressed="${docFilter === k}">${l}<em>${n}</em></button>`).join('')}</div>
176
177
  <label class="dmsr">${ICO('<circle cx="11" cy="11" r="6.5"/><path d="m20 20-4-4"/>')}<input id="dmQ" type="search" placeholder="Find a document" aria-label="Find a document" value="${esc(docQuery)}"></label></div>
177
178
  <div id="dmList"></div>
178
- <p class="note" style="margin-top:12px">The core documents of this initiative. Press a row to read it, see its edit log or its health. Draft it starts a read-only agent run that writes a draft for you to read; nothing is sent. Editing, issuing and dropping a document are not built on this page.</p></section>`;
179
+ <p class="note" style="margin-top:12px">The core documents of this initiative. Press a row to read it, see its edit log or its health. Draft it starts a read-only agent run that writes a draft for you to read; nothing is sent. Editing, issuing and dropping a document are not built on this page. A document you add is saved on the record; PMOS does not read a linked page.</p></section>`;
179
180
  }
180
181
  $('#iMain').addEventListener('input', (e) => { if (e.target.id === 'dmQ') { docQuery = e.target.value; drawDocList(); } });
181
182
  const draftable = () => M.docs.rows.filter((d) => !d.tech && d.st === 'missing' && d.act && d.act.kind === 'draft' && !d.running);
@@ -182,3 +182,32 @@ export function wireCrumb(o) {
182
182
  });
183
183
  $('#crAsk').onclick = () => o.ask && o.ask();
184
184
  }
185
+
186
+ /* ── Add a document: the dialog the Board and the initiative page share (initiative briefing-premium-adddoc) ──────────────────────────────────
187
+ * o = { ws, scope: 'board:<id>' | 'initiative:<id>', sub, onAdded }. The one press posts to POST /api/custom-docs/add and nothing else. */
188
+ export function openAddDoc(o) {
189
+ const ini = String(o.scope).startsWith('initiative:'), phases = ['Discover', 'Plan', 'Build', 'Evaluate'];
190
+ const form = `<div class="addf"><p class="note" style="margin:0">Add a document the core set does not cover, for example a research plan, a UAT plan or a contract. It is saved on the ${ini ? 'initiative' : 'board'}'s record with the address of a copy that lives in Confluence or Google Docs. PMOS does not read or sync that page.</p>
191
+ <label>Title<input id="adT" maxlength="80" placeholder="For example: UAT plan"></label>
192
+ ${ini ? `<label>Phase<select id="adC">${phases.map((k) => `<option>${k}</option>`).join('')}</select></label>` : ''}
193
+ <div><span class="label">Who writes it</span><div class="seg" id="adW" role="group" aria-label="Who writes it"><i class="pill"></i><button type="button" data-w="drafts" aria-pressed="true">PMOS drafts it</button><button type="button" data-w="you" aria-pressed="false">I write it</button></div></div>
194
+ <div><span class="label">Where it lives</span><div class="two"><label><select id="adK" aria-label="Where it lives"><option value="">In PMOS</option><option>Confluence</option><option>Google Docs</option><option>Google Slides</option></select></label><label><input id="adU" maxlength="300" placeholder="Paste the page address" aria-label="Page address" disabled></label></div></div>
195
+ <p class="note" id="adM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="adGo">Add document</button><button class="cta alt" id="adNo">Cancel</button></div></div>`;
196
+ openDlg({ eye: 'New document · real data', title: 'Add a document', sub: o.sub, say: 'Name the document and say who writes it. It is saved on the record.', stream: turnA(ptx('Name the document and say who writes it. I save it on the record and change nothing else. A linked page is kept as an address only.')), noteKey: null, pane: `<article class="paper doc">${form}</article>`, label: 'Document' });
197
+ $('#askF').hidden = true; pillOf($('#adW'));
198
+ let who = 'drafts';
199
+ $('#oMain').onchange = (e) => { if (e.target.id === 'adK') { $('#adU').disabled = !e.target.value; if (e.target.value) $('#adU').focus(); } };
200
+ $('#oMain').onclick = async (e) => {
201
+ const w = e.target.closest('[data-w]');
202
+ if (w) { who = w.dataset.w; $$('#adW button').forEach((x) => x.setAttribute('aria-pressed', x === w)); pillOf($('#adW')); return; }
203
+ if (e.target.closest('#adNo')) { closeDlg(); return; }
204
+ if (!e.target.closest('#adGo')) return;
205
+ const title = $('#adT').value.trim(), m = $('#adM'), kind = $('#adK').value, url = ($('#adU').value || '').trim();
206
+ if (!title) { m.textContent = 'Give the document a title.'; $('#adT').focus(); return; }
207
+ if (kind && !url) { m.textContent = 'Paste the address of the ' + kind + ' page, or choose In PMOS.'; $('#adU').focus(); return; }
208
+ const go = $('#adGo'); go.disabled = true;
209
+ const res = await pmPost('/api/custom-docs/add', { ws: o.ws, scope: o.scope, title, writer: who, phase: ini ? document.getElementById('adC').value : undefined, kind: kind || undefined, url: kind ? url : undefined });
210
+ if (!res || res.ok !== true) { go.disabled = false; m.textContent = (res && res.error) || 'The document could not be added.'; return; }
211
+ toast('Document added. It is saved on the record.'); closeDlg(); if (o.onAdded) await o.onAdded();
212
+ };
213
+ }
@@ -151,6 +151,8 @@ input[type=range]:active::-webkit-slider-thumb{transform:scale(1.15)}
151
151
  .dbody .kv{display:grid;grid-template-columns:110px minmax(0,1fr);gap:6px 14px;font-size:15px}
152
152
  .dbody .kv span:nth-child(odd){color:var(--ink-3)}
153
153
  .cta{height:48px;padding:0 24px;border-radius:var(--r-chip);background:var(--solid);color:var(--on-solid);font-weight:650;display:inline-flex;align-items:center;gap:8px;transition:transform .35s var(--spring)}
154
+ .cta.alt{background:var(--well);color:var(--ink)}
155
+ .cta.alt{background:var(--card)}
154
156
  a.cta{text-decoration:none}
155
157
  .cta:hover{transform:translateY(-2px)}
156
158
  .cta:active{transform:scale(.97)}
@@ -754,7 +756,7 @@ a.cta{text-decoration:none}
754
756
  .dmi.c-Board{background:color-mix(in oklab,rgb(79,109,245) 12%,transparent);color:rgb(58,84,214)}
755
757
  .dmn{display:grid;gap:3px;min-width:0}
756
758
  .dmn b{font-size:15px;font-weight:650;line-height:1.3;display:flex;gap:8px;align-items:center;flex-wrap:wrap}
757
- .dmn>small{font-size:12.5px;line-height:1.45;color:var(--ink-2)}
759
+ .dmn>small{font-size:12.5px;line-height:1.45;color:var(--ink-2);overflow-wrap:anywhere}
758
760
  .dmadd{font-style:normal;font:700 12.5px var(--mono);letter-spacing:.08em;text-transform:uppercase;padding:2px 8px;border-radius:999px;background:var(--well);color:var(--ink-2)}
759
761
  .dmm{display:flex;gap:4px 16px;flex-wrap:wrap;margin-top:3px;font:500 12.5px var(--mono);color:var(--ink-3)}
760
762
  .dmm>span{display:inline-flex;align-items:center;gap:6px}
@@ -66,12 +66,12 @@
66
66
  </div>
67
67
  </div>
68
68
  <section class="card rise" style="--d:8;margin-top:24px" id="cDocs" aria-labelledby="hDocs">
69
- <div class="ch"><span class="ic"><svg class="i" viewBox="0 0 24 24"><path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 13h6M9 17h4"/></svg></span><h2 id="hDocs">Core documents</h2><small id="docCap"></small></div>
69
+ <div class="ch"><span class="ic"><svg class="i" viewBox="0 0 24 24"><path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 13h6M9 17h4"/></svg></span><h2 id="hDocs">Core documents</h2><small id="docCap"></small><button class="fold alt dmadd2" id="addDoc" type="button" hidden>Add a document</button></div>
70
70
  <div id="docTop"></div>
71
71
  <div class="dmg two" id="docBody" role="list"></div>
72
72
  <p class="note" id="docNote" style="margin-top:12px"></p>
73
73
  </section>
74
- <p class="foot" id="foot">This page reads the board's own records, the same ones the Initiatives page reads. Its one press is Draft it on a core document, which starts the existing read-only run that writes a draft and sends nothing. Issue, Drop and moving an initiative are not built here. The Metrics charts are not drawn, because PMOS holds no metric series for a board. A sprint appears only when a session has read Jira.</p>
74
+ <p class="foot" id="foot">This page reads the board's own records, the same ones the Initiatives page reads. Its presses are Draft it on a core document, which starts the existing read-only run that writes a draft and sends nothing, and Add a document, which saves a document on the board's record. Issue, Drop and moving an initiative are not built here. The Metrics charts are not drawn, because PMOS holds no metric series for a board. A sprint appears only when a session has read Jira.</p>
75
75
  </main>
76
76
  <noscript>This page needs JavaScript.</noscript>
77
77
  <script type="module" src="/pm/premium-board.js"></script>
@@ -38,7 +38,7 @@
38
38
  </header>
39
39
  <section class="hero hero-slim"><p class="brief rise" style="--d:2" id="brief" aria-live="polite"></p></section>
40
40
  <div id="iMain"><p class="empty3 plain" id="iRead">The initiative is read from its records. This page shows nothing until it has read, rather than guess.</p></div>
41
- <p class="foot" id="foot">This page reads the initiative's own records, the same ones the Initiatives sheet reads. Its one press is Draft it on a core document, which starts the existing read-only run that writes a draft and sends nothing. Opening a document only reads it. Editing, Issue, Drop and adding a task are not built on this page.</p>
41
+ <p class="foot" id="foot">This page reads the initiative's own records, the same ones the Initiatives sheet reads. Its presses are Draft it on a core document, which starts the existing read-only run that writes a draft and sends nothing, Add a task, and Add a document, which saves a document on the initiative's record. Opening a document only reads it. Editing, Issue and Drop are not built on this page.</p>
42
42
  </main>
43
43
  <noscript>This page needs JavaScript.</noscript>
44
44
  <script type="module" src="/pm/premium-initiative.js"></script>
@@ -42,6 +42,7 @@
42
42
  "briefing-premium-board.test.js",
43
43
  "briefing-premium-insights.test.js",
44
44
  "briefing-premium-initiative.test.js",
45
+ "briefing-premium-adddoc.test.js",
45
46
  "briefing-premium-doc-edit.test.js",
46
47
  "briefing-premium-products.test.js",
47
48
  "briefing-premium-sources.test.js",
@@ -206,6 +207,7 @@
206
207
  "briefing-premium-board.test.js": 1,
207
208
  "briefing-premium-insights.test.js": 1,
208
209
  "briefing-premium-initiative.test.js": 1,
210
+ "briefing-premium-adddoc.test.js": 1,
209
211
  "briefing-premium-doc-edit.test.js": 1,
210
212
  "briefing-premium-products.test.js": 1,
211
213
  "briefing-premium-sources.test.js": 1,
@@ -6,6 +6,7 @@
6
6
  "briefing-premium-board-test.js",
7
7
  "briefing-premium-insights-test.js",
8
8
  "briefing-premium-initiative-test.js",
9
+ "briefing-premium-adddoc-test.js",
9
10
  "briefing-premium-doc-edit-test.js",
10
11
  "briefing-premium-products-test.js",
11
12
  "briefing-premium-sources-test.js",
@@ -18,6 +19,7 @@
18
19
  "briefing-premium-board-test.js": 120,
19
20
  "briefing-premium-insights-test.js": 90,
20
21
  "briefing-premium-initiative-test.js": 120,
22
+ "briefing-premium-adddoc-test.js": 120,
21
23
  "briefing-premium-doc-edit-test.js": 90,
22
24
  "briefing-premium-products-test.js": 90,
23
25
  "briefing-premium-sources-test.js": 90,