create-pmos 0.397.0 → 0.398.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 (145) hide show
  1. package/package.json +13 -13
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-adddoc-test.js +101 -52
  8. package/workspace/briefing-premium-board-test.js +252 -128
  9. package/workspace/briefing-premium-calendar-2-test.js +135 -198
  10. package/workspace/briefing-premium-calendar-3-test.js +143 -418
  11. package/workspace/briefing-premium-calendar-test.js +86 -196
  12. package/workspace/briefing-premium-doc-edit-test.js +95 -83
  13. package/workspace/briefing-premium-initiative-test.js +159 -296
  14. package/workspace/briefing-premium-insights-test.js +337 -219
  15. package/workspace/briefing-premium-metrics-test.js +53 -97
  16. package/workspace/briefing-premium-products-test.js +40 -27
  17. package/workspace/briefing-premium-sources-test.js +66 -48
  18. package/workspace/briefing-premium-test.js +150 -647
  19. package/workspace/briefing-premium-work-test.js +88 -283
  20. package/workspace/changelog.json +12 -0
  21. package/workspace/fixtures/board-premium-trail.js +32 -0
  22. package/workspace/fixtures/premium-viewer-fixtures.js +182 -0
  23. package/workspace/guide/briefing-premium.md +3 -1
  24. package/workspace/guide/home.md +47 -0
  25. package/workspace/guide/index.md +1 -0
  26. package/workspace/lib/agent-roles.js +71 -0
  27. package/workspace/lib/board-premium.js +85 -19
  28. package/workspace/lib/board-trail.js +223 -0
  29. package/workspace/lib/home-work-item.js +58 -0
  30. package/workspace/lib/insights-goals.js +196 -0
  31. package/workspace/lib/insights-premium.js +62 -14
  32. package/workspace/lib/insights-records.js +101 -0
  33. package/workspace/lib/jira-tickets.js +1 -1
  34. package/workspace/lib/route-modules.js +4 -0
  35. package/workspace/lib/routes-board-trail.js +33 -0
  36. package/workspace/lib/routes-home-desk.js +176 -0
  37. package/workspace/lib/routes-insights-premium.js +12 -3
  38. package/workspace/lib/routes-insights-records.js +129 -0
  39. package/workspace/lib/routes-notes.js +1 -0
  40. package/workspace/lib/routes-viewer.js +108 -0
  41. package/workspace/lib/transcript-steps.js +123 -0
  42. package/workspace/lib/viewer-meeting.js +205 -0
  43. package/workspace/lib/viewer-report.js +89 -0
  44. package/workspace/package-lock.json +2 -2
  45. package/workspace/package.json +1 -1
  46. package/workspace/premium-board-actions-test.js +85 -75
  47. package/workspace/premium-briefing-depth-test.js +66 -53
  48. package/workspace/premium-chat-attach-test.js +54 -63
  49. package/workspace/premium-chat-chart-tab-test.js +35 -37
  50. package/workspace/premium-chat-context-test.js +19 -18
  51. package/workspace/premium-chat-goal-view-test.js +23 -23
  52. package/workspace/premium-chat-notes-test.js +26 -31
  53. package/workspace/premium-chat-report-tab-test.js +32 -28
  54. package/workspace/premium-chat-term-test.js +16 -16
  55. package/workspace/premium-chat-viewer-test.js +60 -59
  56. package/workspace/premium-core-doc-issue-test.js +50 -43
  57. package/workspace/premium-html-viewer-test.js +14 -17
  58. package/workspace/premium-phone-card-test.js +7 -2
  59. package/workspace/premium-phone-room-test.js +41 -35
  60. package/workspace/premium-report-read-test.js +115 -197
  61. package/workspace/premium-viewer-download-test.js +19 -22
  62. package/workspace/premium-viewer-flicker-test.js +11 -16
  63. package/workspace/premium-viewer-share-test.js +6 -9
  64. package/workspace/premium-viewer-test.js +41 -60
  65. package/workspace/premium-vw-backlog-test.js +53 -33
  66. package/workspace/premium-vw-cal-test.js +82 -128
  67. package/workspace/premium-vw-copy-test.js +17 -33
  68. package/workspace/premium-vw-doc-test.js +11 -10
  69. package/workspace/premium-vw-item-test.js +50 -49
  70. package/workspace/premium-vw-jira-test.js +53 -27
  71. package/workspace/premium-vw-meet-test.js +118 -187
  72. package/workspace/premium-vw-notes-test.js +85 -108
  73. package/workspace/premium-vw-rec-test.js +72 -194
  74. package/workspace/premium-vw-slides-test.js +46 -50
  75. package/workspace/premium-welcome-test.js +3 -2
  76. package/workspace/premium-work-depth-test.js +61 -53
  77. package/workspace/public/pm/bd-acts.js +305 -0
  78. package/workspace/public/pm/bd-span.js +186 -82
  79. package/workspace/public/pm/bd-stages.js +25 -11
  80. package/workspace/public/pm/c3-doc-sheet.js +1 -1
  81. package/workspace/public/pm/c3-md.js +3 -395
  82. package/workspace/public/pm/c3-phone-detail.js +1 -1
  83. package/workspace/public/pm/c3-phone-model.js +3 -68
  84. package/workspace/public/pm/chat-term.js +3 -3
  85. package/workspace/public/pm/cozy-board.css +497 -230
  86. package/workspace/public/pm/cozy-home.css +570 -142
  87. package/workspace/public/pm/cozy-home.js +5 -3
  88. package/workspace/public/pm/cozy-insights.css +296 -167
  89. package/workspace/public/pm/cozy-md.js +396 -0
  90. package/workspace/public/pm/cozy-nav.js +17 -6
  91. package/workspace/public/pm/cozy-placeholder.js +26 -0
  92. package/workspace/public/pm/cozy-viewer.css +3 -3
  93. package/workspace/public/pm/cozy-viewer.js +144 -0
  94. package/workspace/public/pm/cozy-vw.css +485 -0
  95. package/workspace/public/pm/cozy.css +83 -1
  96. package/workspace/public/pm/home-adddoc.js +48 -0
  97. package/workspace/public/pm/home-app.js +905 -0
  98. package/workspace/public/pm/home-around.js +515 -0
  99. package/workspace/public/pm/home-chat.js +459 -0
  100. package/workspace/public/pm/home-data.js +312 -0
  101. package/workspace/public/pm/home-draft.js +68 -0
  102. package/workspace/public/pm/home-more.js +249 -0
  103. package/workspace/public/pm/home-phone-card.js +109 -0
  104. package/workspace/public/pm/home-work.js +519 -0
  105. package/workspace/public/pm/phone-moment.js +69 -0
  106. package/workspace/public/pm/pm-work-view.js +1 -1
  107. package/workspace/public/pm/premium-attach.js +4 -0
  108. package/workspace/public/pm/premium-board.js +423 -394
  109. package/workspace/public/pm/premium-chart-tab.js +110 -62
  110. package/workspace/public/pm/premium-deck.js +3 -3
  111. package/workspace/public/pm/premium-first.js +25 -21
  112. package/workspace/public/pm/premium-insights.js +792 -568
  113. package/workspace/public/pm/premium-meeting.js +61 -549
  114. package/workspace/public/pm/premium-notes.js +1 -1
  115. package/workspace/public/pm/premium-report-frame.css +20 -0
  116. package/workspace/public/pm/premium-report-read.js +509 -480
  117. package/workspace/public/pm/premium-report-tab.js +87 -63
  118. package/workspace/public/pm/premium-shell.js +72 -119
  119. package/workspace/public/pm/premium-viewer.js +22 -1
  120. package/workspace/public/pm/premium-vw-cal.js +187 -48
  121. package/workspace/public/pm/premium-vw-doc.css +6 -0
  122. package/workspace/public/pm/premium-vw-doc.js +40 -2
  123. package/workspace/public/pm/premium-vw-file.js +2 -2
  124. package/workspace/public/pm/premium-vw-meet.js +6 -83
  125. package/workspace/public/pm/premium-vw-mtg.js +731 -0
  126. package/workspace/public/pm/premium-vw-notes.js +56 -69
  127. package/workspace/public/pm/premium-vw-open.js +35 -0
  128. package/workspace/public/pm/premium-vw-page.js +16 -0
  129. package/workspace/public/pm/premium-vw-rec.js +11 -218
  130. package/workspace/public/pm/premium-vw-slides.css +5 -0
  131. package/workspace/public/pm/premium-vw-slides.js +44 -8
  132. package/workspace/public/pm/term-view.js +22 -0
  133. package/workspace/public/premium-board.html +28 -70
  134. package/workspace/public/premium-initiative.html +8 -48
  135. package/workspace/public/premium-insights.html +22 -60
  136. package/workspace/public/premium-viewer.html +20 -0
  137. package/workspace/public/premium.html +16 -107
  138. package/workspace/server.js +18 -3
  139. package/workspace/test-files.json +1 -0
  140. package/workspace/test-lists/home-libs.json +9 -0
  141. package/workspace/test-lists/premium-report-read.json +1 -1
  142. package/workspace/test-lists/premium-vw-agreed.json +9 -0
  143. package/workspace/test-lists/premium-vw-notes.json +1 -1
  144. package/workspace/public/pm/premium-work.js +0 -729
  145. package/workspace/public/pm/premium.js +0 -1146
@@ -0,0 +1,223 @@
1
+ 'use strict';
2
+ /* board-trail.js — what the Agreed Board draws beside each initiative that the board's own model does not carry
3
+ * (initiative premium-agreed-design, PM scope change of 2026-10-22: "build the missing data instead of empty states").
4
+ *
5
+ * trail({ root, ids, rows, moves, now, io }) → { ok, at, usual, themes, items: { [id]: item } }
6
+ *
7
+ * Everything is DERIVED from what the repository already holds. Nothing here writes:
8
+ * · days in the current stage the last board move into the stage (the board ledger), else the first appearance in git of
9
+ * the newest artifact on the initiative's ladder (record, PRD, rubric, evaluation)
10
+ * · "usually N days" per stage the median days past initiatives spent in that stage, from the same dates (record → PRD is
11
+ * Triage, PRD → rubric is Plan, rubric → evaluation is Build) and from consecutive board moves;
12
+ * null until 3 samples exist. A record reconstructed after the fact (reconstructed_from) is no sample,
13
+ * and neither are two artifacts first seen in the same commit (they were written together).
14
+ * · skipped stages and why the lane's own ladder (scripts/nine-stages.js LANE_STAGES: "the chore lane has no Triage step"),
15
+ * and a board move past a stage, with the move's own reason
16
+ * · the parts of a step's output Triage: the record and brief headings · Discover: the PRD headings · Plan: scope, timeline,
17
+ * tickets drafted and pushed · Evaluate: the evaluation file and the verdict
18
+ * · what waits on the PM the Commit of drafted tickets, a PRD change after the push, the verdict
19
+ * · tickets drafted in PMOS lib/jira-tickets.js view(): drafted, pushed (key), the PRD-changed flag, the Commit gate,
20
+ * the epic, and the Jira reading's subtasks and blocker reason
21
+ * · links prd_path and rubric_path of the record (with the PRD's `version:`), the evaluation file, the epic
22
+ * · dependencies the record's `predecessor:` and `depends_on:` keys, with where each one stands
23
+ * · themes one per objective: the PRD's `theme:` (and optional `theme_note:`, `theme_color:`), else the
24
+ * objective's own title; the health budgets are one theme
25
+ *
26
+ * io (tests pass their own): { text(rel) → string | null, list(relDir) → [names], firstSeen() → Map<rel, epoch ms>,
27
+ * jira(id) → jira-tickets view | null, anchor(raw) → { objective: { id, title } } | null, records() → [rel] }. */
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+ const { execFileSync } = require('child_process');
31
+ const { repoScript } = require('./repo-script.js');
32
+
33
+ const STAGES = ['triage', 'discover', 'plan', 'prioritize', 'build', 'deliver', 'monitor', 'evaluate'];
34
+ const LABEL = { triage: 'Triage', discover: 'Discover', plan: 'Plan', prioritize: 'Prioritize', build: 'Build', deliver: 'Deliver', monitor: 'Monitor', evaluate: 'Evaluate' };
35
+ const FALLBACK_LANES = { feature: STAGES, discovery: ['triage', 'discover', 'prioritize', 'evaluate'], chore: ['plan', 'build', 'deliver', 'evaluate'],
36
+ incident: ['build', 'deliver', 'monitor', 'evaluate'], content: ['discover', 'plan', 'build', 'deliver'], prototype: ['triage', 'discover', 'evaluate'] };
37
+ let LANE_STAGES = FALLBACK_LANES;
38
+ try { LANE_STAGES = require(repoScript('nine-stages.js')).LANE_STAGES || FALLBACK_LANES; } catch { LANE_STAGES = FALLBACK_LANES; }
39
+ const TONES = ['grey', 'blue', 'green', 'amber', 'violet', 'teal'];
40
+ const DAY = 86400000;
41
+ const MIN_SAMPLES = 3;
42
+
43
+ // The parts of an output that a heading of a document stands for (AgBoardStages: "How progress is counted").
44
+ const TRIAGE_PARTS = [['business case', /business case|why (now|this)|\bvalue\b|the bet/i], ['who asked', /who asked|asked by|requested|stakeholder|where (it|this) came from|origin/i],
45
+ ['problem', /problem/i], ['success measure', /success (measure|metric|criteria)|done[ -]criteria|outcome|how we know/i]];
46
+ const DISCOVER_PARTS = [['problem', /problem/i], ['users', /\busers?\b|persona|audience|who (it|this) is for|customers?/i], ['evidence', /evidence|research|signal|\bdata\b|findings/i],
47
+ ['scope', /scope|non-goals|out of scope|requirements/i], ['success metric', /success|metric|done[ -]criteria|acceptance/i], ['risks', /risk/i]];
48
+
49
+ const stageKey = (s) => { const k = String(s || '').toLowerCase().trim(); return { ideate: 'discover', strategize: 'prioritize' }[k] || k; };
50
+ const median = (a) => { if (!a.length) return null; const s = a.slice().sort((x, y) => x - y), m = s.length >> 1; return s.length % 2 ? s[m] : Math.round((s[m - 1] + s[m]) / 2); };
51
+ const dayIso = (ms) => new Date(ms).toISOString().slice(0, 10);
52
+
53
+ /** The leading YAML frontmatter as flat keys (strings, or lists of strings). Enough for the record and PRD keys read here. */
54
+ function frontmatter(text) {
55
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(String(text || ''));
56
+ const out = {};
57
+ if (!m) return out;
58
+ let last = null;
59
+ for (const line of m[1].split(/\r?\n/)) {
60
+ const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line);
61
+ if (kv) { last = kv[1]; const v = kv[2].trim().replace(/^["']|["']$/g, ''); out[last] = v === '' ? [] : v; continue; }
62
+ const li = /^\s*-\s+(.*)$/.exec(line);
63
+ if (li && last && Array.isArray(out[last])) out[last].push(li[1].trim().replace(/^["']|["']$/g, ''));
64
+ }
65
+ return out;
66
+ }
67
+ const headings = (text) => String(text || '').replace(/^---[\s\S]*?\n---/, '').split(/\r?\n/).filter((l) => /^#{1,4}\s|^\*\*[^*]+\*\*|^[A-Z][\w ]{2,40}:\s/.test(l)).join('\n');
68
+ const listOf = (v) => (Array.isArray(v) ? v : v ? String(v).split(/[,\s]+/) : []).map((x) => x.trim()).filter((x) => /^[a-z0-9][\w.-]*$/i.test(x));
69
+ const pathOf = (v) => (typeof v === 'string' && /^[\w./-]+\.md$/.test(v.trim()) ? v.trim() : null);
70
+
71
+ /** The default io: the files of `root`, its git history (one `git log` per HEAD), the Jira draft and reading, the OKR anchors. */
72
+ const gitCache = new Map();
73
+ function defaultIo(root) {
74
+ const read = (rel) => { try { return fs.readFileSync(path.join(root, rel), 'utf8'); } catch { return null; } };
75
+ return {
76
+ text: read,
77
+ list: (dir) => { try { return fs.readdirSync(path.join(root, dir)); } catch { return []; } },
78
+ records: () => { try { return fs.readdirSync(path.join(root, 'planning', 'initiatives')).filter((f) => f.endsWith('.md') && f !== 'README.md' && f !== 'index.md').map((f) => 'planning/initiatives/' + f); } catch { return []; } },
79
+ firstSeen: () => {
80
+ let head = '';
81
+ try { head = execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return new Map(); }
82
+ const hit = gitCache.get(root); if (hit && hit.head === head) return hit.map;
83
+ const map = new Map();
84
+ try {
85
+ const out = execFileSync('git', ['-C', root, 'log', '--diff-filter=A', '--name-only', '--format=@@%at', '--', 'planning'], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
86
+ let at = 0;
87
+ for (const line of out.split('\n')) { if (line.startsWith('@@')) at = Number(line.slice(2)) * 1000; else if (line.trim()) map.set(line.trim(), at); } // newest first: the last write is the first appearance
88
+ } catch { /* not a git checkout: no dates */ }
89
+ gitCache.set(root, { head, map });
90
+ return map;
91
+ },
92
+ jira: (id) => {
93
+ try {
94
+ const T = require('./jira-tickets.js'), S = require('./jira-status.js');
95
+ return T.view(root, id, { snapshot: S.readSnapshot(root, id) });
96
+ } catch { return null; }
97
+ },
98
+ anchor: (() => { let A = null; return (raw) => { try { if (!A) A = require('./initiative-rows.js').anchorsOf(root); return A.resolve(raw); } catch { return null; } }; })(),
99
+ };
100
+ }
101
+
102
+ /** One initiative's dates on its ladder, in order: [stage entered, epoch ms]. */
103
+ function ladderDates(id, fm, seen, evals) {
104
+ const out = [];
105
+ const at = (rel) => (rel && seen.has(rel) ? seen.get(rel) : null);
106
+ const rec = at('planning/initiatives/' + id + '.md'), prd = at(pathOf(fm.prd_path)), rub = at(pathOf(fm.rubric_path)), ev = evals.map(at).filter(Boolean).sort()[0] || null;
107
+ if (rec) out.push(['triage', rec]);
108
+ if (prd && (!rec || prd >= rec)) out.push(['plan', prd]);
109
+ if (rub && (!prd || rub >= prd)) out.push(['build', rub]);
110
+ if (ev && (!rub || ev >= rub)) out.push(['evaluate', ev]);
111
+ return out;
112
+ }
113
+ const evalFiles = (id, names) => names.filter((n) => n.startsWith(id + '-') && n.endsWith('.md') && !/rubric/.test(n)).map((n) => 'planning/evals/' + n);
114
+
115
+ /** The parts of a stage's output with what is done, and the first one that is not. */
116
+ function partsOf(stage, ctx) {
117
+ const P = (name, done, extra) => ({ name, done: !!done, ...(extra || {}) });
118
+ if (stage === 'triage') { const h = headings(ctx.recordText) + '\n' + headings(ctx.briefText); return TRIAGE_PARTS.map(([n, re]) => P(n, re.test(h))); }
119
+ if (stage === 'discover') { const h = headings(ctx.prdText); return DISCOVER_PARTS.map(([n, re]) => P(n, ctx.prdText && re.test(h))); }
120
+ if (stage === 'plan') {
121
+ const d = ctx.drafted, pushed = d.filter((t) => t.key).length;
122
+ return [P('scope', ctx.prdText && /scope|non-goals|requirements/i.test(headings(ctx.prdText))), P('timeline', ctx.row && ctx.row.start && ctx.row.end),
123
+ P(d.length ? (pushed ? pushed + ' of ' + d.length + ' tickets pushed' : d.length + ' tickets drafted, waiting on you') : 'tickets', d.length && pushed === d.length, d.length && pushed < d.length ? { you: true } : null)];
124
+ }
125
+ if (stage === 'evaluate') return [P('report', ctx.evals.length), P('evaluation', ctx.evals.length), P('your verdict', ctx.row && /accepted/i.test(String(ctx.row.reading || '')), { you: !!ctx.evals.length })];
126
+ return null;
127
+ }
128
+
129
+ function trail({ root, ids, rows = [], moves = [], now = Date.now(), io } = {}) {
130
+ const X = io || defaultIo(root);
131
+ const seen = X.firstSeen ? X.firstSeen() : new Map();
132
+ const evalNames = X.list ? X.list('planning/evals') : [];
133
+ const rowBy = new Map(rows.map((r) => [r.id, r]));
134
+ const fmCache = new Map();
135
+ const fmOf = (id) => { if (!fmCache.has(id)) { const t = X.text('planning/initiatives/' + id + '.md'); fmCache.set(id, t == null ? null : { fm: frontmatter(t), text: t }); } return fmCache.get(id); };
136
+
137
+ // "usually N days": every record's ladder, and every run of board moves
138
+ const samples = Object.fromEntries(STAGES.map((s) => [s, []]));
139
+ for (const rel of (X.records ? X.records() : [])) {
140
+ const id = path.basename(rel, '.md'), r = fmOf(id); if (!r || r.fm.reconstructed_from) continue;
141
+ const L = ladderDates(id, r.fm, seen, evalFiles(id, evalNames));
142
+ // two artifacts first seen in the same commit were written together: that says nothing about time in a stage, so it is no sample
143
+ for (let i = 0; i + 1 < L.length; i++) if (L[i + 1][1] !== L[i][1]) samples[L[i][0]].push(Math.max(0, Math.round((L[i + 1][1] - L[i][1]) / DAY)));
144
+ }
145
+ const byIni = new Map();
146
+ for (const m of moves) { if (!m || !m.id || !m.at) continue; if (!byIni.has(m.id)) byIni.set(m.id, []); byIni.get(m.id).push(m); }
147
+ for (const L of byIni.values()) {
148
+ L.sort((a, b) => String(a.at).localeCompare(String(b.at)));
149
+ for (let i = 0; i + 1 < L.length; i++) { const k = stageKey(L[i].to); if (samples[k]) samples[k].push(Math.max(0, Math.round((Date.parse(L[i + 1].at) - Date.parse(L[i].at)) / DAY))); }
150
+ }
151
+ const usual = Object.fromEntries(STAGES.map((s) => [s, samples[s].length >= MIN_SAMPLES ? { days: median(samples[s]), n: samples[s].length } : { days: null, n: samples[s].length }]));
152
+
153
+ const items = {};
154
+ const themes = new Map();
155
+ for (const id of ids || []) {
156
+ const r = fmOf(id);
157
+ if (!r && !rowBy.has(id)) continue; // neither a record nor a row of the board: nothing to say about it
158
+ const row = rowBy.get(id) || {}, fm = r ? r.fm : {};
159
+ const stage = stageKey(row.stage);
160
+ const lane = String(row.lane || fm.lane || 'feature').toLowerCase();
161
+ const evals = evalFiles(id, evalNames);
162
+ const prdRel = pathOf(fm.prd_path), rubRel = pathOf(fm.rubric_path);
163
+ const prdText = prdRel ? X.text(prdRel) : null, prdFm = frontmatter(prdText);
164
+ const briefName = (X.list ? X.list('planning/briefs') : []).find((n) => n.startsWith(id) && n.endsWith('.md'));
165
+ const jv = X.jira ? X.jira(id) : null;
166
+ const tks = jv && jv.ok && Array.isArray(jv.tickets) ? jv.tickets : [];
167
+ const drafted = tks.map((t) => ({ id: t.id, summary: t.summary, key: t.key || null, prdChanged: !!t.prdChanged, waiting: !!t.waiting }));
168
+
169
+ // days in the current stage: the last move into it, else the newest artifact on the ladder
170
+ let since = null, sinceFrom = null;
171
+ const mv = (byIni.get(id) || []).filter((m) => stageKey(m.to) === stage).pop();
172
+ if (mv) { since = Date.parse(mv.at); sinceFrom = 'move'; }
173
+ else { const L = ladderDates(id, fm, seen, evals); if (L.length) { since = L[L.length - 1][1]; sinceFrom = 'git'; } }
174
+
175
+ // skipped: the lane's own ladder, then a move past a stage (with the move's reason)
176
+ const k = STAGES.indexOf(stage), laneSet = new Set(LANE_STAGES[lane] || STAGES);
177
+ const skipped = [];
178
+ for (let j = 0; j < (k < 0 ? 0 : k); j++) if (!laneSet.has(STAGES[j])) skipped.push({ stage: STAGES[j], why: 'The ' + lane + ' lane has no ' + LABEL[STAGES[j]] + ' step.', from: 'lane' });
179
+ for (const m of byIni.get(id) || []) for (const w of m.warnings || []) {
180
+ const s = /^Skipped (.+)$/.exec(String(w)); if (!s) continue;
181
+ const sk = stageKey(s[1]); if (STAGES.includes(sk) && !skipped.some((x) => x.stage === sk)) skipped.push({ stage: sk, why: m.why ? String(m.why) : null, from: 'move', at: m.at });
182
+ }
183
+
184
+ const parts = partsOf(stage, { recordText: r ? r.text : '', briefText: briefName ? X.text('planning/briefs/' + briefName) : '', prdText, drafted, row, evals });
185
+ const unpushed = drafted.filter((t) => !t.key), drift = drafted.filter((t) => t.key && t.prdChanged);
186
+ const you = drift.length ? { text: 'Review the PRD change', why: drift.length + ' pushed ' + (drift.length === 1 ? 'ticket differs' : 'tickets differ') + ' from the PRD now', kind: 'drift' }
187
+ : stage === 'plan' && unpushed.length ? { text: 'Your Commit · push ' + unpushed.length + ' ' + (unpushed.length === 1 ? 'ticket' : 'tickets'), why: 'Drafted in PMOS. Nothing reaches Jira until you commit.', kind: 'commit' }
188
+ : stage === 'evaluate' && evals.length && !/accepted/i.test(String(row.reading || '')) ? { text: 'Your verdict', why: 'The evaluation is written. Keep, iterate or stop is yours.', kind: 'verdict' } : null;
189
+
190
+ const deps = [...new Set(listOf(fm.predecessor).concat(listOf(fm.depends_on)))].filter((d) => d !== id).slice(0, 8).map((d) => {
191
+ const dr = rowBy.get(d), df = fmOf(d);
192
+ return { id: d, title: dr ? dr.title : df ? String(df.fm.title || d) : d, stage: dr ? dr.stage : null, known: !!(dr || df), done: !!(dr && /evaluate|accepted|done/i.test(String(dr.stage || '') + ' ' + String(dr.reading || ''))) };
193
+ });
194
+
195
+ // the theme: the objective of the anchor; the PRD may name it
196
+ const raw = String(row.anchor || fm.parent_kr || '').split(/\s/)[0];
197
+ const res = raw && !/^health:/.test(raw) && X.anchor ? X.anchor(raw) : null;
198
+ const obj = res && res.objective ? res.objective : null;
199
+ const tkey = /^health:/.test(raw) ? 'health' : obj ? obj.id : raw ? 'other' : 'none';
200
+ if (!themes.has(tkey)) themes.set(tkey, { key: tkey, name: null, note: null, tone: null, objective: obj ? obj.title : null, period: obj ? obj.period || null : null, from: null });
201
+ const th = themes.get(tkey);
202
+ if (!th.name && typeof prdFm.theme === 'string' && prdFm.theme.trim()) { th.name = prdFm.theme.trim().slice(0, 60); th.from = prdRel; }
203
+ if (!th.note && typeof prdFm.theme_note === 'string' && prdFm.theme_note.trim()) th.note = prdFm.theme_note.trim().slice(0, 120);
204
+ if (!th.tone && typeof prdFm.theme_color === 'string' && TONES.includes(prdFm.theme_color.trim().toLowerCase())) th.tone = prdFm.theme_color.trim().toLowerCase();
205
+
206
+ const tickets = {};
207
+ for (const t of tks) if (t.key && t.jira) tickets[t.key] = { subtasks: t.jira.subtasks || null, reason: t.jira.reason || null, flagged: !!t.jira.flagged };
208
+
209
+ items[id] = {
210
+ since: since ? dayIso(since) : null, sinceFrom, days: since ? Math.max(0, Math.floor((now - since) / DAY)) : null,
211
+ skipped, parts, next: parts ? (parts.find((p) => !p.done) || {}).name || null : null, you,
212
+ links: { prd: prdRel, prdVersion: prdRel && (typeof prdFm.version === 'string' || typeof prdFm.version === 'number') && String(prdFm.version).trim() ? String(prdFm.version).trim().slice(0, 12) : null,
213
+ rubric: rubRel, evaluation: evals[0] || null, epic: jv && jv.ok && jv.epic && jv.epic.key ? jv.epic.key : null },
214
+ drafted, gate: jv && jv.ok ? jv.gate || null : null, drift: drift.map((t) => t.key), deps, theme: tkey, tickets,
215
+ };
216
+ }
217
+ // a theme with no name on any PRD takes its objective's title; tones in order where none is set
218
+ let ti = 0;
219
+ const out = [...themes.values()].map((t) => ({ ...t, name: t.name || (t.key === 'health' ? 'Health budgets' : t.objective || (t.key === 'none' ? 'No anchor' : 'Other anchors')), tone: t.tone || TONES[ti++ % TONES.length] }));
220
+ return { ok: true, at: new Date(now).toISOString(), usual, themes: out, items };
221
+ }
222
+
223
+ module.exports = { trail, frontmatter, partsOf, ladderDates, median, STAGES, MIN_SAMPLES, TONES };
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+ /* home-work-item.js — "Make a work-item" under a message in Home's chat (initiative premium-agreed-design, Home).
3
+ *
4
+ * makeFromChat(root, initiative, { text, key }) → { ok, ticket, created, draft } | { ok: false, status, error }
5
+ *
6
+ * The message's first line becomes a ticket Drafted in PMOS on the initiative (lib/jira-tickets.js's draft file), in the same form a
7
+ * meeting's next step takes (lib/viewer-meeting.js makeWorkItem): not approved and not pushed. Only the Commit gate pushes a ticket to
8
+ * Jira. The ticket's References name the chat it came from; a second press on the same text in the same chat makes no second ticket. */
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const crypto = require('crypto');
12
+ const VM = require('./viewer-meeting.js');
13
+
14
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/;
15
+ const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,120}$/;
16
+ const line = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
17
+ const hashOf = (t) => crypto.createHash('sha256').update(line(t, 2000).toLowerCase()).digest('hex').slice(0, 8);
18
+ const REF = (key, h) => `- Chat: ${key} · message ${h}`;
19
+
20
+ function makeFromChat(root, initiative, { text, key } = {}) {
21
+ const T = require('./jira-tickets.js');
22
+ if (!root) return { ok: false, status: 409, error: 'the repository is not registered here' };
23
+ if (!ID_RE.test(String(initiative || ''))) return { ok: false, status: 400, error: 'this chat is not in an initiative: link it to one first' };
24
+ const k = KEY_RE.test(String(key || '')) ? String(key) : 'chat';
25
+ const first = String(text || '').split('\n').map((x) => x.replace(/^[#>*\-\s]+/, '')).find((x) => x.trim()) || '';
26
+ const summary = line(first, 200);
27
+ if (!summary) return { ok: false, status: 400, error: 'the message has no text' };
28
+ const rfm = T.recordFm(root, initiative);
29
+ if (!rfm) return { ok: false, status: 404, error: `no initiative ${initiative} in this repository` };
30
+ const h = hashOf(text);
31
+ const d = T.readDraft(root, initiative);
32
+ const had = ((d && d.tickets) || []).find((t) => String((t.sections && t.sections.refs) || '').includes(REF(k, h)));
33
+ if (had) return { ok: true, ticket: had.id, created: false };
34
+ const id = VM.nextTicketId(d ? d.tickets.map((x) => x.id) : [], rfm.title || initiative);
35
+ const t = { id, summary, type: 'Task', priority: 'Medium', sections: {} };
36
+ for (const [s] of T.SECTIONS) t.sections[s] = '';
37
+ t.sections.context = line(String(text).replace(/^\s*#+\s*/gm, ''), 1500); // a heading mark would read as a new ticket or section in the draft
38
+ t.sections.refs = REF(k, h);
39
+ t.drafted = T.contentHash(t);
40
+ const block = [`## ${t.id} · ${summary}`, `- type: ${t.type}`, `- priority: ${t.priority}`, `- drafted: ${t.drafted}`, ''];
41
+ for (const [s, head] of T.SECTIONS) block.push(`### ${head}`, '', String(t.sections[s] || '').trim() || '—', '');
42
+ const file = T.draftPath(root, initiative);
43
+ fs.mkdirSync(path.dirname(file), { recursive: true });
44
+ let text0 = '';
45
+ try { text0 = fs.readFileSync(file, 'utf8'); } catch { text0 = ''; }
46
+ if (!text0) {
47
+ const ts = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
48
+ text0 = ['---', 'type: Reference', `title: "Jira tickets: ${initiative}"`, `timestamp: ${ts}`, '---', '', `# Jira tickets: ${initiative}`, '',
49
+ 'Drafted in PMOS. Read and edit them on the initiative\'s Jira tickets tab, or here. Check the ones that are ready and press Push: only checked tickets are sent.', '',
50
+ 'PMOS owns the text of these tickets and Jira owns their status.', ''].join('\n');
51
+ }
52
+ const tmp = `${file}.${process.pid}.tmp`;
53
+ fs.writeFileSync(tmp, text0.replace(/\n*$/, '\n') + '\n' + block.join('\n'));
54
+ fs.renameSync(tmp, file);
55
+ return { ok: true, ticket: id, created: true, draft: T.draftRel(root, initiative) };
56
+ }
57
+
58
+ module.exports = { makeFromChat };
@@ -0,0 +1,196 @@
1
+ 'use strict';
2
+ /* insights-goals.js — the pure rules behind the premium Insights page's goals, budgets, trends and outcomes (initiative premium-agreed-design G1, G2).
3
+ * PURE: no I/O, no clock of its own. The route reads the files and passes `today` (a 'YYYY-MM-DD' day).
4
+ *
5
+ * GOAL_TYPES · DIRECTIONS · SOURCES
6
+ * goalFields(input, { today }) → { ok, fields } | { ok: false, error } the New goal form → the fields of one KR metric record (its date is `due`)
7
+ * checkpointsOf(base, target, from, by) → [{ by, target }] a yearly goal's quarter-end checkpoints, on the straight line
8
+ * describe(text, goals) → { name, question, goals: [id], range, said: [] } "Describe it, and PMOS fills this in", word for word
9
+ * parseBudgets(md) → [{ id, covers, cap }] the D59 registry (planning/okrs/health-budgets.md)
10
+ * budgetReading(budget, inits) → { n, total, share, over } the budget's share of the board's open initiatives, against its cap
11
+ * trendsOf(rows, today, weeks) → { late: { value, ser }, scope: { value, ser } } Late initiatives and Scope added for Delivery trends
12
+ * skippedOf(warnings) → [stage] the stages the Board recorded as skipped ("Skipped <stage>")
13
+ * windowOf({ shipAt, byAt, verdict, today }) → { opens, closes, state } an outcome's judgement window: from the ship date to the promise date
14
+ * evidenceOf(readings, shipAt, unit) → [text] what the readings say since the ship date
15
+ * periodHits(goals, from, to) → { n, hit } the goals due in a past period, and how many reached their target by then
16
+ * exportCsv(goals) → text the goals as CSV (Export in ⋯)
17
+ *
18
+ * NOTHING HERE MAKES A NUMBER UP. A checkpoint is the straight line from the baseline to the target, said as that. A budget reading is a count of
19
+ * initiatives. Scope added counts the initiatives whose planned start falls in a week. Evidence is the readings themselves. */
20
+
21
+ const GOAL_TYPES = Object.freeze(['Done or not', 'Percentage', 'Count', 'Amount', 'Duration', 'Stay within']);
22
+ const DIRECTIONS = Object.freeze({ Up: 'up', Down: 'down', 'Exactly the target': 'exact' });
23
+ const SOURCES = Object.freeze({ analytics: 'Product analytics', jira: 'Jira query', file: 'A file or export', typed: 'You type it in' });
24
+ const UNIT_OF = Object.freeze({ Percentage: '%', Duration: 'days', Amount: '$', Count: '' });
25
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
26
+ const STEPS_MAX = 12, TEXT_MAX = 120;
27
+
28
+ const fin = (v) => typeof v === 'number' && Number.isFinite(v);
29
+ const tidy = (v, n = TEXT_MAX) => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ').slice(0, n) : '');
30
+ const toNum = (v) => (v === '' || v == null ? NaN : Number(v));
31
+ const ms = (d) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(d || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
32
+ const iso = (t) => new Date(t).toISOString().slice(0, 10);
33
+ const decimals = (v) => (String(v).split('.')[1] || '').length;
34
+ const round = (v, d) => { const k = 10 ** d; return Math.round(v * k) / k; };
35
+ const no = (error) => ({ ok: false, error });
36
+
37
+ /** A yearly goal's checkpoints: the end of each quarter after `from` and before `by`, with the target the straight line reaches there. */
38
+ function checkpointsOf(base, target, from, by) {
39
+ const t0 = ms(from), t1 = ms(by);
40
+ if (!fin(base) || !fin(target) || t0 === null || t1 === null || t1 <= t0) return [];
41
+ const d = Math.max(decimals(base), decimals(target), Math.abs(target - base) < 10 ? 1 : 0), out = [];
42
+ const y0 = new Date(t0).getUTCFullYear();
43
+ for (let y = y0; y <= new Date(t1).getUTCFullYear(); y++) {
44
+ for (const m of [3, 6, 9, 12]) {
45
+ const t = Date.UTC(y, m, 0);
46
+ if (t <= t0 || t >= t1) continue;
47
+ out.push({ by: iso(t), target: round(base + (target - base) * ((t - t0) / (t1 - t0)), d) });
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /** The New goal form → the fields of one KR metric record. A KR metric needs a baseline, a target and a date, so:
54
+ * Done or not is stored as steps done, from 0 to the number of steps (1 when it has none), due on its date;
55
+ * Stay within is stored with its reading now as the baseline and its floor or ceiling as the target; always_on when it has no end. */
56
+ function goalFields(input, { today } = {}) {
57
+ const i = input && typeof input === 'object' ? input : {};
58
+ const name = tidy(i.name);
59
+ if (!name) return no('Give the goal a name.');
60
+ const type = GOAL_TYPES.includes(i.type) ? i.type : null;
61
+ if (!type) return no('Pick a type: ' + GOAL_TYPES.join(', ') + '.');
62
+ const dir = DIRECTIONS[i.direction] || null;
63
+ const always = type === 'Stay within' && i.always_on === true;
64
+ const due = i.due != null ? i.due : i.by; // the page sends `due`: a page press may not carry `by`, which names the writer (pm-guard)
65
+ const by = always ? (DATE.test(String(due || '')) ? due : (String(today || '').slice(0, 4) || new Date().getUTCFullYear()) + '-12-31') : String(due || '');
66
+ if (!DATE.test(by)) return no('Pick the date it is due.');
67
+ const f = { metric: name, type, by };
68
+ if (type === 'Done or not') {
69
+ const steps = (Array.isArray(i.steps) ? i.steps : []).map((s) => tidy(typeof s === 'string' ? s : s && s.text)).filter(Boolean);
70
+ if (steps.length > STEPS_MAX) return no(`A goal can have at most ${STEPS_MAX} steps.`);
71
+ Object.assign(f, { baseline: 0, target: Math.max(1, steps.length), unit: steps.length ? 'steps' : 'done', direction: 'up', steps: steps.map((text) => ({ text, done: false })) });
72
+ } else if (type === 'Stay within') {
73
+ const now = toNum(i.baseline), lim = toNum(i.target), kind = i.limit === 'floor' ? 'floor' : i.limit === 'ceiling' ? 'ceiling' : null;
74
+ if (!fin(now) || !fin(lim)) return no('Type a number for the reading now and for the limit.');
75
+ if (!kind) return no('Say whether the limit is a floor or a ceiling.');
76
+ if (now === lim) return no('The reading now must differ from the limit, so the room left can be read.');
77
+ Object.assign(f, { baseline: now, target: lim, unit: tidy(i.unit, 12), direction: kind === 'ceiling' ? 'down' : 'up', limit: kind, always_on: always });
78
+ } else {
79
+ const base = toNum(i.baseline), tgt = toNum(i.target);
80
+ if (!fin(base) || !fin(tgt)) return no('Type a number for the baseline and the target.');
81
+ if (base === tgt) return no('The target must differ from the baseline.');
82
+ if (!dir) return no('Say whether up or down is better.');
83
+ if ((dir === 'up' && tgt < base) || (dir === 'down' && tgt > base)) return no((dir === 'up' ? 'Up' : 'Down') + ' is better, so the target must be ' + (dir === 'up' ? 'above' : 'below') + ' the baseline.');
84
+ Object.assign(f, { baseline: base, target: tgt, unit: UNIT_OF[type], direction: dir });
85
+ }
86
+ const pillar = tidy(i.objective, 80); if (pillar) f.pillar = pillar;
87
+ const kind = ['Quarter', 'Half', 'Year', 'Custom'].includes(i.period_kind) ? i.period_kind : null;
88
+ if (kind) f.period = { kind, label: tidy(i.period_label, 20) || kind };
89
+ if (kind === 'Year' && type !== 'Done or not' && today) { const cp = checkpointsOf(f.baseline, f.target, today, by); if (cp.length) f.checkpoints = cp; }
90
+ if (SOURCES[i.source]) f.source = i.source;
91
+ const owner = tidy(i.owner, 60); if (owner) f.owner = owner;
92
+ const guard = tidy(i.guardrail, 120); if (guard) f.guardrail = guard;
93
+ return { ok: true, fields: f };
94
+ }
95
+
96
+ /** "Describe it, and PMOS fills this in": the words of the description, matched to the goals by name and objective. Nothing is guessed: a goal is
97
+ * picked only when its name or objective is in the text, and `said` lists the words that matched. */
98
+ const STOP = new Set(['the', 'a', 'an', 'of', 'and', 'or', 'for', 'to', 'in', 'on', 'my', 'our', 'is', 'are', 'how', 'what', 'with', 'by', 'dashboard', 'show', 'me', 'make', 'that', 'this', 'it', 'week', 'weeks', 'first']);
99
+ function describe(text, goals) {
100
+ const t = tidy(text, 300), low = t.toLowerCase();
101
+ if (!t) return { ok: false, error: 'Describe the dashboard in a few words.' };
102
+ const words = new Set(low.split(/[^a-z0-9%]+/).filter((w) => w.length > 2 && !STOP.has(w)));
103
+ const said = [], picked = [];
104
+ for (const g of goals || []) {
105
+ const title = String(g.title || '').toLowerCase(), pillar = String(g.pillar || '').toLowerCase();
106
+ const hitTitle = title && (low.includes(title) || title.split(/[^a-z0-9%]+/).filter((w) => w.length > 2 && !STOP.has(w)).some((w) => words.has(w)));
107
+ const hitPillar = pillar && words.has(pillar);
108
+ if (hitTitle || hitPillar) { picked.push(g.id); said.push(hitTitle ? g.title : g.pillar); }
109
+ }
110
+ const range = /\b(8|eight)\s*weeks?\b|\btwo months?\b/.test(low) ? '8w' : /\b(26|twenty[- ]six)\s*weeks?\b|\bhalf\b|\bsix months?\b/.test(low) ? '26w' : 'Quarter';
111
+ const first = (/^[^?.!]+[?.!]?/.exec(t) || [t])[0].trim(), head = first.replace(/[?.!]+$/, '');
112
+ const name = (head.length > 40 ? head.slice(0, 40).replace(/\s+\S*$/, '') : head).replace(/^./, (c) => c.toUpperCase());
113
+ const asked = /[^?.!]*\?/.exec(t);
114
+ const question = asked ? asked[0].trim() : (/^(are|is|do|does|did|can|will|how|what|which|why|who|where|when)\b/i.test(t) ? head + '?' : '');
115
+ return { ok: true, name, question, goals: picked, range, said: [...new Set(said)] };
116
+ }
117
+
118
+ /** The health budgets of planning/okrs/health-budgets.md: one table row per budget, `health:<id>` | covers | cap % | trigger. */
119
+ function parseBudgets(md) {
120
+ const out = [];
121
+ for (const line of String(md || '').split('\n')) {
122
+ const m = /^\|\s*`health:([a-z0-9-]+)`\s*\|\s*([^|]*)\|\s*(\d+(?:\.\d+)?)\s*%\s*\|/.exec(line);
123
+ if (m) out.push({ id: m[1], covers: m[2].trim(), cap: Number(m[3]) / 100 });
124
+ }
125
+ return out;
126
+ }
127
+ /** A budget's reading: of the board's open initiatives, the share anchored to it, against its cap. An initiative that is done or stopped is not counted. */
128
+ function budgetReading(budget, inits) {
129
+ const open = (inits || []).filter((r) => r && r.status !== 'done' && r.status !== 'cancelled' && !r.stopped);
130
+ const n = open.filter((r) => String(r.anchor || '') === 'health:' + budget.id).length;
131
+ const total = open.length, share = total ? n / total : null;
132
+ return { n, total, share, over: share !== null && fin(budget.cap) ? share > budget.cap : null };
133
+ }
134
+
135
+ /** Late initiatives (status late) and Scope added (initiatives whose planned start falls in each of the last `weeks` weeks, the last one this week). */
136
+ function trendsOf(rows, today, weeks = 8) {
137
+ const R = Array.isArray(rows) ? rows : null;
138
+ if (!R) return { late: { value: null, ser: [] }, scope: { value: null, ser: [] } };
139
+ const t = ms(today) || Date.now(), W = 7 * 864e5, ser = [], late = R.filter((r) => r.status === 'late'), lser = [];
140
+ for (let k = weeks - 1; k >= 0; k--) {
141
+ const hi = t - k * W, lo = hi - W;
142
+ ser.push(R.filter((r) => { const s = ms(r.start); return s !== null && s > lo && s <= hi; }).length);
143
+ /* a week before this one: the initiatives late today whose end date had already passed by then. The Board keeps no history of a status,
144
+ * so one that was late then and is no longer late is not counted; this week is today's count. */
145
+ lser.push(k === 0 ? late.length : late.filter((r) => { const e = ms(r.end); return e !== null && e < hi; }).length);
146
+ }
147
+ return { late: { value: late.length, ser: lser }, scope: { value: ser[ser.length - 1], ser } };
148
+ }
149
+
150
+ /** The stages the Board recorded as skipped when an initiative was moved past them. */
151
+ function skippedOf(warnings) {
152
+ const out = [];
153
+ for (const w of warnings || []) { const m = /^Skipped (.+?)\.?$/.exec(String(w)); if (m) for (const s of m[1].split(/,\s*|\s+and\s+/)) if (s.trim()) out.push(s.trim()); }
154
+ return out;
155
+ }
156
+
157
+ /** An outcome's judgement window: it opens on the ship date and closes on the promise's date. Judged once a verdict is recorded. */
158
+ function windowOf({ shipAt, byAt, verdict, today }) {
159
+ const o = ms(shipAt), c = ms(byAt), t = ms(today);
160
+ const state = verdict ? 'judged' : o === null ? 'none' : c !== null && t !== null && t > c ? 'closed' : t !== null && t < o ? 'not open' : 'open';
161
+ return { opens: o === null ? null : iso(o), closes: c === null ? null : iso(c), share: o !== null && c !== null && c > o && t !== null ? Math.max(0, Math.min(1, (t - o) / (c - o))) : null, state };
162
+ }
163
+
164
+ /** What the readings say since the ship date: the reading at ship, the latest, and how many came after. */
165
+ function evidenceOf(readings, shipAt, unit) {
166
+ const rs = (readings || []).filter((r) => r && fin(r.v) && ms(r.at) !== null).sort((a, b) => ms(a.at) - ms(b.at));
167
+ const s = ms(shipAt), u = String(unit || '').trim(), fmt = (v) => round(v, 2) + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : '');
168
+ if (!rs.length) return [];
169
+ if (s === null) return [`${rs.length} reading${rs.length === 1 ? '' : 's'} recorded; no ship date, so none is read as after it`];
170
+ const before = rs.filter((r) => ms(r.at) <= s), after = rs.filter((r) => ms(r.at) > s), out = [];
171
+ if (before.length) out.push(`${fmt(before[before.length - 1].v)} on ${before[before.length - 1].at.slice(0, 10)}, the last reading before it shipped`);
172
+ if (after.length) out.push(`${fmt(after[after.length - 1].v)} on ${after[after.length - 1].at.slice(0, 10)}, ${after.length} reading${after.length === 1 ? '' : 's'} after it shipped`);
173
+ else out.push('No reading since it shipped');
174
+ return out;
175
+ }
176
+
177
+ /** The goals due in [from, to], and how many reached their target by their date (a reading on or before the date at or past the target). */
178
+ function periodHits(goals, from, to) {
179
+ const a = ms(from), b = ms(to); let n = 0, hit = 0;
180
+ for (const g of goals || []) {
181
+ const by = ms(g.byAt || g.by); if (by === null || by < a || by > b) continue;
182
+ n++;
183
+ const dir = fin(g.target) && fin(g.base) ? Math.sign(g.target - g.base) : 0;
184
+ if (dir && (g.series || []).some((r) => ms(r.at) !== null && ms(r.at) <= by && (dir > 0 ? r.v >= g.target : r.v <= g.target))) hit++;
185
+ }
186
+ return { n, hit };
187
+ }
188
+
189
+ /** The goals as CSV, one row each, with what the page shows. */
190
+ function exportCsv(goals) {
191
+ const q = (v) => { const s = v == null ? '' : String(v); return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
192
+ const head = ['id', 'goal', 'objective', 'type', 'direction', 'baseline', 'target', 'unit', 'by', 'now', 'readings', 'owner', 'pace'];
193
+ return [head.join(',')].concat((goals || []).map((g) => [g.id, g.title, g.pillar, g.type, g.direction || '', g.base, g.target, g.unit, g.byAt, g.now, g.readings, g.owner || '', g.pace ? g.pace.head + ' ' + g.pace.sub : ''].map(q).join(','))).join('\n') + '\n';
194
+ }
195
+
196
+ module.exports = { GOAL_TYPES, DIRECTIONS, SOURCES, UNIT_OF, goalFields, checkpointsOf, describe, parseBudgets, budgetReading, trendsOf, skippedOf, windowOf, evidenceOf, periodHits, exportCsv };