create-pmos 0.826.0 → 0.828.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 (55) hide show
  1. package/package.json +121 -55
  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/changelog.json +120 -16
  8. package/workspace/guide/cli.md +42 -0
  9. package/workspace/lib/arch-warns.js +121 -0
  10. package/workspace/lib/board-cli.js +5 -1
  11. package/workspace/lib/code-map-cli.js +11 -3
  12. package/workspace/lib/features.json +3 -0
  13. package/workspace/lib/five-action-cap.js +84 -0
  14. package/workspace/lib/goals-cli.js +5 -0
  15. package/workspace/lib/people-cli.js +43 -2
  16. package/workspace/lib/pmos-verbs.js +10 -1
  17. package/workspace/lib/portfolio-cli.js +64 -0
  18. package/workspace/lib/portfolio.js +168 -0
  19. package/workspace/lib/review-reasons.js +357 -0
  20. package/workspace/lib/route-modules.js +3 -0
  21. package/workspace/lib/routes-arch-warns.js +39 -0
  22. package/workspace/lib/routes-onboard.js +18 -3
  23. package/workspace/lib/routes-portfolio.js +50 -0
  24. package/workspace/lib/routes-stakeholders.js +42 -0
  25. package/workspace/lib/routes-strategy-card.js +29 -1
  26. package/workspace/lib/routes-use-log.js +6 -1
  27. package/workspace/lib/stakeholder-map.js +232 -0
  28. package/workspace/lib/starter-goals.js +244 -0
  29. package/workspace/lib/voice-cli.js +7 -0
  30. package/workspace/package-lock.json +2 -2
  31. package/workspace/package.json +1 -1
  32. package/workspace/premium-vw-jira-test.js +6 -2
  33. package/workspace/public/pm/bd-principles.js +12 -1
  34. package/workspace/public/pm/cozy-onboard.css +4 -0
  35. package/workspace/public/pm/cozy-onboard.js +17 -1
  36. package/workspace/public/pm/cozy-pick.css +1 -0
  37. package/workspace/public/pm/cozy-pop-work.js +37 -2
  38. package/workspace/public/pm/cozy-today-app.js +48 -1
  39. package/workspace/public/pm/cozy-today-view.js +12 -4
  40. package/workspace/public/pm/five-action-cap.js +104 -0
  41. package/workspace/public/pm/pop-work-model.js +6 -0
  42. package/workspace/public/pm/portfolio.js +67 -0
  43. package/workspace/public/pm/product-switcher.js +7 -1
  44. package/workspace/public/pm/review-reasons.js +75 -0
  45. package/workspace/public/pm/stakeholder-map.js +125 -0
  46. package/workspace/public/pm/starter-goals.js +35 -0
  47. package/workspace/public/premium-portfolio.html +48 -0
  48. package/workspace/server.js +1 -1
  49. package/workspace/stage-card-tasks-test.js +11 -5
  50. package/workspace/test-lists/arch-warns.json +9 -0
  51. package/workspace/test-lists/five-action-cap.json +9 -0
  52. package/workspace/test-lists/portfolio.json +9 -0
  53. package/workspace/test-lists/review-reasons.json +9 -0
  54. package/workspace/test-lists/stakeholder-map.json +9 -0
  55. package/workspace/test-lists/starter-goals.json +9 -0
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+ /* routes-portfolio.js — the Portfolio: every product side by side for a head of product (initiative portfolio, bet A56).
3
+ *
4
+ * GET /api/product-portfolio → { ok, show, rows, rec, as_of } lib/portfolio.js view over every registered product
5
+ * except the embedded PMOS checkout (PMOS itself is not a product). show is false
6
+ * under two products. Reads only; one use-log line (control portfolio)
7
+ * POST /api/product-portfolio/decide { key, kind } kind keep | not-now | undo: the answer to the one recommendation (page press),
8
+ * in <runtime>/portfolio.jsonl, the store `pmos portfolio keep|not-now|undo` writes too
9
+ * Nothing here writes a product's files or sends anything. (/api/portfolio is the older OKR hub of server.js, a different thing.) */
10
+ const path = require('path');
11
+ const guard = require('./pm-guard.js');
12
+ const PF = require('./portfolio.js');
13
+
14
+ /** The products the Portfolio compares: every registered workspace except the embedded PMOS checkout. */
15
+ function productsOf(ctx) {
16
+ const list = (ctx.workspaceList ? ctx.workspaceList() : []) || [];
17
+ const self = ctx.selfRoot ? path.resolve(ctx.selfRoot) : null;
18
+ return list.filter((w) => w && w.root && path.resolve(w.root) !== self).map((w) => ({ ws: w.id, name: w.name || path.basename(w.root), root: w.root }));
19
+ }
20
+
21
+ module.exports = {
22
+ prefixes: ['/api/product-portfolio'],
23
+ productsOf,
24
+ handle: async (req, res, url, ctx) => {
25
+ const p = url.pathname;
26
+ const bad = (error, code) => { ctx.json(res, { ok: false, error }, code || 400); return true; };
27
+ if (p === '/api/product-portfolio') {
28
+ if (req.method !== 'GET') return bad('GET only', 405);
29
+ const v = PF.view(productsOf(ctx), ctx.runtimeDir || null);
30
+ if (ctx.runtimeDir) { try { require('./use-log.js').record(ctx.runtimeDir, [{ kind: 'use', page: 'premium-portfolio', control: 'portfolio', device: 'desk' }], Date.now()); } catch { /* a count only */ } }
31
+ console.log(`${PF.TAG} read products=${v.rows.length} show=${v.show} rec=${v.rec ? 1 : 0}`);
32
+ ctx.json(res, v);
33
+ return true;
34
+ }
35
+ if (p === '/api/product-portfolio/decide') {
36
+ if (req.method !== 'POST') return bad('POST only', 405);
37
+ const got = await ctx.readJson(req);
38
+ if (!got.ok) return bad('invalid JSON body');
39
+ const b = got.body || {};
40
+ const g = guard.requirePagePress(req, b);
41
+ if (!g.ok) return bad(g.error, g.status);
42
+ const r = PF.decide(ctx.runtimeDir || null, { key: b.key, kind: b.kind, by: 'page' });
43
+ if (!r.ok) return bad(r.error);
44
+ console.log(`${PF.TAG} ${r.line.kind} key=${r.line.key}`);
45
+ ctx.json(res, { ok: true, line: r.line });
46
+ return true;
47
+ }
48
+ return bad('no such route', 404);
49
+ },
50
+ };
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+ /* routes-stakeholders.js — an initiative's stakeholder map over HTTP (initiative stakeholder-map, job #1896, idea A371). The store and the
3
+ * fold are lib/stakeholder-map.js (stakeholders.jsonl in the product's records folder, lib/records-dir.js); the verb is `pmos people map`.
4
+ *
5
+ * GET /api/stakeholders?ini=<id>&ws=<id> → { ok, ini, title, rows, kept, drafts }
6
+ * POST /api/stakeholders { ws, ini, person, name?, act, group? } → { ok, line } | 400 act ∈ keep · drop · told · undo
7
+ *
8
+ * WHO WRITES. A page press: pm-guard requirePagePress checks the page's Origin and launch nonce. The chat writes with `pmos people keep|drop|
9
+ * told|undo`. Nothing here reads a connector or sends anything: the ✦ draft update is text the PM copies and sends. */
10
+ const guard = require('./pm-guard.js');
11
+ const SM = require('./stakeholder-map.js');
12
+ const { recordsDirFor } = require('./records-dir.js');
13
+
14
+ const INI_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
15
+ function wsOf(ctx, ws) { try { return ctx && typeof ctx.getWs === 'function' ? ctx.getWs(ws || null) : null; } catch { return null; } }
16
+ const rootOf = (ctx, w) => (ctx && ctx.repoRoot) || (w && w.root) || (ctx && ctx.selfRoot) || null;
17
+ function stateDirOf(ctx, w) { try { return ctx && typeof ctx.stateDirFor === 'function' && w ? ctx.stateDirFor(w) : null; } catch { return null; } }
18
+
19
+ async function handle(req, res, url, ctx) {
20
+ if (url.pathname !== '/api/stakeholders') return false;
21
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
22
+ if (req.method === 'GET') {
23
+ const ini = String(url.searchParams.get('ini') || '');
24
+ if (!INI_RE.test(ini)) return send(400, { ok: false, error: 'Name the initiative: ?ini=<id>.' });
25
+ const wsId = url.searchParams.get('ws') || null;
26
+ const w = wsOf(ctx, wsId), root = rootOf(ctx, w);
27
+ if (!root) return send(404, { ok: false, error: 'no such workspace' });
28
+ const m = SM.read(root, ini, { stateDir: stateDirOf(ctx, w), dir: recordsDirFor(ctx, wsId), people: ctx.people || undefined });
29
+ return send(200, { ok: true, ...m });
30
+ }
31
+ if (req.method !== 'POST') return send(405, { ok: false, error: 'GET or POST' });
32
+ const rd = await ctx.readJson(req);
33
+ if (!rd.ok) return send(400, { ok: false, error: 'the body is not JSON' });
34
+ const body = rd.body || {};
35
+ const g = guard.requirePagePress(req, body);
36
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
37
+ const r = SM.act(recordsDirFor(ctx, body.ws || null), { ini: body.ini, person: body.person, name: body.name, kind: String(body.act || ''), group: body.group },
38
+ { by: (g.actor && g.actor.by) || 'pm' });
39
+ return r.ok ? send(200, { ok: true, line: r.line }) : send(400, { ok: false, error: r.error });
40
+ }
41
+
42
+ module.exports = { prefixes: ['/api/stakeholders'], handle };
@@ -18,6 +18,9 @@
18
18
  * POST /api/positioning/keep { ws, line } → { ok, line, kept } line: { kind, text, cites, from } (from: the drafted text)
19
19
  * POST /api/positioning/drop { ws, id } → { ok, kept }
20
20
  *
21
+ * GET /api/voice?ws=<id> → { ok, rows, unsorted, score, suggest } customer voice by reason (lib/review-reasons.js, idea A427)
22
+ * POST /api/voice/file { ws, reason } → { ok, capture } the ✦: file the complaint as a triage item; /api/voice/undo { ws, capture } takes it back
23
+ *
21
24
  * The notes come from the Board's own backlog route (GET /api/boards/backlog, every view, the new-work stages), so they read the rows the Board draws.
22
25
  * WHO WRITES. A page press: pm-guard requirePagePress checks the page's Origin and launch nonce. Nothing here is sent anywhere. */
23
26
  const guard = require('./pm-guard.js');
@@ -104,9 +107,34 @@ async function positioning(req, res, url, ctx, send) {
104
107
  return r.ok ? send(200, { ok: true, line: r.line, kept: PD.read(dir, card) }) : send(400, { ok: false, error: r.error });
105
108
  }
106
109
 
110
+ /** Customer voice (idea A427, initiative review-reasons): survey comments and app-store reviews grouped by reason, lib/review-reasons.js.
111
+ * GET /api/voice?ws=<id> → { ok, rows, unsorted, score, suggest }; POST /api/voice/file { ws, reason } → { ok, capture };
112
+ * POST /api/voice/undo { ws, capture } → { ok }. Both POSTs are page presses. Nothing is sent anywhere. */
113
+ async function voice(req, res, url, ctx, send) {
114
+ const RR = require('./review-reasons.js');
115
+ if (url.pathname === '/api/voice' && req.method === 'GET') {
116
+ const root = rootFor(ctx, wsOf(ctx, url.searchParams.get('ws') || null));
117
+ let G;
118
+ try { G = RR.group(RR.read(root), Date.now()); } catch (e) { return send(500, { ok: false, error: String((e && e.message) || e).slice(0, 160) }); }
119
+ return send(200, { ok: true, rows: G.rows, unsorted: G.unsorted, score: G.score, suggest: G.suggest });
120
+ }
121
+ if (url.pathname !== '/api/voice/file' && url.pathname !== '/api/voice/undo') return send(404, { ok: false, error: 'no such voice route' });
122
+ if (req.method !== 'POST') return send(405, { ok: false, error: 'POST' });
123
+ const rd = await ctx.readJson(req);
124
+ if (!rd.ok) return send(400, { ok: false, error: 'the body is not JSON' });
125
+ const body = rd.body || {};
126
+ const g = guard.requirePagePress(req, body);
127
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
128
+ const w = wsOf(ctx, body.ws || null), root = rootFor(ctx, w);
129
+ const r = url.pathname === '/api/voice/file' ? RR.file(root, body.reason, { actor: g.actor }) : RR.undo(root, body.capture, { actor: g.actor });
130
+ if (r.ok && ctx.invalidateNeedsAgg) { try { ctx.invalidateNeedsAgg(w ? w.id : null); } catch { /* the needs queue recounts on its own read */ } }
131
+ return r.ok ? send(200, { ok: true, capture: r.capture || null }) : send(r.status || 400, { ok: false, error: r.error });
132
+ }
133
+
107
134
  async function handle(req, res, url, ctx) {
108
135
  const send = (status, body) => { ctx.json(res, body, status); return true; };
109
136
  if (url.pathname.startsWith('/api/positioning')) return positioning(req, res, url, ctx, send);
137
+ if (url.pathname.startsWith('/api/voice')) return voice(req, res, url, ctx, send);
110
138
  if (url.pathname === '/api/strategy-card/draft') {
111
139
  if (req.method !== 'POST') return send(405, { ok: false, error: 'POST' });
112
140
  const rd = await ctx.readJson(req);
@@ -142,4 +170,4 @@ async function handle(req, res, url, ctx) {
142
170
  return r.ok ? send(200, { ok: true, card: r.card, complete: SC.complete(r.card) }) : send(400, { ok: false, error: r.error });
143
171
  }
144
172
 
145
- module.exports = { prefixes: ['/api/strategy-card', '/api/positioning'], handle, seedFor, JOB, SEED_FILE }; // /api/positioning: its own first segment, so a change to it does not reach every page that reads the strategy card
173
+ module.exports = { prefixes: ['/api/strategy-card', '/api/positioning', '/api/voice'], handle, seedFor, JOB, SEED_FILE }; // /api/positioning: its own first segment, so a change to it does not reach every page that reads the strategy card
@@ -7,6 +7,7 @@
7
7
  * POST /api/use-log/clear {} → { ok } Clear, in Settings (also forgets what pages showed)
8
8
  * GET /api/use-log/ease → { ok, window, bar, slow, pages } Settings › Use log › Ease check (bet A453, lib/ease-check.js)
9
9
  * GET /api/use-log/pop → { ok, counts, span } the work popup's four actions (idea A498, pm/pop-cap.js)
10
+ * GET /api/use-log/cap?place= → { ok, counts, span } Work and Today's shown actions (idea A529, pm/five-action-cap.js)
10
11
  * Hide the buttons nobody presses (idea A454; the store and the rule are lib/unused-controls.js):
11
12
  * GET /api/use-log/hidden[?page=] → { ok, hidden: [{ page, control, at }] } the page at load; Settings › Use log
12
13
  * POST /api/use-log/unused { page, present } → { ok, hidden, propose } what the page shows (ids), and the ✦
@@ -26,7 +27,7 @@ const POSTS = ['', 'clear', 'unused', 'hide', 'show', 'decline'];
26
27
  async function handle(req, res, url, ctx) {
27
28
  const send = (status, body) => { ctx.json(res, body, status); return true; };
28
29
  const what = url.pathname.replace(/^\/api\/use-log\/?/, '');
29
- if (!POSTS.includes(what) && what !== 'hidden' && what !== 'ease' && what !== 'pop') return send(404, { ok: false, error: 'no such use-log route' });
30
+ if (!POSTS.includes(what) && what !== 'hidden' && what !== 'ease' && what !== 'pop' && what !== 'cap') return send(404, { ok: false, error: 'no such use-log route' });
30
31
  const dir = ctx.runtimeDir || null;
31
32
  if (what === 'ease') {
32
33
  if (req.method !== 'GET') return send(405, { ok: false, error: 'GET only' });
@@ -38,6 +39,10 @@ async function handle(req, res, url, ctx) {
38
39
  if (req.method !== 'GET') return send(405, { ok: false, error: 'GET only' });
39
40
  return send(200, { ok: true, ...UL.pop(UL.readLines(dir)) });
40
41
  }
42
+ if (what === 'cap') {
43
+ if (req.method !== 'GET') return send(405, { ok: false, error: 'GET only' });
44
+ return send(200, { ok: true, ...require('./five-action-cap.js').fold(UL.readLines(dir), url.searchParams.get('place') || '') });
45
+ }
41
46
  if (what === '' && req.method === 'GET') return send(200, { ok: true, ...UL.summary(UL.readLines(dir)) });
42
47
  if (what === 'hidden') {
43
48
  if (req.method !== 'GET') return send(405, { ok: false, error: 'GET only' });
@@ -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
+ }