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
@@ -3,7 +3,7 @@
3
3
  * (initiative workspace-headless-jobs; PM decision 2026-10-11: keep Jev, no direct Claude API, background
4
4
  * jobs that need no human run headless).
5
5
  *
6
- * kindFor({ agent, origin, skill, env }) → 'notes' | 'skill' | 'ask' | 'drive' | 'scan-web' | 'scan-repo' | 'scan-research-web' | 'scan-research-repo' | 'report-setup' | 'report-find' | 'core-doc' | 'report-design' | 'report-structure-pull' | 'report-sample-fetch' | 'report-structure' | 'report-structure-dry' | 'ms-review' | 'propose' | null (null: open a pane, as before)
6
+ * kindFor({ agent, origin, skill, env }) → 'notes' | 'skill' | 'ask' | 'drive' | 'scan-web' | 'scan-repo' | 'scan-research-web' | 'scan-research-repo' | 'report-setup' | 'report-find' | 'core-doc' | 'report-design' | 'report-structure-pull' | 'report-sample-fetch' | 'report-structure' | 'report-structure-dry' | 'ms-review' | 'propose' | 'metric-draft' | null (null: open a pane, as before)
7
7
  * argsFor(kind, { modelArgs, addDirs, writePaths }) → the argv after `claude` (writePaths: the one render file a report-design job may write;
8
8
  * for the skill kind, the folders the run may write in, from skillWriteDirs)
9
9
  * skillWriteDirs(skill, { root, scratch }) → the absolute folders a background skill run may write in: its scratch folder and the state folders its skill writes
@@ -57,6 +57,10 @@
57
57
  * initiative it looks for it in the PM's sources; each morning it finds why tasks slipped. It reads the repository, the stored reads and, where the PM's
58
58
  * own settings allow it, the PM's sources through connectors; its only write is `pmos propose`, pinned by the server to that initiative and run. Only
59
59
  * the PM's ✓ writes a task, a document or a stage. It sends nothing and never runs in a pane.
60
+ * The `metric-draft` kind is Claude's metric drafts for one product, program or initiative (batch 15 item 1): origin
61
+ * `metric-draft:<ws>:<scope>:<id>:<run>`. It reads the repository, the stored reads and, where the PM's own settings allow it, the PM's sources through
62
+ * connectors; its only write is `pmos metrics draft`, pinned by the server to that scope and run. Only the PM's ✓ keep writes a record. It sends nothing
63
+ * and never runs in a pane.
60
64
  * The `report-structure` and `report-structure-dry` kinds are the report structure step (initiative report-structure): origins `report-structure:<id>` and
61
65
  * `report-structure-dry:<id>`. A turn proposes or refines the plan of a report (sources, charts, outline); a dry run tries a saved version on the last complete
62
66
  * period. Each reads the repository and, where the PM's own Claude Code settings allow it, reads through connectors (none is named in the list, as for
@@ -100,6 +104,9 @@ const MS_REVIEW_ORIGINS = Object.freeze(['ms-review:']);
100
104
  // feedback batch 12 items 2, 3 and 4: Claude looks for a new initiative in the PM's sources, and the morning task check (origin
101
105
  // `propose:<ws>:<initiative>:<run>`, lib/proposal-runs.js). Its only write is `pmos propose`, pinned by the server to that initiative and run.
102
106
  const PROPOSE_ORIGINS = Object.freeze(['propose:']);
107
+ // batch 15 item 1: Claude drafts the metrics of a product, a program or an initiative (origin `metric-draft:<ws>:<scope>:<id>:<run>`,
108
+ // lib/metric-draft-runs.js). Its only write is `pmos metrics draft`, pinned by the server to that scope and run.
109
+ const METRIC_DRAFT_ORIGINS = Object.freeze(['metric-draft:']);
103
110
  // report-design-studio: a studio turn, a cycle render or a re-render to match (origin `report-design:<cadence>`).
104
111
  const REPORT_DESIGN_ORIGINS = Object.freeze(['report-design:']);
105
112
  // report-design-studio: reading ONE linked Google or Confluence file through the PM's own connectors (origin `report-sample-fetch:<cadence>:<sampleId>`).
@@ -154,6 +161,11 @@ const TOOLS = Object.freeze({
154
161
  // that sends; it never writes a task, a document or a stage (only the PM's ✓ does).
155
162
  propose: Object.freeze(['Read', 'Glob', 'Grep', 'Bash(pmos propose *)', 'Bash(pmos initiative export *)', 'Bash(pmos initiative list *)', 'Bash(pmos task list *)',
156
163
  'Bash(pmos source show *)', 'Bash(pmos source status *)', 'Bash(git log *)', 'Bash(date *)']),
164
+ // The metric-draft run (lib/metric-draft-runs.js): read and search the repository and the stored reads, and the one verb that files a draft.
165
+ // The PM's analytics, Jira and documents are read through the PM's own connectors only where the PM's settings allow it. No Write, no Edit,
166
+ // no web fetch, nothing that sends; it never writes a record (only the PM's ✓ keep does).
167
+ 'metric-draft': Object.freeze(['Read', 'Glob', 'Grep', 'Bash(pmos metrics draft *)', 'Bash(pmos initiative export *)', 'Bash(pmos initiative list *)',
168
+ 'Bash(pmos source show *)', 'Bash(pmos source status *)', 'Bash(git log *)', 'Bash(date *)']),
157
169
  // The design run: read and search only. Its one write, the render file, is added per run by argsFor (writePaths). No Bash, no web, nothing that sends.
158
170
  'report-design': Object.freeze(['Read', 'Glob', 'Grep']),
159
171
  // The link fetch run: Read, and its one write (the text copy of the linked file) is added per run by argsFor. No Bash, no web, no connector tool named.
@@ -191,6 +203,7 @@ function kindFor({ agent, origin, skill, env } = {}) {
191
203
  if (CORE_DOC_ORIGINS.some((p) => o.startsWith(p))) return 'core-doc';
192
204
  if (MS_REVIEW_ORIGINS.some((p) => o.startsWith(p))) return 'ms-review';
193
205
  if (PROPOSE_ORIGINS.some((p) => o.startsWith(p))) return 'propose';
206
+ if (METRIC_DRAFT_ORIGINS.some((p) => o.startsWith(p))) return 'metric-draft';
194
207
  if (REPORT_DESIGN_ORIGINS.some((p) => o.startsWith(p))) return 'report-design';
195
208
  if (REPORT_SAMPLE_FETCH_ORIGINS.some((p) => o.startsWith(p))) return 'report-sample-fetch';
196
209
  // 'report-structure-dry:' is not a prefix of 'report-structure:' (the colon differs), so the two are told apart by their prefix alone
@@ -352,4 +365,4 @@ function logLines(r, exitCode) {
352
365
  return out;
353
366
  }
354
367
 
355
- module.exports = { HEADLESS_SKILLS, HEADLESS_ORIGINS, ASK_ORIGINS, DRIVE_ORIGINS, SCAN_WEB_ORIGINS, SCAN_REPO_ORIGINS, SCAN_RESEARCH_WEB_ORIGINS, SCAN_RESEARCH_REPO_ORIGINS, WEB_KINDS, REPORT_SETUP_ORIGINS, REPORT_FIND_ORIGINS, CORE_DOC_ORIGINS, REPORT_DESIGN_ORIGINS, REPORT_SAMPLE_FETCH_ORIGINS, REPORT_STRUCTURE_ORIGINS, REPORT_STRUCTURE_DRY_ORIGINS, TOOLS, SKILL_WRITE_DIRS, DEFAULT_TIMEOUT_MS, kindFor, argsFor, skillWriteDirs, timeoutMs, parseResult, streamLines, outcomeOf, signedOut, SIGNED_OUT_WHY, logLines, switchedOff };
368
+ module.exports = { HEADLESS_SKILLS, HEADLESS_ORIGINS, ASK_ORIGINS, DRIVE_ORIGINS, SCAN_WEB_ORIGINS, SCAN_REPO_ORIGINS, SCAN_RESEARCH_WEB_ORIGINS, SCAN_RESEARCH_REPO_ORIGINS, WEB_KINDS, REPORT_SETUP_ORIGINS, REPORT_FIND_ORIGINS, CORE_DOC_ORIGINS, REPORT_DESIGN_ORIGINS, REPORT_SAMPLE_FETCH_ORIGINS, REPORT_STRUCTURE_ORIGINS, REPORT_STRUCTURE_DRY_ORIGINS, METRIC_DRAFT_ORIGINS, TOOLS, SKILL_WRITE_DIRS, DEFAULT_TIMEOUT_MS, kindFor, argsFor, skillWriteDirs, timeoutMs, parseResult, streamLines, outcomeOf, signedOut, SIGNED_OUT_WHY, logLines, switchedOff };
@@ -38,6 +38,7 @@
38
38
  * placements and the gates keep reading the same record. Same refusals for the title as a new record; no record → 404.
39
39
  *
40
40
  * setAnchor(root, id, anchor, { actor }) → { ok: true, id, from, anchor } | { ok: false, … }
41
+ * restoreAnchor(root, id, from, { actor }) → the same; the Undo of a setAnchor (batch 16: a ✦ strip re-anchor), no resolve check
41
42
  * withdrawSplit(root, id, sha, { actor }) → { ok: true, removed } | { ok: false, … }
42
43
  *
43
44
  * SPLIT AND MERGE (feedback batch 11 item 14). A merge can keep the closing initiative's anchor: only the `parent_kr:` line changes, to an
@@ -218,6 +219,19 @@ function setAnchor(root, id, anchor, { actor } = {}) {
218
219
  const text0 = typeof anchor === 'string' ? anchor.trim() : '';
219
220
  if (!text0 || !ONE_LINE(text0, 120)) return refuse(400, 'an initiative needs an anchor: a KR, or health:<id> from the health budgets (D59)', 'anchor');
220
221
  if (rows.anchorsOf(root).resolve(text0).status !== 'resolved') return refuse(400, `the anchor "${text0}" is not declared in the OKR files or the health budgets (D59)`, 'anchor');
222
+ return writeAnchor(root, id, text0);
223
+ }
224
+
225
+ /** The Undo of a setAnchor: the `parent_kr:` line back to exactly what it was, even an anchor that does not resolve, and no line when there
226
+ * was none. Only an Undo calls it, with the `from` its setAnchor answered. */
227
+ function restoreAnchor(root, id, from, { actor } = {}) {
228
+ if (!actorLib.valid(actor)) return refuse(500, 'initiative-writer: the caller must pass the actor from pm-guard.js or actor.js');
229
+ const text0 = typeof from === 'string' ? from.trim() : '';
230
+ if (text0 && !ONE_LINE(text0, 120)) return refuse(400, 'the anchor to put back is not one line', 'anchor');
231
+ return writeAnchor(root, id, text0);
232
+ }
233
+
234
+ function writeAnchor(root, id, text0) {
221
235
  const f = recordFile(root, id);
222
236
  if (!f.ok) return f;
223
237
  const text = fs.readFileSync(f.file, 'utf8');
@@ -228,7 +242,7 @@ function setAnchor(root, id, anchor, { actor } = {}) {
228
242
  const from = at >= 0 ? unquote(lines[at].slice(10)) : '';
229
243
  if (from === text0) return { ok: true, id, from, anchor: text0, same: true };
230
244
  const line = `parent_kr: ${PLAIN(text0) ? text0 : q(text0)}`;
231
- if (at >= 0) lines[at] = line; else lines.push(line);
245
+ if (!text0) { if (at >= 0) lines.splice(at, 1); } else if (at >= 0) lines[at] = line; else lines.push(line);
232
246
  try { fs.writeFileSync(f.file, '---\n' + lines.join('\n') + '\n---' + m[2] + text.slice(m[0].length), { flag: 'w' }); } catch { return refuse(500, 'the record could not be written — nothing was saved'); }
233
247
  return { ok: true, id, from, anchor: text0 };
234
248
  }
@@ -244,4 +258,4 @@ function withdrawSplit(root, id, want, { actor } = {}) {
244
258
  return { ok: true, removed: true };
245
259
  }
246
260
 
247
- module.exports = { createInitiative, renameInitiative, setAnchor, withdrawSplit, recordSha, slugOf, ID_RE, INPUT_KEYS };
261
+ module.exports = { createInitiative, renameInitiative, setAnchor, restoreAnchor, withdrawSplit, recordSha, slugOf, ID_RE, INPUT_KEYS };
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+ /* insight-moves.js — the drafted move of a ✦ strip finding on Intelligence (feedback batch 16 item 1, the first 0.429.0 gap). The strip said a
3
+ * goal is behind and stopped there; now each finding about a goal that is behind carries at most ONE drafted fix. Claude recommends it, the PM's ✓
4
+ * makes it through the normal file-mode writer, and Undo takes it back. lib/routes-insight-moves.js does the I/O. THE ONE WRITER and THE ONE FOLD
5
+ * of <state>/insight-moves.jsonl. Pure apart from the ledger file, with no clock of its own: every time comes in.
6
+ *
7
+ * THE MOVES, tried in this order; the first that fits is the one drafted, and a finding with none draws no ✓ (zero is silence):
8
+ * chase an active initiative that moves the goal is past its end date, has an owner and a Jira epic: a comment asking the owner for a new
9
+ * date goes to the outbox (channel jira-write). Nothing is sent: it waits in the outbox for the PM's own Send.
10
+ * anchor nothing active moves the goal, and one active initiative of the board has no anchor that resolves while its title shares a word with
11
+ * the goal: its parent_kr is set to the goal (an anchor the OKR files declare, the same check as any anchor change).
12
+ * date the goal will miss its target at this pace and the straight line reaches the target on a later day: the KR metric record's `by`
13
+ * moves to that day.
14
+ * Every number in a move is a field of a record or the projection the finding already states. No move is made from a guess about a cause.
15
+ *
16
+ * THE LEDGER. One line per event, { at, by, kind, sig, ... }:
17
+ * apply { sig, move, undo } the PM's ✓: what was written and what puts it back (date: { by }; anchor: { from }; chase: { entry })
18
+ * undo { sig } the Undo of the last apply of that sig
19
+ *
20
+ * draftFor(finding, model, o) PURE → the move or null. o: { initiatives (the board rows), anchorOk(text) → bool, today (YYYY-MM-DD) }
21
+ * draftAll(model, o) PURE → the model's insight and its `more` each given `move` (null when none), each marked `done` when applied
22
+ * sigOf(move) · fold(lines) → Map sig → { state: applied|undone, at, undo, move } · read(dir) · append(dir, actor, line, at) · ledgerFile(dir)
23
+ */
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const crypto = require('crypto');
27
+
28
+ const LEDGER = 'insight-moves.jsonl';
29
+ const KINDS = new Set(['apply', 'undo']);
30
+ const BEHIND = new Set(['stuck', 'worse', 'off', 'stall', 'miss', 'closing']);
31
+ const MON = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
32
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
33
+ const DAY = 864e5;
34
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
35
+ const str = (v) => (typeof v === 'string' ? v : '');
36
+ const ms = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
37
+ /** 12 January 2027: a date in full, as the reports write it. */
38
+ const full = (v) => { const t = ms(v); if (t === null) return ''; const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()] + ' ' + d.getUTCFullYear(); };
39
+ const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s; };
40
+ const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 12);
41
+ const first = (s) => String(s || '').trim().split(/\s+/)[0] || '';
42
+
43
+ /* ── the words a title shares with a goal: four letters or more, the small words left out ── */
44
+ const STOP = new Set(['with', 'from', 'that', 'this', 'into', 'over', 'more', 'less', 'than', 'your', 'their', 'what', 'when', 'week', 'weeks', 'month',
45
+ 'rate', 'time', 'days', 'count', 'total', 'number', 'percent', 'goal', 'metric', 'make', 'new', 'improve', 'increase', 'reduce', 'better', 'faster']);
46
+ const wordsOf = (s) => [...new Set((String(s || '').toLowerCase().match(/[a-z][a-z0-9]{3,}/g) || []).filter((w) => !STOP.has(w)))];
47
+ const shared = (a, b) => { const B = new Set(wordsOf(b)); return wordsOf(a).filter((w) => B.has(w)); };
48
+
49
+ const ACTIVE = (r) => r && r.status !== 'done' && r.status !== 'cancelled' && !(typeof r.idx === 'number' && r.idx >= 6);
50
+ const sigOf = (m) => 'mv-' + hash([m.kind, m.goal, m.ini || '', m.to || m.epic || ''].join('|'));
51
+
52
+ /** The one move for a finding, or null. */
53
+ function draftFor(f, model, o = {}) {
54
+ if (!isObj(f) || !BEHIND.has(f.kind) || !f.chart) return null;
55
+ const goal = ((model && model.goals) || []).find((g) => g && g.key === f.chart);
56
+ if (!goal || !goal.id) return null;
57
+ const today = DAY_RE.test(str(o.today)) ? o.today : null, t0 = ms(today);
58
+ const active = (goal.moves || []).filter(ACTIVE);
59
+ // chase: the initiative most days past its end, with someone to ask and a ticket to ask on
60
+ if (t0 !== null) {
61
+ const late = active.filter((r) => r.owner && r.epic && ms(r.endAt) !== null && ms(r.endAt) < t0).sort((a, b) => ms(a.endAt) - ms(b.endAt))[0];
62
+ if (late) {
63
+ const days = Math.round((t0 - ms(late.endAt)) / DAY), who = clip(late.owner, 40);
64
+ const body = 'Hi ' + first(who) + ', ' + clip(late.title, 80) + ' was due on ' + full(late.endAt) + ' and is ' + days + (days === 1 ? ' day' : ' days') + ' over. '
65
+ + clip(goal.title, 80) + ' is behind its line' + (goal.nowTxt ? ' at ' + goal.nowTxt : '') + (goal.targetTxt ? ' against a target of ' + goal.targetTxt : '') + '. What is the new date?';
66
+ const m = { kind: 'chase', goal: goal.id, ini: late.id, owner: who, epic: late.epic, days, body,
67
+ text: 'Ask ' + who + ' for a new date on ' + clip(late.title, 60) + ', ' + days + (days === 1 ? ' day' : ' days') + ' over.',
68
+ label: 'Put the comment to ' + who + ' in the outbox', said: 'The comment to ' + who + ' is in the outbox. Nothing is sent until you send it.' };
69
+ return Object.assign(m, { sig: sigOf(m) });
70
+ }
71
+ }
72
+ // anchor: nothing active moves the goal; the one board initiative with no working anchor whose title shares a word with the goal
73
+ if (!active.length && typeof o.anchorOk === 'function') {
74
+ const to = [goal.id, goal.title].find((x) => x && o.anchorOk(x)) || null;
75
+ if (to) {
76
+ const hits = (o.initiatives || []).filter((r) => r && r.id && ACTIVE({ status: r.status }) && !(r.anchor && o.anchorOk(r.anchor)))
77
+ .map((r) => ({ r, w: shared(r.title || r.id, goal.title) })).filter((x) => x.w.length);
78
+ if (hits.length === 1) { // two or more candidates is a guess: none is drafted
79
+ const { r, w } = hits[0];
80
+ const m = { kind: 'anchor', goal: goal.id, ini: String(r.id), from: str(r.anchor), to,
81
+ text: 'Anchor ' + clip(r.title || r.id, 60) + ' to ' + clip(goal.title, 60) + '. Nothing moves this goal, and the title shares "' + w[0] + '".',
82
+ label: 'Anchor ' + clip(r.title || r.id, 60) + ' to this goal', said: clip(r.title || r.id, 60) + ' now moves ' + clip(goal.title, 60) + '.' };
83
+ return Object.assign(m, { sig: sigOf(m) });
84
+ }
85
+ }
86
+ }
87
+ // date: the line through the last readings reaches the target, later than the record's date
88
+ if (f.kind === 'miss' && DAY_RE.test(str(f.whenAt)) && DAY_RE.test(str(goal.byAt)) && f.whenAt > goal.byAt) {
89
+ const m = { kind: 'date', goal: goal.id, from: goal.byAt, to: f.whenAt,
90
+ text: 'Move the target date of ' + clip(goal.title, 60) + ' from ' + full(goal.byAt) + ' to ' + full(f.whenAt) + ', when it gets there at this pace.',
91
+ label: 'Move the target date to ' + full(f.whenAt), said: 'The target date is ' + full(f.whenAt) + ' now.' };
92
+ return Object.assign(m, { sig: sigOf(m) });
93
+ }
94
+ return null;
95
+ }
96
+
97
+ /** The insight and its `more`, each with `move` (null when none). A move the PM already made, and did not undo, is marked done with its day. */
98
+ function draftAll(model, o = {}) {
99
+ const I = model && model.insight;
100
+ if (!I || I.none) return model;
101
+ const F = o.ledger || new Map();
102
+ const one = (f) => { const m = draftFor(f, model, o); if (m) { const x = F.get(m.sig); if (x && x.state === 'applied') m.done = { at: x.at }; } return m; };
103
+ I.move = one({ kind: I.kind, chart: I.chart, whenAt: I.whenAt });
104
+ for (const x of I.more || []) x.move = one(x);
105
+ return model;
106
+ }
107
+
108
+ /* ── the ledger ── */
109
+ function ledgerFile(dir) { return dir ? path.join(dir, LEDGER) : null; }
110
+ function readLines(file) {
111
+ if (!file) return [];
112
+ let text = '';
113
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
114
+ const out = [];
115
+ for (const raw of text.split('\n')) { if (!raw.trim()) continue; try { const l = JSON.parse(raw); if (isObj(l) && KINDS.has(l.kind) && str(l.sig)) out.push(l); } catch { /* a torn line is skipped */ } }
116
+ return out;
117
+ }
118
+ function fold(lines) {
119
+ const F = new Map();
120
+ for (const l of lines || []) {
121
+ if (!isObj(l) || !KINDS.has(l.kind) || !str(l.sig)) continue;
122
+ if (l.kind === 'apply') F.set(l.sig, { state: 'applied', at: str(l.at), undo: isObj(l.undo) ? l.undo : {}, move: isObj(l.move) ? l.move : {} });
123
+ else { const x = F.get(l.sig); if (x && x.state === 'applied') x.state = 'undone'; }
124
+ }
125
+ return F;
126
+ }
127
+ function read(dir) { return fold(readLines(ledgerFile(dir))); }
128
+ function append(dir, actor, ev, at) {
129
+ const line = { at: at || null, by: (actor && actor.by) || null, ...ev };
130
+ fs.mkdirSync(dir, { recursive: true });
131
+ fs.appendFileSync(ledgerFile(dir), JSON.stringify(line) + '\n');
132
+ return line;
133
+ }
134
+
135
+ module.exports = { LEDGER, BEHIND, draftFor, draftAll, sigOf, wordsOf, shared, ledgerFile, readLines, fold, read, append, full };
@@ -125,6 +125,7 @@ function findingsOfChart(c) {
125
125
  if (p && !p.toward) f.push({ kind: 'stall', score: c.pivot ? 101 : 96, text: c.title + ' will miss its ' + tg + ' target on ' + c.by + ' unless it turns.', proj: true,
126
126
  why: (c.pivot ? 'It has been behind its line at three readings in a row. ' : '') + 'Over its last ' + p.n + ' readings it went ' + move(p.from.v, p.now) + ', which is ' + (p.perWeek === 0 ? 'no move' : 'away from the target') + '. A straight line through them never reaches ' + tg + '.' });
127
127
  else if (p && !p.reaches) f.push({ kind: 'miss', score: 95, text: c.title + ' will miss its ' + tg + ' target on ' + c.by + ' at this pace.', proj: true,
128
+ whenAt: p.when && p.when - isoDay(c.lastAt) < 5 * 365 * DAY ? new Date(p.when).toISOString().slice(0, 10) : null, // batch 16: the day the line reaches the target, for a drafted date move
128
129
  why: 'It is at ' + num(now, u) + ' and moving ' + amount(Math.abs(p.perWeek), u) + ' a week toward it, so it reaches about ' + num(r1(p.atDue), u) + ' by ' + c.by + ', ' + amount(r1(p.short), u) + ' short.'
129
130
  + (p.when && p.when - isoDay(c.lastAt) < 5 * 365 * DAY ? ' At this pace it gets there around ' + dayTxt(p.when) + '.' : '') });
130
131
  else if (p) f.push({ kind: 'course', score: 62, text: c.title + ' is short of its target but on course to reach ' + tg + by + '.', proj: true,
@@ -234,8 +235,8 @@ function insightOf(charts, findings, total) {
234
235
  const head = findings[0] || null;
235
236
  return { none: false, off, total: charts.length, asOf: shortDate(last), calm: !head,
236
237
  text: head ? head.text : charts.some((c) => c.target !== null) ? 'Nothing stands out. No measure moved much, and none is far behind its line.' : 'Nothing stands out. No measure here has a target, so the series can only be described.',
237
- why: head ? head.why : '', chart: head ? head.chart : null, kind: head ? head.kind : 'calm', proj: !!(head && head.proj),
238
- more: findings.slice(1, 3).map((x) => ({ text: x.text, chart: x.chart })) };
238
+ why: head ? head.why : '', chart: head ? head.chart : null, kind: head ? head.kind : 'calm', proj: !!(head && head.proj), whenAt: (head && head.whenAt) || null,
239
+ more: findings.slice(1, 3).map((x) => ({ text: x.text, why: x.why || '', chart: x.chart, kind: x.kind, whenAt: x.whenAt || null })) };
239
240
  }
240
241
 
241
242
  /** The opening sentence of a report file (insights-one-list L6): the first prose paragraph after the frontmatter, past headings, lists, tables, quotes, code
@@ -287,7 +288,7 @@ const anchorHits = (a, o) => !!a && (String(a) === String(o.id) || String(a) ===
287
288
  function initOf(r) {
288
289
  const i = lifeIndex(r.stage);
289
290
  return { id: String(r.id), title: clip(r.title || r.id, 120), stage: r.stage || '', idx: i, stageLabel: i >= 0 ? LIFE_LABEL[i] : (r.stage || ''), status: r.status || '', lane: r.lane || '',
290
- owner: r.owner || '', end: r.end ? shortDate(r.end) : '', endAt: r.end ? String(r.end).slice(0, 10) : null, anchor: r.anchor || '',
291
+ owner: r.owner || '', end: r.end ? shortDate(r.end) : '', endAt: r.end ? String(r.end).slice(0, 10) : null, anchor: r.anchor || '', epic: Array.isArray(r.epics) && r.epics.length ? String(r.epics[0]) : null,
291
292
  startAt: r.start ? String(r.start).slice(0, 10) : null, skipped: IG.skippedOf(r.warnings), milestone: milestoneOf(r, i) };
292
293
  }
293
294
  /** The milestone an initiative works toward next, for the goal Viewer's "Moved by" (canvas OvViewers "Goal"): the first milestone stage of its
@@ -299,6 +300,9 @@ function milestoneOf(r, i) {
299
300
  return i < 5 ? { name: LIFE_LABEL[5] } : i < 7 ? { name: LIFE_LABEL[7] } : null;
300
301
  }
301
302
  /** One goal per KR metric record, with or without a series. `today` is a day in ms (UTC midnight). */
303
+ /** A KR metric record's role on Intelligence (batch 15 item 1): the North Star, an input or a guardrail of it, a key result, or a program's or an
304
+ * initiative's own measure (lib/metric-drafts.js writes them on a ✓). A record with none is a key result. */
305
+ const ROLES = ['north-star', 'input', 'guardrail', 'kr', 'program-goal', 'rollup', 'success', 'signal'];
302
306
  function goalsOf(outcomes, charts, inits, today, meta) {
303
307
  return outcomes.map((o) => {
304
308
  const x = (meta && meta[o.id]) || {}; // the fields New goal keeps on the record (lib/insights-goals.js goalFields)
@@ -337,6 +341,7 @@ function goalsOf(outcomes, charts, inits, today, meta) {
337
341
  direction: x.direction || (dir > 0 ? 'up' : dir < 0 ? 'down' : ''),
338
342
  dirTxt: x.type === 'Stay within' ? (x.limit === 'floor' ? 'stay above' : 'stay below') : x.direction === 'exact' ? 'exactly the target' : dir > 0 ? 'up is better' : dir < 0 ? 'down is better' : '',
339
343
  period: x.period || null, checkpoints: Array.isArray(x.checkpoints) ? x.checkpoints : [], source: x.source || '', owner: x.owner || '', guardrail: x.guardrail || '',
344
+ role: ROLES.includes(x.role) ? x.role : null, program: typeof x.program === 'string' ? x.program : null, initiative: typeof x.initiative === 'string' ? x.initiative : null, // Intelligence: North Star, inputs, guardrails; a program's or an initiative's own measure
340
345
  steps: Array.isArray(x.steps) ? x.steps : null, items: Array.isArray(x.items) ? x.items.filter((s) => typeof s === 'string' && s.trim()).map((s) => clip(s.trim(), 60)) : null, limit: x.limit || null, alwaysOn: x.always_on === true, series: rs.map((r) => ({ at: String(r.at).slice(0, 10), v: r.v })), base, baseTxt: base !== null ? num(base, u) : '', from: fromAt ? shortDate(fromAt) : '',
341
346
  now, nowTxt: now !== null ? num(now, u) : '', target: tgt, targetTxt: tgt !== null ? num(tgt, u) : '', by: byAt ? shortDate(byAt) : '', byAt, fromAt,
342
347
  done, timeGone, tone: STATE_TONE[o.status] || 'q', state: o.status || 'unscored', chip: (CHIP[o.status] || ['No line scored'])[0], reason: o.reason || '',
@@ -397,7 +402,7 @@ function build(facts) {
397
402
  const board = f.board || {};
398
403
  const model = {
399
404
  header: { text: (f.pending ? 'Reading the records · ' : '') + 'Real data' + (missing.length ? ' · not read: ' + missing.join(', ') : ''), missing },
400
- board: { ws: board.ws || null, id: board.id || null, name: board.name || 'Insights', switcher: (f.boards || []).map((b) => Object.assign({ ws: b.ws, id: b.id, name: b.name }, fin(b.goals) ? { goals: b.goals } : {})) },
405
+ board: { ws: board.ws || null, id: board.id || null, name: board.name || 'Intelligence', switcher: (f.boards || []).map((b) => Object.assign({ ws: b.ws, id: b.id, name: b.name }, fin(b.goals) ? { goals: b.goals } : {})) },
401
406
  charts, mine, mineGone, mineSaved: mineAll, noSeries, dashboards, rows: charts,
402
407
  findings: findings.length ? findings : [{ kind: 'calm', key: null, text: charts.length ? (charts.some((c) => c.target !== null) ? 'Nothing stands out. No measure moved much, and none is far behind its line.' : 'Nothing stands out. No measure here has a target, so the series can only be described.') : '' }],
403
408
  calm: !findings.length && charts.length > 0,
@@ -5,7 +5,9 @@
5
5
  * FORMS · RANGES · VERDICTS · TARGET_KEYS
6
6
  * ledgerFile(root) · readLines(file)
7
7
  * checkChart(input) → { ok, value } | refusal one chart on one dashboard: { board, dash, goal, form, range, compare, target, forecast, note }
8
- * checkVerdict(input) → { ok, value } | refusal { board, ini, verdict: Keep | Iterate | Stop, learned, goal }
8
+ * checkVerdict(input) → { ok, value } | refusal { board, ini, verdict: Keep | Iterate | Stop, learned, goal, drafted } drafted: the PM kept
9
+ * Claude's drafted verdict with one ✓ on Intelligence ("Did it work?"), and `learned` is the drafted line
10
+ * checkUndo(input) → { ok, value } | refusal { board, ini } a verdict-undo line: the initiative's verdict is taken back (Undo after ✓ Keep)
9
11
  * checkTarget(input) → { ok, value } | refusal a Delivery trends target of the page's own tiles: { key: late | scope, target: number | null }
10
12
  * checkTile(input) → { ok, value } | refusal how any Delivery trends target is read (premium-uncovered-features, IsTarget): { key: one of
11
13
  * TILE_KEYS, dir: 'at least' | 'at most' | 'none', from: 'YYYY-MM-DD' | '', chip: bool }. The number stays where it was kept.
@@ -14,7 +16,7 @@
14
16
  * read(root) → fold(readLines(ledgerFile(root)))
15
17
  * append(root, ev, value, actor, { now }) → { ok, line } THE SINGLE WRITER. `v`, `ev`, `actor` and `at` are set here.
16
18
  *
17
- * THE LINES. { v: 1, ev: 'chart' | 'verdict' | 'target' | 'tile', ...value, actor, at }. The last line of each key wins: a chart per board, dashboard and goal;
19
+ * THE LINES. { v: 1, ev: 'chart' | 'verdict' | 'verdict-undo' | 'target' | 'tile', ...value, actor, at }. The last line of each key wins: a chart per board, dashboard and goal;
18
20
  * a verdict per board and initiative; a target per key; a tile setting per key. A torn line, or one without its key fields, is skipped.
19
21
  * A verdict is recorded here only: it does not move the initiative on the Board and does not change its record. */
20
22
  const fs = require('fs');
@@ -70,7 +72,13 @@ function checkVerdict(input) {
70
72
  if (!VERDICTS.includes(i.verdict)) return refuse(400, 'Pick Keep, Iterate or Stop.');
71
73
  const learned = tidy(i.learned, LEARN_MAX);
72
74
  if (!learned) return refuse(400, 'Say what you learned, in a line.');
73
- return { ok: true, value: { board, ini, verdict: i.verdict, learned, goal: id(i.goal) } };
75
+ return { ok: true, value: Object.assign({ board, ini, verdict: i.verdict, learned, goal: id(i.goal) }, i.drafted === true ? { drafted: true } : {}) };
76
+ }
77
+ function checkUndo(input) {
78
+ const i = isObj(input) ? input : {};
79
+ const board = id(i.board), ini = id(i.ini);
80
+ if (!board || !ini) return refuse(400, 'Name the board and the initiative.');
81
+ return { ok: true, value: { board, ini } };
74
82
  }
75
83
  function checkTarget(input) {
76
84
  const i = isObj(input) ? input : {};
@@ -93,6 +101,7 @@ function fold(lines) {
93
101
  for (const l of lines || []) {
94
102
  if (l.ev === 'chart') { const c = checkChart(l); if (!c.ok) continue; const v = c.value; ((charts[v.board] = charts[v.board] || {})[v.dash] = charts[v.board][v.dash] || {})[v.goal] = Object.assign({}, v, { at: l.at || null }); }
95
103
  else if (l.ev === 'verdict') { const c = checkVerdict(l); if (!c.ok) continue; const v = c.value; (verdicts[v.board] = verdicts[v.board] || {})[v.ini] = Object.assign({}, v, { at: l.at || null, by: l.actor && l.actor.by ? l.actor.by : null }); }
104
+ else if (l.ev === 'verdict-undo') { const c = checkUndo(l); if (!c.ok) continue; if (verdicts[c.value.board]) delete verdicts[c.value.board][c.value.ini]; }
96
105
  else if (l.ev === 'target') { const c = checkTarget(l); if (!c.ok) continue; if (c.value.target === null) delete targets[c.value.key]; else targets[c.value.key] = c.value.target; }
97
106
  else if (l.ev === 'tile') { const c = checkTile(l); if (!c.ok) continue; tiles[c.value.key] = { dir: c.value.dir, from: c.value.from, chip: c.value.chip, at: l.at ? String(l.at).slice(0, 10) : null }; }
98
107
  }
@@ -100,7 +109,7 @@ function fold(lines) {
100
109
  }
101
110
  const read = (root) => fold(readLines(ledgerFile(root)));
102
111
 
103
- const CHECKS = { chart: checkChart, verdict: checkVerdict, target: checkTarget, tile: checkTile };
112
+ const CHECKS = { chart: checkChart, verdict: checkVerdict, 'verdict-undo': checkUndo, target: checkTarget, tile: checkTile };
104
113
  function append(root, ev, input, actor, { now } = {}) {
105
114
  if (!CHECKS[ev]) return refuse(400, 'unknown record: ' + ev);
106
115
  const c = CHECKS[ev](input);
@@ -112,4 +121,4 @@ function append(root, ev, input, actor, { now } = {}) {
112
121
  return { ok: true, line };
113
122
  }
114
123
 
115
- module.exports = { LEDGER, FORMS, RANGES, VERDICTS, TARGET_KEYS, TILE_KEYS, TILE_DIRS, ledgerFile, readLines, checkChart, checkVerdict, checkTarget, checkTile, fold, read, append };
124
+ module.exports = { LEDGER, FORMS, RANGES, VERDICTS, TARGET_KEYS, TILE_KEYS, TILE_DIRS, ledgerFile, readLines, checkChart, checkVerdict, checkUndo, checkTarget, checkTile, fold, read, append };