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,168 @@
1
+ 'use strict';
2
+ /* portfolio.js — the Portfolio: every product side by side for a head of product (bet A56, initiative portfolio, board BatchPlanDS panel 7).
3
+ *
4
+ * rowsOf(facts, { now }) PURE → [{ ws, name, bets, odds, judged, spend, outcome, due }] one row per product, in the given order
5
+ * recommend(rows) PURE → { key, to, from, n, text, why } | null at most one recommendation
6
+ * fold(lines, now) PURE → { [key]: { kind, until } } the decisions that stand (Undo takes the last back)
7
+ * hidden(rec, lines, now) PURE → bool Keep hides it while its facts hold; Not now for 7 days
8
+ * factsOf(root, { now }) → one product's facts, read from its own records (never written)
9
+ * read(products, { now }) → { show, rows, rec } products: [{ ws, name, root }]. rec is the recommendation before decisions
10
+ * view(products, dir, { now }) → { ok, show, rows, rec, as_of } read() with the decisions of <dir>/portfolio.jsonl applied
11
+ * decide(dir, { key, kind, by }, { now }) → { ok, line } | { ok: false, error } THE ONE WRITER of <dir>/portfolio.jsonl
12
+ *
13
+ * THE NUMBERS come from records every PMOS product keeps, so the page works on any user's products:
14
+ * bets the product's work initiatives that are not stopped and whose outcome is not judged yet (lib/outcomes.js scan: subjects less disposed)
15
+ * odds validated of validated plus refuted outcome checks, in percent. Under MIN_JUDGED judged it is null: not known, never a guess
16
+ * spend the cost of the product's agent runs in the last SPEND_DAYS days (factory-traces.jsonl in its state folder). No cost: null
17
+ * outcome the evidence of the product's latest check that held (validated). None: null
18
+ * due its bets whose outcome check is due: they wait on review
19
+ * THE RECOMMENDATION. The product with the most due checks, MIN_DUE or more, is the one to help. When another product has more open bets
20
+ * and none due, PMOS says to move one person from it; otherwise to look at the product first. The reason is the due count.
21
+ *
22
+ * THE STORE. <runtime>/portfolio.jsonl, append-only, one line { at, kind: 'keep'|'not-now'|'undo', key, by, until? }. The key holds the
23
+ * facts (to, from, due count), so a kept recommendation comes back only when they change. Nothing here writes a product's files.
24
+ * The Portfolio shows only with MIN_PRODUCTS products or more (`show`). */
25
+ const fs = require('fs');
26
+ const path = require('path');
27
+
28
+ const FILE = 'portfolio.jsonl';
29
+ const TAG = '[portfolio]';
30
+ const DAY = 86400000;
31
+ const SPEND_DAYS = 30;
32
+ const MIN_JUDGED = 3;
33
+ const MIN_DUE = 2;
34
+ const MIN_PRODUCTS = 2;
35
+ const NOT_NOW_DAYS = 7;
36
+ const KINDS = Object.freeze(['keep', 'not-now', 'undo']);
37
+ const KEY_RE = /^[A-Za-z0-9._:-]{1,200}$/;
38
+
39
+ const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); if (t.length <= n) return t; const c = t.slice(0, n - 1); return (c.slice(0, c.lastIndexOf(' ')) || c).replace(/[,;:\s]+$/, '') + '…'; };
40
+ const timeOf = (c) => { const t = Date.parse(c && (c.at || c.date) || ''); return Number.isFinite(t) ? t : 0; };
41
+
42
+ function rowsOf(facts, { now = Date.now() } = {}) {
43
+ const since = now - SPEND_DAYS * DAY;
44
+ return (facts || []).map((f) => {
45
+ const judgedIds = new Set((f.disposed || []).map((d) => d.id));
46
+ const bets = (f.subjects || []).filter((s) => !judgedIds.has(s.id)).length;
47
+ const held = (f.disposed || []).filter((d) => d.disposition === 'validated').length;
48
+ const refuted = (f.disposed || []).filter((d) => d.disposition === 'refuted').length;
49
+ const judged = held + refuted;
50
+ const odds = judged >= MIN_JUDGED ? Math.round((held / judged) * 100) : null;
51
+ let spend = null;
52
+ for (const r of f.runs || []) {
53
+ const t = Date.parse(r && r.at || '');
54
+ if (!Number.isFinite(t) || t < since || t > now || !Number.isFinite(r.costUsd) || r.costUsd <= 0) continue;
55
+ spend = (spend || 0) + r.costUsd;
56
+ }
57
+ if (spend != null) spend = Math.round(spend * 100) / 100;
58
+ const last = (f.checks || []).filter((c) => c && c.disposition === 'validated' && c.evidence).sort((a, b) => timeOf(b) - timeOf(a))[0];
59
+ return { ws: f.ws, name: f.name || f.ws, bets, odds, judged, spend, outcome: last ? clip(last.evidence, 60) : null, due: (f.due || []).length };
60
+ });
61
+ }
62
+
63
+ function recommend(rows) {
64
+ const R = (rows || []).filter(Boolean);
65
+ const to = R.filter((r) => r.due >= MIN_DUE).sort((a, b) => b.due - a.due || b.bets - a.bets || String(a.name).localeCompare(String(b.name)))[0];
66
+ if (!to) return null;
67
+ const from = R.filter((r) => r !== to && r.due === 0 && r.bets > to.bets).sort((a, b) => b.bets - a.bets || String(a.name).localeCompare(String(b.name)))[0] || null;
68
+ const n = to.due;
69
+ return {
70
+ key: `${to.ws}:${from ? from.ws : '-'}:${n}`,
71
+ to: to.ws, from: from ? from.ws : null, n,
72
+ text: from ? `Move one person from ${from.name} to ${to.name}` : `Look at ${to.name} first`,
73
+ why: `${n} bets there wait on their outcome check.`,
74
+ };
75
+ }
76
+
77
+ function fold(lines, now = Date.now()) {
78
+ const stack = {};
79
+ for (const l of lines || []) {
80
+ if (!l || !KEY_RE.test(String(l.key || '')) || !KINDS.includes(l.kind)) continue;
81
+ const s = (stack[l.key] = stack[l.key] || []);
82
+ if (l.kind === 'undo') s.pop(); else s.push(l);
83
+ }
84
+ const out = {};
85
+ for (const [k, s] of Object.entries(stack)) if (s.length) { const l = s[s.length - 1]; out[k] = { kind: l.kind, until: l.until || null, at: l.at || null }; }
86
+ return out;
87
+ }
88
+
89
+ function hidden(rec, lines, now = Date.now()) {
90
+ if (!rec) return false;
91
+ const d = fold(lines, now)[rec.key];
92
+ if (!d) return false;
93
+ if (d.kind === 'keep') return true;
94
+ return d.kind === 'not-now' && !!d.until && Date.parse(d.until) > now;
95
+ }
96
+
97
+ /** Every outcome check line the product holds, in the places lib/outcomes.js reads them, each file once. */
98
+ function checksOf(root, runsDir) {
99
+ const OC = require('./outcomes.js');
100
+ const files = [...new Set([runsDir, path.join(root, 'pmos', 'state'), path.join(root, 'planning', 'runs')].filter(Boolean).map((d) => path.join(d, 'outcome_checks.jsonl')))];
101
+ const rows = [];
102
+ for (const f of files) {
103
+ let text = ''; try { text = fs.readFileSync(f, 'utf8'); } catch { continue; }
104
+ for (const s of text.split('\n')) { if (!s.trim()) continue; try { const o = JSON.parse(s); if (o && typeof o === 'object') rows.push(o); } catch { /* a torn line */ } }
105
+ }
106
+ return OC.liveChecks(rows);
107
+ }
108
+
109
+ function factsOf(root, { now = Date.now() } = {}) {
110
+ const OC = require('./outcomes.js');
111
+ const S = OC.scan(root, { today: OC.todayOf(now) });
112
+ let runs = [];
113
+ try { const dir = require('./driver.js').stateDirOf(root); runs = require('./factory-traces.js').read(dir, { sinceMs: now - SPEND_DAYS * DAY }); } catch { runs = []; }
114
+ return {
115
+ subjects: S.subjects.map((s) => ({ id: s.id })),
116
+ disposed: S.disposed.map((d) => ({ id: d.id, disposition: d.disposition })),
117
+ due: S.due.map((d) => ({ id: d.id })),
118
+ checks: checksOf(path.resolve(root), S.layout && S.layout.runsDir),
119
+ runs: runs.map((r) => ({ at: r.at, costUsd: r.costUsd })),
120
+ };
121
+ }
122
+
123
+ function read(products, { now = Date.now(), factsOf: F = factsOf } = {}) {
124
+ const list = (products || []).filter((p) => p && p.root);
125
+ const facts = list.map((p) => { let f; try { f = F(p.root, { now }); } catch { f = {}; } return { ...f, ws: p.ws, name: p.name || path.basename(p.root) }; });
126
+ const rows = rowsOf(facts, { now });
127
+ return { show: rows.length >= MIN_PRODUCTS, rows, rec: recommend(rows) };
128
+ }
129
+
130
+ function linesOf(dir) {
131
+ let text = ''; try { text = fs.readFileSync(path.join(dir, FILE), 'utf8'); } catch { return []; }
132
+ const out = [];
133
+ for (const s of text.split('\n')) { if (!s.trim()) continue; try { out.push(JSON.parse(s)); } catch { /* a torn line */ } }
134
+ return out;
135
+ }
136
+
137
+ function view(products, dir, o = {}) {
138
+ const now = o.now || Date.now();
139
+ const r = read(products, o);
140
+ if (!r.show) return { ok: true, show: false, rows: [], rec: null, as_of: new Date(now).toISOString() };
141
+ const rec = r.rec && !hidden(r.rec, dir ? linesOf(dir) : [], now) ? r.rec : null;
142
+ return { ok: true, show: true, rows: r.rows, rec, as_of: new Date(now).toISOString() };
143
+ }
144
+
145
+ function decide(dir, { key, kind, by } = {}, { now = Date.now() } = {}) {
146
+ if (!dir) return { ok: false, error: 'no state folder to keep the decision in' };
147
+ if (!KINDS.includes(kind)) return { ok: false, error: `the answer is one of ${KINDS.join(', ')}` };
148
+ if (!KEY_RE.test(String(key || ''))) return { ok: false, error: 'name the recommendation by its key' };
149
+ if (kind === 'undo' && !fold(linesOf(dir), now)[key]) return { ok: false, error: 'there is no answer to this recommendation to undo' };
150
+ const line = { at: new Date(now).toISOString(), kind, key: String(key), by: String(by || 'pm').slice(0, 40) };
151
+ if (kind === 'not-now') line.until = new Date(now + NOT_NOW_DAYS * DAY).toISOString();
152
+ try {
153
+ fs.mkdirSync(dir, { recursive: true });
154
+ fs.appendFileSync(path.join(dir, FILE), JSON.stringify(line) + '\n', { mode: 0o600 });
155
+ } catch (e) { return { ok: false, error: 'the decision could not be saved: ' + String((e && e.message) || e).slice(0, 160) }; }
156
+ return { ok: true, line };
157
+ }
158
+
159
+ /** One printed line per product, then the recommendation. PURE. */
160
+ function lines(v) {
161
+ if (!v || !v.show) return ['Nothing to compare: the Portfolio needs two or more products.'];
162
+ const money = (n) => (n == null ? '' : '$' + (n >= 100 ? Math.round(n) : n.toFixed(2)));
163
+ const out = v.rows.map((r) => r.name + ': ' + [`${r.bets} bet${r.bets === 1 ? '' : 's'}`, r.odds == null ? '' : `odds ${r.odds}%`, r.spend == null ? '' : `spend ${money(r.spend)} (30 days)`, r.outcome ? `outcome: ${r.outcome}` : ''].filter(Boolean).join(' · '));
164
+ if (v.rec) out.push(`✦ ${v.rec.text}: ${v.rec.why} (pmos portfolio keep|not-now ${v.rec.key})`);
165
+ return out;
166
+ }
167
+
168
+ module.exports = { FILE, TAG, SPEND_DAYS, MIN_JUDGED, MIN_DUE, MIN_PRODUCTS, NOT_NOW_DAYS, KINDS, rowsOf, recommend, fold, hidden, factsOf, read, view, decide, linesOf, lines };
@@ -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,9 +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)
156
+ 'routes-arch-warns', // idea A54: one warning when an initiative names a risky part of the code (reads code-map.json; read-only)
155
157
  'routes-live-rows', // bet A458: chat-made task changes streamed to open pages (runtime live-events.jsonl; read-only event stream)
156
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)
157
160
  ]);
158
161
  const PM_DIR = path.join(__dirname, '..', 'public', 'pm');
159
162
  const MODULE_NAME = /^[a-z0-9][a-z0-9-]*\.js$/;
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+ /* routes-arch-warns.js — the architecture warning of one initiative over HTTP (idea A54, initiative arch-warns). The reading and its rules
3
+ * are lib/arch-warns.js; the code map it reads is code-map.json in the product's records folder (lib/records-dir.js), drawn by
4
+ * lib/routes-code-map.js.
5
+ *
6
+ * GET /api/arch-warns?ini=<id>&ws=<id> → { ok, warn } warn: { part, dir, what, tested, why, at, more, id, path } or null
7
+ *
8
+ * `warn` is null for everything that is not worth a line: no repository, no map yet, no such record, a record that names no part, a part
9
+ * the code map does not call risky, and work that is closed or done. A missing initiative is not an error, because the page asks for every
10
+ * initiative it opens.
11
+ *
12
+ * READ ONLY. It writes nothing, starts no code-map draw and sends nothing anywhere. The test task the ✦ offers is written by the PM's own
13
+ * press, through POST /api/boards/tasks/add. */
14
+ const path = require('path');
15
+ const AW = require('./arch-warns.js');
16
+ const { recordsDirFor } = require('./records-dir.js');
17
+
18
+ const CHECKOUT = path.join(__dirname, '..', '..');
19
+ const ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/;
20
+ function wsOf(ctx, ws) { try { return ctx && typeof ctx.getWs === 'function' ? ctx.getWs(ws || null) : null; } catch { return null; } }
21
+ const rootFor = (ctx, w) => (ctx && ctx.repoRoot) || (w && w.root) || CHECKOUT;
22
+
23
+ function handle(req, res, url, ctx) {
24
+ if (url.pathname !== '/api/arch-warns') return false;
25
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
26
+ if (req.method !== 'GET') return send(405, { ok: false, error: 'GET' });
27
+ const ws = url.searchParams.get('ws') || null;
28
+ const ini = String(url.searchParams.get('ini') || '').trim();
29
+ if (!ID_RE.test(ini)) return send(400, { ok: false, error: 'ini is an initiative id' });
30
+ const dir = recordsDirFor(ctx, ws), root = rootFor(ctx, wsOf(ctx, ws));
31
+ let warn = null;
32
+ try { warn = AW.read(root, dir, ini); } catch { warn = null; } // an unreadable map or record says nothing
33
+ if (!warn) return send(200, { ok: true, warn: null });
34
+ AW.say('warned ' + ini + ': ' + warn.part + ' (' + warn.why + ')');
35
+ // the words live in lib/arch-warns.js, so the page, the terminal and the test all say the same thing
36
+ return send(200, { ok: true, warn: Object.assign({}, warn, { say: AW.sayOf(warn), note: AW.whyOf(warn, { path: warn.path }), task: AW.taskOf(warn) }) });
37
+ }
38
+
39
+ module.exports = { prefixes: ['/api/arch-warns'], handle };
@@ -16,6 +16,7 @@
16
16
  * POST /api/onboard/review { fields, jira } the PM's edits to the draft
17
17
  * POST /api/onboard/init initialize or reuse, register, settle the fundamentals (resumable)
18
18
  * POST /api/onboard/fundamental { key } the one-press change of one fundamentals line (lib/onboard-fundamentals.js)
19
+ * POST /api/onboard/starter { act, n } keep, drop or undo one starter goal (lib/starter-goals.js, job #1916); act: keep|drop|undo
19
20
  * POST /api/onboard/reset start again (the folder and anything written stay)
20
21
  */
21
22
  const fs = require('fs');
@@ -84,12 +85,14 @@ function view(ctx) {
84
85
  }
85
86
 
86
87
  async function handle(req, res, url, ctx) {
87
- const m = /^\/api\/onboard\/(state|own|login|check|project|folder|discover|search|review|init|fundamental|reset)$/.exec(url.pathname);
88
+ const m = /^\/api\/onboard\/(state|own|login|check|project|folder|discover|search|review|init|fundamental|starter|reset)$/.exec(url.pathname);
88
89
  if (!m) return false;
89
90
  const send = (body, code = 200) => { ctx.json(res, body, code); return true; };
90
91
  if (!ctx.claudeSetup) return send({ ok: false, error: 'Claude setup is unavailable.' }, 503);
91
92
  const verb = m[1];
92
- if (verb === 'state') return req.method === 'GET' ? send(view(ctx)) : send({ ok: false, error: 'GET only' }, 405);
93
+ // starter goals (A84, lib/starter-goals.js): the drafts still open for the product set up here, drawn under the fundamentals card
94
+ const starterOf = () => { const s0 = read(ctx); const SG = require('./starter-goals.js'); try { return s0.done && s0.done.root && ctx.getWs(s0.done.ws) ? SG.view(s0.done.root) : null; } catch { return null; } };
95
+ if (verb === 'state') return req.method === 'GET' ? send({ ...view(ctx), starter: starterOf() }) : send({ ok: false, error: 'GET only' }, 405);
93
96
  if (req.method !== 'POST') return send({ ok: false, error: 'POST only' }, 405);
94
97
  const got = await ctx.readJson(req); if (!got.ok) return send({ ok: false, error: 'Invalid JSON.' }, 400);
95
98
  const b = got.body || {}, g = guard.requirePagePress(req, b);
@@ -99,6 +102,16 @@ async function handle(req, res, url, ctx) {
99
102
  try {
100
103
  if (verb === 'reset') { write(ctx, {}); try { fs.unlinkSync(journal(ctx)); } catch {} return send(view(ctx)); }
101
104
  if (verb === 'own') return send(ctx.claudeSetup.ensureOwn());
105
+ // A84: starter goals write only the product's own goal file, so they need no Claude login check (before the bound gate)
106
+ if (verb === 'starter') {
107
+ const ws = st.done && st.done.ws && ctx.getWs(st.done.ws);
108
+ if (!ws || !st.done.root) return send({ ok: false, error: 'Set up the project first.', need: 'init' }, 409);
109
+ const act = str(b.act, 8), n = Number(b.n);
110
+ const o = { runtimeDir: ctx.runtimeDir, useDir: ctx.runtimeDir };
111
+ const SG = require('./starter-goals.js');
112
+ const r = act === 'keep' ? SG.keep(st.done.root, n, o) : act === 'drop' ? SG.drop(st.done.root, n, o) : act === 'undo' ? SG.undo(st.done.root, o) : { ok: false, error: 'act is keep, drop or undo' };
113
+ return send({ ...view(ctx), starter: starterOf(), ok: !!r.ok, error: r.ok ? undefined : r.error, starter_did: r.ok ? { act: r.act || act, n: r.n, kr: r.kr || null, file: r.file || null } : null });
114
+ }
102
115
  if (verb === 'login') {
103
116
  const dir = path.join(ctx.runtimeDir, 'onboarding', 'signin'); fs.mkdirSync(dir, { recursive: true });
104
117
  const r = await ctx.claudeSetup.login(b.profile, null, 'login', dir);
@@ -219,9 +232,11 @@ async function handle(req, res, url, ctx) {
219
232
  try { fundamentals = F.settle({ root: r.root, ws: w.id, sources: (st.found && st.found.sources) || [], fresh: !!(r.journal.steps.kit && r.journal.steps.kit.detail === 'installed'), refresh: ctx.refreshSources ? ctx.refreshSources() : F.refreshAt(ctx.runtimeDir), ...(ctx.launcher !== undefined ? { launcher: ctx.launcher } : {}) }); }
220
233
  catch { fundamentals = { root: r.root, ws: w.id, lines: [], did: {}, error: 'Some fundamentals could not be settled. Change them in Settings.' }; }
221
234
  }
235
+ // A84: starter goals drafted once from the product's own sources, right after the fundamentals; a product with goals gets none
236
+ try { require('./starter-goals.js').draft(r.root, { runtimeDir: ctx.runtimeDir }); } catch { /* no starter goals, setup goes on */ }
222
237
  if (ctx.broadcast) ctx.broadcast({ t: 'focus', ws: w.id });
223
238
  write(ctx, { ...st, init: { ok: true, steps: r.journal.steps }, fundamentals, done: { ws: w.id, name, root: r.root, context: r.journal.steps.context && r.journal.steps.context.detail, at: new Date().toISOString() } });
224
- return send(view(ctx));
239
+ return send({ ...view(ctx), starter: starterOf() });
225
240
  }
226
241
  if (verb === 'fundamental') {
227
242
  if (!st.fundamentals) return send({ ok: false, error: 'Set up the project first.', need: 'init' }, 409);