create-pmos 0.381.0 → 0.383.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +30 -40
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/REMOTE.md +39 -0
  7. package/workspace/briefing-premium-calendar-test.js +1 -1
  8. package/workspace/briefing-premium-initiative-test.js +2 -2
  9. package/workspace/briefing-premium-test.js +1 -1
  10. package/workspace/changelog.json +29 -0
  11. package/workspace/guide/briefing-premium.md +5 -1
  12. package/workspace/lib/briefing-premium-agent.js +19 -9
  13. package/workspace/lib/routes-briefing-premium.js +1 -1
  14. package/workspace/lib/share-store.js +150 -0
  15. package/workspace/package-lock.json +2 -2
  16. package/workspace/package.json +1 -1
  17. package/workspace/premium-viewer-download-test.js +179 -0
  18. package/workspace/premium-viewer-share-test.js +208 -0
  19. package/workspace/premium-work-depth-test.js +1 -1
  20. package/workspace/public/pm/premium-acts.js +3 -4
  21. package/workspace/public/pm/premium-initiative.js +6 -8
  22. package/workspace/public/pm/premium-insights.js +5 -7
  23. package/workspace/public/pm/premium-meeting.js +1 -2
  24. package/workspace/public/pm/premium-report-read.js +4 -3
  25. package/workspace/public/pm/premium-shell.js +16 -7
  26. package/workspace/public/pm/premium-vw-doc.css +44 -0
  27. package/workspace/public/pm/premium-vw-file.js +95 -6
  28. package/workspace/public/pm/premium-vw-share.js +112 -0
  29. package/workspace/public/pm/premium-work.js +4 -4
  30. package/workspace/public/pm/premium.css +1 -1
  31. package/workspace/public/pm/premium.js +7 -7
  32. package/workspace/server.js +82 -0
  33. package/workspace/share-server.js +135 -0
  34. package/workspace/test-lists/premium-viewer-share.json +11 -0
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-viewer-download-test.js — a file in the viewer has a download icon (premium-viewer-share slice 1, PM 2026-10-21: "I should be able to download
4
+ * or share"). public/pm/premium-vw-file.js draws the icon at the right of the file's title; GET /api/doc/export builds Word from a markdown file.
5
+ * W1 downloadsOf(): .html = HTML, PDF · markdown = Markdown, Word .docx, PDF · other text = the original alone · nothing for a file not read
6
+ * W2 printSrc(): the CSP comes first, the page prints itself once loaded, markdown prints as a page of its words
7
+ * W3 GET /api/doc/export: a markdown file becomes a .docx holding its words; outside the workspace 404, not markdown 400, fmt other than docx 400,
8
+ * POST 405, never cached
9
+ * W4 the real premium page: an .html file's icon opens a menu (HTML, PDF); HTML saves the file's own text under its name; PDF prints in a frame
10
+ * sandboxed to scripts and modals, never same-origin; Escape closes the menu and gives the icon focus back
11
+ * W5 a markdown file's menu is Markdown, Word .docx, PDF; Word asks the export route for that file and saves <name>.docx
12
+ * W6 a .js file saves at once, with no menu
13
+ * W7 at 390 the icon is a 44 px target and the page does not scroll sideways
14
+ * PMOS_SHOTS=<dir> also saves the viewer with the menu open at 1280 and 390, light and dark. */
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const { spawn } = require('child_process');
18
+ const { findBrowser } = require('./lib/find-browser');
19
+ const T = require('./test-run').configure({ name: 'premium-viewer-download' });
20
+
21
+ const BASE = T.BASE;
22
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
23
+ 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); } };
24
+ const results = [];
25
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 600) : ''}`); };
26
+ let srv = null; let browser = null;
27
+ const finish = async (code) => {
28
+ if (browser) await browser.close().catch(() => {});
29
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
30
+ T.killTmux();
31
+ const bad = results.filter((x) => !x.cond).length;
32
+ console.log(`\n${results.length - bad}/${results.length} premium-viewer-download assertions passed`);
33
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
34
+ };
35
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
36
+
37
+ const HTMLF = 'pmos/state/reports/leadership/2026-10-19-leadership.html';
38
+ const MDF = 'pmos/state/notes/2026-10-19.md';
39
+ const JSF = 'workspace/lib/a.js';
40
+ const FILES = {
41
+ [HTMLF]: { kind: 'html', text: '<!doctype html><html><head><title>Leadership</title></head><body><h1>Leadership update</h1><p>Three on track.</p></body></html>' },
42
+ [MDF]: { kind: 'markdown', text: '# Weekly notes\n\nThe **sign-up** rate is 38%.\n\n## Next\n\n- Ship the download icon\n' },
43
+ [JSF]: { kind: 'text', text: 'const a = 1;\n' },
44
+ };
45
+ const SHOTS = process.env.PMOS_SHOTS || '';
46
+
47
+ (async () => {
48
+ {
49
+ const M = await import('./public/pm/premium-vw-file.js');
50
+ const fmts = (f) => M.downloadsOf(f).map((o) => o.fmt + ':' + o.label).join();
51
+ ok('W1 an .html file offers HTML, then PDF', fmts({ name: 'r.html', kind: 'html', text: 'x' }) === 'orig:HTML,pdf:PDF', fmts({ name: 'r.html', kind: 'html', text: 'x' }));
52
+ ok('W1 a markdown file offers Markdown, Word .docx, PDF', fmts({ name: 'n.md', kind: 'markdown', text: 'x' }) === 'orig:Markdown,docx:Word .docx,pdf:PDF');
53
+ ok('W1 any other text file offers only the original', fmts({ name: 'a.json', kind: 'text', text: '{}' }) === 'orig:.json file');
54
+ ok('W1 a file still reading, missing or unreadable offers nothing', !M.downloadsOf({ loading: true }).length && !M.downloadsOf({ reason: 'missing' }).length && !M.downloadsOf({ err: 'x' }).length);
55
+ const h = M.printSrc({ name: 'r.html', kind: 'html', text: '<!doctype html><p>x</p>' }), m = M.printSrc({ name: 'n.md', kind: 'markdown', text: '# Notes\n\nThe **rate** is 38%.' });
56
+ ok('W2 the print page keeps the CSP first and prints itself on load', h.startsWith('<!doctype html><meta http-equiv="Content-Security-Policy"') && /addEventListener\("load"[\s\S]*print\(\)/.test(h), h.slice(0, 200));
57
+ ok('W2 markdown prints as a page of its words', /<h1>Notes<\/h1>/.test(m) && /<strong>rate<\/strong>/.test(m) && m.includes(M.FRAME_CSP), m.slice(0, 300));
58
+ ok('W1 the title row of a read file carries the download icon', /data-fdl/.test(M.fileHtml({ name: 'n.md', kind: 'markdown', text: '# N', rel: 'n.md' })) && !/data-fdl/.test(M.fileHtml({ loading: true })));
59
+ }
60
+ const exe = findBrowser();
61
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the premium-viewer-download suite cannot run'); return finish(1); }
62
+ let chromium;
63
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed — the premium-viewer-download suite cannot run'); return finish(1); }
64
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore', env: T.env({ PMOS_WS_PORT: String(T.PORT) }) });
65
+ await T.waitForServer(BASE);
66
+
67
+ // W3 the export route, against the real server and a markdown file of this repository (the home workspace)
68
+ {
69
+ const PRD = 'planning/prd/premium-viewer-share-prd.md';
70
+ const r = await fetch(BASE + '/api/doc/export?path=' + encodeURIComponent(PRD) + '&fmt=docx');
71
+ const buf = Buffer.from(await r.arrayBuffer());
72
+ let words = '';
73
+ try { const RX = require('./lib/report-export.js'); const doc = RX.unzip(buf).find((e) => e.name === 'word/document.xml'); words = doc ? doc.data.toString('utf8') : ''; } catch (e) { words = String(e); }
74
+ ok('W3 a markdown file comes back as a .docx holding its words', r.status === 200 && /wordprocessingml/.test(r.headers.get('content-type') || '') && /filename="premium-viewer-share-prd\.docx"/.test(r.headers.get('content-disposition') || '') && /Download and share a file from the viewer/.test(words), r.status + ' ' + r.headers.get('content-disposition') + ' ' + words.slice(0, 120));
75
+ ok('W3 the file is never cached', r.headers.get('cache-control') === 'no-store');
76
+ const st = async (q, o) => (await fetch(BASE + '/api/doc/export?' + q, o)).status;
77
+ ok('W3 a path outside the workspace answers 404', await st('path=' + encodeURIComponent('../../../etc/hosts') + '&fmt=docx') === 404);
78
+ ok('W3 a file that is not markdown answers 400', await st('path=workspace%2Fpackage.json&fmt=docx') === 400);
79
+ ok('W3 any fmt but docx answers 400', await st('path=' + encodeURIComponent(PRD) + '&fmt=pdf') === 400 && await st('path=' + encodeURIComponent(PRD)) === 400);
80
+ ok('W3 the route is GET only', await st('path=' + encodeURIComponent(PRD) + '&fmt=docx', { method: 'POST' }) === 405);
81
+ }
82
+
83
+ browser = await chromium.launch({ executablePath: exe });
84
+ const open = async ({ w = 1280, h = 900, theme = 'light' } = {}) => {
85
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: theme, acceptDownloads: true });
86
+ const page = await ctx.newPage();
87
+ const errors = []; const asked = [];
88
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
89
+ const json = (body) => (r) => r.fulfill({ contentType: 'application/json', body: JSON.stringify(body) });
90
+ await page.route('**/api/brief-page*', json({ ok: false, error: 'off in this suite' }));
91
+ await page.route('**/api/doc/locate*', (r) => {
92
+ const p = new URL(r.request().url()).searchParams.get('path'), f = FILES[p];
93
+ return json(f ? { ok: true, ws: 'w0', rel: p, abs: '/Users/pm/pmos/' + p, name: p.split('/').pop(), mtime: 1, size: f.text.length } : { ok: false, reason: 'missing', why: 'No such file.' })(r);
94
+ });
95
+ await page.route('**/api/doc?*', (r) => {
96
+ const f = FILES[new URL(r.request().url()).searchParams.get('path')];
97
+ return r.fulfill({ status: 200, contentType: f.kind === 'markdown' ? 'text/markdown' : 'text/plain', headers: { 'X-Doc-Kind': f.kind }, body: f.text });
98
+ });
99
+ await page.route('**/api/doc/export*', (r) => r.fulfill({ status: 200, contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', headers: { 'Content-Disposition': 'attachment; filename="2026-10-19.docx"' }, body: 'PK' }));
100
+ await page.goto(BASE + '/premium.html?theme=' + theme);
101
+ await until(() => page.evaluate(() => !!document.querySelector('#dlg')), 15000);
102
+ await page.evaluate(async () => {
103
+ const S = await import('/pm/premium-shell.js');
104
+ S.openDlg({ eye: 'Your item', title: 'Leadership update', say: 'The report is an HTML file in the repo.', noteKey: null, pane: '<article class="paper doc"><p>Item record</p></article>', label: 'Item record' });
105
+ });
106
+ return { ctx, page, errors, asked };
107
+ };
108
+ const press = (page, file) => page.evaluate((f) => {
109
+ const b = document.createElement('button'); b.type = 'button'; b.className = 'fpath'; b.dataset.file = f; b.textContent = f;
110
+ document.querySelector('#dBody .stream').append(b); b.click();
111
+ }, file);
112
+ const ICON = '#dOut .obody.vw:not([hidden]) [data-fdl]';
113
+ const menu = (page) => page.evaluate(() => [...document.querySelectorAll('#dOut .obody.vw:not([hidden]) .vwdlm [data-fmt]')].map((b) => b.dataset.fmt + ':' + b.querySelector('span').textContent).join());
114
+
115
+ {
116
+ const { page, errors, asked, ctx } = await open();
117
+ await press(page, HTMLF);
118
+ await until(() => page.$(ICON), 8000);
119
+ const where = await page.evaluate((s) => { const b = document.querySelector(s), t = b && b.closest('.vwfh').querySelector('.cft'); return b && t ? { right: b.getBoundingClientRect().left > t.getBoundingClientRect().left, label: b.getAttribute('aria-label'), exp: b.getAttribute('aria-expanded') } : null; }, ICON);
120
+ ok('W4 the .html file shows a download icon at the right of its title', where && where.right && /^Download/.test(where.label) && where.exp === 'false', JSON.stringify(where));
121
+ await page.click(ICON);
122
+ const m1 = await until(() => menu(page), 3000);
123
+ ok('W4 the icon opens a menu: HTML, then PDF', m1 === 'orig:HTML,pdf:PDF', m1);
124
+ ok('W4 the menu takes focus on its first choice', await page.evaluate(() => document.activeElement && document.activeElement.dataset.fmt === 'orig'));
125
+ const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click('#dOut .vwdlm [data-fmt="orig"]')]);
126
+ const body = dl ? fs.readFileSync(await dl.path(), 'utf8') : '';
127
+ ok('W4 HTML saves the file\'s own text under its own name', dl && dl.suggestedFilename() === '2026-10-19-leadership.html' && body === FILES[HTMLF].text, dl ? dl.suggestedFilename() + ' ' + body.slice(0, 60) : 'no download');
128
+ ok('W4 the menu closes after a choice', !(await page.$('#dOut .vwdlm')));
129
+ await page.click(ICON);
130
+ await until(() => menu(page), 3000);
131
+ await page.click('#dOut .vwdlm [data-fmt="pdf"]');
132
+ const pf = await until(() => page.evaluate(() => { const f = document.querySelector('iframe.vwprint'); return f ? { sb: f.getAttribute('sandbox'), src: f.srcdoc } : null; }), 3000);
133
+ ok('W4 PDF prints in a frame sandboxed to scripts and modals, never same-origin', pf && pf.sb === 'allow-scripts allow-modals' && /print\(\)/.test(pf.src) && /Leadership update/.test(pf.src) && /default-src 'none'/.test(pf.src), JSON.stringify(pf && { sb: pf.sb }));
134
+ await page.click(ICON);
135
+ await until(() => menu(page), 3000);
136
+ await page.keyboard.press('Escape');
137
+ const esc = await page.evaluate((s) => ({ gone: !document.querySelector('#dOut .vwdlm'), focus: document.activeElement === document.querySelector(s), dlg: !!document.querySelector('#dlg[open], #dlg.on, #dlg:not([hidden])') }), ICON);
138
+ ok('W4 Escape closes the menu and gives the icon focus back, the dialog stays', esc.gone && esc.focus && esc.dlg, JSON.stringify(esc));
139
+ await page.click(ICON);
140
+ await until(() => menu(page), 3000);
141
+ await page.click('#dOut .obody.vw:not([hidden]) .cft');
142
+ ok('W4 a press elsewhere closes the menu', !!(await until(() => page.evaluate(() => !document.querySelector('#dOut .vwdlm')), 2000)));
143
+
144
+ await press(page, MDF);
145
+ await until(() => page.evaluate(() => { const p = document.querySelector('#dOut .obody.vw:not([hidden]) .cfb'); return p && p.querySelector('strong'); }), 6000);
146
+ await page.click(ICON);
147
+ const m2 = await until(() => menu(page), 3000);
148
+ ok('W5 a markdown file\'s menu is Markdown, Word .docx, PDF', m2 === 'orig:Markdown,docx:Word .docx,pdf:PDF', m2);
149
+ const [dw] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click('#dOut .vwdlm [data-fmt="docx"]')]);
150
+ if (dw) asked.push(dw.url());
151
+ const q = asked[0] ? new URL(asked[0], BASE).searchParams : null;
152
+ ok('W5 Word asks the export route for that file and saves <name>.docx', dw && dw.suggestedFilename() === '2026-10-19.docx' && q && q.get('ws') === 'w0' && q.get('path') === MDF && q.get('fmt') === 'docx', (dw ? dw.suggestedFilename() : 'no download') + ' ' + asked.join());
153
+ await page.click(ICON);
154
+ await until(() => menu(page), 3000);
155
+ const [dm] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click('#dOut .vwdlm [data-fmt="orig"]')]);
156
+ ok('W5 Markdown saves the note\'s own text', dm && dm.suggestedFilename() === '2026-10-19.md' && fs.readFileSync(await dm.path(), 'utf8') === FILES[MDF].text, dm ? dm.suggestedFilename() : 'no download');
157
+
158
+ await press(page, JSF);
159
+ await until(() => page.evaluate(() => { const p = document.querySelector('#dOut .obody.vw:not([hidden]) .cb'); return p && p.dataset.lang === 'js'; }), 6000);
160
+ const [dj] = await Promise.all([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click(ICON)]);
161
+ ok('W6 a .js file saves at once, with no menu', dj && dj.suggestedFilename() === 'a.js' && !(await page.$('#dOut .vwdlm')) && !(await page.$eval(ICON, (b) => b.hasAttribute('aria-haspopup'))), dj ? dj.suggestedFilename() : 'no download');
162
+ ok('W4 no page errors', errors.length === 0, errors.join(' | '));
163
+ await ctx.close();
164
+ }
165
+
166
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const theme of ['light', 'dark']) {
167
+ const { page, ctx } = await open({ w, h, theme });
168
+ await press(page, HTMLF);
169
+ await until(() => page.$(ICON), 8000);
170
+ await sleep(300);
171
+ await page.click(ICON);
172
+ await until(() => menu(page), 3000);
173
+ const geo = await page.evaluate((s) => { const b = document.querySelector(s).getBoundingClientRect(), m = document.querySelector('#dOut .vwdlm').getBoundingClientRect(); return { bw: Math.round(b.width), bh: Math.round(b.height), mr: Math.round(m.right), ml: Math.round(m.left), mw: Math.round(m.width), vw: innerWidth, sx: document.documentElement.scrollWidth - innerWidth }; }, ICON);
174
+ ok(`W7 at ${w} ${theme} the icon is a ${w < 700 ? 44 : 36} px target and the menu fits on screen`, geo.bw >= (w < 700 ? 44 : 36) && geo.bh >= (w < 700 ? 44 : 36) && geo.ml >= 0 && geo.mr <= geo.vw && geo.mw >= 160 && geo.sx <= 0, JSON.stringify(geo));
175
+ if (SHOTS) { fs.mkdirSync(SHOTS, { recursive: true }); await sleep(200); await page.screenshot({ path: path.join(SHOTS, `menu-${w}-${theme}.png`) }); }
176
+ await ctx.close();
177
+ }
178
+ return finish();
179
+ })();
@@ -0,0 +1,208 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-viewer-share-test.js — share links from the viewer (premium-viewer-share slice 2, D97; PM 2026-10-21: "share (no need login to cloudflare,
4
+ * but I can set password)"). lib/share-store.js keeps the copies, POST /api/shares makes one on a page press, share-server.js serves them.
5
+ * K1 the store: 22-character ids, a scrypt hash and never the password, five wrong tries lock for 15 minutes, a link past its end is deleted,
6
+ * the cookie is signed per link and a changed one fails
7
+ * K2 the routes: an agent session and a request without the page's press headers are refused; a file with a secret is refused and the answer
8
+ * names the rule only; 1, 7 or 30 days only; a made link is listed with its password flag and no hash
9
+ * K3 the share server: the password page names neither the file nor PMOS; a wrong password counts down, five lock, the right one opens; the copy
10
+ * is under a sandbox CSP; Download gives the file's own text; every answer is noindex, no-store, no-referrer; any other path is 404
11
+ * K4 Turn off deletes the copy and the link answers "no longer active"; the workspace server refuses the share hostname
12
+ * K5 the page: the share icon opens the popover with a generated password and 7 days; Create link shows the link; a guest opens it with the
13
+ * password in a browser; Turn off asks once more, then removes it; at 390 the popover is a sheet that fits
14
+ * PMOS_SHOTS=<dir> also saves the popover at 1280 and 390, light and dark, and the guest's pages. */
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+ const http = require('http');
19
+ const { spawn } = require('child_process');
20
+ const { findBrowser } = require('./lib/find-browser');
21
+ const T = require('./test-run').configure({ name: 'premium-viewer-share' });
22
+ const store = require('./lib/share-store');
23
+
24
+ const BASE = T.BASE;
25
+ const SHARE_PORT = T.port();
26
+ const SBASE = `http://127.0.0.1:${SHARE_PORT}`;
27
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
28
+ 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); } };
29
+ const results = [];
30
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 600) : ''}`); };
31
+ let srv = null; let browser = null;
32
+ const REPO = path.resolve(__dirname, '..');
33
+ const SECRET_REL = `workspace/.share-test-${process.pid}.md`;
34
+ const finish = async (code) => {
35
+ if (browser) await browser.close().catch(() => {});
36
+ if (srv) { try { srv.kill('SIGTERM'); } catch { /* gone */ } }
37
+ try { fs.unlinkSync(path.join(REPO, SECRET_REL)); } catch { /* not made */ }
38
+ T.killTmux();
39
+ const bad = results.filter((x) => !x.cond).length;
40
+ console.log(`\n${results.length - bad}/${results.length} premium-viewer-share assertions passed`);
41
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
42
+ };
43
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
44
+ const req = (url, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve) => {
45
+ const u = new URL(url);
46
+ const r = http.request({ host: u.hostname, port: u.port, path: u.pathname + u.search, method, headers }, (res) => {
47
+ const parts = []; res.on('data', (c) => parts.push(c)); res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text: Buffer.concat(parts).toString('utf8') }));
48
+ });
49
+ r.on('error', (e) => resolve({ status: 0, headers: {}, text: String(e) }));
50
+ if (body) r.write(body);
51
+ r.end();
52
+ });
53
+ const PRD = 'planning/prd/premium-viewer-share-prd.md';
54
+ const SHOTS = process.env.PMOS_SHOTS || '';
55
+
56
+ (async () => {
57
+ // K1 the store, on its own folder
58
+ {
59
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'share-store-'));
60
+ const now = Date.parse('2026-10-21T10:00:00Z');
61
+ const a = store.create(dir, { name: 'n.md', kind: 'markdown', page: '<p>x</p>', file: '# x', days: 7, password: 'cedar-river-tulip-07', now });
62
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, 'shares', a.id, 'meta.json'), 'utf8'));
63
+ ok('K1 a link has a 22-character id and ends 7 days on', a.ok && store.ID_RX.test(a.id) && a.ends === '2026-10-28T10:00:00.000Z', JSON.stringify(a));
64
+ ok('K1 the password is kept as a scrypt hash, never as itself', /^scrypt\$/.test(meta.pw) && !fs.readFileSync(path.join(dir, 'shares', a.id, 'meta.json'), 'utf8').includes('cedar-river'));
65
+ ok('K1 only 1, 7 or 30 days, and a password of 8 or more', !store.create(dir, { name: 'n', kind: 'text', page: '', file: '', days: 365 }).ok && !store.create(dir, { name: 'n', kind: 'text', page: '', file: '', days: 7, password: 'short' }).ok);
66
+ const tries = [1, 2, 3, 4, 5].map(() => store.checkPassword(dir, a.id, 'wrong', now));
67
+ ok('K1 wrong tries count down and the fifth locks the link', tries.slice(0, 4).map((t) => t.left).join() === '4,3,2,1' && tries[4].locked, JSON.stringify(tries));
68
+ ok('K1 while locked even the right password is refused', store.checkPassword(dir, a.id, 'cedar-river-tulip-07', now + 60000).locked);
69
+ ok('K1 after 15 minutes the right password opens', store.checkPassword(dir, a.id, 'cedar-river-tulip-07', now + store.LOCK_MS + 1000).ok);
70
+ const m = store.get(dir, a.id, now), c = store.sign(m, now + 1000);
71
+ ok('K1 the cookie is signed for this link, and a changed or late one fails', store.verifyCookie(m, c, now) && !store.verifyCookie(m, c.slice(0, -2) + 'xx', now) && !store.verifyCookie(m, c, now + 2000));
72
+ ok('K1 a link past its end is gone from the list and the disk', store.list(dir, now + 8 * 86400000).length === 0 && !fs.existsSync(path.join(dir, 'shares', a.id)));
73
+ ok('K1 a password is three words and two digits', /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(store.newPassword()));
74
+ fs.rmSync(dir, { recursive: true, force: true });
75
+ }
76
+
77
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore',
78
+ env: T.env({ PMOS_WS_PORT: String(T.PORT), PMOS_SHARE_PORT: String(SHARE_PORT), PMOS_SHARE_HOST: 'share.example.test' }) });
79
+ await T.waitForServer(BASE);
80
+ const H = await T.pressHeaders(BASE);
81
+ const post = (p, body, extra = {}) => req(BASE + p, { method: 'POST', headers: { ...H, ...extra }, body: JSON.stringify(body) });
82
+
83
+ // K2 the routes
84
+ {
85
+ ok('K2 a POST without the page\'s press headers is refused', (await req(BASE + '/api/shares', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: PRD, days: 7 }) })).status === 403);
86
+ ok('K2 an agent session cannot make a link', (await post('/api/shares', { path: PRD, days: 7 }, { 'x-pmos-session': 'sess-1' })).status === 403);
87
+ fs.writeFileSync(path.join(REPO, SECRET_REL), '# Keys\n\naws ' + 'AKIA' + 'ABCDEFGHIJKLMNOP' + ' here\n');
88
+ const sec = await post('/api/shares', { path: SECRET_REL, days: 7, password: null });
89
+ ok('K2 a file with a secret is refused, naming the rule and not the text', sec.status === 422 && /aws-access-key/.test(sec.text) && !/AKIAABCD/.test(sec.text), sec.status + ' ' + sec.text);
90
+ ok('K2 only 1, 7 or 30 days', (await post('/api/shares', { path: PRD, days: 3, password: null })).status === 400);
91
+ ok('K2 a path outside the workspace is not shared', (await post('/api/shares', { path: '../../../etc/hosts', days: 7 })).status === 404);
92
+ }
93
+ const PASS = 'harbor-maple-quartz-42';
94
+ const mk = await post('/api/shares', { path: PRD, days: 7, password: PASS });
95
+ const made = JSON.parse(mk.text || '{}');
96
+ ok('K2 a link is made, on the share hostname', mk.status === 200 && made.ok && /^https:\/\/share\.example\.test\/s\/[A-Za-z0-9_-]{22}$/.test(made.url), mk.text);
97
+ const listed = JSON.parse((await req(BASE + '/api/shares')).text || '{}');
98
+ const row = (listed.shares || []).find((x) => x.id === made.id);
99
+ ok('K2 the list shows it with its password flag and no hash or key', row && row.pw === true && row.views === 0 && !('key' in row) && !/scrypt/.test(JSON.stringify(listed)) && listed.host === 'share.example.test', JSON.stringify(listed));
100
+ const pw = JSON.parse((await req(BASE + '/api/shares/password')).text || '{}');
101
+ ok('K2 the page can ask for a generated password', pw.ok && /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(pw.password));
102
+
103
+ // K3 the share server
104
+ const up = await until(async () => (await req(SBASE + '/robots.txt')).status === 200, 10000, 200);
105
+ ok('K3 the share server starts on its own loopback port once a link exists', !!up);
106
+ const S = '/s/' + made.id;
107
+ const lock = await req(SBASE + S);
108
+ const hdr = (r) => r.headers['x-robots-tag'] === 'noindex, nofollow, noarchive' && /no-store/.test(r.headers['cache-control'] || '') && r.headers['referrer-policy'] === 'no-referrer';
109
+ ok('K3 the password page names neither the file nor PMOS', lock.status === 200 && /This page is protected/.test(lock.text) && !/premium-viewer-share|PMOS|Download and share/.test(lock.text), lock.text.slice(0, 200));
110
+ ok('K3 every answer is noindex, no-store and no-referrer', hdr(lock) && hdr(await req(SBASE + '/nope')) && hdr(await req(SBASE + '/robots.txt')));
111
+ ok('K3 robots.txt disallows everything', (await req(SBASE + '/robots.txt')).text === 'User-agent: *\nDisallow: /\n');
112
+ ok('K3 the copy and the file stay closed without the password', (await req(SBASE + S + '/view')).status === 404 && (await req(SBASE + S + '/file')).status === 404);
113
+ const form = (p) => req(SBASE + S, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'pw=' + encodeURIComponent(p) });
114
+ const w1 = await form('nope');
115
+ ok('K3 a wrong password says how many tries are left', w1.status === 401 && /4 tries left/.test(w1.text), w1.status + ' ' + w1.text.slice(0, 300));
116
+ const right = await form(PASS);
117
+ const cookie = String((right.headers['set-cookie'] || [])[0] || '');
118
+ ok('K3 the right password sets a cookie for this link only', right.status === 303 && new RegExp(`Path=/s/${made.id}`).test(cookie) && /HttpOnly/.test(cookie) && /Secure/.test(cookie) && /Max-Age=43200/.test(cookie), cookie);
119
+ const C = { Cookie: cookie.split(';')[0] };
120
+ const page = await req(SBASE + S, { headers: C });
121
+ ok('K3 with the cookie the page frames the copy, with Download and the end date', page.status === 200 && /<iframe src="\/s\/[^"]+\/view"/.test(page.text) && /Download/.test(page.text) && /The link ends/.test(page.text), page.text.slice(0, 300));
122
+ const view = await req(SBASE + S + '/view', { headers: C });
123
+ ok('K3 the copy is under a sandbox CSP and holds the document\'s words', view.status === 200 && /^sandbox[;\s]/.test(view.headers['content-security-policy'] || '') && /default-src 'none'/.test(view.headers['content-security-policy']) && /Download and share a file from the viewer/.test(view.text), view.headers['content-security-policy']);
124
+ const file = await req(SBASE + S + '/file', { headers: C });
125
+ ok('K3 Download gives the file\'s own text as an attachment', file.status === 200 && /attachment; filename="premium-viewer-share-prd\.md"/.test(file.headers['content-disposition'] || '') && file.text === fs.readFileSync(path.join(REPO, PRD), 'utf8'));
126
+ ok('K3 any other path is 404, including the workspace API', (await req(SBASE + '/')).status === 404 && (await req(SBASE + '/api/shares')).status === 404 && (await req(SBASE + '/s/short')).status === 404 && (await req(SBASE + '/premium.html')).status === 404);
127
+ for (let i = 0; i < 5; i++) await form('wrong-' + i);
128
+ const locked = await form(PASS);
129
+ ok('K3 five wrong tries lock the link, even for the right password', locked.status === 429 && /15 minutes/.test(locked.text), locked.status);
130
+ const views = (JSON.parse((await req(BASE + '/api/shares')).text).shares || []).find((x) => x.id === made.id);
131
+ ok('K3 a view is counted, with no address kept', views && views.views === 1 && !/127\.0\.0\.1/.test(fs.readFileSync(path.join(T.STATE_DIR, 'shares', made.id, 'meta.json'), 'utf8')), JSON.stringify(views));
132
+
133
+ // K4 Turn off, and the workspace refuses the share hostname
134
+ const off = await post('/api/shares/off', { id: made.id });
135
+ ok('K4 Turn off deletes the copy and the link says it is no longer active', off.status === 200 && !fs.existsSync(path.join(T.STATE_DIR, 'shares', made.id)) && /no longer active/.test((await req(SBASE + S)).text));
136
+ const wsHost = await req(BASE + '/api/shares', { headers: { Host: 'share.example.test' } });
137
+ ok('K4 the workspace server refuses a request for the share hostname', wsHost.status === 403, wsHost.status);
138
+
139
+ // K5 the page
140
+ const exe = findBrowser();
141
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the browser part cannot run'); return finish(1); }
142
+ let chromium;
143
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
144
+ browser = await chromium.launch({ executablePath: exe });
145
+ const open = async ({ w = 1280, h = 900, theme = 'light' } = {}) => {
146
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: theme });
147
+ const page = await ctx.newPage();
148
+ const errors = [];
149
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
150
+ await page.route('**/api/brief-page*', (r) => r.fulfill({ contentType: 'application/json', body: '{"ok":false,"error":"off in this suite"}' }));
151
+ await page.goto(BASE + '/premium.html?theme=' + theme);
152
+ await until(() => page.evaluate(() => !!document.querySelector('#dlg')), 15000);
153
+ await page.evaluate(async () => {
154
+ const Sh = await import('/pm/premium-shell.js');
155
+ Sh.openDlg({ eye: 'Your item', title: 'Share plan', say: 'The PRD is in the repo.', noteKey: null, pane: '<article class="paper doc"><p>Item record</p></article>', label: 'Item record' });
156
+ });
157
+ await page.evaluate((f) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'fpath'; b.dataset.file = f; b.textContent = f; document.querySelector('#dBody .stream').append(b); b.click(); }, PRD);
158
+ await until(() => page.$('#dOut .obody.vw:not([hidden]) [data-fsh]'), 10000);
159
+ return { ctx, page, errors };
160
+ };
161
+ const ICON = '#dOut .obody.vw:not([hidden]) [data-fsh]';
162
+ {
163
+ const { page, errors, ctx } = await open();
164
+ await page.click(ICON);
165
+ const st = await until(() => page.evaluate(() => { const m = document.querySelector('.vwshp'), i = m && m.querySelector('#vwsPass'); return i && i.value ? { pass: i.value, days: (m.querySelector('[data-days][aria-pressed="true"]') || {}).textContent, sw: m.querySelector('[data-sh="pw"]').getAttribute('aria-checked') } : null; }), 5000);
166
+ ok('K5 the share icon opens the popover: password on and filled, 7 days', st && /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(st.pass) && st.days === '7 days' && st.sw === 'true', JSON.stringify(st));
167
+ if (SHOTS) { fs.mkdirSync(SHOTS, { recursive: true }); await page.screenshot({ path: path.join(SHOTS, 'popover-1280-light.png') }); }
168
+ await page.click('.vwshp [data-sh="make"]');
169
+ const link = await until(() => page.evaluate(() => { const u = document.querySelector('.vwshp .vwsu'); return u ? u.textContent : null; }), 8000);
170
+ const pass = st && st.pass;
171
+ ok('K5 Create link shows the link on the share hostname', /^https:\/\/share\.example\.test\/s\/[A-Za-z0-9_-]{22}$/.test(link || ''), link);
172
+ const n = await page.evaluate(() => (document.querySelector('.vwshp .vwsh:last-of-type') || {}).textContent);
173
+ ok('K5 the open links list shows it', /Open links \(1\)/.test(await page.evaluate(() => document.querySelector('.vwshp').textContent)), n);
174
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, 'made-1280-light.png') });
175
+ // a guest, in another browser context, with no PMOS session
176
+ const g = await browser.newContext({ viewport: { width: 1000, height: 760 } });
177
+ const gp = await g.newPage();
178
+ await gp.goto(SBASE + new URL(link).pathname);
179
+ ok('K5 the guest sees the password page', /This page is protected/.test(await gp.textContent('body')));
180
+ if (SHOTS) await gp.screenshot({ path: path.join(SHOTS, 'guest-lock.png') });
181
+ await gp.fill('input[name="pw"]', pass);
182
+ await gp.click('button[type="submit"]');
183
+ const fr = await until(async () => { const h = await gp.$('iframe'); const f = h && await h.contentFrame(); return f && /Download and share a file from the viewer/.test(await f.textContent('body').catch(() => '')) ? f : null; }, 8000);
184
+ ok('K5 with the password the guest reads the copy', !!fr);
185
+ if (SHOTS) await gp.screenshot({ path: path.join(SHOTS, 'guest-page.png') });
186
+ await g.close();
187
+ const id = new URL(link).pathname.split('/').pop();
188
+ await page.click(`.vwshp [data-off="${id}"]`);
189
+ const sure = await page.textContent(`.vwshp [data-off="${id}"]`);
190
+ await page.click(`.vwshp [data-off="${id}"]`);
191
+ const gone = await until(() => page.evaluate((x) => !document.querySelector(`.vwshp [data-off="${x}"]`), id), 5000);
192
+ ok('K5 Turn off asks once more, then removes the link', sure === 'Sure? Turn off' && gone && !fs.existsSync(path.join(T.STATE_DIR, 'shares', id)), sure);
193
+ await page.keyboard.press('Escape');
194
+ ok('K5 Escape closes the popover', !(await page.$('.vwshp')));
195
+ ok('K5 no page errors', errors.length === 0, errors.join(' | '));
196
+ await ctx.close();
197
+ }
198
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const theme of ['light', 'dark']) {
199
+ const { page, ctx } = await open({ w, h, theme });
200
+ await page.click(ICON);
201
+ await until(() => page.evaluate(() => { const i = document.querySelector('.vwshp #vwsPass'); return i && i.value; }), 5000);
202
+ const geo = await page.evaluate(() => { const r = document.querySelector('.vwshp').getBoundingClientRect(); const b = document.querySelector('.vwshp [data-sh="make"]').getBoundingClientRect(); return { l: Math.round(r.left), r: Math.round(r.right), t: Math.round(r.top), b: Math.round(r.bottom), vw: innerWidth, vh: innerHeight, bh: Math.round(b.height), sx: document.documentElement.scrollWidth - innerWidth }; });
203
+ ok(`K5 at ${w} ${theme} the popover fits on screen${w < 700 ? ' as a sheet with 44 px targets' : ''}`, geo.l >= 0 && geo.r <= geo.vw && geo.t >= 0 && geo.b <= geo.vh && geo.sx <= 0 && (w >= 700 || (geo.bh >= 44 && geo.vh - geo.b < 40)), JSON.stringify(geo));
204
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `popover-${w}-${theme}.png`) });
205
+ await ctx.close();
206
+ }
207
+ return finish();
208
+ })();
@@ -95,7 +95,7 @@ const mk = (edit) => { const v = F.view(); if (edit) edit(v); return WP.build({
95
95
  await undoOf(p);
96
96
  ok('W9 Undo of Accept posts focus/clear for that key', A.last().path === '/api/pm-items/focus/clear' && A.last().body.key === 'job:job-1' && Object.keys(A.last().body).join() === 'key', JSON.stringify(A.last()));
97
97
  const fd = await p.evaluate(() => ({ title: document.querySelector('#dTitle').textContent, text: document.querySelector('#oMain').textContent, ask: document.querySelector('#askF').hidden, add: document.querySelector('[data-fx="jadd"]').disabled }));
98
- ok('W6 See all lists the suggestion with the item it covers, and the PM\'s jobs with open counts', fd.title === 'Focus and jobs' && /to walk in with a decision ready/.test(fd.text) && /Prepare for the Design review/.test(fd.text) && /When a design review is on the calendar, I want to walk in with a decision ready, so the review ends with a disposition\./.test(fd.text) && /1 open item/.test(fd.text) && fd.ask, JSON.stringify(fd));
98
+ ok('W6 See all lists the suggestion with the item it covers, and the PM\'s jobs with open counts', fd.title === 'Focus and jobs' && /to walk in with a decision ready/.test(fd.text) && /Prepare for the Design review/.test(fd.text) && /When a design review is on the calendar, I want to walk in with a decision ready, so the review ends with a disposition\./.test(fd.text) && /1 open item/.test(fd.text) && !fd.ask, JSON.stringify(fd));
99
99
  ok('W6 Add the job stays off until the line has when, I want and so', fd.add && await p.evaluate(async () => { const i = document.querySelector('#xjIn'); i.value = 'when a launch slips'; i.dispatchEvent(new Event('input', { bubbles: true })); return document.querySelector('[data-fx="jadd"]').disabled; }));
100
100
  await p.fill('#xjIn', 'when a launch slips, I want the owner named, so the date holds');
101
101
  ok('W6 …and turns on when it has all three', await p.evaluate(() => !document.querySelector('[data-fx="jadd"]').disabled));
@@ -12,7 +12,7 @@
12
12
  * C, the page's context: { ws, board, boardName, self, first, reload }. A row: { id, title, acts } with acts from lib/board-premium.js actsOf
13
13
  * (or lib/initiative-premium.js): { stages, stage, life: hold | cancelled | null, reason, back, backDay, archived: { reason, into } | null }. */
14
14
  import { pmPost, pmGet } from './http.js';
15
- import { $, $$, esc, openDlg, closeDlg, toast, turnA, ptx } from './premium-shell.js';
15
+ import { $, $$, esc, openDlg, popKey, closeDlg, toast, turnA, ptx } from './premium-shell.js';
16
16
 
17
17
  const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
18
18
  const CHK = '<path d="M5 12.5l4.5 4.5L19 7.5"/>';
@@ -134,15 +134,14 @@ export function onBar(e, C, r) {
134
134
  return true;
135
135
  }
136
136
 
137
- /* ── the dialogs: one form in the standard dialog's pane, the conversation box hidden, as Add a document does ── */
137
+ /* ── the dialogs: one form in the standard dialog's pane, with the conversation beside it (premium-popup-context P1) ── */
138
138
  const happens = (L) => `<div class="bahp"><p class="label">What happens</p><ul>${L.map((t) => `<li>${ICO(CHK)}<span>${esc(t)}</span></li>`).join('')}</ul></div>`;
139
139
  const rec = (t) => `<p class="note barec">${ICO(SHD)}<span>${esc(t)}</span></p>`;
140
140
  const pills = (id, L, cur, lab) => `<div class="chq bapl" id="${id}" role="radiogroup" aria-label="${esc(lab)}">${L.map(([v, l]) => `<button type="button" role="radio" data-v="${v}" aria-checked="${v === cur}" aria-pressed="${v === cur}">${esc(l)}</button>`).join('')}</div>`;
141
141
  const pick = (e, id) => { const p = e.target.closest('#' + id + ' [data-v]'); if (!p) return null; $$('#' + id + ' [data-v]').forEach((q) => { q.setAttribute('aria-pressed', q === p); q.setAttribute('aria-checked', q === p); }); return p.dataset.v; };
142
142
  const msgP = (id) => `<p class="note" id="${id}" role="status"></p>`;
143
143
  function form(o) {
144
- openDlg({ eye: o.eye, title: o.title, sub: o.sub, say: o.say, stream: turnA(ptx(o.say)), noteKey: null, pane: `<article class="paper doc"><div class="addf">${o.body}</div></article>`, label: o.label || 'Detail' });
145
- $('#askF').hidden = true; $('#askNote').hidden = true;
144
+ openDlg({ eye: o.eye, title: o.title, sub: o.sub, say: o.say, stream: turnA(ptx(o.say)), noteKey: popKey('act', o.eye, o.title), pane: `<article class="paper doc"><div class="addf">${o.body}</div></article>`, label: o.label || 'Detail' });
146
145
  }
147
146
  async function press(go, m, fn) {
148
147
  go.disabled = true; m.textContent = '';
@@ -6,7 +6,7 @@
6
6
  * premium-board-actions, pm/premium-acts.js): move to the next stage or back, hold, cancel, archive, resume, reopen and restore, each with Undo. Nothing here issues a document. */
7
7
  import { pmPost } from './http.js';
8
8
  import { mountDocSheet } from './premium-doc-sheet.js';
9
- import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, CHEV, crumbHtml, wireCrumb, chatAbout, AI, openAddDoc, setPageGaps } from './premium-shell.js';
9
+ import { $, $$, esc, openDlg, popKey, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, CHEV, crumbHtml, wireCrumb, chatAbout, AI, openAddDoc, setPageGaps } from './premium-shell.js';
10
10
  import { barHtml, onBar, closeMenu } from './premium-acts.js';
11
11
  import { openWorkItem, recordPress } from './premium-vw-item.js';
12
12
  import { openTicket } from './premium-vw-jira.js';
@@ -134,9 +134,9 @@ function openTask(t) {
134
134
  const rows = [['Type', t.kind || (taskKind(t) === 'req' ? 'PRD requirement' : 'Task')], ['Reference', t.ref], ['Source', t.src], ['Owner', t.owner], ['Starts', t.start ? when(t.start) : ''], ['Due', t.end ? when(t.end) : ''], ['Status', t.state || 'No result recorded']];
135
135
  const say = t.title + (t.state ? ' is ' + t.state.toLowerCase() + '.' : ' has no result recorded. The repository records none for a PRD requirement.');
136
136
  const act = t.pmos ? `<div class="tkact"><span class="label">Status</span><div class="seg tkst" role="group" aria-label="Status"><i class="pill"></i>${STATES.map((s) => `<button data-tks="${esc(s)}" aria-pressed="${t.state === s}">${s}</button>`).join('')}</div></div><p class="note" style="margin-top:12px">A PMOS task is kept on the board. Jira tickets are read-only here: Jira owns their status and dates.</p>` : `<p class="xn">${t.src === 'PRD requirement' ? 'Read from the initiative’s PRD. Nothing on this page changes it.' : 'Read from the board. Jira owns its status and dates.'}</p>`;
137
- openDlg({ eye: 'Task · real data', title: t.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: null, pane: `<article class="paper doc">${kv(rows)}${act}${recordPress('Open the initiative')}</article>`, label: 'Task' });
137
+ openDlg({ eye: 'Task · real data', title: t.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: popKey('task', M.id, t.ref || t.key || t.title), facts: rows, pane: `<article class="paper doc">${kv(rows)}${act}${recordPress('Open the initiative')}</article>`, label: 'Task' });
138
138
  wireRecord();
139
- $('#askF').hidden = true; if ($('#oMain .tkst')) pillOf($('#oMain .tkst'));
139
+ if ($('#oMain .tkst')) pillOf($('#oMain .tkst'));
140
140
  if (taskKind(t) === 'jira' && t.ref) openTicket({ ws: M.board.ws, board: M.board.id, initiative: M.id, ref: t.ref }); // the ticket beside its facts (premium-viewer S5)
141
141
  $$('#oMain [data-tks]').forEach((b) => { b.onclick = async () => {
142
142
  if (b.getAttribute('aria-pressed') === 'true') return;
@@ -156,8 +156,7 @@ function openAddTask() {
156
156
  <div class="two"><label><span>Start <em>optional</em></span><input type="date" id="atF"></label><label><span>Due <em>optional</em></span><input type="date" id="atD"></label></div>
157
157
  <p class="note" style="margin:0">With no dates the board plans the task from tomorrow, for a week.</p>
158
158
  <p class="note" id="atM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="atGo">Add task</button><button class="cta alt" id="atNo">Cancel</button></div></div>`;
159
- openDlg({ eye: 'New task · real data', title: 'Add a task', sub: M.title, say: 'Say what the task is. It is written to the board’s record.', stream: turnA(ptx('Say what the task is and when it is due. It is written to the board’s record, and I change nothing else.')), noteKey: null, pane: `<article class="paper doc">${form}</article>`, label: 'Task' });
160
- $('#askF').hidden = true;
159
+ openDlg({ eye: 'New task · real data', title: 'Add a task', sub: M.title, say: 'Say what the task is. It is written to the board’s record.', stream: turnA(ptx('Say what the task is and when it is due. It is written to the board’s record, and I change nothing else.')), noteKey: popKey('new-task', M.id), pane: `<article class="paper doc">${form}</article>`, label: 'Task' });
161
160
  $('#oMain').onclick = async (e) => {
162
161
  const pre = e.target.closest('[data-pre]'); if (pre) { $('#atT').value = prefs[+pre.dataset.pre]; $('#atT').focus(); return; }
163
162
  if (e.target.closest('#atNo')) { closeDlg(); return; }
@@ -243,10 +242,9 @@ function openAbout(d) {
243
242
  const say = d.title + ' is ' + (d.state || 'not started').toLowerCase() + '. ' + (d.path ? '' : d.st === 'missing' ? 'There is no file to read yet.' : 'It has no file of its own to read.') + (d.what ? ' ' + d.what : '');
244
243
  const rows = [['State', d.state], ['Who writes it', d.by], ['Read by', d.reader], ['How often', d.cadence], ['Updated', d.when], ['Added', d.added]];
245
244
  const holds = d.sections && d.sections.length ? `<p class="label" style="margin:16px 0 8px">What a draft will contain</p><ul class="dabt">${d.sections.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : '';
246
- const why = d.st === 'missing' ? (draftable ? 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent.' : d.act ? '' : 'PMOS does not draft this one. It is written by ' + (d.by ? d.by.toLowerCase() : 'you') + ', or derived from other records.') : d.path ? '' : 'There is no file to open yet, so there is nothing to read here.';
245
+ const why = d.st === 'missing' ? (draftable ? 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent.' : d.act ? '' : /pmos/i.test(d.by || '') ? 'PMOS drafts this one, but a draft cannot be started from this page yet.' : 'PMOS does not draft this one. ' + (d.by ? d.by + '.' : 'You write it.')) : d.path ? '' : 'There is no file to open yet, so there is nothing to read here.';
247
246
  const act = draftable ? `<div class="cact"><button class="cta" id="abDraft">${ICO(SPARK)}${esc(d.act.label)}</button></div>` : d.running ? '<p class="note" role="status" style="margin-top:12px">The agent is drafting this now. It runs in the background and sends nothing.</p>' : '';
248
- openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: null, pane: `<article class="paper doc">${d.what ? `<p class="lede" style="margin:0 0 12px">${esc(d.what)}</p>` : ''}${kv(rows)}${holds}${why ? `<p class="note" style="margin-top:12px">${esc(why)}</p>` : ''}${act}</article>`, label: 'Document' });
249
- $('#askF').hidden = true;
247
+ openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(ptx(say)), noteKey: popKey('doc', M.id, d.key || d.title), facts: rows, pane: `<article class="paper doc">${d.what ? `<p class="lede" style="margin:0 0 12px">${esc(d.what)}</p>` : ''}${kv(rows)}${holds}${why ? `<p class="note" style="margin-top:12px">${esc(why)}</p>` : ''}${act}</article>`, label: 'Document' });
250
248
  const b = $('#abDraft'); if (b) b.onclick = async () => { b.disabled = true; closeDlg(); await draftKey(d.key); };
251
249
  }
252
250
  $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
@@ -7,7 +7,7 @@
7
7
  * adds New report and Shape it in the Studio, whose presses are POST /api/report-setups/setup | from-dashboard and POST /api/report-structure/turn | remove |
8
8
  * revert | accept (PRD R5 to R8). insights-one-list puts the insight first, the pinned dashboard on top and one paged list of dashboards and reports below
9
9
  * (PRD L1 to L6); its one new press is Pin, POST /api/premium-dashboards/pin. Nothing else posts, and nothing is sent outward. */
10
- import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps, infoBtn, growAsk } from './premium-shell.js';
10
+ import { $, $$, esc, openDlg, popKey, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps, infoBtn, growAsk } from './premium-shell.js';
11
11
  import { pmPost, pmGet } from './http.js';
12
12
  import { openStudio } from './premium-studio.js';
13
13
  import { openReport } from './premium-report-read.js';
@@ -341,9 +341,8 @@ $('#repAsk').addEventListener('submit', async (e) => {
341
341
  /* ── the report dialogs: each press is one existing /api/report-setups/* route (PRD R2 to R4) ─────────────────────────────────────────────── */
342
342
  const repPost = (sub, body) => pmPost('/api/report-setups/' + sub, Object.assign({ ws: M.board.ws }, body));
343
343
  function repDlg(o) {
344
- openDlg({ eye: o.eye + ' · real data', title: o.title, sub: o.sub || M.board.name, say: o.say, stream: turnA(ptx(o.say)), noteKey: null, label: 'Report',
344
+ openDlg({ eye: o.eye + ' · real data', title: o.title, sub: o.sub || M.board.name, say: o.say, stream: turnA(ptx(o.say)), noteKey: popKey('report', M.board.ws, o.title), facts: o.facts, label: 'Report',
345
345
  pane: `<article class="paper doc">${o.html}<p class="note" id="rxM" role="status" style="margin:12px 0 0;min-height:1.2em"></p><div class="cact">${o.acts.map(([id, t, alt]) => `<button class="cta${alt ? ' alt' : ''}" data-rx="${id}">${esc(t)}</button>`).join('')}</div></article>` });
346
- $('#askF').hidden = true;
347
346
  $('#oMain').onchange = null;
348
347
  $('#oMain').onclick = async (e) => {
349
348
  const b = e.target.closest('[data-rx]'); if (!b) return;
@@ -407,11 +406,11 @@ function openAsk(a) {
407
406
  }
408
407
  function openSetup(s) {
409
408
  if (!s) return;
410
- const rows = [['Schedule', s.label], ['Status', s.paused ? 'Paused' : 'Active'], ['Next draft', s.paused ? '' : s.next], ['Last issued', s.lastIssued], ['Audience', s.audience], ['Output', s.output], ['Documents', String(s.cycles)], ['Purpose', s.purpose]];
409
+ const rows = [['Schedule', s.label], ['Status', s.paused ? 'Paused' : 'Active'], ['Next draft', s.paused ? '' : s.next], ['Last issued cycle', s.lastIssued], ['Audience', s.audience], ['Output', s.output], ['Documents', String(s.cycles)], ['Purpose', s.purpose]];
411
410
  const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
412
411
  if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
413
412
  if (s.fromWork) acts.push(['studio', 'Shape it in the Studio', 1]);
414
- repDlg({ eye: 'Set-up report', title: s.name, say: s.paused ? 'This report is paused. Resume it to draft it on its schedule again.' : 'This report is drafted on its schedule. You can draft the next cycle now or pause it.',
413
+ repDlg({ eye: 'Set-up report', title: s.name, facts: rows, say: s.paused ? 'This report is paused. Resume it to draft it on its schedule again.' : 'This report is drafted on its schedule. You can draft the next cycle now or pause it.',
415
414
  html: kv(rows) + `<p class="note">${s.fromWork ? (s.structured ? 'Draft it now starts a background run that follows the saved structure.' : 'Draft it now writes the next cycle as a file at once.') : 'This report is drafted from its dashboard on its day.'} Pause and Resume record a line in the report ledger. Nothing is sent.</p>`,
416
415
  acts, on: {
417
416
  draft: press('draft', { id: s.id }, (res) => res.drafting ? 'Drafting started. The draft follows the saved structure.' : 'Drafted: ' + ((res.drafted && res.drafted.path) || 'the next cycle') + '.'),
@@ -492,8 +491,7 @@ function bmOpen(i) {
492
491
  <p class="note" id="bmM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="bmGo">Save target</button>${t.tg != null ? '<button class="cta alt" id="bmClr">Clear target</button>' : ''}</div></div>`;
493
492
  const pane = `<article class="paper doc"><p class="lede" style="margin:0 0 10px">${esc(t.def)}</p>${kv(MT.factRows(t, BM.repo, BM.weeks))}${form}${vals}<p class="note" style="margin-top:12px">${esc(BM.note)}</p></article>`;
494
493
  const say = t.tg != null ? `The target is ${t.tg}. Change it or clear it here; the Board draws it too.` : 'No target is set. Type one and save it; the Board draws it too.';
495
- openDlg({ eye: 'Board measure · real data', title: t.label, sub: BM.repo, say, stream: turnA(ptx(say)), noteKey: null, pane, label: 'Measure' });
496
- $('#askF').hidden = true;
494
+ openDlg({ eye: 'Board measure · real data', title: t.label, sub: BM.repo, say, stream: turnA(ptx(say)), noteKey: popKey('measure', BM.repo, t.key || t.label), facts: MT.factRows(t, BM.repo, BM.weeks), pane, label: 'Measure' });
497
495
  $('#oMain').onchange = null;
498
496
  $('#oMain').onclick = async (e) => {
499
497
  const go = e.target.closest('#bmGo'), clr = e.target.closest('#bmClr'); if (!go && !clr) return;
@@ -816,9 +816,8 @@ export function mountMeeting(d) {
816
816
  }
817
817
  const matPath = () => '/api/meeting-material?event=' + encodeURIComponent(row.id) + '&title=' + encodeURIComponent(row.title) + (row.series ? '&series=' + encodeURIComponent(row.series) : '') + '&date=' + row.day;
818
818
  vmStyle();
819
- d.openDlg({ eye: 'Calendar · real data', title: row.title, sub: [dayLabel(row.day), row.end && hasTime(row.end) ? row.time + ' to ' + hhmm(row.end) : [row.time, row.len].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), compact: true, noteKey: via === 'today' ? 'ev:meeting:' + Date.parse(row.at) : null,
819
+ d.openDlg({ eye: 'Calendar · real data', title: row.title, sub: [dayLabel(row.day), row.end && hasTime(row.end) ? row.time + ' to ' + hhmm(row.end) : [row.time, row.len].filter(Boolean).join(' · ')].filter(Boolean).join(' · '), compact: true, noteKey: via === 'today' ? 'ev:meeting:' + Date.parse(row.at) : 'pop:meeting:' + (String(row.day || '') + '-' + String(row.id || row.title)).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 90),
820
820
  stream: d.turnA(d.ptx('This meeting is in the calendar PMOS holds. Its notes, material and recording appear here only if PMOS holds them.')), pane: detailHtml(meetingView(row, null, null), boards, inis, '', ui), label: 'Meeting' });
821
- if (via !== 'today') $('#askF').hidden = true;
822
821
  const [rp, mt] = await Promise.all([d.pmGet('/api/meeting-replay?event=' + encodeURIComponent(row.id) + '&date=' + row.day), d.pmGet(matPath())]);
823
822
  if ($('#dTitle').textContent !== row.title) return;
824
823
  replay = rp && rp.ok === true ? { state: 'ok', body: rp } : rp && rp.status === 404 ? { state: 'none' } : { state: 'error', error: (rp && rp.error) || 'no answer' };
@@ -13,7 +13,7 @@
13
13
  * issued cycle is frozen: no design row and no turn. Issue (POST /api/report/issue, after a confirm) freezes a draft cycle; the copies in other tools stay in the console.
14
14
  * Edit opens the report's file as a page in the viewer (premium-vw-doc.js, initiative premium-viewer S2): the one document page every markdown file uses,
15
15
  * with Present, Print and Download on its bar. Its words are saved there through the /api/doc-sheet routes. */
16
- import { $, esc, openDlg, toast, turnA, turnU, ptx, setFull } from './premium-shell.js';
16
+ import { $, esc, openDlg, popKey, toast, turnA, turnU, ptx, setFull } from './premium-shell.js';
17
17
  import { pmGet, pmPost } from './http.js';
18
18
  import { vwShow } from './premium-viewer.js';
19
19
  import { openDocPage } from './premium-vw-doc.js';
@@ -388,9 +388,10 @@ export async function openReport(row, hand) {
388
388
  const say = R.issued
389
389
  ? 'This is the ' + when + ' cycle of "' + R.name + '". It is issued, so it is frozen. Read it as a deck or a page, present it, download it or print it. Nothing is sent from here.'
390
390
  : 'This is the ' + when + ' cycle of "' + R.name + '". Read it as a deck or a page, present it, download it or print it. To change how it looks, add a sample or tell me what to change, then press This is it on the version you want. Nothing is sent from here.';
391
- openDlg({ eye: 'Report · ' + (R.issued ? 'issued' : 'draft'), title: R.name, sub: when, stream: turnA(ptx(say)), noteKey: null, pane: '<p class="note">Reading the document.</p>', label: 'Report' });
391
+ openDlg({ eye: 'Report · ' + (R.issued ? 'issued' : 'draft'), title: R.name, sub: when, stream: turnA(ptx(say)), noteKey: R.issued ? popKey('report-cycle', R.id, when) : null, pane: '<p class="note">Reading the document.</p>', label: 'Report' });
392
392
  $('#dlg').classList.add('rdrd');
393
- $('#askF').hidden = true; const an = $('#askNote'); if (an) an.hidden = true;
393
+ $('#dlg').classList.toggle('rdiss', R.issued); // premium-popup-context P1: an issued cycle has the chat; a draft keeps its own "Say how it should look" box
394
+ if (!R.issued) { $('#askF').hidden = true; const an = $('#askNote'); if (an) an.hidden = true; }
394
395
  if (!R.issued) $('#dBody').insertAdjacentHTML('beforeend', `<form class="askbar" id="rdF"><input id="rdIn" placeholder="Say how it should look" maxlength="4000" autocomplete="off" aria-label="Say how the report should look"><button type="submit" aria-label="Send" title="Send">${SEND}</button></form><p class="fine2">A change starts a design run that writes only a new version of the look. The document's words do not change.</p>`);
395
396
  const f = $('#rdF'); if (f) f.onsubmit = onSay;
396
397
  const me = R;