create-pmos 0.538.0 → 0.540.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 (53) hide show
  1. package/package.json +39 -39
  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 +38 -0
  7. package/workspace/guide/agent-capabilities.md +9 -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/guide/settings.md +1 -1
  12. package/workspace/guide/today.md +8 -4
  13. package/workspace/guide/workflows.md +14 -12
  14. package/workspace/ini-workflow-test.js +1 -1
  15. package/workspace/lib/agent-inbox.js +2 -2
  16. package/workspace/lib/ai-cli.js +12 -1
  17. package/workspace/lib/ai-guard.js +16 -6
  18. package/workspace/lib/auto-keep.js +33 -0
  19. package/workspace/lib/autonomy-cli.js +53 -0
  20. package/workspace/lib/autonomy.js +234 -0
  21. package/workspace/lib/bg-queue.js +2 -1
  22. package/workspace/lib/driver-cli.js +26 -10
  23. package/workspace/lib/driver-decide.js +76 -8
  24. package/workspace/lib/driver.js +15 -4
  25. package/workspace/lib/goal-loop.js +221 -0
  26. package/workspace/lib/headless.js +75 -1
  27. package/workspace/lib/job-graph.js +5 -0
  28. package/workspace/lib/loop-cli.js +84 -0
  29. package/workspace/lib/pm-lines-needs.js +3 -0
  30. package/workspace/lib/pmos-verbs.js +6 -1
  31. package/workspace/lib/route-modules.js +1 -0
  32. package/workspace/lib/routes-autonomy.js +95 -0
  33. package/workspace/lib/routes-proposals.js +101 -46
  34. package/workspace/lib/run-tokens.js +70 -0
  35. package/workspace/lib/stage-tools.js +11 -1
  36. package/workspace/lib/today-cli.js +57 -4
  37. package/workspace/lib/today.js +2 -8
  38. package/workspace/package-lock.json +2 -2
  39. package/workspace/package.json +1 -1
  40. package/workspace/public/pm/cozy-news.js +1 -1
  41. package/workspace/public/pm/cozy-onboard.js +2 -2
  42. package/workspace/public/pm/cozy-settings.js +42 -11
  43. package/workspace/public/pm/home-app.js +10 -1
  44. package/workspace/public/pm/home-around.js +2 -2
  45. package/workspace/public/pm/ini-wf.js +3 -3
  46. package/workspace/public/pm/wf-page.css +26 -15
  47. package/workspace/public/pm/wf-page.js +96 -72
  48. package/workspace/public/premium-workflows.html +8 -23
  49. package/workspace/replaced-tests.json +17 -0
  50. package/workspace/server.js +33 -16
  51. package/workspace/test-lists/full-autonomy.json +11 -0
  52. package/workspace/test-run.js +3 -0
  53. package/workspace/workflows-setup-test.js +50 -50
@@ -25,7 +25,9 @@
25
25
  * THE LINES. Every line is { v: 1, ev, …, at }. Who wrote a decision is the call path (lib/actor.js), never a field:
26
26
  * proposal { id, target: { kind, ws, id }, what, data, why, sources: [{ label, ref }], run, by } by an agent session
27
27
  * what `doc` (core-documents): data { key, slot } names a core document draft the run wrote; Keep issues it
28
- * keep|return|drop { proposal, note?, by } PM only: the fold ignores one whose `by` is not pm:*
28
+ * keep|return|drop { proposal, note?, by, auto?, undo? } PM or agent (D98): the fold ignores one whose `by` is neither. A keep with
29
+ * auto: true is one an agent applied by itself (D106); `undo` holds what its record write needs to go back
30
+ * undo { proposal, by, back } D106: a kept proposal is undone; `back` says whether its record write went back
29
31
  * correction { proposal, run, kind: 'return'|'drop', by } one per return or drop; the north star counts it
30
32
  * pause|resume { target, by } · mode { board, mode, by } PM only, as above. `board` '*' is every board.
31
33
  * wake { key, target, board, reason: created|moved|answered|stuck, blocker? } queued: a run should start
@@ -55,10 +57,12 @@ const WHATS = Object.freeze({
55
57
  });
56
58
  // A claim without a pointer is not a proposal (PRD section 2: "Nothing without a pointer").
57
59
  const NEEDS_SOURCE = Object.freeze(['evidence', 'sizing', 'assumption', 'stakeholders']);
58
- const MODES = Object.freeze(['off', 'shadow', 'approve']);
59
- const DEFAULT_MODE = 'approve';
60
+ // D106 (Full autonomy now, PM wawan 2026-11-08): `auto` applies a class A or B proposal at once, with Undo (lib/autonomy.js); class C and a
61
+ // demoted job still wait for the PM. It is the default. `approve` is the old default: every proposal waits.
62
+ const MODES = Object.freeze(['off', 'shadow', 'approve', 'auto']);
63
+ const DEFAULT_MODE = 'auto';
60
64
  const WAKES = Object.freeze(['created', 'moved', 'answered', 'stuck']);
61
- const EVENTS = Object.freeze(['proposal', 'keep', 'return', 'drop', 'correction', 'pause', 'resume', 'mode', 'wake', 'run-start', 'run-end', 'refused', 'blocker', 'epoch']);
65
+ const EVENTS = Object.freeze(['proposal', 'keep', 'return', 'drop', 'correction', 'pause', 'resume', 'mode', 'wake', 'run-start', 'run-end', 'refused', 'blocker', 'epoch', 'undo']);
62
66
  const BUDGET = Object.freeze({ concurrent: 3 });
63
67
  const EFFORTS = Object.freeze(['S', 'M', 'L']);
64
68
  const DAY = 86400000;
@@ -256,6 +260,13 @@ function fold(lines) {
256
260
  if (!p || p.state !== 'open' || !pm(l.by)) break;
257
261
  p.state = l.ev === 'keep' ? 'kept' : l.ev === 'return' ? 'returned' : 'dropped';
258
262
  p.note = typeof l.note === 'string' && l.note ? l.note : null; p.decided_at = l.at || null; p.decided_by = l.by;
263
+ if (l.ev === 'keep') { p.auto = l.auto === true; p.undo = isObj(l.undo) ? l.undo : null; }
264
+ break;
265
+ }
266
+ case 'undo': {
267
+ const p = s.proposals.get(l.proposal);
268
+ if (!p || p.state !== 'kept' || !pm(l.by)) break;
269
+ p.state = 'undone'; p.undone_at = l.at || null; p.undone_by = l.by;
259
270
  break;
260
271
  }
261
272
  case 'correction': s.corrections.push({ proposal: l.proposal || null, run: l.run || null, kind: l.kind, at: l.at || null }); break;
@@ -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 };
@@ -8,6 +8,8 @@
8
8
  * for the skill kind, the folders the run may write in, from skillWriteDirs)
9
9
  * skillWriteDirs(skill, { root, scratch }) → the absolute folders a background skill run may write in: its scratch folder and the state folders its skill writes
10
10
  * parseResult(stdout) → { ok, text, isError, turns, durationMs, costUsd, denied[] }
11
+ * usageOf(stdout) → { tokens, model } | null the token counts of the same result line, for lib/run-tokens.js
12
+ * leanOf(kind, env) · builtinsOf(tools) · userModelOf(env) the lean launch (argsFor lean: true), see LEAN LAUNCH
11
13
  * streamLines(line) → { log: [lines], result: object|null } one stream-json event, for the live log
12
14
  * logLines(result, exitCode) → the lines the read-only log pane shows at the end
13
15
  * outcomeOf(result, { code, signal, timedOut, stopped, timeoutMin }) → { ok, headline, why, turns, durationMs, denied } what the run card says
@@ -364,7 +366,47 @@ function kindFor({ agent, origin, skill, env } = {}) {
364
366
  return null;
365
367
  }
366
368
 
367
- function argsFor(kind, { modelArgs = [], addDirs = [], writePaths = [], budgetUsd = null, connectorTools = [], team = null } = {}) {
369
+ /* LEAN LAUNCH (token efficiency build, Wawan 2026-11-08). A plain `claude -p` loads about 63k tokens of fixed context on every turn: every
370
+ * built-in tool, every MCP server's tools, the skills and slash commands, the user and project settings and CLAUDE.md. A background run
371
+ * needs none of that beyond its own tools. Measured in the cloud: 63.0k → 15.7k tokens per turn, a 3-turn task 196k → 45k, same answer.
372
+ * The four flags only pay together: `--tools` alone, with the MCP servers still on, went UP to 66k.
373
+ * --tools <the kind's built-ins> only the built-in tools its --allowedTools names (Bash for `Bash(pmos *)`), never Task, Skill or TodoWrite
374
+ * --disable-slash-commands no skills or commands in the prompt
375
+ * --setting-sources= no user, project or local settings, and no CLAUDE.md (one argv token: an empty "" can be lost on Windows)
376
+ * --strict-mcp-config no MCP server, for every kind that reads no connector
377
+ * Because the PM's user settings no longer load, the server passes the model of those settings explicitly (userModelOf) when no tier chose one.
378
+ * A kind that reads the PM's connectors (CONNECTOR_READ_KINDS) stays on the full launch until a run on the PM's own computer shows its connector
379
+ * tools still load without the settings. PMOS_LEAN_JOBS: off = every kind on the full launch; all = connector kinds lean too, without
380
+ * --strict-mcp-config (for that check); anything else = the default. */
381
+ const LEAN_FLAGS = Object.freeze(['--disable-slash-commands', '--setting-sources=']);
382
+ /** Does this kind launch lean? (PMOS_LEAN_JOBS in env, see above) */
383
+ function leanOf(kind, env) {
384
+ const v = String(((env || {}).PMOS_LEAN_JOBS) || '').trim().toLowerCase();
385
+ if (/^(off|0|false|no)$/.test(v)) return false;
386
+ if (!TOOLS[kind]) return false;
387
+ return v === 'all' || !CONNECTOR_READ_KINDS.includes(kind);
388
+ }
389
+ /** The built-in tool names in an --allowedTools list: `Bash(pmos *)` → Bash, `Write(/x/**)` → Write; connector tools are not built-ins. */
390
+ function builtinsOf(tools) {
391
+ const out = [];
392
+ for (const t of tools || []) {
393
+ const m = /^([A-Z][A-Za-z]+)(?:\(|$)/.exec(String(t || ''));
394
+ if (m && !out.includes(m[1])) out.push(m[1]);
395
+ }
396
+ return out;
397
+ }
398
+ /** The model in the PM's Claude Code user settings (<CLAUDE_CONFIG_DIR or ~/.claude>/settings.json), or null. A lean run loads no settings, so
399
+ * the server passes this one explicitly and the run keeps the model it had. */
400
+ function userModelOf(env) {
401
+ const e = env || process.env;
402
+ const dir = e.CLAUDE_CONFIG_DIR ? String(e.CLAUDE_CONFIG_DIR) : path.join(e.HOME || require('os').homedir(), '.claude');
403
+ try {
404
+ const m = JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')).model;
405
+ return typeof m === 'string' && /^[\w.\[\]:-]{1,80}$/.test(m.trim()) ? m.trim() : null;
406
+ } catch { return null; }
407
+ }
408
+
409
+ function argsFor(kind, { modelArgs = [], addDirs = [], writePaths = [], budgetUsd = null, connectorTools = [], team = null, lean = false } = {}) {
368
410
  if (!TOOLS[kind]) throw new Error('unknown headless kind: ' + kind);
369
411
  let tools = TOOLS[kind].slice();
370
412
  // A role run: the role's own tools. Its writable paths (auto mode only) are each a folder ("/" at the end: it and what is under it) or one file.
@@ -405,6 +447,10 @@ function argsFor(kind, { modelArgs = [], addDirs = [], writePaths = [], budgetUs
405
447
  // report draft stopped after reading ("Plan mode is on, and the draft step writes files") and wrote nothing. dontAsk runs the list above and denies
406
448
  // the rest, which is what this file already promises; it is not a bypass.
407
449
  const argv = ['-p', '--output-format', 'stream-json', '--verbose', '--no-session-persistence', '--permission-mode', 'dontAsk', '--append-system-prompt', DENIED_RULE, ...modelArgs, '--allowedTools', tools.join(',')];
450
+ if (lean) {
451
+ argv.push('--tools', builtinsOf(tools).join(','), ...LEAN_FLAGS);
452
+ if (!CONNECTOR_READ_KINDS.includes(kind)) argv.push('--strict-mcp-config');
453
+ }
408
454
  // A run with a budget (a grill run, lib/grill.js budgetFor) stops at it, so the monthly credit cap holds
409
455
  const b = Number(budgetUsd);
410
456
  if (budgetUsd != null && Number.isFinite(b) && b > 0) argv.push('--max-budget-usd', String(b));
@@ -439,6 +485,32 @@ function jsonOf(line) {
439
485
  try { const o = JSON.parse(t); return o && typeof o === 'object' ? o : null; } catch { return null; }
440
486
  }
441
487
 
488
+ /** The token counts of a result's `usage`: { input, cacheCreate, cacheRead, output }, or null when it has none. Context read per run =
489
+ * input + cacheCreate + cacheRead (summed over every turn by Claude Code). */
490
+ function tokensOf(u) {
491
+ if (!u || typeof u !== 'object') return null;
492
+ const n = (v) => (Number.isFinite(v) && v >= 0 ? v : 0);
493
+ const t = { input: n(u.input_tokens), cacheCreate: n(u.cache_creation_input_tokens), cacheRead: n(u.cache_read_input_tokens), output: n(u.output_tokens) };
494
+ return t.input + t.cacheCreate + t.cacheRead + t.output > 0 ? t : null;
495
+ }
496
+ /** The model that did most of a run's work (`modelUsage`, by output tokens), or null. */
497
+ function modelOf(mu) {
498
+ if (!mu || typeof mu !== 'object') return null;
499
+ let best = null, top = -1;
500
+ for (const [k, v] of Object.entries(mu)) { const out = v && Number.isFinite(v.outputTokens) ? v.outputTokens : 0; if (out > top) { best = k; top = out; } }
501
+ return best;
502
+ }
503
+
504
+ /** The token counts and model of the result on stdout (the same line parseResult reads), or null. */
505
+ function usageOf(stdout) {
506
+ const lines = String(stdout || '').trim().split('\n');
507
+ for (let i = lines.length - 1; i >= 0; i--) {
508
+ const o = jsonOf(lines[i]);
509
+ if (o && (o.type === 'result' || (!o.type && o.usage))) { const tokens = tokensOf(o.usage); return tokens ? { tokens, model: modelOf(o.modelUsage) } : null; }
510
+ }
511
+ return null;
512
+ }
513
+
442
514
  /** The result object on stdout: the whole of it (`--output-format json`), else the last line whose type is `result`
443
515
  * (`stream-json`), else the last line that parses. Anything unreadable is not a result. */
444
516
  function parseResult(stdout) {
@@ -560,3 +632,5 @@ function runEnvOf(extra) {
560
632
  }
561
633
 
562
634
  module.exports = { CONNECTOR_READ_KINDS, CONNECTOR_READ_SEED, DENIED_RULE, HEADLESS_ENV, headlessEnv, connectorReads, initTools, denialGuard, HEADLESS_SKILLS, HEADLESS_ORIGINS, ASK_ORIGINS, DRIVE_ORIGINS, SCAN_WEB_ORIGINS, SCAN_REPO_ORIGINS, SCAN_RESEARCH_WEB_ORIGINS, SCAN_RESEARCH_REPO_ORIGINS, WEB_KINDS, REPORT_SETUP_ORIGINS, REPORT_FIND_ORIGINS, CORE_DOC_ORIGINS, REPORT_DESIGN_ORIGINS, REPORT_SAMPLE_FETCH_ORIGINS, REPORT_STRUCTURE_ORIGINS, REPORT_STRUCTURE_DRY_ORIGINS, METRIC_DRAFT_ORIGINS, IMPACT_ORIGINS, TOOLS, SKILL_WRITE_DIRS, DEFAULT_TIMEOUT_MS, kindFor, argsFor, skillWriteDirs, timeoutMs, parseResult, streamLines, outcomeOf, signedOut, SIGNED_OUT_WHY, logLines, switchedOff, RUN_ENV, runEnvOf };
635
+ // the lean launch and the token counts (token efficiency build, 2026-11-08)
636
+ const LEAN_API = Object.assign(module.exports, { LEAN_FLAGS, leanOf, builtinsOf, userModelOf, tokensOf, modelOf, usageOf });
@@ -38,11 +38,15 @@ const LEDGERS = Object.freeze({
38
38
  r('lib/proposal-runs.js', 'PR.lessonsOf', "the task checks' next run: dropped proposals and the PM's reasons")] },
39
39
  [`<runtime>/${audit}`]: { concept: 'ai-audit', owner: 'lib/ai-guard.js', readers: [
40
40
  r('lib/ai-cli.js', 'AG.readAudit', '`pmos ai log` and `pmos ai status`')] },
41
+ '<runtime>/run-tokens.jsonl': { concept: 'run-tokens', owner: 'lib/run-tokens.js', readers: [
42
+ r('lib/ai-cli.js', 'run-tokens.js', '`pmos ai status`: tokens read per background run, lean and full')] },
41
43
  '<runtime>/bg-queue.jsonl': { concept: 'background-turns', owner: 'lib/bg-queue.js', readers: [
42
44
  r('lib/routes-lab.js', 'bgQueue.record', 'Intelligence › Lab: what Claude did in the background')] },
43
45
  '<runtime>/grill-runs.jsonl': { concept: 'grill-spend', owner: 'lib/grill.js', readers: [
44
46
  r('lib/bg-queue.js', 'grill-runs.jsonl', 'the spend limit that holds step 5'),
45
47
  r('lib/routes-grill.js', null, "Settings › Claude's checks: this month's spend")] },
48
+ '<runtime>/goal-loops.jsonl': { concept: 'goal-loops', owner: 'lib/goal-loop.js', readers: [
49
+ r('lib/loop-cli.js', null, '`pmos loop status`: each goal, its round and its state')] },
46
50
  '<state>/driver.jsonl': { concept: 'driver-runs', owner: 'lib/driver.js', readers: [
47
51
  r('lib/routes-driver.js', null, "the initiative's Agent strip"),
48
52
  r('lib/driver-needs.js', null, 'Needs you')] },
@@ -114,6 +118,7 @@ const JOBS = Object.freeze([
114
118
  q('reports', 'lib/routes-report-setups.js', ['<state>/report-setups.jsonl', '<state>/ready-reports.jsonl'], ['<state>/report-setups.jsonl']),
115
119
  q('sync', 'lib/auto-sync.js', [], ['git'], 'git only: no model and no ledger'),
116
120
  q('driver', 'lib/driver.js', ['<state>/driver.jsonl'], ['initiative records', 'jira']),
121
+ 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
122
  q('finder', 'lib/report-finder.js', ['<state>/report-setups.jsonl'], ['connectors']),
118
123
  q('coredocs', 'lib/core-docs.js', ['<state>/core-docs.jsonl'], ['initiative records']),
119
124
  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 };