create-pmos 0.413.0 → 0.414.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 (54) hide show
  1. package/package.json +13 -13
  2. package/payload/AGENTS.md +2 -2
  3. package/payload/KIT-VERSION +1 -1
  4. package/payload/mods/pmos-cockpit/README.md +1 -1
  5. package/payload/mods/pmos-cockpit/hooks/lib/guard.mjs +11 -5
  6. package/payload/planning/evals/eval-calibration.md +1 -1
  7. package/payload/planning/okrs/health-budgets.md +1 -1
  8. package/payload/scripts/pmos-log.sh +12 -1
  9. package/payload/state/discoveries.md +1 -1
  10. package/workspace/briefing-premium-board-test.js +45 -9
  11. package/workspace/briefing-premium-test.js +3 -2
  12. package/workspace/changelog.json +12 -0
  13. package/workspace/guide/programs.md +13 -0
  14. package/workspace/guide/workflows.md +7 -0
  15. package/workspace/home-other-product-test.js +18 -0
  16. package/workspace/lib/board-premium.js +1 -0
  17. package/workspace/lib/headless.js +10 -1
  18. package/workspace/lib/initiative-chat.js +2 -1
  19. package/workspace/lib/milestone-review.js +120 -0
  20. package/workspace/lib/milestone-suggest.js +176 -0
  21. package/workspace/lib/pmos-verbs.js +6 -0
  22. package/workspace/lib/program-cli.js +56 -0
  23. package/workspace/lib/programs.js +4 -1
  24. package/workspace/lib/routes-boards.js +4 -2
  25. package/workspace/lib/routes-programs.js +73 -7
  26. package/workspace/lib/task-cli.js +120 -0
  27. package/workspace/milestone-suggest-test.js +175 -0
  28. package/workspace/package-lock.json +2 -2
  29. package/workspace/package.json +1 -1
  30. package/workspace/premium-chat-line-test.js +3 -1
  31. package/workspace/public/pm/bd-ini-model.js +81 -0
  32. package/workspace/public/pm/bd-ini-panel.js +123 -58
  33. package/workspace/public/pm/bd-prog-panel.js +54 -14
  34. package/workspace/public/pm/cozy-home.css +5 -0
  35. package/workspace/public/pm/cozy-panel.css +2 -0
  36. package/workspace/public/pm/cozy-viewer.js +2 -0
  37. package/workspace/public/pm/cozy-xv.css +51 -16
  38. package/workspace/public/pm/cozy-xv.js +6 -5
  39. package/workspace/public/pm/home-app.js +13 -11
  40. package/workspace/public/pm/home-ask.js +9 -3
  41. package/workspace/public/pm/home-chat.js +10 -1
  42. package/workspace/public/pm/home-list.js +12 -7
  43. package/workspace/public/pm/home-today.js +5 -8
  44. package/workspace/public/pm/ms-suggest.css +50 -0
  45. package/workspace/public/pm/ms-suggest.js +98 -0
  46. package/workspace/public/pm/premium-board.js +1 -1
  47. package/workspace/public/pm/premium-initiative-head.js +13 -4
  48. package/workspace/public/pm/program-charter.js +47 -7
  49. package/workspace/public/pm/program-model.js +4 -1
  50. package/workspace/public/pm/wf-page.js +3 -0
  51. package/workspace/server.js +23 -1
  52. package/workspace/skills/milestone-review.skill +53 -0
  53. package/workspace/test-lists/bd-ini-panel.json +5 -0
  54. package/workspace/test-lists/milestone-suggest.json +6 -0
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+ /* lib/milestone-review.js — Claude reviews a program's milestones and files suggestions the PM keeps, changes or drops (feedback batch 4 item 6;
3
+ * canvas XmsgB, the sticky xmsgRules).
4
+ *
5
+ * off(env) → true when PMOS_MS_REVIEW=off (or 0, false, no)
6
+ * reviewPrompt(skill, o) → the prompt of one run. o: { program, run, why, now, open, declined, roots, rows }
7
+ * create(deps) → { tick(opts), active() }
8
+ *
9
+ * WHEN (lib/milestone-suggest.js dueOf): Check now at once; else inside the working hours, for a program never reviewed, after an initiative
10
+ * joins or leaves, after the page saw a ◆ date move (a Jira slip moves one too), when a milestone's date comes, and every Monday from 09:00.
11
+ * At most ONE run at a time for the machine, and one start per tick. A run that ends badly waits 6 hours before the next automatic one.
12
+ *
13
+ * WHAT THE RUN MAY DO. It is headless (lib/headless.js kind ms-review, origin `ms-review:<program>:<run>`): it reads and searches the repositories
14
+ * of the program's initiatives (their records, plan items and meeting notes) and, where the PM's own Claude Code settings allow it, reads Jira and
15
+ * the meeting notes through connectors. Its only write is `pmos program suggest`, pinned by the server to this program and run
16
+ * (PMOS_MS_REVIEW_FILE, PMOS_MS_REVIEW_RUN, PMOS_MS_REVIEW_PROGRAM). It never writes the charter: only the PM's press does (POST
17
+ * /api/programs/suggestion). Nothing is sent.
18
+ *
19
+ * deps: { programs() → [program with home], reviewOf(p) → { file, state } | null, rootOf(ws) → root | null, open(now) → bool (working hours),
20
+ * headlessOff() → bool, env, promptFor(skillId) → skill body | null, rowsOf(p) → [{ id, title, stage, deliver }] (what the server's last
21
+ * board read says, or []), spawn(spec) → session row (through the capacity governor), spawnNow(spec) (Check now), stop(session),
22
+ * append(file, line), warn(what, err) }
23
+ */
24
+ const crypto = require('crypto');
25
+ const MS = require('./milestone-suggest.js');
26
+
27
+ const flagOff = (v) => /^(off|0|false|no)$/i.test(String(v || '').trim());
28
+ const off = (env) => flagOff((env || process.env).PMOS_MS_REVIEW);
29
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
30
+ const WHY = {
31
+ asked: 'The PM pressed Check now.',
32
+ new: 'The program has never been reviewed. If it has no milestones, suggest its first ones.',
33
+ members: 'An initiative joined or left the program.',
34
+ dates: 'A ◆ date of one of its initiatives moved (a plan or Jira change).',
35
+ date: 'A milestone\'s date has come.',
36
+ weekly: 'The weekly review (Monday).',
37
+ };
38
+
39
+ function reviewPrompt(skill, o) {
40
+ const p = o.program;
41
+ const ms = (p.milestones || []).map((m) => `- ${m.id} · ${one(m.name, 80)} · ${m.date || 'no date'} · ${(m.waits || []).length ? 'waits on ' + m.waits.join(', ') : 'a check the PM ticks'}${m.done ? ' · done' : ''}${m.risk ? ' · at risk: ' + one(m.risk, 120) : ''}`);
42
+ const mem = (p.members || []).map((m) => { const r = (o.rows || []).find((x) => x.id === m.initiative); return `- ${m.initiative}${r ? ` · ${one(r.title, 80)} · stage ${one(r.stage, 30) || 'unknown'}${r.deliver ? ' · ◆ ' + r.deliver : ''}` : ''} · repository ${(o.roots || {})[m.ws] || 'not on this machine'}`; });
43
+ const open = (o.open || []).map((i) => `- ${JSON.stringify({ op: i.op, milestone: i.milestone, name: i.name, date: i.date, waits: i.waits, why: i.why, src: i.src })}`);
44
+ const dec = (o.declined || []).map((x) => `- ${x}`);
45
+ const list = (a, none) => (a.length ? a.join('\n') : '- ' + none);
46
+ return `${skill}\n\nThis run:\n- Run: ${o.run}\n- Today: ${new Date(o.now).toISOString().slice(0, 10)}\n- Why it runs: ${WHY[o.why] || WHY.weekly}\n`
47
+ + `- Program: ${p.id} · ${one(p.title, 120)}${p.goal ? ' · goal: ' + one(p.goal, 160) : ''}\n- Span: ${p.start || 'no start'} to ${p.target || 'no target'}${p.jira ? '\n- Jira: ' + one(p.jira, 40) : ''}\n`
48
+ + `- Milestones (${(p.milestones || []).length} of 12):\n${list(ms, 'none yet')}\n- Initiatives in the program:\n${list(mem, 'none')}\n`
49
+ + `- Open suggestions from the last review (file again each one that still holds; one you do not file again is withdrawn):\n${list(open, 'none')}\n`
50
+ + `- Declined by the PM (do not suggest these again from the same source):\n${list(dec, 'none')}\n\n`
51
+ + 'File each suggestion with `pmos program suggest --json -`. File at most 8. Write no charter. Send nothing.';
52
+ }
53
+
54
+ function create(deps) {
55
+ const active = new Map(); // run → { p, file, session }
56
+ const warn = deps.warn || (() => {});
57
+
58
+ function ended(run, r, now = Date.now()) {
59
+ const a = active.get(run); if (!a) return;
60
+ active.delete(run);
61
+ const res = (r && r.result) || {};
62
+ const ok = !!(r && !r.timedOut && !r.stopped && r.code === 0 && res.ok && !res.isError);
63
+ try { deps.append(a.file, { kind: 'review-end', program: a.p.id, run, ok, ...(ok ? {} : { error: one((r && r.note) || res.text || 'the run failed', 200) }) }, new Date(now)); } catch (e) { warn('milestone review end', e); }
64
+ }
65
+
66
+ function start(p, R, why, now) {
67
+ const run = 'r' + now.toString(36) + crypto.randomBytes(3).toString('hex');
68
+ const begin = () => { deps.append(R.file, { kind: 'review-start', program: p.id, run, why, members: MS.membersFp(p) }, new Date(now)); active.set(run, { p, file: R.file, session: null }); };
69
+ const skill = deps.promptFor('milestone-review');
70
+ if (!skill) { begin(); ended(run, { code: 1, note: 'the milestone-review skill is not installed', result: {} }, now); return; }
71
+ const st = R.state;
72
+ const open = st ? MS.openOf(st, p) : [];
73
+ const declined = st ? [...st.items.values()].filter((i) => st.answers.get(i.key) === 'decline').map((i) => `${i.op} ${i.milestone || i.name}${i.date ? ' to ' + i.date : ''} (source: ${i.src.kind}, ${i.src.label})`) : [];
74
+ const roots = {};
75
+ for (const m of p.members || []) if (!(m.ws in roots)) roots[m.ws] = deps.rootOf(m.ws) || '';
76
+ let rows = [];
77
+ try { rows = (deps.rowsOf && deps.rowsOf(p)) || []; } catch { rows = []; }
78
+ const prompt = reviewPrompt(skill, { program: p, run, why, now, open, declined, roots, rows });
79
+ const home = deps.rootOf(p.home);
80
+ const addDirs = [...new Set(Object.values(roots).filter((r) => r && r !== home))];
81
+ // Check now is the PM's press: it starts at once (deps.spawnNow); the rest go through the capacity governor, which may hold a start
82
+ const go = why === 'asked' && deps.spawnNow ? deps.spawnNow : deps.spawn;
83
+ let session = null;
84
+ try {
85
+ session = go({ name: 'Milestone review · ' + one(p.title, 60), ws: p.home, origin: `ms-review:${p.id}:${run}`, initialInput: prompt + '\r', addDirs,
86
+ env: { PMOS_MS_REVIEW_FILE: R.file, PMOS_MS_REVIEW_RUN: run, PMOS_MS_REVIEW_PROGRAM: p.id }, onDone: (r) => ended(run, r) });
87
+ } catch (e) { warn('milestone review', e); }
88
+ if (session && session.held) return; // held by the capacity governor: nothing is written, the next tick tries again
89
+ begin();
90
+ if (!session || session.state === 'exited' || session.headless !== 'ms-review') {
91
+ // a start that did not become a headless run (no `claude`, headless off, a refused model) is a failed run, never a pane
92
+ if (session && session.headless !== 'ms-review' && session.state !== 'exited' && deps.stop) { try { deps.stop(session); } catch { /* best effort */ } }
93
+ ended(run, { code: 1, note: (session && session.note) || 'the review could not start as a background run', result: {} }, now);
94
+ return;
95
+ }
96
+ const a = active.get(run); if (a) a.session = session.id;
97
+ }
98
+
99
+ function tick({ now = Date.now(), env } = {}) {
100
+ if (off(env || deps.env) || (deps.headlessOff && deps.headlessOff())) return { off: true };
101
+ if (active.size) return { running: active.size };
102
+ let open = true;
103
+ try { open = deps.open ? !!deps.open(now) : true; } catch { open = true; }
104
+ for (const p of deps.programs() || []) {
105
+ if (!p || !p.home || p.archived) continue;
106
+ let R = null;
107
+ try { R = deps.reviewOf(p); } catch (e) { warn('milestone review read', e); }
108
+ if (!R) continue;
109
+ const due = MS.dueOf(R.state, p, now, { open });
110
+ if (!due) continue;
111
+ try { start(p, R, due.why, now); } catch (e) { warn('milestone review start', e); }
112
+ return { started: p.id, why: due.why };
113
+ }
114
+ return { started: null };
115
+ }
116
+
117
+ return { tick, active: () => [...active.keys()] };
118
+ }
119
+
120
+ module.exports = { off, reviewPrompt, create, WHY };
@@ -0,0 +1,176 @@
1
+ 'use strict';
2
+ /* lib/milestone-suggest.js — Claude's milestone suggestions for a program, and the reviews that make them (feedback batch 4 item 6; canvas XmsgB,
3
+ * rules on the sticky xmsgRules).
4
+ *
5
+ * validItem(x) → { item } | { error } what one filed suggestion may say
6
+ * sigOf(item) · keyOf(program, item) the source signature (a decline remembers it) and the suggestion's key
7
+ * fold(lines) → { [program]: state } PURE. state: { items: Map key → item, answers: Map key → answer, declined: Set sig,
8
+ * runs: [run], asks: [iso], facts: fp | '' }
9
+ * openOf(state, program, now) → [item] what waits on the PM now: the latest finished review's items, less the answered,
10
+ * the declined and the ones the charter already says
11
+ * viewOf(state, program, now) → { checked, running, open } for GET /api/programs (each program's `review`)
12
+ * applyTo(program, item) → the charter body POST /api/programs/save takes, with the change made (✓ Keep)
13
+ * dueOf(state, program, now, o) → { why } | null should a review start now? o: { open (working hours), membersFp }
14
+ * membersFp(program) the member set as one string: a join or a leave changes it
15
+ * fileOf(stateDir) <state>/milestone-reviews.jsonl, in the charter's workspace
16
+ *
17
+ * A LINE is one of:
18
+ * { kind: 'review-start', program, run, why, members } a review began (why: new | members | asked | dates | date | weekly)
19
+ * { kind: 'review-end', program, run, ok, error? }
20
+ * { kind: 'suggest', program, run, key, item } one suggestion the review run filed (`pmos program suggest`)
21
+ * { kind: 'answer', program, key, answer } the PM's press: keep (written at once) · edit (saved from the charter) · decline
22
+ * { kind: 'review-ask', program, why } Check now (why 'asked'), or the page saw a ◆ date move (why 'dates')
23
+ * { kind: 'facts', program, fp } the ◆ dates the page last saw, so a move asks for a review once
24
+ *
25
+ * THE RULES (xmsgRules). Claude proposes add, move, rename, drop or at risk, each with why and its source. Nothing is written without the PM:
26
+ * keep writes the charter in one press, the pencil opens the charter with the change filled in, decline drops it and Claude does not ask again
27
+ * unless that source changes (the signature holds the source's label, so "Jira, Oct 30" is a new source after "Jira, Oct 22"). A review files
28
+ * the whole list it stands by: a suggestion an older review filed and the latest one did not is no longer open. No change, nothing shows. */
29
+ const path = require('path');
30
+ const crypto = require('crypto');
31
+
32
+ const OPS = ['add', 'move', 'rename', 'drop', 'risk'];
33
+ const SRC = ['deliver', 'jira', 'meeting', 'task', 'target', 'member', 'charter'];
34
+ const ID_RE = /^[a-z0-9][a-z0-9-]{0,60}$/;
35
+ const INI_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/;
36
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
37
+ const MAX_MS = 12;
38
+ const RUN_MS = 30 * 60 * 1000; // a start with no end after this is over (the server stopped mid-run)
39
+ const GAP_MS = 30 * 60 * 1000; // two automatic reviews of one program are this far apart at least
40
+ const RETRY_MS = 6 * 60 * 60 * 1000; // after a failed run, the next automatic one waits this long
41
+ const SLOT_H = 9; // the weekly review: Monday from 09:00
42
+ const str = (v, n) => String(v == null ? '' : v).replace(/[\u0000-\u001f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, n);
43
+ const slug = (t) => String(t || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 50);
44
+ const fileOf = (stateDir) => path.join(stateDir, 'milestone-reviews.jsonl');
45
+
46
+ /** One filed suggestion: { op, milestone?, name?, date?, waits?, why, src: { kind, label } }. Each op says what it needs. */
47
+ function validItem(x) {
48
+ if (!x || typeof x !== 'object' || Array.isArray(x)) return { error: 'a suggestion is a JSON object' };
49
+ const op = String(x.op || '');
50
+ if (!OPS.includes(op)) return { error: 'op is one of ' + OPS.join(', ') };
51
+ const why = str(x.why, 240);
52
+ if (!why) return { error: 'why says, in one line, what you read that makes the change' };
53
+ const s = x.src && typeof x.src === 'object' ? x.src : {};
54
+ if (!SRC.includes(String(s.kind || ''))) return { error: 'src.kind is one of ' + SRC.join(', ') };
55
+ const label = str(s.label, 80);
56
+ if (!label) return { error: 'src.label names the source, for example "Steering, Oct 22" or "Jira DSC-41"' };
57
+ const item = { op, why, src: { kind: String(s.kind), label } };
58
+ if (op !== 'add') {
59
+ if (!ID_RE.test(String(x.milestone || ''))) return { error: op + ' names the milestone by its id (milestone)' };
60
+ item.milestone = String(x.milestone);
61
+ }
62
+ if (op === 'add' || op === 'rename') {
63
+ const name = str(x.name, 80);
64
+ if (!name) return { error: op + ' needs the milestone name (name)' };
65
+ item.name = name;
66
+ }
67
+ if (op === 'add' || op === 'move') {
68
+ if (!DAY_RE.test(String(x.date || ''))) return { error: op + ' needs the date as YYYY-MM-DD (date)' };
69
+ item.date = String(x.date);
70
+ }
71
+ if (op === 'add') {
72
+ const w = Array.isArray(x.waits) ? x.waits.map(String) : [];
73
+ const bad = w.find((i) => !INI_RE.test(i));
74
+ if (bad) return { error: 'waits holds initiative ids; ' + str(bad, 40) + ' is not one' };
75
+ item.waits = [...new Set(w)].slice(0, 20);
76
+ }
77
+ return { item };
78
+ }
79
+ /** What a decline remembers: the change and its source. A new source label is a new signature, so Claude may ask again. */
80
+ const sigOf = (i) => [i.op, i.milestone || slug(i.name), i.date || '', i.op === 'rename' ? slug(i.name) : '', i.src.kind, i.src.label.toLowerCase()].join('|');
81
+ const keyOf = (program, i) => 's' + crypto.createHash('sha1').update(program + '|' + sigOf(i)).digest('hex').slice(0, 12);
82
+
83
+ const blank = () => ({ items: new Map(), answers: new Map(), declined: new Set(), runs: [], asks: [], facts: '', factsAt: '' });
84
+ function fold(lines) {
85
+ const out = {};
86
+ const get = (id) => out[id] || (out[id] = blank());
87
+ for (const l of lines || []) {
88
+ if (!l || typeof l !== 'object' || !ID_RE.test(String(l.program || ''))) continue;
89
+ const s = get(String(l.program));
90
+ if (l.kind === 'review-start' && l.run) s.runs.push({ run: String(l.run), start: l.at || '', why: l.why || '', members: l.members || '', end: '', ok: null, error: '' });
91
+ else if (l.kind === 'review-end' && l.run) { const r = s.runs.find((x) => x.run === String(l.run)); if (r && !r.end) Object.assign(r, { end: l.at || '', ok: !!l.ok, error: l.error || '' }); }
92
+ else if (l.kind === 'suggest' && l.key && l.item) { const v = validItem(l.item); if (v.item) s.items.set(String(l.key), { ...v.item, key: String(l.key), run: String(l.run || ''), at: l.at || '' }); }
93
+ else if (l.kind === 'answer' && l.key && ['keep', 'edit', 'decline'].includes(l.answer)) {
94
+ s.answers.set(String(l.key), l.answer);
95
+ const it = s.items.get(String(l.key));
96
+ if (it && l.answer === 'decline') s.declined.add(sigOf(it));
97
+ } else if (l.kind === 'review-ask') s.asks.push({ at: l.at || '', why: l.why || 'asked' });
98
+ else if (l.kind === 'facts' && typeof l.fp === 'string') { s.facts = l.fp; s.factsAt = l.at || ''; }
99
+ }
100
+ return out;
101
+ }
102
+ const ms = (iso) => { const t = Date.parse(iso || ''); return Number.isFinite(t) ? t : 0; };
103
+ const runningOf = (s, now) => (s ? s.runs.filter((r) => !r.end && now - ms(r.start) < RUN_MS) : []);
104
+ const lastDone = (s) => (s ? s.runs.filter((r) => r.end && r.ok).sort((a, b) => ms(a.end) - ms(b.end)).pop() || null : null);
105
+
106
+ /** True when the charter already says what the item would change, or the item no longer has anything to change. */
107
+ function stale(i, p) {
108
+ const M = (p && p.milestones) || [];
109
+ const m = i.milestone ? M.find((x) => x.id === i.milestone) : null;
110
+ if (i.op === 'add') return M.length >= MAX_MS || M.some((x) => slug(x.name) === slug(i.name));
111
+ if (!m) return true;
112
+ if (i.op === 'move') return m.date === i.date;
113
+ if (i.op === 'rename') return m.name === i.name;
114
+ if (i.op === 'risk') return !!m.risk || !!m.done;
115
+ return false;
116
+ }
117
+ function openOf(s, p) {
118
+ const last = lastDone(s);
119
+ if (!last) return [];
120
+ const out = [];
121
+ for (const it of s.items.values()) {
122
+ if (it.run !== last.run || s.answers.has(it.key) || s.declined.has(sigOf(it)) || stale(it, p)) continue;
123
+ out.push(it);
124
+ }
125
+ // the program's own order: by the date the change is about, then what it is
126
+ const dayOf = (i) => i.date || (((p && p.milestones) || []).find((m) => m.id === i.milestone) || {}).date || '9999';
127
+ return out.sort((a, b) => dayOf(a).localeCompare(dayOf(b)) || OPS.indexOf(a.op) - OPS.indexOf(b.op));
128
+ }
129
+ function viewOf(s, p, now = Date.now()) {
130
+ const last = lastDone(s);
131
+ return { checked: last ? last.end : '', running: runningOf(s, now).length > 0, open: s ? openOf(s, p) : [], facts: (s && s.facts) || '' };
132
+ }
133
+
134
+ /** The charter with the item's change made, as validProgram takes it. The milestone keeps its id; a new one gets one from its name. */
135
+ function applyTo(p, i) {
136
+ let L = ((p && p.milestones) || []).map((m) => ({ ...m, waits: (m.waits || []).slice() }));
137
+ if (i.op === 'add') L.push({ name: i.name, date: i.date, waits: (i.waits || []).slice() });
138
+ else {
139
+ const m = L.find((x) => x.id === i.milestone);
140
+ if (!m) return { error: 'that milestone is no longer in the charter' };
141
+ if (i.op === 'move') m.date = i.date;
142
+ else if (i.op === 'rename') m.name = i.name;
143
+ else if (i.op === 'risk') m.risk = i.why;
144
+ else if (i.op === 'drop') L = L.filter((x) => x !== m);
145
+ }
146
+ if (L.length > MAX_MS) return { error: 'the charter holds 12 milestones at most' };
147
+ L.sort((a, b) => String(a.date || '9999').localeCompare(String(b.date || '9999')));
148
+ return { program: { id: p.id, title: p.title, owner: p.owner, goal: p.goal, why: p.why, start: p.start, target: p.target, jira: p.jira, milestones: L } };
149
+ }
150
+
151
+ const membersFp = (p) => ((p && p.members) || []).map((m) => (m.ws || '') + ':' + m.initiative).sort().join(',');
152
+ /** The Monday 00:00 (local) of the week that holds `t`. */
153
+ function weekStart(t) { const d = new Date(t); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() - ((d.getDay() + 6) % 7)); return d.getTime(); }
154
+
155
+ /** Should a review of this program start now? Check now goes at once; the rest wait for the working hours, keep GAP_MS apart, and RETRY_MS
156
+ * after a failed run. The reasons, in order: asked · new (never reviewed) · members (a join or a leave) · dates (the page saw a ◆ date move) ·
157
+ * date (a milestone's date came) · weekly (Monday from 09:00, once a week). */
158
+ function dueOf(s, p, now, o = {}) {
159
+ if (runningOf(s, now).length) return null;
160
+ const runs = (s && s.runs) || [];
161
+ const last = runs.slice().sort((a, b) => ms(a.start) - ms(b.start)).pop() || null;
162
+ const since = last ? ms(last.start) : 0;
163
+ const asks = ((s && s.asks) || []).filter((a) => ms(a.at) > since);
164
+ if (asks.some((a) => a.why === 'asked')) return { why: 'asked' };
165
+ if (o.open === false) return null;
166
+ if (last && now - since < (last.end && !last.ok ? RETRY_MS : GAP_MS)) return null;
167
+ if (!last) return { why: 'new' };
168
+ if ((last.members || '') !== membersFp(p)) return { why: 'members' };
169
+ if (asks.length) return { why: 'dates' };
170
+ if (((p && p.milestones) || []).some((m) => m.date && DAY_RE.test(m.date) && !m.done && (() => { const d = new Date(m.date + 'T00:00:00').getTime(); return d > since && d <= now; })())) return { why: 'date' };
171
+ const d = new Date(now);
172
+ if (d.getDay() === 1 && d.getHours() >= SLOT_H && since < weekStart(now)) return { why: 'weekly' };
173
+ return null;
174
+ }
175
+
176
+ module.exports = { OPS, SRC, validItem, sigOf, keyOf, fold, openOf, viewOf, applyTo, dueOf, membersFp, fileOf, weekStart, RUN_MS };
@@ -65,6 +65,12 @@ const VERBS = Object.freeze({
65
65
  // Not a pm-os-absorb verb (run: null): workflows-per-initiative (D99) added it through the same table.
66
66
  workflow: Object.freeze({ module: 'workflow-cli.js', run: null, guide: 'workflows.md',
67
67
  help: 'pmos workflow list|show|draft|show-draft|judge|of|move|switch … — the workflows of this repository, the New workflow draft, a reading of an Only-when stage, and an initiative\'s workflow stage (pmos workflow help)' }),
68
+ // Not a pm-os-absorb verb (run: null): feedback batch 4 (Wawan, 2026-10-25) added it through the same table.
69
+ task: Object.freeze({ module: 'task-cli.js', run: null, guide: 'workflows.md',
70
+ help: 'pmos task list|state … — an initiative\'s Board tasks, and setting their state when the PM asks (pmos task help)' }),
71
+ // Not a pm-os-absorb verb (run: null): feedback batch 4 item 6 (Claude suggests program milestones) added it through the same table.
72
+ program: Object.freeze({ module: 'program-cli.js', run: null, guide: 'programs.md',
73
+ help: 'pmos program suggest — Claude\'s milestone suggestions for a program, filed by its review run (pmos program help)' }),
68
74
  // Not a pm-os-absorb verb (run: null): c3-meet-extension added it through the same table.
69
75
  extension: Object.freeze({ module: 'extension-cli.js', run: null, guide: 'console-calendar.md',
70
76
  help: 'pmos extension — the folder of the Chrome extension for Google Meet, and the three steps to load it' }),
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ /* program-cli.js — `pmos program suggest`: the one write of Claude's milestone review run (feedback batch 4 item 6; canvas XmsgB).
3
+ *
4
+ * pmos program suggest --json <file|-> files one suggestion, or a list of them, for the program the review runs on
5
+ *
6
+ * The server pins the program, the run and the file in the run's environment (PMOS_MS_REVIEW_PROGRAM, PMOS_MS_REVIEW_RUN, PMOS_MS_REVIEW_FILE;
7
+ * lib/milestone-review.js); outside such a run the verb refuses. It writes `suggest` lines and nothing else: the charter changes only when the
8
+ * PM keeps a suggestion, on the page. A suggestion the PM declined from the same source answers `declined`, one this run filed already
9
+ * `duplicate`. Exit codes: 0 filed, 1 refused, 2 usage. Nothing is sent. */
10
+ const fs = require('fs');
11
+ const pmItems = require('./pm-items.js');
12
+ const MS = require('./milestone-suggest.js');
13
+
14
+ const COMMANDS = { program: ['suggest'] };
15
+ const USAGE = [
16
+ 'usage: pmos program suggest — Claude\'s milestone suggestions for a program',
17
+ ' pmos program suggest --json <file|->',
18
+ ' File one suggestion (a JSON object) or a list of them, in a milestone review run only. Each one:',
19
+ ' { "op": "add|move|rename|drop|risk", "milestone": "<id, not for add>", "name": "<add, rename>", "date": "YYYY-MM-DD (add, move)",',
20
+ ' "waits": ["<initiative id>", … (add)], "why": "<one line>", "src": { "kind": "deliver|jira|meeting|task|target|member|charter", "label": "Steering, Oct 22" } }',
21
+ ' It answers filed, duplicate or declined for each. The PM keeps, changes or drops it on the page. Nothing is sent.',
22
+ ];
23
+ const MAX_PER_RUN = 8;
24
+
25
+ async function run(argv, { say = (s) => console.log(s), env = process.env, stdin } = {}) {
26
+ const args = argv[0] === 'program' ? argv.slice(1) : argv.slice();
27
+ const verb = args[0];
28
+ if (!verb || verb === 'help' || verb === '--help' || verb === '-h') { for (const l of USAGE) say(l); return verb ? 0 : 1; }
29
+ if (!COMMANDS.program.includes(verb)) { say(`unknown program command "${verb}" — one of ${COMMANDS.program.join(', ')}`); return 2; }
30
+ const i = args.indexOf('--json'), src = i >= 0 ? args[i + 1] : null;
31
+ if (!src) { say('usage: pmos program suggest --json <file|->'); return 2; }
32
+ const file = env.PMOS_MS_REVIEW_FILE, runId = env.PMOS_MS_REVIEW_RUN, program = env.PMOS_MS_REVIEW_PROGRAM;
33
+ if (!file || !runId || !program) { say('✗ pmos program suggest is for Claude\'s milestone review run. The PM changes milestones in the charter'); return 1; }
34
+ let text;
35
+ try { text = src === '-' ? (stdin !== undefined ? String(stdin) : fs.readFileSync(0, 'utf8')) : fs.readFileSync(src, 'utf8'); } catch (e) { say(`✗ could not read ${src}: ${String((e && e.message) || e).slice(0, 120)}`); return 1; }
36
+ let body;
37
+ try { body = JSON.parse(text); } catch { say('✗ the input is not JSON'); return 1; }
38
+ const list = Array.isArray(body) ? body : [body];
39
+ const st = MS.fold(pmItems.readLines(file))[program] || null;
40
+ const mine = st ? [...st.items.values()].filter((x) => x.run === runId) : [];
41
+ let bad = 0;
42
+ for (const x of list) {
43
+ const v = MS.validItem(x);
44
+ if (v.error) { say(`✗ refused: ${v.error}`); bad++; continue; }
45
+ const key = MS.keyOf(program, v.item);
46
+ if (st && st.declined.has(MS.sigOf(v.item))) { say(`declined ${key}: the PM dropped this change from the same source`); continue; }
47
+ if (mine.some((y) => y.key === key)) { say(`duplicate ${key}`); continue; }
48
+ if (mine.length >= MAX_PER_RUN) { say(`✗ refused: a review files ${MAX_PER_RUN} suggestions at most`); bad++; continue; }
49
+ pmItems.appendEvent(file, { kind: 'suggest', program, run: runId, key, item: v.item });
50
+ mine.push({ ...v.item, key, run: runId });
51
+ say(`filed ${key}`);
52
+ }
53
+ return bad ? 1 : 0;
54
+ }
55
+
56
+ module.exports = { run, COMMANDS, USAGE };
@@ -14,7 +14,7 @@
14
14
  * `jira` is an optional key that is only read, never written to Jira.
15
15
  *
16
16
  * A LINE is one of:
17
- * { kind: 'program', id, title, owner?, goal?, start?, target?, jira?, from?, milestones?: [{ id, name, date?, waits: [initiative id], stages?: { [initiative]: ◆ stage key }, done? }] } the last wins
17
+ * { kind: 'program', id, title, owner?, goal?, start?, target?, jira?, from?, milestones?: [{ id, name, date?, waits: [initiative id], stages?: { [initiative]: ◆ stage key }, done?, risk? }] } the last wins
18
18
  * `from`: the initiative a turned program came from ("Turn into a program"), in the charter's workspace
19
19
  * { kind: 'check', program, milestone, done: true|false } the PM marks a program check done (canvas PgMilestones); the last line wins
20
20
  * { kind: 'member', program, initiative } the initiative (of the workspace whose ledger holds the line) joins the program
@@ -60,6 +60,9 @@ function validMilestone(m, taken) {
60
60
  const st = m.stages && typeof m.stages === 'object' && !Array.isArray(m.stages) ? Object.entries(m.stages).filter(([k, v]) => waits.includes(k) && typeof v === 'string' && /^[a-z0-9][a-z0-9-]{0,39}$/.test(v)) : [];
61
61
  if (st.length) out.stages = Object.fromEntries(st);
62
62
  if (!waits.length) out.done = m.done === true; // a program check: the PM marks it done; a milestone with initiatives is done when they are
63
+ // at risk (a kept suggestion of Claude's, canvas XmsgB): why, in one line; the charter clears it
64
+ const risk = str(m.risk, 240);
65
+ if (risk) out.risk = risk;
63
66
  return out;
64
67
  }
65
68
 
@@ -979,7 +979,7 @@ const WRITES = {
979
979
  const state = B.taskState(body.state); // the five task states; an old 'In review' is In progress
980
980
  if (!state) return fail(ctx, res, 400, `state is one of ${B.TASK_STATES.join(', ')}`);
981
981
  if (!p.file) return fail(ctx, res, 409, NO_STATE);
982
- append(p.file, g.actor, { kind: 'task-update', board: p.board.id, task: t.id, state, why: 'status move' });
982
+ append(p.file, g.actor, { kind: 'task-update', board: p.board.id, task: t.id, state, why: typeof body.why === 'string' && body.why.trim() ? body.why.trim().slice(0, 300) : 'status move' });
983
983
  const t2 = B.taskOf(B.fold(readLedger(ctx, p.w)), t.id);
984
984
  ctx.json(res, { ok: true, item: B.rollupItems([B.taskItem(t2)])[0] });
985
985
  },
@@ -1188,6 +1188,8 @@ function writeAs(ctx, route, body, g) {
1188
1188
  function move(ctx, body, g) { return writeAs(ctx, '/api/boards/move', body, g); }
1189
1189
  /** A switch of the initiative's workflow, by the same function POST /api/boards/ini-wf runs. body: { ws, board, id, wf, to?, why? }. */
1190
1190
  function switchWorkflow(ctx, body, g) { return writeAs(ctx, '/api/boards/ini-wf', body, g); }
1191
+ /** A Board task's state, by the same function POST /api/boards/tasks/state runs (`pmos task state`). body: { ws, board, task, state, why? }. */
1192
+ function taskState(ctx, body, g) { return writeAs(ctx, '/api/boards/tasks/state', body, g); }
1191
1193
 
1192
1194
  /** The workflow one initiative runs and where it stands in it, as the Board's row has it (boardRow: wf, wfStage, wfStages, ended), with the
1193
1195
  * board it is on. For `pmos workflow of|move|switch` and the initiative chat's opening (bug 2026-10-25: an agent that could not see the
@@ -1267,4 +1269,4 @@ function meetingBoards(ctx) {
1267
1269
  return { list, detail };
1268
1270
  }
1269
1271
 
1270
- module.exports = { prefixes: ['/api/boards'], handle, move, switchWorkflow, initiativeWorkflow, boardIndex, appendScanAsk, scanDeclineSignal, createAndPlace, ledgerFile, append, frameFor, boardIdOf, meetingBoards, boardsOf, baseRows, boardRow, workflowRowOf, foldOf, portfolio, SELF_REFUSAL, NO_STATE };
1272
+ module.exports = { prefixes: ['/api/boards'], handle, move, switchWorkflow, taskState, initiativeWorkflow, boardIndex, appendScanAsk, scanDeclineSignal, createAndPlace, ledgerFile, append, frameFor, boardIdOf, meetingBoards, boardsOf, baseRows, boardRow, workflowRowOf, foldOf, portfolio, SELF_REFUSAL, NO_STATE };
@@ -11,6 +11,14 @@
11
11
  * POST /api/programs/check { program, milestone, done } the PM marks a program check (a milestone that waits on no initiative) done or
12
12
  * not; the line goes to the workspace the charter is in, whatever `ws` says
13
13
  * POST /api/programs/archive { ws, program }
14
+ * POST /api/programs/suggestion { program, key, answer } the PM's answer to one of Claude's milestone suggestions (canvas XmsgB): keep writes
15
+ * the charter at once, edit marks one the PM saved from the charter, decline drops
16
+ * it for good unless its source changes (lib/milestone-suggest.js)
17
+ * POST /api/programs/review { program } Check now: Claude reviews the milestones at the next tick (lib/milestone-review.js)
18
+ * POST /api/programs/facts { program, fp } the ◆ dates the page reads for the program's initiatives, as one string; a change
19
+ * asks for a review once (a Jira slip moves a ◆ date too). The first one only records
20
+ * Every program in GET /api/programs carries `review`: { checked, running, open: [suggestion], facts } from <state>/milestone-reviews.jsonl of the
21
+ * charter's workspace.
14
22
  * POST /api/programs/order { program, order: [initiative id] } the PM's sequence of the program's initiatives (drag, or Claude's order
15
23
  * from the dates applied); like a check line it goes to the charter's workspace.
16
24
  * The answer holds `was`, the order before, so the page's Undo writes it back
@@ -21,27 +29,45 @@ const path = require('path');
21
29
  const guard = require('./pm-guard.js');
22
30
  const pmItems = require('./pm-items.js');
23
31
  const P = require('./programs.js');
32
+ const MS = require('./milestone-suggest.js');
24
33
 
25
34
  const str = (v, n) => String(v == null ? '' : v).replace(/[\u0000-\u001f]+/g, ' ').trim().slice(0, n);
26
35
  const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
27
36
 
28
- function stateDir(ctx, w) {
37
+ /** The workspace's state folder. A read passes create false: the 1-minute milestone-review tick reads every workspace through all(), and
38
+ * making pmos/state in a repository that has no program wrote into it (day-run E14). */
39
+ function stateDir(ctx, w, create = true) {
29
40
  let d = null;
30
- try { d = ctx.stateDirFor ? ctx.stateDirFor(w, { create: true }) : null; } catch { d = null; }
41
+ try { d = ctx.stateDirFor ? ctx.stateDirFor(w, { create }) : null; } catch { d = null; }
31
42
  return d || (w && w.root ? path.join(w.root, 'pmos', 'state') : null);
32
43
  }
33
- const fileOf = (ctx, w) => { const d = stateDir(ctx, w); return d ? path.join(d, 'programs.jsonl') : null; };
44
+ const fileOf = (ctx, w, create = true) => { const d = stateDir(ctx, w, create); return d ? path.join(d, 'programs.jsonl') : null; };
34
45
  const read = (f) => { try { return f ? pmItems.readLines(f).filter(Boolean) : []; } catch { return []; } };
35
46
 
36
- /** Every registered workspace's ledger, merged. */
37
- function all(ctx) {
47
+ /** Every registered workspace's ledger, merged; each program with Claude's milestone review from its charter's workspace. */
48
+ function all(ctx, now = Date.now()) {
38
49
  const list = (ctx.workspaceList ? ctx.workspaceList() : []) || [];
39
- return P.merge(list.map((w) => ({ ws: w.id, lines: read(fileOf(ctx, w)) })));
50
+ const progs = P.merge(list.map((w) => ({ ws: w.id, lines: read(fileOf(ctx, w, false)) })));
51
+ const R = new Map();
52
+ for (const p of progs) {
53
+ if (!R.has(p.home)) { const w = list.find((x) => x.id === p.home), d = w ? stateDir(ctx, w, false) : null; R.set(p.home, MS.fold(read(d ? MS.fileOf(d) : null))); }
54
+ p.review = MS.viewOf(R.get(p.home)[p.id], p, now);
55
+ }
56
+ return progs;
57
+ }
58
+ /** The review ledger of a program's charter workspace: { file, state } (state is that program's fold), or null. */
59
+ function reviewOf(ctx, p) {
60
+ const w = ctx.getWs ? ctx.getWs(p.home || null) : null, d = w ? stateDir(ctx, w, false) : null;
61
+ if (!d) return null;
62
+ const file = MS.fileOf(d);
63
+ return { file, state: MS.fold(read(file))[p.id] || null };
40
64
  }
41
65
 
42
66
  module.exports = {
43
67
  prefixes: ['/api/programs'],
44
68
  all,
69
+ reviewOf,
70
+ fileOf: (ctx, w) => fileOf(ctx, w),
45
71
  handle: async (req, res, url, ctx) => {
46
72
  const p = url.pathname;
47
73
  const bad = (error, code) => { ctx.json(res, { ok: false, error }, code || 400); return true; };
@@ -57,7 +83,7 @@ module.exports = {
57
83
  const g = guard.requirePagePress(req, b);
58
84
  if (!g.ok) return bad(g.error, g.status);
59
85
  // a check line belongs with the charter, so every workspace's reader applies it to the same milestones
60
- const home = (p === '/api/programs/check' || p === '/api/programs/order') && P.ID_RE.test(String(b.program || '')) ? (all(ctx).find((x) => x.id === b.program) || {}).home : null;
86
+ const home = ['/api/programs/check', '/api/programs/order', '/api/programs/suggestion', '/api/programs/review', '/api/programs/facts'].includes(p) && P.ID_RE.test(String(b.program || '')) ? (all(ctx).find((x) => x.id === b.program) || {}).home : null;
61
87
  const w = ctx.getWs ? ctx.getWs(home || b.ws || null) : null;
62
88
  if (!w) return bad('that workspace is not registered', 404);
63
89
  const file = fileOf(ctx, w);
@@ -128,6 +154,46 @@ module.exports = {
128
154
  ctx.json(res, { ok: true, was, program: known(pid) });
129
155
  return true;
130
156
  }
157
+ if (p === '/api/programs/suggestion' || p === '/api/programs/review' || p === '/api/programs/facts') {
158
+ const prog = known(pid), R = reviewOf(ctx, prog);
159
+ if (!R) return bad('the program\'s workspace has no state folder', 409);
160
+ const note = (line) => pmItems.appendEvent(R.file, { ...line, program: pid }, now);
161
+ if (p === '/api/programs/review') {
162
+ note({ kind: 'review-ask', why: 'asked' });
163
+ ctx.json(res, { ok: true, review: MS.viewOf(reviewOf(ctx, prog).state, prog) });
164
+ return true;
165
+ }
166
+ if (p === '/api/programs/facts') {
167
+ const fp = str(b.fp, 4000);
168
+ if (!fp) return bad('fp holds the ◆ dates as one string');
169
+ const was = (R.state && R.state.facts) || '';
170
+ if (fp === was) { ctx.json(res, { ok: true, asked: false }); return true; }
171
+ note({ kind: 'facts', fp });
172
+ // the first reading only records; a later change asks Claude once (the tick starts the review in the working hours)
173
+ if (was) note({ kind: 'review-ask', why: 'dates' });
174
+ ctx.json(res, { ok: true, asked: !!was });
175
+ return true;
176
+ }
177
+ const key = String(b.key || ''), answer = String(b.answer || '');
178
+ if (!['keep', 'edit', 'decline'].includes(answer)) return bad('answer is keep, edit or decline');
179
+ const it = R.state && R.state.items.get(key);
180
+ if (!it) return bad('no such suggestion', 404);
181
+ if (R.state.answers.has(key)) return bad('this suggestion is answered already', 409);
182
+ if (answer === 'keep') {
183
+ // ✓ writes the change at once, through the same charter line a Save writes (the last line wins)
184
+ const a = MS.applyTo(prog, it);
185
+ if (a.error) return bad(a.error, 409);
186
+ const v = P.validProgram(a.program);
187
+ if (v.error) return bad(v.error);
188
+ const cw = ctx.getWs ? ctx.getWs(prog.home || null) : null, cf = cw ? fileOf(ctx, cw) : null;
189
+ if (!cf) return bad('the program\'s workspace has no state folder', 409);
190
+ pmItems.appendEvent(cf, v, now);
191
+ }
192
+ note({ kind: 'answer', key, answer });
193
+ const after = known(pid);
194
+ ctx.json(res, { ok: true, program: after });
195
+ return true;
196
+ }
131
197
  if (p === '/api/programs/archive') {
132
198
  add({ kind: 'archive', program: pid });
133
199
  ctx.json(res, { ok: true });