create-pmos 0.427.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 (147) hide show
  1. package/package.json +25 -25
  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/board-programs-test.js +16 -2
  7. package/workspace/briefing-premium-board-test.js +27 -22
  8. package/workspace/briefing-premium-insights-test.js +81 -60
  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 +7 -5
  12. package/workspace/changelog.json +24 -0
  13. package/workspace/ev-everywhere-test.js +2 -2
  14. package/workspace/guide/briefing-premium.md +4 -2
  15. package/workspace/guide/home.md +34 -7
  16. package/workspace/guide/index.md +1 -0
  17. package/workspace/guide/metric-drafts.md +48 -0
  18. package/workspace/guide/programs.md +1 -0
  19. package/workspace/home-other-product-test.js +12 -2
  20. package/workspace/intel-report-ui-test.js +189 -0
  21. package/workspace/lib/board-metrics-premium.js +1 -1
  22. package/workspace/lib/headless.js +15 -2
  23. package/workspace/lib/insights-premium.js +5 -1
  24. package/workspace/lib/insights-records.js +14 -5
  25. package/workspace/lib/intel-report.js +419 -0
  26. package/workspace/lib/metric-draft-runs.js +193 -0
  27. package/workspace/lib/metric-drafts.js +231 -0
  28. package/workspace/lib/metrics-cli.js +104 -0
  29. package/workspace/lib/pmos-verbs.js +3 -0
  30. package/workspace/lib/report-setups.js +29 -13
  31. package/workspace/lib/route-modules.js +1 -0
  32. package/workspace/lib/routes-insights-premium.js +2 -2
  33. package/workspace/lib/routes-insights-records.js +13 -5
  34. package/workspace/lib/routes-meeting-material.js +22 -1
  35. package/workspace/lib/routes-metric-drafts.js +141 -0
  36. package/workspace/lib/routes-phone-day.js +13 -2
  37. package/workspace/lib/routes-report-setups.js +92 -3
  38. package/workspace/lib/routes-viewer.js +5 -2
  39. package/workspace/lib/settings-store.js +14 -0
  40. package/workspace/metric-drafts-ui-test.js +209 -0
  41. package/workspace/milestone-pins-test.js +13 -0
  42. package/workspace/milestone-suggest-test.js +10 -4
  43. package/workspace/package-lock.json +2 -2
  44. package/workspace/package.json +1 -1
  45. package/workspace/premium-board-actions-test.js +40 -13
  46. package/workspace/premium-phone-card-test.js +8 -5
  47. package/workspace/premium-rec-tab-test.js +8 -0
  48. package/workspace/premium-vw-item-test.js +7 -3
  49. package/workspace/premium-vw-jira-test.js +2 -1
  50. package/workspace/program-charter-test.js +1 -1
  51. package/workspace/program-leave-test.js +2 -2
  52. package/workspace/program-order-test.js +3 -2
  53. package/workspace/program-panel-test.js +2 -1
  54. package/workspace/public/pm/bd-acts.js +23 -29
  55. package/workspace/public/pm/bd-ini-panel.js +90 -32
  56. package/workspace/public/pm/bd-pin-card.css +4 -4
  57. package/workspace/public/pm/bd-pin-card.js +4 -1
  58. package/workspace/public/pm/bd-prog-panel.js +9 -4
  59. package/workspace/public/pm/bd-span.js +22 -12
  60. package/workspace/public/pm/cozy-aud.css +1 -1
  61. package/workspace/public/pm/cozy-board.css +256 -256
  62. package/workspace/public/pm/cozy-ev.css +45 -45
  63. package/workspace/public/pm/cozy-evmodel.js +1 -1
  64. package/workspace/public/pm/cozy-home-rows.css +23 -23
  65. package/workspace/public/pm/cozy-home.css +207 -207
  66. package/workspace/public/pm/cozy-insights.css +207 -108
  67. package/workspace/public/pm/cozy-live-pill.css +5 -5
  68. package/workspace/public/pm/cozy-mtg-present.css +23 -23
  69. package/workspace/public/pm/cozy-nav.js +1 -1
  70. package/workspace/public/pm/cozy-news.js +2 -2
  71. package/workspace/public/pm/cozy-panel.css +29 -29
  72. package/workspace/public/pm/cozy-pick.css +5 -5
  73. package/workspace/public/pm/cozy-rec-now.css +20 -20
  74. package/workspace/public/pm/cozy-rec-present.css +11 -11
  75. package/workspace/public/pm/cozy-rec-tab.css +13 -13
  76. package/workspace/public/pm/cozy-rec-tab.js +12 -3
  77. package/workspace/public/pm/cozy-settings.js +1 -1
  78. package/workspace/public/pm/cozy-steps.css +9 -9
  79. package/workspace/public/pm/cozy-today.css +107 -71
  80. package/workspace/public/pm/cozy-viewer.css +7 -7
  81. package/workspace/public/pm/cozy-viewer.js +157 -23
  82. package/workspace/public/pm/cozy-vw-mtg.css +81 -81
  83. package/workspace/public/pm/cozy-vw-rp.css +53 -53
  84. package/workspace/public/pm/cozy-vw-shell.css +34 -21
  85. package/workspace/public/pm/cozy-vw.css +117 -117
  86. package/workspace/public/pm/cozy-xv.css +11 -11
  87. package/workspace/public/pm/cozy.css +18 -15
  88. package/workspace/public/pm/hi-pop.css +82 -0
  89. package/workspace/public/pm/hi-pop.js +65 -0
  90. package/workspace/public/pm/home-app.js +83 -28
  91. package/workspace/public/pm/home-day.js +131 -26
  92. package/workspace/public/pm/home-ini.css +38 -108
  93. package/workspace/public/pm/home-ini.js +50 -68
  94. package/workspace/public/pm/home-line.css +7 -7
  95. package/workspace/public/pm/home-list.js +41 -4
  96. package/workspace/public/pm/home-phone-card.js +18 -15
  97. package/workspace/public/pm/home-today.js +18 -7
  98. package/workspace/public/pm/ini-more.js +67 -0
  99. package/workspace/public/pm/ini-view-model.js +3 -2
  100. package/workspace/public/pm/ini-view.css +104 -102
  101. package/workspace/public/pm/ini-view.js +16 -8
  102. package/workspace/public/pm/loose-props.css +13 -13
  103. package/workspace/public/pm/metric-drafts.css +82 -0
  104. package/workspace/public/pm/metric-drafts.js +165 -0
  105. package/workspace/public/pm/ms-suggest.css +8 -8
  106. package/workspace/public/pm/order-model.js +85 -0
  107. package/workspace/public/pm/ov-view.css +12 -12
  108. package/workspace/public/pm/premium-board.js +57 -11
  109. package/workspace/public/pm/premium-chart-tab.js +6 -6
  110. package/workspace/public/pm/premium-insights.js +306 -105
  111. package/workspace/public/pm/premium-report-intel.css +56 -0
  112. package/workspace/public/pm/premium-report-intel.js +232 -0
  113. package/workspace/public/pm/premium-shell.js +2 -2
  114. package/workspace/public/pm/premium-vw-file.js +2 -2
  115. package/workspace/public/pm/premium-vw-item.js +3 -1
  116. package/workspace/public/pm/premium-vw-jira.js +2 -0
  117. package/workspace/public/pm/premium.css +127 -128
  118. package/workspace/public/pm/prog-order.css +6 -6
  119. package/workspace/public/pm/prog-order.js +15 -2
  120. package/workspace/public/pm/program-charter.css +23 -23
  121. package/workspace/public/pm/rp-parts.js +2 -2
  122. package/workspace/public/pm/sort-order.css +17 -0
  123. package/workspace/public/pm/sort-order.js +108 -0
  124. package/workspace/public/pm/split-merge.css +15 -15
  125. package/workspace/public/pm/task-card.css +21 -21
  126. package/workspace/public/pm/tk-tasks.css +37 -37
  127. package/workspace/public/pm/tk-view.css +6 -6
  128. package/workspace/public/pm/tk-view.js +3 -2
  129. package/workspace/public/pm/wf-page.css +28 -28
  130. package/workspace/public/pm/wf-page.js +1 -1
  131. package/workspace/public/premium-board.html +1 -0
  132. package/workspace/public/premium-intelligence.html +82 -0
  133. package/workspace/server.js +38 -3
  134. package/workspace/skills/metric-draft.skill +47 -0
  135. package/workspace/sort-order-test.js +201 -0
  136. package/workspace/stage-card-test.js +1 -0
  137. package/workspace/task-card-test.js +1 -1
  138. package/workspace/test-lists/intel-report-ui.json +5 -0
  139. package/workspace/test-lists/intel-report.json +9 -0
  140. package/workspace/test-lists/metric-drafts-ui.json +5 -0
  141. package/workspace/test-lists/metric-drafts.json +9 -0
  142. package/workspace/test-lists/sort-order.json +6 -0
  143. package/workspace/test-lists/viewer-trail.json +5 -0
  144. package/workspace/test-run.js +3 -0
  145. package/workspace/tk-tasks-test.js +5 -3
  146. package/workspace/viewer-trail-test.js +145 -0
  147. package/workspace/public/premium-insights.html +0 -81
@@ -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 };
@@ -0,0 +1,419 @@
1
+ 'use strict';
2
+ /* intel-report.js — a report made from Intelligence (batch 15 item 4, design A+: RfA1Entry, RfA2Draft, RfA3Page, RfA4Slides, RfA5Next, RfA6Phone).
3
+ * PURE: every function reads the Intelligence model (lib/insights-premium.js build) and returns data or markdown. Nothing here writes a file.
4
+ *
5
+ * SCOPE_RE · scopeOf(source) · sourceOf(scope) a report covers the whole view, one dashboard, or one key result or outcome:
6
+ * source "intelligence:view" | "intelligence:dashboard:<id>" | "intelligence:goal:<id>" | "intelligence:outcome:<id>"
7
+ * goalsIn(model, scope) → the goals the scope covers
8
+ * storylineOf(model, { scope, ask, items }) → { answer, points, items: [{ id, kind, title, sub, on, bind }], scope, name } the draft (RfA2)
9
+ * checkStoryline(input) → { ok, storyline } | { ok: false, error } the shape the setup line keeps
10
+ * defaultsOf(findings, scope, name) → { audience, schedule, output, from } who reads it, how often and the format, from history
11
+ * proposalsOf(model, { findings, dismissed, now }) → [{ kind: found|period-end, id, text, scope, name, defaults }] the ✦ strip items (RfA1, RfA6)
12
+ * documentOf(model, setup, { slot, now, issue, prior }) → markdown one issue (RfA3; RfA5 for issue 2 and on). Frozen once issued (lib/issues.js)
13
+ * storyChecks(markdown) → [{ id, ok, text }] the five checks before it goes out (RfA2 "Checks before it goes out")
14
+ *
15
+ * THE DOCUMENT (research: Minto answer first, action titles, the Amazon WBR scorecard with comments only under misses, IBCS notation, ranges):
16
+ * # <the answer> the governing thought is the title
17
+ * three supporting points, then "Your decision · by <date>" when the PM asked for one
18
+ * ## <finding title> one section per story item; each becomes one slide (premium-report-read.js: a title slide, then one per section)
19
+ * the scorecard groups North Star, Inputs, Key results and Health budget: Now, Plan today, vs plan, vs 4 wks ago, 6 weeks, Status.
20
+ * A comment line follows only an off-plan row: Why, Next, Owner, By. The draft leaves the PM's words as "—" and the check says so.
21
+ * Forecasts are ranges: the straight lines through the last 3 to 6 readings, carried to the target date.
22
+ * "What we don't know yet" names every goal in scope with no reading. The Appendix is off unless the PM turns it on.
23
+ * Every number is a reading, a target or a line through readings. No data, no line: a goal with no reading is never given a number.
24
+ * Plan today is the straight line from the first reading to the target on its date, as the design's footnote says. */
25
+
26
+ const SCOPE_RE = /^(view|(dashboard|goal|outcome):[A-Za-z0-9._:-]{1,100})$/;
27
+ const SOURCE_RE = /^intelligence:(view|(dashboard|goal|outcome):[A-Za-z0-9._:-]{1,100})$/;
28
+ const MON = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
29
+ const DAY = 864e5;
30
+ const ITEM_KINDS = ['ask', 'scorecard', 'exhibit', 'verdict', 'unknown', 'appendix'];
31
+ const FIXED = /^(your decision|what we don.t know yet|appendix|actions from issue \d+|since issue \d+|please confirm|sources)\b/i;
32
+ const LIMITS = { answer: 200, ask: 200, who: 80, items: 12 };
33
+
34
+ const fin = (v) => typeof v === 'number' && Number.isFinite(v);
35
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
36
+ const clip = (s, n) => { s = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s; };
37
+ const dayMs = (v) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
38
+ /** 31 December 2026: a report writes a date in full (lib/report-checks.js dates-in-full). */
39
+ const full = (v) => { const t = typeof v === 'number' ? v : dayMs(v); if (t === null || !fin(t)) return ''; const d = new Date(t); return d.getUTCDate() + ' ' + MON[d.getUTCMonth()] + ' ' + d.getUTCFullYear(); };
40
+ const r2 = (v) => Math.round(v * 100) / 100;
41
+ const pctUnit = (u) => String(u || '').trim() === '%';
42
+ const fmt = (v, u) => { const s = String(r2(v)); const t = String(u || '').trim(); return t ? (/^[A-Za-z$]/.test(t) ? (t === '$' ? '$' + s : s + ' ' + t) : s + t) : s; };
43
+ /** A signed difference: "+1.2 pts" for a percentage, else the unit's own form. A minus is U+2212, as the design writes it. */
44
+ const signed = (v, u) => { if (!fin(v)) return '—'; const a = r2(Math.abs(v)); if (a === 0) return '0'; const s = v > 0 ? '+' : '−'; return s + (pctUnit(u) ? a + (a === 1 ? ' pt' : ' pts') : fmt(a, u)); };
45
+ const SPARK = '▁▂▃▄▅▆▇█';
46
+ const sparkOf = (vals) => { if (vals.length < 2) return ''; const lo = Math.min(...vals), hi = Math.max(...vals), d = hi - lo || 1; return vals.map((v) => SPARK[Math.round((v - lo) / d * 7)]).join(''); };
47
+ const q = (v) => `"${String(v == null ? '' : v).replace(/["\\]/g, "'")}"`;
48
+ const one = (s) => String(s == null ? '' : s).replace(/[\r\n]+/g, ' ').replace(/\|/g, '/').trim();
49
+
50
+ // ── scope ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
51
+ function scopeOf(source) { const m = SOURCE_RE.exec(String(source || '')); return m ? m[1] : null; }
52
+ function sourceOf(scope) { return SCOPE_RE.test(String(scope || '')) ? 'intelligence:' + scope : null; }
53
+ const isIntelligence = (source) => SOURCE_RE.test(String(source || ''));
54
+
55
+ function goalsIn(model, scope) {
56
+ const G = (model && model.goals) || [];
57
+ const s = String(scope || 'view');
58
+ if (s.startsWith('goal:')) return G.filter((g) => g.id === s.slice(5));
59
+ if (s.startsWith('outcome:')) { const o = ((model && model.outcomes) || []).find((x) => x.id === s.slice(8)); return o && o.goal ? G.filter((g) => g.id === o.goal.id) : []; }
60
+ if (s.startsWith('dashboard:')) {
61
+ const D = ((model && model.dashboards) || []).find((d) => d.id === s.slice(10));
62
+ if (!D) return [];
63
+ if (D.id === 'all') return G;
64
+ const keys = new Set(D.keys || []), ids = new Set(D.charts || []);
65
+ return G.filter((g) => ids.has(g.id) || (g.key && keys.has(g.key)));
66
+ }
67
+ return G.filter((g) => !g.program && !g.initiative && !['program-goal', 'rollup', 'success', 'signal'].includes(g.role)); // the product's own measures, as Intelligence lists them
68
+ }
69
+ function scopeName(model, scope) {
70
+ const s = String(scope || 'view');
71
+ const board = (model && model.board && model.board.name) || 'Intelligence';
72
+ if (s.startsWith('goal:')) { const g = goalsIn(model, s)[0]; return g ? clip(g.title, 60) : board; }
73
+ if (s.startsWith('outcome:')) { const o = ((model && model.outcomes) || []).find((x) => x.id === s.slice(8)); return o ? clip(o.title, 60) : board; }
74
+ if (s.startsWith('dashboard:')) { const D = ((model && model.dashboards) || []).find((d) => d.id === s.slice(10)); return D ? clip(D.name, 60) : board; }
75
+ return board;
76
+ }
77
+
78
+ // ── one goal, read for the scorecard ─────────────────────────────────────────────────────────────────────────────────────────
79
+ /** The group of a goal on the scorecard: North Star, Inputs (guardrails with them), Key results. The KR metric record's `role` says it (Intelligence,
80
+ * batch 15 item 1); a pillar named "North Star" or "Inputs" says it for an older record. */
81
+ function groupOf(g) {
82
+ const r = String(g.role || '').toLowerCase(), p = String(g.pillar || '').toLowerCase();
83
+ if (r === 'north-star' || /north star/.test(p)) return 'North Star';
84
+ if (r === 'input' || r === 'guardrail' || /^inputs?\b/.test(p)) return 'Inputs';
85
+ return 'Key results';
86
+ }
87
+ const better = (g) => (g.direction === 'down' ? -1 : g.direction === 'up' ? 1 : (fin(g.target) && fin(g.base) && g.target !== g.base ? Math.sign(g.target - g.base) : 0));
88
+ /** Plan today: the straight line from the first reading to the target on its date. null with no target, no date or no reading. */
89
+ function planToday(g) {
90
+ if (!fin(g.target) || !g.series || !g.series.length || g.type === 'Stay within' || g.type === 'Done or not') return null;
91
+ const start = fin(g.base) ? g.base : g.series[0].v;
92
+ if (!fin(g.timeGone)) return null;
93
+ return start + (g.target - start) * g.timeGone;
94
+ }
95
+ function priorOf(g, days, todayMs) {
96
+ const cut = todayMs - days * DAY;
97
+ const before = (g.series || []).filter((r) => dayMs(r.at) !== null && dayMs(r.at) <= cut);
98
+ return before.length ? before[before.length - 1].v : null;
99
+ }
100
+ /** The range a goal lands in on its date: straight lines through its last 3, 4, 5 and 6 readings, carried to the date. null with fewer than 3 readings. */
101
+ function rangeOf(g) {
102
+ const S = (g.series || []).filter((r) => dayMs(r.at) !== null), due = dayMs(g.byAt);
103
+ if (S.length < 3 || due === null || !fin(g.target)) return null;
104
+ const last = dayMs(S[S.length - 1].at);
105
+ if (due <= last) return null;
106
+ const ends = [];
107
+ for (let n = 3; n <= Math.min(6, S.length); n++) {
108
+ const a = S[S.length - n], z = S[S.length - 1], t0 = dayMs(a.at), t1 = dayMs(z.at);
109
+ if (t1 <= t0) continue;
110
+ let v = z.v + (z.v - a.v) / (t1 - t0) * (due - t1);
111
+ if (pctUnit(g.unit)) v = Math.max(0, Math.min(100, v));
112
+ ends.push(v);
113
+ }
114
+ if (!ends.length) return null;
115
+ const lo = Math.min(...ends), hi = Math.max(...ends), b = better(g);
116
+ const reaches = b > 0 ? lo >= g.target : b < 0 ? hi <= g.target : null;
117
+ return { lo, hi, by: g.byAt, reaches, n: ends.length };
118
+ }
119
+ const r1 = (v) => Math.round(v * 10) / 10;
120
+ /** A range said at one decimal, the way the design writes it: "17–19%", "≈18.2%" when the lines agree. */
121
+ const rangeTxt = (R, u) => { const a = r1(R.lo), b = r1(R.hi); return Math.abs(a - b) < 0.1 ? '≈' + fmt(a, u) : fmt(Math.min(a, b), '') + '–' + fmt(Math.max(a, b), u); };
122
+
123
+ /** One scorecard row. `off` is true for a row that needs a comment: behind its line, never reaching, or over a budget. */
124
+ function rowOf(g, todayMs) {
125
+ const u = g.unit, now = fin(g.now) ? g.now : null;
126
+ const plan = planToday(g), b = better(g);
127
+ const vs = now !== null && plan !== null ? now - plan : null;
128
+ const ago = now !== null ? priorOf(g, 28, todayMs) : null;
129
+ const last = (g.series || []).slice(-6).map((r) => r.v);
130
+ const lastMove = g.series && g.series.length >= 2 ? g.series[g.series.length - 1].v - g.series[g.series.length - 2].v : 0;
131
+ const improving = b && lastMove ? lastMove * b > 0 : null;
132
+ const late = g.tone === 'late' || g.tone === 'red' || g.state === 'drift' || g.state === 'off' || (g.pace && g.pace.tone === 'late');
133
+ const ahead = !late && vs !== null && b && vs * b > 0;
134
+ const status = now === null ? 'No reading' : late ? 'Behind' + (improving === true ? ', improving' : improving === false ? ', worsening' : '') : ahead ? 'Ahead' : g.pace && g.pace.head === 'Reached' ? 'Reached' : 'On plan';
135
+ return {
136
+ id: g.id, title: g.title, sub: g.dirTxt || '', group: groupOf(g), now, nowTxt: now !== null ? fmt(now, u) : '—', planTxt: plan !== null ? fmt(plan, u) : (fin(g.target) ? fmt(g.target, u) : '—'),
137
+ vs, vsTxt: vs === null ? '—' : Math.abs(vs) < 0.005 ? 'on plan' : signed(vs, u), good: vs === null || !b ? null : vs * b >= 0,
138
+ agoTxt: ago !== null ? signed(now - ago, u) : '—', spark: sparkOf(last), status, arrow: lastMove > 0 ? '↑' : lastMove < 0 ? '↓' : '→', off: now !== null && late, ahead,
139
+ owner: g.owner || '', unit: u, range: rangeOf(g), targetTxt: fin(g.target) ? fmt(g.target, u) : 'its target', lastAt: g.series && g.series.length ? g.series[g.series.length - 1].at : null,
140
+ };
141
+ }
142
+ function budgetRowOf(b) {
143
+ const R = b.reading;
144
+ if (!R || R.share === null || !fin(b.cap)) return null;
145
+ const share = R.share * 100, cap = b.cap * 100;
146
+ return { id: 'health:' + b.id, title: b.title, sub: 'stay within ' + r2(cap) + '%', group: 'Health budget', now: share, nowTxt: Math.round(share) + '%', planTxt: Math.round(cap) + '%',
147
+ vs: share - cap, vsTxt: share > cap ? signed(share - cap, '%') : 'within', good: share <= cap, agoTxt: '—', spark: '', status: share > cap ? 'Over' : 'Within', arrow: '', off: share > cap, ahead: false,
148
+ owner: '', unit: '%', range: null, budget: true, n: R.n, total: R.total };
149
+ }
150
+ const GROUPS = ['North Star', 'Inputs', 'Key results', 'Health budget'];
151
+ function scoreRows(model, scope) {
152
+ const todayMs = dayMs(model && model.today) || Date.now();
153
+ const rows = goalsIn(model, scope).map((g) => rowOf(g, todayMs));
154
+ if (String(scope || 'view') === 'view') for (const b of (model && model.budgets) || []) { const r = budgetRowOf(b); if (r) rows.push(r); }
155
+ return GROUPS.map((name) => ({ name, rows: rows.filter((r) => r.group === name) })).filter((x) => x.rows.length);
156
+ }
157
+
158
+ // ── the storyline (RfA2) ─────────────────────────────────────────────────────────────────────────────────────────────────────
159
+ /** The governing thought: what is ahead, what is behind and the gap, in one sentence. Made only from rows that have a reading. */
160
+ function answerOf(groups) {
161
+ const rows = groups.flatMap((g) => g.rows).filter((r) => r.now !== null);
162
+ if (!rows.length) return 'No goal here has a reading yet, so there is nothing to report';
163
+ const off = rows.filter((r) => r.off), ahead = rows.filter((r) => r.ahead);
164
+ if (!off.length) return ahead.length ? clip(ahead[0].title, 60) + ' is ahead of plan, and every other measure is on plan' : 'All ' + rows.length + (rows.length === 1 ? ' measure is' : ' measures are') + ' on plan';
165
+ const worst = off.slice().sort((a, b) => (!!a.budget - !!b.budget) || Math.abs(b.vs || 0) - Math.abs(a.vs || 0))[0]; // a measure before a budget
166
+ if (ahead.length) return clip(ahead[0].title, 60) + ' is ahead of plan; ' + clip(worst.title, 60) + ' is behind' + (worst.range && worst.range.reaches === false ? ' and will miss its target' : '');
167
+ return off.length + ' of ' + rows.length + (rows.length === 1 ? ' measure is' : ' measures are') + ' behind plan; ' + clip(worst.title, 60) + ' is furthest behind';
168
+ }
169
+ function pointOf(r) {
170
+ if (r.budget) return r.title + ' is ' + r.nowTxt + ' of open work, ' + (r.off ? 'over' : 'within') + ' its ' + r.planTxt + ' cap.';
171
+ if (r.range && r.range.reaches === false) return r.title + ' will land at ' + rangeTxt(r.range, r.unit) + ' by ' + full(r.range.by) + ', not ' + r.targetTxt + ', at this pace.';
172
+ if (r.ahead) return r.title + ' is ' + r.nowTxt + ', ' + r.vsTxt + ' above plan' + (r.agoTxt !== '—' ? ' and ' + r.agoTxt + ' in 4 weeks' : '') + '.';
173
+ if (r.off) return r.title + ' is ' + r.nowTxt + ', ' + (r.vsTxt === '—' ? 'behind its line' : r.vsTxt + ' against plan') + '.';
174
+ return r.title + ' is ' + r.nowTxt + ', on plan.';
175
+ }
176
+ function verdictsIn(model, scope) {
177
+ const ids = new Set(goalsIn(model, scope).map((g) => g.id));
178
+ return ((model && model.outcomes) || []).filter((o) => o.verdict && o.verdict.verdict && (!o.goal || ids.has(o.goal.id)) && (!String(scope).startsWith('outcome:') || o.id === String(scope).slice(8)));
179
+ }
180
+ const VERDICT_SAY = { kept: 'is kept', keep: 'is kept', iterate: 'is iterated on', revert: 'is reverted', rolled_back: 'is rolled back', retire: 'is retired' };
181
+ const verdictTitle = (o) => clip(o.title, 60) + ' ' + (VERDICT_SAY[String(o.verdict.verdict).toLowerCase()] || 'has a verdict: ' + clip(o.verdict.verdict, 30)) + (o.verdict.learned ? ': ' + clip(o.verdict.learned, 80) : '');
182
+
183
+ function storylineOf(model, opts = {}) {
184
+ const scope = SCOPE_RE.test(String(opts.scope || '')) ? opts.scope : 'view';
185
+ const groups = scoreRows(model, scope);
186
+ const rows = groups.flatMap((g) => g.rows);
187
+ const read = rows.filter((r) => r.now !== null), off = read.filter((r) => r.off);
188
+ const answer = answerOf(groups);
189
+ const points = read.slice().sort((a, b) => (b.off - a.off) || (b.ahead - a.ahead) || Math.abs(b.vs || 0) - Math.abs(a.vs || 0)).slice(0, 3).map(pointOf);
190
+ const items = [];
191
+ const ask = isObj(opts.ask) && opts.ask.text ? opts.ask : null;
192
+ items.push({ id: 'ask', kind: 'ask', title: ask ? 'Your decision: ' + clip(ask.text, 80) : 'Your decision', sub: ask ? 'the ask · ' + (ask.who || 'who?') + ' · by ' + (ask.by ? full(ask.by) : 'when?') : 'none asked yet', on: !!ask, bind: null });
193
+ if (read.length) items.push({ id: 'scorecard', kind: 'scorecard', title: off.length ? off.length + ' of ' + read.length + ' measures need attention; the rest are on or ahead of plan' : 'All ' + read.length + (read.length === 1 ? ' measure is' : ' measures are') + ' on or ahead of plan',
194
+ sub: 'scorecard · ' + groups.map((g) => g.name).join(', '), on: true, bind: { scope } });
195
+ for (const r of off.filter((x) => !x.budget).slice(0, 4)) items.push({ id: 'goal:' + r.id, kind: 'exhibit', title: r.range && r.range.reaches === false ? r.title + ' lands at ' + rangeTxt(r.range, r.unit) + ', not ' + r.targetTxt + ', at this pace' : r.title + ' is behind plan at ' + r.nowTxt,
196
+ sub: 'chart · readings' + (r.range ? ', with the range to ' + full(r.range.by) : ''), on: true, bind: { goal: r.id } });
197
+ for (const o of verdictsIn(model, scope).slice(0, 3)) items.push({ id: 'outcome:' + o.id, kind: 'verdict', title: verdictTitle(o), sub: 'Did it work? · 1 verdict', on: true, bind: { outcome: o.id } });
198
+ const none = rows.filter((r) => r.now === null);
199
+ if (none.length) items.push({ id: 'unknown', kind: 'unknown', title: "What we don't know yet: " + none.slice(0, 2).map((r) => r.title).join(', ') + (none.length > 2 ? ' and ' + (none.length - 2) + ' more' : ''), sub: 'no reading yet', on: true, bind: { goals: none.map((r) => r.id) } });
200
+ if (read.length) items.push({ id: 'appendix', kind: 'appendix', title: 'Appendix: every measure, its readings and definitions', sub: 'page 2 · for reference', on: false, bind: { scope } });
201
+ const want = new Map(((opts.items || []).filter(isObj)).map((x) => [String(x.id), !!x.on]));
202
+ for (const it of items) if (want.has(it.id) && it.kind !== 'ask') it.on = want.get(it.id);
203
+ return { scope, name: scopeName(model, scope), answer, points, items, ask };
204
+ }
205
+
206
+ /** The storyline the setup line keeps: the PM's edits only. The answer and the items are drafted again from live data at each issue. */
207
+ function checkStoryline(input) {
208
+ const x = isObj(input) ? input : {};
209
+ const out = {};
210
+ if (x.answer != null && x.answer !== '') { if (typeof x.answer !== 'string' || x.answer.trim().length > LIMITS.answer || /[\r\n]/.test(x.answer)) return { ok: false, error: `storyline.answer is one line of at most ${LIMITS.answer} characters` }; out.answer = x.answer.trim(); }
211
+ if (x.ask != null) {
212
+ if (!isObj(x.ask)) return { ok: false, error: 'storyline.ask is { text, who, by }' };
213
+ const t = String(x.ask.text || '').trim(), w = String(x.ask.who || '').trim(), b = String(x.ask.by || '').trim();
214
+ if (t) {
215
+ if (t.length > LIMITS.ask || /[\r\n]/.test(t) || w.length > LIMITS.who || /[\r\n]/.test(w)) return { ok: false, error: 'storyline.ask text and who are one line each' };
216
+ if (b && !/^\d{4}-\d{2}-\d{2}$/.test(b)) return { ok: false, error: 'storyline.ask.by is a date, YYYY-MM-DD' };
217
+ out.ask = { text: t, who: w, by: b };
218
+ }
219
+ }
220
+ if (x.items != null) {
221
+ if (!Array.isArray(x.items) || x.items.length > LIMITS.items) return { ok: false, error: `storyline.items is a list of at most ${LIMITS.items}` };
222
+ out.items = [];
223
+ for (const it of x.items) { if (!isObj(it) || typeof it.id !== 'string' || !/^[a-z]+(:[A-Za-z0-9._:-]{1,100})?$/.test(it.id)) return { ok: false, error: 'each storyline item is { id, on }' }; out.items.push({ id: it.id, on: it.on !== false }); }
224
+ }
225
+ return { ok: true, storyline: out };
226
+ }
227
+
228
+ // ── who reads it, how often, the format (RfA2 chips) ─────────────────────────────────────────────────────────────────────────
229
+ const KIND_SAY = { mail: 'email', calendar: 'meeting', slack: 'Slack message', drive: 'shared file', confluence: 'Confluence page' };
230
+ function defaultsOf(findings, scope, name) {
231
+ const f = (findings || []).find((x) => x && x.proposal && x.proposal.audience) || null;
232
+ if (f) {
233
+ const ev = f.evidence || [], kind = ev.length ? ev[0].kind : null, n = ev.filter((e) => e.kind === kind).length;
234
+ const day = f.proposal.schedule && f.proposal.schedule.day;
235
+ return { name: f.proposal.name ? clip(f.proposal.name, 80) : nameOf(name, f.proposal.schedule), audience: f.proposal.audience, schedule: f.proposal.schedule, output: f.proposal.output || 'pdf', finding: f.id,
236
+ from: kind ? { text: 'from your ' + n + ' ' + (day ? ({ Mon: 'Monday', Tue: 'Tuesday', Wed: 'Wednesday', Thu: 'Thursday', Fri: 'Friday' }[day] || '') + ' ' : '') + (KIND_SAY[kind] || 'item') + (n === 1 ? '' : 's'), why: f.why || '' } : null };
237
+ }
238
+ return { name: nameOf(name, { cadence: 'weekly' }), audience: '', schedule: { cadence: 'weekly', day: 'Mon', time: '09:00' }, output: 'pdf', finding: null, from: null };
239
+ }
240
+ /** "Checkout weekly": the scope's name and how often it goes out. */
241
+ const nameOf = (name, s) => clip((name || 'Intelligence') + ' ' + ({ daily: 'daily', weekly: 'weekly', 'bi-weekly': 'fortnightly', monthly: 'monthly' }[s && s.cadence] || 'report'), 80);
242
+
243
+ // ── the ✦ strip proposals (RfA1, RfA6) ───────────────────────────────────────────────────────────────────────────────────────
244
+ /** A report the data suggests on its own. `found`: a Library "Found in your work" pattern (the same numbers sent again and again).
245
+ * `period-end`: the goals in view reach their date within 14 days, so a review is due. "The same view opened weekly" is not proposed: no
246
+ * record of page opens is kept. `dismissed` holds the ids the PM said Not now to. */
247
+ function proposalsOf(model, { findings = [], dismissed = [], now = Date.now() } = {}) {
248
+ const out = [], no = new Set(dismissed || []);
249
+ const f = (findings || []).find((x) => x && x.proposal && x.proposal.audience && !no.has('found:' + x.id));
250
+ if (f) {
251
+ const ev = (f.evidence || [])[0];
252
+ out.push({ kind: 'found', id: 'found:' + f.id, scope: 'view', name: clip(f.name, 80), text: 'You send ' + clip(f.proposal.audience, 40) + ' these numbers ' + (f.proposal.schedule ? cadenceSay(f.proposal.schedule) : 'again and again') + '. Shall I make it a report that drafts itself?', why: ev ? clip(ev.text, 160) : clip(f.why, 160), defaults: defaultsOf([f]) });
253
+ }
254
+ const today = dayMs(new Date(now).toISOString());
255
+ const due = ((model && model.goals) || []).map((g) => dayMs(g.byAt)).filter((t) => t !== null && t >= today && t - today <= 14 * DAY);
256
+ if (due.length) {
257
+ const at = Math.min(...due), d = new Date(at), qn = Math.floor(d.getUTCMonth() / 3) + 1, id = 'period-end:' + new Date(at).toISOString().slice(0, 10);
258
+ if (!no.has(id)) out.push({ kind: 'period-end', id, scope: 'view', name: 'Q' + qn + ' ' + d.getUTCFullYear() + ' review', text: 'Q' + qn + ' ends ' + full(at) + '. Shall I draft the Q' + qn + ' review from these goals?', why: due.length + (due.length === 1 ? ' goal reaches its date' : ' goals reach their date') + ' by then.',
259
+ defaults: { audience: '', schedule: { cadence: 'monthly', dayOfMonth: 1, time: '09:00' }, output: 'google-slides', finding: null, from: null } });
260
+ }
261
+ return out;
262
+ }
263
+ function cadenceSay(s) { const D = { Mon: 'Monday', Tue: 'Tuesday', Wed: 'Wednesday', Thu: 'Thursday', Fri: 'Friday', Sat: 'Saturday', Sun: 'Sunday' }; return s.cadence === 'weekly' && D[s.day] ? 'every ' + D[s.day] : s.cadence === 'daily' ? 'every day' : s.cadence === 'monthly' ? 'every month' : s.cadence === 'bi-weekly' ? 'every two weeks' : 'often'; }
264
+
265
+ // ── the document (RfA3, RfA4, RfA5) ──────────────────────────────────────────────────────────────────────────────────────────
266
+ const MISSING = '—';
267
+ function scorecardMd(groups, source) {
268
+ const out = ['| Metric | Now | Plan today | vs plan | vs 4 wks ago | 6 weeks | Status |', '|---|---:|---:|---:|---:|---|---|'];
269
+ const notes = [];
270
+ for (const g of groups) {
271
+ out.push(`| **${g.name}** | | | | | | |`);
272
+ for (const r of g.rows) {
273
+ out.push(`| ${one(r.title)}${r.sub ? ' <br>' + one(r.sub) : ''} | ${r.nowTxt} | ${r.planTxt} | ${r.vsTxt} | ${r.agoTxt} | ${r.spark} | ${r.status}${r.arrow ? ' ' + r.arrow : ''} |`);
274
+ if (r.off) notes.push(`> **${one(r.title)}** · Why: ${MISSING} · Next: ${MISSING} · Owner: ${r.owner ? one(r.owner) : MISSING} · By: ${MISSING}`);
275
+ }
276
+ }
277
+ return { table: out.join('\n'), notes, source };
278
+ }
279
+ const sourceLine = (model, extra) => `Source: KR metric records${model && model.board && model.board.name ? ' of ' + one(model.board.name) : ''}, read ${full(model && model.today)}${extra ? '. ' + extra : ''}.`;
280
+
281
+ function exhibitMd(model, g, r) {
282
+ const S = (g.series || []).slice(-8);
283
+ const lines = [];
284
+ lines.push('| Date | Reading |', '|---|---:|');
285
+ for (const x of S) lines.push(`| ${full(x.at)} | ${fmt(x.v, g.unit)} |`);
286
+ if (fin(g.target)) lines.push(`| Target${g.byAt ? ', ' + full(g.byAt) : ''} | ${fmt(g.target, g.unit)} |`);
287
+ const L = [lines.join('\n'), ''];
288
+ if (r.range) L.push(`Expected on ${full(r.range.by)}: ${rangeTxt(r.range, g.unit)} (range: straight lines through the last 3 to ${r.range.n + 2} readings). Target ${fmt(g.target, g.unit)}.`, '');
289
+ L.push(sourceLine(model, 'Record ' + g.id));
290
+ return L.join('\n');
291
+ }
292
+
293
+ /** Actions carried from the issue before: the ask and every comment's Next, with its owner and date. Their status is the PM's to confirm. */
294
+ function actionsOf(prior) {
295
+ const out = [];
296
+ if (!prior) return out;
297
+ const t = String(prior);
298
+ const dec = /^## Your decision[^\n]*\n+([\s\S]*?)(?=\n## |\n# |(?![\s\S]))/m.exec(t);
299
+ if (dec) { const w = /Who:\s*([^·\n]+)/.exec(dec[1]), b = /By:\s*([^·\n]+)/.exec(dec[1]), a = /\*\*([^*]+)\*\*/.exec(dec[1]); if (a) out.push({ action: a[1].trim(), who: w ? w[1].trim() : MISSING, by: b ? b[1].trim() : MISSING }); }
300
+ for (const m of t.matchAll(/^> \*\*([^*]+)\*\* · Why: [^·]*· Next: ([^·]+)· Owner: ([^·]+)· By: ([^\n]+)$/gm)) {
301
+ const next = m[2].trim(); if (!next || next === MISSING) continue;
302
+ if (!out.some((x) => x.action === next && x.who === m[3].trim())) out.push({ action: next, who: m[3].trim(), by: m[4].trim() });
303
+ }
304
+ return out;
305
+ }
306
+ /** The Now of each scorecard row in the issue before, by metric title. */
307
+ function priorNows(prior) {
308
+ const m = new Map();
309
+ for (const l of String(prior || '').split('\n')) { const c = /^\| ([^|*][^|<]*?)(?: <br>[^|]*)? \| ([^|]+) \|/.exec(l); if (c && c[1] !== 'Metric' && !/^-+$/.test(c[1])) m.set(c[1].trim(), c[2].trim()); }
310
+ return m;
311
+ }
312
+
313
+ function documentOf(model, setup, opts = {}) {
314
+ const scope = scopeOf(setup.source) || 'view';
315
+ const st = isObj(setup.storyline) ? setup.storyline : {};
316
+ const S = storylineOf(model, { scope, ask: st.ask, items: st.items });
317
+ const issue = fin(opts.issue) && opts.issue > 0 ? opts.issue : 1;
318
+ const slot = opts.slot || (model && model.today) || '';
319
+ const groups = scoreRows(model, scope);
320
+ const rows = groups.flatMap((g) => g.rows);
321
+ const answer = issue === 1 && st.answer ? st.answer : S.answer;
322
+ const on = (id) => (S.items.find((x) => x.id === id) || {}).on;
323
+ const out = ['---', 'type: Reference', `title: ${q(`${setup.name} ${slot}`)}`, `description: ${q(`Issue ${issue} of ${setup.name}, drafted from Intelligence. Nothing was sent.`)}`,
324
+ `timestamp: ${String(slot).slice(0, 10)}`, `cadence: ${setup.id}`, `slot: ${slot}`, 'status: draft', `output: ${setup.output}`, `source: ${setup.source}`, 'made_by: schedule', `issue: ${issue}`, '---', '',
325
+ `# ${one(answer)}`, '', `${one(setup.name)} · Issue ${issue} · ${full(slot)}${setup.audience ? ' · for ' + one(setup.audience) : ''}`, ''];
326
+ S.points.forEach((p, i) => out.push(`${i + 1}. ${one(p)}`));
327
+ out.push('');
328
+ const prior = opts.prior || null;
329
+ if (issue > 1) {
330
+ const acts = actionsOf(prior);
331
+ out.push(`## Actions from issue ${issue - 1}`, '');
332
+ if (acts.length) { out.push('| Action | Who | Due | Status |', '|---|---|---|---|'); for (const a of acts) out.push(`| ${one(a.action)} | ${one(a.who)} | ${one(a.by)} | please confirm |`); }
333
+ else out.push(`Issue ${issue - 1} carried no action.`);
334
+ out.push('');
335
+ const P = priorNows(prior), moved = rows.filter((r) => r.now !== null && P.has(one(r.title)) && P.get(one(r.title)) !== r.nowTxt);
336
+ out.push(`## Since issue ${issue - 1}`, '');
337
+ if (moved.length) for (const r of moved) out.push(`- ${one(r.title)}: ${P.get(one(r.title))} → ${r.nowTxt}.`);
338
+ else out.push(`No measure moved since issue ${issue - 1}.`);
339
+ out.push('');
340
+ const todayMs = dayMs(model && model.today) || Date.now();
341
+ const stale = rows.filter((r) => !r.off && r.lastAt && todayMs - dayMs(r.lastAt) > 14 * DAY);
342
+ if (stale.length) { out.push('## Please confirm', ''); for (const r of stale) out.push(`- ${one(r.title)} shows ${r.status.toLowerCase()}, but its last reading is from ${full(r.lastAt)}. Is it still true?`); out.push(''); }
343
+ }
344
+ if (S.ask && on('ask')) out.push('## Your decision · by ' + (S.ask.by ? full(S.ask.by) : MISSING), '', `**${one(S.ask.text)}**`, '', `Who: ${S.ask.who ? one(S.ask.who) : MISSING} · By: ${S.ask.by ? full(S.ask.by) : MISSING}`, '');
345
+ for (const it of S.items) {
346
+ if (!it.on || it.kind === 'ask') continue;
347
+ if (it.kind === 'scorecard') {
348
+ const sc = scorecardMd(groups);
349
+ out.push(`## ${one(it.title)}`, '', sc.table, '');
350
+ if (sc.notes.length) out.push(sc.notes.join('\n\n'), '');
351
+ out.push('Plan today is the straight line from the first reading to the target on its date.', '', sourceLine(model), '');
352
+ } else if (it.kind === 'exhibit') {
353
+ const g = (model.goals || []).find((x) => x.id === it.bind.goal), r = rows.find((x) => x.id === it.bind.goal);
354
+ if (!g || !r) continue;
355
+ out.push(`## ${one(it.title)}`, '', exhibitMd(model, g, r), '');
356
+ } else if (it.kind === 'verdict') {
357
+ const o = (model.outcomes || []).find((x) => x.id === it.bind.outcome);
358
+ if (!o) continue;
359
+ out.push(`## ${one(it.title)}`, '', '| Shipped | Promised | Got | Verdict |', '|---|---|---|---|',
360
+ `| ${one(o.title)} | ${o.goal ? one(o.goal.title) + ' to ' + (o.goal.targetTxt || MISSING) : MISSING} | ${o.goal && o.goal.nowTxt ? one(o.goal.nowTxt) : MISSING} | ${one(o.verdict.verdict)} |`, '',
361
+ `Source: the verdict recorded ${o.verdict.at ? full(o.verdict.at) : ''} on the initiative ${one(o.id)}.`, '');
362
+ } else if (it.kind === 'unknown') {
363
+ const ids = new Set(it.bind.goals || []);
364
+ out.push("## What we don't know yet", '');
365
+ for (const r of rows.filter((x) => ids.has(x.id))) out.push(`- ${one(r.title)} has no reading yet, so it is not counted as on track.`);
366
+ out.push('', sourceLine(model), '');
367
+ } else if (it.kind === 'appendix') {
368
+ out.push('## Appendix', '');
369
+ for (const g of goalsIn(model, scope)) {
370
+ out.push(`### ${one(g.title)}`, '', `- Direction: ${g.dirTxt || MISSING}`, `- Target: ${fin(g.target) ? fmt(g.target, g.unit) : MISSING}${g.byAt ? ' by ' + full(g.byAt) : ''}`, `- Readings: ${(g.series || []).length}${g.series && g.series.length ? ', ' + full(g.series[0].at) + ' to ' + full(g.series[g.series.length - 1].at) : ''}`, `- Record: ${one(g.id)}`, '');
371
+ }
372
+ out.push(sourceLine(model), '');
373
+ }
374
+ }
375
+ out.push('Every number is frozen when this issue goes out. Changes go into the next issue.', '');
376
+ return out.join('\n');
377
+ }
378
+
379
+ // ── the five checks before it goes out ───────────────────────────────────────────────────────────────────────────────────────
380
+ const body = (t) => String(t || '').replace(/\r/g, '').replace(/^---\n[\s\S]*?\n---\n?/, '');
381
+ function sections(text) {
382
+ const out = []; let cur = null;
383
+ for (const l of body(text).split('\n')) { const h = /^##\s+(.*)$/.exec(l); if (h) { cur = { h: h[1].trim(), lines: [] }; out.push(cur); continue; } if (cur) cur.lines.push(l); }
384
+ return out;
385
+ }
386
+ const LABEL_ONLY = /^(scorecard|metrics?|overview|summary|kpis?|status|update|charts?|data|details?|results?|goals?|okrs?|key results|numbers|highlights|section \d+)$/i;
387
+ /** A finding title says what is true: five words or more, or a number, and not a bare label. */
388
+ const isFinding = (h) => !LABEL_ONLY.test(h.trim()) && (h.trim().split(/\s+/).length >= 5 || /\d/.test(h));
389
+ const hasFig = (l) => /\d/.test(l.replace(/\b\d{1,2} (January|February|March|April|May|June|July|August|September|October|November|December) \d{4}\b/g, '').replace(/\b\d{4}-\d{2}-\d{2}\b/g, '').replace(/^\s*\d+\.\s/, '').replace(/issue \d+/gi, ''));
390
+
391
+ function storyChecks(markdown) {
392
+ const B = body(markdown).split('\n').map((l) => l.trim()).filter(Boolean);
393
+ const S = sections(markdown);
394
+ const out = [];
395
+ // 1 · the answer first
396
+ const h1 = B[0] && /^#\s+(.+)$/.exec(B[0]);
397
+ out.push(h1 && isFinding(h1[1]) ? { id: 'answer', ok: true, text: 'The answer comes first, in one sentence' } : { id: 'answer', ok: false, text: h1 ? 'The title is a label, not the answer. Say what is true in one sentence' : 'The report does not open on its answer' });
398
+ // 2 · every title is a finding
399
+ const labels = S.filter((s) => !FIXED.test(s.h) && !isFinding(s.h)).map((s) => s.h);
400
+ out.push(labels.length ? { id: 'titles', ok: false, text: (labels.length === 1 ? '1 title is a label: ' : labels.length + ' titles are labels: ') + labels.slice(0, 2).join(', ') } : { id: 'titles', ok: true, text: 'Every title says the finding' });
401
+ // 3 · every number has a comparison and a source
402
+ const bare = S.filter((s) => !/^(your decision|actions from|appendix)/i.test(s.h) && s.lines.some(hasFig) && !s.lines.some((l) => /^source:/i.test(l.trim()))).map((s) => s.h);
403
+ out.push(bare.length ? { id: 'numbers', ok: false, text: (bare.length === 1 ? '1 section has numbers with no source: ' : bare.length + ' sections have numbers with no source: ') + bare.slice(0, 2).join(', ') } : { id: 'numbers', ok: true, text: 'Every number has a comparison and a source' });
404
+ // 4 · every miss has why, next step and owner
405
+ const notes = [...body(markdown).matchAll(/^> \*\*([^*]+)\*\* · Why: ([^·]*)· Next: ([^·]*)· Owner: ([^·]*)· By: (.*)$/gm)];
406
+ const open = [...new Set(notes.filter((m) => [m[2], m[3], m[4], m[5]].some((v) => !v.trim() || v.trim() === MISSING)).map((m) => m[1].trim()))];
407
+ out.push(open.length ? { id: 'misses', ok: false, text: (open.length === 1 ? '1 miss needs' : open.length + ' misses need') + ' why, next step and owner: ' + open.slice(0, 2).join(', ') } : { id: 'misses', ok: true, text: notes.length ? 'Every miss has why, next step and owner' : 'No measure is off plan, so no miss needs a comment' });
408
+ // 5 · every ask has who and by when
409
+ const dec = S.find((s) => /^your decision/i.test(s.h));
410
+ if (!dec) out.push({ id: 'asks', ok: true, text: 'No decision is asked' });
411
+ else {
412
+ const t = dec.lines.join(' '), who = /Who:\s*([^·]+)/.exec(t), by = /By:\s*(.+)$/.exec(t);
413
+ const okWho = who && who[1].trim() && who[1].trim() !== MISSING, okBy = by && by[1].trim() && by[1].trim() !== MISSING;
414
+ out.push(okWho && okBy ? { id: 'asks', ok: true, text: 'Every ask has who and by when' } : { id: 'asks', ok: false, text: 'The decision needs ' + [okWho ? '' : 'who', okBy ? '' : 'by when'].filter(Boolean).join(' and ') });
415
+ }
416
+ return out;
417
+ }
418
+
419
+ module.exports = { SCOPE_RE, SOURCE_RE, ITEM_KINDS, scopeOf, sourceOf, isIntelligence, goalsIn, scopeName, scoreRows, storylineOf, checkStoryline, defaultsOf, proposalsOf, documentOf, storyChecks, actionsOf, rangeOf, planToday };