create-pmos 0.267.0 → 0.269.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.
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-studio-test.js — the Insight Studio's Dashboard mode on the premium Insights page (initiative premium-studio-dashboard;
4
+ * planning/prd/premium-studio-dashboard-prd.md S1 to S10). A real server on a scratch repository whose KR metric records hold two measures with a series
5
+ * and one without. The real page presses the real save route:
6
+ * O opening · C the conversation · B the brief and tray · K the checks · U Undo · S save, edit and remove · P the POST allow-list · F floors */
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const { spawn } = require('child_process');
11
+ const { findBrowser } = require('./lib/find-browser');
12
+ const T = require('./test-run').configure({ name: 'premium-studio' });
13
+
14
+ const BASE = T.BASE;
15
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
16
+ const until = async (fn, ms = 20000, step = 150) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
17
+ const results = [];
18
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 500) : ''}`); };
19
+ let srv = null, browser = null;
20
+ const finish = async (code) => {
21
+ if (browser) await browser.close().catch(() => {});
22
+ if (srv) { try { srv.kill('SIGKILL'); } catch { /* gone */ } }
23
+ T.killTmux();
24
+ const bad = results.filter((x) => !x.cond).length;
25
+ console.log(`\n${results.length - bad}/${results.length} premium-studio assertions passed`);
26
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
27
+ };
28
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
29
+
30
+ /* the scratch repository: Partner activation (3 readings), Time to first call (2 readings), Lonely (1 reading, no series) */
31
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-repo-'));
32
+ const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-state-'));
33
+ fs.mkdirSync(path.join(dir, 'planning', 'records'), { recursive: true });
34
+ const L = [
35
+ { id: '1', kind: 'add', rid: 'krm-a', fields: { metric: 'Partner activation', baseline: 20, target: 50, by: '2026-12-31', pillar: 'Growth', unit: '%' } },
36
+ { id: '2', kind: 'reading', rid: 'krm-a', fields: { at: '2026-07-01', value: 20 } }, { id: '3', kind: 'reading', rid: 'krm-a', fields: { at: '2026-08-01', value: 24 } }, { id: '4', kind: 'reading', rid: 'krm-a', fields: { at: '2026-10-01', value: 30 } },
37
+ { id: '5', kind: 'add', rid: 'krm-t', fields: { metric: 'Time to first call', baseline: 10, target: 4, by: '2026-12-31', pillar: 'Growth', unit: ' days' } },
38
+ { id: '6', kind: 'reading', rid: 'krm-t', fields: { at: '2026-08-01', value: 9 } }, { id: '7', kind: 'reading', rid: 'krm-t', fields: { at: '2026-10-01', value: 7 } },
39
+ { id: '8', kind: 'add', rid: 'krm-l', fields: { metric: 'Lonely', baseline: 1, target: 2, by: '2026-12-31' } }, { id: '9', kind: 'reading', rid: 'krm-l', fields: { at: '2026-10-01', value: 1 } },
40
+ ];
41
+ fs.writeFileSync(path.join(dir, 'planning', 'records', 'kr-metrics.jsonl'), L.map((x) => JSON.stringify(x)).join('\n') + '\n');
42
+ const saved = async () => { const j = await (await fetch(BASE + '/api/insights-premium')).json(); return (j.model && j.model.dashboards || []).filter((d) => d.saved); };
43
+
44
+ (async () => {
45
+ const exe = findBrowser();
46
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the suite cannot run'); return finish(1); }
47
+ let chromium;
48
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
49
+ 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: dir, PMOS_STATE_DIR: stateDir }) });
50
+ await T.waitForServer(BASE);
51
+ browser = await chromium.launch({ executablePath: exe, headless: true, args: ['--no-sandbox'] });
52
+
53
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }), p = await ctx.newPage(), errs = [], posts = [];
54
+ p.on('pageerror', (e) => errs.push(String(e)));
55
+ p.on('request', (r) => { if (r.method() === 'POST') posts.push(new URL(r.url()).pathname); });
56
+ await p.goto(BASE + '/premium-insights.html');
57
+ await until(() => p.evaluate(() => !!document.querySelector('#dashBody .mch') && !!document.querySelector('#pdNew')));
58
+ const say = async (t) => { await p.fill('#stIn', t); await p.press('#stIn', 'Enter'); await sleep(150); return p.evaluate(() => { const a = [...document.querySelectorAll('#dBody .stream .turn.a .tt')]; return a.length ? a[a.length - 1].textContent : ''; }); };
59
+ const chipv = (k) => p.evaluate((x) => (document.querySelector(`#oMain [data-st="chip|${x}"] b`) || {}).textContent || '', k);
60
+ const tiles = () => p.evaluate(() => [...document.querySelectorAll('#stPv .mch .mlab')].map((e) => e.firstChild.textContent));
61
+ const checksTxt = () => p.evaluate(() => (document.querySelector('#stCk .suckb b') || {}).textContent || '');
62
+ const tap = (sel) => p.$eval(sel, (b) => b.click());
63
+ const open = async (sel) => { await p.click(sel); await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !!document.querySelector('#oMain .stu'))); await sleep(300); };
64
+ const shut = async () => { for (let i = 0; i < 2 && await p.evaluate(() => document.querySelector('#dlg').classList.contains('on')); i++) { await p.keyboard.press('Escape'); await sleep(150); } };
65
+
66
+ /* O: New dashboard opens the Studio */
67
+ await open('#pdNew');
68
+ const o = await p.evaluate(() => ({ eye: document.querySelector('#dEye').textContent, full: document.querySelector('#dlg').classList.contains('full'), lib: [...document.querySelectorAll('#stLb .stli b')].map((b) => b.textContent), agent: getComputedStyle(document.querySelector('#askF')).display === 'none', own: !!document.querySelector('#stF') }));
69
+ ok('O1 New dashboard opens the Studio as the wide dialog, full screen at 1280 px', /^Insight Studio · /.test(o.eye) && o.full, JSON.stringify(o));
70
+ ok('O2 the library lists the three measures of the records and nothing else', o.lib.join() === 'Partner activation,Time to first call,Lonely', o.lib.join());
71
+ ok('O3 the agent\'s ask bar is hidden and the Studio\'s own sits in its place', o.agent && o.own);
72
+ ok('O4 a new draft shows Not set on Name and Purpose and 0 charts', await chipv('name') === 'Not set' && await chipv('use') === 'Not set' && await chipv('charts') === '0');
73
+ ok('K1 the checks start at 2 of 6 (count and repeats pass)', await checksTxt() === '2 of 6 checks pass', await checksTxt());
74
+
75
+ /* C: the conversation */
76
+ let a = await say('add Partner activation and Time to first call');
77
+ ok('C1 "add" names the measures it added and draws them', /^Done: added Partner activation, added Time to first call/.test(a) && (await tiles()).join() === 'Partner activation,Time to first call', a);
78
+ a = await say('call it Partner review');
79
+ ok('C2 "call it" sets the name chip', /^Done: named it "Partner review"/.test(a) && await chipv('name') === 'Partner review', a);
80
+ a = await say('it is for the Monday partner review');
81
+ ok('C3 "it is for" sets the purpose', await chipv('use') === 'the Monday partner review', a);
82
+ a = await say('make it the main dashboard');
83
+ ok('C4 "make it the main dashboard" sets Main, and the checks pass 6 of 6', await chipv('main') === 'Yes' && await checksTxt() === '6 of 6 checks pass', a + ' ' + await checksTxt());
84
+ a = await say('add Revenue per seat');
85
+ ok('C5 a measure the board does not have changes nothing and says so', /^I changed nothing/.test(a) && await chipv('charts') === '2', a);
86
+ a = await say('move Time to first call first');
87
+ ok('C6 "move … first" reorders the preview', (await tiles()).join() === 'Time to first call,Partner activation', a);
88
+ ok('C7 no turn posted anything', posts.length === 0, posts.join());
89
+
90
+ /* U: Undo */
91
+ await tap('#oMain [data-st="undo"]'); await sleep(150);
92
+ ok('U1 Undo steps back one change (the move)', (await tiles()).join() === 'Partner activation,Time to first call');
93
+ a = await say('undo');
94
+ ok('U2 "undo" in words steps back again (Main)', await chipv('main') === 'No' && /^Done: one step undone/.test(a), a);
95
+
96
+ /* B and K: the brief, the library and a check's fix */
97
+ await tap('#stLb [data-st="libc|krm-l"]'); await sleep(150);
98
+ const gone = await p.evaluate(() => [...document.querySelectorAll('#stPv .stgone')].map((e) => e.textContent).join(' | '));
99
+ ok('B1 a measure with no series is added, listed as not drawn with the reason, and not drawn', /Lonely has fewer than two readings, so it has no chart/.test(gone) && (await tiles()).length === 2 && await chipv('charts') === '3', gone);
100
+ await tap('#oMain [data-st="ck"]'); await sleep(100);
101
+ const fix = await p.evaluate(() => [...document.querySelectorAll('#stCk .sucl li.bad button')].map((b) => b.textContent));
102
+ ok('K2 the failing check (no main dashboard) offers its fix', fix.join() === 'Make it the main one', fix.join());
103
+ await tap('#stCk .sucl li.bad button'); await sleep(150);
104
+ ok('K3 the fix sets what it names', await chipv('main') === 'Yes' && await checksTxt() === '6 of 6 checks pass');
105
+ await tap('#oMain [data-st="chip|charts"]'); await sleep(100);
106
+ await tap('#stTr [data-st="rm|2"]'); await sleep(100);
107
+ ok('B2 the Charts tray removes a measure', await chipv('charts') === '2');
108
+
109
+ /* S: save, read back, edit, remove */
110
+ await tap('#oMain [data-st="save"]');
111
+ ok('S1 Save closes the Studio and the page draws the saved dashboard as the main one', await until(() => p.evaluate(() => !document.querySelector('#dlg').classList.contains('on') && [...document.querySelectorAll('#dashTabs button')].some((b) => b.textContent === 'Partner review · Main' && b.getAttribute('aria-pressed') === 'true'))));
112
+ let S = await saved();
113
+ ok('S2 the ledger holds the name, purpose, order and Main', S.length === 1 && S[0].name === 'Partner review' && S[0].purpose === 'the Monday partner review' && S[0].charts.join() === 'krm-a,krm-t' && S[0].main, JSON.stringify(S));
114
+ await open('#pdEdit');
115
+ ok('S3 Edit opens the Studio on the saved dashboard', await chipv('name') === 'Partner review' && await chipv('main') === 'Yes' && (await tiles()).join() === 'Partner activation,Time to first call');
116
+ await say('move Time to first call first'); await say('remove Partner activation');
117
+ await tap('#oMain [data-st="save"]');
118
+ await until(async () => { const x = await saved(); return x.length === 1 && x[0].charts.join() === 'krm-t'; });
119
+ S = await saved();
120
+ ok('S4 an edit made in words is saved', S.length === 1 && S[0].charts.join() === 'krm-t', JSON.stringify(S));
121
+ await open('#pdEdit');
122
+ await tap('#oMain [data-st="del"]'); await sleep(100);
123
+ const armed = await p.evaluate(() => ({ b: document.querySelector('#oMain [data-st="del"]').textContent, m: document.querySelector('#stMsg').textContent }));
124
+ ok('S5 Remove asks for a second press and says what stays', armed.b === 'Press again to remove it' && /measures and their records stay/.test(armed.m), JSON.stringify(armed));
125
+ await tap('#oMain [data-st="del"]');
126
+ await until(async () => (await saved()).length === 0);
127
+ ok('S6 the second press removes the dashboard', (await saved()).length === 0);
128
+
129
+ /* P: the POST allow-list and the guard */
130
+ ok('P1 the page posted only to the dashboard save route', posts.length === 3 && posts.every((x) => x === '/api/premium-dashboards/save'), posts.join());
131
+ const j = await (await fetch(BASE + '/api/insights-premium')).json(), body = JSON.stringify({ ws: j.model.board.ws, board: j.model.board.id, name: 'From an agent', purpose: 'x', charts: [] });
132
+ const H = await T.pressHeaders(BASE);
133
+ const asAgent = await fetch(BASE + '/api/premium-dashboards/save', { method: 'POST', headers: { ...H, 'x-pmos-session': 's1' }, body }).then((x) => x.status);
134
+ ok('P2 an agent session is refused by the save route, unchanged', asAgent === 403, String(asAgent));
135
+ ok('P3 no script error', errs.length === 0, errs.join(' | '));
136
+ await ctx.close();
137
+
138
+ /* F: floors at 390 px, both themes */
139
+ for (const theme of ['light', 'dark']) {
140
+ const c2 = await browser.newContext({ viewport: { width: 390, height: 844 }, colorScheme: theme }), q = await c2.newPage();
141
+ await q.goto(BASE + '/premium-insights.html');
142
+ await until(() => q.evaluate(() => !!document.querySelector('#pdNew')));
143
+ await q.click('#pdNew'); await until(() => q.evaluate(() => !!document.querySelector('#oMain .stu'))); await sleep(400);
144
+ // measured once the dialog has finished opening: its rise animation scales the targets while it runs
145
+ const measure = () => q.evaluate(() => {
146
+ const sm = [...document.querySelectorAll('#oMain .stu button')].filter((b) => b.offsetParent).filter((b) => { const r = b.getBoundingClientRect(); return r.height < 44 || r.width < 44; }).map((b) => (b.dataset.st || b.textContent) + ':' + Math.round(b.getBoundingClientRect().width) + 'x' + Math.round(b.getBoundingClientRect().height));
147
+ const pane = document.querySelector('#dOut'); return { small: sm.length, which: sm, side: pane.scrollWidth - pane.clientWidth, doc: document.documentElement.scrollWidth - innerWidth };
148
+ });
149
+ await until(async () => (await measure()).small === 0, 4000);
150
+ const f = await measure();
151
+ ok(`F1 at 390 px (${theme}) every Studio target is 44 px or more and nothing scrolls sideways`, f.small === 0 && f.side <= 1 && f.doc <= 1, JSON.stringify(f));
152
+ await c2.close();
153
+ }
154
+ await shut().catch(() => {});
155
+ finish();
156
+ })().catch((e) => { console.error(e); finish(1); });
@@ -2,9 +2,10 @@
2
2
  * lib/board-premium.js builds from the routes the production Initiatives page reads: the Initiatives card (List, By stage, Timeline), the Sprint and
3
3
  * Coming up cards, Core documents, the dock and the standard dialog. The presses are Draft it on a core document, through POST /api/core-docs/draft,
4
4
  * and the board's own presses of pm/premium-acts.js (initiative premium-board-actions): the New asks card, New initiative, and a row's menu (move,
5
- * hold, cancel, archive and their Undo). Nothing here issues a document. */
5
+ * hold, cancel, archive and their Undo). Issue it on a document draft, read in a dialog, is POST /api/core-docs/issue (initiative premium-core-doc-issue). */
6
6
  import { pmPost } from './http.js';
7
- import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, store, crumbHtml, wireCrumb, kv, H, openAddDoc } from './premium-shell.js';
7
+ import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, CHECK, AI, store, crumbHtml, wireCrumb, kv, H, openAddDoc } from './premium-shell.js';
8
+ import { mdHtml, issueBody } from './premium-doc-edit.js';
8
9
  import { dotsBtn, openMenu, closeMenu, menuKey, asksHtml, onAsks, openIniForm } from './premium-acts.js';
9
10
 
10
11
  const MODE_KEY = 'pmos.premium.openAs';
@@ -105,7 +106,7 @@ function drawSide() {
105
106
  }
106
107
  function docRow(d) {
107
108
  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>`;
108
- 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>`;
109
+ return `<div class="dmr ${esc(d.st || '')}" role="listitem">${d.path ? `<button class="dmo" data-doc="${esc(d.key)}" aria-haspopup="dialog">` : '<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>${d.path ? '</button>' : '</span>'}<span class="dmq">${act}</span></div>`;
109
110
  }
110
111
  let docFilter = 'all', docQuery = '';
111
112
  const draftable = () => (M.docs.rows || []).filter((d) => d.st === 'missing' && d.act && d.act.kind === 'draft' && !d.running);
@@ -128,7 +129,7 @@ function drawDocs() {
128
129
  <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>`;
129
130
  drawDocList();
130
131
  if (hadQ) { const q = $('#dmQ'); q.focus(); q.setSelectionRange(q.value.length, q.value.length); }
131
- $('#docNote').textContent = 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent. Issuing, dropping and adding a document are not built on this page.';
132
+ $('#docNote').textContent = 'Draft it starts a read-only agent run that writes a draft for you to read. Nothing is sent. Press a document to read it; a draft has Issue it, which marks it issued and sends nothing. Dropping a document is not built on this page.';
132
133
  }
133
134
  $('#docTop').addEventListener('click', async (e) => {
134
135
  const f = e.target.closest('[data-dmf]'); if (f) { docFilter = f.dataset.dmf; drawDocList(); return; }
@@ -141,6 +142,7 @@ $('#docTop').addEventListener('click', async (e) => {
141
142
  $('#docTop').addEventListener('input', (e) => { if (e.target.id === 'dmQ') { docQuery = e.target.value; drawDocList(); } });
142
143
  const GOTAB = { rep: '/c3.html?tab=rep', init: '/c3.html?tab=init' };
143
144
  $('#docBody').addEventListener('click', async (e) => {
145
+ const o = e.target.closest('[data-doc]'); if (o) { openReader(M.docs.rows.find((x) => x.key === o.dataset.doc)); return; }
144
146
  const t = e.target.closest('[data-tab]'); if (t) { location.assign(GOTAB[t.dataset.tab] || '/c3.html'); return; }
145
147
  const b = e.target.closest('[data-draft]'); if (!b || b.disabled) return;
146
148
  const key = b.dataset.draft, d = M.docs.rows.find((x) => x.key === key);
@@ -151,6 +153,64 @@ $('#docBody').addEventListener('click', async (e) => {
151
153
  await load();
152
154
  });
153
155
 
156
+ /* ── a board document: read it, and issue a draft (initiative premium-core-doc-issue) ────────────────────── */
157
+ let rd = null; // { d, text, md, err, busy, msg, issued }
158
+ const rdGet = async (url) => { try { const r = await fetch(url, { credentials: 'same-origin' }); return await r.json(); } catch { return null; } };
159
+ function rdBar(r) {
160
+ const d = r.d;
161
+ if (r.issued && d.st !== 'draft') return `<div class="dsiss dsok" data-issue-bar="done" role="status"><span>${CHECK}Issued. Nothing was sent to anyone. The row now reads ${esc(d.state)}.</span></div>`;
162
+ if (d.st !== 'draft' || !d.slot) return '';
163
+ return `<div class="dsiss" data-issue-bar="draft"><span>${AI}PMOS drafted this from its sources. Nothing is sent. Read it, then issue it, or draft it again.</span><span class="dsa"><button class="dmcta dark" data-rd="issue"${r.busy ? ' disabled' : ''}>Issue it</button><button class="dmcta alt" data-rd="again"${r.busy ? ' disabled' : ''}>Draft it again</button></span></div>`
164
+ + (r.msg ? `<p class="note" id="rdErr" role="alert" style="margin:-4px 0 10px;color:var(--ember-ink)">${esc(r.msg)}</p>` : '');
165
+ }
166
+ function drawReader() {
167
+ const r = rd, d = r.d;
168
+ let body;
169
+ if (r.err) body = `<p class="empty3 plain">${esc(r.err)}</p>`;
170
+ else if (r.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
171
+ else { const m = r.md || (r.md = mdHtml(r.text)); body = (m.fm.length ? kv(m.fm) : '') + `<div class="dsrd no"><div class="dsbody">${m.html}</div></div>`; }
172
+ $('#oMain').innerHTML = `<article class="paper doc"><p class="dpath">${esc(d.path)}</p><div class="dsm"><span class="${d.st === 'ok' ? 'ok' : d.st === 'draft' ? 'warn' : 'mut'}">${esc(d.state)}</span>${d.when ? `<span>updated ${esc(d.when)}</span>` : ''}${d.by ? `<span>${esc(d.by)}</span>` : ''}</div>${rdBar(r)}<div id="shBody">${body}</div><p class="xn">${d.st === 'draft' ? 'A board draft is changed by drafting it again; the new draft replaces this one. ' : ''}The file changes only when you press Issue it.</p></article>`;
173
+ }
174
+ async function openReader(d) {
175
+ if (!d || !d.path) return;
176
+ const r = rd = { d, text: null, md: null, err: null, busy: false, msg: '', issued: false };
177
+ const say = d.title + ' is ' + d.state.toLowerCase() + (d.by ? '. ' + d.by + '.' : '.') + ' I can read the file with you and answer questions. I change nothing; only you issue it.';
178
+ openDlg({ eye: 'Document · real data', title: d.title, sub: M.board.name, say, stream: turnA(logHtml({ logTitle: 'Read from the repository', log: ['Found the file ' + d.path, 'Left the file as it is'] })) + turnA(ptx(say)), noteKey: 'doc:' + M.board.id + ':' + d.key, pane: '', label: 'Document' });
179
+ drawReader(); loadThread('doc:' + M.board.id + ':' + d.key);
180
+ await rdRead(r);
181
+ }
182
+ /** The file's latest revision, as the document sheet reads it (the log route first records an outside change, so an issue shows up). */
183
+ async function rdRead(r) {
184
+ const p = encodeURIComponent(r.d.path), ws = M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '';
185
+ const lg = await rdGet('/api/doc-sheet/log?path=' + p + ws); if (rd !== r) return;
186
+ const revs = lg && lg.ok ? lg.revisions || [] : [];
187
+ const at = revs.length ? await rdGet('/api/doc-sheet/at?path=' + p + '&rev=' + revs[revs.length - 1].rev + ws) : null; if (rd !== r) return;
188
+ r.err = null;
189
+ if (at && at.ok) r.text = at.text; else r.err = (at && at.error) || (lg && lg.error) || 'The file could not be read.';
190
+ r.md = null; drawReader();
191
+ }
192
+ $('#oMain').addEventListener('click', async (e) => {
193
+ const b = e.target.closest('[data-rd]'); if (!b || !rd || b.disabled) return;
194
+ const r = rd, d = r.d;
195
+ const fail = (m) => { r.busy = false; r.msg = m; drawReader(); };
196
+ r.msg = '';
197
+ if (b.dataset.rd === 'issue') {
198
+ const q = issueBody(M.board.ws, M.docs.scope, d.key, d.slot, false); if (q.error) return fail(q.error);
199
+ r.busy = true; drawReader();
200
+ const res = await pmPost('/api/core-docs/issue', q.body); if (rd !== r) return;
201
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be issued.');
202
+ toast('Issued. Nothing was sent to anyone.');
203
+ r.issued = true; r.busy = false; await load(); if (rd !== r) return;
204
+ r.d = M.docs.rows.find((x) => x.key === d.key) || r.d; r.text = null; r.md = null; drawReader(); await rdRead(r);
205
+ } else if (b.dataset.rd === 'again') {
206
+ r.busy = true; drawReader();
207
+ const res = await pmPost('/api/core-docs/draft', { ws: M.board.ws, scope: M.docs.scope, key: d.key }); if (rd !== r) return;
208
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The draft could not be started.');
209
+ toast('The agent is drafting “' + d.title + '” again. The new draft replaces this one when it is ready, and it sends nothing.');
210
+ r.busy = false; closeDlg(); await load();
211
+ }
212
+ });
213
+
154
214
  $('#addDoc').onclick = () => openAddDoc({ ws: M.board.ws, scope: M.docs.scope, sub: M.board.name, onAdded: load });
155
215
 
156
216
  /* ── new asks and New initiative (initiative premium-board-actions) ───────────────────────────────────────── */
@@ -1,6 +1,7 @@
1
1
  /* premium-doc-edit.js — the pure half of the premium document sheet's Edit and Proposals tabs (initiative briefing-premium-doc-edit).
2
2
  * No DOM and no fetch: it turns the answers of /api/doc-sheet/* into what the tabs draw, and builds the bodies of the presses. Every figure here is a
3
3
  * field of a route's answer; a proposal's section is stale only because the route says it is. */
4
+ const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
4
5
  const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
5
6
 
6
7
  /** One proposal as the tab draws it. `p` is a row of GET /api/doc-sheet/proposals. */
@@ -68,3 +69,32 @@ export function askLine(a) {
68
69
  if (a.state === 'failed') return a.error || 'The agent could not answer.';
69
70
  return '';
70
71
  }
72
+
73
+ /** Issue press (a core document draft). The route needs the workspace, the scope, the key and the draft's slot, and takes nothing else. */
74
+ export function issueBody(ws, scope, key, slot, unsaved) {
75
+ if (unsaved) return { error: 'You have unsaved changes in the Edit tab. Save or cancel them first, so the document you issue is the one you read.' };
76
+ if (!slot) return { error: 'This document has no open draft to issue.' };
77
+ return { body: { ws, scope, key, slot } };
78
+ }
79
+
80
+ /** The Read tab's text as html with its outline and front matter. Pure: the page puts the html in the sheet. */
81
+ export function mdHtml(text) {
82
+ const lines = String(text || '').replace(/\r/g, '').split('\n'), out = [], outline = [];
83
+ let i = 0, fm = [];
84
+ if (lines[0] === '---') { const e = lines.indexOf('---', 1); if (e > 0) { fm = lines.slice(1, e).map((l) => /^([A-Za-z_][\w -]*):\s*(.*)$/.exec(l)).filter(Boolean).slice(0, 10).map((m) => [m[1], m[2].replace(/^"(.*)"$/, '$1')]); i = e + 1; } }
85
+ let para = [], list = [];
86
+ const flushP = () => { if (para.length) { out.push(`<p>${esc(para.join(' '))}</p>`); para = []; } };
87
+ const flushL = () => { if (list.length) { out.push(`<ul>${list.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>`); list = []; } };
88
+ for (; i < lines.length; i++) {
89
+ const l = lines[i];
90
+ if (/^```/.test(l)) { flushP(); flushL(); const buf = []; for (i++; i < lines.length && !/^```/.test(lines[i]); i++) buf.push(lines[i]); out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`); continue; }
91
+ const h = /^(#{1,4})\s+(.*)$/.exec(l);
92
+ if (h) { flushP(); flushL(); const n = outline.length; outline.push(h[2]); out.push(`<h3 class="d2" id="ds-h${n}">${esc(h[2])}</h3>`); continue; }
93
+ if (/^\s*[-*]\s+/.test(l)) { flushP(); list.push(l.replace(/^\s*[-*]\s+/, '')); continue; }
94
+ if (/^\|/.test(l)) { flushP(); flushL(); const buf = [l]; while (i + 1 < lines.length && /^\|/.test(lines[i + 1])) buf.push(lines[++i]); out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`); continue; }
95
+ if (!l.trim()) { flushP(); flushL(); continue; }
96
+ flushL(); para.push(l.trim());
97
+ }
98
+ flushP(); flushL();
99
+ return { html: out.join(''), outline, fm };
100
+ }
@@ -5,7 +5,7 @@
5
5
  * existing /api/doc-sheet routes, initiative briefing-premium-doc-edit), Add a task and a task's status, and the bar under the stages (initiative
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
- import { proposalsModel, editBody, acceptBody, rejectBody, askBody, askLine } from './premium-doc-edit.js';
8
+ import { proposalsModel, editBody, acceptBody, rejectBody, askBody, askLine, issueBody, mdHtml } from './premium-doc-edit.js';
9
9
  import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, crumbHtml, wireCrumb, AI, openAddDoc } from './premium-shell.js';
10
10
  import { barHtml, onBar, closeMenu } from './premium-acts.js';
11
11
 
@@ -182,7 +182,7 @@ function docsHtml() {
182
182
  <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>
183
183
  <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>
184
184
  <div id="dmList"></div>
185
- <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>`;
185
+ <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. Issue it on a draft's sheet marks the draft as issued; nothing is sent. Dropping a document is not built on this page. A document you add is saved on the record; PMOS does not read a linked page.</p></section>`;
186
186
  }
187
187
  $('#iMain').addEventListener('input', (e) => { if (e.target.id === 'dmQ') { docQuery = e.target.value; drawDocList(); } });
188
188
  const draftable = () => M.docs.rows.filter((d) => !d.tech && d.st === 'missing' && d.act && d.act.kind === 'draft' && !d.running);
@@ -223,25 +223,13 @@ let sheet = null; // { d, tab, text, log, health, props, draft, why, ask, askT
223
223
  const TABS = [['read', 'Read'], ['edit', 'Edit'], ['props', 'Proposals'], ['log', 'Edit log'], ['health', 'Health']];
224
224
  const wsq = () => (M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '');
225
225
  const propsM = (s) => proposalsModel(s.props || []);
226
- function mdHtml(text) {
227
- const lines = String(text || '').replace(/\r/g, '').split('\n'), out = [], outline = [];
228
- let i = 0, fm = [];
229
- if (lines[0] === '---') { const e = lines.indexOf('---', 1); if (e > 0) { fm = lines.slice(1, e).map((l) => /^([A-Za-z_][\w -]*):\s*(.*)$/.exec(l)).filter(Boolean).slice(0, 10).map((m) => [m[1], m[2].replace(/^"(.*)"$/, '$1')]); i = e + 1; } }
230
- let para = [], list = [];
231
- const flushP = () => { if (para.length) { out.push(`<p>${esc(para.join(' '))}</p>`); para = []; } };
232
- const flushL = () => { if (list.length) { out.push(`<ul>${list.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>`); list = []; } };
233
- for (; i < lines.length; i++) {
234
- const l = lines[i];
235
- if (/^```/.test(l)) { flushP(); flushL(); const buf = []; for (i++; i < lines.length && !/^```/.test(lines[i]); i++) buf.push(lines[i]); out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`); continue; }
236
- const h = /^(#{1,4})\s+(.*)$/.exec(l);
237
- if (h) { flushP(); flushL(); const n = outline.length; outline.push(h[2]); out.push(`<h3 class="d2" id="ds-h${n}">${esc(h[2])}</h3>`); continue; }
238
- if (/^\s*[-*]\s+/.test(l)) { flushP(); list.push(l.replace(/^\s*[-*]\s+/, '')); continue; }
239
- if (/^\|/.test(l)) { flushP(); flushL(); const buf = [l]; while (i + 1 < lines.length && /^\|/.test(lines[i + 1])) buf.push(lines[++i]); out.push(`<pre class="mdp">${esc(buf.join('\n'))}</pre>`); continue; }
240
- if (!l.trim()) { flushP(); flushL(); continue; }
241
- flushL(); para.push(l.trim());
242
- }
243
- flushP(); flushL();
244
- return { html: out.join(''), outline, fm };
226
+ /** The bar above a draft (core document Issue, initiative premium-core-doc-issue). The words are fixed; the state is the row's own. */
227
+ function issueBar(s) {
228
+ const d = s.d;
229
+ if (s.issued && d.st !== 'draft') return `<div class="dsiss dsok" data-issue-bar="done" role="status"><span>${CHECK}Issued. Nothing was sent to anyone. The row now reads ${esc(d.state)}.</span></div>`;
230
+ if (d.st !== 'draft' || !d.slot) return '';
231
+ return `<div class="dsiss" data-issue-bar="draft"><span>${AI}PMOS drafted this from its sources. Nothing is sent. Read it, change what you like, then issue it.</span><button class="dmcta dark" data-ds="issue"${s.busy ? ' disabled' : ''}>Issue it</button></div>`
232
+ + (s.msg && s.tab === 'read' ? `<p class="note" id="dsErr" role="alert" style="margin:-4px 0 10px;color:var(--ember-ink)">${esc(s.msg)}</p>` : '');
245
233
  }
246
234
  function sheetPane() {
247
235
  const s = sheet, d = s.d;
@@ -251,7 +239,7 @@ function sheetPane() {
251
239
  if (s.err) body = `<p class="empty3 plain">${esc(s.err)}</p>`;
252
240
  else if (s.tab === 'read') {
253
241
  if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
254
- else { const m = s.md || (s.md = mdHtml(s.text)); body = (m.fm.length ? kv(m.fm) : '') + `<div class="dsrd${m.outline.length > 2 ? '' : ' no'}">${m.outline.length > 2 ? `<nav class="dso" aria-label="Outline"><p class="label">Outline <em>${m.outline.length} headings</em></p>${m.outline.map((t, n) => `<button data-go="${n}">${esc(t)}${s.props && propsM(s).marked.has(t) ? '<i></i>' : ''}</button>`).join('')}</nav>` : ''}<div class="dsbody">${m.html}</div></div>`; }
242
+ else { const m = s.md || (s.md = mdHtml(s.text)); body = issueBar(s) + (m.fm.length ? kv(m.fm) : '') + `<div class="dsrd${m.outline.length > 2 ? '' : ' no'}">${m.outline.length > 2 ? `<nav class="dso" aria-label="Outline"><p class="label">Outline <em>${m.outline.length} headings</em></p>${m.outline.map((t, n) => `<button data-go="${n}">${esc(t)}${s.props && propsM(s).marked.has(t) ? '<i></i>' : ''}</button>`).join('')}</nav>` : ''}<div class="dsbody">${m.html}</div></div>`; }
255
243
  } else if (s.tab === 'edit') {
256
244
  if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
257
245
  else {
@@ -355,6 +343,16 @@ async function sheetPress(act) {
355
343
  const fail = (m) => { s.busy = false; s.msg = m; drawSheet(); };
356
344
  if (act === 'rejno') { s.rejecting = null; s.msg = ''; drawSheet(); return; }
357
345
  if (act === 'discard') { s.draft = null; s.why = ''; s.msg = ''; drawSheet(); return; }
346
+ if (act === 'issue') {
347
+ const r = issueBody(M.board.ws, M.docs.scope, s.d.key, s.d.slot, s.draft != null && s.draft !== s.text); if (r.error) return fail(r.error);
348
+ s.busy = true; s.msg = ''; drawSheet();
349
+ const res = await pmPost('/api/core-docs/issue', r.body); if (sheet !== s) return;
350
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be issued.');
351
+ toast('Issued. Nothing was sent to anyone.');
352
+ s.issued = true; await load(); if (sheet !== s) return;
353
+ s.d = M.docs.rows.find((x) => x.key === s.d.key) || s.d;
354
+ return reloadSheet(s);
355
+ }
358
356
  if (act === 'save') {
359
357
  const r = editBody(s.d.path, s.text, s.draft == null ? s.text : s.draft, s.why); if (r.error) return fail(r.error);
360
358
  s.busy = true; s.msg = ''; drawSheet();
@@ -6,6 +6,7 @@
6
6
  * draft, PRD R2 to R4). Nothing else posts, and nothing is sent outward. */
7
7
  import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv } from './premium-shell.js';
8
8
  import { pmPost } from './http.js';
9
+ import { openStudio } from './premium-studio.js';
9
10
 
10
11
  let M = null; // the model
11
12
  let dash = 'all'; // the dashboard on screen
@@ -105,52 +106,9 @@ function noSeriesHtml() {
105
106
  $('#dashTabs').addEventListener('click', (e) => { const b = e.target.closest('[data-d]'); if (!b) return; dash = b.dataset.d; drawDash(); });
106
107
  $('#dashBar').addEventListener('click', (e) => { if (e.target.closest('#pdEdit')) openDashEdit(curDash()); else if (e.target.closest('#pdNew')) openDashEdit(null); });
107
108
 
108
- /* ── a saved dashboard: the edit dialog (PRD D4/D5). The one press posts POST /api/premium-dashboards/save. ─────────────────────────────── */
109
+ /* ── a dashboard is made and edited in the Insight Studio (initiative premium-studio-dashboard). Its one press posts POST /api/premium-dashboards/save. ── */
109
110
  async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
110
- function openDashEdit(D) {
111
- const fresh = !D, ids = D ? D.charts.slice() : [];
112
- const title = (id) => { const m = (M.measures || []).find((x) => x.id === id); return m ? m.title : id; };
113
- const why = (id) => { const m = (M.measures || []).find((x) => x.id === id); return !m ? 'No record any more' : m.charted ? '' : 'No series yet'; };
114
- const listHtml = () => ids.length ? ids.map((id, i) => `<div class="pdrow" role="listitem"><span><b>${esc(title(id))}</b>${why(id) ? `<small>${esc(why(id))}</small>` : ''}</span><span class="pdmv"><button type="button" class="round" data-mv="${i}:-1" aria-label="Move ${esc(title(id))} up" ${i ? '' : 'disabled'}>${ICO('<path d="M12 19V5M6 11l6-6 6 6"/>')}</button><button type="button" class="round" data-mv="${i}:1" aria-label="Move ${esc(title(id))} down" ${i < ids.length - 1 ? '' : 'disabled'}>${ICO('<path d="M12 5v14M6 13l6 6 6-6"/>')}</button><button type="button" class="round" data-rm="${i}" aria-label="Take ${esc(title(id))} off">${ICO('<path d="M6 6l12 12M18 6 6 18"/>')}</button></span></div>`).join('') : '<p class="note" style="margin:0">No measure yet. Add one below.</p>';
115
- const addHtml = () => { const L = (M.measures || []).filter((m) => !ids.includes(m.id)); return L.length ? `<label>Add a measure<select id="pdAdd"><option value="">Choose a KR metric</option>${L.map((m) => `<option value="${esc(m.id)}">${esc(m.title)}${m.charted ? '' : ' (no series yet)'}</option>`).join('')}</select></label>` : '<p class="note" style="margin:0">Every KR metric of this workspace is on this dashboard.</p>'; };
116
- const checksTxt = () => [ids.length > 6 ? 'This dashboard holds ' + ids.length + ' charts. A dashboard that serves one routine usually holds six or fewer.' : '', new Set(ids).size !== ids.length ? 'The same measure is on this dashboard twice.' : ''].filter(Boolean).join(' ');
117
- const form = `<div class="addf"><p class="note" style="margin:0">A dashboard is a named list of this board's measures. It is saved in the workspace's state folder and changes nothing else: no record, no report and no console layout.</p>
118
- <label>Name<input id="pdN" maxlength="60" value="${esc(D ? D.name : '')}" placeholder="For example: Weekly partner review"></label>
119
- <label>What it is for<input id="pdP" maxlength="200" value="${esc(D ? D.purpose : '')}" placeholder="The routine it serves, in one line"></label>
120
- <label class="pdchk"><input type="checkbox" id="pdMain" ${D && D.main ? 'checked' : ''}>Make it the main dashboard of this board</label>
121
- <div><span class="label">Charts, in order</span><div class="pdlist" id="pdList" role="list">${listHtml()}</div></div>
122
- <div id="pdAddW">${addHtml()}</div>
123
- <p class="note pdck" id="pdCk" role="status">${esc(checksTxt())}</p>
124
- <p class="note" id="pdM" role="status" style="margin:0;min-height:1.2em"></p>
125
- <div class="cact"><button class="cta" id="pdGo">Save</button><button class="cta alt" id="pdNo">Cancel</button>${fresh ? '' : '<button class="cta alt" id="pdDel">Remove the dashboard</button>'}</div></div>`;
126
- openDlg({ eye: (fresh ? 'New dashboard' : 'Dashboard') + ' · real data', title: fresh ? 'New dashboard' : D.name, sub: M.board.name, say: 'Name the dashboard, say what it is for and choose its measures.', stream: turnA(ptx('Name the dashboard, say what it is for and choose its measures in the order you read them. I save it in the workspace\'s state folder and change nothing else.')), noteKey: null, pane: `<article class="paper doc">${form}</article>`, label: 'Dashboard' });
127
- $('#askF').hidden = true;
128
- const redraw = () => { $('#pdList').innerHTML = listHtml(); $('#pdAddW').innerHTML = addHtml(); $('#pdCk').textContent = checksTxt(); };
129
- let armed = false;
130
- $('#oMain').onchange = (e) => { if (e.target.id === 'pdAdd' && e.target.value) { ids.push(e.target.value); redraw(); const s = $('#pdAdd'); if (s) s.focus(); } };
131
- $('#oMain').onclick = async (e) => {
132
- const mv = e.target.closest('[data-mv]'), rm = e.target.closest('[data-rm]');
133
- if (mv) { const [i, d] = mv.dataset.mv.split(':').map(Number), j = i + d; [ids[i], ids[j]] = [ids[j], ids[i]]; redraw(); const b = $(`#pdList [data-mv="${j}:${d}"]`) || $(`#pdList [data-mv="${j}:${-d}"]`); if (b) b.focus(); return; }
134
- if (rm) { ids.splice(+rm.dataset.rm, 1); redraw(); return; }
135
- if (e.target.closest('#pdNo')) { closeDlg(); return; }
136
- const m = $('#pdM');
137
- if (e.target.closest('#pdDel')) {
138
- if (!armed) { armed = true; e.target.closest('#pdDel').textContent = 'Press again to remove it'; m.textContent = 'Removing takes the dashboard off this board. The measures and their records stay.'; return; }
139
- const b = e.target.closest('#pdDel'); b.disabled = true;
140
- const res = await saveDash({ id: D.id, remove: true });
141
- if (!res || res.ok !== true) { b.disabled = false; m.textContent = (res && res.error) || 'The dashboard could not be removed.'; return; }
142
- toast('Dashboard removed. The line is saved in the workspace\'s state folder.'); dash = 'all'; closeDlg(); await load(); return;
143
- }
144
- if (!e.target.closest('#pdGo')) return;
145
- const name = $('#pdN').value.trim(), purpose = $('#pdP').value.trim();
146
- if (!name) { m.textContent = 'Give the dashboard a name.'; $('#pdN').focus(); return; }
147
- if (!purpose) { m.textContent = 'Say what the dashboard is for, in one line.'; $('#pdP').focus(); return; }
148
- const go = $('#pdGo'); go.disabled = true; m.textContent = 'Saving.';
149
- const res = await saveDash({ id: D ? D.id : undefined, name, purpose, charts: ids, main: $('#pdMain').checked });
150
- if (!res || res.ok !== true) { go.disabled = false; m.textContent = (res && res.error) || 'The dashboard could not be saved.'; return; }
151
- toast('Dashboard saved in the workspace\'s state folder.'); if (res.dashboard) dash = res.dashboard.id; closeDlg(); await load();
152
- };
153
- }
111
+ function openDashEdit(D) { openStudio({ M, D, tile: tileHtml, save: saveDash, done: async (id) => { dash = id || 'all'; await load(); } }); }
154
112
  $('#dashBody').addEventListener('click', (e) => { const o = e.target.closest('[data-open]'); if (o) openChart(byKey(o.dataset.open)); });
155
113
  $('#dashBody').addEventListener('keydown', (e) => {
156
114
  const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
@@ -213,6 +213,105 @@ export function openAddDoc(o) {
213
213
  };
214
214
  }
215
215
 
216
+ /* ── Search (Ctrl K or "/") and the bell, in the header of every premium page (initiative premium-search-bell). Reads only; a press goes to a page. ── */
217
+ const SRCH = '<svg class="i" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></svg>';
218
+ const BELL = '<svg class="i" viewBox="0 0 24 24"><path d="M6 16V11a6 6 0 0 1 12 0v5l2 2H4z"/><path d="M10 20a2 2 0 0 0 4 0"/></svg>';
219
+ const IC = (d) => `<svg class="i" viewBox="0 0 24 24"><path d="${d}"/></svg>`;
220
+ const GL = { place: IC('M4 5h16v14H4zM4 10h16'), ini: IC('M12 3l9 9-9 9-9-9z'), doc: IC('M6 3h9l4 4v14H6zM14 3v5h5'), ses: IC('M5 4l14 8-14 8z'), need: IC('M12 4v10M12 18v2') };
221
+ const PLACES = [['Briefing', '/premium.html'], ['My work', '/premium-work.html'], ['Board', '/premium-board.html'], ['Insights', '/premium-insights.html']];
222
+ const PV_WS = new URLSearchParams(location.search).get('ws');
223
+ const pvQ = (sep) => (PV_WS ? sep + 'ws=' + encodeURIComponent(PV_WS) : '');
224
+ async function pvGet(u) { try { const r = await fetch(u, { credentials: 'same-origin' }); return { status: r.status, j: await r.json() }; } catch { return { status: 0, j: null }; } }
225
+ const pvOv = { kind: null, back: null, at: 0, list: [], pal: null, need: null };
226
+ function pvMount() {
227
+ const a = $('#toConsole'); if (!a || $('#pvSearch')) return;
228
+ a.insertAdjacentHTML('beforebegin', `<button class="glass round" id="pvSearch" aria-haspopup="dialog" aria-label="Search (Ctrl K)" title="Search (Ctrl K)">${SRCH}</button><button class="glass round pv-hp" id="pvBell" aria-haspopup="dialog" aria-label="Needs you" title="Needs you">${BELL}<span class="pv-bdg" id="pvBdg" hidden></span></button>`);
229
+ document.body.insertAdjacentHTML('beforeend', '<div class="pv-scrim" id="pvScrim"></div><div class="pv-ov" id="pvOv" role="dialog" aria-modal="true" hidden inert></div>');
230
+ $('#pvSearch').onclick = () => pvOpen('pal'); $('#pvBell').onclick = () => pvOpen('bell'); $('#pvScrim').onclick = pvClose;
231
+ pvNeeds();
232
+ }
233
+ export function pvClose() {
234
+ if (!pvOv.kind) return;
235
+ pvOv.kind = null; $('#pvOv').hidden = true; $('#pvOv').inert = true; $('#pvScrim').classList.remove('on');
236
+ $$('.rail,main.stage,#dock').forEach((x) => { x.inert = false; }); $('#dock').inert = !document.body.classList.contains('docked'); document.documentElement.style.overflow = '';
237
+ if (pvOv.back) { try { pvOv.back.focus(); } catch { /* gone */ } }
238
+ }
239
+ function pvOpen(kind) {
240
+ if (pvOv.kind === kind) { pvClose(); return; }
241
+ if (pvOv.kind) pvClose();
242
+ const ae = document.activeElement; pvOv.back = ae && ae !== document.body ? ae : $(kind === 'pal' ? '#pvSearch' : '#pvBell');
243
+ pvOv.kind = kind; pvOv.at = 0;
244
+ $$('.rail,main.stage,#dock').forEach((x) => { x.inert = true; }); document.documentElement.style.overflow = 'hidden';
245
+ const o = $('#pvOv'); o.className = 'pv-ov ' + kind; o.setAttribute('aria-label', kind === 'pal' ? 'Search' : 'Needs you'); o.hidden = false; o.inert = false; $('#pvScrim').classList.add('on');
246
+ if (kind === 'pal') { o.innerHTML = '<div class="pv-pin">' + SRCH + '<input id="pvQ" type="text" placeholder="Search places, initiatives, documents and sessions" aria-label="Search" autocomplete="off" role="combobox" aria-expanded="true" aria-controls="pvList"><kbd>Esc</kbd></div><div id="pvList" role="listbox" aria-label="Results"></div><p class="pv-note">Ctrl K or / opens this from any page. Arrow keys move, Enter opens.</p>'; $('#pvQ').focus(); pvPal(); }
247
+ else { o.innerHTML = '<div class="pv-hd"><h2>Needs you</h2><small id="pvN"></small></div><div id="pvList" class="pv-lst"></div><p class="pv-note">Read from the Briefing. A press opens it.</p>'; pvBellDraw(); pvNeeds(); }
248
+ }
249
+ const pvGo = (it) => { pvClose(); if (it.go) location.assign(it.go); };
250
+ const pvRow = (it, i, sel) => `<button type="button" class="pv-row" role="option" id="pvo${i}" data-i="${i}" aria-selected="${sel}"><span class="gl">${GL[it.gl]}</span><span><b>${esc(it.t)}</b>${it.s ? `<small>${esc(it.s)}</small>` : ''}</span></button>`;
251
+ async function pvPal() {
252
+ if (!pvOv.pal) {
253
+ const [b, d, s] = await Promise.all([pvGet('/api/boards/backlog?limit=200' + pvQ('&')), pvGet('/api/core-docs?level=board' + pvQ('&')), pvGet('/api/sessions')]);
254
+ const miss = [];
255
+ const ini = b.j && b.j.ok && Array.isArray(b.j.rows) ? b.j.rows.map((r) => ({ g: 'Initiatives', gl: 'ini', t: r.title || r.id, s: [r.lane, r.stage].filter(Boolean).join(' · '), go: '/premium-initiative.html?id=' + encodeURIComponent(r.id) + (b.j.ws ? '&ws=' + encodeURIComponent(b.j.ws) + '&board=' + encodeURIComponent(b.j.board) : '') })) : (miss.push('initiatives'), []);
256
+ const docs = d.j && d.j.ok && Array.isArray(d.j.docs) ? d.j.docs.map((x) => ({ g: 'Documents', gl: 'doc', t: x.title || x.key, s: d.j.scope && d.j.scope.name ? d.j.scope.name : 'Board', go: '/premium-board.html' + pvQ('?') })) : (miss.push('documents'), []);
257
+ const ses = s.j && Array.isArray(s.j.sessions) ? s.j.sessions.filter((x) => !x.automatic).map((x) => ({ g: 'Sessions', gl: 'ses', t: x.name || x.id, s: [x.cwd && x.cwd !== '.' ? x.cwd : '', x.state].filter(Boolean).join(' · '), go: '/c3.html' })) : (miss.push('sessions'), []);
258
+ pvOv.pal = { items: [...PLACES.map(([t, go]) => ({ g: 'Places', gl: 'place', t, s: 'Place', go })), ...ini, ...docs, ...ses], miss };
259
+ }
260
+ if (pvOv.kind === 'pal') pvPalDraw();
261
+ }
262
+ function pvPalDraw() {
263
+ const box = $('#pvList'), q = ($('#pvQ') || { value: '' }).value.trim().toLowerCase(), P = pvOv.pal;
264
+ const items = P ? P.items.filter((x) => !q || (x.t + ' ' + (x.s || '')).toLowerCase().includes(q)) : PLACES.map(([t, go]) => ({ g: 'Places', gl: 'place', t, s: 'Place', go }));
265
+ const per = {}, list = items.filter((x) => (per[x.g] = (per[x.g] || 0) + 1) <= (q ? 6 : 4));
266
+ pvOv.list = list; pvOv.at = Math.min(pvOv.at, Math.max(0, list.length - 1));
267
+ let g = '', h = '';
268
+ list.forEach((it, i) => { if (it.g !== g) { g = it.g; h += `<div class="pv-grp">${esc(g)}</div>`; } h += pvRow(it, i, i === pvOv.at); });
269
+ if (!list.length) h = '<p class="pv-note" role="status">Nothing matches.</p>';
270
+ if (!P) h += '<p class="pv-note" role="status">Reading the records.</p>'; else if (P.miss.length) h += `<p class="pv-note" role="status">Not read: ${esc(P.miss.join(', '))}.</p>`;
271
+ box.innerHTML = h;
272
+ const a = $('#pvo' + pvOv.at); if (a) { $('#pvQ').setAttribute('aria-activedescendant', a.id); a.scrollIntoView({ block: 'nearest' }); }
273
+ }
274
+ /** The Briefing page feeds the bell the answer it has already read (so the bell asks nothing there); every other page asks once. r: the parsed /api/briefing-premium answer or null. */
275
+ export function pvFeed(r) {
276
+ const M = r && r.ok && r.model, L = M && M.list;
277
+ pvOv.need = r && r.state === 'reading' ? { state: 'reading' } : L ? { state: 'ready', count: L.count, rows: L.rows || [] } : { state: 'error' };
278
+ const n = pvOv.need, b = $('#pvBdg'), btn = $('#pvBell'); if (!b) return;
279
+ const on = n.state === 'ready' && n.count > 0;
280
+ b.hidden = !on; b.textContent = on ? (n.count > 99 ? '99+' : String(n.count)) : '';
281
+ btn.setAttribute('aria-label', n.state === 'ready' ? 'Needs you: ' + n.count : 'Needs you');
282
+ if (pvOv.kind === 'bell') pvBellDraw();
283
+ }
284
+ const pvOnBriefing = () => /^\/premium\.html$/.test(location.pathname);
285
+ async function pvNeeds() {
286
+ if (pvOnBriefing()) return;
287
+ const r = await pvGet('/api/briefing-premium' + pvQ('?'));
288
+ pvFeed(r.status === 202 ? { state: 'reading' } : r.j);
289
+ }
290
+ function pvBellDraw() {
291
+ const n = pvOv.need, box = $('#pvList'); if (!box) return;
292
+ $('#pvN').textContent = n && n.state === 'ready' ? String(n.count) : '';
293
+ if (!n || n.state === 'reading') { box.innerHTML = '<p class="pv-note" role="status">Reading the initiative state. What needs you is not known yet.</p>'; return; }
294
+ if (n.state === 'error') { box.innerHTML = '<p class="pv-note" role="status">What needs you could not be read.</p>'; return; }
295
+ if (!n.rows.length) { box.innerHTML = '<p class="pv-note" role="status">Nothing needs you.</p>'; return; }
296
+ pvOv.list = n.rows.map((r) => ({ gl: 'need', t: r.title, s: r.subject, go: '/premium.html' + pvQ('?') }));
297
+ box.innerHTML = pvOv.list.map((it, i) => pvRow(it, i, false).replace('role="option"', 'role="listitem"').replace(' aria-selected="false"', '')).join('') + (n.count > n.rows.length ? `<p class="pv-note">${n.count - n.rows.length} more on the Briefing.</p>` : '');
298
+ }
299
+ document.addEventListener('click', (e) => { const b = e.target.closest('#pvList .pv-row'); if (b && pvOv.list[+b.dataset.i]) pvGo(pvOv.list[+b.dataset.i]); });
300
+ document.addEventListener('input', (e) => { if (e.target.id === 'pvQ') { pvOv.at = 0; pvPalDraw(); } });
301
+ addEventListener('keydown', (e) => {
302
+ if (pvOv.kind) {
303
+ if (e.key === 'Escape') { e.preventDefault(); e.stopImmediatePropagation(); pvClose(); return; }
304
+ if (pvOv.kind === 'pal' && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) { e.preventDefault(); const n = pvOv.list.length; if (n) { pvOv.at = (pvOv.at + (e.key === 'ArrowDown' ? 1 : n - 1)) % n; pvPalDraw(); } }
305
+ else if (pvOv.kind === 'pal' && e.key === 'Enter' && pvOv.list[pvOv.at]) { e.preventDefault(); pvGo(pvOv.list[pvOv.at]); }
306
+ else if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'K')) { e.preventDefault(); pvClose(); }
307
+ return;
308
+ }
309
+ if ($('#dlg').classList.contains('on') || !$('#pvSearch')) return;
310
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && (e.key === 'k' || e.key === 'K')) { e.preventDefault(); pvOpen('pal'); return; }
311
+ const t = document.activeElement;
312
+ if (e.key === '/' && !e.ctrlKey && !e.metaKey && !e.altKey && !(t && t.matches && t.matches('input,textarea,select,[contenteditable="true"]'))) { e.preventDefault(); pvOpen('pal'); }
313
+ }, true);
314
+ pvMount();
216
315
  /* ── Settings: the two things that cannot be defaulted (initiative premium-settings) ────────────────────────────────────────────────────
217
316
  * Workspaces: GET /api/workspaces · POST /api/workspaces, /api/workspaces/forget. Connectors: GET and POST /api/proactive/settings {briefSources}.
218
317
  * Each press saves what the console's section saves, and nothing else. Every other setting runs on a default and stays in the console. */