create-pmos 0.428.0 → 0.429.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 (106) hide show
  1. package/package.json +13 -13
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/briefing-premium-board-test.js +2 -2
  7. package/workspace/briefing-premium-insights-test.js +81 -60
  8. package/workspace/briefing-premium-metrics-test.js +5 -3
  9. package/workspace/briefing-premium-sources-test.js +5 -5
  10. package/workspace/briefing-premium-test.js +5 -4
  11. package/workspace/changelog.json +12 -0
  12. package/workspace/ev-everywhere-test.js +2 -2
  13. package/workspace/guide/home.md +2 -0
  14. package/workspace/guide/index.md +1 -0
  15. package/workspace/guide/metric-drafts.md +48 -0
  16. package/workspace/intel-report-ui-test.js +189 -0
  17. package/workspace/lib/board-metrics-premium.js +1 -1
  18. package/workspace/lib/headless.js +15 -2
  19. package/workspace/lib/insights-premium.js +5 -1
  20. package/workspace/lib/insights-records.js +14 -5
  21. package/workspace/lib/intel-report.js +419 -0
  22. package/workspace/lib/metric-draft-runs.js +193 -0
  23. package/workspace/lib/metric-drafts.js +231 -0
  24. package/workspace/lib/metrics-cli.js +104 -0
  25. package/workspace/lib/pmos-verbs.js +3 -0
  26. package/workspace/lib/report-setups.js +29 -13
  27. package/workspace/lib/route-modules.js +1 -0
  28. package/workspace/lib/routes-insights-premium.js +2 -2
  29. package/workspace/lib/routes-insights-records.js +13 -5
  30. package/workspace/lib/routes-metric-drafts.js +141 -0
  31. package/workspace/lib/routes-phone-day.js +13 -2
  32. package/workspace/lib/routes-report-setups.js +92 -3
  33. package/workspace/lib/routes-viewer.js +5 -2
  34. package/workspace/metric-drafts-ui-test.js +209 -0
  35. package/workspace/package-lock.json +2 -2
  36. package/workspace/package.json +1 -1
  37. package/workspace/premium-phone-card-test.js +8 -5
  38. package/workspace/public/pm/bd-acts.js +3 -3
  39. package/workspace/public/pm/bd-pin-card.css +4 -4
  40. package/workspace/public/pm/bd-prog-panel.js +9 -4
  41. package/workspace/public/pm/cozy-aud.css +1 -1
  42. package/workspace/public/pm/cozy-board.css +256 -256
  43. package/workspace/public/pm/cozy-ev.css +45 -45
  44. package/workspace/public/pm/cozy-evmodel.js +1 -1
  45. package/workspace/public/pm/cozy-home-rows.css +23 -23
  46. package/workspace/public/pm/cozy-home.css +207 -207
  47. package/workspace/public/pm/cozy-insights.css +207 -108
  48. package/workspace/public/pm/cozy-live-pill.css +5 -5
  49. package/workspace/public/pm/cozy-mtg-present.css +23 -23
  50. package/workspace/public/pm/cozy-nav.js +1 -1
  51. package/workspace/public/pm/cozy-news.js +2 -2
  52. package/workspace/public/pm/cozy-panel.css +29 -29
  53. package/workspace/public/pm/cozy-pick.css +5 -5
  54. package/workspace/public/pm/cozy-rec-now.css +20 -20
  55. package/workspace/public/pm/cozy-rec-present.css +11 -11
  56. package/workspace/public/pm/cozy-rec-tab.css +13 -13
  57. package/workspace/public/pm/cozy-settings.js +1 -1
  58. package/workspace/public/pm/cozy-steps.css +9 -9
  59. package/workspace/public/pm/cozy-today.css +107 -71
  60. package/workspace/public/pm/cozy-viewer.css +7 -7
  61. package/workspace/public/pm/cozy-viewer.js +1 -1
  62. package/workspace/public/pm/cozy-vw-mtg.css +81 -81
  63. package/workspace/public/pm/cozy-vw-rp.css +53 -53
  64. package/workspace/public/pm/cozy-vw-shell.css +23 -23
  65. package/workspace/public/pm/cozy-vw.css +117 -117
  66. package/workspace/public/pm/cozy-xv.css +11 -11
  67. package/workspace/public/pm/cozy.css +18 -15
  68. package/workspace/public/pm/hi-pop.css +19 -19
  69. package/workspace/public/pm/home-app.js +28 -2
  70. package/workspace/public/pm/home-day.js +131 -26
  71. package/workspace/public/pm/home-ini.css +32 -32
  72. package/workspace/public/pm/home-line.css +7 -7
  73. package/workspace/public/pm/home-list.js +12 -1
  74. package/workspace/public/pm/home-phone-card.js +18 -15
  75. package/workspace/public/pm/ini-view.css +102 -102
  76. package/workspace/public/pm/ini-view.js +9 -3
  77. package/workspace/public/pm/loose-props.css +13 -13
  78. package/workspace/public/pm/metric-drafts.css +82 -0
  79. package/workspace/public/pm/metric-drafts.js +165 -0
  80. package/workspace/public/pm/ms-suggest.css +8 -8
  81. package/workspace/public/pm/ov-view.css +12 -12
  82. package/workspace/public/pm/premium-chart-tab.js +6 -6
  83. package/workspace/public/pm/premium-insights.js +298 -107
  84. package/workspace/public/pm/premium-report-intel.css +56 -0
  85. package/workspace/public/pm/premium-report-intel.js +232 -0
  86. package/workspace/public/pm/premium-shell.js +2 -2
  87. package/workspace/public/pm/premium-vw-file.js +2 -2
  88. package/workspace/public/pm/premium.css +127 -128
  89. package/workspace/public/pm/prog-order.css +6 -6
  90. package/workspace/public/pm/program-charter.css +23 -23
  91. package/workspace/public/pm/rp-parts.js +2 -2
  92. package/workspace/public/pm/sort-order.css +1 -1
  93. package/workspace/public/pm/split-merge.css +15 -15
  94. package/workspace/public/pm/task-card.css +21 -21
  95. package/workspace/public/pm/tk-tasks.css +37 -37
  96. package/workspace/public/pm/tk-view.css +6 -6
  97. package/workspace/public/pm/wf-page.css +28 -28
  98. package/workspace/public/premium-intelligence.html +82 -0
  99. package/workspace/server.js +38 -3
  100. package/workspace/skills/metric-draft.skill +47 -0
  101. package/workspace/test-lists/intel-report-ui.json +5 -0
  102. package/workspace/test-lists/intel-report.json +9 -0
  103. package/workspace/test-lists/metric-drafts-ui.json +5 -0
  104. package/workspace/test-lists/metric-drafts.json +9 -0
  105. package/workspace/test-run.js +3 -0
  106. package/workspace/public/premium-insights.html +0 -81
@@ -0,0 +1,231 @@
1
+ 'use strict';
2
+ /* metric-drafts.js — the metrics Claude drafts without being asked (batch 15 item 1, the Intelligence build; contract metric-drafts-contract.md,
3
+ * canvas Iq8Suggest and Iq9Draft). THE ONE WRITER and THE ONE FOLD of <state>/metric-drafts.jsonl. lib/routes-metric-drafts.js does the I/O;
4
+ * lib/metric-draft-runs.js starts the runs; lib/metrics-cli.js is what a run files with. Pure, with no clock of its own: every time comes in.
5
+ *
6
+ * THREE SCOPES, ONE LEDGER. A scope is { scope, id }:
7
+ * product id = the workspace id. No North Star: a North Star (1), Inputs (≤3) and Guardrails (≤2). At a quarter's start: Key results (≤5).
8
+ * program id = the program id. The charter has no goal: Program goal (1, with checkpoints at its milestones), Rolls up from (one per
9
+ * product, ≤8) and Guardrail (≤1).
10
+ * initiative id = the initiative id. It has a PRD and no success measure: Proves it worked (1, "4 weeks after release"), Early signal (≤1)
11
+ * and Guardrail (≤1).
12
+ *
13
+ * THE LEDGER. One line per event, { at, by, kind, scope, id, ... }:
14
+ * epoch { known: [initiative id] } the first scan: the initiatives that had a PRD then are history, never drafted unasked
15
+ * start { run, why, title, when } a run began; why ∈ north-star · quarter · goal · success · press
16
+ * step { run, step } the strip: 0 read · 1 shape · 2 measure · 3 target · 4 ready
17
+ * read { run, t, f, state } one source read; the last line for a title in a run wins (state done · now · wait)
18
+ * row { run, row } one drafted row (clean() shape); the last line for a row id wins
19
+ * end { run, ok, stopped?, error?, head?, sub?, src? } the run ended; `pmos metrics draft end` says the head, sub and sources
20
+ * keep { row, rid } ✓: the kr-metrics record it wrote
21
+ * drop { row } ✕
22
+ * undo { row, rid? } a kept row back to open (its record retired), or a dropped one back to open
23
+ * A new run's start clears every row of the scope that was not kept: it drafts again. A kept row is the PM's and stays.
24
+ *
25
+ * ledgerFile(dir) · readLines(file) · read(dir) → fold · append(dir, actor, line, at)
26
+ * fold(lines) PURE → { scopes: Map key → S, epoch } S: { scope, id, title, when, run, runs, rows: Map, head, sub, src }
27
+ * viewOf(F, scope, id, o) PURE → the GET body (no ok): { scope, id, title, when, run: { state, step, reads }, rows, head, sub, src }
28
+ * clean(scope, input) → { row } | { error } what `pmos metrics draft row` checks
29
+ * keepFields(scope, id, row, o) → { fields, reading } | { error } the kr-metrics record a ✓ writes
30
+ * rowId(scope, id, group, name) · keyOf(scope, id) · countIn(S, run, group)
31
+ * SCOPES · GROUPS · LIMITS · ROLES · TYPES · STEPS · WHEN
32
+ */
33
+ const fs = require('fs');
34
+ const path = require('path');
35
+ const crypto = require('crypto');
36
+
37
+ const LEDGER = 'metric-drafts.jsonl';
38
+ const KINDS = new Set(['epoch', 'start', 'step', 'read', 'row', 'end', 'keep', 'drop', 'undo']);
39
+ const SCOPES = ['product', 'program', 'initiative'];
40
+ const GROUPS = { product: ['North Star', 'Inputs', 'Guardrails', 'Key results'], program: ['Program goal', 'Rolls up from', 'Guardrail'], initiative: ['Proves it worked', 'Early signal', 'Guardrail'] };
41
+ const LIMITS = { 'North Star': 1, Inputs: 3, Guardrails: 2, 'Key results': 5, 'Program goal': 1, 'Rolls up from': 8, Guardrail: 1, 'Proves it worked': 1, 'Early signal': 1 };
42
+ const ROLES = {
43
+ product: { 'North Star': 'north-star', Inputs: 'input', Guardrails: 'guardrail', 'Key results': 'kr' },
44
+ program: { 'Program goal': 'program-goal', 'Rolls up from': 'rollup', Guardrail: 'guardrail' },
45
+ initiative: { 'Proves it worked': 'success', 'Early signal': 'signal', Guardrail: 'guardrail' },
46
+ };
47
+ const TYPES = ['Count', 'Percentage', 'Amount', 'Duration', 'Done or not', 'Stay within'];
48
+ const UNIT_OF = { Percentage: '%', Duration: 'days', Amount: '$', Count: '' };
49
+ const STEPS = ['read', 'shape', 'measure', 'target', 'ready'];
50
+ const READ_STATES = ['done', 'now', 'wait'];
51
+ const WHYS = ['north-star', 'quarter', 'goal', 'success', 'press'];
52
+ /** The "when" line of each trigger, as the page says it. */
53
+ const WHEN = {
54
+ 'north-star': 'A product was connected with no North Star',
55
+ quarter: 'A new quarter started',
56
+ goal: 'The program charter has no goal',
57
+ success: 'The initiative has a PRD and no success measure',
58
+ press: 'You asked me to draft again',
59
+ };
60
+ const WINDOW = '4 weeks after release';
61
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
62
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
63
+ const str = (v) => (typeof v === 'string' ? v : '');
64
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
65
+ const fin = (v) => typeof v === 'number' && Number.isFinite(v);
66
+ const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 10);
67
+ const keyOf = (scope, id) => scope + ':' + id;
68
+ const rowId = (scope, id, group, name) => 'md-' + hash([scope, id, group, String(name || '').toLowerCase()].join('|'));
69
+
70
+ /* ── the ledger ── */
71
+ function ledgerFile(dir) { return dir ? path.join(dir, LEDGER) : null; }
72
+ function readLines(file) {
73
+ if (!file) return [];
74
+ let text = '';
75
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
76
+ const out = [];
77
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && KINDS.has(l.kind)) out.push(l); } catch { /* a torn line is skipped */ } }
78
+ return out;
79
+ }
80
+ function read(dir) { return fold(readLines(ledgerFile(dir))); }
81
+ /** One line. `at` is the caller's clock (an ISO string); the writer has none of its own. */
82
+ function append(dir, actor, ev, at) {
83
+ const line = { at: at || null, by: (actor && actor.by) || null, ...ev };
84
+ fs.mkdirSync(dir, { recursive: true });
85
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify(line) + '\n');
86
+ return line;
87
+ }
88
+
89
+ /* ── what a run may file (`pmos metrics draft row`): every number with its source, a missing event with its ticket ── */
90
+ const LIM = { name: 80, txt: 40, why: 160, source: 40, key: 24, text: 400, unit: 12, pillar: 80, label: 40 };
91
+ const numOrNull = (v) => (v === null || v === undefined || v === '' ? { v: null } : fin(v) ? { v } : { error: true });
92
+ /** → { row } | { error }. input: { group, name, type, now, nowTxt, target, targetTxt, by, why, source, ticket, checkpoints, direction, unit, pillar } */
93
+ function clean(scope, input) {
94
+ if (!SCOPES.includes(scope)) return { error: 'scope is one of ' + SCOPES.join(', ') };
95
+ if (!isObj(input)) return { error: 'a row is a JSON object' };
96
+ const group = str(input.group);
97
+ if (!GROUPS[scope].includes(group)) return { error: `group of a ${scope} is one of: ${GROUPS[scope].join(', ')}` };
98
+ const name = one(input.name, LIM.name);
99
+ if (!name) return { error: 'name is the metric, in a few words' };
100
+ const type = str(input.type);
101
+ if (!TYPES.includes(type)) return { error: 'type is one of: ' + TYPES.join(', ') };
102
+ const why = one(input.why, LIM.why);
103
+ if (!why) return { error: 'why is one line: the reason for this metric and its target' };
104
+ const now = numOrNull(input.now), target = numOrNull(input.target);
105
+ if (now.error) return { error: 'now is a number from the readings, or null when no event counts it' };
106
+ if (target.error) return { error: 'target is a number, or null for Done or not' };
107
+ const source = one(input.source, LIM.source);
108
+ let ticket = null;
109
+ if (input.ticket != null) {
110
+ if (!isObj(input.ticket) || !one(input.ticket.key, LIM.key) || !one(input.ticket.text, LIM.text)) return { error: 'ticket is { key, text }: the drafted ticket for the missing event' };
111
+ ticket = { key: one(input.ticket.key, LIM.key), text: one(input.ticket.text, LIM.text) };
112
+ }
113
+ // every number comes from real readings: a "now" names where it was read; no event to count it is said with the drafted ticket
114
+ if (now.v == null && !ticket && type !== 'Done or not') return { error: 'now is null only with a ticket: { key, text } drafts the event that would count it' };
115
+ if (now.v != null && !source) return { error: 'a measured now names its source (Amplitude, Jira, …)' };
116
+ if (target.v == null && type !== 'Done or not') return { error: 'target is a number: from the baseline and past launches' };
117
+ const by = input.by == null || input.by === '' ? null : String(input.by);
118
+ if (by != null && !DAY_RE.test(by)) return { error: 'by is YYYY-MM-DD' };
119
+ if (by == null && type !== 'Stay within') return { error: 'by is the date the target is due (YYYY-MM-DD); only a Stay within guardrail may have none' };
120
+ if (now.v != null && target.v != null && now.v === target.v) return { error: type === 'Stay within' ? 'the limit equals the reading now: give the limit the evidence says (the worst week of the last 8, a service level)' : 'the target equals now: a target moves the metric' };
121
+ const direction = ['up', 'down'].includes(input.direction) ? input.direction : null;
122
+ const checkpoints = [];
123
+ if (input.checkpoints != null) {
124
+ if (!Array.isArray(input.checkpoints) || input.checkpoints.length > 6) return { error: 'checkpoints is a list of at most 6 { by, target, label }' };
125
+ for (const c of input.checkpoints) {
126
+ if (!isObj(c) || !DAY_RE.test(String(c.by || '')) || !fin(c.target)) return { error: 'each checkpoint is { by: YYYY-MM-DD, target: number, label }' };
127
+ checkpoints.push({ by: String(c.by), target: c.target, label: one(c.label, LIM.label) });
128
+ }
129
+ }
130
+ const row = { group, name, type, now: now.v, nowTxt: one(input.nowTxt, LIM.txt) || (now.v == null ? '—' : String(now.v)), target: target.v,
131
+ targetTxt: one(input.targetTxt, LIM.txt) || (target.v == null ? 'Done' : String(target.v)), by, why, source, ticket };
132
+ if (checkpoints.length) row.checkpoints = checkpoints;
133
+ if (direction) row.direction = direction;
134
+ const unit = one(input.unit, LIM.unit); if (unit) row.unit = unit;
135
+ const pillar = one(input.pillar, LIM.pillar); if (pillar && group === 'Key results') row.pillar = pillar;
136
+ return { row };
137
+ }
138
+
139
+ /* ── the fold ── */
140
+ const blank = (scope, id) => ({ scope, id, title: '', when: '', run: null, runs: [], rows: new Map(), head: '', sub: '', src: '' });
141
+ function fold(lines) {
142
+ const scopes = new Map();
143
+ let epoch = null;
144
+ const S = (l) => { const k = keyOf(l.scope, l.id); if (!scopes.has(k)) scopes.set(k, blank(l.scope, l.id)); return scopes.get(k); };
145
+ for (const l of lines || []) {
146
+ if (!isObj(l) || !KINDS.has(l.kind)) continue;
147
+ if (l.kind === 'epoch') { if (!epoch) epoch = { at: str(l.at), known: Array.isArray(l.known) ? l.known.map(String) : [] }; continue; }
148
+ if (!SCOPES.includes(l.scope) || !str(l.id)) continue;
149
+ const s = S(l), cur = s.run && s.run.run === l.run ? s.run : null;
150
+ if (l.kind === 'start' && str(l.run)) {
151
+ s.run = { run: l.run, why: WHYS.includes(l.why) ? l.why : 'press', at: str(l.at), step: 0, reads: [], ended: false, ok: null, stopped: false, error: '' };
152
+ s.runs.push(s.run);
153
+ s.title = one(l.title, 140) || s.title || l.id; s.when = one(l.when, 140) || WHEN[s.run.why] || '';
154
+ s.head = ''; s.sub = ''; s.src = '';
155
+ for (const [rid, r] of s.rows) if (r.state !== 'kept') s.rows.delete(rid);
156
+ } else if (l.kind === 'step' && cur && !cur.ended) { const n = Number(l.step); if (Number.isInteger(n) && n >= 0 && n <= 4) cur.step = Math.max(cur.step, n); }
157
+ else if (l.kind === 'read' && cur && !cur.ended && str(l.t)) {
158
+ const r = { t: one(l.t, 60), f: one(l.f, 200), state: READ_STATES.includes(l.state) ? l.state : 'done' };
159
+ const i = cur.reads.findIndex((x) => x.t === r.t);
160
+ if (i >= 0) cur.reads[i] = r; else cur.reads.push(r);
161
+ } else if (l.kind === 'row' && cur && !cur.ended && isObj(l.row) && str(l.row.id)) {
162
+ const was = s.rows.get(l.row.id);
163
+ if (was && was.state === 'kept') continue; // the PM kept it: a run never changes what the PM kept
164
+ s.rows.set(l.row.id, { ...l.row, state: 'open', run: l.run, at: str(l.at) });
165
+ } else if (l.kind === 'end' && cur && !cur.ended) {
166
+ Object.assign(cur, { ended: true, ok: !!l.ok, stopped: !!l.stopped, error: one(l.error, 200), endAt: str(l.at) });
167
+ if (cur.ok && !cur.stopped) cur.step = 4;
168
+ if (str(l.head)) s.head = one(l.head, 200);
169
+ if (str(l.sub)) s.sub = one(l.sub, 300);
170
+ if (str(l.src)) s.src = one(l.src, 300);
171
+ } else if (l.kind === 'keep' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') Object.assign(r, { state: 'kept', rid: str(l.rid) || null }); }
172
+ else if (l.kind === 'drop' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state === 'open') r.state = 'dropped'; }
173
+ else if (l.kind === 'undo' && str(l.row)) { const r = s.rows.get(l.row); if (r && r.state !== 'open') { r.state = 'open'; delete r.rid; } }
174
+ }
175
+ return { scopes, epoch };
176
+ }
177
+ /** How many rows of a group one run filed (the limits are per run). */
178
+ function countIn(s, run, group) { let n = 0; if (s) for (const r of s.rows.values()) if (r.run === run && r.group === group) n++; return n; }
179
+
180
+ const ROW_KEYS = ['id', 'group', 'name', 'type', 'now', 'nowTxt', 'target', 'targetTxt', 'by', 'why', 'source', 'ticket', 'checkpoints', 'state', 'rid', 'direction', 'unit', 'pillar'];
181
+ /** The GET body (without ok). o: { off } (PMOS_METRIC_DRAFT=off). Zero is silence: no run and no row is run.state idle and rows []. */
182
+ function viewOf(F, scope, id, o = {}) {
183
+ const s = (F && F.scopes.get(keyOf(scope, id))) || blank(scope, id);
184
+ const R = s.run, order = GROUPS[scope] || [];
185
+ const rows = [...s.rows.values()].sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group)).map((r) => {
186
+ const out = {}; for (const k of ROW_KEYS) if (r[k] !== undefined) out[k] = r[k];
187
+ if (out.ticket === undefined) out.ticket = null;
188
+ return out;
189
+ });
190
+ let state = 'idle';
191
+ if (R && !R.ended) state = 'running';
192
+ else if (R && !R.ok && !R.stopped) state = 'failed';
193
+ else if (rows.length) state = 'ready';
194
+ if (o.off && state !== 'running') state = 'off';
195
+ return { scope, id, title: s.title || id, when: s.when, run: { state, step: R ? R.step : 0, reads: R && state !== 'off' ? R.reads.slice() : [], ...(R ? { id: R.run, why: R.why, at: R.at } : {}), ...(R && R.error ? { error: R.error } : {}) },
196
+ rows, head: s.head, sub: s.sub, src: s.src };
197
+ }
198
+
199
+ /* ── ✓ keep: the kr-metrics record (scripts/records). A KR metric needs a baseline, a target and a date, so, as lib/insights-goals.js does:
200
+ * Done or not baseline 0 (not done) or now, target 1; Stay within the reading now and its limit, always on to the year's end when it has no date;
201
+ * no event yet (now null) baseline 0 with measured: false and the ticket, so the page says it waits for the event and never shows the 0 as read ── */
202
+ function keepFields(scope, id, row, o = {}) {
203
+ if (!isObj(row) || !SCOPES.includes(scope)) return { error: 'no such draft' };
204
+ const role = (ROLES[scope] || {})[row.group];
205
+ if (!role) return { error: 'This draft has no group, so it cannot be kept.' };
206
+ const type = row.type, now = fin(row.now) ? row.now : null;
207
+ let baseline, target, direction, by = row.by || null;
208
+ const f = { metric: row.name, type, role };
209
+ if (type === 'Done or not') { baseline = now == null ? 0 : now ? 1 : 0; target = 1; direction = 'up'; f.unit = 'done'; }
210
+ else {
211
+ target = row.target;
212
+ if (!fin(target)) return { error: 'This draft has no target, so it cannot be kept.' };
213
+ baseline = now == null ? 0 : now;
214
+ direction = row.direction || (now == null ? 'up' : target >= now ? 'up' : 'down');
215
+ if (type === 'Stay within') { f.limit = direction === 'down' ? 'ceiling' : 'floor'; if (!by) { by = String(o.today || '').slice(0, 4) + '-12-31'; f.always_on = true; } }
216
+ f.unit = row.unit || UNIT_OF[type] || '';
217
+ }
218
+ if (!DAY_RE.test(String(by || ''))) return { error: 'This draft has no date, so it cannot be kept.' };
219
+ if (baseline === target) return { error: 'The target equals the baseline, so there is nothing to move. Drop it or draft again.' };
220
+ Object.assign(f, { baseline, target, by, direction, source: row.source || '', why: row.why || '' });
221
+ if (now == null && type !== 'Done or not') f.measured = false;
222
+ if (row.ticket) f.ticket = { key: row.ticket.key, text: row.ticket.text };
223
+ if (row.pillar) f.pillar = row.pillar;
224
+ if (scope === 'program') { f.program = id; if (Array.isArray(row.checkpoints) && row.checkpoints.length) f.checkpoints = row.checkpoints.map((c) => ({ by: c.by, target: c.target, label: c.label || '' })); }
225
+ if (scope === 'initiative') { f.initiative = id; f.window = WINDOW; }
226
+ if (scope === 'product') f.product = id;
227
+ f.draft = row.id;
228
+ return { fields: f, reading: now != null && DAY_RE.test(String(o.today || '')) ? { at: o.today, value: now } : null };
229
+ }
230
+
231
+ module.exports = { LEDGER, SCOPES, GROUPS, LIMITS, ROLES, TYPES, STEPS, WHEN, WHYS, WINDOW, ledgerFile, readLines, read, append, fold, viewOf, clean, keepFields, rowId, keyOf, countIn };
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+ /* metrics-cli.js — `pmos metrics draft`: the one write of Claude's metric-draft run (batch 15 item 1; lib/metric-drafts.js, lib/metric-draft-runs.js).
3
+ * What it files waits on the page as a draft until the PM's ✓ keep, which alone writes the kr-metrics record.
4
+ *
5
+ * pmos metrics draft read "<source>" --found "<one line>" [--state done|now|wait] one source read, for the strip's first step
6
+ * pmos metrics draft step shape|measure|target|ready the strip moves on
7
+ * pmos metrics draft row --json <file|-> one drafted row, or a list of them
8
+ * pmos metrics draft end --head "<line>" [--sub "<line>"] [--src "<a · b · c>"] the run is done: what the page says on top
9
+ * pmos metrics draft status what this scope holds: open, kept and dropped
10
+ *
11
+ * The server pins the scope, the run and the ledger in the run's environment (PMOS_METRIC_DRAFT_FILE, _WS, _SCOPE, _ID, _RUN); outside such
12
+ * a run the verb refuses: the PM keeps and drops on the page. A row the PM kept is not filed again. Exit codes: 0 filed, 1 refused, 2 usage.
13
+ * It writes no record and sends nothing. */
14
+ const fs = require('fs');
15
+ const MD = require('./metric-drafts.js');
16
+
17
+ const COMMANDS = { metrics: ['draft'] };
18
+ const SUBS = ['read', 'step', 'row', 'end', 'status'];
19
+ const USAGE = [
20
+ 'usage: pmos metrics draft read|step|row|end|status — the metrics Claude drafts for the PM to keep or drop',
21
+ ' pmos metrics draft read "<source>" --found "<what it says, one line>" [--state done|now|wait]',
22
+ ' pmos metrics draft step shape|measure|target|ready',
23
+ ' pmos metrics draft row --json <file|->',
24
+ ' { "group", "name", "type": "' + MD.TYPES.join('" | "') + '", "now": <number from the readings> | null,',
25
+ ' "nowTxt", "target", "targetTxt", "by": "YYYY-MM-DD", "why": "<one line>", "source": "Amplitude",',
26
+ ' "ticket": { "key", "text" } (only when no event counts it, with now null), "checkpoints"?: [{ "by", "target", "label" }],',
27
+ ' "direction"?: "up" | "down", "unit"?, "pillar"? (Key results) }',
28
+ ' pmos metrics draft end --head "<I drafted …>" [--sub "<where it comes from>"] [--src "<Product brief · Amplitude>"]',
29
+ ' pmos metrics draft status',
30
+ 'Every number comes from a real reading. The PM keeps or drops each row on the page. Nothing is sent.',
31
+ ];
32
+ const flag = (args, k) => { const i = args.indexOf('--' + k); return i >= 0 ? (args[i + 1] === undefined || args[i + 1].startsWith('--') ? true : args[i + 1]) : undefined; };
33
+ function readJson(src, stdin) {
34
+ let text;
35
+ try { text = src === '-' ? (stdin !== undefined ? String(stdin) : fs.readFileSync(0, 'utf8')) : fs.readFileSync(src, 'utf8'); } catch (e) { return { error: `could not read ${src}: ${String((e && e.message) || e).slice(0, 120)}` }; }
36
+ try { return { body: JSON.parse(text) }; } catch { return { error: 'the input is not JSON' }; }
37
+ }
38
+
39
+ async function run(argv, { say = (s) => console.log(s), env = process.env, stdin, now = Date.now() } = {}) {
40
+ const args = argv[0] === 'metrics' ? argv.slice(1) : argv.slice();
41
+ if (!args[0] || ['help', '--help', '-h'].includes(args[0])) { for (const l of USAGE) say(l); return args[0] ? 0 : 1; }
42
+ if (args[0] !== 'draft') { say(`unknown metrics command "${args[0]}". Use: pmos metrics draft ${SUBS.join('|')}`); return 2; }
43
+ const sub = args[1];
44
+ if (!sub || ['help', '--help', '-h'].includes(sub)) { for (const l of USAGE) say(l); return sub ? 0 : 1; }
45
+ if (!SUBS.includes(sub)) { say(`unknown draft command "${sub}". Use one of: ${SUBS.join(', ')}`); return 2; }
46
+ const file = env.PMOS_METRIC_DRAFT_FILE, runId = env.PMOS_METRIC_DRAFT_RUN, scope = env.PMOS_METRIC_DRAFT_SCOPE, id = env.PMOS_METRIC_DRAFT_ID;
47
+ if (!file || !runId || !MD.SCOPES.includes(scope) || !id) { say('✗ pmos metrics draft is for Claude\'s metric-draft run. The PM keeps and drops drafts on the page.'); return 1; }
48
+ const F = MD.fold(MD.readLines(file)), s = F.scopes.get(MD.keyOf(scope, id));
49
+ const at = new Date(now).toISOString();
50
+ const line = (ev) => { fs.appendFileSync(file, JSON.stringify({ at, by: null, scope, id, run: runId, ...ev }) + '\n'); };
51
+
52
+ if (sub === 'status') {
53
+ if (!s || !s.rows.size) say('nothing drafted for ' + scope + ' ' + id);
54
+ else for (const r of s.rows.values()) say(`${r.state.padEnd(7)} ${r.id} · ${r.group} · ${r.name} · now ${r.nowTxt} · target ${r.targetTxt}`);
55
+ return 0;
56
+ }
57
+ if (!s || !s.run || s.run.run !== runId || s.run.ended) { say('✗ this run is not drafting now. It ended, or the PM pressed Stop. File nothing more.'); return 1; }
58
+ const pos = args.slice(2).filter((x, i, a) => !x.startsWith('--') && !(i > 0 && a[i - 1].startsWith('--')));
59
+
60
+ if (sub === 'read') {
61
+ const t = String(pos[0] || '').replace(/\s+/g, ' ').trim().slice(0, 60), f = flag(args, 'found'), state = flag(args, 'state') || 'done';
62
+ if (!t || typeof f !== 'string' || !f.trim()) { say('usage: pmos metrics draft read "<source>" --found "<what it says, one line>" [--state done|now|wait]'); return 2; }
63
+ if (!['done', 'now', 'wait'].includes(state)) { say('✗ --state is done, now or wait'); return 2; }
64
+ line({ kind: 'read', t, f: f.replace(/\s+/g, ' ').trim().slice(0, 200), state });
65
+ say(`read ${t}`);
66
+ return 0;
67
+ }
68
+ if (sub === 'step') {
69
+ const n = MD.STEPS.indexOf(String(pos[0] || ''));
70
+ if (n < 1) { say('usage: pmos metrics draft step shape|measure|target|ready'); return 2; }
71
+ line({ kind: 'step', step: n });
72
+ say(`step ${MD.STEPS[n]}`);
73
+ return 0;
74
+ }
75
+ if (sub === 'end') {
76
+ const head = flag(args, 'head');
77
+ if (typeof head !== 'string' || !head.trim()) { say('usage: pmos metrics draft end --head "<I drafted …>" [--sub "<line>"] [--src "<a · b>"]'); return 2; }
78
+ const opt = (k) => { const v = flag(args, k); return typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, 300) : ''; };
79
+ if (![...s.rows.values()].some((r) => r.run === runId)) { say('✗ this run filed no row. File the rows first, or end with nothing: stop and say why in your answer.'); return 1; }
80
+ line({ kind: 'end', ok: true, head: head.replace(/\s+/g, ' ').trim().slice(0, 200), sub: opt('sub'), src: opt('src') });
81
+ say('ended: ready for the PM');
82
+ return 0;
83
+ }
84
+ // row
85
+ const jsonAt = args.indexOf('--json'), src = jsonAt >= 0 ? args[jsonAt + 1] : null;
86
+ if (!src) { say('usage: pmos metrics draft row --json <file|->'); return 2; }
87
+ const r = readJson(src, stdin); if (r.error) { say('✗ ' + r.error); return 1; }
88
+ let bad = 0;
89
+ const filed = new Map(); // group → rows filed in this call (the limits are per run)
90
+ for (const x of Array.isArray(r.body) ? r.body : [r.body]) {
91
+ const c = MD.clean(scope, x);
92
+ if (c.error) { say(`✗ refused: ${c.error}`); bad++; continue; }
93
+ const rid = MD.rowId(scope, id, c.row.group, c.row.name), was = s.rows.get(rid);
94
+ if (was && was.state === 'kept') { say(`kept ${rid}: the PM kept "${c.row.name}" already. Draft something new.`); continue; }
95
+ const n = MD.countIn(s, runId, c.row.group) + (filed.get(c.row.group) || 0) - (was && was.run === runId ? 1 : 0);
96
+ if (n >= MD.LIMITS[c.row.group]) { say(`✗ refused: ${c.row.group} takes at most ${MD.LIMITS[c.row.group]} in one run`); bad++; continue; }
97
+ line({ kind: 'row', row: { id: rid, ...c.row } });
98
+ if (!(was && was.run === runId)) filed.set(c.row.group, (filed.get(c.row.group) || 0) + 1);
99
+ say(`filed ${rid} · ${c.row.group} · ${c.row.name}${c.row.ticket ? ' · ticket ' + c.row.ticket.key + ' drafted' : ''}`);
100
+ }
101
+ return bad ? 1 : 0;
102
+ }
103
+
104
+ module.exports = { run, COMMANDS, USAGE, SUBS };
@@ -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})$/.test(id)) return refuse(400, 'id is a proposal of the strip: found:<finding> or period-end:<date>');
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,7 @@ 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-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
104
  'routes-refresh', // data-refresh-settings: Settings › Data refresh: what refreshes, when, the refresh log, Refresh now
104
105
  ]);
105
106
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
@@ -59,7 +59,7 @@ module.exports = {
59
59
  let outcomes, goalMeta = {};
60
60
  try {
61
61
  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');
62
+ 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
63
  outcomes = krs.map((k) => strategy.outcomeOf(k, day));
64
64
  goalMeta = Object.fromEntries(krs.map((k) => [k.rid, k])); // premium-agreed-design: the fields New goal keeps (type, direction, period, owner, …)
65
65
  } catch (e) { return fail('the KR metric records could not be read: ' + ((e && e.message) || e)); }
@@ -92,7 +92,7 @@ module.exports = {
92
92
  const counts = new Map();
93
93
  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
94
  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))),
95
+ 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
96
  outcomes, reports: reportsOk ? rp.body.reports || [] : [], reportsOk, missing, saved, mine,
97
97
  setups: setupsOk ? su.body : null, pinned, leads, archived, initiatives, goalMeta, ins, budgets,
98
98
  });
@@ -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') {