create-pmos 0.827.0 → 0.829.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 (103) hide show
  1. package/package.json +217 -45
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/bin/pmos.js +19 -9
  7. package/workspace/board-deliveries-test.js +2 -2
  8. package/workspace/changelog.json +216 -12
  9. package/workspace/guide/cli.md +62 -0
  10. package/workspace/guide/home.md +1 -0
  11. package/workspace/guide/settings-and-switches.md +1 -0
  12. package/workspace/lib/board-cli.js +5 -1
  13. package/workspace/lib/board-premium.js +1 -0
  14. package/workspace/lib/critical-needs.js +162 -0
  15. package/workspace/lib/deps-cli.js +102 -0
  16. package/workspace/lib/engine/boards.js +13 -2
  17. package/workspace/lib/features.json +5 -0
  18. package/workspace/lib/five-action-cap.js +84 -0
  19. package/workspace/lib/needs-providers.js +1 -0
  20. package/workspace/lib/page-one-answer.js +86 -0
  21. package/workspace/lib/pages-cli.js +6 -2
  22. package/workspace/lib/people-cli.js +43 -2
  23. package/workspace/lib/pmos-verbs.js +15 -1
  24. package/workspace/lib/portfolio-cli.js +64 -0
  25. package/workspace/lib/portfolio.js +168 -0
  26. package/workspace/lib/prototype-cli.js +86 -0
  27. package/workspace/lib/report-cli.js +12 -2
  28. package/workspace/lib/report-readers.js +5 -3
  29. package/workspace/lib/review-pack.js +348 -0
  30. package/workspace/lib/review-reasons.js +357 -0
  31. package/workspace/lib/route-modules.js +6 -0
  32. package/workspace/lib/routes-boards.js +25 -2
  33. package/workspace/lib/routes-portfolio.js +50 -0
  34. package/workspace/lib/routes-review-pack.js +42 -0
  35. package/workspace/lib/routes-roadmap-ops.js +53 -1
  36. package/workspace/lib/routes-sim-users.js +66 -0
  37. package/workspace/lib/routes-stakeholders.js +42 -0
  38. package/workspace/lib/routes-strategy-card.js +29 -1
  39. package/workspace/lib/routes-team-waits.js +24 -0
  40. package/workspace/lib/routes-use-log.js +6 -1
  41. package/workspace/lib/sim-users.js +329 -0
  42. package/workspace/lib/stakeholder-map.js +232 -0
  43. package/workspace/lib/task-store.js +1 -1
  44. package/workspace/lib/team-waits.js +167 -0
  45. package/workspace/lib/tradeoff-cards.js +258 -0
  46. package/workspace/lib/tradeoff-cli.js +83 -0
  47. package/workspace/lib/voice-cli.js +7 -0
  48. package/workspace/package-lock.json +2 -2
  49. package/workspace/package.json +1 -1
  50. package/workspace/premium-vw-jira-test.js +6 -2
  51. package/workspace/public/pm/bd-backlog.js +44 -6
  52. package/workspace/public/pm/bd-principles.js +12 -1
  53. package/workspace/public/pm/cozy-library.css +5 -0
  54. package/workspace/public/pm/cozy-pick.css +1 -0
  55. package/workspace/public/pm/cozy-pop-work.js +8 -2
  56. package/workspace/public/pm/cozy-proto.css +5 -0
  57. package/workspace/public/pm/cozy-proto.js +11 -3
  58. package/workspace/public/pm/cozy-today-app.js +53 -3
  59. package/workspace/public/pm/cozy-today-view.js +12 -4
  60. package/workspace/public/pm/day-time.js +8 -0
  61. package/workspace/public/pm/five-action-cap.js +104 -0
  62. package/workspace/public/pm/home-ini.js +3 -2
  63. package/workspace/public/pm/ini-links.js +2 -1
  64. package/workspace/public/pm/ini-tasks.js +5 -2
  65. package/workspace/public/pm/ini-view-model.js +14 -6
  66. package/workspace/public/pm/ini-view.js +12 -2
  67. package/workspace/public/pm/library-model.js +1 -1
  68. package/workspace/public/pm/page-one-answer.css +18 -0
  69. package/workspace/public/pm/page-one-answer.js +134 -0
  70. package/workspace/public/pm/pop-work-model.js +8 -6
  71. package/workspace/public/pm/portfolio.js +67 -0
  72. package/workspace/public/pm/premium-board.js +19 -6
  73. package/workspace/public/pm/premium-library.js +27 -3
  74. package/workspace/public/pm/product-switcher.js +7 -1
  75. package/workspace/public/pm/range-pick.css +12 -0
  76. package/workspace/public/pm/range-pick.js +30 -6
  77. package/workspace/public/pm/review-pack.js +47 -0
  78. package/workspace/public/pm/review-reasons.js +75 -0
  79. package/workspace/public/pm/sim-users.js +34 -0
  80. package/workspace/public/pm/sort-order.js +3 -0
  81. package/workspace/public/pm/stakeholder-map.js +125 -0
  82. package/workspace/public/pm/task-card.js +10 -7
  83. package/workspace/public/pm/team-waits.js +56 -0
  84. package/workspace/public/pm/tradeoff-cards.css +27 -0
  85. package/workspace/public/pm/tradeoff-cards.js +183 -0
  86. package/workspace/public/premium-board.html +1 -0
  87. package/workspace/public/premium-portfolio.html +48 -0
  88. package/workspace/public/today.html +1 -0
  89. package/workspace/run-tests.js +9 -1
  90. package/workspace/server.js +1 -1
  91. package/workspace/stage-card-tasks-test.js +11 -5
  92. package/workspace/test-lists/critical-needs.json +9 -0
  93. package/workspace/test-lists/five-action-cap.json +9 -0
  94. package/workspace/test-lists/page-one-answer.json +9 -0
  95. package/workspace/test-lists/portfolio.json +9 -0
  96. package/workspace/test-lists/review-pack.json +9 -0
  97. package/workspace/test-lists/review-reasons.json +9 -0
  98. package/workspace/test-lists/sim-users.json +9 -0
  99. package/workspace/test-lists/stakeholder-map.json +9 -0
  100. package/workspace/test-lists/task-time-optional.json +9 -0
  101. package/workspace/test-lists/team-waits.json +9 -0
  102. package/workspace/test-lists/tradeoff-cards.json +9 -0
  103. package/workspace/test-timings.json +25 -0
@@ -0,0 +1,232 @@
1
+ 'use strict';
2
+ /* stakeholder-map.js — who decides, who must agree and who needs to know, for one initiative, and when each last heard from the PM
3
+ * (initiative stakeholder-map, job #1896, idea A371; board BatchPeopleDS panel 9, agreed 2026-11-25). THE ONE WRITER and THE ONE FOLD of
4
+ * stakeholders.jsonl. lib/people-cli.js is the verb (`pmos people map|keep|drop|told|undo`), lib/routes-stakeholders.js the routes,
5
+ * public/pm/stakeholder-map.js the People block of the initiative popup on Work.
6
+ *
7
+ * WHERE THE NAMES COME FROM (drafts until the PM keeps them). Nothing is invented; each draft names its source:
8
+ * decides the record's `decider`, `owner` or `sponsor` key
9
+ * must agree a sign-off of this initiative asked of them, or a journal decision of it they objected to (lib/approver-memory.js)
10
+ * needs to know a person in People whose interactions name the initiative: Jira watchers, meeting notes, mail (lib/people.js)
11
+ * The PM's keep (with a group) makes a name a stakeholder; drop takes it off for good (a dropped name is never drafted again); undo takes
12
+ * back the PM's last press on that name.
13
+ *
14
+ * LAST HEARD. The newest of: the person's interactions naming this initiative, else their newest interaction at all, and the PM's own
15
+ * `told` mark ("I sent it"). At STALE_DAYS (3 weeks) or more the row carries a ✦ draft update built from the record's title and status
16
+ * line. PMOS NEVER SENDS IT: the PM copies it and sends it, then marks `told`. A name with no date has no draft (nothing to measure).
17
+ *
18
+ * draftsOf({ ini, record, people, approvals }) → [{ id, name, group, why }]
19
+ * mapOf({ ini, record, people, approvals, lines, now }) → { ini, title, rows: [row], kept, drafts }
20
+ * row: { id, name, group, groupWord, kept, why, last, days, stale, update }
21
+ * readLines(dir) · fold(lines) → Map key → { ini, id, name, group, state: kept | dropped, told }
22
+ * act(dir, { ini, person, name, kind, group }, { by, now }) → { ok, line } | { ok: false, error } kind ∈ keep · drop · told · undo
23
+ * count(dir) → names kept (the health number)
24
+ * CLI: node lib/stakeholder-map.js count <product checkout> prints `[stakeholder-map] kept N` and N alone on the last line
25
+ *
26
+ * Append-only: one line per press { at, by, kind, ini, person, name?, group?, date? }. Nothing here reads a connector or sends anything.
27
+ */
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+
31
+ const FILE = 'stakeholders.jsonl';
32
+ const TAG = '[stakeholder-map]';
33
+ const KINDS = ['keep', 'drop', 'told', 'undo'];
34
+ const GROUPS = Object.freeze(['decides', 'agree', 'know']);
35
+ const GROUP_WORD = Object.freeze({ decides: 'decides', agree: 'must agree', know: 'needs to know' });
36
+ const STALE_DAYS = 21;
37
+ const DAY = 86400000;
38
+
39
+ const one = (v, max = 200) => { const s = String(v == null ? '' : v).replace(/\s+/g, ' ').trim(); return s.length > max ? s.slice(0, max - 1).trimEnd() + '…' : s; };
40
+ const slugOf = (name) => {
41
+ const s = one(name, 80).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 50);
42
+ return s || 'person';
43
+ };
44
+ const keyOf = (ini, id) => String(ini) + '|' + String(id);
45
+ const norm = (s) => one(s, 80).toLowerCase();
46
+ /** Two names are one person: equal, or one is the other's first name ("Ana" and "Ana Lim"). */
47
+ function same(a, b) {
48
+ const x = norm(a), y = norm(b);
49
+ if (!x || !y) return false;
50
+ if (x === y) return true;
51
+ return (!x.includes(' ') && y.split(' ')[0] === x) || (!y.includes(' ') && x.split(' ')[0] === y);
52
+ }
53
+ const dateOf = (v) => { const s = String(v || '').slice(0, 10); return /^\d{4}-\d{2}-\d{2}$/.test(s) ? s : null; };
54
+ const newest = (...ds) => ds.filter(Boolean).sort().pop() || null;
55
+ const GROUP_ALIAS = { decides: 'decides', decide: 'decides', decider: 'decides', agree: 'agree', 'must-agree': 'agree', 'must agree': 'agree', know: 'know', 'needs-to-know': 'know', 'needs to know': 'know', inform: 'know' };
56
+ const groupOf = (g) => GROUP_ALIAS[String(g || '').trim().toLowerCase()] || null;
57
+
58
+ /** The draft names of one initiative, each with its group and where it came from. */
59
+ function draftsOf({ ini, record = {}, people = [], approvals = [] } = {}) {
60
+ const out = [];
61
+ const add = (name, group, why) => {
62
+ const n = one(name, 80);
63
+ if (!n || /^(pm|me|you|unassigned|none|tbd)$/i.test(n)) return;
64
+ const had = out.find((x) => same(x.name, n));
65
+ if (had) { if (GROUPS.indexOf(group) < GROUPS.indexOf(had.group)) { had.group = group; had.why = why; } if (n.length > had.name.length) had.name = n; return; }
66
+ out.push({ name: n, group, why });
67
+ };
68
+ for (const k of ['decider', 'owner', 'sponsor']) {
69
+ const v = record && record[k];
70
+ if (!v) continue;
71
+ for (const n of String(v).replace(/^person:/, '').split(/\s*[,;&]\s*|\s+and\s+/)) add(n.replace(/^person:/, ''), 'decides', `the record names them as ${k}`);
72
+ }
73
+ for (const a of approvals || []) {
74
+ if (!a || a.ini !== ini || !a.who) continue;
75
+ add(a.who, 'agree', a.kind === 'objection' ? `objected to ${one(a.decided || a.text, 60)}` : `sign-off: ${one(a.text, 60)}`);
76
+ }
77
+ for (const p of people || []) {
78
+ const g = p && p.shared && (p.shared.initiatives || []).find((x) => x.id === ini);
79
+ if (!g) continue;
80
+ const src = [...new Set((p.interactions || []).filter((i) => i.initiative === ini).map((i) => ({ jira: 'Jira', notes: 'meeting notes', gather: 'mail', live: 'Live notes', calendar: 'the calendar', plan: 'the plan' })[i.source] || i.source))];
81
+ add(p.name, 'know', `named on this initiative in ${src.join(', ') || 'People'}`);
82
+ }
83
+ // the person's id in People when they are there, so a keep and People agree; else a slug of the name
84
+ for (const d of out) { const p = (people || []).find((x) => same(x.name, d.name)); d.id = p ? p.id : slugOf(d.name); if (p) d.name = p.name; }
85
+ return out;
86
+ }
87
+
88
+ function readLines(dir) {
89
+ if (!dir) return [];
90
+ let text = '';
91
+ try { text = fs.readFileSync(path.join(dir, FILE), 'utf8'); } catch { return []; }
92
+ const out = [];
93
+ for (const l of text.split('\n')) {
94
+ if (!l.trim()) continue;
95
+ try { const o = JSON.parse(l); if (o && KINDS.includes(o.kind) && o.ini && o.person) out.push(o); } catch { /* a torn line is skipped */ }
96
+ }
97
+ return out;
98
+ }
99
+
100
+ /** The PM's presses, folded: one entry per initiative and name. An undo takes back that name's last keep, drop or told. */
101
+ function fold(lines) {
102
+ const steps = new Map(); // key → [line]
103
+ for (const l of lines || []) {
104
+ const k = keyOf(l.ini, l.person);
105
+ if (!steps.has(k)) steps.set(k, []);
106
+ const s = steps.get(k);
107
+ if (l.kind === 'undo') { s.pop(); continue; }
108
+ s.push(l);
109
+ }
110
+ const out = new Map();
111
+ for (const [k, s] of steps) {
112
+ if (!s.length) continue;
113
+ const e = { ini: s[0].ini, id: s[0].person, name: null, group: null, state: null, told: null };
114
+ for (const l of s) {
115
+ if (l.name) e.name = l.name;
116
+ if (l.kind === 'keep') { e.state = 'kept'; e.group = groupOf(l.group) || e.group; }
117
+ else if (l.kind === 'drop') e.state = 'dropped';
118
+ else if (l.kind === 'told') { e.told = newest(e.told, dateOf(l.date || l.at)); }
119
+ }
120
+ out.set(k, e);
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /** The status line the draft update quotes: the record's one-line status, else its goal. */
126
+ const statusOf = (record) => one((record && (record.status_line || record.status || record.goal)) || '', 160);
127
+
128
+ /** The ✦ draft update for one name. The PM sends it, never PMOS. */
129
+ function updateText({ name, title, record, group }) {
130
+ const first = one(name, 80).split(' ')[0];
131
+ const st = statusOf(record);
132
+ const ask = group === 'decides' ? 'Tell me if you want to decide anything before then.' : group === 'agree' ? 'Tell me if anything here does not work for you.' : 'No action needed from you.';
133
+ return one(`Hi ${first}, a short update on ${title}${st ? ': ' + st.replace(/[.\s]+$/, '') : ''}. ${ask}`, 400);
134
+ }
135
+
136
+ function mapOf({ ini, record = {}, people = [], approvals = [], lines = [], now = Date.now() } = {}) {
137
+ const title = one((record && record.title) || ini, 120);
138
+ const marks = fold(lines);
139
+ const drafts = draftsOf({ ini, record, people, approvals });
140
+ const rows = [];
141
+ const seen = new Set();
142
+ const today = new Date(now).toISOString().slice(0, 10);
143
+ const lastOf = (id, name) => {
144
+ const p = (people || []).find((x) => x.id === id) || (people || []).find((x) => same(x.name, name));
145
+ if (!p) return null;
146
+ const here = (p.interactions || []).filter((i) => i.initiative === ini).map((i) => dateOf(i.date)).filter(Boolean).sort().pop();
147
+ return here || dateOf(p.last);
148
+ };
149
+ const push = (d, m) => {
150
+ seen.add(d.id);
151
+ if (m && m.state === 'dropped') return;
152
+ const group = (m && m.group) || d.group || 'know';
153
+ const name = (m && m.name) || d.name;
154
+ const last = newest(lastOf(d.id, name), m && m.told);
155
+ const days = last ? Math.max(0, Math.round((Date.parse(today) - Date.parse(last)) / DAY)) : null;
156
+ const stale = days != null && days >= STALE_DAYS;
157
+ rows.push({ id: d.id, name, group, groupWord: GROUP_WORD[group], kept: !!(m && m.state === 'kept'), why: d.why || 'you kept this name',
158
+ last, days, stale, update: stale ? updateText({ name, title, record, group }) : null });
159
+ };
160
+ for (const d of drafts) push(d, marks.get(keyOf(ini, d.id)));
161
+ // a name the PM kept that no source names any more stays: the PM's keep is the record
162
+ for (const m of marks.values()) if (m.ini === ini && !seen.has(m.id) && m.state === 'kept') push({ id: m.id, name: m.name || m.id, group: m.group, why: 'you kept this name' }, m);
163
+ rows.sort((a, b) => GROUPS.indexOf(a.group) - GROUPS.indexOf(b.group) || a.name.localeCompare(b.name));
164
+ return { ini, title, rows, kept: rows.filter((r) => r.kept).length, drafts: rows.filter((r) => !r.kept).length };
165
+ }
166
+
167
+ function act(dir, input = {}, { by = 'pm', now = Date.now() } = {}) {
168
+ const kind = String(input.kind || '');
169
+ if (!KINDS.includes(kind)) return { ok: false, error: 'keep, drop, told or undo' };
170
+ const ini = one(input.ini, 80), name = one(input.name, 80);
171
+ if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(ini)) return { ok: false, error: 'Name the initiative by its id.' };
172
+ const person = /^[a-z0-9][a-z0-9-]{0,59}$/.test(String(input.person || '')) ? String(input.person) : name ? slugOf(name) : '';
173
+ if (!person) return { ok: false, error: 'Name the person (their id in People, or their name).' };
174
+ const line = { at: new Date(now).toISOString(), by, kind, ini, person };
175
+ if (name) line.name = name;
176
+ if (kind === 'keep' && input.group != null) {
177
+ const g = groupOf(input.group);
178
+ if (!g) return { ok: false, error: 'The group is decides, agree or know.' };
179
+ line.group = g;
180
+ }
181
+ if (kind === 'told') line.date = dateOf(input.date) || line.at.slice(0, 10);
182
+ if (kind === 'undo' && !readLines(dir).some((l) => l.ini === ini && l.person === person)) return { ok: false, error: 'Nothing to undo for ' + person + '.' };
183
+ if (!dir) return { ok: false, error: 'This product has no records folder.' };
184
+ try { fs.mkdirSync(dir, { recursive: true }); fs.appendFileSync(path.join(dir, FILE), JSON.stringify(line) + '\n'); } catch (e) { return { ok: false, error: 'could not save: ' + ((e && e.message) || e) }; }
185
+ try { console.error(`${TAG} ${kind} ${ini} ${person}${line.group ? ' ' + line.group : ''}`); } catch { /* no console */ }
186
+ return { ok: true, line };
187
+ }
188
+
189
+ const count = (dir) => [...fold(readLines(dir)).values()].filter((e) => e.state === 'kept').length;
190
+
191
+ /* ── the record and the sources, read from a product checkout ── */
192
+ function front(text) {
193
+ const L = String(text || '').split('\n'), out = {};
194
+ if (!/^---\s*$/.test(L[0] || '')) return out;
195
+ for (let i = 1; i < L.length && !/^---\s*$/.test(L[i]); i++) {
196
+ const m = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(L[i]);
197
+ if (m) out[m[1]] = m[2].trim().replace(/^(["'])(.*)\1$/, '$2');
198
+ }
199
+ return out;
200
+ }
201
+ /** The initiative's frontmatter from planning/initiatives/<id>.md, pmos/state/initiatives/<id>.md or <stateDir>/initiatives/<id>.md. */
202
+ function recordOf(root, ini, stateDir) {
203
+ const dirs = [path.join(root, 'planning', 'initiatives'), path.join(root, 'pmos', 'state', 'initiatives')];
204
+ if (stateDir) dirs.push(path.join(stateDir, 'initiatives'));
205
+ for (const d of dirs) { try { return front(fs.readFileSync(path.join(d, ini + '.md'), 'utf8')); } catch { /* next */ } }
206
+ return null;
207
+ }
208
+ function recordsDirOf(root) {
209
+ try { const { repoScript } = require('./repo-script.js'); return require(repoScript('signals/layout-paths.js')).pathsFor(root).recordsDir; }
210
+ catch { return path.join(root, 'planning', 'records'); }
211
+ }
212
+ /** Everything mapOf needs, read from the checkout at `root`. o: { now, people (a People view, when the caller has one), stateDir, dir }. */
213
+ function read(root, ini, o = {}) {
214
+ const now = o.now || Date.now();
215
+ let people = o.people;
216
+ if (!people) { try { const v = require('./people-store.js').view(root, { now }); people = v && v.ok ? v.people : []; } catch { people = []; } }
217
+ let approvals = [];
218
+ try { approvals = require('./approver-memory.js').itemsOf(root); } catch { approvals = []; }
219
+ const record = recordOf(root, ini, o.stateDir) || {};
220
+ const dir = o.dir || recordsDirOf(root);
221
+ return { ...mapOf({ ini, record, people, approvals, lines: readLines(dir), now }), found: !!Object.keys(record).length };
222
+ }
223
+
224
+ module.exports = { FILE, TAG, KINDS, GROUPS, GROUP_WORD, STALE_DAYS, slugOf, same, groupOf, draftsOf, readLines, fold, mapOf, updateText, act, count, recordOf, recordsDirOf, read };
225
+
226
+ if (require.main === module) {
227
+ const cmd = process.argv[2];
228
+ if (cmd !== 'count') { console.error('usage: node workspace/lib/stakeholder-map.js count [<product checkout>] (stakeholder names kept)'); process.exit(2); }
229
+ const n = count(recordsDirOf(path.resolve(process.argv[3] || process.cwd())));
230
+ console.log(`${TAG} kept ${n}`);
231
+ console.log(String(n));
232
+ }
@@ -28,7 +28,7 @@ const path = require('path');
28
28
  const ledgers = require('./plan-ledgers.js');
29
29
 
30
30
  const LEDGER = 'initiative-tasks.jsonl';
31
- const TASK_KINDS = Object.freeze(['task', 'task-update', 'task-remove', 'task-restore', 'task-section', 'task-milestone', 'task-pin', 'task-order', 'task-parent', 'task-priority', 'task-description', 'task-comment']);
31
+ const TASK_KINDS = Object.freeze(['task', 'task-update', 'task-remove', 'task-restore', 'task-section', 'task-milestone', 'task-pin', 'task-order', 'task-parent', 'task-priority', 'task-time', 'task-description', 'task-comment']);
32
32
  const KINDS = new Set(TASK_KINDS);
33
33
  const isTaskKind = (k) => KINDS.has(k);
34
34
  const isTaskLine = (r) => !!r && typeof r === 'object' && !Array.isArray(r) && isTaskKind(r.kind);
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+ /* team-waits.js — who waits on which team (initiative team-waits, bet A364; board BatchCodeDS panel 14, Work › Dependencies).
3
+ *
4
+ * An initiative of the product waits on another team: a security review, a data export. The wait lives in a Jira link or in a note on
5
+ * the initiative. This module reads both into one list, oldest first, and keeps the store the page and the chat write.
6
+ *
7
+ * waitsOf(root, { today }) → { file, waits: [wait] } open waits, oldest first
8
+ * wait = { id, ini, title, team, what, since, days, who, email, key, sprint, sprint_end, src }
9
+ * src: 'jira:<KEY>' (a Jira link, written by `pmos deps wait --key`), 'chat' (the chat or a terminal), 'parked' (a parked
10
+ * initiative whose reason says "waiting on <team>"), 'record' (an initiative record with `waiting_on:` and `waiting_since:`)
11
+ * add(root, { ini, team, what, since, who, email, key, sprint, sprint_end, src }, { now, by, via }) → { ok, id, line } | { ok: false, error }
12
+ * end(root, { id }, { now, by, via }) → { ok, line } | { ok: false, error } the wait is over (one `wait-end` line)
13
+ * back(root, { id }, { now, by, via }) → { ok, line } | { ok: false, error } Undo of end (one `wait-back` line)
14
+ * LATE_DAYS a wait this many days old or more is late (spec question Q1, default 14)
15
+ *
16
+ * THE STORE. `team-waits.jsonl` in the product's runs folder (planning/runs or pmos/state, lib/parked-reasons.js layoutOf). Lines are
17
+ * appended, never changed: { kind: 'wait' | 'wait-end' | 'wait-back', id, at, by, via, … }. A torn line has no effect.
18
+ * THE NOTES. Read only: nothing here writes an initiative record or a lifecycle line. A parked hold that waits on another initiative of the
19
+ * same product is not a team wait (pmos parked shows it). A closed or cancelled initiative has no waits.
20
+ * Nothing is sent: the Chase draft (public/pm/team-waits.js chaseDraft) opens in the PM's own mail app. */
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const P = require('./parked-reasons.js');
24
+
25
+ const FILE = 'team-waits.jsonl';
26
+ const TAG = '[team-waits]';
27
+ const DAY = 864e5;
28
+ const LATE_DAYS = 14;
29
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
30
+ const KEY_RE = /^[A-Z][A-Z0-9_]*-\d+$/;
31
+ const ENDED = new Set(['closed', 'cancelled']);
32
+
33
+ const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1).trimEnd() + '…' : t; };
34
+ const dayOf = (v) => (typeof v === 'string' && DATE.test(v.slice(0, 10)) && Number.isFinite(Date.parse(v.slice(0, 10))) ? v.slice(0, 10) : null);
35
+ const daysBetween = (a, b) => Math.max(0, Math.round((Date.parse(b) - Date.parse(a)) / DAY));
36
+
37
+ function jsonl(file) {
38
+ let text = '';
39
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
40
+ const out = [];
41
+ for (const l of text.split('\n')) { if (!l.trim()) continue; try { const r = JSON.parse(l); if (r && typeof r === 'object' && !Array.isArray(r)) out.push(r); } catch { /* a torn line */ } }
42
+ return out;
43
+ }
44
+ const fileOf = (root) => { const L = P.layoutOf(root); return L ? path.join(L.runs, FILE) : null; };
45
+
46
+ /** The initiatives of the product: Map id → { title, waiting_on, waiting_since }. */
47
+ function recordsOf(L) {
48
+ const out = new Map();
49
+ let files = [];
50
+ try { files = fs.readdirSync(L.initiatives).filter((f) => f.endsWith('.md')); } catch { return out; }
51
+ for (const f of files) {
52
+ let head = '';
53
+ try { head = fs.readFileSync(path.join(L.initiatives, f), 'utf8').slice(0, 6000); } catch { continue; }
54
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(head);
55
+ const get = (k) => { const m = fm && new RegExp('^' + k + ':\\s*(.*)$', 'm').exec(fm[1]); return m ? m[1].trim().replace(/^["']|["']$/g, '') : ''; };
56
+ const id = get('id') || f.slice(0, -3);
57
+ out.set(id, { title: get('title') || id, waiting_on: get('waiting_on'), waiting_since: get('waiting_since') });
58
+ }
59
+ return out;
60
+ }
61
+ /** Latest lifecycle state per initiative id. */
62
+ function statesOf(L) {
63
+ const m = new Map();
64
+ for (const r of jsonl(path.join(L.runs, 'lifecycle.jsonl'))) if (typeof r.initiative_id === 'string' && typeof r.state === 'string') m.set(r.initiative_id, r.state);
65
+ return m;
66
+ }
67
+
68
+ /** "Security review: the pen test sign-off" → { team: 'Security review', what: 'the pen test sign-off' }. */
69
+ function splitOn(text) {
70
+ const t = clip(text, 200);
71
+ const m = /^([^:—–]{1,60})\s*[:—–]\s*(.+)$/.exec(t);
72
+ return m ? { team: m[1].trim(), what: m[2].trim() } : { team: t, what: '' };
73
+ }
74
+ /** The team a parked reason waits on: the words after "waiting on/for", "blocked by/on", "depends on". '' when none. */
75
+ function teamOfReason(reason) {
76
+ const m = /\b(?:waiting (?:on|for)|blocked (?:by|on)|depends on|dependent on)\s+(?:the\s+)?(.+)$/i.exec(String(reason || '').trim());
77
+ return m ? clip(m[1].replace(/[.;]+$/, ''), 120) : '';
78
+ }
79
+
80
+ /** The store folded: Map id → wait (open or not). */
81
+ function foldStore(file) {
82
+ const m = new Map();
83
+ for (const r of jsonl(file)) {
84
+ if (typeof r.id !== 'string' || !r.id) continue;
85
+ if (r.kind === 'wait') m.set(r.id, { ...r, open: true });
86
+ else if (r.kind === 'wait-end' && m.has(r.id)) m.get(r.id).open = false;
87
+ else if (r.kind === 'wait-back' && m.has(r.id)) m.get(r.id).open = true;
88
+ }
89
+ return m;
90
+ }
91
+
92
+ function waitsOf(root, { today = P.todayOf() } = {}) {
93
+ root = path.resolve(root);
94
+ const L = P.layoutOf(root);
95
+ if (!L) return { file: null, waits: [] };
96
+ const recs = recordsOf(L), states = statesOf(L);
97
+ const live = (ini) => !ini || !ENDED.has(states.get(ini));
98
+ const titleOf = (ini) => (ini && recs.has(ini) ? recs.get(ini).title : ini || '');
99
+ const out = [];
100
+ const shape = (w) => {
101
+ const since = dayOf(w.since) || today;
102
+ const sprintEnd = dayOf(w.sprint_end);
103
+ return { id: w.id, ini: w.ini || '', title: titleOf(w.ini), team: clip(w.team, 80), what: clip(w.what, 160), since, days: daysBetween(since, today),
104
+ who: clip(w.who, 80), email: /^[^\s@]+@[^\s@]+$/.test(w.email || '') ? w.email : '', key: KEY_RE.test(w.key || '') ? w.key : '',
105
+ sprint: clip(w.sprint, 60), sprint_end: sprintEnd, src: w.src || 'chat' };
106
+ };
107
+ // 1. the store: Jira links and what the chat wrote
108
+ for (const w of foldStore(path.join(L.runs, FILE)).values()) if (w.open && live(w.ini)) out.push(shape(w));
109
+ // 2. the initiative notes: a parked initiative waiting on a team (not on another initiative of the product)
110
+ let parked = [];
111
+ const fromHold = new Set();
112
+ try { parked = P.parkedOf(root, { today }).parked; } catch { parked = []; }
113
+ for (const p of parked) {
114
+ if (p.kind !== 'waiting' || p.after || p.back) continue;
115
+ const team = teamOfReason(p.reason);
116
+ if (!team || recs.has(team)) continue;
117
+ fromHold.add(p.id);
118
+ out.push(shape({ id: 'parked:' + p.id, ini: p.id, ...splitOn(team), since: p.at, src: 'parked' }));
119
+ }
120
+ // 3. an initiative record that says `waiting_on:` (and `waiting_since:`)
121
+ for (const [id, r] of recs) {
122
+ if (!r.waiting_on || !live(id) || fromHold.has(id)) continue; // a hold already said it: say it once
123
+ if (recs.has(r.waiting_on)) continue; // another initiative of the product: not a team
124
+ out.push(shape({ id: 'record:' + id, ini: id, ...splitOn(r.waiting_on), since: r.waiting_since, src: 'record' }));
125
+ }
126
+ out.sort((a, b) => a.since.localeCompare(b.since) || a.title.localeCompare(b.title) || a.id.localeCompare(b.id));
127
+ return { file: path.relative(root, path.join(L.runs, FILE)).split(path.sep).join('/'), waits: out };
128
+ }
129
+
130
+ function append(file, line) {
131
+ fs.mkdirSync(path.dirname(file), { recursive: true });
132
+ fs.appendFileSync(file, JSON.stringify(line) + '\n');
133
+ return line;
134
+ }
135
+ const stamp = (now, by, via) => ({ at: new Date(now).toISOString(), by: by || 'pm', via: via || 'cli' });
136
+
137
+ function add(root, w = {}, { now = Date.now(), by, via } = {}) {
138
+ const file = fileOf(path.resolve(root));
139
+ if (!file) return { ok: false, error: 'no initiatives folder here (planning/initiatives or pmos/state/initiatives)' };
140
+ const team = clip(w.team, 80), what = clip(w.what, 160);
141
+ if (!team && !what) return { ok: false, error: 'say which team it waits on (--team) or what it waits for (--what)' };
142
+ if (w.since && !dayOf(w.since)) return { ok: false, error: '--since must be a day, YYYY-MM-DD' };
143
+ if (w.sprint_end && !dayOf(w.sprint_end)) return { ok: false, error: '--sprint-end must be a day, YYYY-MM-DD' };
144
+ if (w.key && !KEY_RE.test(w.key)) return { ok: false, error: '--key must be a Jira key such as SEC-12' };
145
+ const open = [...foldStore(file).values()].filter((x) => x.open);
146
+ if (w.key) { const dup = open.find((x) => x.key === w.key); if (dup) return { ok: false, error: `${w.key} already has an open wait (${dup.id}); end it first with pmos deps done ${dup.id}` }; }
147
+ const id = 'w' + Date.parse(new Date(now).toISOString()).toString(36) + Math.random().toString(36).slice(2, 5);
148
+ const line = { kind: 'wait', id, ini: String(w.ini || ''), team, what, since: dayOf(w.since) || P.todayOf(now), who: clip(w.who, 80), email: String(w.email || ''),
149
+ key: w.key || '', sprint: clip(w.sprint, 60), sprint_end: dayOf(w.sprint_end) || '', src: w.key ? 'jira:' + w.key : (w.src || 'chat'), ...stamp(now, by, via) };
150
+ append(file, line);
151
+ return { ok: true, id, line };
152
+ }
153
+
154
+ function flip(kind, root, { id } = {}, { now = Date.now(), by, via } = {}) {
155
+ const file = fileOf(path.resolve(root));
156
+ if (!file) return { ok: false, error: 'no initiatives folder here' };
157
+ if (/^(parked|record):/.test(String(id || ''))) return { ok: false, error: 'that wait comes from the initiative itself: change its hold (pmos parked) or its record' };
158
+ const w = foldStore(file).get(String(id || ''));
159
+ if (!w) return { ok: false, error: `no wait ${id}` };
160
+ if (kind === 'wait-end' && !w.open) return { ok: false, error: `${id} is already over` };
161
+ if (kind === 'wait-back' && w.open) return { ok: false, error: `${id} is still open` };
162
+ return { ok: true, line: append(file, { kind, id: w.id, ...stamp(now, by, via) }) };
163
+ }
164
+ const end = (root, a, o) => flip('wait-end', root, a, o);
165
+ const back = (root, a, o) => flip('wait-back', root, a, o);
166
+
167
+ module.exports = { FILE, TAG, LATE_DAYS, waitsOf, add, end, back, teamOfReason, splitOn, fileOf };