codex-supervisor-mcp 0.10.3 → 0.11.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.
@@ -1,11 +1,12 @@
1
1
  import { createWriteStream, existsSync } from "node:fs";
2
2
  import { mkdir, rm, stat } from "node:fs/promises";
3
- import { randomUUID } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { execFileSync, spawn } from "node:child_process";
5
5
  import { join, resolve, sep, dirname, isAbsolute } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import {
8
8
  appendTaskEvent,
9
+ appendTaskEvents,
9
10
  getTask,
10
11
  getSession,
11
12
  readActiveTasks,
@@ -23,7 +24,6 @@ import {
23
24
  releaseTaskRun,
24
25
  reserveTaskOwnership
25
26
  } from "./task-store.js";
26
- import { applyCodexEvent } from "./event-parser.js";
27
27
  import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
28
28
  import { worktreesDir } from "./paths.js";
29
29
  import { buildGuardPreamble, frameWorkerPrompt } from "./prompt.js";
@@ -32,7 +32,6 @@ import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
32
32
  import { rebaseWorktree } from "./landing.js";
33
33
  import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, isArtifactOnlyAcceptance, normalizeAcceptance, runAcceptance } from "./acceptance.js";
34
34
  import { appendFile } from "node:fs/promises";
35
- import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
36
35
  import { findOutsideOwnedChanges } from "./owned-changes.js";
37
36
  import { parseWorkerReport, workerReportSchemaPath } from "./worker-report.js";
38
37
  import { buildHandoff } from "./handoff.js";
@@ -40,20 +39,24 @@ import { compileWorkerContext } from "./context-compiler.js";
40
39
  import { captureExternalOutputs, compareExternalOutputs } from "./external-output.js";
41
40
  import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, runtimeContractHash } from "./worker-preflight.js";
42
41
  import { supervisorMcpDisableArgs } from "./mcp-config.js";
42
+ import { captureWorkspaceManifest, isGitCheckout, prepareWorkspace } from "./workspace-kind.js";
43
+ import { codexRunner } from "./runner-adapter.js";
43
44
 
44
45
  const processes = new Map();
45
46
  // taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
46
47
  const acceptanceRuns = new Map();
47
48
  const cancelledTasks = new Set();
48
- const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
49
49
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
50
50
  const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
51
51
  const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
52
+ const RUN_HOST_STARTUP_TIMEOUT_MS = process.platform === "win32" ? 120000 : 30000;
53
+ const WORKTREE_LOCK_TIMEOUT_MS = 120000;
52
54
 
53
55
  async function recordOutcomeFacts({ task, runId, report, reportEventId = null, acceptanceEventId = null, acceptancePassed = false }) {
54
56
  if (!report?.valid) return;
55
57
  const workItem = await getWorkItemForTask(task.id);
56
58
  if (!workItem) return;
59
+ const validForManifestHash = task.run_evidence?.workspace?.after_manifest?.sha256 ?? null;
57
60
  const candidate = await recordFact({
58
61
  workItemId: workItem.id,
59
62
  scopeType: "run",
@@ -63,6 +66,8 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
63
66
  state: "candidate",
64
67
  sourceEventId: reportEventId,
65
68
  validForSha: task.base_commit ?? null,
69
+ validForContentHash: task.input_context?.content_hash ?? null,
70
+ validForManifestHash,
66
71
  watchedPaths: task.owned_paths ?? []
67
72
  });
68
73
  if (!acceptancePassed) return;
@@ -75,8 +80,11 @@ async function recordOutcomeFacts({ task, runId, report, reportEventId = null, a
75
80
  state: "verified",
76
81
  sourceEventId: acceptanceEventId,
77
82
  validForSha: task.base_commit ?? null,
83
+ validForContentHash: task.input_context?.content_hash ?? null,
84
+ validForManifestHash,
78
85
  watchedPaths: task.owned_paths ?? [],
79
- supersedesId: candidate.id
86
+ supersedesId: candidate.id,
87
+ verifiedBy: "supervisor.acceptance"
80
88
  });
81
89
  await updateWorkItemDelivery(task.id, "verified");
82
90
  }
@@ -159,6 +167,31 @@ async function ensureWorktree(cwd, taskId, baseRef = null) {
159
167
  }
160
168
  }
161
169
 
170
+ function sleep(ms) {
171
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
172
+ }
173
+
174
+ async function withWorktreeCreationLock(cwd, work) {
175
+ const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
176
+ const lockPath = join(worktreesDir, lockName);
177
+ await mkdir(worktreesDir, { recursive: true });
178
+ const deadline = Date.now() + WORKTREE_LOCK_TIMEOUT_MS;
179
+ while (true) {
180
+ try {
181
+ await mkdir(lockPath);
182
+ break;
183
+ } catch (error) {
184
+ if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`);
185
+ await sleep(100);
186
+ }
187
+ }
188
+ try {
189
+ return await work();
190
+ } finally {
191
+ await rm(lockPath, { recursive: true, force: true }).catch(() => {});
192
+ }
193
+ }
194
+
162
195
  function normalizeOwnedPaths(ownedPaths, projectRoot) {
163
196
  if (!Array.isArray(ownedPaths)) return [];
164
197
  return Array.from(new Set(ownedPaths.map((entry) => resolve(projectRoot, String(entry).trim()))));
@@ -213,18 +246,6 @@ function ownershipConflictError(conflicts) {
213
246
  return error;
214
247
  }
215
248
 
216
- // The Codex CLI as a spawnable target. On Windows npm installs a `codex.cmd`
217
- // shim that Node refuses to spawn directly, so bin-resolver.js steps over it and
218
- // hands back `node <entry>` instead; on macOS and Linux this is the bare name,
219
- // unchanged. Resolved per dispatch so a CLI installed later is picked up.
220
- function codexTarget() {
221
- const configured = process.env.CODEX_BIN?.trim();
222
- const located = configured ? configured : (findBinaryPath("codex", { extraDirs: defaultBinDirs() }) ?? "codex");
223
- const target = resolveCommand(located, { npmEntry: CODEX_NPM_ENTRY });
224
- if (target.shim) return { error: shimMessage("codex", target.cmd, "CODEX_BIN") };
225
- return { cmd: target.cmd, prefixArgs: target.prefixArgs };
226
- }
227
-
228
249
  function failedStart(record, reason) {
229
250
  const now = new Date().toISOString();
230
251
  return {
@@ -247,6 +268,9 @@ function failedStart(record, reason) {
247
268
  // failed instead of taking the whole MCP process down.
248
269
  async function spawnAndAwaitStart(target, args, options) {
249
270
  const child = spawn(target.cmd, [...target.prefixArgs, ...args], options);
271
+ const earlyOutput = { stdout: [], stderr: [], capture: true };
272
+ child.stdout?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stdout.push(chunk); });
273
+ child.stderr?.on("data", (chunk) => { if (earlyOutput.capture) earlyOutput.stderr.push(chunk); });
250
274
  const spawnError = await new Promise((resolvePromise) => {
251
275
  let settled = false;
252
276
  child.once("spawn", () => {
@@ -262,22 +286,18 @@ async function spawnAndAwaitStart(target, args, options) {
262
286
  }
263
287
  });
264
288
  });
265
- return { child, spawnError };
289
+ return { child, spawnError, earlyOutput };
266
290
  }
267
291
 
268
292
  // Attaches stream handlers and keeps `record` in the supervisor database.
269
293
  // Every write goes through one serialized chain so concurrent stdout/stderr
270
294
  // callbacks cannot interleave and persist out of order.
271
295
  async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {} }) {
272
- const target = codexTarget();
273
- if (target.error) return failedStart(record, target.error);
274
- try {
275
- const help = execFileSync(target.cmd, [...target.prefixArgs, "exec", "--help"], { encoding: "utf8", timeout: 15000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
276
- 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");
277
- } catch (error) { return failedStart(record, error.code === "ENOENT"
278
- ? `failed to spawn ${target.cmd} for Codex capability preflight: ${error.message}`
279
- : `Codex capability preflight failed: ${error.message}`); }
296
+ const capability = codexRunner.capabilityPreflight();
297
+ if (!capability.ok) return failedStart(record, capability.error);
298
+ const target = capability.target;
280
299
  const outputBefore = snapshotTaskOutput(record);
300
+ const workspaceBefore = record.workspace_metadata?.before_manifest ?? null;
281
301
  const externalBefore = await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [], { checkBaseline: (record.run_count ?? 0) === 0 });
282
302
  const owned = [...findOutsideOwnedChanges(record, []).mapping.map((entry) => entry.worker), ...externalBefore.map((entry) => entry.path)];
283
303
  const guardPolicy = { cwd: record.cwd, worktree: record.cwd, sandbox: record.sandbox, ownedPaths: owned, ...(record.guard_policy ?? {}),
@@ -297,7 +317,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
297
317
  const guardedArgs = [...args.slice(0, -1), ...configArgs, args.at(-1)];
298
318
  prompt = `${buildGuardPreamble(guardPolicy)}\n\n${prompt}`;
299
319
 
300
- const { child, spawnError } = await spawnAndAwaitStart(target, guardedArgs, {
320
+ const { child, spawnError, earlyOutput } = await spawnAndAwaitStart(target, guardedArgs, {
301
321
  stdio: ["pipe", "pipe", "pipe"],
302
322
  env: { ...process.env, NO_COLOR: "1", CODEX_SUPERVISOR_TASK_ID: record.id,
303
323
  CODEX_SUPERVISOR_RUN: String((record.run_count ?? 0) + 1), CODEX_SUPERVISOR_GUARD_POLICY: JSON.stringify(guardPolicy) },
@@ -313,6 +333,8 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
313
333
  // A new run starts clean. A resumed worker used to carry the error from
314
334
  // the run that was lost, so a worker that was plainly running still showed
315
335
  // "process disappeared" until it finished.
336
+ const priorAttemptFingerprint = record.run_evidence?.attempt_fingerprint ?? null;
337
+ const reportOnlyRecovery = record.attention_reason === "invalid_report";
316
338
  let live = {
317
339
  ...record,
318
340
  status: "running",
@@ -381,36 +403,60 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
381
403
  let terminalEvent = false;
382
404
  let rawReport = null;
383
405
  let rawReportEventId = null;
384
- const handleLine = async (line) => {
385
- let event;
386
- try {
387
- event = JSON.parse(line);
388
- } catch (error) {
389
- logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
390
- return;
406
+ const handleLines = async (lines) => {
407
+ const events = [];
408
+ for (const line of lines) {
409
+ try {
410
+ const event = JSON.parse(line);
411
+ logStream.write(`${JSON.stringify(event)}\n`);
412
+ events.push(event);
413
+ } catch (error) {
414
+ logStream.write(`${JSON.stringify({ type: "supervisor.parse_error", line, error: error.message })}\n`);
415
+ }
416
+ }
417
+ if (events.length === 0) return;
418
+ const storedEvents = await appendTaskEvents(record.id, events, { runId, actor: "codex" });
419
+ let next = live;
420
+ for (const [index, event] of events.entries()) {
421
+ if (event.type === "item.completed" && event.item?.type === "agent_message") {
422
+ rawReport = event.item.text;
423
+ rawReportEventId = storedEvents[index].id;
424
+ }
425
+ if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
426
+ next = codexRunner.parseEvent(next, event);
391
427
  }
392
- logStream.write(`${JSON.stringify(event)}\n`);
393
- if (event.type === "item.completed" && event.item?.type === "agent_message") rawReport = event.item.text;
394
- if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
395
- const storedEvent = await appendTaskEvent(record.id, event, { runId, actor: "codex" });
396
- if (event.type === "item.completed" && event.item?.type === "agent_message") rawReportEventId = storedEvent.id;
397
- await persist(applyCodexEvent(live, event));
428
+ await persist(next);
398
429
  };
399
430
 
400
431
  let stdoutRest = "";
401
- child.stdout.on("data", (chunk) => {
432
+ let pendingLines = [];
433
+ let eventFlushPending = false;
434
+ const queueEventLines = (lines) => {
435
+ pendingLines.push(...lines);
436
+ if (eventFlushPending) return;
437
+ eventFlushPending = true;
438
+ eventChain = eventChain.then(async () => {
439
+ await new Promise((resolveFlush) => setImmediate(resolveFlush));
440
+ const batch = pendingLines;
441
+ pendingLines = [];
442
+ eventFlushPending = false;
443
+ await handleLines(batch);
444
+ }).catch((error) => {
445
+ process.stderr.write(`[codex-supervisor] event handling failed for ${record.id}: ${error.message}\n`);
446
+ });
447
+ };
448
+ const handleStdoutChunk = (chunk) => {
402
449
  const split = splitLines(stdoutRest, chunk.toString("utf8"));
403
450
  stdoutRest = split.rest;
404
- for (const line of split.lines) {
405
- if (!line.trim()) continue;
406
- eventChain = eventChain.then(() => handleLine(line)).catch((error) => {
407
- process.stderr.write(`[codex-supervisor] event handling failed for ${record.id}: ${error.message}\n`);
408
- });
409
- }
410
- });
451
+ const lines = split.lines.filter((line) => line.trim());
452
+ if (lines.length) queueEventLines(lines);
453
+ };
454
+ earlyOutput.capture = false;
455
+ for (const chunk of earlyOutput.stdout) handleStdoutChunk(chunk);
456
+ child.stdout.on("data", handleStdoutChunk);
411
457
  child.stdout.on("error", () => {});
412
458
 
413
- let stderr = "";
459
+ let stderr = earlyOutput.stderr.map((chunk) => chunk.toString("utf8")).join("");
414
460
  child.stderr.on("data", (chunk) => {
415
461
  stderr += chunk.toString("utf8");
416
462
  persist({ ...live, stderr_tail: stderr.slice(-4000), updated_at: new Date().toISOString() });
@@ -425,12 +471,15 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
425
471
  });
426
472
  });
427
473
 
428
- child.on("close", async (code, signal) => {
474
+ let settleRun;
475
+ const settled = new Promise((resolveSettled) => { settleRun = resolveSettled; });
476
+ let childSettled = false;
477
+ const finalizeChild = async (code, signal) => {
478
+ if (childSettled) return;
479
+ childSettled = true;
429
480
  if (quotaWatch) clearInterval(quotaWatch);
430
481
  processes.delete(record.id);
431
- if (stdoutRest.trim()) eventChain = eventChain.then(() => handleLine(stdoutRest)).catch((error) => {
432
- process.stderr.write(`[codex-supervisor] final event failed for ${record.id}: ${error.message}\n`);
433
- });
482
+ if (stdoutRest.trim()) queueEventLines([stdoutRest]);
434
483
  await eventChain.catch(() => {});
435
484
  logStream.end();
436
485
  const finishedAt = new Date().toISOString();
@@ -461,10 +510,11 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
461
510
  completed_at: live.completed_at ?? finishedAt,
462
511
  updated_at: finishedAt
463
512
  };
464
- if (status === "failed" && !next.error) {
513
+ const stdinEpipe = /^stdin write failed:.*\bEPIPE\b/i.test(next.error ?? "");
514
+ if (status === "failed" && (!next.error || stdinEpipe)) {
465
515
  next.error = `codex exited with code ${code}${signal ? ` (signal ${signal})` : ""}`;
466
516
  }
467
- if (status === "lost" && !next.error) {
517
+ if (status === "lost" && (!next.error || stdinEpipe)) {
468
518
  next.error = signal ? `codex worker was killed by signal ${signal} before writing a terminal event` : "Codex worker exited without recording a terminal event";
469
519
  }
470
520
  if (status === "cancelled") next.error = null;
@@ -473,18 +523,43 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
473
523
  let externalChanges = [];
474
524
  try { externalChanges = compareExternalOutputs(externalBefore, await captureExternalOutputs(record.guard_policy?.externalOutputs ?? [])); }
475
525
  catch (error) { next.attention_reason = "external_output_unverified"; next.error = error.message; }
526
+ let workspaceAfter = null;
527
+ if (workspaceBefore && Array.isArray(record.workspace_metadata?.manifest_paths)) {
528
+ try {
529
+ workspaceAfter = await captureWorkspaceManifest(record.workspace_metadata.source_root, record.workspace_metadata.manifest_paths);
530
+ } catch (error) {
531
+ next.attention_reason = "workspace_manifest_unverified";
532
+ next.error = error.message;
533
+ }
534
+ }
476
535
  next.run_evidence = {
477
536
  run: live.run_count, commands_run: live.commands.length,
478
537
  structured_report: parseWorkerReport(rawReport),
479
538
  output_before: outputBefore, output_after: outputAfter,
480
- output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null
539
+ output_changed: outputBefore && outputAfter ? outputBefore !== outputAfter : null,
540
+ workspace: workspaceBefore ? {
541
+ kind: record.workspace_kind,
542
+ before_manifest: workspaceBefore,
543
+ after_manifest: workspaceAfter,
544
+ manifest_changed: workspaceAfter ? workspaceBefore.sha256 !== workspaceAfter.sha256 : null
545
+ } : null
481
546
  };
482
547
  next.run_evidence.external_outputs = externalChanges;
483
548
  if (externalChanges.some((entry) => entry.changed)) next.run_evidence.output_changed = true;
484
549
  next.changed_files = [...new Set([...next.changed_files, ...externalChanges.filter((entry) => entry.changed).map((entry) => entry.path)])];
550
+ next.run_evidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
551
+ output_changed: next.run_evidence.output_changed,
552
+ commands_run: live.commands.length,
553
+ changed_files: next.changed_files,
554
+ acceptance_configured: Array.isArray(live.acceptance) && live.acceptance.length > 0,
555
+ workspace_manifest_changed: next.run_evidence.workspace?.manifest_changed ?? null
556
+ })).digest("hex");
485
557
  if (status === "completed" && code === 0 && live.sandbox !== "read-only"
486
558
  && !next.run_evidence.output_changed && next.run_evidence.output_changed !== null
487
- && live.commands.length === 0) next.attention_reason = "no_work";
559
+ && live.commands.length === 0 && !reportOnlyRecovery) {
560
+ next.attention_reason = priorAttemptFingerprint === next.run_evidence.attempt_fingerprint ? "two_stall" : "no_work";
561
+ if (next.attention_reason === "two_stall") next.current_action = "No progress in two consecutive runs; needs attention";
562
+ }
488
563
  if (status === "completed" && !next.run_evidence.structured_report.valid) {
489
564
  next.status = "failed";
490
565
  next.attention_reason = "invalid_report";
@@ -542,8 +617,6 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
542
617
  : next.current_action,
543
618
  updated_at: new Date().toISOString()
544
619
  };
545
- await persist(finalRecord);
546
- await completeRunRecord(finalRecord, live.run_count);
547
620
  await recordOutcomeFacts({
548
621
  task: finalRecord,
549
622
  runId,
@@ -552,19 +625,27 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
552
625
  acceptanceEventId: acceptanceEvent?.id ?? null,
553
626
  acceptancePassed: results.passed === true
554
627
  });
555
- } else {
556
- const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
628
+ if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
557
629
  await persist(finalRecord);
558
630
  await completeRunRecord(finalRecord, live.run_count);
631
+ } else {
632
+ const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
559
633
  await recordOutcomeFacts({
560
634
  task: finalRecord,
561
635
  runId,
562
636
  report: finalRecord.run_evidence?.structured_report,
563
637
  reportEventId: rawReportEventId
564
638
  });
639
+ if (finalRecord.attention_reason === "two_stall") await updateWorkItemDelivery(finalRecord.id, "needs_attention");
640
+ await persist(finalRecord);
641
+ await completeRunRecord(finalRecord, live.run_count);
565
642
  }
566
643
  cancelledTasks.delete(record.id);
567
- });
644
+ };
645
+ child.once("close", (code, signal) => { void finalizeChild(code, signal).finally(settleRun); });
646
+ if (child.exitCode !== null || child.signalCode !== null) {
647
+ setImmediate(() => { void finalizeChild(child.exitCode, child.signalCode).finally(settleRun); });
648
+ }
568
649
 
569
650
  try {
570
651
  child.stdin.end(prompt);
@@ -576,7 +657,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
576
657
  });
577
658
  }
578
659
 
579
- return { ok: true, record: live, child };
660
+ return { ok: true, record: live, child, settled };
580
661
  }
581
662
 
582
663
  // The MCP client may disappear at any point. A detached process owns the
@@ -595,6 +676,7 @@ async function startTrackedRun(job) {
595
676
  ...job.record.input_context,
596
677
  context: compiled.sourceRefs,
597
678
  source_refs: compiled.sourceRefs,
679
+ content_hash: compiled.contentHash,
598
680
  context_snapshot_id: compiled.snapshot.id,
599
681
  context_snapshot_tokens: compiled.snapshot.estimated_tokens,
600
682
  context_fact_count: compiled.factCount
@@ -606,7 +688,10 @@ async function startTrackedRun(job) {
606
688
  env: process.env, windowsHide: true
607
689
  });
608
690
  const started = await new Promise((resolveStart) => {
691
+ let settled = false;
609
692
  const finish = (result) => {
693
+ if (settled) return;
694
+ settled = true;
610
695
  clearTimeout(timer);
611
696
  host.removeAllListeners("message");
612
697
  host.removeAllListeners("exit");
@@ -617,7 +702,7 @@ async function startTrackedRun(job) {
617
702
  const timer = setTimeout(() => {
618
703
  host.kill();
619
704
  finish(failedStart(job.record, "run host startup timed out"));
620
- }, 30000);
705
+ }, RUN_HOST_STARTUP_TIMEOUT_MS);
621
706
  host.once("message", finish);
622
707
  host.once("error", (error) => finish(failedStart(job.record, `run host startup failed: ${error.message}`)));
623
708
  host.once("exit", (code) => finish(failedStart(job.record, `run host exited before startup: ${code}`)));
@@ -629,15 +714,6 @@ async function startTrackedRun(job) {
629
714
  return started;
630
715
  }
631
716
 
632
- function buildExecArgs({ cwd, sandbox, model, reasoningEffort, skipGitRepoCheck }) {
633
- const args = ["exec", "--json", "--cd", cwd, "--sandbox", sandbox];
634
- if (skipGitRepoCheck) args.push("--skip-git-repo-check");
635
- if (model) args.push("--model", model);
636
- args.push("-c", `model_reasoning_effort="${reasoningEffort}"`);
637
- args.push("-");
638
- return args;
639
- }
640
-
641
717
  function validateGoal(goal) {
642
718
  if (!goal || typeof goal !== "object" || typeof goal.objective !== "string" || goal.objective.trim() === "") {
643
719
  throw new Error("goal.objective is required");
@@ -727,7 +803,8 @@ export async function createCodexWorker({
727
803
  goal,
728
804
  dependsOn = [],
729
805
  followupOf = null,
730
- useWorktree = true,
806
+ workspaceKind = null,
807
+ inPlaceAuthorization = null,
731
808
  baseRef = null,
732
809
  preflightId = null,
733
810
  preflight = null,
@@ -779,8 +856,22 @@ export async function createCodexWorker({
779
856
  for (const [name, values] of Object.entries({ forbid, allowedCommands })) {
780
857
  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`);
781
858
  }
859
+ if (baseRef && !isGitCheckout(cwd)) throw invalidBaseRefError(cwd, baseRef);
782
860
 
783
- const projectRoot = cwd;
861
+ const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
862
+ const workspace = await prepareWorkspace({
863
+ cwd,
864
+ workspaceKind,
865
+ sandbox,
866
+ ownedPaths,
867
+ networkAccess,
868
+ acceptance: acceptanceCommands,
869
+ externalOutputs,
870
+ inPlaceAuthorization,
871
+ taskId: id,
872
+ isPreflight: Boolean(preflight)
873
+ });
874
+ const projectRoot = workspace.sourceRoot;
784
875
  const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
785
876
  const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
786
877
  if (conflicts.length > 0) throw ownershipConflictError(conflicts);
@@ -797,12 +888,16 @@ export async function createCodexWorker({
797
888
  }
798
889
  const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
799
890
 
800
- const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
801
- const worktree = useWorktree
802
- ? await ensureWorktree(projectRoot, id, baseRef)
891
+ const worktree = workspace.kind === "git_worktree"
892
+ ? await withWorktreeCreationLock(projectRoot, () => ensureWorktree(projectRoot, id, baseRef))
803
893
  : { path: null, baseCommit: null };
804
894
  const worktreePath = worktree.path;
805
- const effectiveCwd = worktreePath ?? projectRoot;
895
+ if (workspace.kind === "git_worktree" && !worktreePath) {
896
+ const error = new Error("workspaceKind git_worktree could not create an isolated worktree; use read_only_in_place for a non-writing inspection or initialize and commit the repository first");
897
+ error.code = "git_worktree_unavailable";
898
+ throw error;
899
+ }
900
+ const effectiveCwd = worktreePath ?? workspace.executionCwd;
806
901
  if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
807
902
  || preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
808
903
  throw new Error("preflight.probeCommands must be a nonempty list of shell commands");
@@ -814,7 +909,8 @@ export async function createCodexWorker({
814
909
  networkAccess,
815
910
  writableRoots: [...new Set(resolvedWritableRoots)],
816
911
  maxRunMs,
817
- maxTotalMs
912
+ maxTotalMs,
913
+ workspaceKind: workspace.kind
818
914
  };
819
915
  const runtimeContract = buildRuntimeContract({
820
916
  projectRoot,
@@ -825,7 +921,9 @@ export async function createCodexWorker({
825
921
  networkAccess,
826
922
  writableRoots: guardPolicy.writableRoots,
827
923
  context,
828
- contracts
924
+ contracts,
925
+ workspaceKind: workspace.kind,
926
+ workspaceManifestSha256: workspace.beforeManifest?.sha256 ?? null
829
927
  });
830
928
  const preflightMetadata = preflight
831
929
  ? createPreflightMetadata(runtimeContract, preflight.probeCommands)
@@ -839,6 +937,16 @@ export async function createCodexWorker({
839
937
  phase: null,
840
938
  cwd: effectiveCwd,
841
939
  project_root: projectRoot,
940
+ workspace_kind: workspace.kind,
941
+ workspace_metadata: {
942
+ source_root: workspace.sourceRoot,
943
+ execution_root: effectiveCwd,
944
+ manifest_paths: workspace.manifestPaths,
945
+ before_manifest: workspace.beforeManifest,
946
+ in_place_authorization: workspace.kind === "in_place_write" ? String(inPlaceAuthorization).trim() : null,
947
+ landable: workspace.landable,
948
+ cleanable: workspace.cleanable
949
+ },
842
950
  sandbox,
843
951
  model,
844
952
  reasoning_effort: reasoningEffort,
@@ -851,7 +959,14 @@ export async function createCodexWorker({
851
959
  guard_policy: {
852
960
  ...guardPolicy,
853
961
  ...(preflightMetadata ? { preflight: preflightMetadata } : {}),
854
- ...(preflightId ? { preflight_source_id: preflightId } : {})
962
+ ...(preflightId ? { preflight_source_id: preflightId } : {}),
963
+ workspace: {
964
+ kind: workspace.kind,
965
+ source_root: workspace.sourceRoot,
966
+ execution_root: effectiveCwd,
967
+ manifest_paths: workspace.manifestPaths,
968
+ before_manifest_sha256: workspace.beforeManifest?.sha256 ?? null
969
+ }
855
970
  },
856
971
  input_context: { context, contracts },
857
972
  depends_on: Array.isArray(dependsOn) ? dependsOn : [],
@@ -891,7 +1006,12 @@ export async function createCodexWorker({
891
1006
  if (preflightResult.contract_hash !== contractHash) {
892
1007
  const error = new Error(`preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing baseRef, sandbox, ownedPaths, commands, context, contracts, network or writable roots`);
893
1008
  error.code = "preflight_mismatch";
894
- error.details = { preflight_id: preflightId, expected_contract_hash: contractHash, actual_contract_hash: preflightResult.contract_hash };
1009
+ error.details = {
1010
+ preflight_id: preflightId,
1011
+ expected_contract_hash: contractHash,
1012
+ actual_contract_hash: preflightResult.contract_hash,
1013
+ preflight: { expected_contract: runtimeContract, actual_contract: preflightResult.contract }
1014
+ };
895
1015
  throw error;
896
1016
  }
897
1017
  }
@@ -904,10 +1024,11 @@ export async function createCodexWorker({
904
1024
  await runCommand(defaultGitBin,["-C",projectRoot,"worktree","remove",worktreePath]).catch(()=>{});
905
1025
  await runCommand(defaultGitBin,["-C",projectRoot,"branch","-D",`codex/${id}`]).catch(()=>{});
906
1026
  }
1027
+ if (workspace.scratchPath) await rm(workspace.scratchPath, { recursive: true, force: true }).catch(() => {});
907
1028
  throw error;
908
1029
  }
909
1030
 
910
- const args = buildExecArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
1031
+ const args = codexRunner.startArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
911
1032
 
912
1033
  const started = await startTrackedRun({
913
1034
  record,
@@ -1009,13 +1130,7 @@ export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acc
1009
1130
  }
1010
1131
 
1011
1132
  const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
1012
- const args = ["exec", "resume", "--json"];
1013
- args.push("-c", `sandbox_mode="${task.sandbox}"`);
1014
- if (task.model) args.push("--model", task.model);
1015
- args.push("-c", `model_reasoning_effort="${task.reasoning_effort ?? "high"}"`);
1016
- if (task.skip_git_repo_check) args.push("--skip-git-repo-check");
1017
- args.push(task.thread_id);
1018
- args.push("-");
1133
+ const args = codexRunner.resumeArgs(task);
1019
1134
 
1020
1135
  const started = await startTrackedRun({
1021
1136
  record: { ...task, resumed_from: task.resumed_from ?? task.id },
@@ -1064,6 +1179,7 @@ export async function recoverEligibleRuns() {
1064
1179
 
1065
1180
  if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "--run-host") {
1066
1181
  process.once("message", async (job) => {
1182
+ const keepAlive = setInterval(() => {}, 1000);
1067
1183
  let result;
1068
1184
  try {
1069
1185
  result = await trackRunInHost(job);
@@ -1072,9 +1188,10 @@ if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === "-
1072
1188
  result = failedStart(job.record, `run host failed: ${error.message}`);
1073
1189
  await upsertTask(result.record);
1074
1190
  }
1075
- if (process.connected) process.send({ ok: result.ok, record: result.record }, () => {
1076
- if (process.connected) process.disconnect();
1077
- });
1191
+ if (process.connected) await new Promise((resolveSent) => process.send({ ok: result.ok, record: result.record }, resolveSent));
1192
+ if (result.settled) await result.settled;
1193
+ clearInterval(keepAlive);
1194
+ if (process.connected) process.disconnect();
1078
1195
  });
1079
1196
  }
1080
1197
 
@@ -1129,39 +1246,18 @@ function describeProcess(pid) {
1129
1246
  }
1130
1247
 
1131
1248
  function isLikelyCodexProcess(pid) {
1132
- const description = describeProcess(pid);
1133
- return description.includes("codex");
1249
+ return codexRunner.ownsPid(pid, describeProcess);
1134
1250
  }
1135
1251
 
1136
1252
  // Ends a worker and, on Windows, its whole process tree: the direct child there
1137
1253
  // is the JS wrapper around the native Codex binary, so terminating it alone
1138
1254
  // would leave the real CLI running and the task stuck in `running`.
1139
1255
  function terminateChild(child) {
1140
- if (process.platform === "win32" && child.pid) {
1141
- try {
1142
- execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
1143
- stdio: "ignore",
1144
- timeout: 5000,
1145
- windowsHide: true
1146
- });
1147
- return;
1148
- } catch {
1149
- // fall back to the handle-based kill below
1150
- }
1151
- }
1152
- child.kill("SIGTERM");
1256
+ codexRunner.cancelChild(child);
1153
1257
  }
1154
1258
 
1155
1259
  function terminatePid(pid) {
1156
- if (process.platform === "win32") {
1157
- execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
1158
- stdio: "ignore",
1159
- timeout: 5000,
1160
- windowsHide: true
1161
- });
1162
- return;
1163
- }
1164
- process.kill(pid, "SIGTERM");
1260
+ codexRunner.cancelPid(pid);
1165
1261
  }
1166
1262
 
1167
1263
  export async function cancelCodexWorker(taskId) {
@@ -1228,7 +1324,9 @@ export async function createFollowupWorker({
1228
1324
  networkAccess,
1229
1325
  writableRoots,
1230
1326
  maxRunMs,
1231
- maxTotalMs
1327
+ maxTotalMs,
1328
+ workspaceKind,
1329
+ inPlaceAuthorization
1232
1330
  }) {
1233
1331
  const parent = await getTask(taskId);
1234
1332
  if (!parent) throw new Error(`task not found: ${taskId}`);
@@ -1280,7 +1378,8 @@ export async function createFollowupWorker({
1280
1378
  goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
1281
1379
  dependsOn: [],
1282
1380
  followupOf: parent.id,
1283
- useWorktree: true,
1381
+ workspaceKind: workspaceKind ?? (parent.workspace_kind === "legacy" ? null : parent.workspace_kind),
1382
+ inPlaceAuthorization: inPlaceAuthorization ?? parent.workspace_metadata?.in_place_authorization ?? null,
1284
1383
  baseRef: baseRef ?? null,
1285
1384
  // Inherited unless given; the follow-up runs in a fresh worktree cut
1286
1385
  // from the project HEAD, so the parent's checks only pass there once