codex-supervisor-mcp 0.8.0 → 0.9.1

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,25 +2,36 @@ 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
23
  import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
17
24
  import { worktreesDir } from "./paths.js";
18
25
  import { frameWorkerPrompt } from "./prompt.js";
19
- import { readTaskChanges } from "./worktree.js";
26
+ import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
20
27
  import { rebaseWorktree } from "./landing.js";
21
28
  import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance, runAcceptance } from "./acceptance.js";
22
29
  import { appendFile } from "node:fs/promises";
23
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";
24
35
 
25
36
  const processes = new Map();
26
37
  // taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
@@ -102,8 +113,9 @@ async function ensureWorktree(cwd, taskId, baseRef = null) {
102
113
  await runCommand(defaultGitBin, ["-C", taskWorktreeDir, "switch", "-c", branch]);
103
114
  return { path: taskWorktreeDir, baseCommit };
104
115
  } catch (error) {
105
- if (baseRef) throw error;
106
- 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;
107
119
  }
108
120
  }
109
121
 
@@ -183,6 +195,7 @@ function failedStart(record, reason) {
183
195
  phase: null,
184
196
  pid: null,
185
197
  error: reason,
198
+ attention_reason: "start_failed",
186
199
  completed_at: now,
187
200
  updated_at: now
188
201
  }
@@ -215,13 +228,35 @@ async function spawnAndAwaitStart(target, args, options) {
215
228
  // Attaches stream handlers and keeps `record` in the supervisor database.
216
229
  // Every write goes through one serialized chain so concurrent stdout/stderr
217
230
  // callbacks cannot interleave and persist out of order.
218
- async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {} }) {
231
+ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {} }) {
219
232
  const target = codexTarget();
220
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}`;
221
255
 
222
- const { child, spawnError } = await spawnAndAwaitStart(target, args, {
256
+ const { child, spawnError } = await spawnAndAwaitStart(target, guardedArgs, {
223
257
  stdio: ["pipe", "pipe", "pipe"],
224
- 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) },
225
260
  windowsHide: true,
226
261
  ...spawnOptions
227
262
  });
@@ -239,11 +274,18 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
239
274
  status: "running",
240
275
  phase: "starting",
241
276
  pid: child.pid ?? null,
277
+ run_host_pid: process.pid,
242
278
  started_at: now,
243
279
  completed_at: null,
244
280
  exit_code: null,
245
281
  signal: null,
246
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,
247
289
  current_action: null,
248
290
  current_command: null,
249
291
  // A resumed row still carries the last event of the run that ended;
@@ -254,6 +296,15 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
254
296
  updated_at: now
255
297
  };
256
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;
257
308
 
258
309
  let writeChain = Promise.resolve();
259
310
  const persist = (next) => {
@@ -266,6 +317,7 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
266
317
  });
267
318
  return writeChain;
268
319
  };
320
+ await persist(live);
269
321
 
270
322
  const logStream = createWriteStream(logPath, { flags: "a" });
271
323
  logStream.on("error", () => {});
@@ -281,6 +333,8 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
281
333
  });
282
334
 
283
335
  let eventChain = Promise.resolve();
336
+ let terminalEvent = false;
337
+ let rawReport = null;
284
338
  const handleLine = async (line) => {
285
339
  let event;
286
340
  try {
@@ -290,6 +344,8 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
290
344
  return;
291
345
  }
292
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;
293
349
  await appendTaskEvent(record.id, event);
294
350
  await persist(applyCodexEvent(live, event));
295
351
  };
@@ -322,8 +378,12 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
322
378
  });
323
379
  });
324
380
 
325
- child.on("exit", async (code, signal) => {
381
+ child.on("close", async (code, signal) => {
382
+ if (quotaWatch) clearInterval(quotaWatch);
326
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
+ });
327
387
  await eventChain.catch(() => {});
328
388
  logStream.end();
329
389
  const finishedAt = new Date().toISOString();
@@ -335,12 +395,12 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
335
395
  || Boolean(stored?.cancel_requested_at);
336
396
  let status;
337
397
  if (stored && TERMINAL_STATUSES.has(stored.status) && stored.status !== live.status) status = stored.status;
338
- 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;
339
399
  else if (cancelRequested) status = "cancelled";
340
400
  // Killed by a signal nobody asked for: the worker did not fail, it
341
401
  // vanished. Re-running is the fix, so it is reported as lost.
342
402
  else if (signal) status = "lost";
343
- else if (code === 0) status = "completed";
403
+ else if (code === 0) status = "lost";
344
404
  else status = "failed";
345
405
  const next = {
346
406
  ...live,
@@ -358,9 +418,31 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
358
418
  next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
359
419
  }
360
420
  if (status === "lost" && !next.error) {
361
- 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";
362
422
  }
363
423
  if (status === "cancelled") next.error = null;
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
+ }
364
446
 
365
447
  // Acceptance runs after the worker is gone, in two writes. The first
366
448
  // records the terminal status with exit_code still null and the run
@@ -380,24 +462,36 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
380
462
  current_action: "Running acceptance",
381
463
  acceptance_results: { status: "running", passed: null, run: live.run_count, supervisor_pid: process.pid, started_at: finishedAt }
382
464
  });
383
- const results = await runAcceptance(acceptance, {
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, {
384
476
  cwd: record.cwd,
385
477
  timeoutMs: live.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS,
386
478
  run: live.run_count,
479
+ taskId: record.id,
480
+ baseCommit: live.base_commit,
387
481
  control
388
- });
482
+ }); } finally { clearInterval(cancellationWatch); }
389
483
  acceptanceRuns.delete(record.id);
390
484
  const event = { type: "supervisor.acceptance", ...results };
391
485
  await appendTaskEvent(record.id, event).catch(() => {});
392
486
  await appendFile(logPath, `${JSON.stringify(event)}\n`).catch(() => {});
393
- const failing = results.checks.find((check) => check.exit_code !== 0);
487
+ const failing = results.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
394
488
  await persist({
395
489
  ...next,
396
490
  acceptance_results: results,
397
491
  current_action: results.status === "passed"
398
492
  ? "Completed, acceptance passed"
399
493
  : results.status === "failed"
400
- ? `Acceptance failed: ${failing ? `${failing.command.slice(0, 80)} exit ${failing.exit_code ?? (failing.timed_out ? "timeout" : "?")}` : results.error ?? "see acceptance_results"}`
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"}`
401
495
  : next.current_action,
402
496
  updated_at: new Date().toISOString()
403
497
  });
@@ -420,6 +514,45 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
420
514
  return { ok: true, record: live, child };
421
515
  }
422
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
+
423
556
  function buildExecArgs({ cwd, sandbox, model, reasoningEffort, skipGitRepoCheck }) {
424
557
  const args = ["exec", "--json", "--cd", cwd, "--sandbox", sandbox];
425
558
  if (skipGitRepoCheck) args.push("--skip-git-repo-check");
@@ -458,7 +591,15 @@ export async function createCodexWorker({
458
591
  useWorktree = true,
459
592
  baseRef = null,
460
593
  acceptance = null,
461
- acceptanceTimeoutMs = null
594
+ acceptanceTimeoutMs = null,
595
+ forbid = [],
596
+ allowedCommands = [],
597
+ context = [],
598
+ contracts = [],
599
+ externalOutputs = [],
600
+ networkAccess = false,
601
+ maxRunMs = null,
602
+ maxTotalMs = null
462
603
  }) {
463
604
  if (!task || typeof task !== "string") throw new Error("task is required");
464
605
  const acceptanceCommands = normalizeAcceptance(acceptance);
@@ -470,9 +611,18 @@ export async function createCodexWorker({
470
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)");
471
612
  }
472
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
+ }
473
623
 
474
624
  const projectRoot = cwd;
475
- const normalizedOwnedPaths = normalizeOwnedPaths(ownedPaths, projectRoot);
625
+ const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
476
626
  const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
477
627
  if (conflicts.length > 0) throw ownershipConflictError(conflicts);
478
628
 
@@ -480,6 +630,14 @@ export async function createCodexWorker({
480
630
  await upsertSession({ id: sessionId, title: sessionTitle, note: sessionNote });
481
631
  }
482
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
+
483
641
  const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
484
642
  const worktree = useWorktree
485
643
  ? await ensureWorktree(projectRoot, id, baseRef)
@@ -504,6 +662,8 @@ export async function createCodexWorker({
504
662
  session_id: sessionId ?? null,
505
663
  thread_id: null,
506
664
  owned_paths: normalizedOwnedPaths,
665
+ guard_policy: { forbid, allowedCommands, externalOutputs, networkAccess, maxRunMs, maxTotalMs },
666
+ input_context: { context, contracts },
507
667
  depends_on: Array.isArray(dependsOn) ? dependsOn : [],
508
668
  goal_objective: validatedGoal.objective,
509
669
  goal_token_budget: validatedGoal.tokenBudget,
@@ -514,8 +674,10 @@ export async function createCodexWorker({
514
674
  run_count: 0,
515
675
  worktree_path: worktreePath,
516
676
  base_commit: worktree.baseCommit,
517
- acceptance: acceptanceCommands,
518
- acceptance_timeout_ms: acceptanceCommands ? (acceptanceTimeoutMs ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
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,
519
681
  acceptance_results: null,
520
682
  prompt: task,
521
683
  changed_files: [],
@@ -524,7 +686,16 @@ export async function createCodexWorker({
524
686
  updated_at: new Date().toISOString(),
525
687
  run_log: taskRunPath(id)
526
688
  };
527
- 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
+ }
528
699
 
529
700
  const args = buildExecArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
530
701
 
@@ -534,10 +705,9 @@ export async function createCodexWorker({
534
705
  prompt: frameWorkerPrompt(task, {
535
706
  objective: validatedGoal.objective,
536
707
  tokenBudget: validatedGoal.tokenBudget
537
- }, { acceptance: acceptanceCommands }),
708
+ }, { acceptance: combinedAcceptance }),
538
709
  logPath: record.run_log
539
710
  });
540
- await upsertTask(started.record);
541
711
  return started.record;
542
712
  }
543
713
 
@@ -551,17 +721,40 @@ export async function createCodexWorker({
551
721
  // spawn failure cannot leave the row describing the old base. A rebase that
552
722
  // does not go through puts the worktree back and throws with the file list;
553
723
  // the worker is not started. Refused while the worker is still running.
554
- export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined }) {
724
+ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined, context = undefined }) {
555
725
  if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
556
726
  let task = await getTask(taskId);
557
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);
558
749
  // `acceptance` replaces the stored commands when given; an empty list
559
750
  // clears them. Left out, the stored commands stay.
560
- if (acceptance !== undefined) {
561
- const commands = normalizeAcceptance(acceptance);
751
+ if (acceptance !== undefined || session) {
752
+ const commands = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(localAcceptance ?? [])]);
562
753
  task = {
563
754
  ...task,
564
755
  acceptance: commands,
756
+ acceptance_local: localAcceptance,
757
+ session_policy_revision: session?.policy_revision ?? null,
565
758
  acceptance_timeout_ms: commands ? (task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
566
759
  updated_at: new Date().toISOString()
567
760
  };
@@ -624,8 +817,53 @@ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acc
624
817
  logPath: task.run_log,
625
818
  spawnOptions: { cwd }
626
819
  });
627
- await upsertTask(started.record);
628
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
+ });
629
867
  }
630
868
 
631
869
  // `powershell` by name is not always on PATH for a process a GUI client
@@ -729,6 +967,10 @@ export async function cancelCodexWorker(taskId) {
729
967
  }
730
968
  // Another MCP process owns the handle; fall back to the pid recorded on disk.
731
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
+ }
732
974
  if (task?.pid && (await isPidAlive(task.pid)) && isLikelyCodexProcess(task.pid)) {
733
975
  try {
734
976
  terminatePid(task.pid);
@@ -765,7 +1007,15 @@ export async function createFollowupWorker({
765
1007
  goal,
766
1008
  baseRef,
767
1009
  acceptance,
768
- acceptanceTimeoutMs
1010
+ acceptanceTimeoutMs,
1011
+ forbid,
1012
+ allowedCommands,
1013
+ context,
1014
+ contracts,
1015
+ externalOutputs,
1016
+ networkAccess,
1017
+ maxRunMs,
1018
+ maxTotalMs
769
1019
  }) {
770
1020
  const parent = await getTask(taskId);
771
1021
  if (!parent) throw new Error(`task not found: ${taskId}`);
@@ -805,6 +1055,14 @@ export async function createFollowupWorker({
805
1055
  reasoningEffort: reasoningEffort ?? parent.reasoning_effort ?? "high",
806
1056
  skipGitRepoCheck: parent.skip_git_repo_check,
807
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,
808
1066
  goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
809
1067
  dependsOn: [parent.id],
810
1068
  followupOf: parent.id,
@@ -813,7 +1071,7 @@ export async function createFollowupWorker({
813
1071
  // Inherited unless given; the follow-up runs in a fresh worktree cut
814
1072
  // from the project HEAD, so the parent's checks only pass there once
815
1073
  // the parent's work has landed.
816
- acceptance: acceptance === undefined ? parent.acceptance : acceptance,
1074
+ acceptance: acceptance === undefined ? (parent.session_policy_revision == null ? parent.acceptance : parent.acceptance_local) : acceptance,
817
1075
  acceptanceTimeoutMs: acceptanceTimeoutMs ?? parent.acceptance_timeout_ms ?? null
818
1076
  });
819
1077
  }
@@ -3,6 +3,7 @@
3
3
  // Invariant: status is the lifecycle and is only ever assigned queued /
4
4
  // running / completed / failed / cancelled / lost. Progress details go to
5
5
  // phase, which is only meaningful while the work is running.
6
+ import { parseWorkerReport } from "./worker-report.js";
6
7
 
7
8
  function getEventType(event) {
8
9
  return event.type ?? event.event ?? event.msg?.type ?? "unknown";
@@ -17,7 +18,9 @@ function inferCommand(item) {
17
18
  }
18
19
 
19
20
  function inferAgentMessage(item) {
20
- return item?.text ?? item?.message ?? item?.content ?? item?.output_text ?? null;
21
+ const raw = item?.text ?? item?.message ?? item?.content ?? item?.output_text ?? null;
22
+ const parsed = parseWorkerReport(raw);
23
+ return parsed.valid ? parsed.report.result : raw;
21
24
  }
22
25
 
23
26
  // The stored event stream is raw Codex JSONL, so reading a worker's own report
@@ -0,0 +1,29 @@
1
+ import { lstat, readFile, realpath } from "node:fs/promises";
2
+ import { isAbsolute, dirname } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+
5
+ export async function captureExternalOutputs(declarations, { checkBaseline = false } = {}) {
6
+ if (!Array.isArray(declarations) || declarations.length > 20) throw new Error("externalOutputs must contain at most 20 files");
7
+ const captured = [];
8
+ for (const entry of declarations) {
9
+ if (!entry || !isAbsolute(entry.path)) throw new Error("externalOutputs must use absolute file paths");
10
+ let info;
11
+ try { info = await lstat(entry.path); } catch (error) { if (error.code !== "ENOENT") throw error; }
12
+ let snapshot = { path: entry.path, exists: false, sha256: null, content: null, truncated: false };
13
+ if (info) {
14
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 1_000_000) throw new Error("external output must be a regular file of at most 1 MB");
15
+ const bytes = await readFile(entry.path);
16
+ snapshot = { ...snapshot, exists: true, canonical_path: await realpath(entry.path), sha256: createHash("sha256").update(bytes).digest("hex"),
17
+ content: bytes.includes(0) ? null : bytes.subarray(0, 3000).toString("utf8"), truncated: bytes.length > 3000 };
18
+ } else { snapshot.canonical_parent = await realpath(dirname(entry.path)); }
19
+ if (checkBaseline && entry.sha256 && snapshot.sha256 !== entry.sha256) throw new Error(`external output baseline changed: ${entry.path}`);
20
+ captured.push(snapshot);
21
+ }
22
+ return captured;
23
+ }
24
+
25
+ export function compareExternalOutputs(before, after) {
26
+ return before.map((old, index) => ({ path: old.path, before: old, after: after[index],
27
+ changed: old.exists !== after[index]?.exists || old.sha256 !== after[index]?.sha256,
28
+ integration: "shared_file_already_written_not_cherry_pick" }));
29
+ }
package/src/goal-store.js CHANGED
@@ -13,8 +13,9 @@ function toCamelCase(status) {
13
13
  return String(status).replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
14
14
  }
15
15
 
16
- export function readNativeGoal(threadId) {
17
- if (!threadId || !existsSync(goalsDbPath)) return null;
16
+ export function readNativeGoalState(threadId) {
17
+ if (!threadId) return { state: "no_thread", goal: null };
18
+ if (!existsSync(goalsDbPath)) return { state: "missing_database", goal: null };
18
19
  let db;
19
20
  try {
20
21
  db = new DatabaseSync(goalsDbPath, { readOnly: true });
@@ -25,8 +26,8 @@ export function readNativeGoal(threadId) {
25
26
  FROM thread_goals
26
27
  WHERE thread_id = ?
27
28
  `).get(threadId);
28
- if (!row) return null;
29
- return {
29
+ if (!row) return { state: "missing_goal", goal: null };
30
+ return { state: "available", goal: {
30
31
  objective: row.objective,
31
32
  status: toCamelCase(row.status),
32
33
  storage_status: row.status,
@@ -36,11 +37,11 @@ export function readNativeGoal(threadId) {
36
37
  time_used_seconds: row.time_used_seconds ?? 0,
37
38
  created_at: row.created_at_ms ? new Date(row.created_at_ms).toISOString() : null,
38
39
  updated_at: row.updated_at_ms ? new Date(row.updated_at_ms).toISOString() : null
39
- };
40
- } catch {
40
+ } };
41
+ } catch (error) {
41
42
  // A locked or half-migrated Codex database must never break a supervisor
42
43
  // call; the supervisor goal is still returned by the caller.
43
- return null;
44
+ return { state: /locked|busy/i.test(error.message) ? "locked" : "read_error", goal: null, error: error.message };
44
45
  } finally {
45
46
  try {
46
47
  db?.close();
@@ -49,3 +50,5 @@ export function readNativeGoal(threadId) {
49
50
  }
50
51
  }
51
52
  }
53
+
54
+ export function readNativeGoal(threadId) { return readNativeGoalState(threadId).goal; }