create-pmos 0.256.0 → 0.258.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,133 @@
1
+ 'use strict';
2
+ /* lib/insights-premium.js — the premium Insights page's model, built from the KR metric records and the report files the console's Reports tab reads
3
+ * (initiative briefing-premium-insights).
4
+ *
5
+ * build(facts) → model PURE. facts = { now, board, boards, outcomes, reports, reportsOk, missing[] }
6
+ * peekModel() → the last model built, for the agent to find a chart in (null before the first)
7
+ *
8
+ * facts come from the routes of lib/routes-c3-strategy.js and lib/routes-reports.js:
9
+ * board { ws, id, name } the board the page shows (KR metric records belong to its workspace, PRD D2)
10
+ * outcomes GET /api/c3-strategy → .outcomes [{ id, name, pillar, unit, start (the baseline), target, by, now, expected, shortfall, status, pivot, reason, readings: [{ at, v }] }]
11
+ * reports GET /api/report → .reports [{ cadence, slot, path, status, issued: { at, by } | null, edited }]
12
+ *
13
+ * THE RULE THE FILE FOLLOWS (as the other premium models): a number, chip, line or date is made only from a field of a record. A measure with fewer than two
14
+ * readings gets no chart and says why. The time between two readings is drawn as the time it is, so a gap in a series shows as a gap and never as a zero. No
15
+ * forecast is drawn and no cause is given. Run-based series (corrections per 100 runs, merges a week) belong to the Board's Metrics card and are not built here (PRD decision 4). */
16
+
17
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
18
+ const isoDay = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
19
+ const shortDate = (v) => { const t = isoDay(v); if (t === null) return ''; const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()]; };
20
+ const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s; };
21
+ const fin = (v) => typeof v === 'number' && Number.isFinite(v);
22
+ const r2 = (v) => Math.round(v * 100) / 100;
23
+ const num = (v, unit) => { const u = String(unit || '').trim(), s = String(r2(v)); return u ? (/^[A-Za-z]/.test(u) ? s + ' ' + u : s + u) : s; };
24
+ const CHIP = { ok: ['On its line', 'ok'], drift: ['Behind its line', 'warn'], off: ['Well behind its line', 'bad'] };
25
+ const MAX_FINDINGS = 3;
26
+ const KR_FILE = 'planning/records/kr-metrics.jsonl';
27
+
28
+ let last = null;
29
+ const peekModel = () => last;
30
+
31
+ /** One KR metric outcome with two or more readings → a chart. null when it has no series. */
32
+ function chartOf(o) {
33
+ const rs = (o.readings || []).filter((x) => x && fin(x.v) && isoDay(x.at) !== null);
34
+ if (rs.length < 2) return null;
35
+ const u = o.unit || '', tgt = fin(o.target) ? o.target : null, base = fin(o.start) ? o.start : null;
36
+ const t0 = isoDay(rs[0].at), t1 = isoDay(rs[rs.length - 1].at), span = t1 - t0 || 1;
37
+ const ys = rs.map((x) => x.v).concat(tgt !== null ? [tgt] : []);
38
+ const lo = Math.min(...ys), hi = Math.max(...ys), range = hi - lo || 1;
39
+ const pts = rs.map((x) => ({ at: x.at, v: x.v, fx: (isoDay(x.at) - t0) / span, fy: (x.v - lo) / range, txt: num(x.v, u), d: shortDate(x.at) }));
40
+ const now = rs[rs.length - 1].v, prev = rs[rs.length - 2].v;
41
+ const dir = tgt !== null && base !== null && tgt !== base ? Math.sign(tgt - base) : tgt !== null ? Math.sign(tgt - now) : 0;
42
+ const step = now - prev, good = dir ? step * dir > 0 : null;
43
+ const chip = CHIP[o.status] || ['No line scored', 'mut'];
44
+ const rows = [
45
+ ['Latest reading', num(now, u) + ' on ' + shortDate(rs[rs.length - 1].at)],
46
+ tgt !== null ? ['Target', num(tgt, u) + (o.by ? ' by ' + shortDate(o.by) : '')] : null,
47
+ base !== null ? ['Baseline', num(base, u)] : null,
48
+ fin(o.expected) ? ['On its line today', num(o.expected, u)] : null,
49
+ ['Line status', chip[0] + (o.status === 'unscored' && o.reason ? ' — ' + o.reason : '')],
50
+ ['Readings', rs.length + ' from ' + shortDate(rs[0].at) + ' to ' + shortDate(rs[rs.length - 1].at)],
51
+ o.pillar ? ['Pillar', o.pillar] : null,
52
+ ].filter(Boolean);
53
+ const say = o.name + ' stands at ' + num(now, u) + (tgt !== null ? ' against a target of ' + num(tgt, u) : '') + '. ' + (CHIP[o.status] ? 'Against its own line the record says: ' + chip[0].toLowerCase() + '.' : 'The record cannot score it against a line.');
54
+ const rid = clip(o.id, 100);
55
+ return {
56
+ key: 'ins:' + rid, id: o.id, title: clip(o.name, 120), sub: [o.pillar, rs.length + ' readings'].filter(Boolean).join(' · '), pillar: o.pillar || '',
57
+ unit: u, v: num(now, u), at: shortDate(rs[rs.length - 1].at), target: tgt, targetTxt: tgt !== null ? 'target ' + num(tgt, u) : '', by: o.by ? shortDate(o.by) : '',
58
+ ty: tgt !== null ? (tgt - lo) / range : null, state: o.status || 'unscored', chip: chip[0], chipKind: chip[1], off: o.status === 'drift' || o.status === 'off', pivot: !!o.pivot,
59
+ step: r2(step), good, dir, first: rs[0].at, lastAt: rs[rs.length - 1].at, pts, range: [lo, hi],
60
+ ticks: [shortDate(rs[0].at), shortDate(rs[rs.length - 1].at)],
61
+ dialog: {
62
+ eye: 'Measure', logTitle: 'Read from the KR metric record', say, head: 'Where it stands', facts: rows, files: [KR_FILE],
63
+ log: ['Read the KR metric record ' + o.id, 'Took ' + rs.length + ' readings from the record', 'Took the line status from the record: ' + chip[0].toLowerCase()],
64
+ hold: 'Nothing here changes a record. A reading is added where the KR metric is kept, not on this page.',
65
+ pane: { label: 'KR metric record', file: KR_FILE, rows: rs.map((x) => [shortDate(x.at), num(x.v, u)]).reverse() },
66
+ },
67
+ };
68
+ }
69
+
70
+ /** Up to three plain sentences about what stands out, from the series alone. No forecast and no cause. */
71
+ function findingsOf(charts) {
72
+ const out = [];
73
+ for (const c of charts) {
74
+ const u = c.unit, f = [];
75
+ const move = (a, b) => 'from ' + num(a, u) + ' to ' + num(b, u);
76
+ const prev = c.pts[c.pts.length - 2].v, now = c.pts[c.pts.length - 1].v;
77
+ const spread = (c.range[1] - c.range[0]) || 1;
78
+ if (c.pivot) f.push({ kind: 'stuck', score: 100, text: c.title + ' has been behind its line at three readings in a row, and the gap is not closing.' });
79
+ else if (c.off && c.good === false && c.step !== 0) f.push({ kind: 'worse', score: 90, text: c.title + ' is behind its line, and its last reading moved away from the target (' + move(prev, now) + ').' });
80
+ else if (c.off && c.good) f.push({ kind: 'closing', score: 60, text: c.title + ' is behind its line, and its last reading moved toward the target (' + move(prev, now) + ').' });
81
+ else if (c.off) f.push({ kind: 'off', score: 55, text: c.title + ' is behind its line at ' + num(now, u) + '.' });
82
+ else if (c.state === 'ok' && c.good === false && c.step !== 0) f.push({ kind: 'slip', score: 50, text: c.title + ' is on its line, but its last reading moved away from the target (' + move(prev, now) + ').' });
83
+ if (c.target !== null && c.dir && (c.dir > 0 ? now >= c.target : now <= c.target)) f.push({ kind: 'reached', score: 58, text: c.title + ' has reached its target of ' + num(c.target, u) + '.' });
84
+ if (Math.abs(now - prev) / spread >= 0.4 && !(f[0] && f[0].score >= 90)) f.push({ kind: 'move', score: 70, text: c.title + ' moved ' + move(prev, now) + ' in one reading.' });
85
+ f.sort((a, b) => b.score - a.score);
86
+ if (f[0]) out.push(Object.assign(f[0], { key: c.key, chart: c.key }));
87
+ }
88
+ out.sort((a, b) => b.score - a.score);
89
+ return out.slice(0, MAX_FINDINGS);
90
+ }
91
+
92
+ function reportRows(reports) {
93
+ return (reports || []).slice().sort((a, b) => String(b.slot).localeCompare(String(a.slot)) || String(a.cadence).localeCompare(String(b.cadence))).slice(0, 12).map((r) => {
94
+ const issued = !!r.issued;
95
+ return {
96
+ key: 'rep:' + r.cadence + ':' + r.slot, cadence: r.cadence, slot: r.slot, date: shortDate(r.slot), state: issued ? 'issued' : r.status === 'draft' ? 'draft' : 'file',
97
+ stateLabel: issued ? 'Issued' + (r.issued.at ? ' ' + shortDate(r.issued.at) : '') : r.status === 'draft' ? 'Draft' : 'Report file', path: r.path || '',
98
+ };
99
+ });
100
+ }
101
+
102
+ function build(facts) {
103
+ const f = facts || {};
104
+ const outcomes = f.outcomes || [], missing = (f.missing || []).slice();
105
+ const charts = outcomes.map(chartOf).filter(Boolean);
106
+ const noSeries = outcomes.filter((o) => !chartOf(o)).map((o) => ({
107
+ key: 'nos:' + o.id, title: clip(o.name, 120), pillar: o.pillar || '',
108
+ why: (o.readings || []).length === 1 ? 'Only one reading is recorded.' : (o.readings || []).length === 0 ? (o.reason && /reading/i.test(o.reason) ? o.reason : 'No reading is recorded yet.') : 'Its readings do not form a series.',
109
+ }));
110
+ const pillars = [...new Set(charts.map((c) => c.pillar).filter(Boolean))];
111
+ const offOf = (L) => L.filter((c) => c.off).length;
112
+ const dash = (id, name, L) => ({ id, name, keys: L.map((c) => c.key), total: L.length, off: offOf(L), chip: !L.length ? '' : offOf(L) ? offOf(L) + ' off its line' : 'On their lines' });
113
+ const dashboards = [dash('all', 'All measures', charts)].concat(pillars.length > 1 ? pillars.map((p) => dash('p:' + p, p, charts.filter((c) => c.pillar === p))) : []);
114
+ const findings = findingsOf(charts);
115
+ const rep = reportRows(f.reports);
116
+ const off = offOf(charts);
117
+ const board = f.board || {};
118
+ const model = {
119
+ header: { text: (f.pending ? 'Reading the records · ' : '') + 'Real data' + (missing.length ? ' · not read: ' + missing.join(', ') : '') },
120
+ board: { ws: board.ws || null, id: board.id || null, name: board.name || 'Insights', switcher: (f.boards || []).map((b) => ({ ws: b.ws, id: b.id, name: b.name })) },
121
+ charts, noSeries, dashboards, rows: charts,
122
+ findings: findings.length ? findings : [{ kind: 'calm', key: null, text: charts.length ? (charts.some((c) => c.target !== null) ? 'Nothing stands out. No measure moved much, and none is far behind its line.' : 'Nothing stands out. No measure here has a target, so the series can only be described.') : '' }],
123
+ calm: !findings.length && charts.length > 0,
124
+ reports: { rows: rep, ok: f.reportsOk !== false, counts: { draft: rep.filter((r) => r.state === 'draft').length, issued: rep.filter((r) => r.state === 'issued').length }, missing: f.reportsOk === false },
125
+ empty: !outcomes.length ? 'No KR metric is recorded for this workspace, so there is nothing to chart. Add one where the KR metrics are kept.' : !charts.length ? 'No KR metric holds two readings yet, so nothing is drawn.' : '',
126
+ dock: { needs: off, label: off === 1 ? 'measure off its line' : 'measures off their line', next: findings[0] && findings[0].chart ? (charts.find((c) => c.key === findings[0].chart) || {}).title || null : null },
127
+ counts: { charts: charts.length, noSeries: noSeries.length, off, total: outcomes.length },
128
+ };
129
+ last = model;
130
+ return model;
131
+ }
132
+
133
+ module.exports = { build, peekModel, chartOf, findingsOf, shortDate, num };
@@ -52,6 +52,7 @@ const MODULES = Object.freeze([
52
52
  'routes-briefing-premium', // briefing-premium: the premium Briefing's page model from repository state (read-only)
53
53
  'routes-my-work-premium', // briefing-premium-work: the premium My work page's model from the Work page's own list (read-only)
54
54
  'routes-board-premium', // briefing-premium-board: the premium Board page's model from the Initiatives page's own routes (read-only)
55
+ 'routes-insights-premium', // briefing-premium-insights: the premium Insights page's model from the KR metric records and report files (read-only)
55
56
  'routes-initiative-premium', // briefing-premium-initiative: the premium initiative page's model from the Initiatives sheet's own routes (read-only)
56
57
  'routes-brief-page', // console3 Briefing as the brief: Today agenda, Needs you and Mentions (read-only; writes go through routes-pm-items)
57
58
  'routes-mentions', // console3 Briefing Mentions: the PM's read marks (page press only)
@@ -16,6 +16,7 @@ const Ag = require('./briefing-premium-agent.js');
16
16
  const WP = require('./my-work-premium.js');
17
17
  const BoardP = require('./board-premium.js');
18
18
  const InitP = require('./initiative-premium.js');
19
+ const InsP = require('./insights-premium.js');
19
20
  const { repoScript } = require('./repo-script.js');
20
21
  const { correctionEvent } = require(repoScript('card-state.js'));
21
22
  const { appendOutbox } = require(repoScript('outbox.js'));
@@ -66,7 +67,7 @@ async function post(req, res, url, ctx) {
66
67
  }
67
68
  if (act === 'ask') {
68
69
  let wsId; try { const w = merged && sk ? { id: sk.ws } : ctx.getWs && ctx.getWs(url.searchParams.get('ws') || null); wsId = w && w.id; } catch { wsId = undefined; }
69
- const a = Ag.ask({ runtimeDir, key: b.key, text: b.text, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || /^src:/.test(String(b.key || '')) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
70
+ const a = Ag.ask({ runtimeDir, key: b.key, text: b.text, model: /^work:/.test(String(b.key || '')) ? WP.peekModel() : /^board:/.test(String(b.key || '')) ? BoardP.peekModel() : /^ins:/.test(String(b.key || '')) ? InsP.peekModel() : /^(init|doc):/.test(String(b.key || '')) ? InitP.peekModel() : sk || /^src:/.test(String(b.key || '')) ? Prod.peekModel() : BP.peekModel(root), spawnSession: ctx.spawnSession, wsId });
70
71
  ctx.json(res, a.body, a.status);
71
72
  return true;
72
73
  }
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+ /* routes-insights-premium.js — GET /api/insights-premium[?ws=<id>&board=<id>] (initiative briefing-premium-insights).
3
+ *
4
+ * 200 { ok, state: 'ready', model, as_of } | 500 { ok: false, state: 'error', error }
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
+ * 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. */
8
+ const Insights = require('./insights-premium.js');
9
+ const boards = require('./routes-boards.js');
10
+ const strategy = require('./routes-c3-strategy.js');
11
+ const { repoScript } = require('./repo-script.js');
12
+ const { recordsDirFor } = require('./records-dir.js');
13
+ const reports = require('./routes-reports.js');
14
+
15
+ /** GET `pathAndQuery` from a route module's own handler, as the Board page's route does, and return { status, body }. */
16
+ async function via(mod, pathAndQuery, req, ctx) {
17
+ let out = { status: 500, body: null };
18
+ const c = Object.assign({}, ctx, { json: (res, obj, code) => { out = { status: code || 200, body: obj }; } });
19
+ const u = new URL('http://local' + pathAndQuery);
20
+ const handled = await mod.handle({ method: 'GET', headers: (req && req.headers) || {} }, {}, u, c);
21
+ return handled === false ? { status: 404, body: null } : out;
22
+ }
23
+ const qs = (o) => '?' + Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
24
+
25
+ module.exports = {
26
+ prefixes: ['/api/insights-premium'],
27
+ handle: async (req, res, url, ctx) => {
28
+ if (url.pathname !== '/api/insights-premium') return false;
29
+ if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
30
+ const fail = (error) => { ctx.json(res, { ok: false, state: 'error', error: String(error).slice(0, 240) }, 500); return true; };
31
+ try {
32
+ const list = await via(boards, '/api/boards', req, ctx);
33
+ const all = list.body && list.body.ok !== false ? list.body.boards || [] : [];
34
+ const wantWs = url.searchParams.get('ws'), wantId = url.searchParams.get('board');
35
+ const pick = all.find((b) => (!wantWs || b.ws === wantWs) && (!wantId || b.id === wantId)) || all[0] || null;
36
+ const ws = pick ? pick.ws : wantWs;
37
+ const q = qs({ ws });
38
+ const rp = await via(reports, '/api/report' + q, req, ctx);
39
+ let outcomes;
40
+ try {
41
+ const today = new Date(), pad = (n) => String(n).padStart(2, '0'), day = today.getFullYear() + '-' + pad(today.getMonth() + 1) + '-' + pad(today.getDate());
42
+ outcomes = require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics').map((k) => strategy.outcomeOf(k, day));
43
+ } catch (e) { return fail('the KR metric records could not be read: ' + ((e && e.message) || e)); }
44
+ const reportsOk = !!(rp.body && rp.body.ok !== false);
45
+ const model = Insights.build({
46
+ 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'],
48
+ });
49
+ ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
50
+ return true;
51
+ } catch (e) { return fail((e && e.message) || e); }
52
+ },
53
+ };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.256.0",
3
+ "version": "0.258.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.256.0",
9
+ "version": "0.258.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.256.0",
3
+ "version": "0.258.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",
@@ -0,0 +1,70 @@
1
+ /* premium-doc-edit.js — the pure half of the premium document sheet's Edit and Proposals tabs (initiative briefing-premium-doc-edit).
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
+ * field of a route's answer; a proposal's section is stale only because the route says it is. */
4
+ 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
+ /** One proposal as the tab draws it. `p` is a row of GET /api/doc-sheet/proposals. */
7
+ export function proposalView(p) {
8
+ const secs = (p.sections || []).map((s) => ({
9
+ name: s.name, kind: s.kind, stale: !!s.stale,
10
+ add: s.kind === 'removed' ? 'Removes this section' : clip(s.after, 320),
11
+ }));
12
+ const open = p.state === 'proposed';
13
+ const live = secs.filter((s) => !s.stale);
14
+ return {
15
+ id: p.id, hash: p.hash, open, state: p.state,
16
+ who: p.by === 'pm' ? 'You' : 'The agent',
17
+ request: clip(p.prompt, 240),
18
+ sections: secs,
19
+ canAccept: open && live.length > 0,
20
+ staleAll: open && secs.length > 0 && live.length === 0,
21
+ why: p.why ? clip(p.why, 240) : '',
22
+ label: p.state === 'accepted' ? 'Accepted' : p.state === 'rejected' ? 'Rejected' : p.state === 'proposed' ? 'Open' : String(p.state || ''),
23
+ };
24
+ }
25
+
26
+ /** The Proposals tab's lists and the names the Read outline marks. Only open proposals count. */
27
+ export function proposalsModel(rows) {
28
+ const all = (rows || []).map(proposalView);
29
+ const open = all.filter((p) => p.open), closed = all.filter((p) => !p.open);
30
+ const marked = new Set();
31
+ for (const p of open) for (const s of p.sections) marked.add(s.name);
32
+ return { open, closed, count: open.length, marked };
33
+ }
34
+
35
+ /** Save press. Refuses an empty reason or an unchanged text before any post; the route refuses an empty reason too. */
36
+ export function editBody(path, before, text, why) {
37
+ if (typeof text !== 'string') return { error: 'There is no text to save.' };
38
+ if (!String(why || '').trim()) return { error: 'Say why the document changes. The reason is kept in the Edit log.' };
39
+ if (text === before) return { error: 'Nothing has changed yet.' };
40
+ return { body: { path, text, why: String(why).trim() } };
41
+ }
42
+
43
+ /** Accept press. `picked` is the names of the sections to take; a stale section is never sent. With none picked nothing is sent. */
44
+ export function acceptBody(path, p, picked) {
45
+ const live = new Set(p.sections.filter((s) => !s.stale).map((s) => s.name));
46
+ const names = (picked || []).filter((n) => live.has(n));
47
+ if (!names.length) return { error: 'Pick at least one section that is still current.' };
48
+ return { body: { path, id: p.id, hash: p.hash, sections: names } };
49
+ }
50
+
51
+ /** Reject press. A reason is required (the route requires it too). */
52
+ export function rejectBody(path, p, why) {
53
+ if (!String(why || '').trim()) return { error: 'Say why you are rejecting it. The reason is kept in the Edit log.' };
54
+ return { body: { path, id: p.id, why: String(why).trim() } };
55
+ }
56
+
57
+ /** Ask press. */
58
+ export function askBody(path, prompt) {
59
+ if (!String(prompt || '').trim()) return { error: 'Tell the agent what to change.' };
60
+ return { body: { path, prompt: String(prompt).trim() } };
61
+ }
62
+
63
+ /** The ask's state as the tab says it. `a` is GET /api/doc-sheet/ask. */
64
+ export function askLine(a) {
65
+ if (!a) return '';
66
+ if (a.state === 'working') return 'The agent is reading the document. It can read and propose; nothing changes until you accept.';
67
+ if (a.state === 'proposed') return 'The agent proposed a change. It is listed below.';
68
+ if (a.state === 'failed') return a.error || 'The agent could not answer.';
69
+ return '';
70
+ }
@@ -1,9 +1,10 @@
1
1
  /* pm/premium-initiative.js — the premium initiative page (initiative briefing-premium-initiative, slice 6). Reads GET /api/initiative-premium?id= and draws the
2
2
  * model lib/initiative-premium.js builds from the routes the production Initiatives sheet reads: the overview and checks, the Tasks card (PRD requirements and
3
- * the board's tracker items) and the Core documents card. A document row with a file opens the read-only document sheet (Read, Edit log, Health) in the
4
- * standard dialog beside the read-only agent. The one press is Draft it, through POST /api/core-docs/draft. Nothing here edits a document, issues one,
5
- * moves an initiative or adds a task. */
3
+ * the board's tracker items) and the Core documents card. A document row with a file opens the document sheet (Read, Edit, Proposals, Edit log, Health) in the
4
+ * standard dialog beside the read-only agent. The presses are Draft it (POST /api/core-docs/draft), the sheet's Save, Ask the agent, Accept and Reject (the
5
+ * existing /api/doc-sheet routes, initiative briefing-premium-doc-edit), Add a task and a task's status. Nothing here issues a document or moves an initiative. */
6
6
  import { pmPost } from './http.js';
7
+ import { proposalsModel, editBody, acceptBody, rejectBody, askBody, askLine } from './premium-doc-edit.js';
7
8
  import { $, $$, esc, openDlg, closeDlg, setMode, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, kv, H2, CHECK, crumbHtml, wireCrumb, AI } from './premium-shell.js';
8
9
 
9
10
  let M = null; // the model
@@ -210,9 +211,11 @@ function openAsk(q) {
210
211
  setMode('chat');
211
212
  }
212
213
 
213
- /* ── the document sheet: Read, Edit log, Health. Read-only. ─────────────────────────────────────────────── */
214
- let sheet = null; // { d, tab, text, log, health, err }
215
- const TABS = [['read', 'Read'], ['log', 'Edit log'], ['health', 'Health']];
214
+ /* ── the document sheet: Read, Edit, Proposals, Edit log, Health. ─────────────────────────────────────────────── */
215
+ let sheet = null; // { d, tab, text, log, health, props, draft, why, ask, askText, picked, busy, msg, err }
216
+ const TABS = [['read', 'Read'], ['edit', 'Edit'], ['props', 'Proposals'], ['log', 'Edit log'], ['health', 'Health']];
217
+ const wsq = () => (M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '');
218
+ const propsM = (s) => proposalsModel(s.props || []);
216
219
  function mdHtml(text) {
217
220
  const lines = String(text || '').replace(/\r/g, '').split('\n'), out = [], outline = [];
218
221
  let i = 0, fm = [];
@@ -235,13 +238,33 @@ function mdHtml(text) {
235
238
  }
236
239
  function sheetPane() {
237
240
  const s = sheet, d = s.d;
238
- const menu = `<div class="seg" id="shT" role="group" aria-label="Document views"><i class="pill"></i>${TABS.map(([k, n]) => `<button data-sh="${k}" aria-pressed="${s.tab === k}">${n}</button>`).join('')}</div>`;
241
+ const menu = `<div class="seg" id="shT" role="group" aria-label="Document views"><i class="pill"></i>${TABS.map(([k, n]) => `<button data-sh="${k}" aria-pressed="${s.tab === k}">${n}${k === 'props' && s.props && propsM(s).count ? ` <em>${propsM(s).count}</em>` : ''}</button>`).join('')}</div>`;
239
242
  const head = `<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>`;
240
243
  let body = '';
241
244
  if (s.err) body = `<p class="empty3 plain">${esc(s.err)}</p>`;
242
245
  else if (s.tab === 'read') {
243
246
  if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
244
- 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)}</button>`).join('')}</nav>` : ''}<div class="dsbody">${m.html}</div></div>`; }
247
+ 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>`; }
248
+ } else if (s.tab === 'edit') {
249
+ if (s.text == null) body = '<p class="empty3 plain">Reading the file.</p>';
250
+ else {
251
+ const cur = s.draft == null ? s.text : s.draft, nv = ((s.log && s.log.revisions) || []).length + 1;
252
+ body = `<textarea id="dsEd" class="dsed" spellcheck="true" aria-label="Edit the document">${esc(cur)}</textarea>`
253
+ + `<p class="note" id="dsNote" style="margin:8px 0">${cur === s.text ? 'No changes yet.' : 'Changed. Health checks the document again after you save.'}</p>`
254
+ + `<input id="dsWhy" class="dsy" placeholder="Why are you changing it? Kept in the edit log." aria-label="Why are you changing it" value="${esc(s.why || '')}">`
255
+ + `<p class="note" id="dsErr" role="alert" style="margin:6px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`
256
+ + `<div class="dsfoot"><span class="note">Saved by you as v${nv}</span><span><button class="dmcta alt" data-ds="discard">Cancel</button><button class="dmcta dark" id="dsSave" data-ds="save"${s.busy || cur === s.text ? ' disabled' : ''}>Save as v${nv}</button></span></div>`;
257
+ }
258
+ } else if (s.tab === 'props') {
259
+ if (!s.props) body = '<p class="empty3 plain">Reading the proposals.</p>';
260
+ else {
261
+ const m = propsM(s), line = askLine(s.ask);
262
+ body = `<div class="dsask2"><p class="label">${AI}Ask the agent</p><textarea id="dsAsk" rows="3" placeholder="Tell the agent what to change, for example: add a one-paragraph summary at the top" aria-label="Tell the agent what to change">${esc(s.askText || '')}</textarea><div class="dsrow"><button class="dmcta alt" data-ds="ask"${s.busy || (s.ask && s.ask.state === 'working') ? ' disabled' : ''}>${AI}Ask the agent</button></div><p class="note" style="margin:8px 0 0">The agent drafts a proposal and can only read. Nothing in the document changes until you accept it, and your request is kept in the edit log.</p>${line ? `<p class="note" role="status" style="margin:6px 0 0">${esc(line)}</p>` : ''}</div>`
263
+ + `<p class="label" style="margin:18px 0 8px">Open proposals · ${m.count}</p>`
264
+ + (m.count ? m.open.map((p) => propHtml(s, p)).join('') : `<div class="dsnone">${CHECK}No open proposals.</div>`)
265
+ + (m.closed.length ? `<p class="label" style="margin:18px 0 8px">Closed · ${m.closed.length}</p>${m.closed.map((p) => `<div class="dsp ${esc(p.state)}"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${p.why ? `<q>${esc(p.why)}</q>` : ''}</div><span class="dst2">${esc(p.label)}</span></div>`).join('')}` : '')
266
+ + `<p class="note" id="dsErr" role="alert" style="margin:10px 0 0;color:var(--ember-ink)">${esc(s.msg || '')}</p>`;
267
+ }
245
268
  } else if (s.tab === 'log') {
246
269
  if (!s.log) body = '<p class="empty3 plain">Reading the log.</p>';
247
270
  else {
@@ -253,19 +276,33 @@ function sheetPane() {
253
276
  if (!s.health) body = '<p class="empty3 plain">Checking the document.</p>';
254
277
  else body = `<p class="note" style="margin:0 0 10px">${s.health.passed} of ${s.health.total} checks that had the input they need passed. A check with no input is not counted.</p><div class="ckl">${s.health.checks.map((c) => `<div class="ckr ${c.pass === true ? 'done' : c.pass === false ? 'blocked' : 'skipped'}"><i></i><b>${esc(c.id)}</b><span>${c.pass === true ? 'Passed' : c.pass === false ? 'Not passed' : 'No input'}</span><small>${esc(c.reason || '')}</small></div>`).join('')}</div>`;
255
278
  }
256
- return `<article class="paper doc">${head}${menu}<div id="shBody">${body}</div><p class="xn">Read-only. Editing a document and accepting an agent’s proposal are not built on this page.</p></article>`;
279
+ return `<article class="paper doc">${head}${menu}<div id="shBody">${body}</div><p class="xn">Every change is kept in the Edit log with its reason. The file changes only when you press Save or Accept.</p></article>`;
280
+ }
281
+ function propHtml(s, p) {
282
+ const picked = s.picked && s.picked[p.id], on = (n) => (picked ? picked.includes(n) : true);
283
+ const secs = p.sections.map((x) => `<div class="dsdf">${p.sections.length > 1 && !x.stale ? `<label><input type="checkbox" data-pk="${esc(p.id)}" value="${esc(x.name)}"${on(x.name) ? ' checked' : ''}> ` : ''}<b>${esc(x.name)}</b>${p.sections.length > 1 && !x.stale ? '</label>' : ''} ${x.stale ? '<span class="dst2">Changed since this was proposed</span>' : `<ins>+ ${esc(x.add)}</ins>`}</div>`).join('');
284
+ return `<div class="dsp"><div><b>${esc(p.who)}</b><span>${esc(p.request)}</span>${secs}${p.staleAll ? '<q>The document changed since this was proposed, so it cannot be accepted. Ask again.</q>' : ''}</div><div class="dsa">${p.canAccept ? `<button class="dmcta dark" data-ds="acc:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Accept</button>` : ''}<button class="dmcta alt" data-ds="rej:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject</button></div>${s.rejecting === p.id ? `<div class="dsrow" style="grid-column:1/-1"><input id="dsRj" class="dsy" placeholder="Why are you rejecting it? Kept in the edit log." aria-label="Why are you rejecting it" value="${esc(s.rejWhy || '')}"><button class="dmcta dark" data-ds="rejgo:${esc(p.id)}"${s.busy ? ' disabled' : ''}>Reject it</button><button class="dmcta alt" data-ds="rejno">Cancel</button></div>` : ''}</div>`;
257
285
  }
258
286
  function drawSheet() { $('#oMain').innerHTML = sheetPane(); pillOf($('#shT')); }
259
287
  async function getJson(url, init) { try { const r = await fetch(url, Object.assign({ credentials: 'same-origin' }, init || {})); return await r.json(); } catch { return null; } }
260
288
  async function loadTab(tab) {
261
289
  const s = sheet, p = encodeURIComponent(s.d.path), ws = M.board.ws ? '&ws=' + encodeURIComponent(M.board.ws) : '';
262
- if (tab === 'read' && s.text == null) {
290
+ if (tab !== 'props' && tab !== 'log' && tab !== 'health' && !s.props) {
291
+ const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
292
+ if (sheet !== s) return;
293
+ if (pr && pr.ok) s.props = pr.proposals || [];
294
+ }
295
+ if ((tab === 'read' || tab === 'edit') && s.text == null) {
263
296
  const lg = s.log || (s.log = await getJson('/api/doc-sheet/log?path=' + p + ws));
264
297
  if (sheet !== s) return;
265
298
  const revs = lg && lg.ok ? lg.revisions || [] : [];
266
299
  const at = revs.length ? await getJson('/api/doc-sheet/at?path=' + p + '&rev=' + revs[revs.length - 1].rev + ws) : null;
267
300
  if (sheet !== s) return;
268
301
  if (at && at.ok) s.text = at.text; else s.err = (at && at.error) || (lg && lg.error) || 'The file could not be read.';
302
+ } else if (tab === 'props' && !s.props) {
303
+ const pr = await getJson('/api/doc-sheet/proposals?path=' + p + ws);
304
+ if (sheet !== s) return;
305
+ if (!pr || pr.ok === false) s.err = (pr && pr.error) || 'The proposals could not be read.'; else s.props = pr.proposals || [];
269
306
  } else if (tab === 'log' && !s.log) {
270
307
  s.log = await getJson('/api/doc-sheet/log?path=' + p + ws);
271
308
  if (sheet !== s) return;
@@ -279,16 +316,81 @@ async function loadTab(tab) {
279
316
  }
280
317
  function openSheet(d) {
281
318
  if (!d || !d.path) return;
282
- sheet = { d, tab: 'read', text: null, log: null, health: null, err: null };
283
- const key = 'doc:' + M.id + ':' + d.key, say = d.title + ' is ' + d.state.toLowerCase() + (d.by ? '. ' + d.by + '.' : '.') + ' I can read the file with you and answer questions. I change nothing.';
319
+ sheet = { d, tab: 'read', text: null, log: null, health: null, props: null, draft: null, why: '', ask: null, askText: '', picked: {}, busy: false, msg: '', err: null };
320
+ const key = 'doc:' + M.id + ':' + d.key, 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 change the file, with Save or Accept.';
284
321
  openDlg({ eye: 'Document · real data', title: d.title, sub: M.title, say, stream: turnA(logHtml({ logTitle: 'Read from the repository', log: ['Found the file ' + d.path, 'Read its revisions from the document sheet', 'Left the file as it is'] })) + turnA(ptx(say)), noteKey: key, pane: '', label: 'Document' });
285
322
  drawSheet(); loadThread(key); loadTab('read');
286
323
  }
287
324
  $('#oMain').addEventListener('click', (e) => {
288
325
  const t = e.target.closest('[data-sh]');
289
- if (t && sheet) { sheet.tab = t.dataset.sh; sheet.err = null; drawSheet(); loadTab(sheet.tab); return; }
326
+ if (t && sheet) { keepDraft(); sheet.tab = t.dataset.sh; sheet.err = null; sheet.msg = ''; drawSheet(); loadTab(sheet.tab); return; }
327
+ const b = e.target.closest('[data-ds]'); if (b && sheet) { sheetPress(b.dataset.ds); return; }
290
328
  const g = e.target.closest('[data-go]'); if (g) { const h = $('#ds-h' + g.dataset.go); if (h) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); }
291
329
  });
330
+ $('#oMain').addEventListener('change', (e) => { const c = e.target.closest('[data-pk]'); if (c && sheet) sheet.picked[c.dataset.pk] = $$('[data-pk]', $('#oMain')).filter((x) => x.dataset.pk === c.dataset.pk && x.checked).map((x) => x.value); });
331
+ $('#oMain').addEventListener('input', (e) => {
332
+ if (!sheet) return;
333
+ if (e.target.id === 'dsEd') { sheet.draft = e.target.value; const ch = sheet.draft !== sheet.text; $('#dsSave').disabled = !ch || sheet.busy; $('#dsNote').textContent = ch ? 'Changed. Health checks the document again after you save.' : 'No changes yet.'; }
334
+ else if (e.target.id === 'dsWhy') sheet.why = e.target.value;
335
+ else if (e.target.id === 'dsAsk') sheet.askText = e.target.value;
336
+ else if (e.target.id === 'dsRj') sheet.rejWhy = e.target.value;
337
+ });
338
+ function keepDraft() { if (!sheet) return; const ed = $('#dsEd'), w = $('#dsWhy'), a = $('#dsAsk'), rj = $('#dsRj'); if (rj) sheet.rejWhy = rj.value; if (ed) sheet.draft = ed.value; if (w) sheet.why = w.value; if (a) sheet.askText = a.value; }
339
+ /* the sheet's presses: each posts to one existing /api/doc-sheet route (ws in the query, as the routes read it) and then reads the routes again */
340
+ const dsPost = (route, body) => pmPost('/api/doc-sheet/' + route + (M.board.ws ? '?ws=' + encodeURIComponent(M.board.ws) : ''), body);
341
+ async function reloadSheet(s) {
342
+ s.text = null; s.md = null; s.log = null; s.health = null; s.props = null; s.draft = null; s.why = ''; s.rejecting = null;
343
+ await loadTab(s.tab);
344
+ if (sheet === s) { s.busy = false; drawSheet(); }
345
+ }
346
+ async function sheetPress(act) {
347
+ const s = sheet; keepDraft();
348
+ const fail = (m) => { s.busy = false; s.msg = m; drawSheet(); };
349
+ if (act === 'rejno') { s.rejecting = null; s.msg = ''; drawSheet(); return; }
350
+ if (act === 'discard') { s.draft = null; s.why = ''; s.msg = ''; drawSheet(); return; }
351
+ if (act === 'save') {
352
+ const r = editBody(s.d.path, s.text, s.draft == null ? s.text : s.draft, s.why); if (r.error) return fail(r.error);
353
+ s.busy = true; s.msg = ''; drawSheet();
354
+ const res = await dsPost('edit', r.body); if (sheet !== s) return;
355
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The document could not be saved.');
356
+ toast('Saved. The reason is in the Edit log.'); return reloadSheet(s);
357
+ }
358
+ if (act === 'ask') {
359
+ const r = askBody(s.d.path, s.askText); if (r.error) return fail(r.error);
360
+ s.busy = true; s.msg = ''; drawSheet();
361
+ const res = await dsPost('ask', r.body); if (sheet !== s) return;
362
+ s.busy = false;
363
+ if (!res || res.ok !== true || !res.id) return fail((res && res.error) || 'The agent could not be asked.');
364
+ s.askText = ''; s.ask = { state: 'working', id: res.id }; drawSheet(); return pollAsk(s, res.id);
365
+ }
366
+ const [kind, id] = [act.split(':')[0], act.slice(act.indexOf(':') + 1)];
367
+ const p = propsM(s).open.find((x) => x.id === id); if (!p) return;
368
+ if (kind === 'acc') {
369
+ const r = acceptBody(s.d.path, p, s.picked[id] || p.sections.filter((x) => !x.stale).map((x) => x.name)); if (r.error) return fail(r.error);
370
+ s.busy = true; s.msg = ''; drawSheet();
371
+ const res = await dsPost('accept', r.body); if (sheet !== s) return;
372
+ if (!res || res.ok !== true) { await reloadSheet(s); return fail((res && res.error) || 'The proposal could not be accepted.'); }
373
+ toast('Accepted. The file changed and the request is in the Edit log.'); return reloadSheet(s);
374
+ }
375
+ if (kind === 'rej') { s.rejecting = id; s.rejWhy = ''; s.msg = ''; drawSheet(); const f = $('#dsRj'); if (f) f.focus(); return; }
376
+ if (kind === 'rejgo') {
377
+ const r = rejectBody(s.d.path, p, s.rejWhy); if (r.error) return fail(r.error);
378
+ s.busy = true; s.msg = ''; drawSheet();
379
+ const res = await dsPost('reject', r.body); if (sheet !== s) return;
380
+ if (!res || res.ok !== true) return fail((res && res.error) || 'The proposal could not be rejected.');
381
+ toast('Rejected. The file is as it was.'); return reloadSheet(s);
382
+ }
383
+ }
384
+ async function pollAsk(s, id) {
385
+ for (let i = 0; i < 400 && sheet === s; i++) {
386
+ await new Promise((r) => setTimeout(r, 2000));
387
+ const a = await getJson('/api/doc-sheet/ask?id=' + encodeURIComponent(id) + wsq()); if (sheet !== s) return;
388
+ if (!a || a.ok === false) { s.ask = { state: 'failed', error: (a && a.error) || 'The answer could not be read.' }; drawSheet(); return; }
389
+ s.ask = a;
390
+ if (a.state !== 'working') { s.props = null; await loadTab('props'); if (sheet === s) drawSheet(); return; }
391
+ if (s.tab === 'props') drawSheet();
392
+ }
393
+ }
292
394
  $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
293
395
 
294
396
  /* ── load: the routes derive the initiatives in the background, so the first answers are "reading" ────────── */