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
@@ -12,6 +12,13 @@
12
12
  * POST /api/roadmap-ops/breakdown/dependency { rid, jira, remove? } → { ok } the item waits on that Jira ticket
13
13
  * POST /api/roadmap-ops/people { id, points_per_week } → { ok, people } writes <runtime>/people.json
14
14
  *
15
+ * TRADE-OFF CARDS (initiative tradeoff-cards, job #1918, idea A325; lib/tradeoff-cards.js), a second prefix:
16
+ * GET /api/tradeoffs?ws=<id> → { ok, ws, margin, pairs: [card], kept: { id: { eid, other, other_title, reason, at } } }
17
+ * GET /api/tradeoffs?ids=<a,b,…> → the same for the workspace whose records hold most of those initiatives (Work's rows on screen)
18
+ * GET /api/tradeoffs/card?ws=<id>&a=&b= → { ok, ws, card } any two on the Roadmap (a drag put one above the other)
19
+ * POST /api/tradeoffs/keep { ws, a, b, first, reason } → { ok, note } the reason, and the rank when the lower one goes first
20
+ * POST /api/tradeoffs/undo { ws, note } → { ok, of } (note: the kept note's eid; `eid` is a writer field)
21
+ *
15
22
  * STATE: bets in planning/records/bets.jsonl (scripts/records); breakdown items in <records>/breakdown-pmos.jsonl
16
23
  * (scripts/breakdown-ops.js); people in <runtime>/people.json (the file routes-forecast.js already reads).
17
24
  * WHO WRITES: every POST passes pm-guard requirePagePress; an agent session is refused (403). Pure handlers are exported.
@@ -121,10 +128,55 @@ const POSTS = {
121
128
  '/people': (c, b) => setPeople(c.runtimeDir, b),
122
129
  };
123
130
 
131
+ /** Trade-off cards (A325): reads answer the workspace's repository; the writes are the page's press (requirePagePress). */
132
+ async function tradeoffs(req, res, url, ctx) {
133
+ const TC = require('./tradeoff-cards.js');
134
+ const actorLib = require('./actor.js');
135
+ const wsOf = (id) => { try { return ctx.getWs(id || null); } catch { return null; } };
136
+ const now = ctx.now ? ctx.now() : Date.now();
137
+ if (req.method === 'GET') {
138
+ const ids = url.searchParams.get('ids');
139
+ const w = !url.searchParams.get('ws') && ids
140
+ ? TC.wsForIds(typeof ctx.workspaceList === 'function' ? ctx.workspaceList() : [], ids.split(','))
141
+ : wsOf(url.searchParams.get('ws'));
142
+ if (!w || !w.root) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
143
+ try {
144
+ if (url.pathname === '/api/tradeoffs/card') {
145
+ const r = TC.cardFor(w.root, url.searchParams.get('a') || '', url.searchParams.get('b') || '', { now });
146
+ ctx.json(res, r.ok ? { ok: true, ws: w.id, card: r.card } : { ok: false, error: r.error }, r.ok ? 200 : r.status);
147
+ return true;
148
+ }
149
+ const r = TC.read(w.root, { now });
150
+ console.info(TC.TAG + ' read ws=' + w.id + ' pairs=' + r.pairs.length + ' kept=' + Object.keys(r.kept).length);
151
+ ctx.json(res, { ok: true, ws: w.id, ...r });
152
+ } catch (e) {
153
+ console.warn(TC.TAG + ' could not read ' + w.id + ': ' + ((e && e.message) || e));
154
+ ctx.json(res, { ok: false, error: 'The trade-offs could not be read.' }, 500);
155
+ }
156
+ return true;
157
+ }
158
+ if (req.method !== 'POST' || !['/api/tradeoffs/keep', '/api/tradeoffs/undo'].includes(url.pathname)) { ctx.json(res, { ok: false, error: 'GET, or POST keep or undo' }, 405); return true; }
159
+ const got = await ctx.readJson(req);
160
+ if (!got.ok) { ctx.json(res, { ok: false, error: 'invalid JSON body' }, 400); return true; }
161
+ const body = got.body || {};
162
+ const g = guard.requirePagePress(req, body);
163
+ if (!g.ok) { ctx.json(res, { ok: false, error: g.error }, g.status); return true; }
164
+ const w = wsOf(body.ws);
165
+ if (!w || !w.root) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
166
+ const actor = g.actor || actorLib.fromUi(); // D98: an agent session's press keeps the agent's name
167
+ const r = url.pathname === '/api/tradeoffs/keep'
168
+ ? TC.keep(w.root, { a: body.a, b: body.b, first: body.first, reason: body.reason }, { actor, now })
169
+ : TC.undo(w.root, String(body.note || ''), { actor, now });
170
+ ctx.json(res, r.ok ? { ok: true, ...(r.note ? { note: r.note } : { of: r.of }) } : { ok: false, error: r.error }, r.ok ? 200 : r.status);
171
+ return true;
172
+ }
173
+
124
174
  module.exports = {
125
- prefixes: ['/api/roadmap-ops'],
175
+ prefixes: ['/api/roadmap-ops', '/api/tradeoffs'],
176
+ tradeoffs,
126
177
  betAdd, betMove, betTakeOff, betAnchorSuggestions, breakdownAdd, breakdownEdit, breakdownDelete, breakdownUndo, breakdownDependency, setPeople, healthBudgets, rootOf,
127
178
  handle: async (req, res, url, ctx) => {
179
+ if (url.pathname === '/api/tradeoffs' || url.pathname.startsWith('/api/tradeoffs/')) return tradeoffs(req, res, url, ctx);
128
180
  const sub = url.pathname.slice('/api/roadmap-ops'.length);
129
181
  if (req.method === 'GET' && sub === '/bet/anchor-suggestions') {
130
182
  const r = betAnchorSuggestions(rootOf(ctx, url.searchParams.get('ws')), { id: url.searchParams.get('id') }, ctx);
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+ /* routes-sim-users.js — simulated users try the prototype (initiative sim-users, idea A20, board BatchReleaseDS panel 24). The store and the
3
+ * walk are lib/sim-users.js; the Viewer (pm/cozy-proto.js through pm/sim-users.js) and `pmos prototype` (lib/prototype-cli.js) read and
4
+ * write the same store through these routes, so what the chat changes shows in the Viewer's Findings.
5
+ *
6
+ * GET /api/sim-users/findings?ws&initiative[&file] → { ok, findings, file, version, personas, base } the findings of one prototype
7
+ * version (file: a version's specimen path; without it, the initiative's prototype now). The first read of a version and persona
8
+ * set runs the walk and stores it; later reads read the stored run. findings is null when the version's flow has no key task.
9
+ * GET /api/sim-users/personas?ws → { ok, personas, base, removed } the personas that walk (the base four when none is recorded)
10
+ * POST /api/sim-users/personas { ws?, op: add, name, needs, from } | { ws?, op: remove | restore, id } → { ok, persona, undo? }
11
+ * `pmos prototype persona …` (the chat's agent, no Origin, D98, like the prototype rules); from a page, a page press.
12
+ * A finding never scores the prototype; nothing here writes to a version's folder or the proposals ledger, and no model is called. */
13
+ const guard = require('./pm-guard.js');
14
+ const SU = require('./sim-users.js');
15
+
16
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
17
+ const fail = (ctx, res, status, error) => { ctx.json(res, { ok: false, error }, status); return true; };
18
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/;
19
+ function wsOf(ctx, id) { let w = null; try { w = ctx.getWs(id || null); } catch { w = null; } return w && (!id || w.id === id) ? w : null; }
20
+ const dirOf = (ctx, w) => { try { return ctx.stateDirFor ? ctx.stateDirFor(w) : null; } catch { return null; } };
21
+
22
+ function findings(ctx, res, url) {
23
+ const w = wsOf(ctx, url.searchParams.get('ws')); if (!w) return fail(ctx, res, 404, 'no such workspace');
24
+ const dir = dirOf(ctx, w), ini = url.searchParams.get('initiative') || '', want = url.searchParams.get('file') || '';
25
+ if (!dir || !ID_RE.test(ini)) return fail(ctx, res, 400, 'initiative names an initiative');
26
+ const PR = require('./proposals.js'), LAB = require('./idle-lab.js'), LR = require('./live-round.js');
27
+ const F = PR.read(dir), all = PR.versionsOf(F, ini, 500);
28
+ // a named file must be a version of this initiative; without one, the prototype now (or its newest version)
29
+ const cur = want ? all.find((v) => v.file === want) || null : PR.currentOf(F, ini) || all[0] || null;
30
+ if (want && !cur) return fail(ctx, res, 404, 'That version is no longer here');
31
+ const P = SU.personasOf(SU.read(dir));
32
+ const abs = cur ? LAB.specimenPath(ctx.runtimeDir, cur.file) : null, data = abs ? LR.partsAt(abs) : {};
33
+ let out = null;
34
+ if (abs && data.flow) { try { out = SU.forVersion(dir, { ini, file: cur.file, abs, flow: data.flow }); } catch (e) { console.warn(SU.LOG, 'findings:', e.message); } }
35
+ ctx.json(res, { ok: true, findings: out, file: cur ? cur.file : null, version: cur ? cur.n : null, personas: P.walking, base: P.base });
36
+ return true;
37
+ }
38
+ function personas(ctx, res, url) {
39
+ const w = wsOf(ctx, url.searchParams.get('ws')); if (!w) return fail(ctx, res, 404, 'no such workspace');
40
+ const P = SU.personasOf(SU.read(dirOf(ctx, w)));
41
+ ctx.json(res, { ok: true, personas: P.walking, base: P.base, removed: P.removed });
42
+ return true;
43
+ }
44
+ const READS = { '/api/sim-users/findings': findings, '/api/sim-users/personas': personas };
45
+
46
+ module.exports = {
47
+ prefixes: ['/api/sim-users'],
48
+ handle: async (req, res, url, ctx) => {
49
+ const p0 = url.pathname;
50
+ if (req.method === 'GET') { const fn = READS[p0]; if (!fn) return fail(ctx, res, 404, 'not found'); return fn(ctx, res, url); }
51
+ if (req.method !== 'POST') return fail(ctx, res, 405, 'GET or POST only');
52
+ if (p0 !== '/api/sim-users/personas') return fail(ctx, res, 404, 'not found');
53
+ const got = await ctx.readJson(req);
54
+ if (!got.ok || !isObj(got.body)) return fail(ctx, res, 400, 'the body must be a JSON object');
55
+ let by;
56
+ if (req.headers.origin) { const g = guard.requirePagePress(req, got.body); if (!g.ok) return fail(ctx, res, g.status, g.error); by = (g.actor && g.actor.by) || 'pm:page'; }
57
+ else by = /^(pm|agent):[\w.:-]{1,80}$/.test(String(got.body.by || '')) ? got.body.by : 'agent:cli';
58
+ const w = wsOf(ctx, typeof got.body.ws === 'string' && got.body.ws ? got.body.ws : null); if (!w) return fail(ctx, res, 404, 'no such workspace');
59
+ const dir = dirOf(ctx, w); if (!dir) return fail(ctx, res, 409, 'This repository has no PMOS state folder.');
60
+ const b = got.body, op = b.op;
61
+ const r = op === 'add' ? SU.addPersona(dir, b, { by }) : op === 'remove' ? SU.removePersona(dir, b.id, { by }) : op === 'restore' ? SU.restorePersona(dir, b.id, { by }) : { ok: false, error: 'op is add, remove or restore' };
62
+ if (!r.ok) return fail(ctx, res, 400, r.error);
63
+ ctx.json(res, r);
64
+ return true;
65
+ },
66
+ };
@@ -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
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+ /* routes-team-waits.js — Work › Dependencies' "Waiting on other teams" (initiative team-waits, bet A364). lib/team-waits.js is the store.
3
+ *
4
+ * GET /api/team-waits?ws=<id> → { ok, ws, today, waits: [lib/team-waits.js wait] } open waits, oldest first; 404 for an unknown ws
5
+ *
6
+ * Read only. The chat and a terminal write the same store with `pmos deps wait|done|undo` (lib/deps-cli.js), so what they write shows here
7
+ * on the next read. Nothing is sent: Chase is a draft in the PM's own mail app (public/pm/team-waits.js chaseDraft). */
8
+ const TW = require('./team-waits.js');
9
+ const { todayOf } = require('./parked-reasons.js');
10
+
11
+ async function handle(req, res, url, ctx) {
12
+ if (url.pathname !== '/api/team-waits') { ctx.json(res, { ok: false, error: 'no such route' }, 404); return true; }
13
+ if (req.method !== 'GET') { ctx.json(res, { ok: false, error: 'GET only' }, 405); return true; }
14
+ let w = null;
15
+ try { w = ctx.getWs(url.searchParams.get('ws') || null); } catch { w = null; }
16
+ if (!w || !w.root) { ctx.json(res, { ok: false, error: 'no such workspace' }, 404); return true; }
17
+ const today = todayOf();
18
+ let waits = [];
19
+ try { waits = TW.waitsOf(w.root, { today }).waits; } catch { waits = []; }
20
+ ctx.json(res, { ok: true, ws: w.id, today, waits });
21
+ return true;
22
+ }
23
+
24
+ module.exports = { prefixes: ['/api/team-waits'], handle };
@@ -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,329 @@
1
+ 'use strict';
2
+ /* sim-users.js — simulated users try the prototype (initiative sim-users, idea A20, board BatchReleaseDS panel 24, Wawan agreed 2026-11-25).
3
+ *
4
+ * Before a prototype version shows in the Viewer, a few simulated users (one per persona) walk the version's key tasks: the scenarios of
5
+ * its flow.json (lib/live-round.js flowOf). The PM sees findings, not clicks: where they got stuck, why, and how many. Each finding names
6
+ * the screen (and element) it came from, so the Viewer opens that screen. A finding is a hint for the grilling: it NEVER scores the
7
+ * prototype, never changes it, and calls no model. The walk is a fixed set of checks over the version's HTML, so it runs on any product.
8
+ *
9
+ * THE WALK. For each step of a scenario, on the step's screen (data-screen), the press that leads on is the step's tap (data-el) or the
10
+ * element that goes to the next screen (data-go, or a link to #<screen>). Every persona gets stuck where the screen is missing or no
11
+ * press leads on. Then each persona's needs are checked on that press:
12
+ * keyboard the press is a button, a link with href, a field, a summary, or has tabindex ≥ 0
13
+ * reader the press has a name to hear: its words, aria-label, aria-labelledby, title, or an image's alt
14
+ * words the press shows words (not only a symbol), and the screen has a heading
15
+ * thumb the press is not set smaller than 44 px (inline width, height or the attributes)
16
+ * PERSONAS come from the user's records: `pmos prototype persona add --name … --needs … --from <record>` (no --from, no persona). With
17
+ * none recorded, the four base personas walk (BASE: abilities, not made-up people).
18
+ *
19
+ * THE STORE. <state>/sim-users.jsonl, append-only:
20
+ * { at, kind: 'persona', op: 'add' | 'remove' | 'restore', id, persona?, by } the newest line for an id wins
21
+ * { at, kind: 'run', log: '[sim-users]', ini, file, sig, personas: [id], findings } one per version and persona set (forVersion)
22
+ *
23
+ * parse(html) PURE → root node · screensOf(root) PURE → Map(id → node) · pressOf(screen, step, next) PURE → node | null
24
+ * simulate({ html, flow, personas }) PURE → [{ persona, task, done, at?, el?, why? }]
25
+ * findingsOf(tries, { flow, personas }) PURE → { personas: n, rows: [{ state, text, who, screen, el?, task, n }] } | null
26
+ * personasOf(lines) PURE → { mine: [persona], removed: [persona], walking: [persona], base: bool }
27
+ * validPersona(input) PURE → { persona } | { error }
28
+ * read(dir) · addPersona(dir, input, { by }) · removePersona(dir, id, { by }) · restorePersona(dir, id, { by })
29
+ * forVersion(dir, { ini, file, abs, flow }) → findings | null (runs or reads the stored run) · count(dir, { days }) → n
30
+ */
31
+ const fs = require('fs');
32
+ const path = require('path');
33
+ const crypto = require('crypto');
34
+
35
+ const FILE = 'sim-users.jsonl';
36
+ const LOG = '[sim-users]';
37
+ const MAX_PERSONAS = 6;
38
+ const MIN_PX = 44;
39
+ const NEEDS = Object.freeze({
40
+ keyboard: 'uses only the keyboard',
41
+ reader: 'listens with a screen reader',
42
+ words: 'is new and reads the words',
43
+ thumb: 'taps with a thumb on a phone',
44
+ });
45
+ const BASE = Object.freeze([
46
+ Object.freeze({ id: 'new-user', name: 'New user', needs: ['words'], base: true }),
47
+ Object.freeze({ id: 'keyboard-only', name: 'Keyboard only', needs: ['keyboard'], base: true }),
48
+ Object.freeze({ id: 'screen-reader', name: 'Screen reader', needs: ['reader'], base: true }),
49
+ Object.freeze({ id: 'on-a-phone', name: 'On a phone', needs: ['thumb'], base: true }),
50
+ ]);
51
+
52
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
53
+ const str = (v) => (typeof v === 'string' ? v : '');
54
+ const one = (v, n) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim().slice(0, n);
55
+ const hash = (s) => crypto.createHash('sha1').update(String(s)).digest('hex').slice(0, 12);
56
+ const slug = (s) => one(s, 60).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
57
+
58
+ /* ── a small HTML reader: enough of the tree to walk screens and presses ── */
59
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
60
+ const RAW = new Set(['script', 'style', 'template', 'textarea', 'title']);
61
+ function decode(s) {
62
+ return String(s).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp|#39);/gi, (m, e) => {
63
+ const k = e.toLowerCase();
64
+ if (k[0] === '#') { const n = k[1] === 'x' ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10); return Number.isFinite(n) && n > 0 && n < 0x110000 ? String.fromCodePoint(n) : ''; }
65
+ return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }[k] || m;
66
+ });
67
+ }
68
+ function attrsOf(s) {
69
+ const a = {}, re = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
70
+ let m; while ((m = re.exec(s))) a[m[1].toLowerCase()] = decode(m[2] != null ? m[2] : m[3] != null ? m[3] : m[4] != null ? m[4] : '');
71
+ return a;
72
+ }
73
+ /** PURE. The HTML as a tree: { tag, attrs, kids: [node | text] }. Comments, scripts and styles are skipped; an unclosed tag closes with its parent. */
74
+ function parse(html) {
75
+ const root = { tag: '#root', attrs: {}, kids: [] }, stack = [root];
76
+ const src = String(html == null ? '' : html).replace(/<!--[\s\S]*?-->/g, ' ');
77
+ const re = /<\/?([a-zA-Z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/g;
78
+ let last = 0, m;
79
+ const text = (t) => { if (t && /\S/.test(t)) stack[stack.length - 1].kids.push(decode(t)); };
80
+ while ((m = re.exec(src))) {
81
+ text(src.slice(last, m.index)); last = re.lastIndex;
82
+ const tag = m[1].toLowerCase();
83
+ if (m[0][1] === '/') {
84
+ const i = stack.map((n) => n.tag).lastIndexOf(tag);
85
+ if (i > 0) stack.length = i;
86
+ continue;
87
+ }
88
+ const node = { tag, attrs: attrsOf(m[2]), kids: [] };
89
+ stack[stack.length - 1].kids.push(node);
90
+ if (RAW.has(tag)) {
91
+ const end = src.toLowerCase().indexOf('</' + tag, re.lastIndex);
92
+ const inner = src.slice(re.lastIndex, end < 0 ? src.length : end);
93
+ if (tag === 'textarea' || tag === 'title') node.kids.push(decode(inner));
94
+ re.lastIndex = last = end < 0 ? src.length : src.indexOf('>', end) + 1 || src.length;
95
+ continue;
96
+ }
97
+ if (!VOID.has(tag) && !/\/\s*$/.test(m[2])) stack.push(node);
98
+ }
99
+ text(src.slice(last));
100
+ return root;
101
+ }
102
+ function walk(node, fn) { for (const k of node.kids || []) if (isObj(k)) { if (fn(k) === false) return false; if (walk(k, fn) === false) return false; } return true; }
103
+ function find(node, test) { let hit = null; walk(node, (n) => { if (test(n)) { hit = n; return false; } return true; }); return hit; }
104
+ function textOf(node) { return (node.kids || []).map((k) => (typeof k === 'string' ? k : textOf(k))).join(' ').replace(/\s+/g, ' ').trim(); }
105
+ /** PURE. The screens of a prototype: data-screen id → node. */
106
+ function screensOf(root) { const out = new Map(); walk(root, (n) => { const id = n.attrs['data-screen']; if (id && !out.has(id)) out.set(id, n); return true; }); return out; }
107
+ /** PURE. The press that leads from this step to the next: the step's tap (data-el), else what goes to the next screen. */
108
+ function pressOf(screen, step, next) {
109
+ if (!screen) return null;
110
+ const goes = (n) => (next && (n.attrs['data-go'] === next || n.attrs.href === '#' + next));
111
+ if (step && step.tap) {
112
+ const t = find(screen, (n) => n.attrs['data-el'] === step.tap);
113
+ if (t) return goes(t) ? t : (find(t, goes) || t);
114
+ }
115
+ return next ? find(screen, goes) : null;
116
+ }
117
+
118
+ /* ── each need on a press ── */
119
+ const FOCUSABLE = new Set(['button', 'input', 'select', 'textarea', 'summary']);
120
+ function reachable(n) {
121
+ if (n.attrs.tabindex != null && n.attrs.tabindex !== '' && Number(n.attrs.tabindex) < 0) return false;
122
+ if (FOCUSABLE.has(n.tag) && n.attrs.disabled == null) return true;
123
+ if (n.tag === 'a' && n.attrs.href != null) return true;
124
+ return n.attrs.tabindex != null && Number(n.attrs.tabindex) >= 0;
125
+ }
126
+ function nameOf(n, root) {
127
+ if (one(n.attrs['aria-label'], 200)) return one(n.attrs['aria-label'], 200);
128
+ if (n.attrs['aria-labelledby'] && root) {
129
+ const ids = n.attrs['aria-labelledby'].split(/\s+/), words = ids.map((id) => { const t = find(root, (x) => x.attrs.id === id); return t ? textOf(t) : ''; }).join(' ').trim();
130
+ if (words) return one(words, 200);
131
+ }
132
+ const t = textOf(n); if (/[\p{L}\p{N}]/u.test(t)) return one(t, 200);
133
+ if (n.tag === 'input' && one(n.attrs.value, 200)) return one(n.attrs.value, 200);
134
+ const img = n.tag === 'img' ? n : find(n, (x) => x.tag === 'img' && one(x.attrs.alt, 200));
135
+ if (img && one(img.attrs.alt, 200)) return one(img.attrs.alt, 200);
136
+ return one(n.attrs.title, 200);
137
+ }
138
+ const shown = (n) => { const t = textOf(n) || (n.tag === 'input' ? str(n.attrs.value) : ''); return /[\p{L}\p{N}]{2,}/u.test(t); };
139
+ const hasHeading = (screen) => !!find(screen, (n) => /^h[1-6]$/.test(n.tag) || n.attrs.role === 'heading');
140
+ function px(style, prop) { const m = new RegExp('(?:^|;)\\s*(?:min-)?' + prop + '\\s*:\\s*(\\d+(?:\\.\\d+)?)px', 'i').exec(str(style)); return m ? Number(m[1]) : null; }
141
+ function tooSmall(n) {
142
+ const w = px(n.attrs.style, 'width') ?? (/^\d+$/.test(str(n.attrs.width)) ? Number(n.attrs.width) : null);
143
+ const h = px(n.attrs.style, 'height') ?? (/^\d+$/.test(str(n.attrs.height)) ? Number(n.attrs.height) : null);
144
+ return (w != null && w < MIN_PX) || (h != null && h < MIN_PX);
145
+ }
146
+ /** PURE. Why this persona gets stuck on this press, or '' when it gets past. */
147
+ function blockOf(need, press, screen, root, label) {
148
+ if (need === 'keyboard' && !reachable(press)) return `${label} cannot be reached with the keyboard`;
149
+ if (need === 'reader' && !nameOf(press, root)) return `${label} has no name to hear`;
150
+ if (need === 'words' && !shown(press)) return `${label} shows no words, only a symbol`;
151
+ if (need === 'words' && !hasHeading(screen)) return 'no heading says where they are';
152
+ if (need === 'thumb' && tooSmall(press)) return `${label} is smaller than a thumb (${MIN_PX} px)`;
153
+ return '';
154
+ }
155
+
156
+ /* ── the walk ── */
157
+ /** PURE. Each persona walks each scenario of the flow over the version's HTML. → [{ persona, task, done, at?, el?, why? }] */
158
+ function simulate({ html, flow, personas }) {
159
+ const scen = (flow && Array.isArray(flow.scenarios) ? flow.scenarios : []).filter((s) => s && Array.isArray(s.steps) && s.steps.length);
160
+ const who = Array.isArray(personas) ? personas : [];
161
+ if (!scen.length || !who.length) return [];
162
+ const root = parse(html), screens = screensOf(root), titleOf = titlesOf(flow, screens);
163
+ const out = [];
164
+ for (const s of scen) {
165
+ for (const p of who) {
166
+ let stuck = null;
167
+ for (let i = 0; i < s.steps.length && !stuck; i += 1) {
168
+ const step = s.steps[i], next = i + 1 < s.steps.length ? s.steps[i + 1].screen : '';
169
+ const scr = screens.get(step.screen);
170
+ if (!scr) { stuck = { at: step.screen, why: `the screen ${titleOf(step.screen)} is not in the prototype` }; break; }
171
+ if (!next) break;
172
+ const press = pressOf(scr, step, next);
173
+ if (!press) { stuck = { at: step.screen, why: `nothing on it leads on to ${titleOf(next)}` }; break; }
174
+ const label = pressLabel(press, root);
175
+ for (const need of p.needs || []) { const why = blockOf(need, press, scr, root, label); if (why) { stuck = { at: step.screen, el: str(press.attrs['data-el']), why }; break; } }
176
+ }
177
+ out.push(stuck ? { persona: p.id, task: s.id, done: false, ...stuck } : { persona: p.id, task: s.id, done: true });
178
+ }
179
+ }
180
+ return out;
181
+ }
182
+ function titlesOf(flow, screens) {
183
+ const t = new Map(((flow && flow.screens) || []).map((x) => [x.id, one(x.title, 60)]));
184
+ return (id) => t.get(id) || one(screens && screens.get(id) ? screens.get(id).attrs['data-label'] : '', 60) || id;
185
+ }
186
+ function pressLabel(n, root) {
187
+ const name = one(n.attrs['data-label'], 40) || one(nameOf(n, root), 40);
188
+ return name ? `the ${name} press` : 'the press';
189
+ }
190
+
191
+ /* ── findings, not clicks ── */
192
+ /** PURE. tries → { personas: n, rows } | null. A stuck place is one row ("k of N personas stuck at "<screen>": why"), stuck rows first,
193
+ * the most stuck first; a task every persona finished is one row ("All N finished "<task>""). No tries: null (zero is silence). */
194
+ function findingsOf(tries, { flow, personas } = {}) {
195
+ if (!Array.isArray(tries) || !tries.length) return null;
196
+ const who = new Map((personas || []).map((p) => [p.id, p.name]));
197
+ const N = new Set(tries.map((t) => t.persona)).size;
198
+ const tasks = new Map(((flow && flow.scenarios) || []).map((s) => [s.id, one(s.name || s.id, 60)]));
199
+ const screenTitle = titlesOf(flow, null);
200
+ const stuck = new Map(), byTask = new Map();
201
+ for (const t of tries) {
202
+ if (!byTask.has(t.task)) byTask.set(t.task, []);
203
+ byTask.get(t.task).push(t);
204
+ if (t.done) continue;
205
+ // one row per place they got stuck (a task's screen), with every reason found there
206
+ const k = t.task + '\u0000' + t.at;
207
+ if (!stuck.has(k)) stuck.set(k, { task: t.task, screen: t.at, el: t.el || '', whys: [], who: new Set() });
208
+ const g = stuck.get(k);
209
+ g.who.add(t.persona);
210
+ if (!g.whys.includes(t.why)) g.whys.push(t.why);
211
+ if (!g.el && t.el) g.el = t.el;
212
+ }
213
+ const rows = [];
214
+ for (const g of stuck.values()) {
215
+ const n = g.who.size;
216
+ // "the Pay press cannot …; the Pay press has no name" says the press once: "the Pay press cannot …; has no name"
217
+ const lead = /^(the (?:.+? )?press) /.exec(g.whys[0]), whys = g.whys.map((w, i) => (i && lead && w.startsWith(lead[1] + ' ') ? w.slice(lead[1].length + 1) : w));
218
+ rows.push({ state: 'risk', n, task: g.task, screen: g.screen, ...(g.el ? { el: g.el } : {}),
219
+ text: `${n === N ? (N === 1 ? 'The persona' : `All ${N} personas`) : `${n} of ${N} personas`} stuck at "${screenTitle(g.screen)}": ${whys.join('; ')}`,
220
+ who: [...g.who].map((id) => who.get(id) || id).join(', ') });
221
+ }
222
+ rows.sort((a, b) => b.n - a.n || a.text.localeCompare(b.text));
223
+ for (const [task, ts] of byTask) {
224
+ if (!ts.every((t) => t.done)) continue;
225
+ const first = ((flow && flow.scenarios) || []).find((s) => s.id === task);
226
+ rows.push({ state: 'on', n: ts.length, task, screen: first ? first.steps[0].screen : '', text: `All ${ts.length} finished "${tasks.get(task) || task}"`, who: '' });
227
+ }
228
+ return { personas: N, rows };
229
+ }
230
+
231
+ /* ── personas, from the user's records ── */
232
+ /** PURE. A persona to add: { name, needs: [need] | "a,b", from: the record it comes from }. → { persona } | { error } */
233
+ function validPersona(input) {
234
+ const x = isObj(input) ? input : {};
235
+ const name = one(x.name, 60);
236
+ if (!name) return { error: 'a persona needs a name (--name "<who they are>")' };
237
+ const from = one(x.from, 200);
238
+ if (!from) return { error: 'a persona needs the record it comes from (--from "<file, page or quote>"): PMOS uses the user\'s real records, never made-up people' };
239
+ const needs = [...new Set((Array.isArray(x.needs) ? x.needs : str(x.needs).split(/[\s,]+/)).map((n) => String(n).trim().toLowerCase()).filter(Boolean))];
240
+ const bad = needs.filter((n) => !NEEDS[n]);
241
+ if (bad.length) return { error: `${bad.join(', ')} is not a need. Needs: ${Object.keys(NEEDS).join(', ')}` };
242
+ if (!needs.length) return { error: `a persona needs at least one need (--needs ${Object.keys(NEEDS).join(',')})` };
243
+ const id = slug(x.id || name);
244
+ if (!id) return { error: 'the name needs a letter or a number' };
245
+ return { persona: { id, name, needs, from } };
246
+ }
247
+ /** PURE. The persona lines folded: the newest line for an id wins. walking: the product's own personas, or BASE when none. */
248
+ function personasOf(lines) {
249
+ const by = new Map();
250
+ for (const l of lines || []) {
251
+ if (!isObj(l) || l.kind !== 'persona' || !str(l.id)) continue;
252
+ const prev = by.get(l.id) || {};
253
+ if (l.op === 'add' && isObj(l.persona)) by.set(l.id, { persona: l.persona, on: true, at: l.at });
254
+ else if (l.op === 'remove' && prev.persona) by.set(l.id, { ...prev, on: false, at: l.at });
255
+ else if (l.op === 'restore' && prev.persona) by.set(l.id, { ...prev, on: true, at: l.at });
256
+ }
257
+ const mine = [...by.values()].filter((x) => x.on).map((x) => x.persona).slice(0, MAX_PERSONAS);
258
+ const removed = [...by.values()].filter((x) => !x.on).map((x) => x.persona);
259
+ return { mine, removed, walking: mine.length ? mine : BASE.slice(), base: !mine.length };
260
+ }
261
+
262
+ /* ── the store ── */
263
+ const fileOf = (dir) => path.join(dir, FILE);
264
+ function read(dir) {
265
+ if (!dir) return [];
266
+ let text = ''; try { text = fs.readFileSync(fileOf(dir), 'utf8'); } catch { return []; }
267
+ const out = [];
268
+ for (const l of text.split('\n')) { if (!l.trim()) continue; try { const j = JSON.parse(l); if (isObj(j)) out.push(j); } catch { /* a torn line */ } }
269
+ return out;
270
+ }
271
+ function append(dir, line) { fs.mkdirSync(dir, { recursive: true }); fs.appendFileSync(fileOf(dir), JSON.stringify(line) + '\n'); }
272
+ function addPersona(dir, input, { by = 'agent:cli', now = Date.now() } = {}) {
273
+ if (!dir) return { ok: false, error: 'This repository has no PMOS state folder.' };
274
+ const v = validPersona(input); if (v.error) return { ok: false, error: v.error };
275
+ const P = personasOf(read(dir));
276
+ if (!P.mine.some((p) => p.id === v.persona.id) && P.mine.length >= MAX_PERSONAS) return { ok: false, error: `at most ${MAX_PERSONAS} personas walk a prototype: remove one first` };
277
+ append(dir, { at: new Date(now).toISOString(), kind: 'persona', op: 'add', id: v.persona.id, persona: v.persona, by });
278
+ return { ok: true, persona: v.persona };
279
+ }
280
+ function turn(op) {
281
+ return (dir, id, { by = 'agent:cli', now = Date.now() } = {}) => {
282
+ if (!dir) return { ok: false, error: 'This repository has no PMOS state folder.' };
283
+ const P = personasOf(read(dir)), list = op === 'remove' ? P.mine : P.removed, p = list.find((x) => x.id === String(id));
284
+ if (!p) return { ok: false, error: op === 'remove' ? `no persona ${id} walks now (pmos prototype personas lists them)` : `no removed persona ${id}` };
285
+ append(dir, { at: new Date(now).toISOString(), kind: 'persona', op, id: p.id, by });
286
+ return { ok: true, persona: p, undo: op === 'remove' ? `pmos prototype persona restore ${p.id}` : `pmos prototype persona remove ${p.id}` };
287
+ };
288
+ }
289
+ const removePersona = turn('remove');
290
+ const restorePersona = turn('restore');
291
+
292
+ /** The findings of one prototype version: the stored run when the version and the persona set are the same, else a new run (stored).
293
+ * Reads the version's HTML; writes only to the state folder, never to the version's folder or the proposals ledger. */
294
+ function forVersion(dir, { ini, file, abs, flow }, { now = Date.now() } = {}) {
295
+ if (!abs || !flow || !Array.isArray(flow.scenarios) || !flow.scenarios.length) return null;
296
+ let html = ''; try { html = fs.readFileSync(abs, 'utf8'); } catch { return null; }
297
+ const lines = read(dir), P = personasOf(lines);
298
+ const sig = hash(JSON.stringify([html, flow.scenarios, flow.screens, P.walking]));
299
+ for (let i = lines.length - 1; i >= 0; i -= 1) { const l = lines[i]; if (l.kind === 'run' && l.file === file && l.sig === sig) return l.findings; }
300
+ const findings = findingsOf(simulate({ html, flow, personas: P.walking }), { flow, personas: P.walking });
301
+ if (dir) {
302
+ try { append(dir, { at: new Date(now).toISOString(), kind: 'run', log: LOG, ini: one(ini, 80), file: one(file, 300), sig, personas: P.walking.map((p) => p.id), findings }); }
303
+ catch (e) { console.warn(LOG, 'not stored:', e.message); }
304
+ }
305
+ return findings;
306
+ }
307
+ /** The runs in the last days (the health number). */
308
+ function count(dir, { days = 7, now = Date.now() } = {}) {
309
+ const since = now - Math.max(1, Number(days) || 7) * 864e5;
310
+ return read(dir).filter((l) => l.kind === 'run' && l.log === LOG && Date.parse(l.at) >= since).length;
311
+ }
312
+
313
+ module.exports = { FILE, LOG, NEEDS, BASE, MIN_PX, MAX_PERSONAS, parse, screensOf, pressOf, simulate, findingsOf, validPersona, personasOf, read, addPersona, removePersona, restorePersona, forVersion, count };
314
+
315
+ if (require.main === module) {
316
+ // node lib/sim-users.js count [--days 7] [--dir <state folder>]: the health number on the last line
317
+ const a = process.argv.slice(2), at = (k) => { const i = a.indexOf('--' + k); return i >= 0 ? a[i + 1] : undefined; };
318
+ if (a[0] !== 'count') { console.error('usage: node lib/sim-users.js count [--days 7] [--dir <state folder>]'); process.exit(2); }
319
+ let dir = at('dir');
320
+ // the product's state folder (pmos/state or .pmos, as the server's stateDirFor finds it), from here up; else the per-user folder
321
+ for (let d = process.cwd(); !dir; ) {
322
+ for (const rel of ['pmos/state', '.pmos']) if (!dir && fs.existsSync(path.join(d, rel, FILE))) dir = path.join(d, rel);
323
+ const up = path.dirname(d); if (up === d) break; d = up;
324
+ }
325
+ if (!dir) { try { dir = require('./state-root.js').defaultRoot({ env: process.env }); } catch { dir = ''; } }
326
+ const n = count(dir, { days: at('days') });
327
+ console.log(`${LOG} ${n} simulated-user run${n === 1 ? '' : 's'} on prototype versions in the last ${Number(at('days')) || 7} days`);
328
+ console.log(String(n));
329
+ }