create-pmos 0.827.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 (43) hide show
  1. package/package.json +86 -32
  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 +85 -12
  8. package/workspace/guide/cli.md +29 -0
  9. package/workspace/lib/board-cli.js +5 -1
  10. package/workspace/lib/features.json +2 -0
  11. package/workspace/lib/five-action-cap.js +84 -0
  12. package/workspace/lib/people-cli.js +43 -2
  13. package/workspace/lib/pmos-verbs.js +7 -1
  14. package/workspace/lib/portfolio-cli.js +64 -0
  15. package/workspace/lib/portfolio.js +168 -0
  16. package/workspace/lib/review-reasons.js +357 -0
  17. package/workspace/lib/route-modules.js +2 -0
  18. package/workspace/lib/routes-portfolio.js +50 -0
  19. package/workspace/lib/routes-stakeholders.js +42 -0
  20. package/workspace/lib/routes-strategy-card.js +29 -1
  21. package/workspace/lib/routes-use-log.js +6 -1
  22. package/workspace/lib/stakeholder-map.js +232 -0
  23. package/workspace/lib/voice-cli.js +7 -0
  24. package/workspace/package-lock.json +2 -2
  25. package/workspace/package.json +1 -1
  26. package/workspace/premium-vw-jira-test.js +6 -2
  27. package/workspace/public/pm/bd-principles.js +12 -1
  28. package/workspace/public/pm/cozy-pick.css +1 -0
  29. package/workspace/public/pm/cozy-pop-work.js +6 -1
  30. package/workspace/public/pm/cozy-today-app.js +48 -1
  31. package/workspace/public/pm/cozy-today-view.js +12 -4
  32. package/workspace/public/pm/five-action-cap.js +104 -0
  33. package/workspace/public/pm/portfolio.js +67 -0
  34. package/workspace/public/pm/product-switcher.js +7 -1
  35. package/workspace/public/pm/review-reasons.js +75 -0
  36. package/workspace/public/pm/stakeholder-map.js +125 -0
  37. package/workspace/public/premium-portfolio.html +48 -0
  38. package/workspace/server.js +1 -1
  39. package/workspace/stage-card-tasks-test.js +11 -5
  40. package/workspace/test-lists/five-action-cap.json +9 -0
  41. package/workspace/test-lists/portfolio.json +9 -0
  42. package/workspace/test-lists/review-reasons.json +9 -0
  43. package/workspace/test-lists/stakeholder-map.json +9 -0
@@ -0,0 +1,357 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* review-reasons.js — reviews grouped by reason, not by score (idea A427, initiative review-reasons; done test
4
+ * planning/done-tests/review-reasons.md; board BatchMoreADS panel 28).
5
+ *
6
+ * Survey comments and app-store reviews, grouped by the reason behind them. Rows sort by how fast each reason grows. One ✦
7
+ * names the fastest-growing complaint; accepting it files a triage item (a capture note, lib/capture.js, which the needs
8
+ * queue proposes through lib/triage.js) with Undo. The score stays, as one line under the reasons.
9
+ *
10
+ * THE LEDGER: customer-voice.jsonl in the product's runs folder (planning/runs/ for PMOS itself, pmos/state/ in a kit
11
+ * repository; lib/plan-ledgers.js runsDir). Append-only JSON lines:
12
+ * { v: 1, ev: 'comment', cid, at, source, score, scale, reason, text, via } one comment as the customer wrote it
13
+ * { v: 1, ev: 'reason', cid, reason, at, via } names (or renames) a comment's reason
14
+ * { v: 1, ev: 'filed', reason, capture, at, by } the ✦ was accepted: a triage item was filed
15
+ * { v: 1, ev: 'unfiled', capture, at, by } its Undo
16
+ * cid 'vc_' + 10 hex of sha1(source, at, text): the same comment imported twice is one comment
17
+ * source survey | review | other
18
+ * score a number on `scale` (5 for a store's stars, 10 for an NPS survey), or null
19
+ *
20
+ * WHO NAMES A REASON (spec question 2, default kept): whoever adds the comment (the import's reason column, or the chat).
21
+ * A comment with no reason joins the one named reason it shares at least 2 words with, more than any other; otherwise it
22
+ * stays unsorted, and the block says how many. No model runs here.
23
+ *
24
+ * group(lines, now) → { rows, unsorted, loose, score, suggest, filed } PURE
25
+ * growthWord(last, prev) → 'up 3×' | 'up' | 'new' | 'flat' | 'down' PURE
26
+ * parseComment(o, now) → { ok, line } | { ok: false, error } PURE
27
+ * parseCsv(text) → [row objects] PURE
28
+ * ledgerFile(root) · read(root) · add(root, o) · importFile(root, file) · nameReason(root, cid, reason)
29
+ * file(root, reason, { actor, now }) · undo(root, capture, { actor, now }) · count(root, now)
30
+ *
31
+ * CLI (`pmos voice`, lib/voice-cli.js through lib/pmos-verbs.js; what chat and agents run; nothing else writes the ledger):
32
+ * pmos voice add --text "<comment>" [--reason "<reason>"] [--score 2] [--scale 5|10] [--source review] [--at <iso>]
33
+ * pmos voice import <file.csv|file.json> columns: text, reason, score, scale, source, at (a header row in a CSV)
34
+ * pmos voice reason <cid> "<reason>"
35
+ * pmos voice list [--json]
36
+ * pmos voice file "<reason>" files the reason as a triage item; prints the Undo line
37
+ * pmos voice undo <capture id>
38
+ * pmos voice count last line: reasons with a comment in the last 30 days
39
+ * Every option takes --root <checkout>; without it, the git root of the current folder. Every log line carries [voice].
40
+ * Nothing here calls a model or sends anything. Exit codes: 0 done, 1 refused, 2 usage.
41
+ */
42
+ const fs = require('fs');
43
+ const path = require('path');
44
+ const crypto = require('crypto');
45
+
46
+ const TAG = '[voice]';
47
+ const FILE = 'customer-voice.jsonl';
48
+ const SOURCES = Object.freeze(['survey', 'review', 'other']);
49
+ const MAX_TEXT = 500;
50
+ const MAX_REASON = 80;
51
+ const MAX_SHOWN = 20;
52
+ const DAY = 86400000;
53
+ const WINDOW_DAYS = 90;
54
+ const TREND_DAYS = 30;
55
+ const MIN_SUGGEST = 2; // a complaint needs at least this many comments in the last 30 days before PMOS names it
56
+ const CID_RE = /^vc_[0-9a-f]{10}$/;
57
+ const CAPTURE_RE = /^capture-\d{4}-\d{2}-\d{2}-\d+$/;
58
+ const LINE_BREAK = /[\r\n\x00-\x08\x0b-\x1f]/;
59
+ const STOP = new Set(['the', 'and', 'for', 'with', 'from', 'that', 'this', 'are', 'was', 'not', 'but', 'too', 'very', 'than', 'when', 'have', 'has', 'its', 'our', 'your', 'you', 'all', 'any', 'can']);
60
+
61
+ const str = (v) => (v == null ? '' : String(v)).trim();
62
+ const oneLine = (s) => str(s).replace(/\s+/g, ' ');
63
+ const words = (s) => [...new Set(String(s || '').toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3 && !STOP.has(w)))];
64
+ const cidOf = (source, at, text) => 'vc_' + crypto.createHash('sha1').update([source, at, text].join('\0')).digest('hex').slice(0, 10);
65
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
66
+
67
+ /** One `comment` line from what a caller gives, or the reason it is refused. PURE. */
68
+ function parseComment(o = {}, now = new Date()) {
69
+ const text = oneLine(o.text), reason = oneLine(o.reason), source = str(o.source || 'other').toLowerCase();
70
+ if (!text) return { ok: false, error: 'the comment has no text: --text "<what the customer wrote>"' };
71
+ if (!SOURCES.includes(source)) return { ok: false, error: `the source is one of: ${SOURCES.join(', ')}` };
72
+ if (reason.length > MAX_REASON) return { ok: false, error: `the reason is at most ${MAX_REASON} characters` };
73
+ const scale = o.scale == null || o.scale === '' ? (o.score != null && Number(o.score) > 5 ? 10 : 5) : Number(o.scale);
74
+ if (scale !== 5 && scale !== 10) return { ok: false, error: 'the scale is 5 (stars) or 10 (an NPS survey)' };
75
+ let score = null;
76
+ if (o.score != null && o.score !== '') {
77
+ score = Number(o.score);
78
+ if (!Number.isFinite(score) || score < 0 || score > scale) return { ok: false, error: `the score is a number from 0 to ${scale}` };
79
+ }
80
+ const atMs = o.at ? Date.parse(o.at) : new Date(now).getTime();
81
+ if (!Number.isFinite(atMs)) return { ok: false, error: 'the date is not one PMOS can read; use 2026-11-20 or an ISO time' };
82
+ const at = new Date(atMs).toISOString();
83
+ const t = text.slice(0, MAX_TEXT);
84
+ return { ok: true, line: { v: 1, ev: 'comment', cid: cidOf(source, at, t), at, source, score, scale, reason: reason || null, text: t, via: o.via || 'cli' } };
85
+ }
86
+
87
+ /** 'up 3×' from twice or more, 'up' from a quarter more, 'new' when the 30 days before had none, 'down' below three
88
+ * quarters, else 'flat'. PURE. */
89
+ function growthWord(last, prev) {
90
+ if (!prev) return last ? 'new' : 'flat';
91
+ const r = last / prev;
92
+ if (r >= 2) return `up ${Math.round(r)}×`;
93
+ if (r >= 1.25) return 'up';
94
+ if (r < 0.75) return 'down';
95
+ return 'flat';
96
+ }
97
+ const growing = (w) => w === 'new' || /^up/.test(w);
98
+ const lowScore = (c) => c.score != null && (c.scale === 10 ? c.score <= 6 : c.score <= 3);
99
+
100
+ /** The live comments (a reason line renames one), and the filed triage items still standing. PURE. */
101
+ function fold(lines) {
102
+ const comments = new Map(), filed = new Map();
103
+ for (const l of lines || []) {
104
+ if (!l || typeof l !== 'object') continue;
105
+ if (l.ev === 'comment' && CID_RE.test(String(l.cid || '')) && str(l.text) && !comments.has(l.cid)) {
106
+ const scale = l.scale === 10 ? 10 : 5, score = Number.isFinite(Number(l.score)) && l.score !== null ? Number(l.score) : null;
107
+ comments.set(l.cid, { cid: l.cid, at: String(l.at || ''), source: SOURCES.includes(l.source) ? l.source : 'other', score, scale,
108
+ reason: oneLine(l.reason).slice(0, MAX_REASON) || null, text: str(l.text).slice(0, MAX_TEXT) });
109
+ } else if (l.ev === 'reason' && comments.has(l.cid)) comments.get(l.cid).reason = oneLine(l.reason).slice(0, MAX_REASON) || null;
110
+ else if (l.ev === 'filed' && CAPTURE_RE.test(String(l.capture || '')) && str(l.reason)) filed.set(l.capture, { reason: str(l.reason), capture: l.capture, at: l.at || null });
111
+ else if (l.ev === 'unfiled') filed.delete(l.capture);
112
+ }
113
+ return { comments: [...comments.values()], filed };
114
+ }
115
+
116
+ /** A comment with no reason joins the ONE named reason it shares at least 2 words with, more than any other. PURE. */
117
+ function placeUnnamed(text, reasons) {
118
+ const have = new Set(words(text));
119
+ let best = null, bestN = 0, tie = false;
120
+ for (const r of reasons) {
121
+ const n = words(r).filter((w) => have.has(w)).length;
122
+ if (n > bestN) { best = r; bestN = n; tie = false; } else if (n === bestN && n > 0) tie = true;
123
+ }
124
+ return bestN >= 2 && !tie ? best : null;
125
+ }
126
+
127
+ /** The score line: the mean of a 5 scale, the NPS of a 10 scale, and how many comments each counts. '' when none is scored. PURE. */
128
+ function scoreLine(list) {
129
+ const five = list.filter((c) => c.score != null && c.scale === 5), ten = list.filter((c) => c.score != null && c.scale === 10);
130
+ const parts = [];
131
+ if (five.length) parts.push(`Score ${(five.reduce((s, c) => s + c.score, 0) / five.length).toFixed(1)} of 5 from ${plural(five.length, 'comment', 'comments')}`);
132
+ if (ten.length) {
133
+ const pro = ten.filter((c) => c.score >= 9).length, det = ten.filter((c) => c.score <= 6).length;
134
+ parts.push(`NPS ${Math.round((pro - det) * 100 / ten.length)} from ${plural(ten.length, 'answer', 'answers')}`);
135
+ }
136
+ return parts.join(' · ');
137
+ }
138
+
139
+ /** Lines → { rows, unsorted, score, suggest, filed }. PURE.
140
+ * rows: one per reason with a comment in the last 90 days, { reason, n, last, prev, growth, complaint, filed, comments },
141
+ * sorted by growth ((last + 1) / (prev + 1)), then by count. suggest: the fastest-growing complaint not filed yet, or null. */
142
+ function group(lines, now = Date.now()) {
143
+ const t = new Date(now).getTime();
144
+ const { comments, filed } = fold(lines);
145
+ const recent = comments.filter((c) => { const a = Date.parse(c.at); return Number.isFinite(a) && a <= t + DAY && t - a <= WINDOW_DAYS * DAY; });
146
+ const named = [...new Set(recent.map((c) => c.reason).filter(Boolean))];
147
+ const by = new Map();
148
+ const loose = [];
149
+ for (const c of recent) {
150
+ const reason = c.reason || placeUnnamed(c.text, named);
151
+ if (!reason) { loose.push(c); continue; }
152
+ if (!by.has(reason)) by.set(reason, []);
153
+ by.get(reason).push(c);
154
+ }
155
+ const filedBy = new Map([...filed.values()].map((f) => [f.reason, f.capture]));
156
+ const rows = [...by.entries()].map(([reason, list]) => {
157
+ const age = (c) => (t - Date.parse(c.at)) / DAY;
158
+ const last = list.filter((c) => age(c) <= TREND_DAYS).length, prev = list.filter((c) => age(c) > TREND_DAYS && age(c) <= 2 * TREND_DAYS).length;
159
+ const scored = list.filter((c) => c.score != null);
160
+ const complaint = scored.length > 0 && scored.filter(lowScore).length * 2 > scored.length;
161
+ const sorted = list.slice().sort((a, b) => b.at.localeCompare(a.at));
162
+ return { reason, n: list.length, last, prev, growth: growthWord(last, prev), rate: (last + 1) / (prev + 1), complaint, filed: filedBy.get(reason) || null,
163
+ comments: sorted.slice(0, MAX_SHOWN).map((c) => ({ cid: c.cid, at: c.at, source: c.source, score: c.score, scale: c.scale, text: c.text })) };
164
+ }).sort((a, b) => b.rate - a.rate || b.n - a.n || a.reason.localeCompare(b.reason));
165
+ const pick = rows.find((r) => r.complaint && growing(r.growth) && r.last >= MIN_SUGGEST && !r.filed) || null;
166
+ const suggest = pick ? { reason: pick.reason, line: `${pick.reason} is the fastest-growing complaint. Make it a work item?` } : null;
167
+ return { rows, unsorted: loose.length, loose: loose.slice(0, MAX_SHOWN).map((c) => ({ cid: c.cid, text: c.text })), score: scoreLine(recent), suggest, filed: [...filed.values()] };
168
+ }
169
+
170
+ /** A small CSV reader: a header row, commas, double quotes around a field that holds a comma or a quote. PURE. */
171
+ function parseCsv(text) {
172
+ const rows = [];
173
+ let row = [], f = '', q = false;
174
+ const s = String(text || '').replace(/^/, '');
175
+ for (let i = 0; i < s.length; i++) {
176
+ const ch = s[i];
177
+ if (q) { if (ch === '"') { if (s[i + 1] === '"') { f += '"'; i++; } else q = false; } else f += ch; continue; }
178
+ if (ch === '"') q = true;
179
+ else if (ch === ',') { row.push(f); f = ''; }
180
+ else if (ch === '\n' || ch === '\r') { if (ch === '\r' && s[i + 1] === '\n') i++; row.push(f); f = ''; if (row.some((x) => x.trim())) rows.push(row); row = []; }
181
+ else f += ch;
182
+ }
183
+ row.push(f); if (row.some((x) => x.trim())) rows.push(row);
184
+ if (!rows.length) return [];
185
+ const head = rows[0].map((h) => h.trim().toLowerCase());
186
+ return rows.slice(1).map((r) => Object.fromEntries(head.map((h, i) => [h, r[i] == null ? '' : r[i]])));
187
+ }
188
+
189
+ /* ── the ledger ── */
190
+ function ledgerFile(root) { return path.join(require('./plan-ledgers.js').runsDir(root), FILE); }
191
+ function read(root) {
192
+ let raw = '';
193
+ try { raw = fs.readFileSync(ledgerFile(root), 'utf8'); } catch { return []; }
194
+ const out = [];
195
+ for (const l of raw.split('\n')) { if (!l.trim()) continue; try { out.push(JSON.parse(l)); } catch { /* a line it cannot read is skipped */ } }
196
+ return out;
197
+ }
198
+ function append(root, lines) {
199
+ const file = ledgerFile(root);
200
+ fs.mkdirSync(path.dirname(file), { recursive: true });
201
+ fs.appendFileSync(file, lines.map((l) => JSON.stringify(l)).join('\n') + '\n');
202
+ }
203
+ function sig(root) { try { const s = fs.statSync(ledgerFile(root)); return `${s.size}:${s.mtimeMs}`; } catch { return '0'; } }
204
+
205
+ function add(root, o, now = new Date()) {
206
+ const p = parseComment(o, now);
207
+ if (!p.ok) return p;
208
+ const known = new Set(fold(read(root)).comments.map((c) => c.cid));
209
+ if (known.has(p.line.cid)) return { ok: true, cid: p.line.cid, already: true };
210
+ append(root, [p.line]);
211
+ return { ok: true, cid: p.line.cid, already: false };
212
+ }
213
+
214
+ /** Comments from an export file (CSV with a header row, or a JSON array). → { ok, added, already, refused: [{ row, error }] } */
215
+ function importFile(root, file, now = new Date()) {
216
+ let raw = '';
217
+ try { raw = fs.readFileSync(file, 'utf8'); } catch (e) { return { ok: false, error: `the file cannot be read: ${String((e && e.message) || e).slice(0, 160)}` }; }
218
+ let items = null;
219
+ if (/\.json$/i.test(file) || /^\s*\[/.test(raw)) { try { items = JSON.parse(raw); } catch { return { ok: false, error: 'the file is not JSON PMOS can read' }; } }
220
+ else items = parseCsv(raw);
221
+ if (!Array.isArray(items)) return { ok: false, error: 'the file holds no list of comments' };
222
+ const known = new Set(fold(read(root)).comments.map((c) => c.cid));
223
+ const fresh = [], refused = [];
224
+ let already = 0;
225
+ items.forEach((it, i) => {
226
+ const o = it && typeof it === 'object' ? it : {};
227
+ const p = parseComment({ text: o.text || o.comment || o.review || o.body, reason: o.reason, score: o.score != null && o.score !== '' ? o.score : (o.rating != null && o.rating !== '' ? o.rating : null),
228
+ scale: o.scale, source: o.source || 'other', at: o.at || o.date, via: 'import' }, now);
229
+ if (!p.ok) { refused.push({ row: i + 1, error: p.error }); return; }
230
+ if (known.has(p.line.cid)) { already++; return; }
231
+ known.add(p.line.cid); fresh.push(p.line);
232
+ });
233
+ if (fresh.length) append(root, fresh);
234
+ return { ok: true, added: fresh.length, already, refused };
235
+ }
236
+
237
+ function nameReason(root, cid, reason, now = new Date()) {
238
+ const r = oneLine(reason);
239
+ if (!CID_RE.test(String(cid || ''))) return { ok: false, error: 'name the comment by its id (vc_ and 10 letters or digits; pmos voice list shows them)' };
240
+ if (!r || r.length > MAX_REASON) return { ok: false, error: `the reason is one line of 1 to ${MAX_REASON} characters` };
241
+ if (!fold(read(root)).comments.some((c) => c.cid === cid)) return { ok: false, error: `no comment ${cid} in this product's customer voice` };
242
+ append(root, [{ v: 1, ev: 'reason', cid, reason: r, at: new Date(now).toISOString(), via: 'cli' }]);
243
+ return { ok: true };
244
+ }
245
+
246
+ /** The ✦ accepted: file `reason` as a triage item (a capture note). → { ok, capture, text } | { ok: false, status, error } */
247
+ function file(root, reason, { actor = null, now = new Date() } = {}) {
248
+ const G = group(read(root), new Date(now).getTime());
249
+ const row = G.rows.find((r) => r.reason === str(reason));
250
+ if (!row) return { ok: false, status: 404, error: `no reason "${str(reason).slice(0, MAX_REASON)}" in the last ${WINDOW_DAYS} days` };
251
+ if (row.filed) return { ok: false, status: 409, error: `already filed as ${row.filed}` };
252
+ const text = `Customer voice: ${row.reason}. ${plural(row.last, 'comment', 'comments')} in the last ${TREND_DAYS} days (${row.growth}), ${row.n} in ${WINDOW_DAYS} days.\n\n`
253
+ + row.comments.slice(0, 3).map((c) => `> ${c.text}`).join('\n') + '\n\nFiled by PMOS from the product\'s customer voice (pmos voice).';
254
+ const stateDir = require('./triage.js').stateDir(root);
255
+ const w = require('./capture.js').write(stateDir, { text, actor: actor && actor.by ? actor : { by: 'agent:unknown' }, now: new Date(now) });
256
+ if (!w.ok) return w;
257
+ append(root, [{ v: 1, ev: 'filed', reason: row.reason, capture: w.id, at: new Date(now).toISOString(), by: (actor && actor.by) || 'agent:unknown' }]);
258
+ console.error(`${TAG} filed "${row.reason}" as ${w.id}`);
259
+ return { ok: true, capture: w.id, text };
260
+ }
261
+
262
+ /** Undo a filing: remove the capture note PMOS filed, unless an initiative was already made from it. */
263
+ function undo(root, capture, { actor = null, now = new Date() } = {}) {
264
+ const id = str(capture);
265
+ if (!CAPTURE_RE.test(id)) return { ok: false, status: 400, error: 'name the triage item by its capture id (capture-YYYY-MM-DD-n)' };
266
+ const { filed } = fold(read(root));
267
+ if (!filed.has(id)) return { ok: false, status: 404, error: `${id} was not filed from customer voice, so PMOS leaves it alone` };
268
+ let made = {};
269
+ try { made = require('./placements.js').createdFrom(root) || {}; } catch { made = {}; }
270
+ if (made[id]) return { ok: false, status: 409, error: `an initiative was already made from ${id}; PMOS leaves it alone` };
271
+ const stateDir = require('./triage.js').stateDir(root);
272
+ try { fs.unlinkSync(path.join(stateDir, require('./capture.js').DIR, id + '.md')); } catch (e) { if (!e || e.code !== 'ENOENT') return { ok: false, status: 500, error: 'the triage item could not be removed' }; }
273
+ append(root, [{ v: 1, ev: 'unfiled', capture: id, at: new Date(now).toISOString(), by: (actor && actor.by) || 'agent:unknown' }]);
274
+ console.error(`${TAG} undid ${id}`);
275
+ return { ok: true };
276
+ }
277
+
278
+ /** The health number: reasons with a comment in the last 30 days. */
279
+ function count(root, now = Date.now()) { return group(read(root), now).rows.filter((r) => r.last > 0).length; }
280
+
281
+ /* ── the CLI ── */
282
+ const COMMANDS = { voice: ['add', 'import', 'reason', 'list', 'file', 'undo', 'count'] };
283
+ const USAGE = [
284
+ 'usage: pmos voice add --text "<comment>" [--reason "<reason>"] [--score <n>] [--scale 5|10] [--source survey|review|other] [--at <date>]',
285
+ ' pmos voice import <file.csv|file.json> (columns: text, reason, score, scale, source, at)',
286
+ ' pmos voice reason <comment id> "<reason>"',
287
+ ' pmos voice list [--json]',
288
+ ' pmos voice file "<reason>" · pmos voice undo <capture id>',
289
+ ' pmos voice count',
290
+ 'Each takes --root <checkout>. Work shows the reasons as Customer voice, under the strategy. PMOS sends nothing.',
291
+ ];
292
+ function repoOf(cwd) {
293
+ let d = path.resolve(cwd);
294
+ for (;;) { if (fs.existsSync(path.join(d, '.git'))) return d; const up = path.dirname(d); if (up === d) return path.resolve(cwd); d = up; }
295
+ }
296
+ function run(argv, o = {}) {
297
+ const say = o.say || ((s) => console.log(s)), now = o.now || new Date();
298
+ const args = argv[0] === 'voice' ? argv.slice(1) : argv.slice();
299
+ const pos = [], flags = {};
300
+ const VAL = new Set(['root', 'text', 'reason', 'score', 'scale', 'source', 'at']);
301
+ for (let i = 0; i < args.length; i++) {
302
+ const a = args[i];
303
+ if (a.startsWith('--') && VAL.has(a.slice(2))) flags[a.slice(2)] = args[++i];
304
+ else if (a === '--json') flags.json = true;
305
+ else pos.push(a);
306
+ }
307
+ const cmd = pos[0];
308
+ if (!cmd || cmd === 'help' || cmd === '--help') { USAGE.forEach((l) => say(l)); return cmd ? 0 : 2; }
309
+ if (!COMMANDS.voice.includes(cmd)) { say(`✗ ${cmd} is not a command of pmos voice`); USAGE.forEach((l) => say(l)); return 2; }
310
+ const root = path.resolve(flags.root || o.root || repoOf(o.cwd || process.cwd()));
311
+ const actorOf = () => { try { return require('./actor.js').fromCli({ isTTY: !!process.stdin.isTTY, env: process.env }); } catch { return null; } };
312
+ if (cmd === 'add') {
313
+ const r = add(root, { text: flags.text, reason: flags.reason, score: flags.score, scale: flags.scale, source: flags.source, at: flags.at }, now);
314
+ if (!r.ok) { say(`${TAG} refused: ${r.error}`); return 1; }
315
+ say(r.already ? `${TAG} ${r.cid} is already there.` : `${TAG} added ${r.cid}. Work shows it under Customer voice.`);
316
+ return 0;
317
+ }
318
+ if (cmd === 'import') {
319
+ if (!pos[1]) { USAGE.forEach((l) => say(l)); return 2; }
320
+ const r = importFile(root, path.resolve(o.cwd || process.cwd(), pos[1]), now);
321
+ if (!r.ok) { say(`${TAG} refused: ${r.error}`); return 1; }
322
+ say(`${TAG} added ${plural(r.added, 'comment', 'comments')}${r.already ? `; ${r.already} already there` : ''}${r.refused.length ? `; ${r.refused.length} refused (row ${r.refused[0].row}: ${r.refused[0].error})` : ''}.`);
323
+ return 0;
324
+ }
325
+ if (cmd === 'reason') {
326
+ const r = nameReason(root, pos[1], pos.slice(2).join(' ') || flags.reason, now);
327
+ if (!r.ok) { say(`${TAG} refused: ${r.error}`); return 1; }
328
+ say(`${TAG} ${pos[1]} now sits under "${oneLine(pos.slice(2).join(' ') || flags.reason)}".`);
329
+ return 0;
330
+ }
331
+ if (cmd === 'file') {
332
+ const r = file(root, pos.slice(1).join(' ') || flags.reason, { actor: actorOf(), now });
333
+ if (!r.ok) { say(`${TAG} refused: ${r.error}`); return 1; }
334
+ say(`${TAG} filed as triage item ${r.capture}. Undo: pmos voice undo ${r.capture}`);
335
+ return 0;
336
+ }
337
+ if (cmd === 'undo') {
338
+ const r = undo(root, pos[1], { actor: actorOf(), now });
339
+ if (!r.ok) { say(`${TAG} refused: ${r.error}`); return 1; }
340
+ say(`${TAG} took ${pos[1]} back.`);
341
+ return 0;
342
+ }
343
+ const G = group(read(root), new Date(now).getTime());
344
+ if (cmd === 'count') { const n = G.rows.filter((r) => r.last > 0).length; say(`${TAG} ${plural(n, 'reason', 'reasons')} with a comment in the last ${TREND_DAYS} days.`); say(String(n)); return 0; }
345
+ if (flags.json) { say(JSON.stringify({ ok: true, ...G })); return 0; }
346
+ if (!G.rows.length && !G.unsorted) { say('No customer comments yet. pmos voice import reads an export from your survey tool or app store.'); return 0; }
347
+ for (const r of G.rows) say(`- ${r.reason}: ${r.n} (30 days: ${r.growth})${r.complaint ? ' · complaint' : ''}${r.filed ? ` · filed ${r.filed}` : ''}`);
348
+ if (G.unsorted) { say(`${plural(G.unsorted, 'comment has', 'comments have')} no reason yet; pmos voice reason <id> "<reason>" names one:`); for (const c of G.loose) say(` ${c.cid} ${c.text.slice(0, 100)}`); }
349
+ if (G.score) say(G.score);
350
+ if (G.suggest) say(`✦ ${G.suggest.line} pmos voice file "${G.suggest.reason}"`);
351
+ return 0;
352
+ }
353
+
354
+ module.exports = { TAG, FILE, SOURCES, WINDOW_DAYS, TREND_DAYS, parseComment, growthWord, fold, placeUnnamed, scoreLine, group, parseCsv,
355
+ ledgerFile, read, sig, add, importFile, nameReason, file, undo, count, run, COMMANDS, USAGE };
356
+
357
+ if (require.main === module) process.exitCode = run(process.argv.slice(2));
@@ -151,10 +151,12 @@ const MODULES = Object.freeze([
151
151
  'routes-strategy-card', // bet A458: a product's five-line strategy above its Board, and the gentle "doesn't fit" note on new work (records strategy-card.jsonl; page-press POST)
152
152
  'routes-principles', // bet A352: a product's principles drafted from its decisions, kept or dropped on the Board (records principles.jsonl; page-press POST)
153
153
  'routes-prefs', // bet A461: view preferences that follow the person to the phone and other browsers (runtime view-prefs.json; page-press POST)
154
+ 'routes-stakeholders', // bet A371: an initiative's stakeholder map, decides / must agree / needs to know, in the Work popup (records stakeholders.jsonl; page-press POST)
154
155
  'routes-code-map', // idea A176: the product's code map on Work, redrawn when the default branch moves (records code-map.json; read-only)
155
156
  'routes-arch-warns', // idea A54: one warning when an initiative names a risky part of the code (reads code-map.json; read-only)
156
157
  'routes-live-rows', // bet A458: chat-made task changes streamed to open pages (runtime live-events.jsonl; read-only event stream)
157
158
  'routes-connector-data', // connector-data (A150): what each connector reads and writes, from lib/connector-data.js (read only)
159
+ 'routes-portfolio', // bet A56: the Portfolio, every product side by side, and the answer to its one recommendation (runtime portfolio.jsonl; page-press POST)
158
160
  ]);
159
161
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
160
162
  const MODULE_NAME = /^[a-z0-9][a-z0-9-]*\.js$/;
@@ -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' });