create-pmos 0.397.0 → 0.399.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 (195) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-adddoc-test.js +105 -52
  8. package/workspace/briefing-premium-board-test.js +284 -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 +85 -196
  12. package/workspace/briefing-premium-doc-edit-test.js +99 -83
  13. package/workspace/briefing-premium-initiative-test.js +175 -290
  14. package/workspace/briefing-premium-insights-test.js +414 -219
  15. package/workspace/briefing-premium-metrics-test.js +55 -97
  16. package/workspace/briefing-premium-products-test.js +44 -28
  17. package/workspace/briefing-premium-sources-test.js +70 -49
  18. package/workspace/briefing-premium-test.js +155 -648
  19. package/workspace/briefing-premium-work-test.js +88 -283
  20. package/workspace/changelog.json +24 -0
  21. package/workspace/ev-everywhere-test.js +210 -0
  22. package/workspace/fixtures/board-premium-trail.js +32 -0
  23. package/workspace/fixtures/premium-viewer-fixtures.js +187 -0
  24. package/workspace/guide/briefing-premium.md +3 -1
  25. package/workspace/guide/home.md +68 -0
  26. package/workspace/guide/index.md +1 -0
  27. package/workspace/lib/agent-roles.js +71 -0
  28. package/workspace/lib/board-grill.js +63 -0
  29. package/workspace/lib/board-premium.js +121 -24
  30. package/workspace/lib/board-trail.js +223 -0
  31. package/workspace/lib/home-work-item.js +58 -0
  32. package/workspace/lib/initiative-layout.js +77 -0
  33. package/workspace/lib/insights-goals.js +196 -0
  34. package/workspace/lib/insights-premium.js +64 -15
  35. package/workspace/lib/insights-records.js +115 -0
  36. package/workspace/lib/jira-tickets.js +1 -1
  37. package/workspace/lib/meeting-points.js +52 -0
  38. package/workspace/lib/news-for-you.js +88 -0
  39. package/workspace/lib/notes-series.js +29 -6
  40. package/workspace/lib/report-confirm.js +48 -0
  41. package/workspace/lib/route-modules.js +12 -0
  42. package/workspace/lib/routes-board-docs.js +46 -0
  43. package/workspace/lib/routes-board-grill.js +90 -0
  44. package/workspace/lib/routes-board-trail.js +33 -0
  45. package/workspace/lib/routes-home-desk.js +176 -0
  46. package/workspace/lib/routes-home-review.js +108 -0
  47. package/workspace/lib/routes-initiative-layout.js +57 -0
  48. package/workspace/lib/routes-insights-premium.js +16 -4
  49. package/workspace/lib/routes-insights-records.js +133 -0
  50. package/workspace/lib/routes-meeting-points.js +37 -0
  51. package/workspace/lib/routes-news.js +57 -0
  52. package/workspace/lib/routes-notes.js +3 -1
  53. package/workspace/lib/routes-report-confirm.js +31 -0
  54. package/workspace/lib/routes-search.js +38 -0
  55. package/workspace/lib/routes-viewer.js +108 -0
  56. package/workspace/lib/search-index.js +176 -0
  57. package/workspace/lib/transcript-steps.js +123 -0
  58. package/workspace/lib/viewer-meeting.js +205 -0
  59. package/workspace/lib/viewer-report.js +89 -0
  60. package/workspace/package-lock.json +2 -2
  61. package/workspace/package.json +1 -1
  62. package/workspace/premium-board-actions-test.js +128 -82
  63. package/workspace/premium-briefing-depth-test.js +104 -90
  64. package/workspace/premium-chat-attach-test.js +54 -63
  65. package/workspace/premium-chat-chart-tab-test.js +37 -37
  66. package/workspace/premium-chat-context-test.js +19 -18
  67. package/workspace/premium-chat-goal-view-test.js +23 -23
  68. package/workspace/premium-chat-notes-test.js +26 -31
  69. package/workspace/premium-chat-report-tab-test.js +46 -28
  70. package/workspace/premium-chat-term-test.js +16 -16
  71. package/workspace/premium-chat-viewer-test.js +60 -59
  72. package/workspace/premium-core-doc-issue-test.js +52 -43
  73. package/workspace/premium-html-viewer-test.js +14 -17
  74. package/workspace/premium-phone-card-test.js +10 -3
  75. package/workspace/premium-phone-room-test.js +41 -35
  76. package/workspace/premium-report-read-test.js +152 -197
  77. package/workspace/premium-viewer-download-test.js +19 -22
  78. package/workspace/premium-viewer-flicker-test.js +11 -16
  79. package/workspace/premium-viewer-share-test.js +6 -9
  80. package/workspace/premium-viewer-test.js +41 -60
  81. package/workspace/premium-vw-backlog-test.js +53 -33
  82. package/workspace/premium-vw-cal-test.js +97 -128
  83. package/workspace/premium-vw-copy-test.js +17 -33
  84. package/workspace/premium-vw-doc-test.js +17 -10
  85. package/workspace/premium-vw-item-test.js +50 -49
  86. package/workspace/premium-vw-jira-test.js +53 -27
  87. package/workspace/premium-vw-meet-test.js +115 -187
  88. package/workspace/premium-vw-notes-test.js +88 -109
  89. package/workspace/premium-vw-rec-test.js +71 -194
  90. package/workspace/premium-vw-slides-test.js +46 -50
  91. package/workspace/premium-welcome-test.js +3 -2
  92. package/workspace/premium-work-depth-test.js +61 -53
  93. package/workspace/public/pm/bd-acts.js +383 -0
  94. package/workspace/public/pm/bd-asks.js +261 -0
  95. package/workspace/public/pm/bd-pop.js +59 -0
  96. package/workspace/public/pm/bd-span.js +222 -82
  97. package/workspace/public/pm/bd-stages.js +25 -11
  98. package/workspace/public/pm/bd-views.js +169 -0
  99. package/workspace/public/pm/c3-doc-sheet.js +1 -1
  100. package/workspace/public/pm/c3-md.js +3 -395
  101. package/workspace/public/pm/c3-phone-detail.js +1 -1
  102. package/workspace/public/pm/c3-phone-model.js +3 -68
  103. package/workspace/public/pm/chat-term.js +3 -3
  104. package/workspace/public/pm/cozy-board.css +798 -230
  105. package/workspace/public/pm/cozy-ev.css +228 -0
  106. package/workspace/public/pm/cozy-evmodel.js +106 -0
  107. package/workspace/public/pm/cozy-evui.js +47 -0
  108. package/workspace/public/pm/cozy-home.css +570 -142
  109. package/workspace/public/pm/cozy-home.js +5 -3
  110. package/workspace/public/pm/cozy-insights.css +437 -170
  111. package/workspace/public/pm/cozy-md.js +396 -0
  112. package/workspace/public/pm/cozy-nav.js +104 -29
  113. package/workspace/public/pm/cozy-news.js +140 -0
  114. package/workspace/public/pm/cozy-placeholder.js +26 -0
  115. package/workspace/public/pm/cozy-search.js +203 -0
  116. package/workspace/public/pm/cozy-settings.js +198 -0
  117. package/workspace/public/pm/cozy-sources.js +89 -0
  118. package/workspace/public/pm/cozy-today.css +217 -0
  119. package/workspace/public/pm/cozy-viewer.css +3 -3
  120. package/workspace/public/pm/cozy-viewer.js +145 -0
  121. package/workspace/public/pm/cozy-vw-mtg.css +350 -0
  122. package/workspace/public/pm/cozy-vw-rp.css +152 -0
  123. package/workspace/public/pm/cozy-vw.css +485 -0
  124. package/workspace/public/pm/cozy.css +83 -1
  125. package/workspace/public/pm/home-adddoc.js +48 -0
  126. package/workspace/public/pm/home-app.js +1179 -0
  127. package/workspace/public/pm/home-around.js +413 -0
  128. package/workspace/public/pm/home-chat.js +512 -0
  129. package/workspace/public/pm/home-data.js +312 -0
  130. package/workspace/public/pm/home-dictate.js +54 -0
  131. package/workspace/public/pm/home-draft.js +68 -0
  132. package/workspace/public/pm/home-ini-model.js +190 -0
  133. package/workspace/public/pm/home-ini.css +171 -0
  134. package/workspace/public/pm/home-ini.js +456 -0
  135. package/workspace/public/pm/home-list.js +276 -0
  136. package/workspace/public/pm/home-more.js +132 -0
  137. package/workspace/public/pm/home-phone-card.js +109 -0
  138. package/workspace/public/pm/home-review.js +104 -0
  139. package/workspace/public/pm/home-task.js +67 -0
  140. package/workspace/public/pm/home-today.js +144 -0
  141. package/workspace/public/pm/home-work.js +547 -0
  142. package/workspace/public/pm/phone-moment.js +69 -0
  143. package/workspace/public/pm/pm-work-view.js +1 -1
  144. package/workspace/public/pm/premium-attach.js +4 -0
  145. package/workspace/public/pm/premium-board.js +548 -395
  146. package/workspace/public/pm/premium-chart-tab.js +109 -62
  147. package/workspace/public/pm/premium-deck.js +3 -3
  148. package/workspace/public/pm/premium-first.js +23 -21
  149. package/workspace/public/pm/premium-insights.js +1102 -581
  150. package/workspace/public/pm/premium-meeting.js +61 -549
  151. package/workspace/public/pm/premium-mtg-present.js +138 -0
  152. package/workspace/public/pm/premium-mtg-replay.js +142 -0
  153. package/workspace/public/pm/premium-notes.js +1 -1
  154. package/workspace/public/pm/premium-report-frame.css +20 -0
  155. package/workspace/public/pm/premium-report-read.js +669 -476
  156. package/workspace/public/pm/premium-report-tab.js +116 -67
  157. package/workspace/public/pm/premium-shell.js +76 -123
  158. package/workspace/public/pm/premium-viewer.js +22 -1
  159. package/workspace/public/pm/premium-vw-cal.js +277 -48
  160. package/workspace/public/pm/premium-vw-doc.css +6 -0
  161. package/workspace/public/pm/premium-vw-doc.js +40 -2
  162. package/workspace/public/pm/premium-vw-file.js +2 -2
  163. package/workspace/public/pm/premium-vw-meet.js +6 -83
  164. package/workspace/public/pm/premium-vw-mtg.js +958 -0
  165. package/workspace/public/pm/premium-vw-notes.js +116 -68
  166. package/workspace/public/pm/premium-vw-open.js +35 -0
  167. package/workspace/public/pm/premium-vw-page.js +16 -0
  168. package/workspace/public/pm/premium-vw-rec.js +11 -218
  169. package/workspace/public/pm/premium-vw-slides.css +5 -0
  170. package/workspace/public/pm/premium-vw-slides.js +44 -8
  171. package/workspace/public/pm/rp-parts.js +269 -0
  172. package/workspace/public/pm/term-view.js +22 -0
  173. package/workspace/public/premium-board.html +29 -70
  174. package/workspace/public/premium-initiative.html +8 -48
  175. package/workspace/public/premium-insights.html +26 -64
  176. package/workspace/public/premium-viewer.html +20 -0
  177. package/workspace/public/premium.html +18 -107
  178. package/workspace/r/m1.png +0 -0
  179. package/workspace/r/m2.png +0 -0
  180. package/workspace/r/m3.png +0 -0
  181. package/workspace/r/nl.png +0 -0
  182. package/workspace/server.js +18 -3
  183. package/workspace/test-files.json +1 -0
  184. package/workspace/test-lists/home-libs.json +9 -0
  185. package/workspace/test-lists/initiative-layout.json +9 -0
  186. package/workspace/test-lists/premium-report-read.json +1 -1
  187. package/workspace/test-lists/premium-uncovered-meetings.json +9 -0
  188. package/workspace/test-lists/premium-uncovered-reports.json +9 -0
  189. package/workspace/test-lists/premium-vw-agreed.json +9 -0
  190. package/workspace/test-lists/premium-vw-notes.json +1 -1
  191. package/workspace/test-lists/uf-everywhere.json +15 -0
  192. package/workspace/test-lists/uf-home.json +9 -0
  193. package/workspace/test-lists/uncovered-board.json +9 -0
  194. package/workspace/public/pm/premium-work.js +0 -729
  195. package/workspace/public/pm/premium.js +0 -1146
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+ /* agent-roles.js — the role name a session shows in the chat and the list (initiative premium-agreed-design, Home).
3
+ *
4
+ * roleOf({ skill, origin, first }) → { key, name, initial }
5
+ * ROLES · TABLE
6
+ *
7
+ * The Agreed design names each agent by its role ("Communicator", "Delivery lead") with a two-letter avatar. A session has no role
8
+ * record of its own, so the role is DERIVED from the skill that started it, in this order:
9
+ * 1. skill the skill the session was spawned for (server.js keeps it as modelAsk.skill and persists it)
10
+ * 2. origin a skill named in the origin tag ("schedule:<skill>", "skill:<skill>", "core-doc:<skill>")
11
+ * 3. first the first slash command of the conversation ("/prd …"), which the client reads from the transcript
12
+ * A session that names none of the skills below is "Claude" (initial C): the fallback, never a guess.
13
+ * Pure: the client imports the same table through GET /api/home-desk (roles), so both sides say the same name. */
14
+
15
+ const ROLES = Object.freeze({
16
+ claude: { key: 'claude', name: 'Claude', initial: 'C' },
17
+ spec: { key: 'spec', name: 'Spec writer', initial: 'Sp' },
18
+ eval: { key: 'eval', name: 'Evaluator', initial: 'Ev' },
19
+ strategy: { key: 'strategy', name: 'Strategist', initial: 'St' },
20
+ research: { key: 'research', name: 'Researcher', initial: 'Re' },
21
+ design: { key: 'design', name: 'Designer', initial: 'De' },
22
+ delivery: { key: 'delivery', name: 'Delivery lead', initial: 'Dl' },
23
+ comms: { key: 'comms', name: 'Communicator', initial: 'Co' },
24
+ build: { key: 'build', name: 'Builder', initial: 'Bu' },
25
+ });
26
+
27
+ /** [role key, pattern over a skill name]. The first match wins, so the narrow patterns come first. */
28
+ const TABLE = Object.freeze([
29
+ ['eval', /^(eval-rubric|evaluator|explain-run|correction-signal-derive|eval|evals?-.+|.*-eval)$/],
30
+ ['spec', /^(prd|requirements-elicitation|write-spec|spec|.*-prd)$/],
31
+ ['design', /^(design-brief|design-reconcile|prototype|prototype-grill|design.*)$/],
32
+ ['delivery', /^(tracker-handoff|sprint-planning|jira.*|delivery.*|release-plan.*)$/],
33
+ ['comms', /^(pm-communication|stakeholder-update|weekly-update|copywriting|release-notes?|roadmap-update|status-report|comms.*)$/],
34
+ ['research', /^(discovery|source-to-concept|synthesize-research|research.*|interview.*|ingest-repo)$/],
35
+ ['strategy', /^(okr|strategic-brief|pmos-router|metrics-review|health-budgets?|strategy.*|okrs?-.+)$/],
36
+ ['build', /^(builder|factory.*|build-.+)$/],
37
+ ]);
38
+
39
+ const clean = (s) => String(s == null ? '' : s).trim().toLowerCase().replace(/^\//, '').replace(/\.skill$/, '').replace(/^.*[/:]/, '');
40
+
41
+ /** The role of one skill name, or null. */
42
+ function roleOfSkill(skill) {
43
+ const k = clean(skill);
44
+ if (!k || !/^[a-z0-9][a-z0-9._-]{0,80}$/.test(k)) return null;
45
+ for (const [role, re] of TABLE) if (re.test(k)) return ROLES[role];
46
+ return null;
47
+ }
48
+
49
+ /** A skill named in an origin tag: "schedule:okr", "skill:prd", "core-doc:prd:viewer" → the first part that is a known skill. */
50
+ function skillOfOrigin(origin) {
51
+ const parts = String(origin || '').split(':').slice(1);
52
+ for (const p of parts) if (roleOfSkill(p)) return p;
53
+ return null;
54
+ }
55
+
56
+ /** The first slash command of a conversation's first user text ("/prd viewer" → "prd"), or null. */
57
+ function slashOf(text) {
58
+ const m = /^\s*\/([a-z0-9][a-z0-9._:-]{0,60})/i.exec(String(text || ''));
59
+ return m ? m[1] : null;
60
+ }
61
+
62
+ function roleOf({ skill, origin, first } = {}) {
63
+ return roleOfSkill(skill) || roleOfSkill(skillOfOrigin(origin)) || roleOfSkill(slashOf(first)) || ROLES.claude;
64
+ }
65
+
66
+ /** The table as plain data for the page: [{ key, name, initial, patterns: [source] }]. */
67
+ function tableForPage() {
68
+ return Object.values(ROLES).map((r) => ({ ...r, patterns: TABLE.filter(([k]) => k === r.key).map(([, re]) => re.source) }));
69
+ }
70
+
71
+ module.exports = { ROLES, TABLE, roleOf, roleOfSkill, skillOfOrigin, slashOf, tableForPage };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ /* lib/board-grill.js — the first questions of a new initiative (initiative premium-uncovered-features, Board: BdNew, BdGrill).
3
+ *
4
+ * fold(lines, id) → { id, why, material: { links, files }, answers: { [q]: text }, later, at } PURE
5
+ * questionsOf(state) → [{ key, n, of, topic, q, why, chips, answer }] PURE
6
+ * summaryOf(state) → { open, total, later, took: [line] } PURE
7
+ *
8
+ * A new initiative starts in Triage with no lane choice. Right after it is made, the Board shows what PMOS took from the PM's words and
9
+ * material, then asks only what they leave open, one question at a time. The questions are the BRD's four parts (the Triage output:
10
+ * business case, who asked, problem, success measure). A part the Why already answers is not asked. "Later" keeps the open questions as
11
+ * the initiative's next step.
12
+ *
13
+ * FILE MODE ONLY (D64/D66): one append-only file, <state>/triage-answers.jsonl, with lines
14
+ * { kind: 'start', initiative, why, links: [{ url, label }] } the New initiative panel's Why and links
15
+ * { kind: 'file', initiative, name, type, size, path } a file the PM added (its bytes are in <state>/material/<initiative>/)
16
+ * { kind: 'answer', initiative, q, answer } one answer (the last one per question wins)
17
+ * { kind: 'later', initiative } the PM closed the questions with Later
18
+ * Nothing here reads the material for the PM or sends it anywhere: an agent session reads it during Triage. */
19
+
20
+ /** The BRD's parts as questions. `answeredBy` says when the Why already answers one, so it is not asked. */
21
+ const QUESTIONS = [
22
+ { key: 'problem', topic: 'Problem', q: 'What problem does it solve, and who is stuck today?', why: 'The BRD starts from the problem. Your Why did not name it, so PMOS asks.',
23
+ chips: [], answeredBy: (why) => words(why) >= 8 },
24
+ { key: 'who', topic: 'Who asked', q: 'Who asked for it, or who feels the problem most?', why: 'The BRD names who asked, so the right people review it.',
25
+ chips: ['Customers', 'Partners', 'An internal team', 'Not sure yet'] },
26
+ { key: 'case', topic: 'Business case', q: 'What does it win or save if it works?', why: 'The business case decides its rank against the other initiatives.',
27
+ chips: ['Revenue', 'Retention', 'Cost', 'Risk', 'Not sure yet'] },
28
+ { key: 'success', topic: 'Success', q: 'What would show it worked?', why: 'The success measure becomes the target that Monitor reads after the release.',
29
+ chips: ['A metric moves', 'Fewer support tickets', 'A customer renews', 'Not sure yet'] },
30
+ ];
31
+ const KEYS = new Set(QUESTIONS.map((x) => x.key));
32
+ const words = (s) => String(s || '').trim().split(/\s+/).filter((w) => w.length > 1).length;
33
+
34
+ /** The state of one initiative from the file's lines. Pure. */
35
+ function fold(lines, id) {
36
+ const st = { id, why: '', material: { links: [], files: [] }, answers: {}, later: false, at: null };
37
+ for (const l of lines || []) {
38
+ if (!l || l.initiative !== id) continue;
39
+ if (l.kind === 'start') {
40
+ st.why = typeof l.why === 'string' ? l.why : st.why; st.at = st.at || l.at || null;
41
+ for (const k of Array.isArray(l.links) ? l.links : []) if (k && k.url && !st.material.links.some((x) => x.url === k.url)) st.material.links.push({ url: String(k.url), label: String(k.label || k.url) });
42
+ } else if (l.kind === 'file' && l.name) st.material.files.push({ name: String(l.name), type: String(l.type || ''), size: Number(l.size) || 0, path: l.path || null });
43
+ else if (l.kind === 'answer' && KEYS.has(l.q)) { if (String(l.answer || '').trim()) st.answers[l.q] = String(l.answer).trim(); else delete st.answers[l.q]; }
44
+ else if (l.kind === 'later') st.later = true;
45
+ }
46
+ return st;
47
+ }
48
+ /** The questions PMOS asks: the BRD parts the Why does not answer, numbered, each with its answer when there is one. Pure. */
49
+ function questionsOf(st) {
50
+ const ask = QUESTIONS.filter((x) => !(x.answeredBy && x.answeredBy(st.why)));
51
+ return ask.map((x, i) => ({ key: x.key, n: i + 1, of: ask.length, topic: x.topic, q: x.q, why: x.why, chips: x.chips.slice(), answer: st.answers[x.key] || '' }));
52
+ }
53
+ /** How many questions are still open, and what PMOS took from the Why and the material, in plain lines. Pure. */
54
+ function summaryOf(st) {
55
+ const qs = questionsOf(st), open = qs.filter((x) => !x.answer).length, L = st.material.links.length, F = st.material.files.length;
56
+ const took = [];
57
+ if (st.why.trim()) took.push('Your Why: ' + st.why.trim());
58
+ if (QUESTIONS[0].answeredBy(st.why)) took.push('It names the problem, so PMOS does not ask about it.');
59
+ if (L || F) took.push('Material: ' + [L ? L + ' ' + (L === 1 ? 'link' : 'links') : '', F ? F + ' ' + (F === 1 ? 'file' : 'files') : ''].filter(Boolean).join(' and ') + '. An agent reads it in Triage and drafts the BRD from it.');
60
+ return { open, total: qs.length, later: st.later, took };
61
+ }
62
+
63
+ module.exports = { QUESTIONS, fold, questionsOf, summaryOf };
@@ -89,35 +89,93 @@ function ticketsBy(sprints, items) {
89
89
  }
90
90
  return by;
91
91
  }
92
- /** The stage track of one row: its step, the output that finishes it, progress toward it and the tickets behind that progress. */
92
+ /** The parts that finish each step, as the Agreed design's "What finishes each step" frame names them. Only Build and Deliver (Jira tickets),
93
+ * Plan (dates and pushed tickets) and Prioritize (anchor and rank) have a record PMOS reads; the other parts are named but not counted. */
94
+ const PARTS = {
95
+ triage: ['business case', 'who asked', 'problem', 'success measure'],
96
+ discover: ['problem', 'users', 'evidence', 'scope', 'success metric', 'risks'],
97
+ plan: ['scope', 'timeline', 'tickets in Jira'],
98
+ prioritize: ['KR or health budget', 'rank'],
99
+ monitor: ['days of data', 'outcome report'],
100
+ evaluate: ['report', 'evaluation', 'your verdict'],
101
+ };
102
+ /** A progress the record holds: the route gives a fraction (0..1), older readings a percent. → a whole percent, or null. */
103
+ const pctOf = (v) => { const n = Number(v); if (v == null || v === '' || !Number.isFinite(n)) return null; return Math.max(0, Math.min(100, Math.round(n <= 1 ? n * 100 : n))); };
104
+ /** The stage track of one row: its step, the output that finishes it, the parts or tickets counted toward it, the steps it skipped
105
+ * (a move past a stage leaves a "Skipped <stage>" warning on the row) and what waits on the PM. Nothing is invented: a part PMOS
106
+ * has no record for is named and left uncounted. */
93
107
  function trackOf(r, tickets, today, release) {
94
- const k = stepIndex(r.stage, r.cat), step = STEPS[k] || null;
108
+ const k = stepIndex(r.stage, r.cat), step = STEPS[k] || null, key = step ? step.key : null;
95
109
  const tk = (tickets || []).slice(0, 40);
96
110
  const done = tk.filter((t) => t.status === 'Done').length, blocked = tk.filter((t) => t.blocked);
97
111
  const pts = tk.filter((t) => t.points != null), ptsAll = pts.reduce((n, t) => n + t.points, 0), ptsDone = pts.filter((t) => t.status === 'Done').reduce((n, t) => n + t.points, 0);
98
112
  const byPts = pts.length === tk.length && ptsAll > 0;
99
- const jira = !!(step && (step.key === 'build' || step.key === 'deliver') && tk.length);
113
+ const jira = !!((key === 'build' || key === 'deliver') && tk.length);
100
114
  let out = step ? step.output : 'No step on record';
101
- if (step && step.key === 'deliver' && release) out = release + ' shipped + your sign-off';
115
+ if (key === 'deliver' && release) out = release + ' shipped + your sign-off';
116
+ const pct = r.progress != null ? r.progress : null;
102
117
  const prog = jira
103
118
  ? { done: byPts ? ptsDone : done, total: byPts ? ptsAll : tk.length, unit: byPts ? 'pts' : 'tickets', parts: tk.map((t) => t.cls || '') }
104
- : r.progress != null ? { done: Math.round(r.progress), total: 100, unit: '%', parts: null } : null;
105
- const review = tk.filter((t) => t.status === 'In review');
106
- const next = blocked.length ? { tone: 'red', text: blocked[0].key + ' blocked' + (blocked[0].reason ? ' · ' + blocked[0].reason : '') }
107
- : review.length ? { tone: '', text: review.map((t) => t.key).slice(0, 2).join(', ') + ' in review' }
108
- : prog ? null : { tone: '', text: step ? 'Nothing is counted toward it yet' : 'Its stage is not one of the eight steps' };
119
+ : pct != null ? { done: pct, total: 100, unit: '%', parts: null } : null;
120
+ // the segments of the Output bar and the words under it
121
+ let segs = [], count = '', line = [];
122
+ if (jira) {
123
+ segs = tk.map((t) => ({ cls: t.cls || '', tk: t.key }));
124
+ count = prog.done + ' of ' + prog.total + (byPts ? ' pts' : '');
125
+ if (blocked.length) line.push({ text: blocked[0].key + ' blocked' + (blocked[0].reason ? ' · ' + blocked[0].reason : ''), tone: 'red' });
126
+ const review = tk.filter((t) => t.status === 'In review');
127
+ if (review.length) line.push({ text: review.map((t) => t.key + (review.length === 1 ? ' ' + t.title : '')).slice(0, 2).join(', ') + ' in review' });
128
+ if (!line.length) { const doing = tk.filter((t) => t.status === 'In progress'); line.push({ text: doing.length ? doing.length + ' in progress · ' + (tk.length - done - doing.length) + ' to do' : done === tk.length ? 'Every ticket is done' : (tk.length - done) + ' to do' }); }
129
+ } else if (key === 'plan' || key === 'prioritize') {
130
+ const have = key === 'plan' ? [null, !!(r.start && r.end), tk.length > 0] : [!!r.anchor, Number.isInteger(r.rank)];
131
+ segs = have.map((h, i) => ({ cls: h ? 'dn' : '', name: cap1(PARTS[key][i], 0), st: h === true ? 'done' : h === null ? 'not on record' : 'to do' }));
132
+ const n = have.filter(Boolean).length, known = have.filter((h) => h !== null).length;
133
+ count = n + ' of ' + have.length;
134
+ const words = PARTS[key].map((w, i) => (have[i] === true ? cap1(w, i) + ' ✓' : have[i] === null ? cap1(w, i) + ' not on record' : cap1(w, i)));
135
+ if (key === 'prioritize' && !r.anchor) line.push({ text: 'Needs a KR or health budget' });
136
+ else line.push({ text: words.join(' · ') });
137
+ if (known === 0) count = '— of ' + have.length;
138
+ } else if (step && PARTS[key]) {
139
+ segs = PARTS[key].map((w) => ({ cls: '', name: cap1(w, 0), st: 'not counted' }));
140
+ count = '— of ' + PARTS[key].length + ' parts';
141
+ line.push({ text: PARTS[key].map(cap1).join(' · '), muted: true });
142
+ } else if (key === 'build' || key === 'deliver') {
143
+ segs = [{ cls: 'na' }];
144
+ count = 'No tickets yet';
145
+ line.push({ text: 'No Jira ticket has been read for it yet', muted: true });
146
+ } else if (step) {
147
+ count = 'Not counted yet';
148
+ line.push({ text: 'Nothing is counted toward it yet' });
149
+ } else line.push({ text: 'Its stage is not one of the eight steps' });
150
+ if (!jira && pct != null) { count = pct + '%'; }
151
+ // a step the row was moved past (lib/routes-boards.js keeps the move's "Skipped <stage>" warning)
152
+ const skipped = [...new Set((r.warnings || []).map((w) => (typeof w === 'string' ? /^Skipped (.+)$/.exec(w) : null)).filter(Boolean).map((m) => stepIndex(m[1], null)).filter((i) => i >= 0 && (k < 0 || i < k)))].sort((a, b) => a - b);
153
+ // what waits on the PM: the sign-off of a release whose tickets are all done (the last part of Deliver is the PM's)
154
+ const you = key === 'deliver' && tk.length && done === tk.length ? 'Your sign-off' + (release ? ' · ' + release : '') : null;
109
155
  const upd = r.updated ? days(String(r.updated).slice(0, 10), today) : null;
110
156
  const fc = tk.filter((t) => t.status !== 'Done' && t.sprintEnd).map((t) => t.sprintEnd).sort().pop() || null;
111
- return { k, key: step ? step.key : null, label: step ? step.label : (r.stage || 'No stage'), ms: !!(step && step.ms), output: out, prog, next, tickets: tk, blocked: blocked.length,
112
- idle: upd != null && upd >= 30 && r.status !== 'done' ? upd : null, forecast: fc, forecastLabel: fc ? shortDate(fc) : '' };
157
+ const next = line.find((x) => x.tone === 'red') || null;
158
+ return { k, key, label: step ? step.label : (r.stage || 'No stage'), ms: !!(step && step.ms), output: out, prog, pct: jira ? null : pct, segs, count, line, next, tickets: tk, blocked: blocked.length, skipped, you,
159
+ days: null, idle: upd != null && upd >= 30 && r.status !== 'done' ? upd : null, forecast: fc, forecastLabel: fc ? shortDate(fc) : '' };
160
+ }
161
+ const cap1 = (w, i) => (i === 0 ? w.charAt(0).toUpperCase() + w.slice(1) : w);
162
+ /** The short label of an anchor: q3-2026:o2:kr1 → KR 2.1; health:<id> → Health budget. */
163
+ function krShort(anchor) {
164
+ const a = String(anchor || '');
165
+ if (!a) return '';
166
+ if (/^health:/.test(a)) return 'Health budget';
167
+ const m = /:o(\d+):kr(\d+)/i.exec(a);
168
+ return m ? 'KR ' + m[1] + '.' + m[2] : clip(a, 24);
113
169
  }
114
170
  /** The anchor's theme, for the long timeline spans: the objective a KR belongs to, or the health budgets. */
115
171
  function themeOf(anchor) {
116
172
  const a = String(anchor || '');
117
- if (!a) return { key: 'none', label: 'No anchor' };
118
- if (/^health:/.test(a)) return { key: 'health', label: 'Health budgets' };
119
- const m = /^(.*?):(o\d+)/i.exec(a);
120
- return m ? { key: m[1] + ':' + m[2], label: m[2].toUpperCase() + ' · ' + m[1] } : { key: a, label: a };
173
+ if (!a) return { key: 'none', label: 'No anchor', kind: 'none', period: '' };
174
+ if (/^health:/.test(a)) return { key: 'health', label: 'Health budgets', kind: 'health', period: '' };
175
+ const m = /^(.*?):o(\d+)/i.exec(a);
176
+ if (!m) return { key: a, label: clip(a, 40), kind: 'other', period: '' };
177
+ const q = /^q(\d)-(\d{4})$/i.exec(m[1]);
178
+ return { key: m[1] + ':o' + m[2], label: 'Objective ' + m[2], kind: 'kr', period: q ? 'Q' + q[1] + ' ' + q[2] : m[1] };
121
179
  }
122
180
 
123
181
  /** What the row's ⋯ menu and the initiative page's bar can do, from the row's own fields (initiative premium-board-actions): its workflow's stage names,
@@ -128,13 +186,35 @@ function actsOf(r, boardNames) {
128
186
  const life = r.status === 'on hold' ? 'hold' : r.status === 'cancelled' ? 'cancelled' : null;
129
187
  return {
130
188
  stages: own, stage: r.stage || null, life, reason: life ? clip(st.reason || '', 300) : '', back: life === 'hold' && st.back ? shortDate(st.back) : '', backDay: life === 'hold' && st.back ? String(st.back).slice(0, 10) : null,
131
- archived: r.archived ? { reason: clip(r.archived.reason || '', 300), into: r.archived.into ? (r.archived.intoTitle || r.archived.into) : null } : null,
189
+ ...(life && st.at ? { since: shortDate(String(st.at).slice(0, 10)) } : {}),
190
+ archived: r.archived ? { reason: clip(r.archived.reason || '', 300), into: r.archived.into ? (r.archived.intoTitle || r.archived.into) : null, ...(r.archived.at ? { at: shortDate(String(r.archived.at).slice(0, 10)) } : {}) } : null,
132
191
  };
133
192
  }
134
- const askOf = (a) => {
193
+ /** The words an ask and an initiative title share (three letters or more, not common words), for "Close to: <initiative>". */
194
+ const STOP = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'who', 'what', 'when', 'can', 'are', 'was', 'not', 'our', 'your', 'their', 'they', 'keep', 'asking', 'want', 'wants', 'need', 'needs', 'into', 'each', 'all', 'any', 'has', 'have', 'its']);
195
+ const sig = (s) => new Set(String(s || '').toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3 && !STOP.has(w)));
196
+ /** The open initiative an ask is closest to: it shares two words with its title, or half of a short title's words. Null when none does. */
197
+ function closeTo(line, rows) {
198
+ const want = sig(line);
199
+ let best = null;
200
+ for (const r of rows || []) {
201
+ const have = sig(r.title), shared = [...have].filter((w) => want.has(w)).length;
202
+ if (!have.size || !(shared >= 2 || (shared >= 1 && shared / have.size >= 0.5))) continue;
203
+ if (!best || shared > best.n) best = { n: shared, id: r.id, key: r.key, title: r.title, stage: (r.track && r.track.label) || r.stage || '' };
204
+ }
205
+ return best ? { id: best.id, key: best.key, title: best.title, stage: best.stage } : null;
206
+ }
207
+ /** One ask as the New asks card draws it (initiative premium-uncovered-features, BdAsks): who and where it came from, the draft, the product it is for
208
+ * and why, the products it could be for when the record names more than one, a prior rejection and the open initiative it is close to. */
209
+ const askOf = (a, board, rows) => {
135
210
  const d = a.draft || {};
211
+ const products = Array.isArray(a.products) ? a.products.filter((x) => x && (x.id || x.name)).slice(0, 4).map((x) => ({ id: String(x.id || x.name), name: String(x.name || x.id), why: clip(x.why || '', 160) })) : [];
136
212
  return { id: a.id, line: clip(a.line, 500), source: a.source || '', by: a.by || '', at: a.at ? shortDate(String(a.at).slice(0, 10)) : '',
137
- draft: { title: clip(d.title || a.line, 120), lane: LANES.includes(d.lane) ? d.lane : null, anchor: d.anchor_suggestion || '' } };
213
+ draft: { title: clip(d.title || a.line, 120), lane: LANES.includes(d.lane) ? d.lane : null, anchor: d.anchor_suggestion || '' },
214
+ product: products.length > 1 ? null : { name: (products[0] && products[0].name) || board.name || '', why: (products[0] && products[0].why) || (a.source ? 'came in through ' + clip(a.source, 80) + ' on this board' : 'came in on this board') },
215
+ products: products.length > 1 ? products : [],
216
+ prior: (Array.isArray(d.prior_rejections) ? d.prior_rejections : []).slice(0, 3).map((x) => ({ file: String(x.file || ''), title: clip(x.title || '', 120) })),
217
+ close: closeTo(a.line, rows) };
138
218
  };
139
219
 
140
220
  function rowOf(r, wf, today) {
@@ -143,7 +223,7 @@ function rowOf(r, wf, today) {
143
223
  const facts = [
144
224
  ['Lane', r.lane], ['Stage', r.stage ? r.stage + (r.stageSource ? ' (' + r.stageSource + ')' : '') : ''], ['Anchor', r.anchor], ['Horizon', r.horizon],
145
225
  ['Status', STATUS_LABEL[r.status] || (r.status ? r.status.charAt(0).toUpperCase() + r.status.slice(1) : '')], ['Owner', r.owner],
146
- ['Progress', r.progress != null ? Math.round(r.progress) + '%' : ''], ['Starts', r.start ? shortDate(r.start) : ''], ['Ends', r.end ? shortDate(r.end) : ''],
226
+ ['Progress', pctOf(r.progress) != null ? pctOf(r.progress) + '%' : ''], ['Starts', r.start ? shortDate(r.start) : ''], ['Ends', r.end ? shortDate(r.end) : ''],
147
227
  ['Last changed', r.updated ? shortDate(String(r.updated).slice(0, 10)) : ''], ['Possible duplicate of', r.dupOf], ['Warnings', (r.warnings || []).map((w) => (typeof w === 'string' ? w : w && (w.text || w.message || w.id)) || '').filter(Boolean).join('; ')],
148
228
  ].filter((x) => x[1]);
149
229
  const over = r.end && today && days(r.end, today) > 0 && r.status !== 'done';
@@ -151,9 +231,9 @@ function rowOf(r, wf, today) {
151
231
  key: 'board:' + r.id, id: r.id, title: clip(r.title, 140), sub: [r.owner || 'No owner', r.lane].filter(Boolean).join(' · '),
152
232
  status: r.status || null, statusLabel: r.status && r.status !== 'on track' ? (STATUS_LABEL[r.status] || r.status) : null, bad, late: r.status === 'late',
153
233
  stage: r.stage || null, cat: r.cat || null, stageNote: r.stageSource === 'derived' ? 'derived' : null,
154
- seg: names.map((n, j) => (j < cur ? 'p' : j === cur ? 'n' : '')), progress: r.progress != null ? Math.max(0, Math.min(100, Math.round(r.progress))) : null,
234
+ seg: names.map((n, j) => (j < cur ? 'p' : j === cur ? 'n' : '')), progress: pctOf(r.progress),
155
235
  finish: r.end ? shortDate(r.end) : 'Not planned', over: !!over, start: r.start || null, end: r.end || null,
156
- owner: r.owner || null, lane: r.lane || null, anchor: r.anchor || null, updated: r.updated || null, overDays: over ? days(r.end, today) : 0,
236
+ owner: r.owner || null, lane: r.lane || null, anchor: r.anchor || null, kr: krShort(r.anchor), rank: Number.isInteger(r.rank) ? r.rank : null, warnings: (r.warnings || []).filter((w) => typeof w === 'string').slice(0, 12), epics: Array.isArray(r.epics) ? r.epics.filter((e) => typeof e === 'string').slice(0, 6) : [], updated: r.updated || null, reading: r.reading || null, overDays: over ? days(r.end, today) : 0,
157
237
  acts: actsOf(r, names),
158
238
  dialog: {
159
239
  eye: 'Initiative', logTitle: 'Read from the board',
@@ -183,7 +263,15 @@ function build(f) {
183
263
  // the Agreed design's stage track (premium-agreed-design): tickets, output and progress per row
184
264
  const tkBy = ticketsBy((f.sprints && Array.isArray(f.sprints.sprints)) ? f.sprints.sprints : [], f.items || []);
185
265
  const relOfIni = new Map(); if (f.nextRelease && f.nextRelease.at) for (const id of f.nextRelease.ini || []) relOfIni.set(id, f.nextRelease.name || f.nextRelease.id);
186
- for (const r of rows.concat(stageRows, gone.cancelled, gone.archived)) if (!r.track) { r.track = trackOf(r, tkBy.get(r.id), todayIso, relOfIni.get(r.id)); r.theme = themeOf(r.anchor); }
266
+ const relAt = f.nextRelease && f.nextRelease.at ? String(f.nextRelease.at).slice(0, 10) : null;
267
+ // the Jira epic of each initiative, from the board's work items (Linked: Epic <key>)
268
+ const epicBy = new Map(); for (const w of f.items || []) if (w && w.kind === 'Epic' && w.key && w.ini && !epicBy.has(w.ini)) epicBy.set(w.ini, w.key);
269
+ for (const r of rows.concat(stageRows, gone.cancelled, gone.archived)) if (!r.track) {
270
+ r.track = trackOf(r, tkBy.get(r.id), todayIso, relOfIni.get(r.id)); r.theme = themeOf(r.anchor);
271
+ if (epicBy.has(r.id) && !r.epics.includes(epicBy.get(r.id))) r.epics.unshift(epicBy.get(r.id));
272
+ // the release it rides on, with the days to it (the status line says when it ships)
273
+ r.release = relOfIni.has(r.id) && relAt ? { name: relOfIni.get(r.id), at: shortDate(relAt), iso: relAt, days: days(todayIso, relAt) } : null;
274
+ }
187
275
  // the timeline: only an initiative with both a start and an end date has a bar
188
276
  const dated = rows.filter((r) => r.start && r.end && isoDay(r.start) && isoDay(r.end));
189
277
  let timeline;
@@ -275,9 +363,18 @@ function build(f) {
275
363
  // the Agreed design (premium-agreed-design): the eight steps with the board's own count in each, the Jira read time and the chip counts
276
364
  steps: STEPS.map((st, i) => ({ ...st, count: stages.filter((c) => stepIndex(c.stage, c.cat) === i).reduce((n, c) => n + c.count, 0) })),
277
365
  jira: { source: sp.source || 'none', readAt: sp.readAt || null, release: nr && nr.at ? { name: nr.name || nr.id, at: shortDate(String(nr.at).slice(0, 10)), iso: String(nr.at).slice(0, 10) } : null,
278
- sprint: active ? { name: active.name, start: active.start ? String(active.start).slice(0, 10) : null, end: active.end ? String(active.end).slice(0, 10) : null } : null },
366
+ sprint: active ? { name: active.name, start: active.start ? String(active.start).slice(0, 10) : null, end: active.end ? String(active.end).slice(0, 10) : null } : null,
367
+ // every sprint of the reading, oldest first, with its points where the reading holds them (initiative premium-uncovered-features, BdSprint)
368
+ sprints: sp.source === 'jira' ? sprints.slice().sort((a, b) => String(a.start || '').localeCompare(String(b.start || ''))).map((x) => {
369
+ const iss = x.issues || [], pts = iss.filter((i) => Number.isFinite(i.points)), k = x.counts || {};
370
+ return { name: x.name, state: x.state || '', start: x.start ? String(x.start).slice(0, 10) : null, end: x.end ? String(x.end).slice(0, 10) : null, now: x === active,
371
+ pts: pts.length ? { done: pts.filter((i) => tkStatus(i.status, i.category) === 'Done').reduce((n, i) => n + i.points, 0), total: pts.reduce((n, i) => n + i.points, 0) } : null,
372
+ counts: { done: k.done || 0, doing: k.doing || 0, todo: k.todo || 0 } };
373
+ }) : [],
374
+ // the open tickets that sit in no sprint: the backlog
375
+ backlog: [...tkBy.entries()].flatMap(([ini, list]) => list.filter((t) => !t.sprint && t.status !== 'Done').map((t) => ({ key: t.key, title: t.title, ini, iniTitle: ((rows.find((r) => r.id === ini) || {}).title) || '', points: t.points, status: t.status }))).slice(0, 60) },
279
376
  chips: { late, risk, blocked: rows.filter((r) => r.track && r.track.blocked).length, idle: rows.filter((r) => r.track && r.track.idle != null).length, asks: f.asks == null ? null : f.asks.filter((a) => a && a.state !== 'accepted' && a.state !== 'declined').length },
280
- asks: f.asks == null ? { missing: true, rows: [] } : { rows: f.asks.filter((a) => a && a.state !== 'accepted' && a.state !== 'declined').slice(0, 50).map(askOf) },
377
+ asks: f.asks == null ? { missing: true, rows: [] } : { rows: f.asks.filter((a) => a && a.state !== 'accepted' && a.state !== 'declined').slice(0, 50).map((a) => askOf(a, board, rows)) },
281
378
  dock: { needs: risk + late, label: 'need a look', release: nr && nr.at ? { at: shortDate(String(nr.at).slice(0, 10)), name: nr.name || nr.id } : null, next: (rows.find((r) => r.late) || rows.find((r) => r.bad) || {}).title || null },
282
379
  rows: rows.concat(stageRows.filter((r) => !rows.some((x) => x.key === r.key)), gone.cancelled, gone.archived, [sprintRow, relRow].filter(Boolean)).concat([{ key: 'board:this-board', id: null, title: board.name || 'This board', sub: 'Board', dialog: { eye: 'Board', logTitle: 'Read from the board', log: ['Read the board and its initiatives', 'Counted them by status', 'Changed nothing'], say: (board.name || 'This board') + ' has ' + open + ' open ' + plural(open, 'initiative', 'initiatives') + ': ' + on + ' on track, ' + risk + ' at risk, ' + late + ' late' + (hold ? ', ' + hold + ' on hold' : '') + '.', head: 'Where it stands', facts: [['Open initiatives', String(open)], ['On track', String(on)], ['At risk', String(risk)], ['Late', String(late)], ['On hold', hold ? String(hold) : '']].filter((x) => x[1] !== ''), hold: 'Nothing here changes a board.', pane: { label: 'Board record', file: '', note: 'The board as its records hold it.', rows: [['Open initiatives', String(open)], ['On track', String(on)], ['At risk', String(risk)], ['Late', String(late)], ['On hold', hold ? String(hold) : '']].filter((x) => x[1] !== '') } } }]),
283
380
  };
@@ -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 };