create-pmos 0.830.0 → 0.832.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 +129 -50
  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/changelog.json +128 -36
  7. package/workspace/guide/backlog.md +1 -1
  8. package/workspace/guide/cli.md +27 -1
  9. package/workspace/guide/layout.md +4 -1
  10. package/workspace/guide/programs.md +2 -1
  11. package/workspace/lib/anchor-id.js +226 -0
  12. package/workspace/lib/artefacts-cli.js +25 -1
  13. package/workspace/lib/events-place.js +11 -4
  14. package/workspace/lib/features.json +2 -0
  15. package/workspace/lib/initiative-cli.js +67 -2
  16. package/workspace/lib/layouts-cli.js +6 -0
  17. package/workspace/lib/lessons-draft.js +242 -0
  18. package/workspace/lib/list-balance.js +18 -3
  19. package/workspace/lib/pmos-verbs.js +6 -0
  20. package/workspace/lib/prefs-sync.js +1 -1
  21. package/workspace/lib/route-modules.js +2 -0
  22. package/workspace/lib/routes-c3-strategy.js +2 -1
  23. package/workspace/lib/routes-events-place.js +19 -1
  24. package/workspace/lib/routes-proposals.js +2 -2
  25. package/workspace/lib/routes-screen-layouts.js +56 -0
  26. package/workspace/lib/routes-switches.js +35 -0
  27. package/workspace/lib/switch-owners.js +152 -0
  28. package/workspace/lib/switches-cli.js +85 -0
  29. package/workspace/lib/three-layouts.js +214 -0
  30. package/workspace/package-lock.json +2 -2
  31. package/workspace/package.json +1 -1
  32. package/workspace/public/pm/bd-goal.js +33 -0
  33. package/workspace/public/pm/bd-pop-ds.css +16 -0
  34. package/workspace/public/pm/bd-work-ds.css +6 -0
  35. package/workspace/public/pm/bd-work.js +34 -8
  36. package/workspace/public/pm/card-fold.js +123 -0
  37. package/workspace/public/pm/cozy-ev.css +7 -0
  38. package/workspace/public/pm/cozy-events-view.js +8 -4
  39. package/workspace/public/pm/cozy-nav.js +2 -0
  40. package/workspace/public/pm/cozy-pop-work.js +8 -3
  41. package/workspace/public/pm/cozy-today-app.js +28 -1
  42. package/workspace/public/pm/cozy-today-model.js +13 -5
  43. package/workspace/public/pm/cozy-today-view.js +10 -1
  44. package/workspace/public/pm/list-balance.js +16 -2
  45. package/workspace/public/pm/premium-board.js +7 -1
  46. package/workspace/public/pm/readonly.js +2 -0
  47. package/workspace/public/pm/switch-owners.js +70 -0
  48. package/workspace/public/pm/three-layouts.js +66 -0
  49. package/workspace/public/premium-board.html +2 -0
  50. package/workspace/stage-card-tasks-test.js +1 -0
  51. package/workspace/test-lists/anchor-id.json +9 -0
  52. package/workspace/test-lists/card-fold.json +9 -0
  53. package/workspace/test-lists/lessons-on-close.json +9 -0
  54. package/workspace/test-lists/switch-owners.json +9 -0
  55. package/workspace/test-lists/three-layouts.json +9 -0
@@ -0,0 +1,242 @@
1
+ 'use strict';
2
+ /* lessons-draft.js — PMOS drafts an initiative's Lessons when its experiment closes (initiative lessons-on-close, job #1971, idea A542; done
3
+ * test planning/done-tests/lessons-on-close.md).
4
+ *
5
+ * D107 made Lessons one of the seven artefacts (lib/artefacts.js). An experiment closes when an outcome check is recorded on it, or when the PM
6
+ * keeps the ✦ that stops it (a met kill line or a refuted check: the D70 lifecycle line, state cancelled). Then PMOS reads what the experiment
7
+ * set out to do and what happened, and writes up to five Lessons lines on experiment:<id>, each with its sources. Every line is an agent's
8
+ * set: `pmos artefacts undo <a-id>` takes it back.
9
+ *
10
+ * factsOf(root, id) → { id, title, expected, kill, intent, goal, doneRows: [text], result: { kind, disposition?, evidence, date } | null,
11
+ * decisions: [text], sources: { experiment, done, result, decision } } | null READ-ONLY
12
+ * closedOf(root, id) → the result that closed it ({ kind: 'check'|'stopped', … }) or null
13
+ * promptOf(F) · parse(text, F) the session's prompt and its answer read back ([{ text, sources }], at most MAX) PURE
14
+ * fallbackOf(F) → [{ text, sources }] a plain draft from the facts' own words, when no session answers PURE
15
+ * lessonsHere(state, id) → { pm: [set], agent: [set] } the Lessons lines on experiment:<id>, by who wrote them PURE
16
+ * draft(ctx, { root, id, dir, now }) → { ok, wrote: [line], made: 'session'|'facts' } | { ok: true, wrote: [], why }
17
+ * onClose(ctx, { root, id }) the hook: drafts once, in the background, after a check is recorded or an experiment is stopped
18
+ * due(root, { dir }) → [id] closed experiments with no Lessons line yet
19
+ * kept(dir, { now, days }) → the drafted lines still standing that were written in the last `days` days (the health number)
20
+ *
21
+ * NEVER over the PM: an initiative with a Lessons line the PM wrote gets no draft, and nothing here undoes or edits a line. A second check on
22
+ * an initiative that has drafted Lessons drafts nothing more. The session is one normal PMOS session (`claude -p` through the existing
23
+ * read-only `briefing-ask:` ask kind, no tools but Read), as lib/task-describe.js uses. Tests inject ctx.askClaude(prompt, { job, key }).
24
+ * The copy says PMOS, never the model's name. */
25
+ const fs = require('fs');
26
+ const path = require('path');
27
+ const crypto = require('crypto');
28
+ const A = require('./artefacts.js');
29
+
30
+ const MAX = 5;
31
+ const BY = 'agent:lessons-draft';
32
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
33
+ const DAY = 864e5;
34
+ const clip = (s, n) => { const t = String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); return t.length <= n ? t : t.slice(0, n - 1).replace(/[,;:\s]+$/, '') + '…'; };
35
+ const linesOf = (f) => { try { return fs.readFileSync(f, 'utf8').replace(/\r\n?/g, '\n').split('\n'); } catch { return null; } };
36
+ const rel = (root, f) => path.relative(root, f).split(path.sep).join('/');
37
+ const unquote = (v) => String(v || '').trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');
38
+ function jsonRows(file) { const L = linesOf(file); if (!L) return []; const out = []; for (const s of L) { if (!s.trim()) continue; try { const o = JSON.parse(s); if (o && typeof o === 'object') out.push(o); } catch { /* torn */ } } return out; }
39
+
40
+ function layoutOf(root) {
41
+ const kit = fs.existsSync(path.join(root, 'pmos', 'state'));
42
+ return { kit, initiatives: kit ? path.join(root, 'pmos', 'state', 'initiatives') : path.join(root, 'planning', 'initiatives'), runsDir: kit ? path.join(root, 'pmos', 'state') : path.join(root, 'planning', 'runs') };
43
+ }
44
+ const ledger = (root, L, name) => [...new Set([path.join(L.runsDir, name), path.join(root, 'pmos', 'state', name), path.join(root, 'planning', 'runs', name)])].flatMap(jsonRows);
45
+ function frontOf(L) {
46
+ const fm = {}; let end = 0;
47
+ if (!L || !/^---\s*$/.test(L[0] || '')) return { fm, end };
48
+ for (let i = 1; i < L.length && i < 200; i++) { if (/^---\s*$/.test(L[i])) { end = i + 1; break; } const m = /^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/.exec(L[i]); if (m && !(m[1] in fm)) fm[m[1]] = unquote(m[2]); }
49
+ return { fm, end };
50
+ }
51
+ /** The first paragraph under "## <name>". */
52
+ function sectionOf(L, name) {
53
+ const at = L.findIndex((l) => new RegExp('^##\\s+' + name + '\\s*$', 'i').test(l));
54
+ if (at < 0) return '';
55
+ const out = [];
56
+ for (let i = at + 1; i < L.length && !/^#{1,2}\s/.test(L[i]); i++) { if (!L[i].trim()) { if (out.length) break; continue; } out.push(L[i].trim()); }
57
+ return clip(out.join(' '), 400);
58
+ }
59
+
60
+ /** The result that closed the experiment: its standing outcome check, else the D70 line that stopped it. null while it runs. */
61
+ function closedOf(root, id) {
62
+ root = path.resolve(root);
63
+ const L = layoutOf(root);
64
+ let checks = [];
65
+ try { checks = require('./outcomes.js').liveChecks(ledger(root, L, 'outcome_checks.jsonl')); } catch { checks = []; }
66
+ const c = checks.filter((r) => r.initiative_id === id && r.disposition).pop();
67
+ let life = null;
68
+ for (const r of ledger(root, L, 'lifecycle.jsonl')) if (r && r.initiative_id === id && r.state) life = r;
69
+ if (life && life.state === 'cancelled') return { kind: 'stopped', evidence: clip(life.reason || 'Stopped.', 400), date: String(life.at || '').slice(0, 10), ref: rel(root, path.join(L.runsDir, 'lifecycle.jsonl')) };
70
+ if (c) return { kind: 'check', disposition: c.disposition, evidence: clip(c.evidence, 400), date: c.date || String(c.at || '').slice(0, 10), ref: rel(root, path.join(L.runsDir, 'outcome_checks.jsonl')) };
71
+ return null;
72
+ }
73
+
74
+ function factsOf(root, id) {
75
+ root = path.resolve(root);
76
+ if (!ID_RE.test(String(id || ''))) return null;
77
+ const L = layoutOf(root), file = path.join(L.initiatives, id + '.md'), R = linesOf(file);
78
+ if (!R) return null;
79
+ const { fm } = frontOf(R);
80
+ const doneFile = fm.done_test_path ? path.resolve(root, String(fm.done_test_path).replace(/^\//, '')) : null;
81
+ const D = doneFile && doneFile.startsWith(root + path.sep) ? linesOf(doneFile) : null;
82
+ const doneRows = (D || []).map((l) => /^\|\s*([A-Z]{1,3}\d{1,3})\s*\|\s*(.+?)\s*\|/.exec(l)).filter(Boolean).map((m) => clip(m[1] + ': ' + m[2], 240)).slice(0, 8);
83
+ const decFile = path.join(root, 'pm-decisions.md'), DL = linesOf(decFile) || [];
84
+ const idRe = new RegExp('(^|[^a-z0-9-])' + id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^a-z0-9-]|$)', 'i');
85
+ const decisions = DL.filter((l) => idRe.test(l) && l.trim().length > id.length + 8).slice(-3).map((l) => clip(l.replace(/^\s*[-*#|>]+\s*/, ''), 300));
86
+ return {
87
+ id, title: fm.title || id, expected: clip(fm.expected_outcome || '', 300), kill: clip(fm.kill || '', 300),
88
+ intent: sectionOf(R, 'Intent'), goal: sectionOf(R, 'Goal'), doneRows, result: closedOf(root, id), decisions,
89
+ sources: { experiment: rel(root, file), done: D ? rel(root, doneFile) : '', result: '', decision: decisions.length ? 'pm-decisions.md' : '' },
90
+ };
91
+ }
92
+
93
+ const SRC = { experiment: 'the experiment', done: 'the done test', result: 'the result', decision: 'a decision' };
94
+ function srcList(F, keys) {
95
+ const out = [];
96
+ for (const k of keys) {
97
+ const ref = k === 'result' ? (F.result && F.result.ref) || '' : F.sources[k];
98
+ if (ref && !out.some((x) => x.ref === ref)) out.push({ label: SRC[k], ref });
99
+ }
100
+ return out;
101
+ }
102
+ const WORD = { worked: 'worked', confirmed: 'worked', refuted: 'did not work', 'did-not-work': 'did not work', inconclusive: 'was inconclusive' };
103
+ const resultWord = (r) => (!r ? '' : r.kind === 'stopped' ? 'was stopped' : WORD[r.disposition] || 'was checked (' + r.disposition + ')');
104
+
105
+ /** PURE. */
106
+ function promptOf(F) {
107
+ const r = F.result;
108
+ return [
109
+ 'You write the Lessons of one closed product experiment for a product manager. Write from the facts below only. Invent nothing.',
110
+ 'Write 1 to 5 lines. Each line is one lesson in plain words (at most 200 characters): what this experiment teaches the next one.',
111
+ 'End each line with its source in brackets, one of [experiment], [done test], [result], [decision]. A line with no source is dropped.',
112
+ 'Start each line with "- ". Write nothing else.',
113
+ '',
114
+ `Experiment: ${F.title} (${F.id})`,
115
+ F.intent ? `Intent: ${F.intent}` : '',
116
+ F.goal ? `Goal: ${F.goal}` : '',
117
+ F.expected ? `Expected outcome: ${F.expected}` : '',
118
+ F.kill ? `Kill line: ${F.kill}` : '',
119
+ F.doneRows.length ? 'Done test:\n' + F.doneRows.map((x) => ' ' + x).join('\n') : '',
120
+ r ? `Result (${r.date}): it ${resultWord(r)}. ${r.evidence}` : '',
121
+ F.decisions.length ? 'Decisions:\n' + F.decisions.map((x) => ' ' + x).join('\n') : '',
122
+ ].filter(Boolean).join('\n');
123
+ }
124
+ const TAG = { experiment: 'experiment', 'done test': 'done', result: 'result', decision: 'decision' };
125
+ /** PURE. The session's lines with a known source, at most MAX. */
126
+ function parse(text, F) {
127
+ const out = [];
128
+ for (const raw of String(text || '').split('\n')) {
129
+ const m = /^\s*[-*]\s+(.+?)\s*\[(experiment|done test|result|decision)\]\s*\.?\s*$/i.exec(raw);
130
+ if (!m) continue;
131
+ const k = TAG[m[2].toLowerCase()], t = clip(m[1].replace(/\s*[—–-]\s*$/, ''), 300);
132
+ const sources = srcList(F, [k]);
133
+ if (t.length < 12 || !sources.length || /\bclaude\b/i.test(t)) continue;
134
+ out.push({ text: t, sources });
135
+ if (out.length >= MAX) break;
136
+ }
137
+ return out;
138
+ }
139
+ /** PURE. A plain draft in the facts' own words. */
140
+ function fallbackOf(F) {
141
+ const r = F.result, out = [];
142
+ if (r) out.push({ text: clip(`${F.title} ${resultWord(r)} (${r.date}): ${r.evidence.replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['result']) });
143
+ if (F.expected && r) out.push({ text: clip(`It set out to show: ${F.expected.replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['experiment']) });
144
+ if (F.kill && r && r.kind === 'stopped') out.push({ text: clip(`Its kill line was: ${F.kill.replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['experiment']) });
145
+ if (F.doneRows.length && r) out.push({ text: clip(`The done test checked ${F.doneRows.length} ${F.doneRows.length === 1 ? 'thing' : 'things'}, first ${F.doneRows[0].replace(/[.\s]+$/, '')}.`, 300), sources: srcList(F, ['done']) });
146
+ return out.filter((x) => x.sources.length).slice(0, MAX);
147
+ }
148
+
149
+ /** PURE. */
150
+ function lessonsHere(state, id) {
151
+ const x = state && state.get('experiment:' + id), m = x && x.get('lessons');
152
+ const sets = m ? m.sets.filter((l) => l.field === 'line') : [];
153
+ return { pm: sets.filter((l) => /^pm:/.test(String(l.by || ''))), agent: sets.filter((l) => !/^pm:/.test(String(l.by || ''))) };
154
+ }
155
+
156
+ /* ── the session ── */
157
+ const MODEL = 'claude-sonnet-5-5';
158
+ const LEAN = Object.freeze([{ flag: '--strict-mcp-config' }, { flag: '--disable-slash-commands' }, { flag: '--setting-sources', value: 'user' }, { flag: '--tools', value: 'Read' }]);
159
+ const TIMEOUT_MS = 90000;
160
+ function viaSession(ctx, prompt, key) {
161
+ if (typeof ctx.askClaude === 'function') return Promise.resolve(ctx.askClaude(prompt, { job: 'lessons-draft', key })).catch(() => null);
162
+ const origin = 'briefing-ask:lessons-draft:' + key;
163
+ let headless = null; try { headless = require('./headless.js'); } catch { headless = null; }
164
+ if (typeof ctx.spawnSession !== 'function' || !headless || headless.kindFor({ agent: 'claude', origin }) !== 'ask') return Promise.resolve(null);
165
+ return new Promise((resolve) => {
166
+ let settled = false; const done = (v) => { if (settled) return; settled = true; clearTimeout(t); resolve(v); };
167
+ const t = setTimeout(() => done(null), TIMEOUT_MS);
168
+ let s = null;
169
+ try {
170
+ s = ctx.spawnSession({ name: 'lessons: draft them', agent: 'claude', origin, initialInput: prompt,
171
+ modelAsk: { explicit: { model: MODEL, effort: 'low' } }, launchFlags: LEAN.map((f) => ({ ...f })),
172
+ onDone: (d) => { const r = d && d.result; done(r && r.ok && !r.isError ? String(r.text || '') : null); } });
173
+ } catch { s = null; }
174
+ if (!s || s.state === 'exited') done(null);
175
+ });
176
+ }
177
+
178
+ const RUNNING = new Set();
179
+ async function draft(ctx, { root, id, dir = null, now = Date.now() } = {}) {
180
+ root = path.resolve(root || '.');
181
+ if (!ID_RE.test(String(id || ''))) return { ok: false, error: 'name the initiative by its id' };
182
+ let d = dir; if (!d) { try { d = A.dirOf(root); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } }
183
+ const f = A.file(d);
184
+ const here = lessonsHere(A.fold(A.readLines(f)), id);
185
+ if (here.pm.length) return { ok: true, wrote: [], why: 'you wrote its lessons: PMOS leaves them as they are' };
186
+ if (here.agent.length) return { ok: true, wrote: [], why: 'PMOS drafted its lessons already' };
187
+ const F = factsOf(root, id);
188
+ if (!F) return { ok: false, error: `no initiative ${id} here` };
189
+ if (!F.result) return { ok: true, wrote: [], why: `${id} is still running: its lessons are drafted when its outcome check or kill line closes it` };
190
+ const key = crypto.createHash('sha1').update(root + '\n' + id + '\n' + promptOf(F)).digest('hex').slice(0, 12);
191
+ const said = await viaSession(ctx || {}, promptOf(F), key);
192
+ const got = said != null ? parse(said, F) : [];
193
+ const L = got.length ? got : fallbackOf(F), made = got.length ? 'session' : 'facts';
194
+ // the PM may have written while the session ran: read again, and write nothing over their lessons
195
+ const again = lessonsHere(A.fold(A.readLines(f)), id);
196
+ if (again.pm.length || again.agent.length) return { ok: true, wrote: [], why: again.pm.length ? 'you wrote its lessons: PMOS leaves them as they are' : 'PMOS drafted its lessons already' };
197
+ const wrote = [];
198
+ for (const x of L) {
199
+ const r = A.set(f, { scope: 'experiment:' + id, artefact: 'lessons', field: 'line', text: x.text, sources: x.sources }, { by: BY, via: 'pmos' }, { now });
200
+ if (r.ok) wrote.push(r.line);
201
+ }
202
+ console.info(`[lessons-draft] drafted ${id} lines=${wrote.length} made=${made} closed=${F.result.kind}`);
203
+ return { ok: true, wrote, made };
204
+ }
205
+
206
+ /** The hook (lib/routes-proposals.js): after a check is recorded or an experiment is stopped. Drafts in the background, once per id at a time. */
207
+ function onClose(ctx, { root, id, dir = null } = {}) {
208
+ const k = String(root) + '|' + id;
209
+ if (RUNNING.has(k)) return null;
210
+ RUNNING.add(k);
211
+ const p = Promise.resolve().then(() => draft(ctx, { root, id, dir })).catch((e) => { console.warn('[lessons-draft] ' + id + ': ' + String((e && e.message) || e).slice(0, 160)); return null; })
212
+ .finally(() => RUNNING.delete(k));
213
+ return p;
214
+ }
215
+
216
+ function due(root, { dir = null } = {}) {
217
+ root = path.resolve(root);
218
+ const L = layoutOf(root);
219
+ let d = dir; if (!d) { try { d = A.dirOf(root); } catch { d = null; } }
220
+ const S = d ? A.fold(A.readLines(A.file(d))) : new Map();
221
+ const ids = new Set();
222
+ for (const r of ledger(root, L, 'outcome_checks.jsonl')) if (r && r.initiative_id && r.disposition) ids.add(r.initiative_id);
223
+ for (const r of ledger(root, L, 'lifecycle.jsonl')) if (r && r.initiative_id && r.state === 'cancelled') ids.add(r.initiative_id);
224
+ return [...ids].filter((id) => ID_RE.test(id) && closedOf(root, id) && fs.existsSync(path.join(L.initiatives, id + '.md'))).filter((id) => { const h = lessonsHere(S, id); return !h.pm.length && !h.agent.length; }).sort();
225
+ }
226
+
227
+ function kept(dir, { now = Date.now(), days = 7 } = {}) {
228
+ const lines = A.readLines(A.file(dir));
229
+ const undone = new Set(lines.filter((l) => l.ev === 'undo').map((l) => l.ref));
230
+ return lines.filter((l) => l.ev === 'set' && l.artefact === 'lessons' && l.by === BY && !undone.has(l.id) && Date.parse(l.at) >= now - days * DAY).length;
231
+ }
232
+
233
+ module.exports = { MAX, BY, factsOf, closedOf, promptOf, parse, fallbackOf, lessonsHere, draft, onClose, due, kept };
234
+
235
+ // `node lib/lessons-draft.js kept [--days N]`: the health number on its last line
236
+ if (require.main === module) {
237
+ const a = process.argv.slice(2), i = a.indexOf('--days'), days = i >= 0 ? Number(a[i + 1]) || 7 : 7;
238
+ if (a[0] !== 'kept') { console.log('usage: node lib/lessons-draft.js kept [--days N]'); process.exit(2); }
239
+ let root = process.cwd(); try { root = require('child_process').execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || root; } catch { /* cwd */ }
240
+ let dir = null; try { dir = A.dirOf(root); } catch { dir = null; }
241
+ console.log(String(dir ? kept(dir, { days }) : 0));
242
+ }
@@ -6,6 +6,7 @@
6
6
  * item already has and says the mix in one line, with a quiet note only when one kind passes the PM's line (default 60 percent).
7
7
  *
8
8
  * kindOf(item) → 'feature' | 'fix' | 'debt' | 'discovery' | 'other'
9
+ * an initiative on a workflow (`wf`): the kind the workflow's name says ("Simple feature" → feature), else its lane; never `type`.
9
10
  * the item's own words, first that names one: kind, lane, type (a Jira issue type). feature · story · epic → feature;
10
11
  * incident · bug · defect · fix → fix; chore · debt · tech-debt · refactor → debt (a plain Jira Task is other); discovery · spike · prototype ·
11
12
  * research → discovery. Anything else, or nothing, is other. Never guessed from the title.
@@ -46,10 +47,24 @@ function wordKind(w) {
46
47
  return '';
47
48
  }
48
49
 
49
- /** The item's kind from its own fields, never from its title. */
50
+ /** The kind a workflow's name (or id) names: "Simple feature" → feature, "Bug triage" → fix; '' when it names none. */
51
+ function workflowKind(wf) {
52
+ if (!wf || typeof wf !== 'object') return '';
53
+ for (const src of [wf.name, wf.id]) {
54
+ const w = norm(String(src == null ? '' : src).replace(/[-]+/g, ' ')).split(' ').filter(Boolean);
55
+ for (let i = 0; i < w.length; i++) { const k = wordKind(w[i] + ' ' + (w[i + 1] || '')) || wordKind(w[i]); if (k) return k; }
56
+ }
57
+ return '';
58
+ }
59
+
60
+ /** The item's kind from its own fields, never from its title. An initiative on a workflow (a row with `wf`): the kind its workflow
61
+ * names, else its lane; a legacy `type:` decides nothing there, since the workflow sets the kind (kind-follows-workflow, #1731).
62
+ * Any other item: kind, lane, type (a Jira issue type). */
50
63
  function kindOf(item) {
51
64
  if (!item || typeof item !== 'object') return 'other';
52
- for (const f of ['kind', 'lane', 'type', 'issuetype']) {
65
+ const onWf = item.wf && typeof item.wf === 'object';
66
+ if (onWf) { const k = workflowKind(item.wf); if (k) return k; }
67
+ for (const f of onWf ? ['lane'] : ['kind', 'lane', 'type', 'issuetype']) {
53
68
  const v = valOf(item[f]);
54
69
  const k = wordKind(v && typeof v === 'object' ? v.name : v);
55
70
  if (k) return k;
@@ -98,7 +113,7 @@ function roadmapItems(root, { today } = {}) {
98
113
  return S.subjects.filter((it) => !it.accepted).map((it) => ({ id: it.id, title: it.title, lane: it.lane, outcome_metric: it.metric }));
99
114
  }
100
115
 
101
- module.exports = { KINDS, KIND_LABEL, OUTCOMES, OUTCOME_LABEL, DEFAULT_MAX, MIN_ITEMS, TAG, kindOf, outcomeOf, balanceOf, line, roadmapItems };
116
+ module.exports = { KINDS, KIND_LABEL, OUTCOMES, OUTCOME_LABEL, DEFAULT_MAX, MIN_ITEMS, TAG, workflowKind, kindOf, outcomeOf, balanceOf, line, roadmapItems };
102
117
 
103
118
  if (require.main === module) {
104
119
  const a = process.argv.slice(2);
@@ -191,6 +191,9 @@ const VERBS = Object.freeze({
191
191
  // Not a pm-os-absorb verb (run: null): initiative product-principles-draft (bet A352) added it through the same table.
192
192
  principles: Object.freeze({ module: 'principles-cli.js', run: null, guide: 'cli.md',
193
193
  help: 'pmos principles list|sources|draft|keep|drop|undo|add — the product\'s principles, drafted from its decisions, each citing them; keep or drop each (pmos principles help)' }),
194
+ // Not a pm-os-absorb verb (run: null): initiative switch-owners (job #1908, idea A263) added it through the same table.
195
+ switches: Object.freeze({ module: 'switches-cli.js', run: null, guide: 'cli.md',
196
+ help: 'pmos switches list|add|set|undo|turn|cancel|count — who has which switch: each customer\'s switch, why, and who agreed; turning one waits for you (pmos switches help)' }),
194
197
  // Not a pm-os-absorb verb (run: null): initiative positioning-draft (idea A328) added it through the same table.
195
198
  positioning: Object.freeze({ module: 'positioning-cli.js', run: null, guide: 'cli.md',
196
199
  help: 'pmos positioning strategy|list|keep|drop — the product\'s positioning and key messages, each citing its strategy lines (pmos positioning help)' }),
@@ -264,6 +267,9 @@ const VERBS = Object.freeze({
264
267
  help: 'pmos signal add|remove|list|count — the customer signals behind each roadmap item; Work shows the count (pmos signal help)' }),
265
268
  launcher: Object.freeze({ module: 'launcher-cli.js', run: null, guide: 'cli.md',
266
269
  help: 'pmos launcher on|off|status — a PMOS app and a login item, so the workspace starts without a terminal' }),
270
+ // Not a pm-os-absorb verb (run: null): initiative three-layouts (job #1904, A317) added it through the same table.
271
+ layouts: Object.freeze({ module: 'layouts-cli.js', run: null, guide: 'cli.md',
272
+ help: 'pmos layouts show|pick|undo|taste — a new screen\'s three layouts, the one PMOS recommends from your picks, and your pick (pmos layouts help)' }),
267
273
  // bet A459a (job #1751): a new public API, held out of auto-merge until Wawan's final yes
268
274
  mcp: Object.freeze({ module: 'mcp-cli.js', run: null, guide: 'cli.md',
269
275
  help: 'pmos mcp [--root <repo>] — PMOS cards for another agent, as A2UI v1.0 over MCP (stdio)' }),
@@ -49,7 +49,7 @@ const KEYS = Object.freeze({
49
49
  'pmos.home.cardfold', 'pmos-report-orders-hidden', 'cz-live-side',
50
50
  'pmos.pop.five', // the work popup's four toolbar actions, worked out weekly from use (idea A498, pm/pop-cap.js)
51
51
  ]),
52
- prefix: Object.freeze(['pmos.board.', 'pmos.pv.tab:', 'pmos.dash.view:', 'cz-vw-fold:']),
52
+ prefix: Object.freeze(['pmos.board.', 'pmos.pv.tab:', 'pmos.dash.view:', 'cz-vw-fold:', 'pmos.fold:']),
53
53
  });
54
54
  const EXACT = new Set(KEYS.exact);
55
55
 
@@ -152,12 +152,14 @@ const MODULES = Object.freeze([
152
152
  'routes-use-log', // bet A466: the local use log, page opens and controls pressed, on this computer only (runtime use-log.jsonl; page-press POST)
153
153
  '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)
154
154
  'routes-principles', // bet A352: a product's principles drafted from its decisions, kept or dropped on the Board (records principles.jsonl; page-press POST)
155
+ 'routes-switches', // idea A263: who has which switch, per customer, on Work; turning one waits for the PM's own press (records switches.jsonl; page-press POST)
155
156
  'routes-prefs', // bet A461: view preferences that follow the person to the phone and other browsers (runtime view-prefs.json; page-press POST)
156
157
  'routes-skill-map', // bet A208: the team skill map on Work, for the person and their lead only (records skill-map.jsonl; page-press POST)
157
158
  '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)
158
159
  'routes-code-map', // idea A176: the product's code map on Work, redrawn when the default branch moves (records code-map.json; read-only)
159
160
  'routes-arch-warns', // idea A54: one warning when an initiative names a risky part of the code (reads code-map.json; read-only)
160
161
  'routes-live-rows', // bet A458: chat-made task changes streamed to open pages (runtime live-events.jsonl; read-only event stream)
162
+ 'routes-screen-layouts', // three-layouts (A317): a new screen's three layouts, the ✦ pick and its Undo (product state layouts.jsonl; page-press POST)
161
163
  'routes-team-waits', // team-waits (A364): Work › Dependencies' waits on other teams (GET, read-only; team-waits.jsonl written by pmos deps)
162
164
  'routes-connector-data', // connector-data (A150): what each connector reads and writes, from lib/connector-data.js (read only)
163
165
  'routes-review-pack', // job #1910 (A343): the monthly review packs for Library › Reports, drafted when due (<state>/reports/review-pack/; page-press POST)
@@ -15,6 +15,7 @@
15
15
  *
16
16
  * Sources: planning/records/{kr-metrics,bets,hypotheses}.jsonl through scripts/records, and <runtime>/signals/signals.jsonl. No facts
17
17
  * reader is used, so the route never starts a cold repository read. A number that no record holds is null, never invented. */
18
+ const { anchorId } = require('./anchor-id.js');
18
19
  const path = require('path');
19
20
  const fs = require('fs');
20
21
  const { repoScript } = require('./repo-script.js');
@@ -111,7 +112,7 @@ function signalsOf(outcomes, sig, readingsByMetric) {
111
112
  function synergyOf(krs, bets) {
112
113
  if (!bets.length) return null;
113
114
  const cols = krs.map((k) => ({ id: k.rid, n: String(k.metric || k.rid), icon: 'target' }));
114
- const hit = (b, c) => !!b.parent_kr && (String(b.parent_kr) === c.id || String(b.parent_kr) === c.n);
115
+ const hit = (b, c) => { const a = anchorId(b.parent_kr); return !!a && (a === c.id || a === c.n || String(b.parent_kr) === c.n); }; // the id, not its note (A547)
115
116
  const rows = bets.slice().sort((a, b) => a.rank - b.rank).map((b) => ({ id: b.rid, title: String(b.title), parked: b.horizon === 'later', weights: cols.map((c) => (hit(b, c) ? 1 : 0)), initiative: b.initiative || null }));
116
117
  const notes = [];
117
118
  cols.forEach((c, j) => { if (!rows.some((r) => !r.parked && r.weights[j] > 0)) notes.push({ icon: 'alert', tone: 'bad', text: c.n + ' has no active bet.' }); });
@@ -123,6 +123,24 @@ function readMeetings(runtimeDir, now) {
123
123
  const events = require('./calendar-events.js').readAll(runtimeDir, { now: now.getTime() });
124
124
  let links = null;
125
125
  try { const CL = require('./calendar-links.js'); links = CL.read(runtimeDir); for (const e of events) { const l = links.get(CL.keyOf(e)); if (l && l.kind === 'initiative' && l.initiative) e.initiative = l.initiative; } } catch { /* the brief's own link stays */ }
126
+ attachNotes(events, runtimeDir, now);
127
+ return events;
128
+ }
129
+ /** The note of each meeting that has passed: { id, line } (its first summary line; a private note gives its id only), so a past day on
130
+ * Events shows the meeting with its notes. The same match as lib/notes.js sameEvent: the event id, else the start minute and title.
131
+ * Meetings from today on are left alone. A notes folder that cannot be read gives no notes. */
132
+ function attachNotes(events, runtimeDir, now) {
133
+ const today = localDay(now);
134
+ const past = events.filter((e) => e && typeof e.at === 'string' && e.at.slice(0, 10) < today);
135
+ if (!past.length) return events;
136
+ let rows = [];
137
+ try { const N = require('./notes.js'); const l = N.list(runtimeDir, { now: now.getTime() }); rows = l && l.ok ? l.notes.filter((n) => n && n.meeting && n.meeting.kind === 'event') : []; } catch { return events; }
138
+ if (!rows.length) return events;
139
+ const same = require('./notes.js').sameEvent;
140
+ for (const e of past) {
141
+ const n = rows.find((r) => same(r.meeting, { event_id: e.id, start: e.at, title: e.title }));
142
+ if (n) e.note = { id: n.id, line: n.private ? '' : String((n.summary_lines || [])[0] || '') };
143
+ }
126
144
  return events;
127
145
  }
128
146
  /** Does PMOS read a calendar at all: an import ledger, the remembered calendar, or a meeting in hand? */
@@ -161,7 +179,7 @@ async function handle(deps) {
161
179
  }
162
180
 
163
181
  module.exports = {
164
- foldMarks, markLine, handlePure: handle, readers: { readSchedules, readDrafts, readOwn, readMarks, readJira, readMeetings, calendarRead },
182
+ foldMarks, markLine, handlePure: handle, readers: { readSchedules, readDrafts, readOwn, readMarks, readJira, readMeetings, calendarRead, attachNotes },
165
183
  prefixes: ['/api/events-place'],
166
184
  handle: async (req, res, url, ctx) => {
167
185
  if (url.pathname === '/api/events-place/mark') {
@@ -399,7 +399,7 @@ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
399
399
  else {
400
400
  const by = g.actor && g.actor.by && g.actor.by !== 'agent:auto' ? g.actor.by : 'agent:outcomes';
401
401
  const r = O.recordCheck(p.w.root, { initiative: ini, disposition: d.disposition, evidence: d.evidence, by, via: 'pmos', sources: x.sources || [] });
402
- if (r.ok) add({ op: 'verdict', at: r.line.at, disposition: d.disposition, horizon: d.horizon });
402
+ if (r.ok) { add({ op: 'verdict', at: r.line.at, disposition: d.disposition, horizon: d.horizon }); require('./lessons-draft.js').onClose(ctx, { root: p.w.root, id: ini }); } // lessons-on-close (A542)
403
403
  else x.failed = r.error;
404
404
  }
405
405
  } else if (x.group === 'outcome' && x.type === 'test') {
@@ -428,7 +428,7 @@ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
428
428
  // a met kill line (lib/kill-check.js, its ref is the record's kill line) says so, not "the outcome check said"
429
429
  const reason = (require('./kill-check.js').isKillRef(d.ref) ? `${String(d.evidence || '').replace(/[.\s]+$/, '')} (read ${d.check}).`
430
430
  : `The outcome check on ${d.check} said it did not work: ${String(d.evidence || '').replace(/[.\s]+$/, '')}.`).slice(0, 440);
431
- const stop = (why) => { const r = O.setLife(p.w.root, ini, 'cancelled', why, g.actor); if (r.ok) add({ op: 'life', from: r.from || 'active', to: 'cancelled' }); };
431
+ const stop = (why) => { const r = O.setLife(p.w.root, ini, 'cancelled', why, g.actor); if (r.ok) { add({ op: 'life', from: r.from || 'active', to: 'cancelled' }); require('./lessons-draft.js').onClose(ctx, { root: p.w.root, id: ini }); } }; // lessons-on-close (A542)
432
432
  if (d.next === 'kill') stop(reason);
433
433
  else if (d.next === 'iterate') {
434
434
  const t = RB.taskAdd(ctx, { ws: p.w.id, board: p.board.id, initiative: ini, title: 'Change what the outcome check showed, then check again', notes: [reason, source ? 'From ' + source : ''].filter(Boolean).join('\n').slice(0, 1900) }, g);
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ /* routes-screen-layouts.js — three layouts for a new screen, pick one (initiative three-layouts, job #1904, idea A317). lib/three-layouts.js
3
+ * is the store and the rules; this is the HTTP the Work popup's Layouts block reads and writes (pm/three-layouts.js).
4
+ *
5
+ * GET /api/screen-layouts?ws&ini → { ok, none: true } the initiative adds no screen (zero is silence), or has no record
6
+ * → { ok, ini, title, layouts: [A, B, C], rec: { key, letter, name, why }, picked, kept, taste }
7
+ * POST /api/screen-layouts/pick { ws, ini, key } → { ok, picked, kept } key: A|B|C or list|summary|action. A page press only.
8
+ * POST /api/screen-layouts/undo { ws, ini } → { ok } the pick taken back. A page press only.
9
+ * STATE: the product's own state folder (stateDirFor), layouts.jsonl, append-only. GET writes nothing. Nothing is sent; no model is called.
10
+ * (`/api/layouts` is the workspace's pane layouts in server.js, hence the longer name.) */
11
+ const T = require('./three-layouts.js');
12
+
13
+ function wsOf(ctx, id) {
14
+ const w = ctx.getWs ? ctx.getWs(id || '') : null;
15
+ return w && (!id || w.id === id) && w.root ? w : null;
16
+ }
17
+ const dirOf = (ctx, w, create) => (ctx.stateDirFor ? ctx.stateDirFor(w) : null) || T.stateDirOf(w.root, create);
18
+
19
+ module.exports = {
20
+ prefixes: ['/api/screen-layouts'],
21
+ handle: async (req, res, url, ctx) => {
22
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
23
+ const p = url.pathname;
24
+ if (p === '/api/screen-layouts' && req.method === 'GET') {
25
+ const w = wsOf(ctx, url.searchParams.get('ws') || '');
26
+ if (!w) return send(404, { ok: false, error: 'no such workspace' });
27
+ const ini = String(url.searchParams.get('ini') || '');
28
+ return send(200, T.viewOf(w.root, ini, { stateDir: dirOf(ctx, w, false) }));
29
+ }
30
+ if (req.method !== 'POST' || (p !== '/api/screen-layouts/pick' && p !== '/api/screen-layouts/undo')) return false;
31
+ const got = await ctx.readJson(req);
32
+ if (!got.ok) return send(400, { ok: false, error: 'invalid JSON body' });
33
+ const b = got.body || {};
34
+ const g = require('./pm-guard.js').requirePagePress(req, b);
35
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
36
+ const w = wsOf(ctx, typeof b.ws === 'string' ? b.ws : '');
37
+ if (!w) return send(404, { ok: false, error: 'no such workspace' });
38
+ const r = T.recordOf(w.root, String(b.ini || ''));
39
+ if (!r) return send(404, { ok: false, error: 'no initiative ' + String(b.ini || '') + ' here' });
40
+ const dir = dirOf(ctx, w, true);
41
+ if (!dir) return send(503, { ok: false, error: 'this product has no state folder, so the pick cannot be kept' });
42
+ const by = (g.actor && g.actor.by) || 'pm';
43
+ if (p === '/api/screen-layouts/undo') {
44
+ if (!T.pickedOf(T.readLines(dir), r.id)) return send(200, { ok: true, picked: null });
45
+ T.append(dir, T.undoLine({ ini: r.id, by }).line);
46
+ console.info(`${T.TAG} undo ini=${r.id}`);
47
+ return send(200, { ok: true, picked: null });
48
+ }
49
+ const L = T.pickLine({ ini: r.id, key: b.key, title: r.title, by });
50
+ if (L.error) return send(400, { ok: false, error: L.error });
51
+ T.append(dir, L.line);
52
+ console.info(`${T.TAG} pick ini=${r.id} key=${L.line.key}`);
53
+ try { if (ctx.runtimeDir) require('./use-log.js').record(ctx.runtimeDir, [{ kind: 'use', page: 'premium-board', control: 'layoutPick', device: 'desk' }]); } catch { /* a count, never a reason to fail */ }
54
+ return send(200, { ok: true, picked: L.line.key, kept: L.line.kept });
55
+ },
56
+ };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+ /* routes-switches.js — who has which switch over HTTP (idea A263, initiative switch-owners). The store is lib/switch-owners.js (switches.jsonl
3
+ * in the product's records folder, lib/records-dir.js); the verb is `pmos switches`; the block is public/pm/switch-owners.js on Work.
4
+ *
5
+ * GET /api/switches?ws=<id> → { ok, switches: [row], marked }
6
+ * POST /api/switches { ws, act, id } → { ok, row } | 400 act ∈ confirm (the PM's ✓ "I turned it") · cancel (✕ "keep it as it is") · undo
7
+ *
8
+ * WHO WRITES. A page press only: pm-guard requirePagePress checks the page's Origin and launch nonce, and only then is the press the PM's own
9
+ * (by: 'pm'), the one way a switch's recorded state changes. Nothing here sends anything. */
10
+ const guard = require('./pm-guard.js');
11
+ const SW = require('./switch-owners.js');
12
+ const { recordsDirFor } = require('./records-dir.js');
13
+
14
+ const ACTS = ['confirm', 'cancel', 'undo'];
15
+
16
+ async function handle(req, res, url, ctx) {
17
+ if (url.pathname !== '/api/switches') return false;
18
+ const send = (status, body) => { ctx.json(res, body, status); return true; };
19
+ if (req.method === 'GET') {
20
+ const rows = SW.read(recordsDirFor(ctx, url.searchParams.get('ws') || null));
21
+ return send(200, { ok: true, switches: rows, marked: rows.filter((r) => r.marks.length).length });
22
+ }
23
+ if (req.method !== 'POST') return send(405, { ok: false, error: 'GET or POST' });
24
+ const rd = await ctx.readJson(req);
25
+ if (!rd.ok) return send(400, { ok: false, error: 'the body is not JSON' });
26
+ const body = rd.body || {};
27
+ const g = guard.requirePagePress(req, body);
28
+ if (!g.ok) return send(g.status, { ok: false, error: g.error });
29
+ const act = String(body.act || '');
30
+ if (!ACTS.includes(act)) return send(400, { ok: false, error: 'act is confirm, cancel or undo' });
31
+ const r = SW[act](recordsDirFor(ctx, body.ws || null), String(body.id || ''), { by: 'pm' });
32
+ return r.ok ? send(200, { ok: true, row: r.row }) : send(400, { ok: false, error: r.error });
33
+ }
34
+
35
+ module.exports = { prefixes: ['/api/switches'], handle };