agent-supervisor-mcp 0.0.0-stage → 2.0.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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +208 -0
  3. package/README.md +206 -2
  4. package/package.json +76 -4
  5. package/skills/agent-supervisor/SKILL.md +139 -0
  6. package/src/app/acceptance.js +263 -0
  7. package/src/app/auto-cleanup.js +91 -0
  8. package/src/app/cancel.js +57 -0
  9. package/src/app/cleanup-facts.js +101 -0
  10. package/src/app/cleanup-plan.js +166 -0
  11. package/src/app/compose.js +17 -0
  12. package/src/app/context-compiler.js +83 -0
  13. package/src/app/dispatch.js +398 -0
  14. package/src/app/followup.js +104 -0
  15. package/src/app/land-chain.js +134 -0
  16. package/src/app/landing.js +357 -0
  17. package/src/app/ownership.js +57 -0
  18. package/src/app/rebase.js +216 -0
  19. package/src/app/restore-worktree.js +51 -0
  20. package/src/app/resume.js +179 -0
  21. package/src/app/run-state.js +26 -0
  22. package/src/app/settled.js +28 -0
  23. package/src/app/side-chat.js +370 -0
  24. package/src/app/sse.js +20 -0
  25. package/src/app/start-run.js +77 -0
  26. package/src/app/verify-push.js +114 -0
  27. package/src/app/worktree-setup.js +218 -0
  28. package/src/domain/acceptance-baseline.js +65 -0
  29. package/src/domain/acceptance-spec.js +30 -0
  30. package/src/domain/cleanup-policy.js +44 -0
  31. package/src/domain/command-outcome.js +6 -0
  32. package/src/domain/failure-class.js +63 -0
  33. package/src/domain/owned-changes.js +27 -0
  34. package/src/domain/prompt.js +161 -0
  35. package/src/domain/side-turn-view.js +73 -0
  36. package/src/domain/status.js +50 -0
  37. package/src/domain/thread-health.js +33 -0
  38. package/src/domain/truncate.js +148 -0
  39. package/src/domain/worker-branch.js +6 -0
  40. package/src/domain/worker-changes.js +58 -0
  41. package/src/domain/worker-env.js +14 -0
  42. package/src/domain/worker-preflight.js +167 -0
  43. package/src/domain/worker-report.js +85 -0
  44. package/src/domain/worker-report.schema.json +10 -0
  45. package/src/infra/bin-resolver.js +287 -0
  46. package/src/infra/cleanup-hint.js +29 -0
  47. package/src/infra/crash-guard.js +44 -0
  48. package/src/infra/external-output.js +29 -0
  49. package/src/infra/git.js +61 -0
  50. package/src/infra/handoff.js +38 -0
  51. package/src/infra/paths.js +34 -0
  52. package/src/infra/process.js +59 -0
  53. package/src/infra/sandbox-roots.js +106 -0
  54. package/src/infra/skill-sync.js +109 -0
  55. package/src/infra/stage-store.js +39 -0
  56. package/src/infra/store/db.js +265 -0
  57. package/src/infra/store/event-body.js +82 -0
  58. package/src/infra/store/events.js +149 -0
  59. package/src/infra/store/facts.js +338 -0
  60. package/src/infra/store/reconcile.js +173 -0
  61. package/src/infra/store/records.js +171 -0
  62. package/src/infra/store/runner-readers.js +16 -0
  63. package/src/infra/store/schema.js +306 -0
  64. package/src/infra/store/sessions.js +138 -0
  65. package/src/infra/store/tasks.js +351 -0
  66. package/src/infra/update/auto-update-worker.js +186 -0
  67. package/src/infra/update/auto-update.js +143 -0
  68. package/src/infra/update/update-check.js +246 -0
  69. package/src/infra/workspace-kind.js +165 -0
  70. package/src/infra/worktree.js +361 -0
  71. package/src/interface/bin/acceptance-cli.js +62 -0
  72. package/src/interface/bin/cleanup.js +81 -0
  73. package/src/interface/bin/monitor.jsx +301 -0
  74. package/src/interface/bin/setup.js +342 -0
  75. package/src/interface/bin/stage.js +17 -0
  76. package/src/interface/bin/web-server.js +53 -0
  77. package/src/interface/mcp/handlers/delivery.js +165 -0
  78. package/src/interface/mcp/handlers/dispatch.js +236 -0
  79. package/src/interface/mcp/handlers/facts.js +204 -0
  80. package/src/interface/mcp/handlers/overview.js +106 -0
  81. package/src/interface/mcp/handlers/results.js +262 -0
  82. package/src/interface/mcp/handlers/review.js +115 -0
  83. package/src/interface/mcp/handlers/wait.js +141 -0
  84. package/src/interface/mcp/meta.js +7 -0
  85. package/src/interface/mcp/result.js +34 -0
  86. package/src/interface/mcp/schemas.js +24 -0
  87. package/src/interface/mcp/server.js +64 -0
  88. package/src/interface/mcp/tools/deliver.js +48 -0
  89. package/src/interface/mcp/tools/dispatch.js +90 -0
  90. package/src/interface/mcp/tools/optional.js +57 -0
  91. package/src/interface/mcp/tools/read.js +115 -0
  92. package/src/interface/mcp/tools/run.js +57 -0
  93. package/src/interface/mcp/tools/shapes.js +67 -0
  94. package/src/interface/mcp/tools/track.js +84 -0
  95. package/src/interface/mcp/update-state.js +34 -0
  96. package/src/interface/mcp/views/overview.js +183 -0
  97. package/src/interface/mcp/views/task.js +224 -0
  98. package/src/interface/web/app.js +226 -0
  99. package/src/interface/web/views.js +227 -0
  100. package/src/mcp-server.js +4 -0
  101. package/src/run-host/entry.js +26 -0
  102. package/src/run-host/finalize.js +243 -0
  103. package/src/run-host/launch.js +49 -0
  104. package/src/run-host/live-run.js +76 -0
  105. package/src/run-host/outcome-facts.js +61 -0
  106. package/src/run-host/streams.js +102 -0
  107. package/src/run-host/track.js +132 -0
  108. package/src/runners/claude/adapter.js +118 -0
  109. package/src/runners/claude/events.js +100 -0
  110. package/src/runners/claude/tool-guard.js +48 -0
  111. package/src/runners/codex/adapter.js +157 -0
  112. package/src/runners/codex/chat-chunks.js +97 -0
  113. package/src/runners/codex/event-parser.js +266 -0
  114. package/src/runners/codex/goal-store.js +54 -0
  115. package/src/runners/codex/mcp-config.js +39 -0
  116. package/src/runners/codex/tool-guard.js +184 -0
  117. package/src/runners/contract-check.js +82 -0
  118. package/src/runners/contract.js +53 -0
  119. package/src/runners/registry.js +45 -0
  120. package/web/dist/assets/index-D-A2xlpx.js +154 -0
  121. package/web/dist/assets/index-f8esISCp.css +2 -0
  122. package/web/dist/index.html +15 -0
@@ -0,0 +1,227 @@
1
+ // What the board shows: session and worker rows built from the store, read-only.
2
+ import { branchOf } from "../../domain/worker-branch.js";
3
+ import { ACTIVE_STATUSES } from "../../domain/status.js";
4
+ import { supervisorRoot } from "../../infra/paths.js";
5
+ import { restoreEventBodies } from "../../infra/store/event-body.js";
6
+ import { listTaskEventKinds, readAgentMessages, readTaskEvents } from "../../infra/store/events.js";
7
+ import { reconcileDetachedActiveTasks } from "../../infra/store/reconcile.js";
8
+ import { readSessions } from "../../infra/store/sessions.js";
9
+ import { getTask, readTasks } from "../../infra/store/tasks.js";
10
+ import { readTaskChanges } from "../../infra/worktree.js";
11
+ import { readNativeGoal } from "../../infra/store/runner-readers.js";
12
+
13
+ const NO_SESSION = "none";
14
+
15
+ function clip(value, maxChars) {
16
+ if (value === null || value === undefined) return null;
17
+ const text = String(value);
18
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
19
+ }
20
+
21
+ function durationMs(task) {
22
+ const start = Date.parse(task.started_at ?? task.created_at ?? "");
23
+ if (Number.isNaN(start)) return null;
24
+ const end = Date.parse(task.completed_at ?? "");
25
+ const stop = Number.isNaN(end) ? Date.now() : end;
26
+ return Math.max(0, stop - start);
27
+ }
28
+
29
+ // The row every list shows. No prompt, no raw events: those are per-worker
30
+ // reads, so a session with forty threads stays one cheap request.
31
+ function workerRow(task) {
32
+ return {
33
+ id: task.id,
34
+ title: task.title,
35
+ status: task.status,
36
+ phase: task.phase ?? null,
37
+ session_id: task.session_id ?? null,
38
+ thread_id: task.thread_id ?? null,
39
+ goal: task.goal_objective ?? null,
40
+ goal_status: task.goal_status ?? null,
41
+ model: task.model ?? null,
42
+ sandbox: task.sandbox,
43
+ project_root: task.project_root,
44
+ worktree_path: task.worktree_path ?? null,
45
+ branch: task.worktree_path ? branchOf(task) : null,
46
+ base_commit: task.base_commit ?? null,
47
+ owned_paths: task.owned_paths ?? [],
48
+ depends_on: task.depends_on ?? [],
49
+ followup_of: task.followup_of ?? null,
50
+ resumed_from: task.resumed_from ?? null,
51
+ run_count: task.run_count ?? 0,
52
+ current_action: clip(task.current_action, 300),
53
+ last_message: clip(task.last_message, 400),
54
+ changed_file_count: liveChangeCount(task),
55
+ acceptance: task.acceptance_results?.status ?? null,
56
+ landed_at: task.landed_at ?? null,
57
+ command_count: (task.commands ?? []).length,
58
+ error: task.error ?? null,
59
+ exit_code: task.exit_code ?? null,
60
+ pid: task.pid ?? null,
61
+ created_at: task.created_at || null,
62
+ started_at: task.started_at || null,
63
+ updated_at: task.updated_at || null,
64
+ completed_at: task.completed_at || null,
65
+ duration_ms: durationMs(task)
66
+ };
67
+ }
68
+
69
+ // Changed-file counts for the list. The stored changed_files on a row only
70
+ // knows about file_change events; the truth is the worktree diff, which costs
71
+ // two git calls per worker. Terminal rows never change again, so their count
72
+ // is memoised on (id, updated_at); running rows are re-read every time.
73
+ const changeCountCache = new Map();
74
+ function liveChangeCount(task) {
75
+ const key = `${task.id}:${task.updated_at}:${task.status}`;
76
+ const cached = changeCountCache.get(key);
77
+ if (cached !== undefined && !ACTIVE_STATUSES.has(task.status)) return cached;
78
+ const count = readTaskChanges(task).length;
79
+ changeCountCache.set(key, count);
80
+ if (changeCountCache.size > 2000) changeCountCache.delete(changeCountCache.keys().next().value);
81
+ return count;
82
+ }
83
+
84
+ function sessionKey(task) {
85
+ return task.session_id || NO_SESSION;
86
+ }
87
+
88
+ function latest(values) {
89
+ return values.filter(Boolean).sort().at(-1) ?? null;
90
+ }
91
+
92
+ // What a session is about. The title the main thread recorded wins; without
93
+ // one, the goals of its workers are the next best description.
94
+ function aboutSession(meta, tasks) {
95
+ if (meta?.title) return { title: meta.title, note: meta.note ?? null, derived: false };
96
+ const goals = Array.from(new Set(tasks.map((task) => task.goal_objective).filter(Boolean)));
97
+ const summary = goals.slice(0, 3).map((goal) => clip(goal, 60)).join(";");
98
+ return { title: summary || null, note: null, derived: true };
99
+ }
100
+
101
+ function sessionRow(key, tasks, meta = null) {
102
+ const counts = {};
103
+ for (const task of tasks) counts[task.status] = (counts[task.status] ?? 0) + 1;
104
+ const active = tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
105
+ const byActivity = [...tasks].sort((a, b) => String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? "")));
106
+ const lastReport = byActivity.find((task) => task.last_message);
107
+ const about = aboutSession(meta, tasks);
108
+ return {
109
+ id: key,
110
+ unsessioned: key === NO_SESSION,
111
+ title: about.title,
112
+ note: about.note,
113
+ title_derived: about.derived,
114
+ worker_count: tasks.length,
115
+ active_count: active.length,
116
+ counts,
117
+ project_roots: Array.from(new Set(tasks.map((task) => task.project_root).filter(Boolean))),
118
+ first_created_at: tasks.map((task) => task.created_at).filter(Boolean).sort()[0] ?? null,
119
+ last_activity_at: latest(tasks.map((task) => task.updated_at)),
120
+ // What the session is doing right now: one line per running thread.
121
+ now: active.map((task) => ({
122
+ id: task.id,
123
+ title: task.title,
124
+ phase: task.phase ?? null,
125
+ current_action: clip(task.current_action, 160)
126
+ })),
127
+ last_report: lastReport
128
+ ? { id: lastReport.id, title: lastReport.title, text: clip(lastReport.last_message, 240), at: lastReport.updated_at }
129
+ : null
130
+ };
131
+ }
132
+
133
+ // Pagination for the lists: `limit` rows after `offset`, newest activity
134
+ // first for sessions, dispatch order for workers. The page says whether
135
+ // there is more so the board loads the rest as the user scrolls.
136
+ export function pageParams(url, defaultLimit) {
137
+ const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? defaultLimit) || defaultLimit));
138
+ const offset = Math.max(0, Number(url.searchParams.get("offset") ?? 0) || 0);
139
+ return { limit, offset };
140
+ }
141
+
142
+ function paginate(items, { limit, offset }) {
143
+ return { items: items.slice(offset, offset + limit), total: items.length, offset, limit, has_more: offset + limit < items.length };
144
+ }
145
+
146
+ export async function overview({ limit, offset } = { limit: 20, offset: 0 }) {
147
+ await reconcileDetachedActiveTasks();
148
+ const tasks = await readTasks();
149
+ const metas = new Map((await readSessions()).map((row) => [row.id, row]));
150
+ const groups = new Map();
151
+ for (const task of tasks) {
152
+ const key = sessionKey(task);
153
+ if (!groups.has(key)) groups.set(key, []);
154
+ groups.get(key).push(task);
155
+ }
156
+ const sessions = Array.from(groups, ([key, group]) => sessionRow(key, group, metas.get(key) ?? null)).sort((a, b) => {
157
+ if (a.active_count !== b.active_count) return b.active_count - a.active_count;
158
+ return String(b.last_activity_at ?? "").localeCompare(String(a.last_activity_at ?? ""));
159
+ });
160
+ const page = paginate(sessions, { limit, offset });
161
+ return {
162
+ generated_at: new Date().toISOString(),
163
+ store: supervisorRoot,
164
+ total_workers: tasks.length,
165
+ active_workers: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
166
+ total_sessions: sessions.length,
167
+ offset: page.offset,
168
+ limit: page.limit,
169
+ has_more: page.has_more,
170
+ sessions: page.items
171
+ };
172
+ }
173
+
174
+ export async function session(key, { limit, offset } = { limit: 40, offset: 0 }) {
175
+ await reconcileDetachedActiveTasks();
176
+ const tasks = (await readTasks()).filter((task) => sessionKey(task) === key);
177
+ if (tasks.length === 0) return null;
178
+ const meta = (await readSessions()).find((row) => row.id === key) ?? null;
179
+ const ordered = [...tasks].sort((a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")));
180
+ const page = paginate(ordered, { limit, offset });
181
+ return {
182
+ ...sessionRow(key, tasks, meta),
183
+ offset: page.offset,
184
+ limit: page.limit,
185
+ has_more: page.has_more,
186
+ workers: page.items.map(workerRow)
187
+ };
188
+ }
189
+
190
+ export async function worker(taskId) {
191
+ const task = await getTask(taskId);
192
+ if (!task) return null;
193
+ const reports = await readAgentMessages(taskId, 10);
194
+ // Token spend comes from Codex's own turn.completed usage blocks; one per
195
+ // run, so a resumed worker sums its runs.
196
+ const usage = { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, reasoning_output_tokens: 0, turns: 0 };
197
+ for (const event of await readTaskEvents(taskId, 50, ["turn.completed"])) {
198
+ const block = event?.usage ?? {};
199
+ usage.turns += 1;
200
+ for (const key of ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens"]) {
201
+ usage[key] += Number(block[key] ?? 0) || 0;
202
+ }
203
+ }
204
+ const commands = (task.commands ?? []).slice(-40).map((entry) => ({
205
+ ...entry,
206
+ command: clip(entry.command, 600)
207
+ }));
208
+ return {
209
+ ...workerRow(task),
210
+ prompt: task.prompt ?? null,
211
+ changed_files: readTaskChanges(task),
212
+ commands,
213
+ reports: reports.length > 0 ? reports : task.last_message ? [task.last_message] : [],
214
+ native_goal: readNativeGoal(task.thread_id, task.worker),
215
+ usage,
216
+ notices: task.notices ?? null,
217
+ run_log: task.run_log ?? null,
218
+ event_kinds: await listTaskEventKinds(taskId)
219
+ };
220
+ }
221
+
222
+ export async function events(taskId, url) {
223
+ const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get("limit") ?? 150)));
224
+ const kinds = url.searchParams.get("kinds")?.split(",").filter(Boolean) ?? null;
225
+ const task = await getTask(taskId);
226
+ return { task_id: taskId, events: await restoreEventBodies(await readTaskEvents(taskId, limit, kinds), task?.run_log ?? null) };
227
+ }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // Stable entry point. Client registrations store this absolute path, so it stays
3
+ // here; the server itself lives in interface/mcp.
4
+ import "./interface/mcp/server.js";
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // The detached process that owns one run: it reads the worker's output, writes
3
+ // the exit and runs acceptance, and outlives the MCP server that started it.
4
+ import "../app/compose.js";
5
+ import { failedStart } from "../app/run-state.js";
6
+ import { upsertTask } from "../infra/store/tasks.js";
7
+ import { installCrashGuard } from "../infra/crash-guard.js";
8
+ import { trackRunInHost } from "./track.js";
9
+
10
+ installCrashGuard("run-host", { exitOnRejection: true });
11
+
12
+ process.once("message", async (job) => {
13
+ const keepAlive = setInterval(() => {}, 1000);
14
+ let result;
15
+ try {
16
+ result = await trackRunInHost(job);
17
+ if (!result.ok) await upsertTask(result.record);
18
+ } catch (error) {
19
+ result = failedStart(job.record, `run host failed: ${error.message}`);
20
+ await upsertTask(result.record);
21
+ }
22
+ if (process.connected) await new Promise((resolveSent) => process.send({ ok: result.ok, record: result.record }, resolveSent));
23
+ if (result.settled) await result.settled;
24
+ clearInterval(keepAlive);
25
+ if (process.connected) process.disconnect();
26
+ });
@@ -0,0 +1,243 @@
1
+ // What happens after the worker process closes: decide the terminal status,
2
+ // gather the evidence of what the run did, flag runs that need attention, run
3
+ // acceptance and write the final row.
4
+ import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "../app/acceptance.js";
5
+ import { acceptanceRuns, cancelledTasks, processes } from "../app/run-state.js";
6
+ import { TERMINAL_STATUSES } from "../domain/status.js";
7
+ import { parseWorkerReportForRun } from "../domain/worker-report.js";
8
+ import { captureExternalOutputs, compareExternalOutputs } from "../infra/external-output.js";
9
+ import { appendTaskEvent, completeRunRecord } from "../infra/store/events.js";
10
+ import { updateWorkItemDelivery } from "../infra/store/records.js";
11
+ import { getTask } from "../infra/store/tasks.js";
12
+ import { captureWorkspaceManifest } from "../infra/workspace-kind.js";
13
+ import { readTaskChanges, snapshotTaskOutput } from "../infra/worktree.js";
14
+ import { persist } from "./live-run.js";
15
+ import { projectOutcomeFacts } from "./outcome-facts.js";
16
+ import { queueEventLines } from "./streams.js";
17
+ import { createHash } from "node:crypto";
18
+ import { appendFile } from "node:fs/promises";
19
+
20
+ function terminalStatus(run, stored, code, signal) {
21
+ const { live } = run;
22
+ // A cancel can be issued from another MCP process, so the marker is read
23
+ // back from disk rather than trusted to this process's memory.
24
+ const cancelRequested = cancelledTasks.has(run.record.id)
25
+ || Boolean(live.cancel_requested_at)
26
+ || Boolean(stored?.cancel_requested_at);
27
+ if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) return stored.status;
28
+ if (run.terminalEvent && TERMINAL_STATUSES.has(live.status)) return live.status;
29
+ if (cancelRequested) return "cancelled";
30
+ // The supervisor stopped it for running out of time; the signal was its own.
31
+ if (run.quotaReason) return "timed_out";
32
+ // Killed by a signal nobody asked for: the worker did not fail, it
33
+ // vanished. Re-running is the fix, so it is reported as lost.
34
+ if (signal) return "lost";
35
+ if (code === 0) return "lost";
36
+ return "failed";
37
+ }
38
+
39
+ function terminalRow(run, status, code, signal, finishedAt) {
40
+ const { live } = run;
41
+ const next = {
42
+ ...live,
43
+ status,
44
+ phase: null,
45
+ changed_files: readTaskChanges(live),
46
+ exit_code: code,
47
+ signal,
48
+ current_command: null,
49
+ current_action: status === "completed" ? "Completed" : live.current_action,
50
+ completed_at: live.completed_at ?? finishedAt,
51
+ updated_at: finishedAt
52
+ };
53
+ const stdinEpipe = /^stdin write failed:.*\bEPIPE\b/i.test(next.error ?? "");
54
+ if (status === "failed" && (!next.error || stdinEpipe)) {
55
+ next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
56
+ }
57
+ if (status === "lost" && (!next.error || stdinEpipe)) {
58
+ next.error = signal ? `codex worker was killed by signal ${signal} before writing a terminal event` : "Codex worker exited without recording a terminal event";
59
+ }
60
+ if (status === "cancelled") next.error = null;
61
+ if (run.quotaReason) {
62
+ next.attention_reason = run.quotaReason;
63
+ next.error = `Supervisor time quota exceeded: ${run.quotaReason}; inspect partial work before changing the budget`;
64
+ }
65
+ return next;
66
+ }
67
+
68
+ async function externalChangesOf(run, next) {
69
+ try {
70
+ return compareExternalOutputs(run.externalBefore, await captureExternalOutputs(run.record.guard_policy?.externalOutputs ?? []));
71
+ } catch (error) {
72
+ next.attention_reason = "external_output_unverified";
73
+ next.error = error.message;
74
+ return [];
75
+ }
76
+ }
77
+
78
+ async function workspaceAfterOf(run, next) {
79
+ const metadata = run.record.workspace_metadata;
80
+ if (!run.workspaceBefore || !Array.isArray(metadata?.manifest_paths)) return null;
81
+ try {
82
+ return await captureWorkspaceManifest(metadata.source_root, metadata.manifest_paths);
83
+ } catch (error) {
84
+ next.attention_reason = "workspace_manifest_unverified";
85
+ next.error = error.message;
86
+ return null;
87
+ }
88
+ }
89
+
90
+ // Records what the run changed and a fingerprint of the attempt, used to tell
91
+ // two consecutive runs that made no progress.
92
+ async function attachEvidence(run, next) {
93
+ const { live, record, workspaceBefore, outputBefore } = run;
94
+ const outputAfter = snapshotTaskOutput(live);
95
+ const externalChanges = await externalChangesOf(run, next);
96
+ const workspaceAfter = await workspaceAfterOf(run, next);
97
+ const structuredReport = parseWorkerReportForRun(run.rawReport, { outputSchema: run.outputSchema });
98
+ next.run_evidence = {
99
+ run: live.run_count, commands_run: live.commands.length,
100
+ structured_report: structuredReport,
101
+ output_before: outputBefore, output_after: outputAfter,
102
+ output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null,
103
+ workspace: workspaceBefore ? {
104
+ kind: record.workspace_kind,
105
+ before_manifest: workspaceBefore,
106
+ after_manifest: workspaceAfter,
107
+ manifest_changed: workspaceAfter ? workspaceBefore.sha256 !== workspaceAfter.sha256 : null
108
+ } : null
109
+ };
110
+ next.run_evidence.external_outputs = externalChanges;
111
+ if (externalChanges.some((entry) => entry.changed)) next.run_evidence.output_changed = true;
112
+ next.changed_files = [...new Set([...next.changed_files, ...externalChanges.filter((entry) => entry.changed).map((entry) => entry.path)])];
113
+ next.run_evidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
114
+ output_changed: next.run_evidence.output_changed,
115
+ commands_run: live.commands.length,
116
+ changed_files: next.changed_files,
117
+ acceptance_configured: Array.isArray(live.acceptance) && live.acceptance.length > 0,
118
+ workspace_manifest_changed: next.run_evidence.workspace?.manifest_changed ?? null
119
+ })).digest("hex");
120
+ }
121
+
122
+ // "The evidence could not be read" outranks what the evidence would have
123
+ // said: no_work and invalid_report are both conclusions drawn from it.
124
+ const UNVERIFIED = new Set(["external_output_unverified", "workspace_manifest_unverified"]);
125
+
126
+ export function flagAttention(run, next, status, code) {
127
+ const { live } = run;
128
+ if (UNVERIFIED.has(next.attention_reason)) return;
129
+ if (status === "completed" && code === 0 && live.sandbox !== "read-only"
130
+ && !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
131
+ && live.commands.length === 0 && !run.reportOnlyRecovery) {
132
+ next.attention_reason = run.priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
133
+ if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
134
+ }
135
+ if (status === "completed" && !next.run_evidence.structured_report.valid && !live.guard_policy?.preflight) {
136
+ // The report is a summary, not the business result. Keep the completed
137
+ // lifecycle and let acceptance plus the reviewed diff decide whether it
138
+ // can land; a report-only recovery can still repair the summary.
139
+ next.attention_reason = "invalid_report";
140
+ next.error = `Invalid final worker report: ${next.run_evidence.structured_report.error}`;
141
+ next.current_action = "Work completed, but the final report is invalid; acceptance and diff remain authoritative";
142
+ }
143
+ }
144
+
145
+ // The terminal lifecycle and exit code are primary evidence. Persist them
146
+ // before fact projection, which is secondary and may fail on a stale control
147
+ // record without turning completed work into lost work.
148
+ async function writeFinal(run, finalRecord, factOptions) {
149
+ await persist(run, finalRecord, "final persist");
150
+ await projectOutcomeFacts(run, finalRecord, factOptions);
151
+ if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
152
+ await completeRunRecord(finalRecord, run.live.run_count);
153
+ }
154
+
155
+ function failingCheckLabel(failing, results) {
156
+ if (!failing) return results.error ?? "see acceptance_results";
157
+ const why = failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code ?? "?");
158
+ return `${failing.command.slice(0, 80)} exit ${why}`;
159
+ }
160
+
161
+ async function runAcceptanceChecks(run, acceptance) {
162
+ const { record, live } = run;
163
+ const control = { kill: null, cancelled: false, isCancelled: () => control.cancelled };
164
+ acceptanceRuns.set(record.id, control);
165
+ // A fresh MCP has no in-memory acceptance handle. Consume its durable
166
+ // cancellation marker while a command runs, then stop subsequent checks.
167
+ const cancellationWatch = setInterval(async () => {
168
+ const current = await getTask(record.id).catch(() => null);
169
+ if (current?.cancel_requested_at) {
170
+ control.cancelled = true;
171
+ control.kill?.();
172
+ }
173
+ }, 100);
174
+ try {
175
+ return await runAcceptance(acceptance, {
176
+ cwd: record.cwd,
177
+ timeoutMs: live.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS,
178
+ run: live.run_count,
179
+ taskId: record.id,
180
+ baseCommit: live.base_commit,
181
+ control
182
+ });
183
+ } finally {
184
+ clearInterval(cancellationWatch);
185
+ }
186
+ }
187
+
188
+ // Acceptance runs after the worker is gone, in two writes. The first records
189
+ // the terminal status with exit_code still null and the run marked as this
190
+ // process's, so a wait keeps waiting and reconcile (which sees a dead codex
191
+ // pid) leaves the row alone; the second records exit_code and the verdict.
192
+ // changed_files is read before the checks run so build output they leave
193
+ // behind is not counted as the worker's.
194
+ async function settleWithAcceptance(run, next, acceptance, finishedAt) {
195
+ const { record, live } = run;
196
+ await persist(run, {
197
+ ...next,
198
+ exit_code: null,
199
+ signal: null,
200
+ current_action: "Running acceptance",
201
+ acceptance_results: { status: "running", passed: null, run: live.run_count, supervisor_pid: process.pid, started_at: finishedAt }
202
+ });
203
+ const results = await runAcceptanceChecks(run, acceptance);
204
+ acceptanceRuns.delete(record.id);
205
+ const event = { type: "supervisor.acceptance", ...results };
206
+ const acceptanceEvent = await appendTaskEvent(record.id, event, { runId: run.runId, actor: "supervisor" }).catch(() => null);
207
+ await appendFile(run.logPath, `${JSON.stringify(event)}\n`).catch(() => {});
208
+ const failing = results.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
209
+ const finalRecord = {
210
+ ...next,
211
+ acceptance_results: results,
212
+ current_action: results.status === "passed"
213
+ ? "Completed, acceptance passed"
214
+ : results.status === "failed"
215
+ ? `Acceptance failed: ${failingCheckLabel(failing, results)}`
216
+ : next.current_action,
217
+ updated_at: new Date().toISOString()
218
+ };
219
+ await writeFinal(run, finalRecord, { acceptanceEventId: acceptanceEvent?.id ?? null, acceptancePassed: results.passed === true });
220
+ }
221
+
222
+ export async function finalizeChild(run, code, signal) {
223
+ if (run.childSettled) return;
224
+ run.childSettled = true;
225
+ const { record } = run;
226
+ if (run.quotaWatch) clearInterval(run.quotaWatch);
227
+ processes.delete(record.id);
228
+ if (run.stdoutRest.trim()) queueEventLines(run, [run.stdoutRest]);
229
+ await run.eventChain.catch(() => {});
230
+ run.logStream.end();
231
+ const finishedAt = new Date().toISOString();
232
+ const stored = await getTask(record.id).catch(() => null);
233
+ const status = terminalStatus(run, stored, code, signal);
234
+ const next = terminalRow(run, status, code, signal, finishedAt);
235
+ await attachEvidence(run, next);
236
+ flagAttention(run, next, status, code);
237
+
238
+ const { live } = run;
239
+ const acceptance = Array.isArray(live.acceptance) && live.acceptance.length > 0 ? live.acceptance : null;
240
+ if (acceptance && (status === "completed" || status === "failed")) await settleWithAcceptance(run, next, acceptance, finishedAt);
241
+ else await writeFinal(run, acceptance ? { ...next, acceptance_results: null } : next);
242
+ cancelledTasks.delete(record.id);
243
+ }
@@ -0,0 +1,49 @@
1
+ // What a worker process is started with: the guard policy, the CLI arguments
2
+ // that install it, and the environment the worker's tools read.
3
+ import { workspaceSetupWriteRoots } from "../app/worktree-setup.js";
4
+ import { findOutsideOwnedChanges } from "../domain/owned-changes.js";
5
+ import { buildGuardPreamble } from "../domain/prompt.js";
6
+ import { withWorkerToolPath } from "../domain/worker-env.js";
7
+ import { cacheRoots } from "../infra/sandbox-roots.js";
8
+ import { runnerOf } from "../runners/registry.js";
9
+ import { dirname } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ function guardPolicyFor(record, externalBefore, outputSchema) {
13
+ const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
14
+ return { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
15
+ output_schema: outputSchema,
16
+ goalTokenBudget: record.goal_token_budget ?? null,
17
+ allowedCommands: [
18
+ ...(record.guard_policy?.allowedCommands ?? []),
19
+ ...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command),
20
+ // This CLI writes only data/stages/<this task>.json. It is part of the
21
+ // runtime contract, not an ad-hoc command the model must declare. The
22
+ // task id comes from the injected environment; stage.js has no override.
23
+ 'node "$AGENT_SUPERVISOR_STAGE_CLI"*',
24
+ 'node "$AGENT_SUPERVISOR_ACCEPTANCE_CLI"*'
25
+ ] };
26
+ }
27
+
28
+ // Directories the sandbox must let the worker write besides its worktree.
29
+ function writableRootsFor(record, externalBefore) {
30
+ return [...new Set([
31
+ ...externalBefore.map((file) => dirname(file.path)),
32
+ ...cacheRoots(),
33
+ ...workspaceSetupWriteRoots(record),
34
+ ...(record.guard_policy?.writableRoots ?? [])
35
+ ])];
36
+ }
37
+
38
+ export function buildLaunch({ record, args, prompt, outputSchema, externalBefore }) {
39
+ const guardPolicy = guardPolicyFor(record, externalBefore, outputSchema);
40
+ const stageCli = fileURLToPath(new URL("../interface/bin/stage.js", import.meta.url));
41
+ const acceptanceCli = fileURLToPath(new URL("../interface/bin/acceptance-cli.js", import.meta.url));
42
+ const guardedArgs = runnerOf(record).launchArgs({ args, record, outputSchema, writableRoots: writableRootsFor(record, externalBefore) });
43
+ const env = () => withWorkerToolPath({ ...process.env, NO_COLOR: "1", AGENT_SUPERVISOR_TASK_ID: record.id,
44
+ AGENT_SUPERVISOR_BASE_COMMIT: record.base_commit ?? "",
45
+ AGENT_SUPERVISOR_STAGE_CLI: stageCli,
46
+ AGENT_SUPERVISOR_ACCEPTANCE_CLI: acceptanceCli,
47
+ AGENT_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), AGENT_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) });
48
+ return { guardedArgs, prompt: `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`, env };
49
+ }
@@ -0,0 +1,76 @@
1
+ // The state of one run while its worker is alive, and the single serialized
2
+ // write path that keeps the task row in step with it. Every write goes through
3
+ // one chain so concurrent stdout/stderr callbacks cannot persist out of order.
4
+ import { terminateChild } from "../app/cancel.js";
5
+ import { runnerOf } from "../runners/registry.js";
6
+ import { runIdFor } from "../infra/store/db.js";
7
+ import { appendTaskEvent } from "../infra/store/events.js";
8
+ import { upsertTask } from "../infra/store/tasks.js";
9
+
10
+ // A new run starts clean. A resumed worker used to carry the error from the
11
+ // run that was lost, so a worker that was plainly running still showed
12
+ // "process disappeared" until it finished.
13
+ export function startingRow(record, child, outputSchema, now) {
14
+ return {
15
+ ...record,
16
+ status: "running",
17
+ phase: "starting",
18
+ pid: child.pid ?? null,
19
+ run_host_pid: process.pid,
20
+ started_at: now,
21
+ completed_at: null,
22
+ exit_code: null,
23
+ signal: null,
24
+ error: null,
25
+ // What an earlier run wrote to stderr says nothing about how this one ends.
26
+ stderr_tail: null,
27
+ cancel_requested_at: null,
28
+ acceptance_results: null,
29
+ attention_reason: null,
30
+ run_evidence: null,
31
+ guard_policy: { ...record.guard_policy, output_schema: outputSchema },
32
+ commands: [],
33
+ last_message: null,
34
+ current_action: null,
35
+ current_command: null,
36
+ // A resumed row still carries the last event of the run that ended;
37
+ // idle time for this run counts from now.
38
+ last_event_at: now,
39
+ last_event_type: null,
40
+ run_count: (record.run_count ?? 0) + 1,
41
+ updated_at: now
42
+ };
43
+ }
44
+
45
+ // Stops the worker when its per-run or total time budget runs out.
46
+ export function watchQuota(run, now) {
47
+ const maxRunMs = run.record.guard_policy?.maxRunMs;
48
+ const maxTotalMs = run.record.guard_policy?.maxTotalMs;
49
+ if (!maxRunMs && !maxTotalMs) return null;
50
+ return setInterval(() => {
51
+ if (run.quotaReason) return;
52
+ if (maxRunMs && Date.now() - Date.parse(now) >= maxRunMs) run.quotaReason = "run_time_limit";
53
+ else if (maxTotalMs && Date.now() - Date.parse(run.record.created_at) >= maxTotalMs) run.quotaReason = "total_time_limit";
54
+ if (run.quotaReason) terminateChild(run.child, runnerOf(run.record));
55
+ }, 250);
56
+ }
57
+
58
+ function writeSnapshot(run, next) {
59
+ run.live = next;
60
+ const snapshot = run.live;
61
+ const pending = run.writeChain.then(() => upsertTask(snapshot));
62
+ // Keep later writes usable after one failed snapshot. Callers that need
63
+ // failure visibility use the returned promise explicitly.
64
+ run.writeChain = pending.catch(() => {});
65
+ return pending;
66
+ }
67
+
68
+ export async function persist(run, next, label = "persist") {
69
+ try {
70
+ await writeSnapshot(run, next);
71
+ } catch (error) {
72
+ await appendTaskEvent(next.id, { type: "supervisor.persist_failed", label, error: error.message, run: next.run_count },
73
+ { runId: runIdFor(next.id, next.run_count), actor: "supervisor" }).catch(() => null);
74
+ process.stderr.write(`[agent-supervisor] ${label} failed for ${next.id}: ${error.message}\n`);
75
+ }
76
+ }