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,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 };
@@ -0,0 +1,193 @@
1
+ 'use strict';
2
+ /* metric-draft-runs.js — Claude's runs that draft metrics without being asked (batch 15 item 1; lib/metric-drafts.js, contract metric-drafts-contract.md).
3
+ *
4
+ * off(env) → true when PMOS_METRIC_DRAFT=off (or 0, false, no)
5
+ * quarterOf(day) → { start, end, prevStart, prevEnd } of the quarter `day` (YYYY-MM-DD) is in
6
+ * dueOf(o) PURE → [{ scope, id, why, title }] the scopes of one workspace that need a draft now, in the order they start
7
+ * promptOf(skill, o) → the prompt of one run. o: { run, scope, id, why, title, today, facts: [line], kept: [line], dropped: [line] }
8
+ * create(deps) → { tick(opts), start({ ws, scope, id, why, press, now }), stop(run), active() }
9
+ *
10
+ * WHEN A RUN STARTS (headless kind `metric-draft`, origin `metric-draft:<ws>:<scope>:<id>:<run>`), with no press:
11
+ * north-star the product (the workspace) has no kr-metrics record with role north-star
12
+ * quarter the first 14 days of a quarter, once that quarter, when the last quarter had key results (role kr) to learn from
13
+ * goal a program charter (in this workspace) has no goal and no kr-metrics record with role program-goal for it
14
+ * success an initiative has a PRD and no kr-metrics record with initiative: <id>. The first scan writes the epoch: an initiative that
15
+ * had its PRD then is history, so only one that gets its PRD later is drafted unasked (the PM can press Draft again on any)
16
+ * A scope that was drafted once is not drafted again unasked; one whose last run failed tries again the next day. A retired record counts
17
+ * as no record. "Draft again" (POST /api/metric-drafts/start) starts a run at once, why `press`.
18
+ *
19
+ * WHAT THE RUN MAY DO (lib/headless.js kind `metric-draft`): read and search the repository and the stored reads, read through the PM's own
20
+ * connectors where the PM's Claude Code settings allow it, and file with `pmos metrics draft`, pinned by the server to this scope and run
21
+ * (PMOS_METRIC_DRAFT_FILE, _WS, _SCOPE, _ID, _RUN). It writes no record: only the PM's ✓ keep does. Nothing is sent.
22
+ *
23
+ * At most 2 runs at once for the machine; one per scope id; the scan of a workspace at most every 10 minutes. ■ Stop ends a run at once.
24
+ *
25
+ * deps: { workspaces() → [w], isLead(w), stateDirFor(w), records(w) → [kr-metrics record], programs(w) → [{ id, title, goal, milestones,
26
+ * members }] (the charters in this workspace), initiatives(w) → [{ id, title }] (those with a PRD), titleOf(w, scope, id) → string,
27
+ * facts(w, scope, id) → [line] (what the server knows: the charter, the PRD path, the members), open(now) → bool (the day-check
28
+ * window), headlessOff() → bool, env, promptFor(skillId) → skill body | null, spawn(spec), spawnNow(spec), stop(session), warn(what, err) }
29
+ */
30
+ const crypto = require('crypto');
31
+ const MD = require('./metric-drafts.js');
32
+
33
+ const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
34
+ const off = (env) => flagOff((env || process.env).PMOS_METRIC_DRAFT);
35
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
36
+ const MAX = 2;
37
+ const SCAN_MS = 10 * 60e3;
38
+ const QUARTER_DAYS = 14;
39
+ const localDay = (ms) => { const d = new Date(ms); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
40
+ const p2 = (n) => String(n).padStart(2, '0');
41
+ const lastDay = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate(); // m is 1..12
42
+
43
+ /** The quarter `day` is in, and the one before it. */
44
+ function quarterOf(day) {
45
+ const m = /^(\d{4})-(\d{2})/.exec(String(day || '')); if (!m) return null;
46
+ const y = +m[1], q0 = Math.floor((+m[2] - 1) / 3) * 3 + 1, py = q0 === 1 ? y - 1 : y, pq = q0 === 1 ? 10 : q0 - 3;
47
+ return { start: `${y}-${p2(q0)}-01`, end: `${y}-${p2(q0 + 2)}-${p2(lastDay(y, q0 + 2))}`, prevStart: `${py}-${p2(pq)}-01`, prevEnd: `${py}-${p2(pq + 2)}-${p2(lastDay(py, pq + 2))}` };
48
+ }
49
+ const live = (records) => (records || []).filter((r) => r && r.retired !== true);
50
+ /** Unasked, a scope is drafted once; a failed run tries again on a later day. */
51
+ function mayDraft(s, why, day) {
52
+ const runs = s ? s.runs.filter((r) => why === 'quarter' ? r.why === 'quarter' : r.why !== 'quarter') : [];
53
+ const last = runs[runs.length - 1];
54
+ if (!last) return true;
55
+ if (!last.ended) return false;
56
+ return !last.ok && !last.stopped && String(last.at).slice(0, 10) !== day;
57
+ }
58
+
59
+ /**
60
+ * PURE. The scopes of one workspace that need a draft now.
61
+ * o: { ws, records: [kr-metrics], programs: [{ id, title, goal }], initiatives: [{ id, title }], F (the fold), today (YYYY-MM-DD local) }
62
+ */
63
+ function dueOf(o) {
64
+ const out = [], F = o.F || { scopes: new Map(), epoch: null }, R = live(o.records), day = o.today;
65
+ const sOf = (scope, id) => F.scopes.get(MD.keyOf(scope, id));
66
+ if (!R.some((r) => r.role === 'north-star') && mayDraft(sOf('product', o.ws), 'north-star', day)) out.push({ scope: 'product', id: o.ws, why: 'north-star', title: o.wsTitle || o.ws });
67
+ const Q = quarterOf(day);
68
+ if (Q && day <= addDays(Q.start, QUARTER_DAYS - 1) && R.some((r) => r.role === 'kr' && r.by >= Q.prevStart && r.by <= Q.prevEnd)) {
69
+ const s = sOf('product', o.ws), done = s && s.runs.some((r) => r.why === 'quarter' && String(r.at).slice(0, 10) >= Q.start && (r.ok || !r.ended || String(r.at).slice(0, 10) === day));
70
+ if (!done && !out.some((x) => x.scope === 'product')) out.push({ scope: 'product', id: o.ws, why: 'quarter', title: o.wsTitle || o.ws });
71
+ }
72
+ for (const p of o.programs || []) {
73
+ if (!p || !p.id || one(p.goal, 200)) continue;
74
+ if (R.some((r) => r.program === p.id && r.role === 'program-goal')) continue;
75
+ if (mayDraft(sOf('program', p.id), 'goal', day)) out.push({ scope: 'program', id: p.id, why: 'goal', title: p.title || p.id });
76
+ }
77
+ const known = new Set((F.epoch && F.epoch.known) || []);
78
+ if (F.epoch) for (const i of o.initiatives || []) {
79
+ if (!i || !i.id || known.has(i.id)) continue;
80
+ if (R.some((r) => r.initiative === i.id)) continue;
81
+ if (mayDraft(sOf('initiative', i.id), 'success', day)) out.push({ scope: 'initiative', id: i.id, why: 'success', title: i.title || i.id });
82
+ }
83
+ return out;
84
+ }
85
+ function addDays(day, n) { const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day); const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3] + n)); return d.toISOString().slice(0, 10); }
86
+
87
+ const SHAPE = {
88
+ product: 'a North Star (1), Inputs (at most 3) and Guardrails (at most 2)',
89
+ quarter: 'next quarter\'s Key results (at most 5), from how the last quarter ended',
90
+ program: 'a Program goal (1, with checkpoints at its milestones), Rolls up from (one per product) and a Guardrail (at most 1)',
91
+ initiative: 'Proves it worked (1, read 4 weeks after release), an Early signal (at most 1) and a Guardrail (at most 1)',
92
+ };
93
+ function promptOf(skill, o) {
94
+ const list = (a, none) => (a && a.length ? a.map((x) => '- ' + x).join('\n') : '- ' + none);
95
+ const shape = o.why === 'quarter' ? SHAPE.quarter : SHAPE[o.scope];
96
+ return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Scope: ${o.scope} ${o.id} · ${one(o.title, 140)}\n- Why it runs: ${MD.WHEN[o.why] || MD.WHEN.press} (${o.why})\n- Today: ${o.today}\n`
97
+ + `- Draft: ${shape}. Groups: ${(o.why === 'quarter' ? ['Key results'] : MD.GROUPS[o.scope].filter((g) => g !== 'Key results')).join(', ')}.\n`
98
+ + `- What PMOS knows:\n${list(o.facts, 'nothing more')}\n`
99
+ + `- Already kept by the PM (do not draft these again):\n${list(o.kept, 'none')}\n`
100
+ + `- Dropped by the PM (do not draft these again unless the evidence is new):\n${list(o.dropped, 'none')}\n\n`
101
+ + 'File with `pmos metrics draft` only (the server pins this scope and run). Write no record. Send nothing.';
102
+ }
103
+
104
+ function create(deps) {
105
+ const active = new Map(); // run → { ws, scope, id, dir, session }
106
+ const warn = deps.warn || (() => {});
107
+ const lastScan = new Map(); // ws → ms
108
+
109
+ function ended(run, r, now = Date.now()) {
110
+ const a = active.get(run); if (!a) return;
111
+ active.delete(run);
112
+ const s = MD.read(a.dir).scopes.get(MD.keyOf(a.scope, a.id));
113
+ if (!s || !s.run || s.run.run !== run || s.run.ended) return; // `pmos metrics draft end` or ■ Stop wrote it already
114
+ const res = (r && r.result) || {};
115
+ const ok = !!(r && !r.timedOut && !r.stopped && r.code === 0 && res.ok !== false && !res.isError);
116
+ try { MD.append(a.dir, null, { kind: 'end', scope: a.scope, id: a.id, run, ok, ...(ok ? {} : { error: one((r && r.note) || res.text || 'the run failed', 200) }) }, new Date(now).toISOString()); } catch (e) { warn('metric draft end', e); }
117
+ }
118
+
119
+ /** Start one run now. → { ok, run } | { ok: false, error, held? } */
120
+ function start({ ws, scope, id, why = 'press', press = true, now = Date.now() } = {}) {
121
+ if (off(deps.env) || (deps.headlessOff && deps.headlessOff())) return { ok: false, error: 'Claude\'s metric drafts are off (PMOS_METRIC_DRAFT or PMOS_HEADLESS).' };
122
+ if (!MD.SCOPES.includes(scope) || !id) return { ok: false, error: 'Say which product, program or initiative to draft for.' };
123
+ const w = (deps.workspaces() || []).find((x) => x.id === ws);
124
+ if (!w) return { ok: false, error: 'no such workspace' };
125
+ const dir = deps.stateDirFor(w);
126
+ if (!dir) return { ok: false, error: 'This repository has no PMOS state folder, so nothing can be drafted.' };
127
+ for (const [r, a] of active) if (a.ws === ws && a.scope === scope && a.id === id) return { ok: true, run: r, already: true };
128
+ if (active.size >= MAX) return { ok: false, held: true, error: 'Claude is drafting two others now. It drafts this one when one ends.' };
129
+ const skill = deps.promptFor('metric-draft');
130
+ if (!skill) return { ok: false, error: 'The metric-draft skill is not installed.' };
131
+ const run = 'md' + now.toString(36) + crypto.randomBytes(3).toString('hex');
132
+ const title = one((deps.titleOf && deps.titleOf(w, scope, id)) || id, 140);
133
+ const s = MD.read(dir).scopes.get(MD.keyOf(scope, id));
134
+ const rows = s ? [...s.rows.values()] : [];
135
+ const line = (r) => r.group + ' · ' + r.name + (r.targetTxt ? ' · ' + r.targetTxt : '');
136
+ let facts = [];
137
+ try { facts = (deps.facts && deps.facts(w, scope, id)) || []; } catch { facts = []; }
138
+ const prompt = promptOf(skill, { run, scope, id, why, title, today: localDay(now), facts, kept: rows.filter((r) => r.state === 'kept').map(line), dropped: rows.filter((r) => r.state === 'dropped').map(line) });
139
+ const go = press && deps.spawnNow ? deps.spawnNow : deps.spawn;
140
+ active.set(run, { ws, scope, id, dir, session: null });
141
+ let session = null;
142
+ try {
143
+ session = go({ name: 'Drafting metrics · ' + one(title, 60), ws, origin: `metric-draft:${ws}:${scope}:${id}:${run}`, initialInput: prompt + '\r', ...(scope === 'initiative' ? { initiative: id } : {}),
144
+ env: { PMOS_METRIC_DRAFT_FILE: MD.ledgerFile(dir), PMOS_METRIC_DRAFT_WS: ws, PMOS_METRIC_DRAFT_SCOPE: scope, PMOS_METRIC_DRAFT_ID: id, PMOS_METRIC_DRAFT_RUN: run }, onDone: (r) => ended(run, r) });
145
+ } catch (e) { warn('metric draft run', e); }
146
+ if (session && session.held) { active.delete(run); return { ok: false, held: true, error: 'Claude is busy with other runs. It tries again in a minute.' }; }
147
+ // the start line lands before the run's first `pmos metrics draft` (the run starts reading after this returns), stamped with the tick's clock
148
+ MD.append(dir, null, { kind: 'start', scope, id, run, why, title, when: MD.WHEN[why] || '' }, new Date(now).toISOString());
149
+ if (!session || session.state === 'exited' || session.headless !== 'metric-draft') {
150
+ if (session && session.headless !== 'metric-draft' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
151
+ ended(run, { code: 1, note: (session && session.note) || 'the run could not start in the background', result: {} }, now);
152
+ return { ok: false, error: (session && session.note) || 'Claude could not start drafting.' };
153
+ }
154
+ const a = active.get(run); if (a) a.session = session;
155
+ return { ok: true, run };
156
+ }
157
+
158
+ function stop(run) { const a = active.get(run); if (a && a.session && deps.stop) deps.stop(a.session); }
159
+
160
+ function tick({ now = Date.now(), env } = {}) {
161
+ if (off(env || deps.env) || (deps.headlessOff && deps.headlessOff())) return { off: true };
162
+ if (active.size >= MAX) return { running: active.size };
163
+ let open = true;
164
+ try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
165
+ if (!open) return { started: null, closed: true };
166
+ const day = localDay(now);
167
+ for (const w of deps.workspaces() || []) {
168
+ if (deps.isLead && !deps.isLead(w)) continue;
169
+ if (now - (lastScan.get(w.id) || -Infinity) < SCAN_MS) continue;
170
+ const dir = deps.stateDirFor(w); if (!dir) continue;
171
+ lastScan.set(w.id, now);
172
+ const F = MD.read(dir);
173
+ let records = [], programs = [], initiatives = [];
174
+ try { records = deps.records(w) || []; } catch (e) { warn('metric draft records', e); continue; }
175
+ try { programs = (deps.programs && deps.programs(w)) || []; } catch { programs = []; }
176
+ try { initiatives = (deps.initiatives && deps.initiatives(w)) || []; } catch { initiatives = []; }
177
+ // the first scan writes the epoch: the initiatives that have a PRD now are history (an old PRD is not a new one)
178
+ if (!F.epoch) { MD.append(dir, null, { kind: 'epoch', scope: null, id: null, known: initiatives.map((i) => i.id) }, new Date(now).toISOString()); F.epoch = { known: initiatives.map((i) => i.id) }; }
179
+ const due = dueOf({ ws: w.id, wsTitle: w.name || w.id, records, programs, initiatives, F, today: day });
180
+ for (const d of due) {
181
+ if ([...active.values()].some((a) => a.ws === w.id && a.scope === d.scope && a.id === d.id)) continue;
182
+ const r = start({ ws: w.id, scope: d.scope, id: d.id, why: d.why, press: false, now });
183
+ if (r.ok) return { started: d.scope + ':' + d.id, why: d.why };
184
+ if (r.held) { lastScan.delete(w.id); return { held: true }; }
185
+ }
186
+ }
187
+ return { started: null };
188
+ }
189
+
190
+ return { tick, start, stop, active: () => [...active.keys()], runOf: (ws, scope, id) => { for (const [r, a] of active) if (a.ws === ws && a.scope === scope && a.id === id) return r; return null; } };
191
+ }
192
+
193
+ module.exports = { off, quarterOf, dueOf, promptOf, create, MAX, SCAN_MS, QUARTER_DAYS };