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,370 @@
1
+ // Side questions about a worker, the way Codex's own /btw (/side) does it:
2
+ // the worker's thread is forked into a separate session, the question is
3
+ // asked there, and the worker's thread is never touched. The fork runs in
4
+ // the worker's worktree with a read-only sandbox, so it can read anything on
5
+ // disk and change nothing. One side session per worker; the first turn forks,
6
+ // later turns resume the fork, "end" deletes the fork.
7
+ //
8
+ // A turn is streamed to the page as an AI SDK UI message stream (SSE). The
9
+ // page is only a viewer: every chunk is also kept on the turn row, so a page
10
+ // that left (tab switched, drawer closed, reload) comes back, replays what it
11
+ // missed and keeps receiving; a turn nobody watches still runs to the end and
12
+ // its answer is there when someone looks. Only an explicit stop kills a turn.
13
+ //
14
+ // States a page has to handle:
15
+ // worker without thread_id ........ cannot ask
16
+ // no side session ................. first question forks
17
+ // session idle .................... next question resumes the fork
18
+ // turn running, page attached ..... streaming
19
+ // turn running, nobody attached ... attach: replay + tail
20
+ // turn running, other page asked .. attach the same way, or stop it
21
+ // turn finished unwatched ......... answer in the history
22
+ // turn failed / timed out / stopped error on the turn, session still usable
23
+ // board restarted mid-turn ........ turn marked interrupted
24
+ // session ended ................... fork deleted, history cleared
25
+ import { ensureTaskWorktree } from "./restore-worktree.js";
26
+ import "./compose.js";
27
+ import { answerOf, partsFromChunks, turnView } from "../domain/side-turn-view.js";
28
+ import { closeSideSession, getSideSession, insertSideTurn, interruptRunningSideTurns, openSideSession, readSideTurns, setSideSessionFork, updateSideTurn } from "../infra/store/sessions.js";
29
+ import { getTask } from "../infra/store/tasks.js";
30
+ import { unsupported } from "../runners/contract.js";
31
+ import { loadRunner, runnerOf } from "../runners/registry.js";
32
+ import { endStream, sseHead, writeChunk } from "./sse.js";
33
+ import { randomUUID } from "node:crypto";
34
+
35
+ const TURN_TIMEOUT_MS = 10 * 60 * 1000;
36
+
37
+ // What a side question is, said to the fork every time. Without it the fork
38
+ // treats the question as a new task: one real fork spent its whole turn
39
+ // trying to ssh to a build host from inside the read-only sandbox, probing
40
+ // the network, and finally reaching for an MCP tool.
41
+ const SIDE_PREAMBLE = `This is a side question about the work you did in this thread, asked from a read-only fork. Rules for this turn:
42
+ - Answer from what you already know from this thread. You may read files in the working directory to check.
43
+ - The sandbox is read-only and has no network: do not try ssh, curl, builds, tests, package installs or writes; they will fail and waste the turn. MCP tools are disabled here.
44
+ - If answering properly needs something you cannot check from here (a remote machine, a running service, a command), say exactly what and stop; do not retry.
45
+ - Nothing you do here changes the work. If the work needs changing, say what should change; the main thread will ask the worker itself.
46
+ - Be direct and short. Lead with the answer.`;
47
+
48
+ export function sideQuestionText(question) {
49
+ return `${SIDE_PREAMBLE}\n\nQuestion:\n${question}`;
50
+ }
51
+
52
+ // The fork inherits the worker's MCP servers. A side question must not be
53
+ // able to dispatch, resume or cancel anything through them, and a fork that
54
+ // waits on a tool it cannot use burns its turn; every server named in the
55
+ // Codex config is switched off for the turn. Sub-tables
56
+ // ([mcp_servers.x.env]) are not servers and are skipped.
57
+ //
58
+ // A side question runs with none of the user's MCP servers: it only reads.
59
+ export function sideTurnConfigArgs(configText, runner = runnerOf(null)) {
60
+ return runner.sideChat.disableMcpServerArgs(configText);
61
+ }
62
+
63
+ // The session to ask on. A fork taken before the worker was resumed no
64
+ // longer reflects the worker's thread; it is dropped and a new one taken
65
+ // from the current thread. `fresh` forces that. Returns the session and why
66
+ // it was (re)opened: "requested", "worker_resumed", "first" or null.
67
+ export async function prepareSideSession(task, { fresh = false } = {}) {
68
+ let session = await getSideSession(task.id);
69
+ let refreshed = null;
70
+ const stale =
71
+ session?.fork_thread_id &&
72
+ session.worker_run_count !== null &&
73
+ session.worker_run_count !== undefined &&
74
+ (task.run_count ?? 0) > session.worker_run_count;
75
+ if (session && (fresh || stale)) {
76
+ await endSideSession(task.id);
77
+ session = null;
78
+ refreshed = fresh ? "requested" : "worker_resumed";
79
+ }
80
+ if (!session) {
81
+ session = await openSideSession(task.id, task.run_count ?? 0);
82
+ refreshed = refreshed ?? "first";
83
+ }
84
+ return { session, refreshed };
85
+ }
86
+
87
+ // taskId -> { turnId, child, chunks, watchers: Set<res>, startedAt, question, state }
88
+ const running = new Map();
89
+
90
+ let swept = false;
91
+ async function sweepOnce() {
92
+ if (swept) return;
93
+ swept = true;
94
+ await interruptRunningSideTurns();
95
+ }
96
+
97
+ // ---- public API
98
+
99
+ export async function sideSessionState(taskId) {
100
+ await sweepOnce();
101
+ const session = await getSideSession(taskId);
102
+ const live = running.get(taskId) ?? null;
103
+ const turns = (await readSideTurns(taskId)).map((t) => ({
104
+ id: t.id,
105
+ question: t.question,
106
+ status: t.status,
107
+ started_at: t.started_at,
108
+ ended_at: t.ended_at,
109
+ usage: t.usage,
110
+ error: t.error,
111
+ parts: partsFromChunks(t.chunks)
112
+ }));
113
+ return {
114
+ active: Boolean(session),
115
+ fork_thread_id: session?.fork_thread_id ?? null,
116
+ busy: Boolean(live),
117
+ busy_since: live?.startedAt ?? null,
118
+ busy_turn_id: live?.turnId ?? null,
119
+ watchers: live ? live.watchers.size : 0,
120
+ turns
121
+ };
122
+ }
123
+
124
+ // Attach a page to the running turn: replay what it has produced so far,
125
+ // then keep it in the audience. 204 when nothing is running.
126
+ export function attachToTurn(taskId, res) {
127
+ const live = running.get(taskId);
128
+ if (!live) {
129
+ res.writeHead(204);
130
+ res.end();
131
+ return false;
132
+ }
133
+ sseHead(res);
134
+ for (const chunk of live.chunks) writeChunk(res, chunk);
135
+ live.watchers.add(res);
136
+ res.on("close", () => live.watchers.delete(res));
137
+ return true;
138
+ }
139
+
140
+ function startSideChild(target, task, session) {
141
+ const runner = runnerOf(task);
142
+ const side = runner.sideChat;
143
+ const forkArgs = side.forkArgs({ forkThreadId: session.fork_thread_id, workerThreadId: task.thread_id, model: task.model });
144
+ const args = side.withConfig(forkArgs, sideTurnConfigArgs(side.configText(), runner));
145
+ const cwd = task.worktree_path || task.project_root || process.cwd();
146
+ return runner.start(target, args, {
147
+ cwd,
148
+ stdio: ["pipe", "pipe", "pipe"],
149
+ env: { ...process.env, NO_COLOR: "1" },
150
+ windowsHide: true
151
+ });
152
+ }
153
+
154
+ // The in-memory side of a running turn: its chunks so far, who is watching,
155
+ // and how it was stopped. Chunks are written through to the store in batches.
156
+ async function openLiveTurn(task, text, child) {
157
+ const turnId = `turn-${Date.now()}-${randomUUID().slice(0, 8)}`;
158
+ const startedAt = new Date().toISOString();
159
+ const state = { toolsSeen: new Set(), completed: false, failed: false, usage: null };
160
+ const live = { turnId, child, chunks: [], watchers: new Set(), startedAt, question: text, state, stderr: "", stoppedBy: null, persistTimer: null,
161
+ chunksFor: runnerOf(task).sideChat.chunksFor };
162
+ const persistSoon = () => {
163
+ if (live.persistTimer) return;
164
+ live.persistTimer = setTimeout(() => {
165
+ live.persistTimer = null;
166
+ updateSideTurn(turnId, { chunks: live.chunks }).catch(() => {});
167
+ }, 250);
168
+ };
169
+ live.broadcast = (chunk) => {
170
+ live.chunks.push(chunk);
171
+ for (const w of live.watchers) writeChunk(w, chunk);
172
+ persistSoon();
173
+ };
174
+ live.stop = (reason) => {
175
+ live.stoppedBy = reason;
176
+ runnerOf(task).cancelChild(child);
177
+ };
178
+ running.set(task.id, live);
179
+ await insertSideTurn({ id: turnId, task_id: task.id, question: text, status: "running", chunks: [], started_at: startedAt });
180
+ return live;
181
+ }
182
+
183
+ function pipeSideOutput(child, live, session, taskId) {
184
+ let rest = "";
185
+ child.stdout.setEncoding("utf8");
186
+ child.stdout.on("data", (chunk) => {
187
+ rest += chunk;
188
+ let nl;
189
+ while ((nl = rest.indexOf("\n")) !== -1) {
190
+ const line = rest.slice(0, nl).trim();
191
+ rest = rest.slice(nl + 1);
192
+ if (!line) continue;
193
+ let event;
194
+ try {
195
+ event = JSON.parse(line);
196
+ } catch {
197
+ continue;
198
+ }
199
+ if (event.type === "thread.started" && !session.fork_thread_id && event.thread_id) {
200
+ session.fork_thread_id = event.thread_id;
201
+ setSideSessionFork(taskId, event.thread_id).catch(() => {});
202
+ }
203
+ for (const part of live.chunksFor(event, live.state)) live.broadcast(part);
204
+ }
205
+ });
206
+ child.stderr.setEncoding("utf8");
207
+ child.stderr.on("data", (chunk) => {
208
+ live.stderr = (live.stderr + chunk).slice(-4000);
209
+ });
210
+ }
211
+
212
+ // How the turn ended, and the error to show when it did not complete.
213
+ function sideTurnOutcome(live, code, signal) {
214
+ if (live.state.failed) return { status: "failed", error: live.chunks.find((c) => c.type === "error")?.errorText ?? "Codex turn failed", announce: false };
215
+ if (live.state.completed) return { status: "completed", error: null, announce: false };
216
+ if (live.stoppedBy === "timeout") {
217
+ return { status: "timed_out", error: `the side turn ran past ${TURN_TIMEOUT_MS / 60000} minutes and was stopped`, announce: true };
218
+ }
219
+ if (live.stoppedBy) return { status: "stopped", error: "stopped", announce: true };
220
+ const tail = live.stderr.trim().split("\n").filter((l) => !l.includes("rmcp::transport")).slice(-3).join("\n");
221
+ const why = signal ? `stopped by ${signal}` : `codex exited with code ${code}`;
222
+ return { status: "failed", error: tail ? `${why}: ${tail}` : why, announce: true };
223
+ }
224
+
225
+ async function settleSideTurn(live, taskId, code, signal) {
226
+ if (live.persistTimer) clearTimeout(live.persistTimer);
227
+ const { status, error, announce } = sideTurnOutcome(live, code, signal);
228
+ if (announce) live.broadcast({ type: "error", errorText: error });
229
+ live.broadcast({ type: "finish" });
230
+ for (const w of live.watchers) endStream(w);
231
+ live.watchers.clear();
232
+ running.delete(taskId);
233
+ await updateSideTurn(live.turnId, { status, chunks: live.chunks, usage: live.state.usage, error, ended_at: new Date().toISOString() }).catch(() => {});
234
+ return status;
235
+ }
236
+
237
+ // For a caller that only wants to know whether to offer the question box.
238
+ export function supportsSideChat(task) {
239
+ try {
240
+ return runnerOf(task).capabilities.side_chat === true;
241
+ } catch {
242
+ return false; // a runner this process has not loaded
243
+ }
244
+ }
245
+
246
+ // Checked before a session row is opened, so a runner without a side chat leaves nothing behind.
247
+ export async function requireSideChat(task) {
248
+ const runner = await loadRunner(task.worker);
249
+ if (!runner.capabilities.side_chat) throw unsupported(runner, "side_chat", "asking a worker a side question");
250
+ return runner;
251
+ }
252
+
253
+ // Start a turn. `res` (optional) becomes the first watcher. Resolves when the
254
+ // turn has ended, however it ended.
255
+ export async function runSideTurn({ task, text, res = null, fresh = false }) {
256
+ await sweepOnce();
257
+ const runner = await requireSideChat(task);
258
+ if (!task.thread_id) throw Object.assign(new Error("this worker recorded no thread_id, so there is no thread to fork"), { code: "no_thread" });
259
+ if (running.has(task.id)) throw Object.assign(new Error("a side turn is already running for this worker"), { code: "busy" });
260
+ const target = runner.resolveTarget();
261
+ if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
262
+
263
+ const { session, refreshed } = await prepareSideSession(task, { fresh });
264
+ // The fork reads the worker's files; a cleaned-up worktree comes back from its branch.
265
+ await ensureTaskWorktree(task);
266
+ const child = startSideChild(target, task, session);
267
+ const live = await openLiveTurn(task, text, child);
268
+ if (res) {
269
+ sseHead(res);
270
+ live.watchers.add(res);
271
+ res.on("close", () => live.watchers.delete(res));
272
+ }
273
+ live.broadcast({ type: "start", messageId: live.turnId });
274
+ const timer = setTimeout(() => live.stop("timeout"), TURN_TIMEOUT_MS);
275
+ pipeSideOutput(child, live, session, task.id);
276
+ child.stdin.on("error", () => {});
277
+ child.stdin.end(sideQuestionText(text));
278
+
279
+ return new Promise((resolve) => {
280
+ const finish = async (code, signal) => {
281
+ clearTimeout(timer);
282
+ const status = await settleSideTurn(live, task.id, code, signal);
283
+ resolve({ status, turnId: live.turnId, forkThreadId: session.fork_thread_id, refreshed });
284
+ };
285
+ child.on("error", (error) => {
286
+ live.stderr += `\nfailed to start codex: ${error.message}`;
287
+ finish(-1, null);
288
+ });
289
+ child.on("exit", finish);
290
+ });
291
+ }
292
+
293
+ // The newest side turn of a worker, for a caller that asked earlier and
294
+ // comes back for the answer. Null when nothing was ever asked.
295
+ export async function latestSideTurn(taskId) {
296
+ await sweepOnce();
297
+ const turns = await readSideTurns(taskId);
298
+ const live = running.get(taskId) ?? null;
299
+ const latest = turns.at(-1) ?? null;
300
+ const session = await getSideSession(taskId);
301
+ if (!latest) return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: null };
302
+ const view = turnView(latest);
303
+ if (live && live.turnId === latest.id) {
304
+ view.status = "running";
305
+ view.answer = answerOf({ chunks: live.chunks });
306
+ }
307
+ return { active: Boolean(session), fork_thread_id: session?.fork_thread_id ?? null, busy: Boolean(live), turn: view };
308
+ }
309
+
310
+ // Ask the worker a question on the side, without touching its own thread,
311
+ // and wait up to `timeoutMs` for the answer. A turn that outlives the budget
312
+ // keeps running in this process; the caller reads it back with latestSideTurn.
313
+ export async function askWorker({ task, question, timeoutMs = 110000, fresh = false }) {
314
+ // Decided here, before the race, so a turn that outruns the budget still
315
+ // reports whether the fork was taken anew.
316
+ await requireSideChat(task);
317
+ const { refreshed } = await prepareSideSession(task, { fresh });
318
+ const turn = runSideTurn({ task, text: question });
319
+ // runSideTurn throws synchronously-ish (rejected promise) for no_thread,
320
+ // busy and codex_missing before anything starts; surface those as-is.
321
+ let timer;
322
+ const budget = new Promise((resolve) => {
323
+ timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
324
+ });
325
+ try {
326
+ const outcome = await Promise.race([turn.then((r) => ({ timedOut: false, ...r })), budget]);
327
+ if (!outcome.timedOut) {
328
+ const state = await latestSideTurn(task.id);
329
+ return { ...state, timed_out: false, refreshed };
330
+ }
331
+ turn.catch(() => {});
332
+ const state = await latestSideTurn(task.id);
333
+ return { ...state, timed_out: true, refreshed };
334
+ } finally {
335
+ clearTimeout(timer);
336
+ }
337
+ }
338
+
339
+ export function stopSideTurn(taskId) {
340
+ const live = running.get(taskId);
341
+ if (!live) return { stopped: false };
342
+ live.stop("user");
343
+ return { stopped: true, turn_id: live.turnId };
344
+ }
345
+
346
+ // Close the side session: stop a running turn, delete the fork so it does
347
+ // not pile up in Codex's session list, forget the history.
348
+ export async function endSideSession(taskId) {
349
+ const live = running.get(taskId);
350
+ if (live) live.stop("ended");
351
+ const row = await closeSideSession(taskId);
352
+ if (!row) return { ended: false };
353
+ let deleted = false;
354
+ if (row.fork_thread_id) {
355
+ // The task may be gone and its runner not loaded here; then the fork is left to the CLI's own housekeeping.
356
+ const stored = await getTask(taskId);
357
+ const runner = stored ? await loadRunner(stored.worker).catch(() => null) : null;
358
+ const target = runner?.capabilities.side_chat ? runner.resolveTarget() : { error: "no runner" };
359
+ if (!target.error) {
360
+ deleted = await new Promise((resolve) => {
361
+ // --force: without a terminal codex asks for confirmation and exits.
362
+ const child = runner.start(target, runner.sideChat.deleteArgs(row.fork_thread_id), { stdio: "ignore", windowsHide: true, env: { ...process.env, NO_COLOR: "1" } });
363
+ const t = setTimeout(() => { runner.cancelChild(child); resolve(false); }, 15000);
364
+ child.on("exit", (code) => { clearTimeout(t); resolve(code === 0); });
365
+ child.on("error", () => { clearTimeout(t); resolve(false); });
366
+ });
367
+ }
368
+ }
369
+ return { ended: true, fork_thread_id: row.fork_thread_id, deleted };
370
+ }
package/src/app/sse.js ADDED
@@ -0,0 +1,20 @@
1
+ // Server-sent events plumbing for the side chat stream.
2
+ // ---- stream plumbing
3
+
4
+ export function sseHead(res) {
5
+ res.writeHead(200, {
6
+ "content-type": "text/event-stream; charset=utf-8",
7
+ "cache-control": "no-cache, no-transform",
8
+ connection: "keep-alive",
9
+ "x-vercel-ai-ui-message-stream": "v1",
10
+ "x-accel-buffering": "no"
11
+ });
12
+ }
13
+
14
+ export function writeChunk(res, chunk) {
15
+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
16
+ }
17
+
18
+ export function endStream(res) {
19
+ if (!res.writableEnded) res.end("data: [DONE]\n\n");
20
+ }
@@ -0,0 +1,77 @@
1
+ import "./compose.js";
2
+ import { spawnProcess } from "../infra/process.js";
3
+ import { upsertTask } from "../infra/store/tasks.js";
4
+ import { compileWorkerContext } from "./context-compiler.js";
5
+ import { failedStart, MAX_RUN_HOST_PROMPT_BYTES, RUN_HOST_STARTUP_TIMEOUT_MS } from "./run-state.js";
6
+ import { closeSync, openSync } from "node:fs";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ // The MCP client may disappear at any point. A detached process owns the
10
+ // streams, exit write and acceptance until all three settle; IPC is only a
11
+ // startup handshake and never the channel carrying worker results.
12
+ export async function startTrackedRun(job) {
13
+ if (Buffer.byteLength(String(job.prompt ?? ""), "utf8") > MAX_RUN_HOST_PROMPT_BYTES) {
14
+ const result = failedStart(job.record, `worker prompt is too large for the detached run host IPC channel (maximum ${MAX_RUN_HOST_PROMPT_BYTES} bytes); reduce task text and move materials to context files`);
15
+ await upsertTask(result.record);
16
+ return result;
17
+ }
18
+ const compiled = await compileWorkerContext(job.record, { attempt: (job.record.run_count ?? 0) + 1 });
19
+ job.record = {
20
+ ...job.record,
21
+ input_context: {
22
+ ...job.record.input_context,
23
+ context: compiled.sourceRefs,
24
+ source_refs: compiled.sourceRefs,
25
+ content_hash: compiled.contentHash,
26
+ context_snapshot_id: compiled.snapshot.id,
27
+ context_snapshot_tokens: compiled.snapshot.estimated_tokens,
28
+ context_fact_count: compiled.factCount
29
+ }
30
+ };
31
+ job.prompt = `${compiled.text}\n\n${job.prompt}\n\nRequired input refs (read-only): ${JSON.stringify(compiled.sourceRefs)}\nRequired contracts: ${JSON.stringify(job.record.input_context.contracts ?? [])}`;
32
+ const hostLogPath = job.logPath.endsWith(".jsonl")
33
+ ? job.logPath.replace(/\.jsonl$/, ".host.log")
34
+ : `${job.logPath}.host.log`;
35
+ let hostLogFd;
36
+ try {
37
+ hostLogFd = openSync(hostLogPath, "a");
38
+ } catch (error) {
39
+ const result = failedStart(job.record, `cannot open run host log ${hostLogPath}: ${error.message}`);
40
+ await upsertTask(result.record);
41
+ return result;
42
+ }
43
+ let host;
44
+ try {
45
+ host = spawnProcess(process.execPath, [fileURLToPath(new URL("../run-host/entry.js", import.meta.url)), "--run-host"], {
46
+ detached: true, stdio: ["ignore", hostLogFd, hostLogFd, "ipc"],
47
+ env: process.env, windowsHide: true
48
+ });
49
+ } finally {
50
+ closeSync(hostLogFd);
51
+ }
52
+ const started = await new Promise((resolveStart) => {
53
+ let settled = false;
54
+ const finish = (result) => {
55
+ if (settled) return;
56
+ settled = true;
57
+ clearTimeout(timer);
58
+ host.removeAllListeners("message");
59
+ host.removeAllListeners("exit");
60
+ if (host.connected) host.disconnect();
61
+ host.unref();
62
+ resolveStart(result);
63
+ };
64
+ const timer = setTimeout(() => {
65
+ host.kill();
66
+ finish(failedStart(job.record, "run host startup timed out"));
67
+ }, RUN_HOST_STARTUP_TIMEOUT_MS);
68
+ host.once("message", finish);
69
+ host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
70
+ host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
71
+ host.send(job, (error) => {
72
+ if (error) finish(failedStart(job.record, `run host IPC failed: ${error.message}`));
73
+ });
74
+ });
75
+ if (!started.ok) await upsertTask(started.record);
76
+ return started;
77
+ }
@@ -0,0 +1,114 @@
1
+ // Proves a landed commit is on a remote branch. Read-only towards the remote:
2
+ // it fetches and compares, and never pushes or deploys.
3
+ import "./compose.js";
4
+ import { runGit } from "../infra/git.js";
5
+ import { appendTaskEvent } from "../infra/store/events.js";
6
+ import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
7
+ import { recordJsonArtifact, updateWorkItemDelivery } from "../infra/store/records.js";
8
+ import { getTask, upsertTask } from "../infra/store/tasks.js";
9
+ import { runIdFor } from "../infra/store/db.js";
10
+
11
+ const git = (cwd, args) => runGit(cwd, args, { timeout: 60000 });
12
+
13
+ async function recordPushFacts(task, proof, { eventId, artifactId }) {
14
+ const workItem = await getWorkItemForTask(task.id);
15
+ if (!workItem) return;
16
+ const { remote, branch, remoteHead } = proof;
17
+ const shared = {
18
+ workItemId: workItem.id,
19
+ scopeId: workItem.id,
20
+ state: "verified",
21
+ sourceEventId: eventId,
22
+ sourceArtifactId: artifactId,
23
+ validForSha: task.landed_head,
24
+ watchedPaths: task.owned_paths ?? [],
25
+ verifiedBy: "supervisor.remote_readback"
26
+ };
27
+ await recordFact({
28
+ ...shared,
29
+ scopeType: "work_item",
30
+ key: "push_verified",
31
+ value: { remote, branch, landed_head: task.landed_head, remote_head: remoteHead }
32
+ });
33
+ await recordFact({
34
+ ...shared,
35
+ scopeType: "dependency",
36
+ key: "push_delivery_summary",
37
+ value: { task_id: task.id, landed_head: task.landed_head, remote, branch, remote_head: remoteHead }
38
+ });
39
+ }
40
+
41
+ // Writes the task row, the delivery state, the event, the proof artifact and the facts.
42
+ async function recordPushVerified(task, proof) {
43
+ const { remote, branch, remoteHead } = proof;
44
+ const now = new Date().toISOString();
45
+ await upsertTask({ ...task, push_verified_at: now, push_remote: remote, push_branch: branch, push_remote_head: remoteHead, updated_at: now });
46
+ await updateWorkItemDelivery(task.id, "push_verified");
47
+ const runId = runIdFor(task.id, task.run_count ?? 1);
48
+ const event = await appendTaskEvent(task.id, {
49
+ type: "supervisor.push_verified",
50
+ remote,
51
+ branch,
52
+ landed_head: task.landed_head,
53
+ remote_head: remoteHead,
54
+ verified_at: now
55
+ }, { runId, actor: "supervisor" });
56
+ const artifact = await recordJsonArtifact({
57
+ runId,
58
+ type: "push_proof",
59
+ value: { remote, branch, landed_head: task.landed_head, remote_head: remoteHead, verified_at: now, event_id: event.id },
60
+ securityClass: "internal"
61
+ });
62
+ await recordPushFacts(task, proof, { eventId: event.id, artifactId: artifact.id });
63
+ return { now, artifact };
64
+ }
65
+
66
+ function remoteHeadOf(task, remote, branch) {
67
+ git(task.project_root, ["remote", "get-url", remote]);
68
+ git(task.project_root, ["fetch", "--no-tags", remote, `refs/heads/${branch}`]);
69
+ return git(task.project_root, ["rev-parse", "FETCH_HEAD"]);
70
+ }
71
+
72
+ function reaches(task, remoteHead) {
73
+ try {
74
+ git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, remoteHead]);
75
+ return true;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ export async function verifyDeliveryPush({ taskId, remote, branch }) {
82
+ const task = await getTask(taskId);
83
+ if (!task) return { error: "task_not_found", task_id: taskId };
84
+ const targetBranch = branch ?? task.landed_branch;
85
+ if (!task.landed_at || !task.landed_head || !targetBranch) {
86
+ return { error: "not_landed", task_id: taskId, reason: "land the worker first; this task has no landed head and branch to verify" };
87
+ }
88
+ try {
89
+ const remoteHead = remoteHeadOf(task, remote, targetBranch);
90
+ if (!reaches(task, remoteHead)) {
91
+ return {
92
+ error: "not_pushed",
93
+ task_id: taskId,
94
+ remote,
95
+ branch: targetBranch,
96
+ landed_head: task.landed_head,
97
+ remote_head: remoteHead,
98
+ reason: "landed_head is not reachable from the fetched remote branch"
99
+ };
100
+ }
101
+ const { now, artifact } = await recordPushVerified(task, { remote, branch: targetBranch, remoteHead });
102
+ return {
103
+ task_id: taskId,
104
+ remote,
105
+ branch: targetBranch,
106
+ landed_head: task.landed_head,
107
+ remote_head: remoteHead,
108
+ artifact_id: artifact.id,
109
+ push_verified_at: now
110
+ };
111
+ } catch (error) {
112
+ return { error: "push_verification_failed", task_id: taskId, remote, branch: targetBranch, reason: error.message.split("\n")[0] };
113
+ }
114
+ }