create-pmos 0.428.0 → 0.430.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-board-test.js +4 -4
  8. package/workspace/briefing-premium-insights-test.js +82 -61
  9. package/workspace/briefing-premium-metrics-test.js +5 -3
  10. package/workspace/briefing-premium-sources-test.js +5 -5
  11. package/workspace/briefing-premium-test.js +5 -4
  12. package/workspace/changelog.json +24 -0
  13. package/workspace/ev-everywhere-test.js +2 -2
  14. package/workspace/guide/adler.md +45 -0
  15. package/workspace/guide/briefing-premium.md +2 -0
  16. package/workspace/guide/home.md +4 -2
  17. package/workspace/guide/index.md +2 -0
  18. package/workspace/guide/metric-drafts.md +49 -0
  19. package/workspace/guide/programs.md +2 -0
  20. package/workspace/intel-report-ui-test.js +189 -0
  21. package/workspace/intelligence-gaps-ui-test.js +168 -0
  22. package/workspace/lib/board-metrics-premium.js +1 -1
  23. package/workspace/lib/headless.js +15 -2
  24. package/workspace/lib/initiative-writer.js +16 -2
  25. package/workspace/lib/insight-moves.js +135 -0
  26. package/workspace/lib/insights-premium.js +9 -4
  27. package/workspace/lib/insights-records.js +14 -5
  28. package/workspace/lib/intel-report.js +432 -0
  29. package/workspace/lib/metric-draft-runs.js +193 -0
  30. package/workspace/lib/metric-drafts.js +261 -0
  31. package/workspace/lib/metrics-cli.js +104 -0
  32. package/workspace/lib/page-opens.js +74 -0
  33. package/workspace/lib/pmos-verbs.js +3 -0
  34. package/workspace/lib/report-setups.js +29 -13
  35. package/workspace/lib/route-modules.js +3 -0
  36. package/workspace/lib/routes-insight-moves.js +119 -0
  37. package/workspace/lib/routes-insights-premium.js +12 -3
  38. package/workspace/lib/routes-insights-records.js +13 -5
  39. package/workspace/lib/routes-metric-drafts.js +150 -0
  40. package/workspace/lib/routes-page-opens.js +26 -0
  41. package/workspace/lib/routes-phone-day.js +13 -2
  42. package/workspace/lib/routes-report-setups.js +97 -3
  43. package/workspace/lib/routes-viewer.js +5 -2
  44. package/workspace/lib/settings-store.js +6 -0
  45. package/workspace/metric-drafts-ui-test.js +209 -0
  46. package/workspace/milestone-suggest-test.js +4 -4
  47. package/workspace/package-lock.json +2 -2
  48. package/workspace/package.json +1 -1
  49. package/workspace/premium-phone-card-test.js +8 -5
  50. package/workspace/premium-viewer-flicker-test.js +1 -1
  51. package/workspace/public/pm/bd-acts.js +3 -3
  52. package/workspace/public/pm/bd-pin-card.css +4 -4
  53. package/workspace/public/pm/bd-prog-panel.js +12 -7
  54. package/workspace/public/pm/bd-prog.js +2 -2
  55. package/workspace/public/pm/cozy-adler.css +82 -0
  56. package/workspace/public/pm/cozy-adler.js +270 -0
  57. package/workspace/public/pm/cozy-aud.css +1 -1
  58. package/workspace/public/pm/cozy-board.css +256 -256
  59. package/workspace/public/pm/cozy-ev.css +48 -45
  60. package/workspace/public/pm/cozy-evmodel.js +1 -1
  61. package/workspace/public/pm/cozy-home-rows.css +23 -23
  62. package/workspace/public/pm/cozy-home.css +211 -207
  63. package/workspace/public/pm/cozy-insights.css +221 -108
  64. package/workspace/public/pm/cozy-live-pill.css +5 -5
  65. package/workspace/public/pm/cozy-mtg-present.css +23 -23
  66. package/workspace/public/pm/cozy-nav.js +3 -1
  67. package/workspace/public/pm/cozy-news.js +2 -2
  68. package/workspace/public/pm/cozy-panel.css +29 -29
  69. package/workspace/public/pm/cozy-pick.css +5 -5
  70. package/workspace/public/pm/cozy-rec-now.css +20 -20
  71. package/workspace/public/pm/cozy-rec-present.css +11 -11
  72. package/workspace/public/pm/cozy-rec-tab.css +13 -13
  73. package/workspace/public/pm/cozy-search.js +4 -2
  74. package/workspace/public/pm/cozy-settings.js +16 -3
  75. package/workspace/public/pm/cozy-steps.css +9 -9
  76. package/workspace/public/pm/cozy-today.css +122 -71
  77. package/workspace/public/pm/cozy-viewer.css +7 -7
  78. package/workspace/public/pm/cozy-viewer.js +1 -1
  79. package/workspace/public/pm/cozy-vw-mtg.css +81 -81
  80. package/workspace/public/pm/cozy-vw-rp.css +53 -53
  81. package/workspace/public/pm/cozy-vw-shell.css +23 -23
  82. package/workspace/public/pm/cozy-vw.css +117 -117
  83. package/workspace/public/pm/cozy-xv.css +11 -11
  84. package/workspace/public/pm/cozy.css +34 -15
  85. package/workspace/public/pm/hi-pop.css +19 -19
  86. package/workspace/public/pm/home-app.js +33 -9
  87. package/workspace/public/pm/home-chat.js +10 -2
  88. package/workspace/public/pm/home-day.js +155 -27
  89. package/workspace/public/pm/home-ini.css +32 -32
  90. package/workspace/public/pm/home-line.css +7 -7
  91. package/workspace/public/pm/home-list.js +12 -1
  92. package/workspace/public/pm/home-phone-card.js +18 -15
  93. package/workspace/public/pm/home-today.js +5 -3
  94. package/workspace/public/pm/ini-view-model.js +1 -1
  95. package/workspace/public/pm/ini-view.css +108 -102
  96. package/workspace/public/pm/ini-view.js +22 -3
  97. package/workspace/public/pm/loose-props.css +13 -13
  98. package/workspace/public/pm/metric-drafts.css +89 -0
  99. package/workspace/public/pm/metric-drafts.js +204 -0
  100. package/workspace/public/pm/ms-suggest.css +8 -8
  101. package/workspace/public/pm/ms-suggest.js +2 -1
  102. package/workspace/public/pm/ov-view.css +12 -12
  103. package/workspace/public/pm/premium-board.js +2 -2
  104. package/workspace/public/pm/premium-chart-tab.js +6 -6
  105. package/workspace/public/pm/premium-insights.js +364 -107
  106. package/workspace/public/pm/premium-report-intel.css +56 -0
  107. package/workspace/public/pm/premium-report-intel.js +232 -0
  108. package/workspace/public/pm/premium-shell.js +2 -2
  109. package/workspace/public/pm/premium-vw-cal.js +1 -1
  110. package/workspace/public/pm/premium-vw-file.js +2 -2
  111. package/workspace/public/pm/premium-welcome.js +3 -2
  112. package/workspace/public/pm/premium.css +130 -128
  113. package/workspace/public/pm/prog-order.css +6 -6
  114. package/workspace/public/pm/program-charter.css +23 -23
  115. package/workspace/public/pm/program-model.js +7 -0
  116. package/workspace/public/pm/rp-parts.js +2 -2
  117. package/workspace/public/pm/sort-order.css +1 -1
  118. package/workspace/public/pm/split-merge.css +15 -15
  119. package/workspace/public/pm/split-merge.js +2 -1
  120. package/workspace/public/pm/task-card.css +21 -21
  121. package/workspace/public/pm/tk-tasks.css +37 -37
  122. package/workspace/public/pm/tk-view.css +6 -6
  123. package/workspace/public/pm/wf-page.css +28 -28
  124. package/workspace/public/premium-intelligence.html +82 -0
  125. package/workspace/server.js +38 -3
  126. package/workspace/skills/metric-draft.skill +47 -0
  127. package/workspace/test-lists/intel-report-ui.json +5 -0
  128. package/workspace/test-lists/intel-report.json +9 -0
  129. package/workspace/test-lists/intelligence-gaps-ui.json +5 -0
  130. package/workspace/test-lists/intelligence-gaps.json +5 -0
  131. package/workspace/test-lists/metric-drafts-ui.json +5 -0
  132. package/workspace/test-lists/metric-drafts.json +9 -0
  133. package/workspace/test-run.js +3 -0
  134. package/workspace/public/premium-insights.html +0 -81
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+ /* page-opens.js — the pages the PM opens, by day (feedback batch 16 item 1, the third 0.429.0 gap). The ✦ strip on Intelligence may propose
3
+ * "You open this every week. Shall I make it a report?" only when this record says so (honest state). THE ONE WRITER and THE ONE FOLD of
4
+ * <runtime>/page-opens.jsonl. LOCAL ONLY: the file is in the workspace's runtime folder on this computer, never in the repository, and nothing
5
+ * reads it but the proposal below. No clock of its own: every time comes in.
6
+ *
7
+ * THE LEDGER. One line per page, view and day, { at, ws, page, view }. A second open of the same view on the same day writes nothing.
8
+ * page 'intelligence' (PAGES) view 'view' (the whole page) or 'dashboard:<id>' (a saved dashboard on screen), as lib/intel-report.js scopes
9
+ *
10
+ * record(dir, { ws, page, view }, at) → { ok, wrote } | { ok: false, error }
11
+ * readLines(dir) · ledgerFile(dir)
12
+ * weeklyOf(lines, { ws, page, now, weeks }) PURE → { view, weeks, day, opens } | null
13
+ * the view opened in each of the last `weeks` calendar weeks (Monday to Sunday; 3 by default), the week now counted when it has an open.
14
+ * `day` is the weekday it is opened on most (Mon…Sun), so a report can be ready before it. Two views that both qualify: the one opened more.
15
+ */
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ const FILE = 'page-opens.jsonl';
20
+ const PAGES = ['intelligence'];
21
+ const VIEW_RE = /^(view|dashboard:[A-Za-z0-9._:-]{1,100})$/;
22
+ const WS_RE = /^[A-Za-z0-9._-]{1,120}$/;
23
+ const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
24
+ const DAY = 864e5;
25
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
26
+ const dayOf = (at) => String(at || '').slice(0, 10);
27
+
28
+ function ledgerFile(dir) { return dir ? path.join(dir, FILE) : null; }
29
+ function readLines(dir) {
30
+ const f = ledgerFile(dir); if (!f) return [];
31
+ let text = '';
32
+ try { text = fs.readFileSync(f, 'utf8'); } catch { return []; }
33
+ const out = [];
34
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && typeof l.at === 'string' && PAGES.includes(l.page) && VIEW_RE.test(String(l.view))) out.push(l); } catch { /* a torn line is skipped */ } }
35
+ return out;
36
+ }
37
+ function record(dir, o, at) {
38
+ if (!dir) return { ok: false, error: 'This workspace has no runtime folder, so the open is not recorded.' };
39
+ if (!isObj(o) || !WS_RE.test(String(o.ws || ''))) return { ok: false, error: 'ws names the workspace' };
40
+ if (!PAGES.includes(o.page)) return { ok: false, error: 'page is one of: ' + PAGES.join(', ') };
41
+ const view = o.view == null || o.view === '' ? 'view' : String(o.view);
42
+ if (!VIEW_RE.test(view)) return { ok: false, error: 'view is view or dashboard:<id>' };
43
+ const d = dayOf(at);
44
+ if (readLines(dir).some((l) => l.ws === o.ws && l.page === o.page && l.view === view && dayOf(l.at) === d)) return { ok: true, wrote: false };
45
+ fs.mkdirSync(dir, { recursive: true });
46
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify({ at, ws: o.ws, page: o.page, view }) + '\n');
47
+ return { ok: true, wrote: true };
48
+ }
49
+
50
+ /** The Monday (UTC) of the week a time falls in. */
51
+ const mondayOf = (t) => { const d = new Date(t), back = (d.getUTCDay() + 6) % 7; return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - back * DAY; };
52
+ function weeklyOf(lines, { ws, page = 'intelligence', now = Date.now(), weeks = 3 } = {}) {
53
+ const L = (lines || []).filter((l) => l && l.ws === ws && l.page === page && !Number.isNaN(Date.parse(l.at)));
54
+ if (!L.length) return null;
55
+ const thisWeek = mondayOf(now);
56
+ const byView = new Map();
57
+ for (const l of L) { if (!byView.has(l.view)) byView.set(l.view, []); byView.get(l.view).push(Date.parse(l.at)); }
58
+ let best = null;
59
+ for (const [view, T] of byView) {
60
+ const wk = new Set(T.map(mondayOf));
61
+ // the run of weeks ending this week (or last week, when this week has no open yet)
62
+ let end = wk.has(thisWeek) ? thisWeek : thisWeek - 7 * DAY, n = 0;
63
+ while (wk.has(end - n * 7 * DAY)) n++;
64
+ if (n < weeks) continue;
65
+ const from = end - (n - 1) * 7 * DAY, inRun = T.filter((t) => t >= from), count = new Array(7).fill(0);
66
+ for (const t of inRun) count[new Date(t).getUTCDay()]++;
67
+ const top = count.indexOf(Math.max(...count));
68
+ const cand = { view, weeks: n, day: DAYS[top], opens: inRun.length };
69
+ if (!best || cand.opens > best.opens) best = cand;
70
+ }
71
+ return best;
72
+ }
73
+
74
+ module.exports = { FILE, PAGES, VIEW_RE, ledgerFile, readLines, record, weeklyOf };
@@ -78,6 +78,9 @@ const VERBS = Object.freeze({
78
78
  // Not a pm-os-absorb verb (run: null): feedback batch 12 items 2, 3 and 4 (Claude proposes, the one ✦) added it through the same table.
79
79
  propose: Object.freeze({ module: 'propose-cli.js', run: null, guide: 'claude-proposes.md',
80
80
  help: 'pmos propose look|found|date|done|name|status … — what Claude\'s run files under an initiative\'s ✦ for the PM to keep or drop (pmos propose help)' }),
81
+ // Not a pm-os-absorb verb (run: null): batch 15 item 1 (Claude drafts metrics without being asked) added it through the same table.
82
+ metrics: Object.freeze({ module: 'metrics-cli.js', run: null, guide: 'metric-drafts.md',
83
+ help: 'pmos metrics draft read|step|row|end|status … — what Claude\'s metric-draft run files for the PM to keep or drop (pmos metrics help)' }),
81
84
  driver: Object.freeze({ module: 'driver-cli.js', run: null, guide: 'initiative-driver.md',
82
85
  help: 'pmos driver propose|status|keep|return|drop|pause|resume|mode … — the Initiative Driver: drafts for you to keep, send back or drop (pmos driver help)' }),
83
86
  // Not a pm-os-absorb verb (run: null): initiative horizon-scan added it through the same table; horizon-scan-portfolio added section, propose, setting and --boards.
@@ -17,13 +17,16 @@
17
17
  * scheduleFor(setup) · registerSchedule(store, setup, opts) · unregisterSchedule(store, setup) the draft-only schedule
18
18
  * askStart / askChange / askCancel / askEnd / fileProposal(file, …) the Ask box
19
19
  * fileFinding / dismissFinding / setFinder / findStart / findEnd the weekly finder
20
+ * stripDismiss(file, { id }) Not now on a report the Intelligence ✦ strip proposed
20
21
  * migrate(root, { runtimeDir, wsId, isHome, titleOf, now }) the dashboard schedules, once
21
22
  * dashboardKeys(root) the dashboard keys the old schedule tick leaves alone (migrated, or held by a setup)
22
23
  * writeDocument(root, setup, slot, markdown, { now }) <state>/reports/<id>/<slot>.md for a dashboard-sourced setup
23
24
  *
24
25
  * THE LINES. Every line is { v: 1, ev, …, at, by? }. Who wrote a line is the call path (lib/actor.js), never an argument:
25
- * setup { id, name, purpose, audience, source: 'work'|'dashboard:<key>', output, schedule, sources[], sections[], learned_from, fixes[],
26
- * product, ws, last_run, def_sha, from? } the PM pressed Set up. `from` is { ask } or { finding }
26
+ * setup { id, name, purpose, audience, source: 'work'|'dashboard:<key>'|'intelligence:<scope>', output, schedule, sources[], sections[], learned_from, fixes[],
27
+ * product, ws, last_run, def_sha, from?, storyline? } the PM pressed Set up. `from` is { ask } or { finding }.
28
+ * An Intelligence-sourced setup (batch 15 item 4, lib/intel-report.js) keeps the PM's storyline edits: { answer?, ask?: { text, who, by }, items?: [{ id, on }] }.
29
+ * It is drafted like a dashboard-sourced one, by the tick in lib/routes-report-setups.js, from the live Intelligence model
27
30
  * change { id, …the fields that changed } the PM edited a recurring report
28
31
  * pause · resume · remove { id } a removed setup is a deleted TEMPLATE: its schedule stops, its documents stay
29
32
  * doc-discard { doc, path } the PM discarded an unissued draft (the file is deleted; this line keeps the record)
@@ -39,8 +42,9 @@
39
42
  * finding-dismiss { id?, pattern } "Not a report": the pattern is not proposed again
40
43
  * finder { cadence?, sources? } the finder settings: weekly | off, and the four sources
41
44
  * migrated { keys[], count } the one-time move of the dashboard schedules
45
+ * strip-dismiss { id } Not now on a report the Intelligence ✦ strip proposed (lib/intel-report.js proposalsOf)
42
46
  *
43
- * FOLD. { setups: Map id → setup, removed: Map id → setup (deleted templates), archived: Set of doc ids, discarded: [{ doc, path, at }], asks: Map, findings: Map, dismissed: { patterns, names }, finder: { cadence, sources }, finds: [], migrated }.
47
+ * FOLD. { setups: Map id → setup, removed: Map id → setup (deleted templates), archived: Set of doc ids, discarded: [{ doc, path, at }], asks: Map, findings: Map, dismissed: { patterns, names }, finder: { cadence, sources }, finds: [], migrated, stripDismissed: Set of strip proposal ids }.
44
48
  * A later line wins field by field; a `remove` moves the setup to `removed` (its name stays on its documents); a line that does not parse, or names an unknown event, is skipped.
45
49
  *
46
50
  * THE BI-WEEKLY PARITY. lib/schedule-logic.js fires a bi-weekly schedule on the first matching weekday slot that is at least 12.5 days after
@@ -57,10 +61,11 @@ const crypto = require('crypto');
57
61
  const logic = require('./schedule-logic.js');
58
62
  const reportDraft = require('./report-draft.js');
59
63
  const docSync = require('./doc-sync.js');
64
+ const IR = require('./intel-report.js');
60
65
 
61
66
  const LEDGER = 'report-setups.jsonl';
62
67
  const EVENTS = Object.freeze(['setup', 'change', 'pause', 'resume', 'remove', 'drafted', 'ask-start', 'proposal', 'proposal-change', 'proposal-cancel', 'ask-end',
63
- 'find-start', 'find-end', 'finding', 'finding-dismiss', 'finder', 'migrated', 'doc-discard', 'doc-archive']);
68
+ 'find-start', 'find-end', 'finding', 'finding-dismiss', 'finder', 'migrated', 'doc-discard', 'doc-archive', 'strip-dismiss']);
64
69
  const OUTPUTS = Object.freeze(['google-slides', 'google-doc', 'google-sheets', 'confluence', 'pdf']);
65
70
  const CADENCES = Object.freeze(['daily', 'weekly', 'bi-weekly', 'monthly']);
66
71
  const DAYS = Object.freeze(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']);
@@ -175,7 +180,9 @@ function checkProposal(input) {
175
180
  if (!oneLine(x.purpose, LIMITS.purpose)) return { ok: false, error: `purpose is one line of 1 to ${LIMITS.purpose} characters` };
176
181
  if (!oneLine(x.audience, LIMITS.audience)) return { ok: false, error: `audience is one line of 1 to ${LIMITS.audience} characters` };
177
182
  const source = x.source == null || x.source === '' ? 'work' : x.source;
178
- if (source !== 'work' && !DASH_RE.test(String(source))) return { ok: false, error: 'source is work, or dashboard:portfolio, dashboard:board:<id> or dashboard:initiative:<id>' };
183
+ if (source !== 'work' && !DASH_RE.test(String(source)) && !IR.isIntelligence(source)) return { ok: false, error: 'source is work, dashboard:portfolio, dashboard:board:<id>, dashboard:initiative:<id> or intelligence:<scope>' };
184
+ let storyline = null;
185
+ if (x.storyline != null) { const c = IR.checkStoryline(x.storyline); if (!c.ok) return c; storyline = c.storyline; }
179
186
  if (!OUTPUTS.includes(x.output)) return { ok: false, error: `output is one of ${OUTPUTS.join(', ')}` };
180
187
  const sch = checkSchedule(x.schedule);
181
188
  if (!sch.ok) return sch;
@@ -196,7 +203,7 @@ function checkProposal(input) {
196
203
  return { ok: true, proposal: {
197
204
  name: x.name.trim(), purpose: x.purpose.trim(), audience: clean(x.audience), source, output: x.output, schedule: sch.schedule,
198
205
  sources: sources.list, sections: sections.list.length ? sections.list : FRAME.slice(), learned_from: x.learned_from ? x.learned_from.trim() : null,
199
- fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}),
206
+ fixes: fixes.list, found, ...(x.product ? { product: clean(x.product) } : {}), ...(storyline ? { storyline } : {}),
200
207
  } };
201
208
  }
202
209
 
@@ -211,11 +218,11 @@ function checkEvidence(list) {
211
218
  }
212
219
 
213
220
  // ── the fold ─────────────────────────────────────────────────────────────────────────────────────────
214
- const SETUP_FIELDS = ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes', 'product', 'def_sha'];
221
+ const SETUP_FIELDS = ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes', 'product', 'def_sha', 'storyline'];
215
222
 
216
223
  function fold(lines) {
217
224
  const st = { setups: new Map(), removed: new Map(), archived: new Set(), discarded: [], asks: new Map(), findings: new Map(), dismissed: { patterns: new Set(), names: new Set() },
218
- finder: { cadence: 'weekly', sources: { ...FINDER_DEFAULTS } }, finds: [], migrated: null };
225
+ finder: { cadence: 'weekly', sources: { ...FINDER_DEFAULTS } }, finds: [], migrated: null, stripDismissed: new Set() };
219
226
  for (const l of lines || []) {
220
227
  if (!isObj(l)) continue;
221
228
  switch (l.ev) {
@@ -223,7 +230,8 @@ function fold(lines) {
223
230
  if (!ID_RE.test(String(l.id || '')) || st.setups.has(l.id)) break;
224
231
  st.setups.set(l.id, { id: l.id, name: l.name, purpose: l.purpose, audience: l.audience, source: l.source || 'work', output: l.output, schedule: l.schedule,
225
232
  sources: l.sources || [], sections: l.sections || FRAME.slice(), learned_from: l.learned_from || null, fixes: l.fixes || [], product: l.product || null,
226
- ws: l.ws || null, status: 'active', created_at: l.at, last_run: l.last_run || l.at, def_sha: l.def_sha || null, from: l.from || null, migrated: !!l.migrated, drafted: [] });
233
+ ws: l.ws || null, status: 'active', created_at: l.at, last_run: l.last_run || l.at, def_sha: l.def_sha || null, from: l.from || null, migrated: !!l.migrated, drafted: [],
234
+ ...(isObj(l.storyline) ? { storyline: l.storyline } : {}) });
227
235
  if (l.from && l.from.ask) st.asks.delete(l.from.ask);
228
236
  if (l.from && l.from.finding && st.findings.has(l.from.finding)) st.findings.get(l.from.finding).state = 'set-up';
229
237
  break;
@@ -258,6 +266,7 @@ function fold(lines) {
258
266
  case 'finding':
259
267
  if (FINDING_RE.test(String(l.id || '')) && !st.findings.has(l.id)) st.findings.set(l.id, { id: l.id, run: l.run || null, pattern: l.pattern, name: l.name, why: l.why, evidence: l.evidence || [], confidence: l.confidence, proposal: l.proposal, at: l.at, state: 'open' });
260
268
  break;
269
+ case 'strip-dismiss': if (typeof l.id === 'string') st.stripDismissed.add(l.id); break;
261
270
  case 'finding-dismiss': {
262
271
  const f = l.id ? st.findings.get(l.id) : null;
263
272
  if (f) f.state = 'dismissed';
@@ -371,7 +380,7 @@ function definitionText(setup, { product, now = new Date() } = {}) {
371
380
  '## Audience', '', `${setup.audience}. Needs your call holds asks to them only, each with who and by when.`, '',
372
381
  '## Output', '', `The finished report is ${OUTPUT_WORDS[setup.output] || setup.output}. PMOS keeps the report as a document in this repository; a copy is made only when the PM presses Create the copy.`, '',
373
382
  '## Schedule', '', scheduleSentence(setup.schedule, now), '',
374
- '## Sources', '', list(setup.sources, dash ? `- The dashboard ${setup.source.slice('dashboard:'.length)}, as its report frame reads it.` : '- The local ledgers that `pmos report draft` reads.'), '',
383
+ '## Sources', '', list(setup.sources, IR.isIntelligence(setup.source) ? `- Intelligence (${IR.scopeOf(setup.source)}): the KR metric records, health budgets and verdicts it reads.` : dash ? `- The dashboard ${setup.source.slice('dashboard:'.length)}, as its report frame reads it.` : '- The local ledgers that `pmos report draft` reads.'), '',
375
384
  '## Sections', '', 'The script writes the frame and every number. The agent writes only the notes.', '',
376
385
  ...FRAME.map((id, i) => `${i + 1}. ${SECTION_NOTES[id]}`), '',
377
386
  '## Learned from earlier copies', '', setup.learned_from || 'None yet. Add what the earlier copies show after the first cycle.', '',
@@ -509,7 +518,7 @@ function setUp(root, input, opts = {}) {
509
518
  }
510
519
  append(file, { ev: 'setup', id, name: p.name, purpose: p.purpose, audience: p.audience, source: p.source, output: p.output, schedule: p.schedule, sources: p.sources,
511
520
  sections: p.sections, learned_from: p.learned_from, fixes: p.fixes, product: setup.product, ws: opts.wsId || null, last_run: lastRun, def_sha: def.sha,
512
- ...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}) }, { now, by: opts.by });
521
+ ...(from ? { from } : {}), ...(opts.migrated ? { migrated: true } : {}), ...(p.storyline ? { storyline: p.storyline } : {}) }, { now, by: opts.by });
513
522
  const next = nextDraftAt(p.schedule, lastRun, now);
514
523
  const folded = fold(readLines(file)).setups.get(id);
515
524
  return { ok: true, setup: folded, definition: def.path, first_draft: next ? { slot: localDay(next), at: next.toISOString(), day: next.getDay() } : null };
@@ -525,7 +534,7 @@ function change(root, id, patch, opts = {}) {
525
534
  if (!merged.ok) return refuse(400, merged.error);
526
535
  const now = opts.now == null ? new Date() : new Date(opts.now);
527
536
  const fields = {};
528
- for (const k of ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes']) {
537
+ for (const k of ['name', 'purpose', 'audience', 'output', 'schedule', 'sources', 'sections', 'learned_from', 'fixes', 'storyline']) {
529
538
  if (Object.prototype.hasOwnProperty.call(patch || {}, k) && JSON.stringify(merged.proposal[k]) !== JSON.stringify(cur[k])) fields[k] = merged.proposal[k];
530
539
  }
531
540
  if (!Object.keys(fields).length) return { ok: true, setup: cur, unchanged: true };
@@ -699,6 +708,13 @@ function dismissFinding(file, { id, name, by, now }) {
699
708
  append(file, { ev: 'finding-dismiss', id: l.finding.id, pattern: l.finding.pattern }, { now, by });
700
709
  return { ok: true };
701
710
  }
711
+ /** Not now on a report the Intelligence ✦ strip proposed: that proposal is not offered again. */
712
+ function stripDismiss(file, { id, by, now }) {
713
+ if (typeof id !== 'string' || !/^(found:rf-[0-9a-f]{10}|period-end:\d{4}-\d{2}-\d{2}|opened:(view|dashboard:[A-Za-z0-9._:-]{1,100}))$/.test(id)) return refuse(400, 'id is a proposal of the strip: found:<finding>, period-end:<date> or opened:<view>');
714
+ if (fold(readLines(file)).stripDismissed.has(id)) return { ok: true, unchanged: true };
715
+ append(file, { ev: 'strip-dismiss', id }, { now, by });
716
+ return { ok: true };
717
+ }
702
718
  function setFinder(file, { cadence, sources, by, now }) {
703
719
  const line = {};
704
720
  if (cadence !== undefined) { if (!FINDER_CADENCES.includes(cadence)) return refuse(400, `cadence is ${FINDER_CADENCES.join(' or ')}`); line.cadence = cadence; }
@@ -802,6 +818,6 @@ module.exports = {
802
818
  ledgerFile, stateDir, append, readLines, fold, stateOf, openFindings, isDismissed, slugOf, patternOf, checkProposal, checkEvidence, checkSchedule,
803
819
  scheduleLabel, scheduleOf, firstSlot, initialLastRun, nextDraftAt, definitionText, writeDefinition, definitionsOf, definitionFile, shaOf,
804
820
  fileScheduleStore, scheduleFor, registerSchedule, updateSchedule, unregisterSchedule,
805
- setUp, change, pause, resume, remove, reschedule, discardDraft, archiveDoc, documentAt, askStart, askChange, askCancel, askEnd, fileProposal, findStart, findEnd, fileFinding, dismissFinding, lookupFinding, setFinder,
821
+ setUp, change, pause, resume, remove, reschedule, discardDraft, archiveDoc, documentAt, askStart, askChange, askCancel, askEnd, fileProposal, findStart, findEnd, fileFinding, dismissFinding, stripDismiss, lookupFinding, setFinder,
806
822
  writeDocument, frameMarkdown, migrate, migratedKeys, dashboardKeys, dashTitle, keyOfSource, longDate, localDay,
807
823
  };
@@ -100,6 +100,9 @@ const MODULES = Object.freeze([
100
100
  'routes-premium-charts', // premium-studio-chart: the charts the PM makes in the Insight Studio (premium-charts.jsonl; page-press POST save)
101
101
  'routes-report-design', // report-design-studio: the design studio (describe, samples, turns, versions, This is it), cycle renders and decisions, speaker notes and pins
102
102
  '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)
103
+ 'routes-insight-moves', // batch 16 item 1: the ✓ and Undo of a drafted move on the Intelligence ✦ strip (insight-moves.jsonl; date, anchor, chase to the outbox)
104
+ 'routes-page-opens', // batch 16 item 1: the pages the PM opens, by day, local only (runtime page-opens.jsonl); drives the weekly report proposal
105
+ 'routes-metric-drafts', // batch 15 item 1: the metrics Claude drafts unasked for a product, a program or an initiative; ✓ keep writes kr-metrics (metric-drafts.jsonl; page-press POST)
103
106
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
104
107
  ]);
105
108
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
@@ -0,0 +1,119 @@
1
+ 'use strict';
2
+ /* routes-insight-moves.js — the ✓ and the Undo of a ✦ strip move on Intelligence (feedback batch 16 item 1; the drafts are lib/insight-moves.js).
3
+ *
4
+ * POST /api/insight-moves/apply { ws, board, sig } → { ok, sig, kind, said } ✓: the move the strip shows now, made through its writer
5
+ * POST /api/insight-moves/undo { ws, sig } → { ok, sig } the last ✓ of that move, taken back
6
+ *
7
+ * The page sends only the move's sig. The route builds Intelligence again (GET /api/insights-premium, the page's own read) and makes the move it
8
+ * finds under that sig, so a stale page or a crafted body can never write a move Claude did not draft. A sig that is no longer drafted is 409.
9
+ *
10
+ * THE WRITERS, the same ones the rest of PMOS uses:
11
+ * date scripts/records edit of the KR metric record: { by } Undo: { by: the day it had }
12
+ * anchor lib/initiative-writer.js setAnchor (PM-only act 'anchor', pm-guard) Undo: restoreAnchor, the line exactly as it was
13
+ * chase scripts/outbox.js draftOutbox → lib/outbox-store.js, channel jira-write Undo: the outbox entry discarded (a sent entry stays: 409)
14
+ * Each ✓ and each Undo is one line of <state>/insight-moves.jsonl. With no state folder every write answers 409. Nothing is sent outward. */
15
+ const guard = require('./pm-guard.js');
16
+ const MV = require('./insight-moves.js');
17
+ const { repoScript } = require('./repo-script.js');
18
+ const { recordsDirFor } = require('./records-dir.js');
19
+
20
+ const text = (v) => (typeof v === 'string' ? v : '');
21
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
22
+ const records = () => require(repoScript('records/index.js'));
23
+ const UI = () => require(repoScript('trust/ledger.js')).actorFrom({ ui: true });
24
+ const NO_STATE = 'This repository has no PMOS state folder (pmos/state, state or .pmos). Nothing is saved until the folder exists.';
25
+ const dirOf = (ctx, w) => { try { return ctx.stateDirFor ? ctx.stateDirFor(w) : null; } catch { return null; } };
26
+
27
+ /** The Intelligence model, read the way the page reads it. */
28
+ async function modelOf(req, ctx, ws, board) {
29
+ let out = null;
30
+ const c = Object.assign({}, ctx, { json: (res, obj) => { out = obj; } });
31
+ const q = new URLSearchParams(); if (ws) q.set('ws', ws); if (board) q.set('board', board);
32
+ await require('./routes-insights-premium.js').handle({ method: 'GET', headers: (req && req.headers) || {} }, {}, new URL('http://local/api/insights-premium?' + q.toString()), c);
33
+ return out && out.ok ? out.model : null;
34
+ }
35
+ const movesIn = (m) => { const I = (m && m.insight) || {}; return [I.move].concat((I.more || []).map((x) => x.move)).filter(Boolean); };
36
+
37
+ function write(ctx, w, mv, actor) {
38
+ if (mv.kind === 'date') {
39
+ let e;
40
+ try { e = records().edit(recordsDirFor(ctx, w.id), 'kr-metrics', mv.goal, { by: mv.to }, UI(), 'Moved the target date Claude drafted on Intelligence'); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; }
41
+ return e.ok ? { undo: { by: mv.from } } : { error: 'The date could not be moved: ' + (e.reasons || []).join('; ') };
42
+ }
43
+ if (mv.kind === 'anchor') {
44
+ const r = require('./initiative-writer.js').setAnchor(w.root, mv.ini, mv.to, { actor });
45
+ return r.ok ? { undo: { from: r.from || '' } } : { error: r.error || 'The anchor could not be set.' };
46
+ }
47
+ if (mv.kind === 'chase') {
48
+ if (!ctx.runtimeDir) return { error: 'This workspace has no outbox, so the comment could not be drafted.' };
49
+ try {
50
+ const e = require(repoScript('outbox.js')).draftOutbox({ channel: 'jira-write', recipient: mv.epic, subject: 'A new date for ' + mv.ini, body: mv.body, origin: 'pm' });
51
+ const entry = { id: 'out-' + require('crypto').randomBytes(6).toString('hex'), ...e };
52
+ require('./outbox-store.js').appendEvent(ctx.runtimeDir, { event: 'queued', ...entry }, new Date());
53
+ return { undo: { entry: entry.id } };
54
+ } catch (x) { return { error: 'The comment could not go to the outbox: ' + String((x && x.message) || x).slice(0, 160) }; }
55
+ }
56
+ return { error: 'There is no such move.' };
57
+ }
58
+
59
+ function unwrite(ctx, w, x, actor, req) {
60
+ const mv = x.move || {}, u = x.undo || {};
61
+ if (mv.kind === 'date') {
62
+ let e;
63
+ try { e = records().edit(recordsDirFor(ctx, w.id), 'kr-metrics', mv.goal, { by: u.by }, UI(), 'Undo of a moved target date'); } catch (y) { e = { ok: false, reasons: [String((y && y.message) || y).slice(0, 160)] }; }
64
+ return e.ok ? {} : { error: 'The date could not be put back: ' + (e.reasons || []).join('; ') };
65
+ }
66
+ if (mv.kind === 'anchor') {
67
+ const r = require('./initiative-writer.js').restoreAnchor(w.root, mv.ini, u.from || '', { actor });
68
+ return r.ok ? {} : { error: r.error || 'The anchor could not be put back.' };
69
+ }
70
+ if (mv.kind === 'chase') {
71
+ const r = require('./routes-outbox.js').discard(req, { id: u.entry }, ctx.runtimeDir);
72
+ return r.status === 200 ? {} : { status: r.status, error: (r.body && r.body.error) === 'a sent entry is a record and is not discarded' ? 'The comment was sent already, so it cannot be taken back.' : 'The comment could not be taken out of the outbox.' };
73
+ }
74
+ return { error: 'There is no such move.' };
75
+ }
76
+
77
+ async function handle(req, res, url, ctx) {
78
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
79
+ const what = url.pathname.replace(/^\/api\/insight-moves\/?/, '');
80
+ if (!['apply', 'undo'].includes(what)) return send(bad(404, 'no such insight-moves route'));
81
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
82
+ const read = await ctx.readJson(req);
83
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
84
+ const body = read.body || {};
85
+ let w = null;
86
+ try { w = ctx.getWs(text(body.ws) || null); } catch { w = null; }
87
+ if (!w || (body.ws && w.id !== body.ws)) return send(bad(404, 'no such workspace'));
88
+ const sig = text(body.sig);
89
+ if (!/^mv-[0-9a-f]{12}$/.test(sig)) return send(bad(400, 'sig names the move the strip shows'));
90
+ const dir = dirOf(ctx, w);
91
+ if (!dir) return send(bad(409, NO_STATE));
92
+ const at = () => new Date().toISOString();
93
+
94
+ if (what === 'apply') {
95
+ const m = await self.modelOf(req, ctx, w.id, text(body.board) || null);
96
+ if (!m) return send(bad(500, 'Intelligence could not be read, so nothing was changed.'));
97
+ const mv = movesIn(m).find((x) => x.sig === sig);
98
+ if (!mv) return send(bad(409, 'That move is no longer drafted. Nothing changed.'));
99
+ if (mv.done) return send(bad(409, 'You made this move already.'));
100
+ const g = mv.kind === 'anchor' ? guard.requirePmPress(req, body, { act: 'anchor' }) : guard.requirePagePress(req, body);
101
+ if (!g.ok) return send(bad(g.status, g.error));
102
+ const r = write(ctx, w, mv, g.actor);
103
+ if (r.error) return send(bad(400, r.error));
104
+ const move = { kind: mv.kind, goal: mv.goal, ...(mv.ini ? { ini: mv.ini } : {}), ...(mv.to ? { to: mv.to } : {}), ...(mv.epic ? { epic: mv.epic } : {}) };
105
+ MV.append(dir, g.actor, { kind: 'apply', sig, move, undo: r.undo }, at());
106
+ return send({ status: 200, body: { ok: true, sig, kind: mv.kind, said: mv.said } });
107
+ }
108
+ // undo
109
+ const x = MV.read(dir).get(sig);
110
+ if (!x || x.state !== 'applied') return send(bad(409, 'There is nothing to undo.'));
111
+ const g = x.move.kind === 'anchor' ? guard.requirePmPress(req, body, { act: 'anchor' }) : guard.requirePagePress(req, body);
112
+ if (!g.ok) return send(bad(g.status, g.error));
113
+ const r = unwrite(ctx, w, x, g.actor, req);
114
+ if (r.error) return send(bad(r.status || 400, r.error));
115
+ MV.append(dir, g.actor, { kind: 'undo', sig }, at());
116
+ return send({ status: 200, body: { ok: true, sig } });
117
+ }
118
+
119
+ const self = module.exports = { prefixes: ['/api/insight-moves'], handle, modelOf }; // modelOf is read through `self`, so a test can stand in for it
@@ -9,7 +9,8 @@
9
9
  * briefing-premium-reports adds the board's saved dashboards (lib/premium-dashboards.js list) and the workspace's GET /api/report-setups answer
10
10
  * (setups, findings, asks). That GET is the console's own read: like the console, it may move old dashboard schedules into recurring reports once
11
11
  * per repository. insights-one-list adds the pinned dashboard (lib/premium-dashboards.js pinned) and the opening sentence of each report file, read here
12
- * from the workspace's repository. This route itself writes nothing. The page's presses post to /api/report-setups/* and /api/premium-dashboards/save. */
12
+ * from the workspace's repository. Feedback batch 16 item 1 gives each ✦ strip finding its drafted move (lib/insight-moves.js draftAll; the ✓ is
13
+ * lib/routes-insight-moves.js). This route itself writes nothing. The page's presses post to /api/report-setups/* and /api/premium-dashboards/save. */
13
14
  const Insights = require('./insights-premium.js');
14
15
  const boards = require('./routes-boards.js');
15
16
  const strategy = require('./routes-c3-strategy.js');
@@ -59,7 +60,7 @@ module.exports = {
59
60
  let outcomes, goalMeta = {};
60
61
  try {
61
62
  const today = new Date(), pad = (n) => String(n).padStart(2, '0'), day = today.getFullYear() + '-' + pad(today.getMonth() + 1) + '-' + pad(today.getDate());
62
- const krs = require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics');
63
+ const krs = require(repoScript('records/index.js')).list(recordsDirFor(ctx, ws), 'kr-metrics').filter((k) => k.retired !== true); // an undone ✓ on a drafted metric retires its record
63
64
  outcomes = krs.map((k) => strategy.outcomeOf(k, day));
64
65
  goalMeta = Object.fromEntries(krs.map((k) => [k.rid, k])); // premium-agreed-design: the fields New goal keeps (type, direction, period, owner, …)
65
66
  } catch (e) { return fail('the KR metric records could not be read: ' + ((e && e.message) || e)); }
@@ -92,10 +93,18 @@ module.exports = {
92
93
  const counts = new Map();
93
94
  const goalsIn = (w) => { if (!counts.has(w)) { let n = null; try { n = w === ws ? outcomes.length : require(repoScript('records/index.js')).list(recordsDirFor(ctx, w), 'kr-metrics').length; } catch { n = null; } counts.set(w, n); } return counts.get(w) === null ? {} : { goals: counts.get(w) }; };
94
95
  const model = Insights.build({
95
- now: Date.now(), board: pick ? { ws: pick.ws, id: pick.id, name: pick.name } : { ws, id: null, name: 'Insights' }, boards: all.map((x) => Object.assign({ ws: x.ws, id: x.id, name: x.name }, goalsIn(x.ws))),
96
+ now: Date.now(), board: pick ? { ws: pick.ws, id: pick.id, name: pick.name } : { ws, id: null, name: 'Intelligence' }, boards: all.map((x) => Object.assign({ ws: x.ws, id: x.id, name: x.name }, goalsIn(x.ws))),
96
97
  outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing, saved, mine,
97
98
  setups: setupsOk ? su.body : null, pinned, leads, archived, initiatives, goalMeta, ins, budgets,
98
99
  });
100
+ // batch 16 item 1: each ✦ strip finding about a goal that is behind carries one drafted move (lib/insight-moves.js), done ones marked
101
+ if (pick) {
102
+ try {
103
+ const root = require('path').resolve(ctx.getWs(pick.ws).root), A = require('./initiative-rows.js').anchorsOf(root);
104
+ const dir = ctx.stateDirFor ? ctx.stateDirFor(ctx.getWs(pick.ws)) : null;
105
+ require('./insight-moves.js').draftAll(model, { initiatives: initiatives || [], today: model.today, anchorOk: (t) => A.resolve(t).status === 'resolved', ledger: dir ? require('./insight-moves.js').read(dir) : new Map() });
106
+ } catch { /* no move is drafted: the strip says the finding without a ✓ */ }
107
+ }
99
108
  ctx.json(res, { ok: true, state: 'ready', model, as_of: Date.now() });
100
109
  return true;
101
110
  } catch (e) { return fail((e && e.message) || e); }
@@ -9,7 +9,9 @@
9
9
  * POST /api/insights-records/chart { ws, board, dash, goal, form, range, compare, target, forecast, note, add } → { ok }
10
10
  * one chart line (lib/insights-records.js); with add, the goal is first added to the dashboard
11
11
  * POST /api/insights-records/describe { ws, text } → { ok, name, question, goals, range, said } reads the goals; writes nothing
12
- * POST /api/insights-records/verdict { ws, board, ini, verdict, learned, goal } → { ok, verdict } one verdict line; the Board is not changed
12
+ * POST /api/insights-records/verdict { ws, board, ini, verdict, learned, goal, drafted } → { ok, verdict } one verdict line; the Board is not changed.
13
+ * Intelligence's "Did it work?" sends Claude's drafted line as `learned` with drafted: true when the PM presses ✓ Keep
14
+ * POST /api/insights-records/verdict-undo { ws, board, ini } → { ok } takes the initiative's verdict back (Undo after ✓ Keep): one verdict-undo line
13
15
  * POST /api/insights-records/target { ws, key: late | scope, target } → { ok, targets }
14
16
  * POST /api/insights-records/tile { ws, key, dir: at least | at most | none, from, chip } → { ok, tiles } how a Delivery trends target is
15
17
  * read (premium-uncovered-features, IsTarget): its direction, the day it counts from and whether the Board chip shows it
@@ -52,7 +54,7 @@ async function handle(req, res, url, ctx) {
52
54
  res.end(IG.exportCsv(m.goals || []));
53
55
  return true;
54
56
  }
55
- if (!['goal', 'steps', 'dashboard', 'chart', 'describe', 'verdict', 'target', 'tile'].includes(what)) return send(bad(404, 'no such insights-records route'));
57
+ if (!['goal', 'steps', 'dashboard', 'chart', 'describe', 'verdict', 'verdict-undo', 'target', 'tile'].includes(what)) return send(bad(404, 'no such insights-records route'));
56
58
  if (req.method !== 'POST') return send(bad(405, 'POST only'));
57
59
  const read = await ctx.readJson(req);
58
60
  if (!read.ok) return send(bad(400, 'the body is not JSON'));
@@ -72,7 +74,7 @@ async function handle(req, res, url, ctx) {
72
74
  if (what === 'goal') {
73
75
  const f = IG.goalFields(body, { today: today() });
74
76
  if (!f.ok) return send(bad(400, f.error));
75
- const r = records().add(recordsDirFor(ctx, w.id), 'kr-metrics', f.fields, UI(), 'New goal from Insights');
77
+ const r = records().add(recordsDirFor(ctx, w.id), 'kr-metrics', f.fields, UI(), 'New goal from Intelligence');
76
78
  return send(r.ok ? { status: 200, body: { ok: true, rid: r.rid, fields: f.fields } } : bad(400, r.reasons.join('; ')));
77
79
  }
78
80
  if (what === 'steps') {
@@ -81,9 +83,9 @@ async function handle(req, res, url, ctx) {
81
83
  if (!cur || !Array.isArray(cur.steps) || !cur.steps.length) return send(bad(404, 'That goal has no steps.'));
82
84
  if (!Array.isArray(body.done) || body.done.length !== cur.steps.length) return send(bad(400, 'Say which of its steps are done.'));
83
85
  const steps = cur.steps.map((s, i) => ({ text: s.text, done: body.done[i] === true })), n = steps.filter((s) => s.done).length, root = recordsDirFor(ctx, w.id);
84
- const e = records().edit(root, 'kr-metrics', cur.rid, { steps }, UI(), 'Steps ticked on Insights');
86
+ const e = records().edit(root, 'kr-metrics', cur.rid, { steps }, UI(), 'Steps ticked on Intelligence');
85
87
  if (!e.ok) return send(bad(400, e.reasons.join('; ')));
86
- const r = records().addReading(root, cur.rid, { at: today(), value: n }, UI(), 'Steps done, from Insights');
88
+ const r = records().addReading(root, cur.rid, { at: today(), value: n }, UI(), 'Steps done, from Intelligence');
87
89
  return send(r.ok ? { status: 200, body: { ok: true, done: n } } : bad(400, r.reasons.join('; ')));
88
90
  }
89
91
  if (what === 'target' || what === 'tile') {
@@ -99,6 +101,12 @@ async function handle(req, res, url, ctx) {
99
101
  const r = IR.append(w.root, 'verdict', body, g.actor, { now });
100
102
  return send(r.ok ? { status: 200, body: { ok: true, verdict: r.line } } : bad(r.status, r.error));
101
103
  }
104
+ if (what === 'verdict-undo') {
105
+ const had = ((IR.read(w.root).verdicts || {})[text(body.board)] || {})[text(body.ini)];
106
+ if (!had) return send(bad(404, 'That initiative has no verdict to take back.'));
107
+ const r = IR.append(w.root, 'verdict-undo', body, g.actor, { now });
108
+ return send(r.ok ? { status: 200, body: { ok: true } } : bad(r.status, r.error));
109
+ }
102
110
  const ks = dashRoutes.krIds(ctx, w.id);
103
111
  if (!ks) return send(bad(503, 'The KR metric records could not be read, so the charts cannot be checked.'));
104
112
  if (what === 'chart') {
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+ /* routes-metric-drafts.js — the metrics Claude drafts without being asked (batch 15 item 1; contract metric-drafts-contract.md). The fold is
3
+ * lib/metric-drafts.js; the runs are lib/metric-draft-runs.js (ctx.metricDraftRuns). Only the PM's ✓ keep writes: one kr-metrics record
4
+ * (planning/records/kr-metrics.jsonl through scripts/records, the workspace's folder from lib/records-dir.js).
5
+ *
6
+ * GET /api/metric-drafts?ws=&scope=&id= → { ok, scope, id, title, when, run: { state: idle|running|ready|failed|off, step, reads },
7
+ * rows, head, sub, src } rows [] and run.state idle when nothing is drafted
8
+ * POST /api/metric-drafts/keep { ws, scope, id, row } → { ok, rid } ✓ one row: the record and, when now is known, one reading
9
+ * POST /api/metric-drafts/keep-all { ws, scope, id } → { ok, kept: n, failed } ✓ every open row
10
+ * POST /api/metric-drafts/drop { ws, scope, id, row } → { ok } ✕
11
+ * POST /api/metric-drafts/edit { ws, scope, id, row, name?, target?, source? } → { ok, row } the inline edit of an open row (batch 16 item 1)
12
+ * POST /api/metric-drafts/undo { ws, scope, id, row } → { ok } kept → open (its record edited { retired: true }); dropped → open
13
+ * POST /api/metric-drafts/start { ws, scope, id } → { ok, run } Draft again
14
+ * POST /api/metric-drafts/stop { ws, scope, id } → { ok } ■ Stop: the run ends; what it filed stays a draft
15
+ *
16
+ * WHICH LEDGER. A product's and an initiative's drafts are in the state folder of `ws`. A program's are in its charter's workspace (its home,
17
+ * lib/routes-programs.js all), whatever `ws` says, so a program reads the same from every product.
18
+ *
19
+ * WHO WRITES. As routes-premium-dashboards.js: a POST that carries an agent session header is refused (403), and pm-guard requirePagePress
20
+ * checks the launch nonce and the page's origin. With no state folder the read answers nothing and every write answers 409.
21
+ *
22
+ * wsFor(ctx, ws, scope, id) → the workspace whose ledger holds the scope, or null */
23
+ const guard = require('./pm-guard.js');
24
+ const MD = require('./metric-drafts.js');
25
+ const Runs = require('./metric-draft-runs.js');
26
+ const { repoScript } = require('./repo-script.js');
27
+ const { recordsDirFor } = require('./records-dir.js');
28
+
29
+ const text = (v) => (typeof v === 'string' ? v : '');
30
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
31
+ const records = () => require(repoScript('records/index.js'));
32
+ const UI = () => require(repoScript('trust/ledger.js')).actorFrom({ ui: true });
33
+ const NO_STATE = 'This repository has no PMOS state folder (pmos/state, state or .pmos). Nothing is saved until the folder exists.';
34
+ const todayIso = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
35
+ const dirOf = (ctx, w) => { try { return ctx.stateDirFor ? ctx.stateDirFor(w) : null; } catch { return null; } };
36
+
37
+ function wsFor(ctx, ws, scope, id) {
38
+ let w = null;
39
+ try { w = ctx.getWs(ws || null); } catch { w = null; }
40
+ if (ws && w && w.id !== ws) w = null;
41
+ if (scope === 'program') {
42
+ try {
43
+ const p = require('./routes-programs.js').all(ctx).find((x) => x.id === id);
44
+ const list = (ctx.workspaceList ? ctx.workspaceList() : []) || [];
45
+ const home = p && list.find((x) => x.id === p.home);
46
+ if (home) return home;
47
+ } catch { /* the programs could not be read: the ledger of `ws` */ }
48
+ }
49
+ return w;
50
+ }
51
+ const offNow = (ctx) => Runs.off(ctx.env || process.env);
52
+ const viewFor = (ctx, w, scope, id) => { const dir = dirOf(ctx, w); return MD.viewOf(dir ? MD.read(dir) : null, scope, id, { off: offNow(ctx) }); };
53
+
54
+ async function handle(req, res, url, ctx) {
55
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
56
+ const what = url.pathname.replace(/^\/api\/metric-drafts\/?/, '');
57
+ if (what === '') {
58
+ if (req.method !== 'GET') return send(bad(405, 'GET only'));
59
+ const scope = url.searchParams.get('scope') || '', id = url.searchParams.get('id') || '', ws = url.searchParams.get('ws') || '';
60
+ if (!MD.SCOPES.includes(scope)) return send(bad(400, 'scope is product, program or initiative'));
61
+ const w = wsFor(ctx, ws, scope, id || ws);
62
+ if (!w) return send(bad(404, 'no such workspace'));
63
+ const sid = scope === 'product' ? (id || w.id) : id;
64
+ if (!sid) return send(bad(400, 'id names the program or the initiative'));
65
+ return send({ status: 200, body: { ok: true, ...viewFor(ctx, w, scope, sid) } });
66
+ }
67
+ if (!['keep', 'keep-all', 'drop', 'undo', 'start', 'stop', 'edit'].includes(what)) return send(bad(404, 'no such metric-drafts route'));
68
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
69
+ if (req.headers && req.headers['x-pmos-session']) return send(bad(403, 'Only the PM keeps, drops or starts a draft, from the page. A run files drafts with pmos metrics draft.'));
70
+ const read = await ctx.readJson(req);
71
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
72
+ const body = read.body || {};
73
+ const g = guard.requirePagePress(req, body);
74
+ if (!g.ok) return send(bad(g.status, g.error));
75
+ const scope = text(body.scope);
76
+ if (!MD.SCOPES.includes(scope)) return send(bad(400, 'scope is product, program or initiative'));
77
+ const w = wsFor(ctx, text(body.ws), scope, text(body.id));
78
+ if (!w) return send(bad(404, 'no such workspace'));
79
+ const id = scope === 'product' ? (text(body.id) || w.id) : text(body.id);
80
+ if (!id) return send(bad(400, 'id names the program or the initiative'));
81
+ if (scope === 'product' && id !== w.id) return send(bad(400, 'A product\'s id is its workspace id.'));
82
+ const dir = dirOf(ctx, w);
83
+ if (!dir) return send(bad(409, NO_STATE));
84
+ const at = () => new Date().toISOString();
85
+ const S = () => MD.read(dir).scopes.get(MD.keyOf(scope, id));
86
+
87
+ if (what === 'start') {
88
+ if (!ctx.metricDraftRuns) return send(bad(503, 'Claude\'s runs are off on this server.'));
89
+ const r = ctx.metricDraftRuns.start({ ws: w.id, scope, id, why: 'press' });
90
+ if (!r || !r.ok) return send(bad(409, (r && r.error) || 'Claude could not start drafting.'));
91
+ return send({ status: 200, body: { ok: true, run: r.run } });
92
+ }
93
+ if (what === 'stop') {
94
+ const s = S();
95
+ if (!s || !s.run || s.run.ended) return send(bad(409, 'Claude is not drafting now.'));
96
+ try { if (ctx.metricDraftRuns) ctx.metricDraftRuns.stop(s.run.run); } catch { /* the end line below says it stopped */ }
97
+ MD.append(dir, g.actor, { kind: 'end', scope, id, run: s.run.run, ok: true, stopped: true }, at());
98
+ return send({ status: 200, body: { ok: true } });
99
+ }
100
+ const s = S();
101
+ const root = recordsDirFor(ctx, w.id), today = todayIso();
102
+ const keepOne = (row) => {
103
+ const k = MD.keepFields(scope, id, row, { today });
104
+ if (k.error) return { error: k.error };
105
+ let r;
106
+ try { r = records().add(root, 'kr-metrics', k.fields, UI(), 'Kept a metric Claude drafted'); } catch (e) { return { error: 'The record could not be written: ' + String((e && e.message) || e).slice(0, 160) }; }
107
+ if (!r.ok) return { error: r.reasons.join('; ') };
108
+ if (k.reading) { try { records().addReading(root, r.rid, k.reading, UI(), 'The reading Claude drafted it from'); } catch { /* the record stands; the next reading fills it */ } }
109
+ MD.append(dir, g.actor, { kind: 'keep', scope, id, row: row.id, rid: r.rid }, at());
110
+ return { rid: r.rid };
111
+ };
112
+ if (what === 'keep-all') {
113
+ const open = s ? [...s.rows.values()].filter((r) => r.state === 'open') : [];
114
+ if (!open.length) return send(bad(409, 'There is nothing open to keep.'));
115
+ let kept = 0; const failed = [];
116
+ for (const row of open) { const r = keepOne(row); if (r.rid) kept++; else failed.push({ row: row.id, error: r.error }); }
117
+ return send(kept ? { status: 200, body: { ok: true, kept, failed } } : bad(400, failed[0].error));
118
+ }
119
+ const row = s && s.rows.get(text(body.row));
120
+ if (!row) return send(bad(404, 'There is no such draft.'));
121
+ if (what === 'keep') {
122
+ if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it already.' : 'You dropped it. Undo first.'));
123
+ const r = keepOne(row);
124
+ return send(r.rid ? { status: 200, body: { ok: true, rid: r.rid } } : bad(400, r.error));
125
+ }
126
+ if (what === 'edit') {
127
+ if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it. Undo it first, then edit.' : 'You dropped it. Undo first.'));
128
+ const pick = {}; for (const k of ['name', 'target', 'source']) if (body[k] !== undefined) pick[k] = body[k];
129
+ const e = MD.editOf(row, pick);
130
+ if (e.error) return send(bad(400, e.error));
131
+ if (Object.keys(e.set).length) MD.append(dir, g.actor, { kind: 'edit', scope, id, row: row.id, set: e.set }, at());
132
+ return send({ status: 200, body: { ok: true, row: { ...row, ...e.set }, changed: Object.keys(e.set).length > 0 } });
133
+ }
134
+ if (what === 'drop') {
135
+ if (row.state !== 'open') return send(bad(409, row.state === 'kept' ? 'You kept it. Undo it first.' : 'You dropped it already.'));
136
+ MD.append(dir, g.actor, { kind: 'drop', scope, id, row: row.id }, at());
137
+ return send({ status: 200, body: { ok: true } });
138
+ }
139
+ // undo: a kept row's record is retired (readers skip it), a dropped row comes back
140
+ if (row.state === 'open') return send(bad(409, 'There is nothing to undo.'));
141
+ if (row.state === 'kept' && row.rid) {
142
+ let e;
143
+ try { e = records().edit(root, 'kr-metrics', row.rid, { retired: true }, UI(), 'Undo of a kept draft'); } catch (x) { e = { ok: false, reasons: [String((x && x.message) || x).slice(0, 160)] }; }
144
+ if (!e.ok && !(e.reasons || []).some((m) => /no such record/.test(m))) return send(bad(400, 'The record could not be retired: ' + (e.reasons || []).join('; ')));
145
+ }
146
+ MD.append(dir, g.actor, { kind: 'undo', scope, id, row: row.id, ...(row.rid ? { rid: row.rid } : {}) }, at());
147
+ return send({ status: 200, body: { ok: true } });
148
+ }
149
+
150
+ module.exports = { prefixes: ['/api/metric-drafts'], handle, wsFor };