create-pmos 0.538.0 → 0.539.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 (36) hide show
  1. package/package.json +14 -26
  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 +13 -0
  7. package/workspace/guide/agent-capabilities.md +7 -5
  8. package/workspace/guide/agents-act.md +68 -0
  9. package/workspace/guide/index.md +2 -1
  10. package/workspace/guide/initiative-driver.md +16 -7
  11. package/workspace/lib/agent-inbox.js +2 -2
  12. package/workspace/lib/ai-guard.js +16 -6
  13. package/workspace/lib/auto-keep.js +33 -0
  14. package/workspace/lib/autonomy-cli.js +53 -0
  15. package/workspace/lib/autonomy.js +234 -0
  16. package/workspace/lib/bg-queue.js +2 -1
  17. package/workspace/lib/driver-cli.js +26 -10
  18. package/workspace/lib/driver-decide.js +76 -8
  19. package/workspace/lib/driver.js +15 -4
  20. package/workspace/lib/goal-loop.js +221 -0
  21. package/workspace/lib/job-graph.js +3 -0
  22. package/workspace/lib/loop-cli.js +84 -0
  23. package/workspace/lib/pm-lines-needs.js +3 -0
  24. package/workspace/lib/pmos-verbs.js +6 -1
  25. package/workspace/lib/route-modules.js +1 -0
  26. package/workspace/lib/routes-autonomy.js +95 -0
  27. package/workspace/lib/routes-proposals.js +101 -46
  28. package/workspace/lib/stage-tools.js +11 -1
  29. package/workspace/lib/today.js +2 -8
  30. package/workspace/package-lock.json +2 -2
  31. package/workspace/package.json +1 -1
  32. package/workspace/public/pm/home-around.js +2 -2
  33. package/workspace/replaced-tests.json +17 -0
  34. package/workspace/server.js +26 -14
  35. package/workspace/test-lists/full-autonomy.json +11 -0
  36. package/workspace/test-run.js +3 -0
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+ /* goal-loop.js — a long-running goal: the PM sets it once, and agents work on it round after round until it is done (D106, "Full
3
+ * autonomy now", PM wawan 2026-11-08: "Human is bottleneck").
4
+ *
5
+ * THE LOOP. One goal = done criteria, a budget and a list of forbidden actions, set once. Each round is one background agent run:
6
+ * plan the next step → act → verify against the done criteria → checkpoint (`pmos loop checkpoint`)
7
+ * The loop goes on by itself until one of these ends it:
8
+ * done the agent's checkpoint names every done criterion met (verified by the agent; the page says so)
9
+ * spent the budget is used: its rounds, or its hours since the start
10
+ * interrupted a checkpoint names an interrupt cause from INTERRUPTS (D65(f): only a named cause reaches the PM), or 3 rounds in a row met
11
+ * no new criterion (cause no-progress). The PM answers with `pmos loop resume <id>`, and the loop goes on
12
+ * stopped the PM (or an agent, D98) stopped it
13
+ * A round that ends with no checkpoint counts as a round with no progress. A server restart closes the open round (reason restart) and
14
+ * the next tick starts the next round: the loop resumes by itself from its ledger.
15
+ *
16
+ * WHAT A ROUND MAY DO. Class A and B changes, applied with Undo (lib/autonomy.js). Never a class C act: a message to a person, a Jira move
17
+ * others see, a merge into a product repository, a delete, spend. Those it files as proposals for the PM's daily press, and goes on with
18
+ * the rest. Never an action on the goal's forbidden list. `pmos ai off` and PMOS_AUTONOMY=off stop every loop.
19
+ *
20
+ * THE LEDGER: <runtime folder>/goal-loops.jsonl, append-only, THIS FILE IS ITS ONE WRITER. Lines { v: 1, at, ev, id, ... }:
21
+ * start { id, ws, goal, done: [criterion], forbid: [action], budget: { rounds, hours }, by }
22
+ * round-start { id, n, session }
23
+ * checkpoint { id, n, met: [criterion], open: [criterion], note, interrupt?: cause, by }
24
+ * round-end { id, n, ok, reason? }
25
+ * resume { id, by, note? } the PM answered an interrupt
26
+ * stop { id, by, reason? }
27
+ *
28
+ * LEDGER · INTERRUPTS · DEFAULT_BUDGET · NO_PROGRESS
29
+ * checkStart(input) → { ok, goal } | { ok: false, error }
30
+ * read(dir) · fold(lines, { now }) → Map(id → loop) loop: { id, ws, goal, done, forbid, budget, state, cause?, rounds, met, open, round?, … }
31
+ * start(dir, input, actor, { now }) → { ok, id } · checkpoint(dir, id, cp, actor, { now }) · resume(dir, id, actor) · stop(dir, id, actor)
32
+ * promptOf(loop) → the round's prompt
33
+ * create(deps) → { tick({ now }), active() } deps: { dir() → runtime folder, getWs(id), spawn(spec), killed() → null | reason, warn }
34
+ */
35
+ const fs = require('fs');
36
+ const path = require('path');
37
+ const crypto = require('crypto');
38
+
39
+ const LEDGER = 'goal-loops.jsonl';
40
+ const EVENTS = Object.freeze(['start', 'round-start', 'checkpoint', 'round-end', 'resume', 'stop']);
41
+ // D65(f): everything else reaches the PM only as an interrupt with a named cause
42
+ const INTERRUPTS = Object.freeze({
43
+ 'needs-class-c': 'It needs an act only the PM approves: a message to a person, a Jira move others see, a merge into a product repository, a delete or spend.',
44
+ 'needs-secret': 'It needs a sign-in or a secret only the PM has.',
45
+ unsliceable: 'It cannot cut the goal into steps it can check.',
46
+ 'verify-fail': 'Its check failed and it has no retries left.',
47
+ conflict: 'Its work conflicts with other work.',
48
+ 'outcome-overdue': 'An outcome check it depends on is overdue.',
49
+ 'no-progress': 'Three rounds in a row met no new done criterion.',
50
+ });
51
+ const DEFAULT_BUDGET = Object.freeze({ rounds: 20, hours: 24 });
52
+ const MAX_BUDGET = Object.freeze({ rounds: 200, hours: 24 * 14 });
53
+ const NO_PROGRESS = 3;
54
+ const ID_RE = /^gl-[0-9a-f]{10}$/;
55
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
56
+ const one = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
57
+ const list = (a, n, len) => (Array.isArray(a) ? a.map((x) => one(x, len)).filter(Boolean).slice(0, n) : []);
58
+
59
+ function checkStart(i) {
60
+ const o = isObj(i) ? i : {};
61
+ const goal = one(o.goal, 300);
62
+ if (goal.length < 8) return { ok: false, error: 'goal is one sentence of 8 to 300 characters: what is true when it is done' };
63
+ const done = list(o.done, 12, 200);
64
+ if (!done.length) return { ok: false, error: 'a goal needs at least one done criterion (--done "…"), each one checkable' };
65
+ const forbid = list(o.forbid, 12, 200);
66
+ const b = isObj(o.budget) ? o.budget : {};
67
+ const rounds = b.rounds == null ? DEFAULT_BUDGET.rounds : Number(b.rounds);
68
+ const hours = b.hours == null ? DEFAULT_BUDGET.hours : Number(b.hours);
69
+ if (!Number.isInteger(rounds) || rounds < 1 || rounds > MAX_BUDGET.rounds) return { ok: false, error: `the budget's rounds is a whole number from 1 to ${MAX_BUDGET.rounds}` };
70
+ if (!Number.isFinite(hours) || hours <= 0 || hours > MAX_BUDGET.hours) return { ok: false, error: `the budget's hours is a number above 0 and at most ${MAX_BUDGET.hours}` };
71
+ const ws = o.ws == null ? null : one(o.ws, 80);
72
+ return { ok: true, goal: { goal, done, forbid, budget: { rounds, hours }, ws } };
73
+ }
74
+
75
+ /* ── the ledger ── */
76
+ const file = (dir) => (dir ? path.join(dir, LEDGER) : null);
77
+ function read(dir) {
78
+ let text = '';
79
+ try { text = fs.readFileSync(file(dir), 'utf8'); } catch { return []; }
80
+ const out = [];
81
+ for (const raw of text.split('\n')) {
82
+ if (!raw.trim()) continue;
83
+ try { const l = JSON.parse(raw); if (isObj(l) && EVENTS.includes(l.ev) && ID_RE.test(String(l.id))) out.push(l); } catch { /* a torn line is skipped */ }
84
+ }
85
+ return out;
86
+ }
87
+ function append(dir, line, { now } = {}) {
88
+ if (!dir) throw new Error('goal-loop: no runtime folder');
89
+ const out = { v: 1, at: new Date(now == null ? Date.now() : now).toISOString(), ...line };
90
+ fs.mkdirSync(dir, { recursive: true });
91
+ fs.appendFileSync(file(dir), JSON.stringify(out) + '\n');
92
+ return out;
93
+ }
94
+
95
+ function fold(lines, { now } = {}) {
96
+ const t = now == null ? Date.now() : now;
97
+ const loops = new Map();
98
+ for (const l of lines || []) {
99
+ const g = loops.get(l.id);
100
+ if (l.ev === 'start') {
101
+ if (g) continue;
102
+ loops.set(l.id, { id: l.id, ws: l.ws || null, goal: l.goal, done: l.done || [], forbid: l.forbid || [], budget: l.budget || { ...DEFAULT_BUDGET }, by: l.by || null,
103
+ startedAt: l.at, state: 'running', cause: null, rounds: 0, met: [], open: (l.done || []).slice(), round: null, note: '', history: [], noNew: 0, endedAt: null });
104
+ continue;
105
+ }
106
+ if (!g || ['done', 'stopped'].includes(g.state)) continue;
107
+ if (l.ev === 'round-start') { if (!g.round) { g.round = { n: l.n, session: l.session || null, at: l.at, checkpoint: false }; g.rounds = Math.max(g.rounds, l.n || 0); } }
108
+ else if (l.ev === 'checkpoint') {
109
+ const met = (l.met || []).filter((x) => g.done.includes(x));
110
+ const gained = met.filter((x) => !g.met.includes(x)).length;
111
+ g.met = [...new Set([...g.met, ...met])];
112
+ g.open = g.done.filter((x) => !g.met.includes(x));
113
+ g.note = l.note || '';
114
+ g.history.push({ n: l.n || g.rounds, at: l.at, met: g.met.length, note: g.note });
115
+ if (g.round) g.round.checkpoint = true;
116
+ g.noNew = gained ? 0 : g.noNew + 1;
117
+ if (!g.open.length) { g.state = 'done'; g.endedAt = l.at; }
118
+ else if (l.interrupt && INTERRUPTS[l.interrupt]) { g.state = 'interrupted'; g.cause = l.interrupt; }
119
+ else if (g.noNew >= NO_PROGRESS) { g.state = 'interrupted'; g.cause = 'no-progress'; }
120
+ } else if (l.ev === 'round-end') {
121
+ if (g.round && !g.round.checkpoint && l.reason !== 'restart') { g.noNew++; if (g.state === 'running' && g.noNew >= NO_PROGRESS) { g.state = 'interrupted'; g.cause = 'no-progress'; } }
122
+ g.round = null;
123
+ } else if (l.ev === 'resume') { if (g.state === 'interrupted') { g.state = 'running'; g.cause = null; g.noNew = 0; g.resumeNote = l.note || ''; } }
124
+ else if (l.ev === 'stop') { g.state = 'stopped'; g.cause = l.reason || null; g.endedAt = l.at; g.round = null; }
125
+ }
126
+ for (const g of loops.values()) {
127
+ if (g.state !== 'running') continue;
128
+ const hoursUsed = (t - Date.parse(g.startedAt)) / 3600000;
129
+ if (g.rounds >= g.budget.rounds && !g.round) { g.state = 'spent'; g.cause = `it used its ${g.budget.rounds} rounds`; }
130
+ else if (hoursUsed >= g.budget.hours && !g.round) { g.state = 'spent'; g.cause = `it used its ${g.budget.hours} hours`; }
131
+ }
132
+ return loops;
133
+ }
134
+
135
+ const newId = () => 'gl-' + crypto.randomBytes(5).toString('hex');
136
+ function start(dir, input, actor, { now } = {}) {
137
+ const c = checkStart(input);
138
+ if (!c.ok) return c;
139
+ const id = newId();
140
+ append(dir, { ev: 'start', id, ...c.goal, by: (actor && actor.by) || null }, { now });
141
+ return { ok: true, id };
142
+ }
143
+ function loopOf(dir, id, now) { return fold(read(dir), { now }).get(id) || null; }
144
+ function checkpoint(dir, id, cp, actor, { now } = {}) {
145
+ const g = loopOf(dir, id, now);
146
+ if (!g) return { ok: false, error: `no goal loop ${one(id, 40)}` };
147
+ if (g.state !== 'running') return { ok: false, error: `the goal loop is ${g.state}` };
148
+ const o = isObj(cp) ? cp : {};
149
+ if (o.interrupt != null && !INTERRUPTS[o.interrupt]) return { ok: false, error: `interrupt is one of ${Object.keys(INTERRUPTS).filter((k) => k !== 'no-progress').join(', ')}` };
150
+ const met = list(o.met, 12, 200);
151
+ const unknown = met.filter((x) => !g.done.includes(x));
152
+ if (unknown.length) return { ok: false, error: `met names done criteria word for word; these are not criteria of this goal: ${unknown.join('; ')}` };
153
+ const note = one(o.note, 500);
154
+ if (!note) return { ok: false, error: 'note is one line: what this round did and how you checked it' };
155
+ append(dir, { ev: 'checkpoint', id, n: g.round ? g.round.n : g.rounds, met, open: g.done.filter((x) => !met.includes(x) && !g.met.includes(x)), note, ...(o.interrupt ? { interrupt: o.interrupt } : {}), by: (actor && actor.by) || null }, { now });
156
+ return { ok: true, loop: loopOf(dir, id, now) };
157
+ }
158
+ function resume(dir, id, actor, { now, note } = {}) {
159
+ const g = loopOf(dir, id, now);
160
+ if (!g) return { ok: false, error: `no goal loop ${one(id, 40)}` };
161
+ if (g.state !== 'interrupted') return { ok: false, error: `the goal loop is ${g.state}, not waiting on you` };
162
+ append(dir, { ev: 'resume', id, by: (actor && actor.by) || null, ...(note ? { note: one(note, 500) } : {}) }, { now });
163
+ return { ok: true };
164
+ }
165
+ function stop(dir, id, actor, { now, reason } = {}) {
166
+ const g = loopOf(dir, id, now);
167
+ if (!g) return { ok: false, error: `no goal loop ${one(id, 40)}` };
168
+ if (['done', 'stopped'].includes(g.state)) return { ok: false, error: `the goal loop is ${g.state} already` };
169
+ append(dir, { ev: 'stop', id, by: (actor && actor.by) || null, ...(reason ? { reason: one(reason, 200) } : {}) }, { now });
170
+ return { ok: true };
171
+ }
172
+
173
+ function promptOf(g) {
174
+ const bullets = (a, none) => (a && a.length ? a.map((x) => '- ' + x).join('\n') : '- ' + none);
175
+ return [
176
+ `[PMOS goal loop ${g.id}, round ${g.rounds + 1} of at most ${g.budget.rounds}] The PM set this goal once. Work on it now, on your own.`,
177
+ `Goal: ${g.goal}`,
178
+ 'Done criteria (check each one; copy it word for word when it is met):', bullets(g.done, 'none'),
179
+ 'Met so far:', bullets(g.met, 'none yet'),
180
+ `Last round: ${g.note || 'this is the first round'}${g.resumeNote ? `\nThe PM answered your interrupt: ${g.resumeNote}` : ''}`,
181
+ 'Never do these (the PM forbade them):', bullets(g.forbid, 'nothing extra'),
182
+ '',
183
+ 'This round: 1. plan the next step toward an open criterion. 2. do it. 3. verify it against the criterion (read what you made, run its check).',
184
+ '4. checkpoint, as the LAST thing you do: pmos loop checkpoint ' + g.id + ' --met "<criterion>" (once per criterion met, word for word) --note "<what you did and how you checked it>"',
185
+ 'You may apply class A and B changes (reversible upkeep and judgment); each is logged with Undo. You may NOT send a message to a person, move a Jira ticket others see, merge into a product repository, delete or spend:',
186
+ 'file those as proposals and go on with the rest. Do not stop to ask for approval. If the goal truly cannot go on without the PM, checkpoint with --interrupt <cause>, one of:',
187
+ ...Object.entries(INTERRUPTS).filter(([k]) => k !== 'no-progress').map(([k, v]) => ` ${k}: ${v}`),
188
+ ].join('\n');
189
+ }
190
+
191
+ /** The server's part: each tick, close a round whose run is gone and start the next round of every running loop. */
192
+ function create(deps) {
193
+ const live = new Map(); // loop id → { n, session }
194
+ function tick({ now } = {}) {
195
+ const t = now == null ? Date.now() : now;
196
+ const dir = deps.dir();
197
+ if (!dir) return { started: 0 };
198
+ const why = deps.killed ? deps.killed() : null;
199
+ let started = 0;
200
+ for (const g of fold(read(dir), { now: t }).values()) {
201
+ // a round the ledger holds open but no run of this server holds: the server restarted (or the run was lost). Close it; the next tick goes on.
202
+ if (g.round && !live.has(g.id)) { append(dir, { ev: 'round-end', id: g.id, n: g.round.n, ok: false, reason: 'restart' }, { now: t }); continue; }
203
+ if (g.state !== 'running' || g.round || live.has(g.id) || why) continue;
204
+ const w = g.ws && deps.getWs ? deps.getWs(g.ws) : null;
205
+ const n = g.rounds + 1;
206
+ let s = null;
207
+ try {
208
+ s = deps.spawn({ name: `Goal: ${one(g.goal, 60)}`, ws: w ? w.id : (g.ws || undefined), origin: `goal-loop:${g.id}:${n}`, initialInput: promptOf(g),
209
+ onDone: () => { live.delete(g.id); try { const cur = fold(read(dir)).get(g.id); if (cur && cur.round && cur.round.n === n) append(dir, { ev: 'round-end', id: g.id, n, ok: true }); } catch (e) { if (deps.warn) deps.warn('goal loop round end', e); } } });
210
+ } catch (e) { if (deps.warn) deps.warn('goal loop start', e); s = null; }
211
+ if (!s || s.held || s.state === 'exited') continue; // held by the capacity governor: the next tick tries again
212
+ live.set(g.id, { n, session: s.id || null });
213
+ append(dir, { ev: 'round-start', id: g.id, n, session: s.id || null }, { now: t });
214
+ started++;
215
+ }
216
+ return { started };
217
+ }
218
+ return { tick, active: () => [...live.keys()] };
219
+ }
220
+
221
+ module.exports = { LEDGER, INTERRUPTS, DEFAULT_BUDGET, MAX_BUDGET, NO_PROGRESS, ID_RE, checkStart, read, fold, start, checkpoint, resume, stop, promptOf, create, loopOf };
@@ -43,6 +43,8 @@ const LEDGERS = Object.freeze({
43
43
  '<runtime>/grill-runs.jsonl': { concept: 'grill-spend', owner: 'lib/grill.js', readers: [
44
44
  r('lib/bg-queue.js', 'grill-runs.jsonl', 'the spend limit that holds step 5'),
45
45
  r('lib/routes-grill.js', null, "Settings › Claude's checks: this month's spend")] },
46
+ '<runtime>/goal-loops.jsonl': { concept: 'goal-loops', owner: 'lib/goal-loop.js', readers: [
47
+ r('lib/loop-cli.js', null, '`pmos loop status`: each goal, its round and its state')] },
46
48
  '<state>/driver.jsonl': { concept: 'driver-runs', owner: 'lib/driver.js', readers: [
47
49
  r('lib/routes-driver.js', null, "the initiative's Agent strip"),
48
50
  r('lib/driver-needs.js', null, 'Needs you')] },
@@ -114,6 +116,7 @@ const JOBS = Object.freeze([
114
116
  q('reports', 'lib/routes-report-setups.js', ['<state>/report-setups.jsonl', '<state>/ready-reports.jsonl'], ['<state>/report-setups.jsonl']),
115
117
  q('sync', 'lib/auto-sync.js', [], ['git'], 'git only: no model and no ledger'),
116
118
  q('driver', 'lib/driver.js', ['<state>/driver.jsonl'], ['initiative records', 'jira']),
119
+ q('goal-loops', 'lib/goal-loop.js', ['<runtime>/goal-loops.jsonl'], ['<runtime>/goal-loops.jsonl'], 'D106: each round is a run started through the capacity governor; the run writes its own records'),
117
120
  q('finder', 'lib/report-finder.js', ['<state>/report-setups.jsonl'], ['connectors']),
118
121
  q('coredocs', 'lib/core-docs.js', ['<state>/core-docs.jsonl'], ['initiative records']),
119
122
  q('milestones', 'lib/milestone-review.js', ['<state>/milestone-reviews.jsonl'], ['program charters']),
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+ /* loop-cli.js — `pmos loop`: long-running goals (D106, lib/goal-loop.js). The PM sets a goal once; background agent rounds work on it
3
+ * until it is done, its budget is spent, or a named interrupt needs the PM.
4
+ *
5
+ * pmos loop start --goal "<one sentence>" --done "<criterion>" … [--forbid "<action>" …] [--rounds N] [--hours H] [--ws <id>]
6
+ * pmos loop status [<id>] [--json] every loop, or one, with its state, rounds and the criteria met
7
+ * pmos loop checkpoint <id> --note "<what and how checked>" [--met "<criterion>" …] [--interrupt <cause>] a round's last act
8
+ * pmos loop resume <id> [--note "<your answer>"] answer an interrupt: the loop goes on
9
+ * pmos loop stop <id> [--note "<why>"]
10
+ * every command: [--json]
11
+ *
12
+ * Who wrote a line is the call path (lib/actor.js), never an argument. D98: an agent session may start, resume and stop a loop too.
13
+ * Exit codes: 0 done, 1 refused, 2 usage. Nothing is sent. */
14
+ const GL = require('./goal-loop.js');
15
+ const actorLib = require('./actor.js');
16
+
17
+ const COMMANDS = { loop: ['start', 'status', 'checkpoint', 'resume', 'stop'] };
18
+ const USAGE = [
19
+ 'usage: pmos loop start|status|checkpoint|resume|stop — a long-running goal that agents work on until it is done',
20
+ ' pmos loop start --goal "<one sentence>" --done "<criterion>" … [--forbid "<action>" …] [--rounds N] [--hours H] [--ws <id>]',
21
+ ' pmos loop status [<id>] [--json]',
22
+ ' pmos loop checkpoint <id> --note "<what you did and how you checked it>" [--met "<criterion>" …] [--interrupt <cause>]',
23
+ ' pmos loop resume <id> [--note "<your answer>"]',
24
+ ' pmos loop stop <id> [--note "<why>"]',
25
+ `Interrupt causes: ${Object.keys(GL.INTERRUPTS).filter((k) => k !== 'no-progress').join(', ')}. A loop never sends, merges into a product repository, deletes or spends: it files those as proposals.`,
26
+ ];
27
+ const MULTI = new Set(['done', 'forbid', 'met']);
28
+ const VALUE = new Set(['goal', 'done', 'forbid', 'rounds', 'hours', 'ws', 'note', 'met', 'interrupt', 'root']);
29
+
30
+ function parse(argv) {
31
+ const pos = [], flags = {}, many = { done: [], forbid: [], met: [] };
32
+ for (let i = 0; i < argv.length; i++) {
33
+ const a = argv[i];
34
+ if (!a.startsWith('--')) { pos.push(a); continue; }
35
+ const k = a.slice(2);
36
+ if (k === 'json' || k === 'help') { flags[k] = true; continue; }
37
+ const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) { flags[k] = ''; continue; }
38
+ i++;
39
+ if (MULTI.has(k)) many[k].push(v); else flags[k] = v;
40
+ }
41
+ return { pos, flags, many };
42
+ }
43
+
44
+ function run(argv, { say = (s) => console.log(s), env = process.env, isTTY, now, dir = null } = {}) {
45
+ const args = argv[0] === 'loop' ? argv.slice(1) : argv.slice();
46
+ const verb = args[0];
47
+ if (!verb || ['help', '--help', '-h'].includes(verb)) { for (const l of USAGE) say(l); return verb ? 0 : 1; }
48
+ if (!COMMANDS.loop.includes(verb)) { say(`unknown loop command "${verb}" — one of ${COMMANDS.loop.join(', ')}`); return 2; }
49
+ const { pos, flags, many } = parse(args.slice(1));
50
+ for (const k of Object.keys(flags)) if (k !== 'json' && k !== 'help' && !VALUE.has(k)) { say(`unknown option --${k}`); return 2; }
51
+ const json = !!flags.json;
52
+ const runtime = dir || require('./state-root.js').defaultRoot({ env });
53
+ const actor = actorLib.fromCli({ isTTY: isTTY === undefined ? !!(process.stdin.isTTY && process.stdout.isTTY) : isTTY, env });
54
+ const fail = (e, code = 1) => { say(json ? JSON.stringify({ ok: false, error: e }) : `✗ ${e}`); return code; };
55
+ const ok = (o, line) => { say(json ? JSON.stringify({ ok: true, ...o }) : line); return 0; };
56
+
57
+ if (verb === 'start') {
58
+ const r = GL.start(runtime, { goal: flags.goal, done: many.done, forbid: many.forbid, ws: flags.ws || null,
59
+ budget: { ...(flags.rounds != null ? { rounds: Number(flags.rounds) } : {}), ...(flags.hours != null ? { hours: Number(flags.hours) } : {}) } }, actor, { now });
60
+ if (!r.ok) return fail(r.error, 2);
61
+ return ok({ id: r.id }, `✓ goal loop ${r.id} started. Agents work on it round by round; pmos loop status ${r.id} shows where it is.`);
62
+ }
63
+ if (verb === 'status') {
64
+ const loops = [...GL.fold(GL.read(runtime), { now }).values()].filter((g) => !pos[0] || g.id === pos[0]);
65
+ if (pos[0] && !loops.length) return fail(`no goal loop ${pos[0]}`);
66
+ const out = loops.map((g) => ({ id: g.id, goal: g.goal, state: g.state, cause: g.cause, why: g.cause && GL.INTERRUPTS[g.cause] ? GL.INTERRUPTS[g.cause] : g.cause, rounds: g.rounds, budget: g.budget, met: g.met, open: g.open, note: g.note }));
67
+ if (json) { say(JSON.stringify({ ok: true, loops: out })); return 0; }
68
+ if (!out.length) { say('no goal loops'); return 0; }
69
+ for (const g of out) say(`${g.id} · ${g.state}${g.why ? ` (${g.why})` : ''} · round ${g.rounds} of ${g.budget.rounds} · ${g.met.length} of ${g.met.length + g.open.length} met — ${g.goal}`);
70
+ return 0;
71
+ }
72
+ const id = pos[0];
73
+ if (!id) { say(`usage: pmos loop ${verb} <id>`); return 2; }
74
+ if (verb === 'checkpoint') {
75
+ const r = GL.checkpoint(runtime, id, { met: many.met, note: flags.note, interrupt: flags.interrupt || undefined }, actor, { now });
76
+ if (!r.ok) return fail(r.error);
77
+ return ok({ state: r.loop.state, met: r.loop.met, open: r.loop.open }, `✓ checkpoint: ${r.loop.met.length} of ${r.loop.done.length} met · ${r.loop.state}`);
78
+ }
79
+ if (verb === 'resume') { const r = GL.resume(runtime, id, actor, { now, note: flags.note }); return r.ok ? ok({ id }, `✓ ${id} goes on`) : fail(r.error); }
80
+ const r = GL.stop(runtime, id, actor, { now, reason: flags.note });
81
+ return r.ok ? ok({ id }, `✓ ${id} stopped`) : fail(r.error);
82
+ }
83
+
84
+ module.exports = { run, COMMANDS, USAGE };
@@ -303,6 +303,9 @@ function rowsFresh(w) {
303
303
  const s = scan(w.root);
304
304
  const byLine = new Map();
305
305
  for (const f of s.flags) {
306
+ // D106: a missing `via` alone is no card on Today. D98 lets an agent write these lines and D106 lets it act, so on 2 Nov 140 of 176
307
+ // Today items were this flag. scripts/check-pm-lines.js still reads every flag; Today shows only the ones that say who wrote it is wrong.
308
+ if (f.kind === 'no-via') continue;
306
309
  const key = `${f.rel}:${f.n}`;
307
310
  if (!byLine.has(key)) byLine.set(key, { first: f, causes: [] });
308
311
  byLine.get(key).causes.push(f.cause);
@@ -112,7 +112,12 @@ const VERBS = Object.freeze({
112
112
  outcomes: Object.freeze({ module: 'outcomes-cli.js', run: null, guide: 'outcomes.md',
113
113
  help: 'pmos outcomes list|propose|declare|record — every initiative\'s expected outcome and check date: Claude\'s cited drafts, the PM\'s yes, and the verdict when a check is due (pmos outcomes help)' }),
114
114
  driver: Object.freeze({ module: 'driver-cli.js', run: null, guide: 'initiative-driver.md',
115
- help: 'pmos driver propose|status|keep|return|drop|pause|resume|mode … — the Initiative Driver: drafts for you to keep, send back or drop (pmos driver help)' }),
115
+ help: 'pmos driver propose|status|keep|return|drop|undo|pause|resume|mode … — the Initiative Driver: class A and B changes apply with Undo, the rest wait for you (pmos driver help)' }),
116
+ // D106 (Full autonomy now): what agents do by themselves, and the goals they work on until done
117
+ autonomy: Object.freeze({ module: 'autonomy-cli.js', run: null, guide: 'agents-act.md',
118
+ help: 'pmos autonomy status|restore — what agents applied by themselves (with Undo) and the jobs back to propose (pmos autonomy help)' }),
119
+ loop: Object.freeze({ module: 'loop-cli.js', run: null, guide: 'agents-act.md',
120
+ help: 'pmos loop start|status|checkpoint|resume|stop — a goal agents work on until it is done (pmos loop help)' }),
116
121
  // Not a pm-os-absorb verb (run: null): initiative horizon-scan added it through the same table; horizon-scan-portfolio added section, propose, setting and --boards.
117
122
  scan: Object.freeze({ module: 'scan-cli.js', run: null, guide: 'horizon-scan.md',
118
123
  help: 'pmos scan file|section|propose|list [--sections]|match|suggest [--boards]|status|setting|cadence|watch [--boards] … — the Horizon scan: the portfolio watch list, the findings, the report sections and the proposals the PM approves, changes or dismisses (pmos scan help)' }),
@@ -85,6 +85,7 @@ const MODULES = Object.freeze([
85
85
  'routes-task-plans', // batch 11 item 8: drafts of an initiative's tasks, saved plans, Make live (task-plans.jsonl; page-press POST)
86
86
  'routes-task-links', // batch 11 item 15: links between tasks, Claude's proposals, the quiet moves (task-links.jsonl; page-press POST)
87
87
  'routes-proposals', // batch 12 items 2, 3 and 4: everything Claude proposes on an initiative, under its one ✦ (proposals.jsonl; page-press POST)
88
+ 'routes-autonomy', // D106: what agents did by themselves (the Done group, 14 days), its Undo, and the demotions Home says once (autonomy.jsonl)
88
89
  'routes-your-move', // workspace grill W3: Your move's overdue outcome verdicts (drafted from Jira) and the first key result with no reading (GET)
89
90
  'routes-lab', // idle lab (build U): Intelligence › Lab, the compare view, the specimen files and the Lab's own ✦ (idle-lab.jsonl; page-press POST)
90
91
  'routes-loose', // batch 13 item 3: Claude's clean-up of Home's "Not in an initiative" under the group's ✦ (loose-props/; page-press POST)
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+ /* routes-autonomy.js — what agents did by themselves, and its Undo (D106, "Full autonomy now").
3
+ *
4
+ * GET /api/autonomy?ws → { ok, ws, done: [change], notices: [demotion] }
5
+ * change: { ref, job, title, cls, at, undo_until } the changes agents applied by themselves in the last 14 days that nobody undid,
6
+ * newest first: the Done group. notices: the jobs that fell back to propose and Home has not said so yet (say it once).
7
+ * POST /api/autonomy/undo { ws, ref } → { ok, back, demoted? } Undo of one change: a Driver proposal (p-…) or a ✦ batch (pk-…)
8
+ * POST /api/autonomy/seen { ws, job, product, until } → { ok } Home said the demotion once
9
+ *
10
+ * Every POST passes pm-guard requirePagePress. An Undo is a correction (the north star) and a setback of its job (lib/autonomy.js).
11
+ */
12
+ const path = require('path');
13
+ const guard = require('./pm-guard.js');
14
+ const A = require('./autonomy.js');
15
+ const D = require('./driver.js');
16
+
17
+ const text = (v) => (typeof v === 'string' ? v : '');
18
+ const bad = (status, error) => ({ status, body: { ok: false, error } });
19
+ const DAY = 86400000;
20
+
21
+ function wsOf(ctx, id) {
22
+ const w = ctx.getWs(id || '');
23
+ return w && (!id || w.id === id) ? w : null;
24
+ }
25
+ const runtimeOf = (ctx) => ctx.runtimeDir || require('./state-root.js').defaultRoot();
26
+
27
+ /** The state folders a workspace keeps autonomy lines in: the server's (✦) and the Driver's, once each. */
28
+ function dirsOf(ctx, w) {
29
+ const out = [];
30
+ const a = ctx.stateDirFor ? ctx.stateDirFor(w) : null;
31
+ const b = D.stateDirOf(w.root);
32
+ for (const d of [a, b]) if (d && !out.includes(path.resolve(d))) out.push(path.resolve(d));
33
+ return out;
34
+ }
35
+
36
+ async function undoRef(ctx, w, ref, g) {
37
+ if (D.PROPOSAL_RE.test(ref)) {
38
+ const stateDir = D.stateDirOf(w.root) || (ctx.stateDirFor && ctx.stateDirFor(w));
39
+ const file = D.ledgerFile(stateDir);
40
+ const decideLib = require('./driver-decide.js');
41
+ const stageTools = require('./stage-tools.js');
42
+ const r = await decideLib.undo({ file, proposal: ref, actor: g.actor, stateDir, product: w.id, ctx: {
43
+ stageFile: path.join(stateDir, stageTools.LEDGER), itemsDir: path.join(runtimeOf(ctx), 'pm-items'), correctionsFile: path.join(runtimeOf(ctx), 'corrections.jsonl'), root: w.root } });
44
+ return r.ok ? { status: 200, body: { ok: true, back: r.back, ...(r.demoted ? { demoted: r.demoted } : {}) } } : bad(r.status, r.error);
45
+ }
46
+ if (/^pk-[0-9a-f]{10}$/.test(ref)) {
47
+ const PR = require('./proposals.js');
48
+ const dir = ctx.stateDirFor ? ctx.stateDirFor(w) : null;
49
+ const line = dir ? PR.readLines(PR.ledgerFile(dir)).find((l) => l.kind === 'keep' && l.batch === ref) : null;
50
+ if (!line) return bad(404, 'no change was applied under that id');
51
+ const RP = require('./routes-proposals.js');
52
+ const RB = require('./routes-boards.js');
53
+ const fr = RB.frameFor(ctx, w);
54
+ const board = (fr.boards || []).find((b) => b.id === line.board);
55
+ if (!board) return bad(404, `the board ${line.board} is gone`);
56
+ const r = RP.undoCore({ ...ctx, runtimeDir: runtimeOf(ctx) }, { w, fr, board, file: null }, g, ref);
57
+ return r.ok ? { status: 200, body: { ok: true, back: r.back > 0 || !r.kept, ...(r.demoted ? { demoted: r.demoted } : {}) } } : bad(r.status, r.error);
58
+ }
59
+ return bad(400, 'ref is a Driver proposal id (p-…) or a ✦ batch id (pk-…)');
60
+ }
61
+
62
+ async function handle(req, res, url, ctx) {
63
+ const send = (r) => { ctx.json(res, r.body, r.status); return true; };
64
+ const sub = url.pathname.replace(/^\/api\/autonomy\/?/, '');
65
+ if (sub === '' && req.method === 'GET') {
66
+ const w = wsOf(ctx, url.searchParams.get('ws'));
67
+ if (!w) return send(bad(404, 'no such workspace'));
68
+ const done = [], notices = [];
69
+ for (const d of dirsOf(ctx, w)) {
70
+ for (const a of A.done(d)) done.push({ ref: a.ref, job: a.job, title: a.title, cls: a.cls, at: a.at, undo_until: new Date(Date.parse(a.at) + A.UNDO_DAYS * DAY).toISOString() });
71
+ for (const n of A.notices(d)) notices.push(n);
72
+ }
73
+ done.sort((a, b) => Date.parse(b.at) - Date.parse(a.at));
74
+ return send({ status: 200, body: { ok: true, ws: w.id, done, notices } });
75
+ }
76
+ if (sub !== 'undo' && sub !== 'seen') return send(bad(404, 'no such autonomy route'));
77
+ if (req.method !== 'POST') return send(bad(405, 'POST only'));
78
+ const read = await ctx.readJson(req);
79
+ if (!read.ok) return send(bad(400, 'the body is not JSON'));
80
+ const body = read.body;
81
+ const g = guard.requirePagePress(req, body);
82
+ if (!g.ok) return send(bad(g.status, g.error));
83
+ const w = wsOf(ctx, text(body.ws));
84
+ if (!w) return send(bad(404, 'no such workspace'));
85
+ if (sub === 'undo') {
86
+ const r = await undoRef(ctx, w, text(body.ref), g);
87
+ try { if (r.status === 200 && ctx.invalidateNeedsAgg) ctx.invalidateNeedsAgg(w.id); } catch { /* the next poll recounts */ }
88
+ return send(r);
89
+ }
90
+ const job = text(body.job), until = text(body.until);
91
+ for (const d of dirsOf(ctx, w)) if (A.notices(d).some((n) => n.job === job && n.until === until)) A.markSeen(d, { job, product: body.product == null ? null : text(body.product), until });
92
+ return send({ status: 200, body: { ok: true } });
93
+ }
94
+
95
+ module.exports = { prefixes: ['/api/autonomy'], handle, undoRef };