create-pmos 0.262.0 → 0.264.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,127 @@
1
+ 'use strict';
2
+ /* premium-dashboards.js — the dashboards the PM makes on the premium Insights page (initiative briefing-premium-reports, PRD D1 and D2).
3
+ * THE ONE WRITER and THE ONE FOLD of <state>/premium-dashboards.jsonl.
4
+ *
5
+ * NAME_MAX · PURPOSE_MAX · CHARTS_MAX · ADVISED_MAX
6
+ * ledgerFile(root) · readLines(file)
7
+ * check(input) → { ok: true, value } | { ok: false, status, error } PURE: the shape only
8
+ * fold(lines) → { [board]: [{ id, board, name, purpose, charts, main, at }] } PURE
9
+ * list(root, board) → the dashboards of one board, the main one first, then in the order they were made
10
+ * save(root, input, actor, { now, known }) → { ok: true, dashboard, dashboards } | { ok: false, status, error }
11
+ *
12
+ * THE LEDGER. Lines { v: 1, ev: save | remove, id, board, name, purpose, charts, main, actor, at }. `board` is the board's id in the workspace whose
13
+ * state folder holds the file. `charts` is an ordered list of KR metric ids. The fold keeps the last save of each id and drops an id once it is removed.
14
+ * One dashboard per board is main: the latest save that says main wins, and the others read as not main. The file is never rewritten. A torn line, or one
15
+ * without an id and a board, is skipped. This store is the premium page's own: the console's dashboard layouts (lib/report-dashboards.js) are not touched.
16
+ */
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ const LEDGER = 'premium-dashboards.jsonl';
21
+ const NAME_MAX = 60;
22
+ const PURPOSE_MAX = 200;
23
+ const CHARTS_MAX = 24; // a hard limit on what one save may hold
24
+ const ADVISED_MAX = 6; // the Studio's check: a dashboard serves one routine and holds six charts or fewer (said, never enforced)
25
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/;
26
+
27
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
28
+ const refuse = (status, error) => ({ ok: false, status, error });
29
+ const tidy = (v) => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : '');
30
+ const norm = (t) => tidy(t).toLowerCase();
31
+
32
+ function ledgerFile(root) {
33
+ const abs = path.resolve(String(root));
34
+ return path.join(abs, require('./report-draft.js').stateRel(abs), LEDGER);
35
+ }
36
+ function readLines(file) {
37
+ let text = '';
38
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
39
+ const out = [];
40
+ for (const raw of text.split('\n')) {
41
+ if (!raw.trim()) continue;
42
+ try { const l = JSON.parse(raw); if (isObj(l) && (l.ev === 'save' || l.ev === 'remove') && typeof l.id === 'string' && typeof l.board === 'string') out.push(l); } catch { /* a torn line is skipped */ }
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** Check the fields of a save or a remove. Whether the board and the charts exist is the route's check (it passes `known`). */
48
+ function check(input) {
49
+ const i = isObj(input) ? input : {};
50
+ const board = typeof i.board === 'string' ? i.board : '';
51
+ if (!ID_RE.test(board)) return refuse(400, 'Name the board the dashboard belongs to.');
52
+ const id = i.id == null || i.id === '' ? null : i.id;
53
+ if (id !== null && (typeof id !== 'string' || !ID_RE.test(id))) return refuse(400, 'That dashboard id is not valid.');
54
+ if (i.remove === true) {
55
+ if (id === null) return refuse(400, 'Say which dashboard to remove.');
56
+ return { ok: true, value: { remove: true, id, board } };
57
+ }
58
+ const name = tidy(i.name);
59
+ if (!name) return refuse(400, 'Give the dashboard a name.');
60
+ if (name.length > NAME_MAX) return refuse(400, `The name can be at most ${NAME_MAX} characters.`);
61
+ const purpose = tidy(i.purpose);
62
+ if (!purpose) return refuse(400, 'Say what the dashboard is for, in one line.');
63
+ if (purpose.length > PURPOSE_MAX) return refuse(400, `The purpose can be at most ${PURPOSE_MAX} characters.`);
64
+ if (!Array.isArray(i.charts)) return refuse(400, 'charts must be a list of KR metric ids.');
65
+ if (i.charts.length > CHARTS_MAX) return refuse(400, `A dashboard can hold at most ${CHARTS_MAX} charts.`);
66
+ const charts = [];
67
+ for (const c of i.charts) {
68
+ if (typeof c !== 'string' || !ID_RE.test(c)) return refuse(400, 'Each chart must be a KR metric id.');
69
+ if (!charts.includes(c)) charts.push(c);
70
+ }
71
+ return { ok: true, value: { remove: false, id, board, name, purpose, charts, main: i.main === true } };
72
+ }
73
+
74
+ /** Every board's dashboards after the ledger's lines, in order. PURE. The main one of a board is the last one saved with main; a later save of that
75
+ * same dashboard without main, or its removal, leaves the board with none. */
76
+ function fold(lines) {
77
+ const byId = new Map(); // id → dashboard; `first` keeps the order they were first made
78
+ const mainOf = new Map(); // board → id
79
+ let made = 0;
80
+ for (const l of lines || []) {
81
+ const prev = byId.get(l.id);
82
+ if (prev && prev.board !== l.board) continue; // an id never moves between boards
83
+ if (l.ev === 'remove') { byId.delete(l.id); if (mainOf.get(l.board) === l.id) mainOf.delete(l.board); continue; }
84
+ byId.set(l.id, { id: l.id, board: l.board, name: tidy(l.name), purpose: tidy(l.purpose), charts: Array.isArray(l.charts) ? l.charts.filter((c) => typeof c === 'string') : [], at: l.at || null, first: prev ? prev.first : made++ });
85
+ if (l.main === true) mainOf.set(l.board, l.id); else if (mainOf.get(l.board) === l.id) mainOf.delete(l.board);
86
+ }
87
+ const out = {};
88
+ for (const d of byId.values()) (out[d.board] = out[d.board] || []).push(d);
89
+ for (const b of Object.keys(out)) {
90
+ out[b] = out[b].map((d) => Object.assign(d, { main: mainOf.get(b) === d.id }))
91
+ .sort((a, z) => (z.main - a.main) || (a.first - z.first))
92
+ .map(({ id, board, name, purpose, charts, main, at }) => ({ id, board, name, purpose, charts, main, at }));
93
+ }
94
+ return out;
95
+ }
96
+
97
+ const list = (root, board) => fold(readLines(ledgerFile(root)))[board] || [];
98
+
99
+ /** THE SINGLE WRITER of premium-dashboards.jsonl. `v`, `id` (for a new one) and `at` are set here.
100
+ * known = { charts: Set of KR metric ids of the workspace } — a chart outside it is refused. */
101
+ function save(root, input, actor, { now, known } = {}) {
102
+ const c = check(input);
103
+ if (!c.ok) return c;
104
+ const v = c.value;
105
+ const file = ledgerFile(root);
106
+ const have = list(root, v.board);
107
+ const t = now == null ? Date.now() : now;
108
+ let line;
109
+ if (v.remove) {
110
+ if (!have.some((d) => d.id === v.id)) return refuse(404, 'That dashboard is not on this board.');
111
+ line = { v: 1, ev: 'remove', id: v.id, board: v.board, actor: actor || null, at: new Date(t).toISOString() };
112
+ } else {
113
+ if (v.id !== null && !have.some((d) => d.id === v.id)) return refuse(404, 'That dashboard is not on this board.');
114
+ if (have.some((d) => d.id !== v.id && norm(d.name) === norm(v.name))) return refuse(409, `“${v.name}” is already a dashboard on this board.`);
115
+ const ks = known && known.charts;
116
+ const gone = ks ? v.charts.filter((x) => !ks.has(x)) : [];
117
+ if (gone.length) return refuse(400, `No KR metric record is called ${gone.map((x) => '“' + x + '”').join(', ')} in this workspace.`);
118
+ const id = v.id || 'pd-' + t.toString(36) + '-' + (readLines(file).length + 1);
119
+ line = { v: 1, ev: 'save', id, board: v.board, name: v.name, purpose: v.purpose, charts: v.charts, main: v.main, actor: actor || null, at: new Date(t).toISOString() };
120
+ }
121
+ fs.mkdirSync(path.dirname(file), { recursive: true });
122
+ fs.appendFileSync(file, JSON.stringify(line) + '\n');
123
+ const after = list(root, v.board);
124
+ return { ok: true, dashboard: v.remove ? null : after.find((d) => d.id === line.id) || null, dashboards: after };
125
+ }
126
+
127
+ module.exports = { NAME_MAX, PURPOSE_MAX, CHARTS_MAX, ADVISED_MAX, ledgerFile, readLines, check, fold, list, save };
@@ -82,6 +82,7 @@ const MODULES = Object.freeze([
82
82
  'routes-report-setups', // report-workspace: recurring reports, the Ask box, the finder, the report documents and their export (report-setups.jsonl)
83
83
  'routes-core-docs', // core-documents: the core documents of each level, Draft it (a core-doc run), Issue it and Drop (core-docs.jsonl)
84
84
  'routes-custom-docs', // briefing-premium-adddoc: the documents the PM adds beyond the core set, Add a document (custom-docs.jsonl)
85
+ 'routes-premium-dashboards', // briefing-premium-reports: the dashboards the PM makes on premium Insights (premium-dashboards.jsonl; page-press POST save)
85
86
  'routes-report-design', // report-design-studio: the design studio (describe, samples, turns, versions, This is it), cycle renders and decisions, speaker notes and pins
86
87
  'routes-report-structure', // report-structure: the structure step (turns, versions, Use this structure, sources and their checks, dry run) and the chart store (GET /api/charts)
87
88
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
@@ -4,13 +4,18 @@
4
4
  * 200 { ok, state: 'ready', model, as_of } | 500 { ok: false, state: 'error', error }
5
5
  * model is lib/insights-premium.js build(), made from what the console's Reports tab reads: /api/boards (the board list), the KR metric records of the
6
6
  * workspace with the line status the Calendar's Quarter pane computes from them (routes-c3-strategy.js outcomeOf; /api/c3-strategy itself drops the dated
7
- * readings, so the records are read here), and /api/report (the report files). None starts a cold repository read, so this route does not answer 202. Read-only: it writes nothing and the page posts nothing. */
7
+ * readings, so the records are read here), and /api/report (the report files). None starts a cold repository read, so this route does not answer 202.
8
+ * briefing-premium-reports adds the board's saved dashboards (lib/premium-dashboards.js list) and the workspace's GET /api/report-setups answer
9
+ * (setups, findings, asks). That GET is the console's own read: like the console, it may move old dashboard schedules into recurring reports once
10
+ * per repository. This route itself writes nothing. The page's presses post to /api/report-setups/* and /api/premium-dashboards/save. */
8
11
  const Insights = require('./insights-premium.js');
9
12
  const boards = require('./routes-boards.js');
10
13
  const strategy = require('./routes-c3-strategy.js');
11
14
  const { repoScript } = require('./repo-script.js');
12
15
  const { recordsDirFor } = require('./records-dir.js');
13
16
  const reports = require('./routes-reports.js');
17
+ const setups = require('./routes-report-setups.js');
18
+ const PD = require('./premium-dashboards.js');
14
19
 
15
20
  /** GET `pathAndQuery` from a route module's own handler, as the Board page's route does, and return { status, body }. */
16
21
  async function via(mod, pathAndQuery, req, ctx) {
@@ -42,9 +47,16 @@ module.exports = {
42
47
  outcomes = require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics').map((k) => strategy.outcomeOf(k, day));
43
48
  } catch (e) { return fail('the KR metric records could not be read: ' + ((e && e.message) || e)); }
44
49
  const reportsOk = !!(rp.body && rp.body.ok !== false);
50
+ const missing = reportsOk ? [] : ['reports'];
51
+ let saved = [];
52
+ if (pick && pick.id) { try { saved = PD.list(require('path').resolve(ctx.getWs(pick.ws).root), pick.id); } catch { missing.push('dashboards'); } }
53
+ const su = await via(setups, '/api/report-setups' + q, req, ctx).catch(() => ({ status: 500, body: null }));
54
+ const setupsOk = su.status === 200 && !!su.body && Array.isArray(su.body.setups);
55
+ if (!setupsOk) missing.push('report setups');
45
56
  const model = Insights.build({
46
57
  now: Date.now(), board: pick ? { ws: pick.ws, id: pick.id, name: pick.name } : { ws, id: null, name: 'Insights' }, boards: all.map((x) => ({ ws: x.ws, id: x.id, name: x.name })),
47
- outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing: reportsOk ? [] : ['reports'],
58
+ outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing, saved,
59
+ setups: setupsOk ? su.body : null,
48
60
  });
49
61
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
50
62
  return true;
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+ /* routes-premium-dashboards.js — the dashboards the PM makes on the premium Insights page (initiative briefing-premium-reports, PRD D2).
3
+ *
4
+ * POST /api/premium-dashboards/save { ws, board, id?, name, purpose, charts, main, remove? } → { ok, dashboard, dashboards }
5
+ * one `save` or `remove` line in <state>/premium-dashboards.jsonl (lib/premium-dashboards.js, the one writer)
6
+ *
7
+ * The page reads the dashboards through GET /api/insights-premium, so this module has no GET.
8
+ *
9
+ * WHO WRITES. The POST refuses a request that carries an agent session header (403), as routes-custom-docs.js does, and passes pm-guard
10
+ * requirePagePress: the launch nonce and the page's origin. The board must be one of the workspace's boards (routes-boards.js frameFor), and every chart
11
+ * must be a KR metric record of that workspace (its `rid`, the id the Insights model gives a chart). The route stores what the PM chose and nothing else: no chart, report or console layout changes. */
12
+ const guard = require('./pm-guard.js');
13
+ const PD = require('./premium-dashboards.js');
14
+ const boards = require('./routes-boards.js');
15
+ const { repoScript } = require('./repo-script.js');
16
+ const { recordsDirFor } = require('./records-dir.js');
17
+
18
+ const text = (v) => (typeof v === 'string' ? v : '');
19
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
20
+
21
+ function wsOf(ctx, id) {
22
+ const w = ctx.getWs(id || null);
23
+ return w && (!id || w.id === id) ? w : null;
24
+ }
25
+ /** The board ids of a workspace (lib/routes-boards.js frameFor). null when they cannot be read. */
26
+ function boardIds(ctx, w) {
27
+ try { return new Set(boards.frameFor(ctx, w).boards.map((b) => b.id)); } catch { return null; }
28
+ }
29
+ /** The KR metric ids of a workspace. null when the records cannot be read. */
30
+ function krIds(ctx, ws) {
31
+ try { return new Set(require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics').map((k) => k.rid).filter(Boolean)); } catch { return null; }
32
+ }
33
+
34
+ async function handle(req, res, url, ctx) {
35
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
36
+ if (url.pathname !== '/api/premium-dashboards/save') return send(bad(404, 'no such premium-dashboards route'));
37
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
38
+ const read = await ctx.readJson(req);
39
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
40
+ const body = read.body || {};
41
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'an agent session cannot change a dashboard. Only a press on the page does'));
42
+ const g = guard.requirePagePress(req, body);
43
+ if (!g.ok) return send(bad(g.status, g.error));
44
+ const w = wsOf(ctx, text(body.ws));
45
+ if (!w) return send(bad(404, 'no such workspace'));
46
+ const c = PD.check(body);
47
+ if (!c.ok) return send(bad(c.status, c.error));
48
+ const ids = boardIds(ctx, w);
49
+ if (!ids) return send(bad(503, 'The boards could not be read. Try again in a moment.'));
50
+ if (!ids.has(c.value.board)) return send(bad(404, 'no such board in this workspace'));
51
+ let known = null;
52
+ if (!c.value.remove) {
53
+ const ks = krIds(ctx, w.id);
54
+ if (!ks) return send(bad(503, 'The KR metric records could not be read, so the charts cannot be checked.'));
55
+ known = { charts: ks };
56
+ }
57
+ const r = PD.save(w.root, body, g.actor, { now: Date.now(), known });
58
+ if (!r.ok) return send(bad(r.status, r.error));
59
+ return send({ status: 200, body: { ok: true, dashboard: r.dashboard, dashboards: r.dashboards } });
60
+ }
61
+
62
+ module.exports = { prefixes: ['/api/premium-dashboards'], handle };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.262.0",
3
+ "version": "0.264.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.262.0",
9
+ "version": "0.264.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.262.0",
3
+ "version": "0.264.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -141,3 +141,26 @@ button.nfr:hover,button.nfr:focus-visible{background:color-mix(in oklab,var(--in
141
141
  .ndm small{color:var(--ink-3)}
142
142
  .ntf .lk,.nsch .lk{min-height:44px;display:inline-flex;align-items:center}
143
143
  .ntf{min-height:44px}
144
+ /* briefing-premium-reports: a saved dashboard's bar and edit dialog, the report Ask box and the report dialogs */
145
+ .pdbar{margin:12px 0 4px}
146
+ .pdbar .pdp{flex:1 1 240px;margin:0;color:var(--ink-2)}
147
+ .pdbar .dmcta,.nask .dmcta{min-height:44px}
148
+ .pdck:empty{display:none}
149
+ .pdck{margin:10px 0 0;color:var(--ember)}
150
+ .pdlist{display:grid;gap:6px}
151
+ .pdrow{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 8px 8px 14px;border-radius:14px;background:var(--well)}
152
+ .pdrow>span:first-child{min-width:0;display:grid;gap:2px}
153
+ .pdrow b{font-size:15px;font-weight:600;overflow-wrap:anywhere}
154
+ .pdrow small{color:var(--ink-3);font-size:12.5px}
155
+ .pdmv{display:flex;gap:4px;flex:none}
156
+ .pdmv .round{width:44px;height:44px;color:var(--ink-2)}
157
+ .pdmv .round:disabled{opacity:.35}
158
+ .addf label.pdchk{display:flex;align-items:center;gap:10px;min-height:44px;font-size:15px;font-weight:550;color:var(--ink)}
159
+ .addf .pdchk input{width:22px;height:22px;flex:none;accent-color:var(--ember)}
160
+ .nask{display:flex;gap:8px;margin:4px 0 0}
161
+ .nask input{flex:1;min-width:0;height:44px;border-radius:14px;border:1px solid var(--hair);background:var(--card-solid);padding:0 12px;font:inherit;font-size:15px;color:var(--ink)}
162
+ .nask input:focus-visible{outline:2px solid var(--ember);outline-offset:1px}
163
+ .nask-n{margin:6px 0 0 4px;font-size:12.5px}
164
+ .pdev{margin:0 0 12px;padding-left:18px;display:grid;gap:4px}
165
+ .pdev small{color:var(--ink-3)}
166
+ .dplist button[role="switch"]{min-height:44px;width:100%}
@@ -1,7 +1,11 @@
1
1
  /* pm/premium-insights.js — the premium Insights page (initiative briefing-premium-insights, slice 9). Reads GET /api/insights-premium and draws the model
2
2
  * lib/insights-premium.js builds from the KR metric records and the report files the console's Reports tab reads: the Dashboards card (charts with a target
3
- * line, what stands out), the Reports card, the dock and the standard dialog. Nothing here posts: no press changes a record, and nothing is sent. */
4
- import { $, $$, esc, openDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb } from './premium-shell.js';
3
+ * line, what stands out), the Reports card, the dock and the standard dialog.
4
+ * briefing-premium-reports adds the PM's presses, each through pmPost and so behind the launch nonce: a saved dashboard (POST /api/premium-dashboards/save,
5
+ * PRD D2 to D6) and the report presses of the console's Reports workspace (POST /api/report-setups/ask | change | cancel | setup | dismiss | pause | resume |
6
+ * draft, PRD R2 to R4). Nothing else posts, and nothing is sent outward. */
7
+ import { $, $$, esc, openDlg, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv } from './premium-shell.js';
8
+ import { pmPost } from './http.js';
5
9
 
6
10
  let M = null; // the model
7
11
  let dash = 'all'; // the dashboard on screen
@@ -9,7 +13,9 @@ wireRail('rep');
9
13
  const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
10
14
  const DOCI = '<path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 13h6M9 17h4"/>';
11
15
  const CHV2 = '<svg class="i" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6"/></svg>';
16
+ const AIC = '<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"/>';
12
17
  const byKey = (k) => (M && M.charts || []).find((c) => c.key === k) || null;
18
+ const savedDash = () => (M.dashboards || []).filter((d) => d.saved);
13
19
 
14
20
  /* ── header ───────────────────────────────────────────────────────────────────────────────────────────────────── */
15
21
  let crumbed = false;
@@ -63,7 +69,9 @@ function drawDash() {
63
69
  const D = curDash(), L = D.keys.map(byKey).filter(Boolean);
64
70
  $('#dashCap').textContent = M.counts.total ? M.counts.charts + ' drawn · ' + M.counts.noSeries + ' without a series' : '';
65
71
  const tabs = $('#dashTabs'); tabs.hidden = M.dashboards.length < 2;
66
- if (!tabs.hidden) { tabs.innerHTML = '<i class="pill"></i>' + M.dashboards.map((d) => `<button data-d="${esc(d.id)}" aria-pressed="${d.id === D.id}">${esc(d.name)}</button>`).join(''); pillOf(tabs); }
72
+ if (!tabs.hidden) { tabs.innerHTML = '<i class="pill"></i>' + M.dashboards.map((d) => `<button data-d="${esc(d.id)}" aria-pressed="${d.id === D.id}"${d.main ? ' title="The main dashboard"' : ''}>${esc(d.name)}${d.main ? ' · Main' : ''}</button>`).join(''); pillOf(tabs); }
73
+ drawDashBar(D);
74
+ if (D.saved) { drawSaved(D, L); return; }
67
75
  if (!M.charts.length) {
68
76
  $('#dashBody').innerHTML = `<div class="nempty" style="margin-top:14px"><p><b>${esc(M.counts.total ? 'No KR metric holds two readings yet.' : 'No KR metric is recorded for this workspace.')}</b> ${esc(M.counts.total ? 'A chart needs a series, so nothing is drawn.' : 'There is nothing to chart. Add one where the KR metrics are kept.')}</p></div>` + noSeriesHtml();
69
77
  return;
@@ -74,11 +82,75 @@ function drawDash() {
74
82
  + `<p class="mhint" style="margin-top:6px"><b>${tot - off} of ${tot}</b> on their line${off ? `. <b class="mflag">${off} ${off === 1 ? 'is' : 'are'} behind it.</b>` : '.'} Each chart is one KR metric, drawn at the dates of its readings. A gap between readings is left as a gap. The dashed line is the target.</p>`
75
83
  + `<div class="ngrid">${L.map((c) => `<div class="ntw">${tileHtml(c)}<div class="ntf"><button class="lk" data-open="${esc(c.key)}">Details</button></div></div>`).join('')}</div>` + noSeriesHtml();
76
84
  }
85
+ /* The bar under the switch: a saved dashboard's purpose and Edit, and New dashboard (PRD D3/D4). Hidden when the page has no board to save on. */
86
+ function drawDashBar(D) {
87
+ const bar = $('#dashBar'); bar.hidden = !M.board.id;
88
+ if (bar.hidden) return;
89
+ bar.innerHTML = (D.saved ? `<p class="note pdp">${D.main ? '<b>Main dashboard.</b> ' : ''}${esc(D.purpose)}</p><button class="dmcta alt" id="pdEdit" aria-haspopup="dialog">Edit</button>` : '')
90
+ + '<button class="dmcta alt" id="pdNew" aria-haspopup="dialog">New dashboard</button>';
91
+ }
92
+ function drawSaved(D, L) {
93
+ const off = D.off, tot = L.length;
94
+ const gone = D.gone.length ? `<p class="label ngl">Not drawn · ${D.gone.length}</p><div class="dplist" role="list">${D.gone.map((g) => `<div class="nempty" role="listitem" style="margin-bottom:6px"><p><b>${esc(g.title)}</b><br>${esc(g.why)}</p></div>`).join('')}</div>` : '';
95
+ const checks = D.checks.length ? `<p class="note pdck">${D.checks.map(esc).join(' ')}</p>` : '';
96
+ $('#dashBody').innerHTML = (tot ? `<div class="mprog" role="progressbar" aria-label="Measures on their line" aria-valuemin="0" aria-valuemax="${tot}" aria-valuenow="${tot - off}"><b style="width:${(tot - off) / tot * 100}%"></b></div>`
97
+ + `<p class="mhint" style="margin-top:6px"><b>${tot - off} of ${tot}</b> on their line${off ? `. <b class="mflag">${off} ${off === 1 ? 'is' : 'are'} behind it.</b>` : '.'} The charts are drawn in the order you saved. The dashed line is the target.</p>`
98
+ + `<div class="ngrid">${L.map((c) => `<div class="ntw">${tileHtml(c)}<div class="ntf"><button class="lk" data-open="${esc(c.key)}">Details</button></div></div>`).join('')}</div>`
99
+ : `<div class="nempty" style="margin-top:14px"><p><b>This dashboard draws no chart yet.</b> Press Edit to add a measure with a series.</p></div>`) + checks + gone;
100
+ }
77
101
  function noSeriesHtml() {
78
102
  const N = M.noSeries; if (!N.length) return '';
79
103
  return `<p class="label ngl">No series recorded · ${N.length}</p><div class="dplist" role="list">${N.map((n) => `<div class="nempty" role="listitem" style="margin-bottom:6px"><p><b>${esc(n.title)}</b>${n.pillar ? ' · ' + esc(n.pillar) : ''}<br>${esc(n.why)} It is not drawn.</p></div>`).join('')}</div>`;
80
104
  }
81
105
  $('#dashTabs').addEventListener('click', (e) => { const b = e.target.closest('[data-d]'); if (!b) return; dash = b.dataset.d; drawDash(); });
106
+ $('#dashBar').addEventListener('click', (e) => { if (e.target.closest('#pdEdit')) openDashEdit(curDash()); else if (e.target.closest('#pdNew')) openDashEdit(null); });
107
+
108
+ /* ── a saved dashboard: the edit dialog (PRD D4/D5). The one press posts POST /api/premium-dashboards/save. ─────────────────────────────── */
109
+ 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
+ }
82
154
  $('#dashBody').addEventListener('click', (e) => { const o = e.target.closest('[data-open]'); if (o) openChart(byKey(o.dataset.open)); });
83
155
  $('#dashBody').addEventListener('keydown', (e) => {
84
156
  const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
@@ -93,33 +165,157 @@ $('#dashBody').addEventListener('pointermove', (e) => {
93
165
  $('#dashBody').addEventListener('pointerleave', () => $$('#dashBody .mch.hv').forEach((x) => chartAt(x)));
94
166
 
95
167
  /* ── reports ──────────────────────────────────────────────────────────────────────────────────────────────────── */
168
+ let askTimer = 0;
169
+ const dismissing = new Map(); // finding id → timer: "Not a report" waits 5 s for an Undo before it is sent
170
+ const ASKST = { running: ['Working', 'draft'], ready: ['Ready to review', 'issued'], failed: ['Failed', 'none'] };
96
171
  function repRow(r) {
97
- return `<div class="dmr ${esc(r.state)}" role="listitem"><button class="dmo" data-rep="1"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(r.cadence)} · ${esc(r.date || r.slot)}</b><small>${esc(r.path)}</small><span class="dmm"><span class="s ${esc(r.state === 'issued' ? 'issued' : 'draft')}">${esc(r.stateLabel)}</span></span></span></button></div>`;
172
+ return `<div class="dmr ${esc(r.state)}" role="listitem"><button class="dmo" data-rep="1" title="Opens in the console's Reports tab"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(r.cadence)} · ${esc(r.date || r.slot)}</b><small>${esc(r.path)}</small><span class="dmm"><span class="s ${esc(r.state === 'issued' ? 'issued' : 'draft')}">${esc(r.stateLabel)}</span><span>Opens in the console</span></span></span></button></div>`;
98
173
  }
174
+ const foundRow = (f) => `<div class="dmr" role="listitem"><button class="dmo" data-found="${esc(f.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(AIC)}</span><span class="dmn"><b>${esc(f.name)}</b><small>${esc(f.why)}</small><span class="dmm">${f.confidence ? `<span>${esc(f.confidence)}</span>` : ''}<span>${f.evidence.length} ${f.evidence.length === 1 ? 'sign' : 'signs'} in your work</span></span></span></button></div>`;
175
+ const askRow = (a) => `<div class="dmr" role="listitem"><button class="dmo" data-ask="${esc(a.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(AIC)}</span><span class="dmn"><b>${esc(a.proposal && a.proposal.name ? a.proposal.name : a.text)}</b><small>You asked: ${esc(a.text)}</small><span class="dmm"><span class="s ${ASKST[a.state][1]}">${ASKST[a.state][0]}</span>${a.changed ? '<span>Changed once</span>' : ''}</span></span></button></div>`;
176
+ const setupRow = (s) => `<div class="dmr" role="listitem"><button class="dmo" data-setup="${esc(s.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(s.name)}</b><small>${esc([s.label, s.audience ? 'for ' + s.audience : ''].filter(Boolean).join(' · '))}</small><span class="dmm"><span class="s ${s.paused ? 'none' : 'issued'}">${s.paused ? 'Paused' : s.drafting ? 'Drafting' : 'Set up'}</span>${s.next && !s.paused ? `<span>Next draft ${esc(s.next)}</span>` : ''}</span></span></button></div>`;
99
177
  function drawReps() {
100
- const R = M.reports;
178
+ const R = M.reports, found = (R.found || []).filter((f) => !dismissing.has(f.id)), asks = R.asks || [], setups = R.setups || [];
101
179
  $('#repCap').textContent = R.rows.length ? String(R.rows.length) : '';
180
+ const group = (id, label, L, row) => L.length ? `<div class="dmg ngrp" id="${id}" role="list"><p class="label">${esc(label)} · ${L.length}</p>${L.map(row).join('')}</div>` : '';
102
181
  $('#repBody').innerHTML = `<p class="mhint">A report is a file in the repository. PMOS drafts it, you read it. <b>Nothing is sent from here.</b></p>`
182
+ + `<form class="nask" id="repAsk"><input id="repAskIn" maxlength="500" autocomplete="off" placeholder="Ask PMOS to set up a report" aria-label="Ask PMOS to set up a report"><button class="dmcta" id="repAskGo" type="submit">Ask</button></form>`
183
+ + '<p class="note nask-n">This starts a background run that only proposes a report. Nothing is set up until you press Set it up.</p>'
184
+ + (R.setupsOk === false ? '<div class="nempty"><p><b>The report setups could not be read</b>, so what PMOS found and what you set up are not listed.</p></div>'
185
+ : group('repAsks', 'Your requests', asks, askRow) + group('repFound', 'Found in your work', found, foundRow) + group('repSetups', 'Set up', setups, setupRow))
103
186
  + (R.missing ? '<div class="nempty"><p><b>The report files could not be read</b>, so none is listed.</p></div>'
104
- : R.rows.length ? `<p class="note" style="margin:6px 0 10px"><b>${R.counts.draft}</b> ${R.counts.draft === 1 ? 'draft' : 'drafts'} · <b>${R.counts.issued}</b> issued</p><div class="dmg ngrp" role="list">${R.rows.map(repRow).join('')}</div>`
105
- : '<div class="nempty"><p><b>No report file is on record.</b> PMOS drafts one when you ask for it in the console.</p></div>')
106
- + `<p class="nsch"><button class="lk" id="repOpen">Open the Reports tab</button> to read, edit or issue one. Schedules are not shown here.</p>`;
187
+ : R.rows.length ? `<div class="dmg ngrp" id="repDocs" role="list"><p class="label">Documents · <b>${R.counts.draft}</b> ${R.counts.draft === 1 ? 'draft' : 'drafts'} · <b>${R.counts.issued}</b> issued</p>${R.rows.map(repRow).join('')}</div>`
188
+ : '<div class="nempty"><p><b>No report file is on record.</b> Set one up above, or ask PMOS for one.</p></div>')
189
+ + `<p class="nsch"><button class="lk" id="repOpen">Open the Reports tab</button> to read, edit or issue a document.</p>`;
190
+ clearTimeout(askTimer);
191
+ if (asks.some((a) => a.state === 'running')) askTimer = setTimeout(load, 5000);
192
+ }
193
+ $('#repBody').addEventListener('click', (e) => {
194
+ if (e.target.closest('[data-rep]') || e.target.closest('#repOpen')) { location.assign('/c3.html?tab=rep'); return; }
195
+ const f = e.target.closest('[data-found]'), a = e.target.closest('[data-ask]'), s = e.target.closest('[data-setup]');
196
+ if (f) openFound((M.reports.found || []).find((x) => x.id === f.dataset.found));
197
+ else if (a) openAsk((M.reports.asks || []).find((x) => x.id === a.dataset.ask));
198
+ else if (s) openSetup((M.reports.setups || []).find((x) => x.id === s.dataset.setup));
199
+ });
200
+ $('#repBody').addEventListener('submit', async (e) => {
201
+ if (e.target.id !== 'repAsk') return;
202
+ e.preventDefault();
203
+ const inp = $('#repAskIn'), text = inp.value.trim(), go = $('#repAskGo');
204
+ if (!text) { toast('Say what the report is for, then press Ask.'); inp.focus(); return; }
205
+ go.disabled = true;
206
+ const res = await repPost('ask', { text });
207
+ go.disabled = false;
208
+ if (!res || res.ok !== true) { toast((res && res.error) || 'The request could not start.'); return; }
209
+ inp.value = ''; toast('Asked. A background run is working on a proposal. Nothing is set up yet.'); await load();
210
+ });
211
+
212
+ /* ── the report dialogs: each press is one existing /api/report-setups/* route (PRD R2 to R4) ─────────────────────────────────────────────── */
213
+ const repPost = (sub, body) => pmPost('/api/report-setups/' + sub, Object.assign({ ws: M.board.ws }, body));
214
+ function repDlg(o) {
215
+ 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',
216
+ 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>` });
217
+ $('#askF').hidden = true;
218
+ $('#oMain').onchange = null;
219
+ $('#oMain').onclick = async (e) => {
220
+ const b = e.target.closest('[data-rx]'); if (!b) return;
221
+ const m = $('#rxM'), fn = o.on[b.dataset.rx]; if (!fn) return;
222
+ $$('#oMain [data-rx]').forEach((x) => { x.disabled = true; });
223
+ const after = await fn(m, b);
224
+ if (after === 'keep') { $$('#oMain [data-rx]').forEach((x) => { x.disabled = false; }); return; }
225
+ if (after === 'keep-off') return;
226
+ closeDlg(); await load();
227
+ };
228
+ }
229
+ /* A press: post, then say the result in words, or keep the dialog open with the server's refusal. */
230
+ const press = (sub, body, said) => async (m) => {
231
+ m.textContent = 'Recording.';
232
+ const res = await repPost(sub, body);
233
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'That did not go through.'; return 'keep'; }
234
+ toast(typeof said === 'function' ? said(res) : said); return null;
235
+ };
236
+ const setupSaid = (res) => { const d = res.drafted || {}; return 'Set up. ' + (d.path ? 'The first draft is ' + d.path + '.' : 'The first draft was not written' + (d.error ? ': ' + d.error : '') + '. Draft it now on the report tries again.'); };
237
+ const propHtml = (p) => p && p.rows.length ? kv(p.rows) : '<p class="note" style="margin:0">The proposal holds no fields yet.</p>';
238
+ function openFound(f) {
239
+ if (!f) return;
240
+ repDlg({ eye: 'Found in your work', title: f.name, say: f.why + ' Set it up, or say it is not a report.',
241
+ html: `<p class="lede" style="margin:0 0 12px">${esc(f.why)}</p>${propHtml(f.proposal)}<h3 class="h2">What PMOS saw · ${f.evidence.length}</h3><ul class="pdev">${f.evidence.map((x) => `<li>${esc(x.text)}${x.kind ? ` <small>${esc(x.kind)}</small>` : ''}</li>`).join('')}</ul><p class="note">Set it up records the report in the report ledger and drafts its first cycle as a file. Not a report hides it; you can undo for 5 seconds.</p>`,
242
+ acts: [['set', 'Set it up'], ['no', 'Not a report', 1]],
243
+ on: {
244
+ set: press('setup', { finding: f.id }, setupSaid),
245
+ no: (m) => {
246
+ const t = setTimeout(async () => { dismissing.delete(f.id); const res = await repPost('dismiss', { finding: f.id }); if (!res || res.ok !== true) toast((res && res.error) || 'Not a report did not go through.'); await load(); }, 5000);
247
+ dismissing.set(f.id, t); drawReps();
248
+ m.innerHTML = 'Hidden. It is recorded as not a report in 5 seconds. <button class="lk" id="rxUndo">Undo</button>';
249
+ $('#rxUndo').onclick = () => { clearTimeout(dismissing.get(f.id)); dismissing.delete(f.id); drawReps(); m.textContent = 'Undone. Nothing was recorded.'; $$('#oMain [data-rx]').forEach((x) => { x.disabled = false; }); };
250
+ return 'keep-off';
251
+ },
252
+ } });
253
+ }
254
+ function openAsk(a) {
255
+ if (!a) return;
256
+ if (a.state === 'running') {
257
+ repDlg({ eye: 'Your request', title: a.text, say: 'A background run is working on a proposal. It proposes only; nothing is set up until you press Set it up.', html: `<p class="lede" style="margin:0">A background run is working on this request. This page checks again every 5 seconds.</p>`, acts: [['cancel', 'Cancel the request', 1]], on: { cancel: press('cancel', { id: a.id }, 'Request cancelled.') } });
258
+ return;
259
+ }
260
+ if (a.state === 'failed') {
261
+ repDlg({ eye: 'Your request', title: a.text, say: 'The run ended without a proposal.', html: `<p class="lede" style="margin:0">${esc(a.error || 'The run ended without a proposal.')}</p>`, acts: [['cancel', 'Remove the request', 1]], on: { cancel: press('cancel', { id: a.id }, 'Request removed.') } });
262
+ return;
263
+ }
264
+ repDlg({ eye: 'Your request', title: (a.proposal && a.proposal.name) || a.text, say: 'Here is the proposal. Set it up, ask for a change, or cancel.',
265
+ html: `<p class="note" style="margin:0 0 10px">You asked: ${esc(a.text)}</p>${propHtml(a.proposal)}<div class="addf" style="margin-top:14px"><label>A change to ask for<input id="rxChg" maxlength="500" placeholder="For example: monthly, not weekly"></label></div><p class="note">Change it starts the run again with your words. Set it up records the report and drafts its first cycle as a file.</p>`,
266
+ acts: [['set', 'Set it up'], ['chg', 'Change it', 1], ['cancel', 'Cancel', 1]],
267
+ on: {
268
+ set: press('setup', { ask: a.id }, setupSaid),
269
+ chg: (m) => { const t = $('#rxChg').value.trim(); if (!t) { m.textContent = 'Say what to change.'; $('#rxChg').focus(); return 'keep'; } return press('change', { id: a.id, text: t }, 'Asked for the change. The run is revising the proposal.')(m); },
270
+ cancel: press('cancel', { id: a.id }, 'Request cancelled.'),
271
+ } });
272
+ }
273
+ function openSetup(s) {
274
+ if (!s) return;
275
+ 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]];
276
+ const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
277
+ if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
278
+ 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.',
279
+ 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>`,
280
+ acts, on: {
281
+ 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') + '.'),
282
+ pause: press('pause', { id: s.id }, 'Paused. It is not drafted until you resume it.'),
283
+ resume: press('resume', { id: s.id }, 'Resumed. It is drafted on its schedule again.'),
284
+ } });
107
285
  }
108
- $('#repBody').addEventListener('click', (e) => { if (e.target.closest('[data-rep]') || e.target.closest('#repOpen')) location.assign('/c3.html?tab=rep'); });
109
286
 
110
287
  /* ── dock ─────────────────────────────────────────────────────────────────────────────────────────────────────── */
111
288
  function drawDock() { $('#dN').textContent = M.dock.needs; $('#dLab').textContent = M.dock.label; $('#dNext').innerHTML = M.dock.next ? `<i></i>First <b>${esc(M.dock.next)}</b>` : 'No measure is behind its line'; }
112
289
 
113
290
  /* ── the dialog: the measure's record, no press, the read-only agent beside it ───────────────────────────────── */
114
- function cardHtml(c) { return `<div class="acard" id="card"><p class="ct">What this page can do</p><p class="nodef" id="holdWhy">${esc(c.dialog.hold)}</p></div>`; }
291
+ function cardHtml(c) { return `<div class="acard" id="card"><p class="ct">What this page can do</p><p class="nodef" id="holdWhy">${esc(c.dialog.hold)} The switches under On your dashboards save a dashboard and change no record.</p></div>`; }
115
292
  function paneHtml(c) {
116
293
  const p = c.dialog.pane;
117
- return `<article class="paper doc"><p class="dpath">${esc(p.file)}</p><div class="kv2">${c.dialog.facts.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div><h3 class="h2">All ${c.pts.length} readings</h3><div class="kv2">${p.rows.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div><p class="xn">Read from the KR metric record. The line status is the record's own: the straight line from its baseline to its target. Nothing here is a forecast.</p></article>`;
294
+ return `<article class="paper doc"><p class="dpath">${esc(p.file)}</p>${onDashHtml(c)}<div class="kv2">${c.dialog.facts.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div><h3 class="h2">All ${c.pts.length} readings</h3><div class="kv2">${p.rows.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div><p class="xn">Read from the KR metric record. The line status is the record's own: the straight line from its baseline to its target. Nothing here is a forecast.</p></article>`;
295
+ }
296
+ /* Add to a dashboard (PRD D6): one switch per saved dashboard of the board. A press saves that dashboard with the chart added or taken off. */
297
+ function onDashHtml(c) {
298
+ if (!M.board.id) return '';
299
+ const L = savedDash();
300
+ return `<h3 class="h2">On your dashboards</h3>${L.length ? `<div class="dplist" role="group" aria-label="Add to a dashboard">${L.map((d) => { const on = d.charts.includes(c.id); return `<button role="switch" aria-checked="${on}" aria-pressed="${on}" data-pdsw="${esc(d.id)}"><span><b>${esc(d.name)}</b><small>${d.charts.length} ${d.charts.length === 1 ? 'chart' : 'charts'}</small></span><i>${on ? 'On it' : 'Add'}</i></button>`; }).join('')}</div>` : '<p class="note" style="margin:0 0 12px">No saved dashboard on this board yet. Make one with New dashboard.</p>'}<p class="note" id="pdSwM" role="status" style="min-height:1.2em"></p>`;
118
301
  }
119
302
  function openChart(c) {
120
303
  if (!c) return;
121
304
  const d = c.dialog;
122
305
  openDlg({ eye: d.eye + ' · real data', title: c.title, sub: c.sub + ' · ' + c.chip, say: d.say, stream: turnA(logHtml(d)) + turnA(ptx(d.say)) + cardHtml(c), noteKey: c.key, pane: paneHtml(c), label: 'KR metric record' });
306
+ $('#oMain').onchange = null;
307
+ $('#oMain').onclick = async (e) => {
308
+ const b = e.target.closest('[data-pdsw]'); if (!b || b.disabled) return;
309
+ const D = savedDash().find((x) => x.id === b.dataset.pdsw); if (!D) return;
310
+ const on = D.charts.includes(c.id), charts = on ? D.charts.filter((x) => x !== c.id) : D.charts.concat(c.id);
311
+ b.disabled = true; $('#pdSwM').textContent = 'Saving.';
312
+ const res = await saveDash({ id: D.id, name: D.name, purpose: D.purpose, charts, main: D.main });
313
+ b.disabled = false;
314
+ if (!res || res.ok !== true) { $('#pdSwM').textContent = (res && res.error) || 'The dashboard could not be saved.'; return; }
315
+ D.charts = charts; b.setAttribute('aria-checked', !on); b.setAttribute('aria-pressed', !on); $('i', b).textContent = on ? 'Add' : 'On it'; $('small', b).textContent = charts.length + ' ' + (charts.length === 1 ? 'chart' : 'charts');
316
+ $('#pdSwM').textContent = on ? 'Taken off ' + D.name + '.' : 'Added to ' + D.name + '.';
317
+ load();
318
+ };
123
319
  loadThread(c.key);
124
320
  setTimeout(() => { const b = $('#dBody'); b.scrollTop = b.scrollHeight; }, 120);
125
321
  }