codex-supervisor-mcp 0.7.3 → 0.9.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.
@@ -2,24 +2,40 @@ import { createWriteStream, existsSync } from "node:fs";
2
2
  import { mkdir, rm, stat } from "node:fs/promises";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { execFileSync, spawn } from "node:child_process";
5
- import { join, resolve, sep } from "node:path";
5
+ import { join, resolve, sep, dirname } from "node:path";
6
+ import { fileURLToPath } from "node:url";
6
7
  import {
7
8
  appendTaskEvent,
8
9
  getTask,
10
+ getSession,
9
11
  readActiveTasks,
12
+ readTasks,
13
+ readTasksBySession,
10
14
  readTaskEvents,
11
15
  taskRunPath,
12
16
  upsertSession,
13
- upsertTask
17
+ upsertTask,
18
+ claimTaskRun,
19
+ releaseTaskRun,
20
+ reserveTaskOwnership
14
21
  } from "./task-store.js";
15
22
  import { applyCodexEvent } from "./event-parser.js";
16
- import { TERMINAL_STATUSES } from "./status.js";
23
+ import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
17
24
  import { worktreesDir } from "./paths.js";
18
- import { withGoalPreamble } from "./prompt.js";
19
- import { readTaskChanges } from "./worktree.js";
25
+ import { frameWorkerPrompt } from "./prompt.js";
26
+ import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
27
+ import { rebaseWorktree } from "./landing.js";
28
+ import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance, runAcceptance } from "./acceptance.js";
29
+ import { appendFile } from "node:fs/promises";
20
30
  import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
31
+ import { findOutsideOwnedChanges } from "./owned-changes.js";
32
+ import { parseWorkerReport, workerReportSchemaPath } from "./worker-report.js";
33
+ import { buildHandoff } from "./handoff.js";
34
+ import { captureExternalOutputs, compareExternalOutputs } from "./external-output.js";
21
35
 
22
36
  const processes = new Map();
37
+ // taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
38
+ const acceptanceRuns = new Map();
23
39
  const cancelledTasks = new Set();
24
40
  const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
25
41
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
@@ -97,8 +113,9 @@ async function ensureWorktree(cwd, taskId, baseRef = null) {
97
113
  await runCommand(defaultGitBin, ["-C", taskWorktreeDir, "switch", "-c", branch]);
98
114
  return { path: taskWorktreeDir, baseCommit };
99
115
  } catch (error) {
100
- if (baseRef) throw error;
101
- return { path: null, baseCommit: null };
116
+ const failure = new Error(`could not create isolated worker checkout: ${error.message}`);
117
+ failure.code = "worktree_creation_failed";
118
+ throw failure;
102
119
  }
103
120
  }
104
121
 
@@ -178,6 +195,7 @@ function failedStart(record, reason) {
178
195
  phase: null,
179
196
  pid: null,
180
197
  error: reason,
198
+ attention_reason: "start_failed",
181
199
  completed_at: now,
182
200
  updated_at: now
183
201
  }
@@ -210,13 +228,35 @@ async function spawnAndAwaitStart(target, args, options) {
210
228
  // Attaches stream handlers and keeps `record` in the supervisor database.
211
229
  // Every write goes through one serialized chain so concurrent stdout/stderr
212
230
  // callbacks cannot interleave and persist out of order.
213
- async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {} }) {
231
+ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {} }) {
214
232
  const target = codexTarget();
215
233
  if (target.error) return failedStart(record, target.error);
234
+ try {
235
+ const help = execFileSync(target.cmd, [...target.prefixArgs, "exec", "--help"], { encoding: "utf8", timeout: 15000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
236
+ if (!help.includes("--dangerously-bypass-hook-trust") || !help.includes("--output-schema")) return failedStart(record, "Codex CLI lacks required per-run hooks/output-schema; install Codex 0.162 or newer before dispatch");
237
+ } catch (error) { return failedStart(record, error.code === "ENOENT"
238
+ ? `failed to spawn ${target.cmd} for Codex capability preflight: ${error.message}`
239
+ : `Codex capability preflight failed: ${error.message}`); }
240
+ const outputBefore = snapshotTaskOutput(record);
241
+ const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
242
+ const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
243
+ const guardPolicy = { cwd: record.cwd, ownedPaths: owned, ...(record.guard_policy ?? {}),
244
+ allowedCommands: [...(record.guard_policy?.allowedCommands ?? []), ...(record.acceptance ?? []).map((check) => typeof check === "string" ? check : check.command)] };
245
+ const guard = fileURLToPath(new URL("./tool-guard.js", import.meta.url));
246
+ const quoteCommand = (path) => process.platform === "win32" ? `"${path.replace(/"/g, '""')}"` : `'${path.replace(/'/g, "'\\''")}'`;
247
+ const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
248
+ const configArgs = ["--output-schema", workerReportSchemaPath, "--dangerously-bypass-hook-trust", "-c",
249
+ `hooks.PreToolUse=[{matcher="Bash|apply_patch",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
250
+ configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
251
+ if (externalBefore.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify([...new Set(externalBefore.map((file) => dirname(file.path)))])}`);
252
+ // Insert before the prompt/session positional arguments for exec/resume.
253
+ const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
254
+ prompt = `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(owned)}. Shell verification must exactly match declared commands ${JSON.stringify(guardPolicy.allowedCommands)}. Forbidden: ${JSON.stringify(guardPolicy.forbid ?? [])}. Undeclared shell programs are denied; report a needed validation command instead of bypassing the guard.\n\n${prompt}`;
216
255
 
217
- const { child, spawnError } = await spawnAndAwaitStart(target, args, {
256
+ const { child, spawnError } = await spawnAndAwaitStart(target, guardedArgs, {
218
257
  stdio: ["pipe", "pipe", "pipe"],
219
- env: { ...process.env, NO_COLOR: "1" },
258
+ env: { ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
259
+ CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) },
220
260
  windowsHide: true,
221
261
  ...spawnOptions
222
262
  });
@@ -234,17 +274,37 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
234
274
  status: "running",
235
275
  phase: "starting",
236
276
  pid: child.pid ?? null,
277
+ run_host_pid: process.pid,
237
278
  started_at: now,
238
279
  completed_at: null,
239
280
  exit_code: null,
240
281
  signal: null,
241
282
  error: null,
283
+ cancel_requested_at: null,
284
+ acceptance_results: null,
285
+ attention_reason: null,
286
+ run_evidence: null,
287
+ commands: [],
288
+ last_message: null,
242
289
  current_action: null,
243
290
  current_command: null,
291
+ // A resumed row still carries the last event of the run that ended;
292
+ // idle time for this run counts from now.
293
+ last_event_at: now,
294
+ last_event_type: null,
244
295
  run_count: (record.run_count ?? 0) + 1,
245
296
  updated_at: now
246
297
  };
247
298
  processes.set(record.id, child);
299
+ let quotaReason = null;
300
+ const maxRunMs = record.guard_policy?.maxRunMs;
301
+ const maxTotalMs = record.guard_policy?.maxTotalMs;
302
+ const quotaWatch = maxRunMs || maxTotalMs ? setInterval(() => {
303
+ if (quotaReason) return;
304
+ if (maxRunMs && Date.now() - Date.parse(now) >= maxRunMs) quotaReason = "run_time_limit";
305
+ else if (maxTotalMs && Date.now() - Date.parse(record.created_at) >= maxTotalMs) quotaReason = "total_time_limit";
306
+ if (quotaReason) terminateChild(child);
307
+ }, 250) : null;
248
308
 
249
309
  let writeChain = Promise.resolve();
250
310
  const persist = (next) => {
@@ -257,6 +317,7 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
257
317
  });
258
318
  return writeChain;
259
319
  };
320
+ await persist(live);
260
321
 
261
322
  const logStream = createWriteStream(logPath, { flags: "a" });
262
323
  logStream.on("error", () => {});
@@ -272,6 +333,8 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
272
333
  });
273
334
 
274
335
  let eventChain = Promise.resolve();
336
+ let terminalEvent = false;
337
+ let rawReport = null;
275
338
  const handleLine = async (line) => {
276
339
  let event;
277
340
  try {
@@ -281,6 +344,8 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
281
344
  return;
282
345
  }
283
346
  logStream.write(`${JSON.stringify(event)}\n`);
347
+ if (event.type === "item.completed" && event.item?.type === "agent_message") rawReport = event.item.text;
348
+ if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
284
349
  await appendTaskEvent(record.id, event);
285
350
  await persist(applyCodexEvent(live, event));
286
351
  };
@@ -313,8 +378,12 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
313
378
  });
314
379
  });
315
380
 
316
- child.on("exit", async (code, signal) => {
381
+ child.on("close", async (code, signal) => {
382
+ if (quotaWatch) clearInterval(quotaWatch);
317
383
  processes.delete(record.id);
384
+ if (stdoutRest.trim()) eventChain = eventChain.then(() => handleLine(stdoutRest)).catch((error) => {
385
+ process.stderr.write(`[codex-supervisor] final event failed for ${record.id}: ${error.message}\n`);
386
+ });
318
387
  await eventChain.catch(() => {});
319
388
  logStream.end();
320
389
  const finishedAt = new Date().toISOString();
@@ -326,12 +395,12 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
326
395
  || Boolean(stored?.cancel_requested_at);
327
396
  let status;
328
397
  if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) status = stored.status;
329
- else if (TERMINAL_STATUSES.has(live.status) && live.status !== "failed") status = live.status;
398
+ else if (terminalEvent && TERMINAL_STATUSES.has(live.status)) status = live.status;
330
399
  else if (cancelRequested) status = "cancelled";
331
400
  // Killed by a signal nobody asked for: the worker did not fail, it
332
401
  // vanished. Re-running is the fix, so it is reported as lost.
333
402
  else if (signal) status = "lost";
334
- else if (code === 0) status = "completed";
403
+ else if (code === 0) status = "lost";
335
404
  else status = "failed";
336
405
  const next = {
337
406
  ...live,
@@ -349,10 +418,86 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
349
418
  next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
350
419
  }
351
420
  if (status === "lost" && !next.error) {
352
- next.error = `codex worker was killed by signal ${signal} before writing a terminal event`;
421
+ next.error = signal ? `codex worker was killed by signal ${signal} before writing a terminal event` : "Codex worker exited without recording a terminal event";
353
422
  }
354
423
  if (status === "cancelled") next.error = null;
355
- await persist(next);
424
+ if (quotaReason) { next.attention_reason = quotaReason; next.error = `Supervisor time quota exceeded: ${quotaReason}; inspect partial work before changing the budget`; }
425
+ const outputAfter = snapshotTaskOutput(live);
426
+ let externalChanges = [];
427
+ try { externalChanges = compareExternalOutputs(externalBefore, await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [])); }
428
+ catch (error) { next.attention_reason = "external_output_unverified"; next.error = error.message; }
429
+ next.run_evidence = {
430
+ run: live.run_count, commands_run: live.commands.length,
431
+ structured_report: parseWorkerReport(rawReport),
432
+ output_before: outputBefore, output_after: outputAfter,
433
+ output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null
434
+ };
435
+ next.run_evidence.external_outputs = externalChanges;
436
+ if (externalChanges.some((entry) => entry.changed)) next.run_evidence.output_changed = true;
437
+ next.changed_files = [...new Set([...next.changed_files, ...externalChanges.filter((entry) => entry.changed).map((entry) => entry.path)])];
438
+ if (status === "completed" && code === 0 && live.sandbox !== "read-only"
439
+ && !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
440
+ && live.commands.length === 0) next.attention_reason = "no_work";
441
+ if (status === "completed" && !next.run_evidence.structured_report.valid) {
442
+ next.status = "failed";
443
+ next.attention_reason = "invalid_report";
444
+ next.error = `Invalid final worker report: ${next.run_evidence.structured_report.error}`;
445
+ }
446
+
447
+ // Acceptance runs after the worker is gone, in two writes. The first
448
+ // records the terminal status with exit_code still null and the run
449
+ // marked as this process's, so a wait keeps waiting and reconcile
450
+ // (which sees a dead codex pid) leaves the row alone; the second
451
+ // records exit_code and the verdict. changed_files is read before the
452
+ // checks run so build output they leave behind is not counted as the
453
+ // worker's.
454
+ const acceptance = Array.isArray(live.acceptance) && live.acceptance.length > 0 ? live.acceptance : null;
455
+ if (acceptance && (status === "completed" || status === "failed")) {
456
+ const control = { kill: null, cancelled: false, isCancelled: () => control.cancelled };
457
+ acceptanceRuns.set(record.id, control);
458
+ await persist({
459
+ ...next,
460
+ exit_code: null,
461
+ signal: null,
462
+ current_action: "Running acceptance",
463
+ acceptance_results: { status: "running", passed: null, run: live.run_count, supervisor_pid: process.pid, started_at: finishedAt }
464
+ });
465
+ // A fresh MCP has no in-memory acceptance handle. Consume its durable
466
+ // cancellation marker while a command runs, then stop subsequent checks.
467
+ const cancellationWatch = setInterval(async () => {
468
+ const current = await getTask(record.id).catch(() => null);
469
+ if (current?.cancel_requested_at) {
470
+ control.cancelled = true;
471
+ control.kill?.();
472
+ }
473
+ }, 100);
474
+ let results;
475
+ try { results = await runAcceptance(acceptance, {
476
+ cwd: record.cwd,
477
+ timeoutMs: live.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS,
478
+ run: live.run_count,
479
+ taskId: record.id,
480
+ baseCommit: live.base_commit,
481
+ control
482
+ }); } finally { clearInterval(cancellationWatch); }
483
+ acceptanceRuns.delete(record.id);
484
+ const event = { type: "supervisor.acceptance", ...results };
485
+ await appendTaskEvent(record.id, event).catch(() => {});
486
+ await appendFile(logPath, `${JSON.stringify(event)}\n`).catch(() => {});
487
+ const failing = results.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
488
+ await persist({
489
+ ...next,
490
+ acceptance_results: results,
491
+ current_action: results.status === "passed"
492
+ ? "Completed, acceptance passed"
493
+ : results.status === "failed"
494
+ ? `Acceptance failed: ${failing ? `${failing.command.slice(0, 80)} exit ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code ?? "?")}` : results.error ?? "see acceptance_results"}`
495
+ : next.current_action,
496
+ updated_at: new Date().toISOString()
497
+ });
498
+ } else {
499
+ await persist(acceptance ? { ...next, acceptance_results: null } : next);
500
+ }
356
501
  cancelledTasks.delete(record.id);
357
502
  });
358
503
 
@@ -369,6 +514,45 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
369
514
  return { ok: true, record: live, child };
370
515
  }
371
516
 
517
+ // The MCP client may disappear at any point. A detached process owns the
518
+ // streams, exit write and acceptance until all three settle; IPC is only a
519
+ // startup handshake and never the channel carrying worker results.
520
+ async function startTrackedRun(job) {
521
+ const session = job.record.session_id ? await getSession(job.record.session_id) : null;
522
+ if (session) job.prompt = `Current session objective (revision ${session.policy_revision}): ${session.objective ?? "not specified"}. Follow this latest scope; do not revive earlier session requirements. Approval state: ${session.approval_state}.\n\n${job.prompt}`;
523
+ const peers = job.record.session_id ? (await readTasksBySession(job.record.session_id)).filter((task) => task.id !== job.record.id) : [];
524
+ const handoff = await buildHandoff({ goal: job.record.goal_objective, todo: job.record.title,
525
+ peers, contracts: job.record.input_context?.contracts ?? [], context: job.record.input_context?.context ?? [] });
526
+ job.record = { ...job.record, input_context: { ...job.record.input_context, context: handoff.source_refs, source_refs: handoff.source_refs } };
527
+ job.prompt = `${handoff.text}\n\n${job.prompt}\n\nRequired input refs (read-only): ${JSON.stringify(handoff.source_refs)}\nRequired contracts: ${JSON.stringify(job.record.input_context.contracts ?? [])}`;
528
+ const host = spawn(process.execPath, [fileURLToPath(import.meta.url), "--run-host"], {
529
+ detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"],
530
+ env: process.env, windowsHide: true
531
+ });
532
+ const started = await new Promise((resolveStart) => {
533
+ const finish = (result) => {
534
+ clearTimeout(timer);
535
+ host.removeAllListeners("message");
536
+ host.removeAllListeners("exit");
537
+ if (host.connected) host.disconnect();
538
+ host.unref();
539
+ resolveStart(result);
540
+ };
541
+ const timer = setTimeout(() => {
542
+ host.kill();
543
+ finish(failedStart(job.record, "run host startup timed out"));
544
+ }, 30000);
545
+ host.once("message", finish);
546
+ host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
547
+ host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
548
+ host.send(job, (error) => {
549
+ if (error) finish(failedStart(job.record, `run host IPC failed: ${error.message}`));
550
+ });
551
+ });
552
+ if (!started.ok) await upsertTask(started.record);
553
+ return started;
554
+ }
555
+
372
556
  function buildExecArgs({ cwd, sandbox, model, reasoningEffort, skipGitRepoCheck }) {
373
557
  const args = ["exec", "--json", "--cd", cwd, "--sandbox", sandbox];
374
558
  if (skipGitRepoCheck) args.push("--skip-git-repo-check");
@@ -405,20 +589,40 @@ export async function createCodexWorker({
405
589
  dependsOn = [],
406
590
  followupOf = null,
407
591
  useWorktree = true,
408
- baseRef = null
592
+ baseRef = null,
593
+ acceptance = null,
594
+ acceptanceTimeoutMs = null,
595
+ forbid = [],
596
+ allowedCommands = [],
597
+ context = [],
598
+ contracts = [],
599
+ externalOutputs = [],
600
+ networkAccess = false,
601
+ maxRunMs = null,
602
+ maxTotalMs = null
409
603
  }) {
410
604
  if (!task || typeof task !== "string") throw new Error("task is required");
605
+ const acceptanceCommands = normalizeAcceptance(acceptance);
411
606
  if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
412
607
  if (!allowedReasoningEfforts.has(reasoningEffort)) {
413
608
  throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
414
609
  }
415
- if (!Array.isArray(ownedPaths) || ownedPaths.length === 0) {
416
- throw new Error("ownedPaths is required and must list at least one path this worker is allowed to write");
610
+ if (!Array.isArray(ownedPaths) || (ownedPaths.length === 0 && sandbox !== "read-only")) {
611
+ throw new Error("ownedPaths is required and must list at least one path this worker is allowed to write (an empty list is allowed only for a read-only worker)");
417
612
  }
418
613
  const validatedGoal = validateGoal(goal);
614
+ await buildHandoff({ context, contracts });
615
+ await captureExternalOutputs(externalOutputs, { checkBaseline: true });
616
+ if (externalOutputs.length && !acceptanceCommands?.length) throw new Error("shared outputs require explicit acceptance commands");
617
+ if (externalOutputs.length && sandbox === "read-only") throw new Error("a read-only worker cannot declare writable shared outputs");
618
+ if (networkAccess && sandbox !== "workspace-write") throw new Error("networkAccess is only configurable for workspace-write workers");
619
+ for (const value of [maxRunMs, maxTotalMs]) if (value !== null && (!Number.isInteger(value) || value < 1000)) throw new Error("time limits must be integer milliseconds of at least 1000");
620
+ for (const [name, values] of Object.entries({ forbid, allowedCommands })) {
621
+ if (!Array.isArray(values) || values.length > 100 || values.some((value) => typeof value !== "string" || !value.trim())) throw new Error(`${name} must be a list of at most 100 nonempty strings`);
622
+ }
419
623
 
420
624
  const projectRoot = cwd;
421
- const normalizedOwnedPaths = normalizeOwnedPaths(ownedPaths, projectRoot);
625
+ const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
422
626
  const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
423
627
  if (conflicts.length > 0) throw ownershipConflictError(conflicts);
424
628
 
@@ -426,6 +630,14 @@ export async function createCodexWorker({
426
630
  await upsertSession({ id: sessionId, title: sessionTitle, note: sessionNote });
427
631
  }
428
632
 
633
+ const session = sessionId ? await getSession(sessionId) : null;
634
+ if (session?.approval_state === "waiting_user") {
635
+ const error = new Error("session is waiting for user approval; do not dispatch or auto-resume");
636
+ error.code = "session_waiting_user";
637
+ throw error;
638
+ }
639
+ const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
640
+
429
641
  const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
430
642
  const worktree = useWorktree
431
643
  ? await ensureWorktree(projectRoot, id, baseRef)
@@ -450,6 +662,8 @@ export async function createCodexWorker({
450
662
  session_id: sessionId ?? null,
451
663
  thread_id: null,
452
664
  owned_paths: normalizedOwnedPaths,
665
+ guard_policy: { forbid, allowedCommands, externalOutputs, networkAccess, maxRunMs, maxTotalMs },
666
+ input_context: { context, contracts },
453
667
  depends_on: Array.isArray(dependsOn) ? dependsOn : [],
454
668
  goal_objective: validatedGoal.objective,
455
669
  goal_token_budget: validatedGoal.tokenBudget,
@@ -460,6 +674,11 @@ export async function createCodexWorker({
460
674
  run_count: 0,
461
675
  worktree_path: worktreePath,
462
676
  base_commit: worktree.baseCommit,
677
+ acceptance: combinedAcceptance,
678
+ acceptance_local: acceptanceCommands,
679
+ session_policy_revision: session?.policy_revision ?? null,
680
+ acceptance_timeout_ms: combinedAcceptance ? (acceptanceTimeoutMs ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
681
+ acceptance_results: null,
463
682
  prompt: task,
464
683
  changed_files: [],
465
684
  commands: [],
@@ -467,35 +686,117 @@ export async function createCodexWorker({
467
686
  updated_at: new Date().toISOString(),
468
687
  run_log: taskRunPath(id)
469
688
  };
470
- await upsertTask(record);
689
+ try { await reserveTaskOwnership(record); }
690
+ catch (error) {
691
+ if (worktreePath) {
692
+ // This checkout belongs to this not-yet-started dispatch and contains
693
+ // no model edits. Remove it normally; never force-remove user work.
694
+ await runCommand(defaultGitBin,["-C",projectRoot,"worktree","remove",worktreePath]).catch(()=>{});
695
+ await runCommand(defaultGitBin,["-C",projectRoot,"branch","-D",`codex/${id}`]).catch(()=>{});
696
+ }
697
+ throw error;
698
+ }
471
699
 
472
700
  const args = buildExecArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
473
701
 
474
702
  const started = await startTrackedRun({
475
703
  record,
476
704
  args,
477
- prompt: withGoalPreamble(task, {
705
+ prompt: frameWorkerPrompt(task, {
478
706
  objective: validatedGoal.objective,
479
707
  tokenBudget: validatedGoal.tokenBudget
480
- }),
708
+ }, { acceptance: combinedAcceptance }),
481
709
  logPath: record.run_log
482
710
  });
483
- await upsertTask(started.record);
484
711
  return started.record;
485
712
  }
486
713
 
487
714
  // Continue the *same* Codex session. The worktree, thread id, ownership and
488
715
  // goal are all inherited from the original task, and the row is reused so one
489
716
  // logical piece of work stays one row.
490
- export async function resumeCodexWorker({ taskId, prompt }) {
717
+ //
718
+ // `rebaseOnto` names a ref, resolved in the project directory (HEAD, main, a
719
+ // sha): the worktree is moved onto it first so the worker continues on
720
+ // current code, and base_commit is recorded before the worker starts so a
721
+ // spawn failure cannot leave the row describing the old base. A rebase that
722
+ // does not go through puts the worktree back and throws with the file list;
723
+ // the worker is not started. Refused while the worker is still running.
724
+ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined, context = undefined }) {
491
725
  if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
492
- const task = await getTask(taskId);
726
+ let task = await getTask(taskId);
493
727
  if (!task) throw new Error(`task not found: ${taskId}`);
728
+ if (task.guard_policy?.maxTotalMs && Date.now() - Date.parse(task.created_at) >= task.guard_policy.maxTotalMs) {
729
+ const error = new Error("total time quota exceeded; inspect partial work and explicitly dispatch a revised budget");error.code="time_quota_exceeded";throw error;
730
+ }
731
+ if (context !== undefined) {
732
+ await buildHandoff({ context });
733
+ task = { ...task, input_context: { ...task.input_context, context } };
734
+ }
735
+ const claim = await claimTaskRun(taskId, task.run_count ?? 0);
736
+ if (!claim) {
737
+ const error = new Error(`task ${taskId} is active or already claimed by another dispatcher; wait for it to settle`);
738
+ error.code = "worker_active";
739
+ throw error;
740
+ }
741
+ try {
742
+ const session = task.session_id ? await getSession(task.session_id) : null;
743
+ if (session?.approval_state === "waiting_user") {
744
+ const error = new Error("session is waiting for user approval; do not resume");
745
+ error.code = "session_waiting_user";
746
+ throw error;
747
+ }
748
+ const localAcceptance = acceptance === undefined ? (task.session_policy_revision == null ? task.acceptance : task.acceptance_local) : normalizeAcceptance(acceptance);
749
+ // `acceptance` replaces the stored commands when given; an empty list
750
+ // clears them. Left out, the stored commands stay.
751
+ if (acceptance !== undefined || session) {
752
+ const commands = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(localAcceptance ?? [])]);
753
+ task = {
754
+ ...task,
755
+ acceptance: commands,
756
+ acceptance_local: localAcceptance,
757
+ session_policy_revision: session?.policy_revision ?? null,
758
+ acceptance_timeout_ms: commands ? (task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
759
+ updated_at: new Date().toISOString()
760
+ };
761
+ await upsertTask(task);
762
+ }
494
763
  if (!task.thread_id) {
495
764
  throw new Error(
496
765
  `task ${taskId} has no Codex thread_id recorded. Only workers created by this version of codex-supervisor-mcp can be resumed; use create_codex_followup_worker otherwise.`
497
766
  );
498
767
  }
768
+ let rebase = null;
769
+ if (rebaseOnto) {
770
+ if (ACTIVE_STATUSES.has(task.status) || processes.has(task.id)) {
771
+ const error = new Error(`task ${taskId} is still ${task.status}; wait for it to settle (or cancel it) before rebasing its worktree`);
772
+ error.code = "worker_active";
773
+ throw error;
774
+ }
775
+ if (!task.worktree_path) {
776
+ const error = new Error(`task ${taskId} ran in place and has no worktree to rebase`);
777
+ error.code = "no_worktree";
778
+ throw error;
779
+ }
780
+ let ontoCommit;
781
+ try {
782
+ ontoCommit = resolveCommit(task.project_root, rebaseOnto);
783
+ } catch {
784
+ const error = new Error(`rebaseOnto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
785
+ error.code = "invalid_rebase_onto";
786
+ throw error;
787
+ }
788
+ rebase = rebaseWorktree(task, ontoCommit);
789
+ if (rebase.error) {
790
+ const error = new Error(rebase.reason);
791
+ error.code = rebase.error;
792
+ error.details = rebase;
793
+ throw error;
794
+ }
795
+ if (!rebase.noop && rebase.base_commit !== task.base_commit) {
796
+ task = { ...task, base_commit: rebase.base_commit, updated_at: new Date().toISOString() };
797
+ await upsertTask(task);
798
+ }
799
+ }
499
800
 
500
801
  const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
501
802
  const args = ["exec", "resume", "--json"];
@@ -509,15 +810,60 @@ export async function resumeCodexWorker({ taskId, prompt }) {
509
810
  const started = await startTrackedRun({
510
811
  record: { ...task, resumed_from: task.resumed_from ?? task.id },
511
812
  args,
512
- prompt: withGoalPreamble(prompt, {
813
+ prompt: frameWorkerPrompt(prompt, {
513
814
  objective: task.goal_objective ?? task.title ?? task.id,
514
815
  resume: true
515
- }),
816
+ }, { acceptance: task.acceptance }),
516
817
  logPath: task.run_log,
517
818
  spawnOptions: { cwd }
518
819
  });
519
- await upsertTask(started.record);
520
- return started.record;
820
+ return rebase ? { ...started.record, rebase } : started.record;
821
+ } finally { await releaseTaskRun(taskId, claim); }
822
+ }
823
+
824
+ export async function recoverEligibleRuns() {
825
+ const recovered = [];
826
+ for (const task of await readTasks()) {
827
+ if ((task.run_count ?? 0) !== 1 || !task.thread_id
828
+ || !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
829
+ || !(task.status === "lost" || task.attention_reason === "no_work")
830
+ || ["blocked", "paused", "budget_limited", "usage_limited"].includes(task.goal_status)
831
+ || /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
832
+ || /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
833
+ || await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)) continue;
834
+ const session = task.session_id ? await getSession(task.session_id) : null;
835
+ if (session?.approval_state === "waiting_user") continue;
836
+ try {
837
+ const result = await resumeCodexWorker({ taskId: task.id,
838
+ prompt: `One automatic recovery after ${task.attention_reason ?? task.status}. Original task: ${task.prompt}\nContinue from files already present; do not repeat completed edits. Make concrete progress, run declared checks, and report remaining blockers accurately. This is the only automatic retry.` });
839
+ const event = { type: "supervisor.recovery", automatic: true, from_run: 1, to_run: result.run_count,
840
+ reason: task.attention_reason ?? task.status, started_at: new Date().toISOString() };
841
+ await appendTaskEvent(task.id, event);
842
+ await appendFile(task.run_log, `${JSON.stringify(event)}\n`);
843
+ recovered.push({ id: task.id, run: result.run_count, reason: event.reason });
844
+ } catch (error) {
845
+ if (!["worker_active", "session_waiting_user"].includes(error.code)) {
846
+ await appendTaskEvent(task.id, { type: "supervisor.recovery_refused", reason: error.code ?? "resume_failed" });
847
+ }
848
+ }
849
+ }
850
+ return recovered;
851
+ }
852
+
853
+ if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "--run-host") {
854
+ process.once("message", async (job) => {
855
+ let result;
856
+ try {
857
+ result = await trackRunInHost(job);
858
+ if (!result.ok) await upsertTask(result.record);
859
+ } catch (error) {
860
+ result = failedStart(job.record, `run host failed: ${error.message}`);
861
+ await upsertTask(result.record);
862
+ }
863
+ if (process.connected) process.send({ ok: result.ok, record: result.record }, () => {
864
+ if (process.connected) process.disconnect();
865
+ });
866
+ });
521
867
  }
522
868
 
523
869
  // `powershell` by name is not always on PATH for a process a GUI client
@@ -607,6 +953,12 @@ function terminatePid(pid) {
607
953
  }
608
954
 
609
955
  export async function cancelCodexWorker(taskId) {
956
+ const acceptance = acceptanceRuns.get(taskId);
957
+ if (acceptance) {
958
+ acceptance.cancelled = true;
959
+ acceptance.kill?.();
960
+ return { cancelled: true, via: "acceptance", pid: null };
961
+ }
610
962
  const child = processes.get(taskId);
611
963
  if (child) {
612
964
  cancelledTasks.add(taskId);
@@ -615,6 +967,10 @@ export async function cancelCodexWorker(taskId) {
615
967
  }
616
968
  // Another MCP process owns the handle; fall back to the pid recorded on disk.
617
969
  const task = await getTask(taskId);
970
+ if (task?.acceptance_results?.status === "running" && await isPidAlive(task.acceptance_results.supervisor_pid)) {
971
+ await upsertTask({ ...task, cancel_requested_at: new Date().toISOString(), updated_at: new Date().toISOString() });
972
+ return { cancelled: true, via: "acceptance", pid: null };
973
+ }
618
974
  if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
619
975
  try {
620
976
  terminatePid(task.pid);
@@ -649,7 +1005,17 @@ export async function createFollowupWorker({
649
1005
  reasoningEffort,
650
1006
  ownedPaths,
651
1007
  goal,
652
- baseRef
1008
+ baseRef,
1009
+ acceptance,
1010
+ acceptanceTimeoutMs,
1011
+ forbid,
1012
+ allowedCommands,
1013
+ context,
1014
+ contracts,
1015
+ externalOutputs,
1016
+ networkAccess,
1017
+ maxRunMs,
1018
+ maxTotalMs
653
1019
  }) {
654
1020
  const parent = await getTask(taskId);
655
1021
  if (!parent) throw new Error(`task not found: ${taskId}`);
@@ -689,10 +1055,23 @@ export async function createFollowupWorker({
689
1055
  reasoningEffort: reasoningEffort ?? parent.reasoning_effort ?? "high",
690
1056
  skipGitRepoCheck: parent.skip_git_repo_check,
691
1057
  ownedPaths: ownedPaths ?? parent.owned_paths,
1058
+ forbid: forbid ?? parent.guard_policy?.forbid ?? [],
1059
+ allowedCommands: allowedCommands ?? parent.guard_policy?.allowedCommands ?? [],
1060
+ context: context ?? parent.input_context?.context ?? [],
1061
+ contracts: contracts ?? parent.input_context?.contracts ?? [],
1062
+ externalOutputs: externalOutputs ?? parent.guard_policy?.externalOutputs ?? [],
1063
+ networkAccess: networkAccess ?? parent.guard_policy?.networkAccess ?? false,
1064
+ maxRunMs: maxRunMs ?? parent.guard_policy?.maxRunMs ?? null,
1065
+ maxTotalMs: maxTotalMs ?? parent.guard_policy?.maxTotalMs ?? null,
692
1066
  goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
693
1067
  dependsOn: [parent.id],
694
1068
  followupOf: parent.id,
695
1069
  useWorktree: true,
696
- baseRef: baseRef ?? null
1070
+ baseRef: baseRef ?? null,
1071
+ // Inherited unless given; the follow-up runs in a fresh worktree cut
1072
+ // from the project HEAD, so the parent's checks only pass there once
1073
+ // the parent's work has landed.
1074
+ acceptance: acceptance === undefined ? (parent.session_policy_revision == null ? parent.acceptance : parent.acceptance_local) : acceptance,
1075
+ acceptanceTimeoutMs: acceptanceTimeoutMs ?? parent.acceptance_timeout_ms ?? null
697
1076
  });
698
1077
  }