codex-supervisor-mcp 0.11.1 → 0.12.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.
package/src/mcp-server.js CHANGED
@@ -59,10 +59,13 @@ import {
59
59
  import { readNativeGoal, readNativeGoalState } from "./goal-store.js";
60
60
  import { collectWorkerChanges } from "./worker-changes.js";
61
61
  import { buildHostGoalSync } from "./prompt.js";
62
- import { baseBehind, readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
62
+ import { baseBehind, readTaskChanges, readWorktreeDiff, splitPatchHunks, workspaceSetupIgnorePaths, worktreeRef } from "./worktree.js";
63
63
  import { summarizeVerification } from "./event-parser.js";
64
64
  import { readPreflightResult } from "./worker-preflight.js";
65
65
  import { acceptanceVerdict, runAcceptance } from "./acceptance.js";
66
+ import { classifyFailure } from "./failure-class.js";
67
+ import { threadHealth } from "./thread-health.js";
68
+ import { readStage } from "./stage-store.js";
66
69
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
67
70
  import { approxTokenCount, truncateEventStrings, truncateMiddleChars, truncateReport } from "./truncate.js";
68
71
  import { checkForUpdate, updateNotice } from "./update-check.js";
@@ -204,11 +207,14 @@ function sleep(ms) {
204
207
  function isSettled(task) {
205
208
  if (!TERMINAL_STATUSES.has(task.status)) return false;
206
209
  if (task.attention_reason === "start_failed") return true;
210
+ if (task.guard_policy?.preflight && readPreflightResult(task).status === "passed") return true;
207
211
  if (task.status !== "completed" && task.status !== "failed") return true;
208
212
  // Acceptance is running in the supervisor process that owned the worker;
209
213
  // the codex pid is already dead, so that process is what to wait on.
210
214
  if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
211
- if (["interrupted", "cancelled"].includes(task.acceptance_results?.status)) return true;
215
+ if (["interrupted", "cancelled"].includes(task.acceptance_results?.status)) {
216
+ return task.exit_code !== null && task.exit_code !== undefined;
217
+ }
212
218
  if (task.exit_code !== null && task.exit_code !== undefined) return true;
213
219
  // A dead Codex pid does not prove that its owner's close handler finished
214
220
  // draining the stream and writing the exit status. Leave the half-written
@@ -225,12 +231,44 @@ function isSettled(task) {
225
231
  const LIVE_COMMAND_PREVIEW_CHARS = 120;
226
232
  function liveness(task) {
227
233
  if (!ACTIVE_STATUSES.has(task.status)) {
228
- return { idle_seconds: null, command_running: false, current_command: null };
234
+ const stage = readStage(task.id);
235
+ return {
236
+ idle_seconds: null,
237
+ command_running: false,
238
+ current_command: null,
239
+ current_stage: null,
240
+ current_stage_detail: null,
241
+ last_stage: stage?.stage ?? null,
242
+ stage_updated_at: stage?.updated_at ?? null
243
+ };
229
244
  }
230
245
  const since = Date.parse(task.last_event_at ?? task.started_at ?? "");
231
246
  const idle = Number.isFinite(since) ? Math.max(0, Math.floor((Date.now() - since) / 1000)) : null;
232
247
  const command = task.current_command ? clip(task.current_command, LIVE_COMMAND_PREVIEW_CHARS) : null;
233
- return { idle_seconds: idle, command_running: Boolean(task.current_command), current_command: command };
248
+ const stage = readStage(task.id);
249
+ const active = ACTIVE_STATUSES.has(task.status);
250
+ return {
251
+ idle_seconds: idle,
252
+ command_running: Boolean(task.current_command),
253
+ current_command: command,
254
+ current_stage: active ? stage?.stage ?? null : null,
255
+ current_stage_detail: active ? stage?.detail ?? null : null,
256
+ last_stage: active ? null : stage?.stage ?? null,
257
+ stage_updated_at: stage?.updated_at ?? null
258
+ };
259
+ }
260
+
261
+ function compactLiveness(task) {
262
+ const live = liveness(task);
263
+ return {
264
+ idle_seconds: live.idle_seconds,
265
+ command_running: live.command_running,
266
+ current_command: live.current_command,
267
+ ...(live.current_stage ? { current_stage: live.current_stage } : {}),
268
+ ...(live.current_stage_detail ? { current_stage_detail: live.current_stage_detail } : {}),
269
+ ...(live.last_stage ? { last_stage: live.last_stage } : {}),
270
+ ...(live.stage_updated_at ? { stage_updated_at: live.stage_updated_at } : {})
271
+ };
234
272
  }
235
273
 
236
274
  // The acceptance verdict as get_worker_result reports it, with the one
@@ -297,7 +335,10 @@ function summarizeTask(task) {
297
335
  goal_objective: task.goal_objective,
298
336
  goal_token_budget: task.goal_token_budget,
299
337
  goal_status: task.goal_status,
338
+ goal_tokens_used: task.goal_tokens_used ?? null,
339
+ thread_health: threadHealth(task),
300
340
  attention_reason: task.attention_reason ?? null,
341
+ failure: classifyFailure(task),
301
342
  changed_file_count: (task.changed_files ?? []).length,
302
343
  command_count: (task.commands ?? []).length,
303
344
  run_count: task.run_count ?? 0,
@@ -374,6 +415,7 @@ function receipt(task) {
374
415
  goal_objective: task.goal_objective,
375
416
  goal_token_budget: task.goal_token_budget,
376
417
  error: task.error ?? null,
418
+ failure: classifyFailure(task),
377
419
  run_count: task.run_count ?? 0,
378
420
  run_log: task.run_log,
379
421
  created_at: task.created_at,
@@ -382,6 +424,7 @@ function receipt(task) {
382
424
  }
383
425
 
384
426
  function overviewRow(task, caps) {
427
+ const live = liveness(task);
385
428
  return {
386
429
  id: task.id,
387
430
  title: clip(task.title, caps.title),
@@ -390,9 +433,13 @@ function overviewRow(task, caps) {
390
433
  goal: clip(task.goal_objective, caps.goal),
391
434
  goal_status: task.goal_status ?? null,
392
435
  last_action: clip(task.current_action, caps.action),
393
- idle_seconds: liveness(task).idle_seconds,
436
+ idle_seconds: live.idle_seconds,
394
437
  command_running: Boolean(task.current_command) && ACTIVE_STATUSES.has(task.status),
438
+ ...(live.current_stage ? { current_stage: live.current_stage } : {}),
439
+ ...(live.last_stage ? { last_stage: live.last_stage } : {}),
395
440
  acceptance: acceptanceVerdict(task),
441
+ ...(classifyFailure(task)?.code ? { failure_code: classifyFailure(task).code } : {}),
442
+ ...(threadHealth(task).state === "handoff_recommended" ? { handoff_recommended: true } : {}),
396
443
  changed_files: (task.changed_files ?? []).length,
397
444
  depends_on: task.depends_on ?? [],
398
445
  owned_paths: (task.owned_paths ?? []).map((entry) => clip(entry, caps.path))
@@ -565,6 +612,14 @@ const acceptanceCheck = z.union([
565
612
  }).strict()
566
613
  ]);
567
614
  const acceptanceInput = z.union([z.string().min(1), z.array(acceptanceCheck).max(10)]);
615
+ const workspaceSetupInput = z.object({
616
+ links: z.array(z.object({
617
+ path: z.string().min(1),
618
+ source: z.string().min(1)
619
+ }).strict()).max(20).optional(),
620
+ submodules: z.boolean().optional(),
621
+ commands: z.array(z.string().min(1)).max(20).optional()
622
+ }).strict();
568
623
 
569
624
  const observerId = process.env.CODEX_SUPERVISOR_OBSERVER_ID?.trim() || `mcp-${randomUUID()}`;
570
625
  const deltaObserverId = process.env.CODEX_SUPERVISOR_DELTA_OBSERVER_ID?.trim() || `${observerId}:delta`;
@@ -671,6 +726,7 @@ server.registerTool(
671
726
  baseRef: z.string().min(1).optional(),
672
727
  workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
673
728
  inPlaceAuthorization: z.string().min(1).max(2000).optional(),
729
+ workspaceSetup: workspaceSetupInput.optional(),
674
730
  probeCommands: z.array(z.string().min(1)).min(1).max(20)
675
731
  }
676
732
  },
@@ -758,6 +814,7 @@ server.registerTool(
758
814
  baseRef: z.string().min(1).optional(),
759
815
  workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
760
816
  inPlaceAuthorization: z.string().min(1).max(2000).optional(),
817
+ workspaceSetup: workspaceSetupInput.optional(),
761
818
  // A successful preflight_codex_worker task id. When present, this worker
762
819
  // is refused unless base commit and the complete runtime contract match.
763
820
  preflight_id: z.string().min(1).optional(),
@@ -812,6 +869,7 @@ server.registerTool(
812
869
  maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
813
870
  workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
814
871
  inPlaceAuthorization: z.string().min(1).max(2000).optional(),
872
+ workspaceSetup: workspaceSetupInput.optional(),
815
873
  goal: z
816
874
  .object({
817
875
  objective: z.string().min(1),
@@ -929,6 +987,7 @@ server.registerTool(
929
987
  timeoutMinutes: z.number().int().min(1).max(360).default(1),
930
988
  timeoutMs: z.number().int().min(1000).max(21600000).optional(),
931
989
  pollMs: z.number().int().min(250).max(10000).default(1000),
990
+ emitProgress: z.boolean().default(false),
932
991
  // Off by default. A wait is the call clients background and then replay
933
992
  // as a notification, so its payload has to stay small; ten events per
934
993
  // worker was the bulk of it. Ask for events explicitly, or read
@@ -953,6 +1012,7 @@ server.registerTool(
953
1012
  timeoutMinutes,
954
1013
  timeoutMs,
955
1014
  pollMs,
1015
+ emitProgress,
956
1016
  includeEvents,
957
1017
  eventLimit,
958
1018
  eventMaxChars,
@@ -966,15 +1026,16 @@ server.registerTool(
966
1026
  const progressToken = extra?._meta?.progressToken;
967
1027
  let lastProgressAt = -Infinity;
968
1028
 
1029
+ let clientCancelled = false;
969
1030
  while (Date.now() - startedAt < effectiveTimeoutMs) {
970
- if (extra?.signal.aborted) break;
1031
+ if (extra?.signal.aborted) { clientCancelled = true; break; }
971
1032
  await reconcileDetachedActiveTasks();
972
1033
  tasks = (await getTasks(task_ids)).filter(Boolean);
973
1034
  const settledCount = tasks.filter(isSettled).length;
974
1035
  const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
975
1036
  if (isDone) break;
976
1037
  const elapsed = Date.now() - startedAt;
977
- if (progressToken != null && elapsed - lastProgressAt >= 30000) {
1038
+ if (emitProgress && progressToken != null && elapsed - lastProgressAt >= 30000) {
978
1039
  await extra.sendNotification({ method: "notifications/progress", params: {
979
1040
  progressToken, progress: elapsed, total: effectiveTimeoutMs,
980
1041
  message: `${settledCount}/${task_ids.length} workers settled; wait budget only`
@@ -1011,6 +1072,7 @@ server.registerTool(
1011
1072
  mode,
1012
1073
  timed_out: timedOut,
1013
1074
  still_running: timedOut,
1075
+ termination_reason: clientCancelled ? "client_cancelled" : timedOut ? "budget_exhausted" : "settled",
1014
1076
  next_step: timedOut
1015
1077
  ? `Workers are still running; the ${budgetLabel} wait budget ran out, not the workers. Call wait_codex_workers again with the same task_ids, or use get_orchestration_overview for a cheap progress read. Raise timeoutMinutes only if your client's MCP tool timeout allows it.`
1016
1078
  : null,
@@ -1033,7 +1095,7 @@ server.registerTool(
1033
1095
  exit_code: task.exit_code ?? null,
1034
1096
  changed_file_count: readTaskChanges(task).length,
1035
1097
  acceptance: acceptanceVerdict(task),
1036
- ...liveness(task),
1098
+ ...compactLiveness(task),
1037
1099
  updated_at: task.updated_at ?? null
1038
1100
  }))
1039
1101
  : summaries
@@ -1647,28 +1709,86 @@ server.registerTool(
1647
1709
  {
1648
1710
  title: "Get worker diff",
1649
1711
  description:
1650
- "The worker's actual changes as patches: everything between the commit its worktree started from and its working tree, committed or not, plus untracked files. This is the ground truth to check a worker's report against. maxChars bounds the whole answer: files past the budget come back listed but without a patch, so the file list is always complete. paths narrows the diff to those files or directories.",
1712
+ "The worker's actual changes. By default this is a complete file/hunk index; request one file to page through hunks with pageSize or cursor. Supplying maxChars without file preserves the legacy bounded full-diff response. This is the ground truth to check a worker's report against.",
1651
1713
  inputSchema: {
1652
1714
  task_id: z.string().min(1),
1653
- maxChars: z.number().int().min(0).max(1000000).default(60000),
1715
+ maxChars: z.number().int().min(0).max(1000000).optional(),
1716
+ file: z.string().min(1).optional(),
1717
+ hunk: z.number().int().min(0).optional(),
1718
+ pageSize: z.number().int().min(1).max(20).default(4),
1719
+ cursor: z.string().min(1).optional(),
1654
1720
  paths: z.array(z.string().min(1)).optional()
1655
1721
  }
1656
1722
  },
1657
- async ({ task_id, maxChars, paths }) => {
1723
+ async ({ task_id, maxChars, file, hunk, pageSize, cursor, paths }) => {
1658
1724
  const task = await getTask(task_id);
1659
1725
  if (!task) return textResult({ error: "task_not_found", task_id });
1660
1726
  if (!task.worktree_path) {
1661
1727
  return textResult({ error: "no_worktree", task_id, external_outputs: externalOutputView(task, maxChars), reason: "this worker ran in place (its cwd is not a git repository or the worktree could not be created), so there is no isolated diff to read; call get_worker_result with includeFiles: true for the files it touched" });
1662
1728
  }
1663
- const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [] });
1664
- return textResult({
1729
+ if (!file && maxChars !== undefined) {
1730
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [], ignorePaths: workspaceSetupIgnorePaths(task) });
1731
+ return textResult({
1732
+ task_id,
1733
+ title: task.title,
1734
+ status: task.status,
1735
+ worktree_path: task.worktree_path,
1736
+ branch: `codex/${task.id}`,
1737
+ ...diff,
1738
+ external_outputs: externalOutputView(task, maxChars)
1739
+ });
1740
+ }
1741
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 10_000_000, paths: paths ?? [], ignorePaths: workspaceSetupIgnorePaths(task) });
1742
+ if (diff.error) return textResult({ ...diff, task_id });
1743
+ const files = diff.files.map((entry) => {
1744
+ const parsed = splitPatchHunks(entry);
1745
+ return { path: entry.path, status: entry.status, from: entry.from, additions: entry.additions, deletions: entry.deletions, hunk_count: parsed.hunks.length };
1746
+ });
1747
+ const base = {
1665
1748
  task_id,
1666
1749
  title: task.title,
1667
1750
  status: task.status,
1668
1751
  worktree_path: task.worktree_path,
1669
1752
  branch: `codex/${task.id}`,
1670
1753
  ...diff,
1671
- external_outputs: externalOutputView(task, maxChars)
1754
+ files,
1755
+ external_outputs: externalOutputView(task, maxChars || 6000)
1756
+ };
1757
+ if (!file) return textResult({ ...base, summary_only: true, next_step: "choose files[].path, then request file plus hunk or cursor" });
1758
+ const selected = diff.files.find((entry) => entry.path === file);
1759
+ if (!selected) return textResult({ error: "diff_file_not_found", task_id, file, files });
1760
+ const parsed = splitPatchHunks(selected);
1761
+ let offset = 0;
1762
+ if (cursor) {
1763
+ try {
1764
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
1765
+ if (value.task_id !== task_id || value.file !== file || !Number.isInteger(value.offset) || value.offset < 0) throw new Error("mismatch");
1766
+ offset = value.offset;
1767
+ } catch {
1768
+ return textResult({ error: "invalid_diff_cursor", task_id, file });
1769
+ }
1770
+ }
1771
+ if (hunk !== undefined) offset = hunk;
1772
+ if (offset >= parsed.hunks.length) return textResult({ error: "diff_hunk_not_found", task_id, file, hunk: offset, hunk_count: parsed.hunks.length });
1773
+ let remaining = maxChars ?? 24000;
1774
+ const hunks = [];
1775
+ for (let index = offset; index < parsed.hunks.length && hunks.length < pageSize; index += 1) {
1776
+ if (remaining <= 0) break;
1777
+ const item = parsed.hunks[index];
1778
+ const patchText = item.patch.length > remaining ? truncateMiddleChars(item.patch, remaining) : item.patch;
1779
+ hunks.push({ ...item, patch: patchText, truncated: patchText.length < item.patch.length });
1780
+ remaining -= patchText.length;
1781
+ }
1782
+ const nextOffset = offset + hunks.length;
1783
+ const nextCursor = nextOffset < parsed.hunks.length
1784
+ ? Buffer.from(JSON.stringify({ task_id, file, offset: nextOffset })).toString("base64url")
1785
+ : null;
1786
+ return textResult({
1787
+ ...base,
1788
+ file: { path: selected.path, status: selected.status, from: selected.from, additions: selected.additions, deletions: selected.deletions, hunk_count: parsed.hunks.length },
1789
+ hunks,
1790
+ next_cursor: nextCursor,
1791
+ summary_only: false
1672
1792
  });
1673
1793
  }
1674
1794
  );
@@ -1,4 +1,6 @@
1
1
  import { ACTIVE_STATUSES, isGoalNeedingAttention } from "./status.js";
2
+ import { classifyFailure } from "./failure-class.js";
3
+ import { threadHealth } from "./thread-health.js";
2
4
 
3
5
  function readyToLand(task) {
4
6
  return task.status === "completed" && task.exit_code === 0 && (!task.acceptance_results || task.acceptance_results.passed === true) && !task.landed_at;
@@ -37,7 +39,9 @@ export function buildOverviewDelta(tasks, cursor = {}, { readyToCleanTaskIds = n
37
39
  const isReadyToLand = land.some((item) => item.id === task.id);
38
40
  const isReadyToClean = clean.some((item) => item.id === task.id);
39
41
  const reason = attentionReason(task);
40
- const fingerprint = JSON.stringify([task.run_count ?? 0, task.status, task.exit_code ?? null, task.attention_reason ?? null, task.landed_head ?? null, task.push_verified_at ?? null, task.delivery_state ?? null, isReadyToClean, reason, task.updated_at]);
42
+ const failure = classifyFailure(task);
43
+ const health = threadHealth(task);
44
+ const fingerprint = JSON.stringify([task.run_count ?? 0, task.status, task.exit_code ?? null, task.attention_reason ?? null, task.landed_head ?? null, task.push_verified_at ?? null, task.delivery_state ?? null, isReadyToClean, reason, task.goal_tokens_used ?? null, health.state, task.updated_at]);
41
45
  nextCursor[task.id] = fingerprint;
42
46
  if (cursor[task.id] !== fingerprint) {
43
47
  changes.push({
@@ -47,6 +51,9 @@ export function buildOverviewDelta(tasks, cursor = {}, { readyToCleanTaskIds = n
47
51
  delivery_state: task.delivery_state ?? "draft",
48
52
  attention: isAttention,
49
53
  attention_reason: reason,
54
+ failure_source: failure?.source ?? null,
55
+ failure_code: failure?.code ?? null,
56
+ handoff_recommended: health.state === "handoff_recommended",
50
57
  ready_to_land: isReadyToLand,
51
58
  ready_to_clean: isReadyToClean,
52
59
  next_action: nextAction(task, { attention: isAttention, readyToLand: isReadyToLand, readyToClean: isReadyToClean }),
package/src/paths.js CHANGED
@@ -20,5 +20,6 @@ export const dataDir = join(supervisorRoot, "data");
20
20
  export const dbPath = join(dataDir, "supervisor.sqlite");
21
21
  export const runsDir = join(dataDir, "runs");
22
22
  export const artifactsDir = join(dataDir, "artifacts");
23
+ export const stagesDir = join(dataDir, "stages");
23
24
  export const worktreesDir = join(supervisorRoot, "worktrees");
24
25
  export const scratchDir = join(supervisorRoot, "scratch");
package/src/prompt.js CHANGED
@@ -38,6 +38,7 @@ export function buildGoalPreamble({ objective, tokenBudget = null, resume = fals
38
38
  return [
39
39
  "Do this first, before any other work:",
40
40
  `Call the create_goal tool with objective exactly "${goal}"${budget}.`,
41
+ tokenBudget ? "Use only the token budget given above; do not invent a smaller or larger one." : "Do not set a token_budget; the dispatcher did not provide one.",
41
42
  "That goal is how your supervisor tracks this work; do not skip it.",
42
43
  'When the objective is achieved and no required work remains, call update_goal with status "complete".',
43
44
  'If the same blocker repeats for three consecutive turns and you cannot make progress, call update_goal with status "blocked" instead.'
@@ -52,12 +53,14 @@ export const REPORT_SECTIONS = ["Result", "Verification", "Not done / risks"];
52
53
  // may do instead of being told to use apply_patch they cannot use.
53
54
  export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands = [], forbid = [], networkAccess = false, workspaceKind = null } = {}) {
54
55
  const forbidden = JSON.stringify(forbid);
56
+ const stage = 'For a long gate, checkpoint phases with node "$CODEX_SUPERVISOR_STAGE_CLI" "gate:s3" --detail "current check"; stage text is visible to status/overview/wait and must not contain secrets.';
55
57
  if (sandbox === "read-only") {
56
58
  return [
57
59
  "Runtime supervisor guard: this is a read-only task.",
58
60
  "The sandbox denies every file write, the temp directory included, and it has no network, so do not try to write files, fetch URLs or install anything: they fail and waste the turn.",
59
61
  "Run the read commands you need (rg, cat, git, jq, the project's own read-only tools) and put the findings in the final report.",
60
- `Forbidden: ${forbidden}.`
62
+ `Forbidden: ${forbidden}.`,
63
+ stage
61
64
  ].join(" ");
62
65
  }
63
66
  if (Array.isArray(ownedPaths) && ownedPaths.length === 0) {
@@ -69,6 +72,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
69
72
  `${location}, so the shell is unrestricted apart from the red lines; keep notes and downloads inside it.`,
70
73
  networkAccess ? "Network is available." : "There is no network in this sandbox; ask for it instead of retrying a failing fetch.",
71
74
  `Forbidden: ${forbidden}.`,
75
+ stage,
72
76
  "Report what you found and name the files a writer would have to change."
73
77
  ].join(" ");
74
78
  }
@@ -76,7 +80,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
76
80
  // shell as a heredoc; the guard accepts that shape too, so the worker is told
77
81
  // about it instead of stalling on a tool it does not have.
78
82
  const shellEdit = "If your toolset has no apply_patch tool, run it through the shell as apply_patch <<'EOF' ... EOF; the guard checks the file paths the same way. A declared command ending in * is a prefix, so go test ./internal/* covers go test ./internal/service -run TestX.";
79
- return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} Safe read-only inspection commands (rg, cat, sed without -i, git status/diff/log, jq without -i, find without -exec/-delete) are allowed and never reserve another worker's paths. Commands that validate, write, execute code or have side effects must exactly match declared commands ${JSON.stringify(allowedCommands)}. Forbidden: ${forbidden}. Undeclared shell programs are denied; report a needed validation command instead of bypassing the guard.`;
83
+ return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} Safe read-only inspection commands (rg, cat, sed without -i, git status/diff/log, jq without -i, find without -exec/-delete) are allowed and never reserve another worker's paths. Commands that validate, write, execute code or have side effects must exactly match declared commands ${JSON.stringify(allowedCommands)}. Forbidden: ${forbidden}. Undeclared shell programs are denied; report a needed validation command instead of bypassing the guard. ${stage}`;
80
84
  }
81
85
 
82
86
  // The acceptance commands are shown to the worker. Hiding them would not
@@ -0,0 +1,39 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { stagesDir } from "./paths.js";
4
+
5
+ function validate(taskId, stage, detail) {
6
+ if (!/^codex-[A-Za-z0-9-]+$/.test(String(taskId ?? ""))) throw new Error("invalid task id for stage checkpoint");
7
+ const name = String(stage ?? "").trim();
8
+ if (!name || name.length > 200) throw new Error("stage must be 1-200 characters");
9
+ const note = detail == null ? null : String(detail).trim();
10
+ if (note && note.length > 1000) throw new Error("stage detail must be at most 1000 characters");
11
+ return { name, note };
12
+ }
13
+
14
+ export function stagePath(taskId) {
15
+ validate(taskId, "stage", null);
16
+ return join(stagesDir, `${taskId}.json`);
17
+ }
18
+
19
+ export function writeStage(taskId, stage, detail = null) {
20
+ const value = validate(taskId, stage, detail);
21
+ mkdirSync(stagesDir, { recursive: true });
22
+ const destination = stagePath(taskId);
23
+ const staging = `${destination}.tmp-${process.pid}-${Date.now()}`;
24
+ const payload = { task_id: taskId, stage: value.name, detail: value.note, updated_at: new Date().toISOString() };
25
+ writeFileSync(staging, JSON.stringify(payload, null, 2));
26
+ renameSync(staging, destination);
27
+ return payload;
28
+ }
29
+
30
+ export function readStage(taskId) {
31
+ let path;
32
+ try { path = stagePath(taskId); } catch { return null; }
33
+ if (!existsSync(path)) return null;
34
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
35
+ }
36
+
37
+ export function clearStage(taskId) {
38
+ try { rmSync(stagePath(taskId), { force: true }); } catch { /* invalid legacy task id */ }
39
+ }
package/src/stage.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { writeStage } from "./stage-store.js";
3
+
4
+ const argv = process.argv.slice(2);
5
+ let taskId = process.env.CODEX_SUPERVISOR_TASK_ID;
6
+ let detail = null;
7
+ const positional = [];
8
+ for (let index = 0; index < argv.length; index += 1) {
9
+ if (argv[index] === "--detail") detail = argv[++index];
10
+ else positional.push(argv[index]);
11
+ }
12
+ const stage = positional.join(" ").trim();
13
+ if (!taskId || !stage) {
14
+ console.error('usage: codex-supervisor-stage "gate:s3" [--detail "..."] (task comes from CODEX_SUPERVISOR_TASK_ID)');
15
+ process.exit(2);
16
+ }
17
+ process.stdout.write(`${JSON.stringify(writeStage(taskId, stage, detail))}\n`);
package/src/task-store.js CHANGED
@@ -10,6 +10,7 @@ import { normalizeAcceptance } from "./acceptance.js";
10
10
  import { createHash, randomUUID } from "node:crypto";
11
11
  import { captureWorkspaceManifest } from "./workspace-kind.js";
12
12
  import { buildHandoff } from "./handoff.js";
13
+ import { readPreflightResult } from "./worker-preflight.js";
13
14
 
14
15
  let db;
15
16
 
@@ -667,11 +668,17 @@ export async function reconcileDetachedActiveTasks() {
667
668
  await reconcileInterruptedAcceptance();
668
669
  const incomplete = (await readTasks()).filter((task) =>
669
670
  ["completed", "failed"].includes(task.status) && task.exit_code == null && task.started_at
670
- && !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid) && !task.acceptance_results
671
+ && !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid)
672
+ && (!task.acceptance_results || ["interrupted", "cancelled"].includes(task.acceptance_results.status))
671
673
  && Date.now() - Date.parse(task.updated_at) > 5000);
672
674
  for (const task of incomplete) {
673
675
  await writeTask({ ...task, status: "lost", phase: null,
674
- error: "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
676
+ error: task.acceptance_results?.status === "interrupted"
677
+ ? "Worker ended but its supervisor did not record the process exit before acceptance; resume this run"
678
+ : "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
679
+ current_action: task.acceptance_results?.status === "interrupted"
680
+ ? "Acceptance interrupted: worker process exit was not recorded; resume this run"
681
+ : "Resume required: process exit was not recorded",
675
682
  updated_at: new Date().toISOString() });
676
683
  }
677
684
  const tasks = await readActiveTasks();
@@ -748,11 +755,17 @@ function checkOwnership(taskId, incoming) {
748
755
  return a===b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
749
756
  };
750
757
  const conflicts = [];
751
- const pending = openDb().prepare("SELECT t.id,t.title,t.status,t.owned_paths,t.acceptance_results,t.started_at,t.exit_code,c.owner_pid FROM tasks t LEFT JOIN run_claims c ON c.task_id=t.id WHERE t.id<>? AND (c.owner_pid IS NOT NULL OR status IN ('queued','running') OR json_extract(acceptance_results,'$.status')='running' OR (status IN ('completed','failed') AND started_at IS NOT NULL AND exit_code IS NULL AND acceptance_results IS NULL))").all(taskId);
758
+ const pending = openDb().prepare("SELECT t.id,t.title,t.status,t.owned_paths,t.acceptance_results,t.started_at,t.exit_code,t.guard_policy,t.commands,t.attention_reason,c.owner_pid FROM tasks t LEFT JOIN run_claims c ON c.task_id=t.id WHERE t.id<>? AND (c.owner_pid IS NOT NULL OR status IN ('queued','running') OR json_extract(acceptance_results,'$.status')='running' OR (status IN ('completed','failed') AND started_at IS NOT NULL AND exit_code IS NULL AND acceptance_results IS NULL))").all(taskId);
752
759
  for (const row of pending) {
753
760
  const settling = decodeJson(row.acceptance_results,null)?.status === "running"
754
761
  || (["completed","failed"].includes(row.status) && row.started_at && row.exit_code == null && !row.acceptance_results);
755
762
  if (row.owner_pid && !ACTIVE_STATUSES.has(row.status) && !settling && !isPidAlive(row.owner_pid)) continue;
763
+ const preflightTask = {
764
+ ...row,
765
+ guard_policy: decodeJson(row.guard_policy, null),
766
+ commands: decodeJson(row.commands, [])
767
+ };
768
+ if (preflightTask.guard_policy?.preflight && readPreflightResult(preflightTask).status === "passed") continue;
756
769
  const paths=decodeJson(row.owned_paths,[]);
757
770
  const matching=incoming.flatMap(path=>paths.filter(other=>overlaps(path,other)).map(other=>({incoming:path,existing:other})));
758
771
  if(matching.length)conflicts.push({task_id:row.id,title:row.title,status:row.status,overlapping_paths:matching});
@@ -0,0 +1,33 @@
1
+ const DEFAULT_HANDOFF_TOKEN_THRESHOLD = 300000;
2
+ const LONG_THREAD_RATIO = 0.75;
3
+
4
+ export function handoffTokenThreshold(env = process.env) {
5
+ const raw = env.CODEX_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD;
6
+ if (raw == null || raw === "") return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
7
+ const value = Number(raw);
8
+ if (!Number.isFinite(value) || value < 0) return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
9
+ return value;
10
+ }
11
+
12
+ export function threadHealth(task, { threshold = handoffTokenThreshold() } = {}) {
13
+ if (threshold === 0) return { state: "disabled", threshold: 0, tokens_used: task?.goal_tokens_used ?? 0, next_step: null };
14
+ const tokens = Number(task?.goal_tokens_used ?? 0);
15
+ if (!Number.isFinite(tokens) || tokens <= 0) return { state: "ok", threshold, tokens_used: 0, next_step: null };
16
+ if (tokens >= threshold) {
17
+ return {
18
+ state: "handoff_recommended",
19
+ threshold,
20
+ tokens_used: tokens,
21
+ next_step: "Start a fresh 1000-1500-token handoff with create_codex_followup_worker; keep this thread as evidence"
22
+ };
23
+ }
24
+ if (tokens >= Math.floor(threshold * LONG_THREAD_RATIO)) {
25
+ return {
26
+ state: "getting_long",
27
+ threshold,
28
+ tokens_used: tokens,
29
+ next_step: "Finish this bounded step, then create a follow-up worker instead of extending the thread"
30
+ };
31
+ }
32
+ return { state: "ok", threshold, tokens_used: tokens, next_step: null };
33
+ }
@@ -0,0 +1,14 @@
1
+ import { delimiter, dirname } from "node:path";
2
+
3
+ // Codex may wrap a shell command as either `zsh -lc` or `zsh -c`. The latter
4
+ // does not load the user's login profile, so a Homebrew or version-manager
5
+ // Node directory can disappear even though the supervisor itself is running
6
+ // under that exact executable. Put the current Node directory first and keep
7
+ // the inherited PATH for every other toolchain.
8
+ export function withWorkerToolPath(env, execPath = process.execPath, pathDelimiter = delimiter) {
9
+ const nodeDir = dirname(execPath);
10
+ const inherited = env.PATH ?? env.Path ?? "";
11
+ const parts = inherited.split(pathDelimiter).filter((part) => part && part !== nodeDir);
12
+ const value = [nodeDir, ...parts].join(pathDelimiter);
13
+ return { ...env, PATH: value, ...(process.platform === "win32" ? { Path: value } : {}) };
14
+ }
@@ -27,13 +27,30 @@ export function normalizeObservedCommand(command) {
27
27
  let body = wrapped[1].trim();
28
28
  const quote = body[0];
29
29
  if ((quote === "'" || quote === '"') && body.at(-1) === quote) body = body.slice(1, -1);
30
+ // Codex may display the wrapped command with JSON-style escaped quotes.
31
+ // Decode those before reversing zsh's display-only quote insertions.
32
+ body = body.replace(/\\"/g, '"');
33
+ // An interactive zsh protects history expansion and quoted literals by
34
+ // inserting "' around them, for example if("'!ready) and ('"'setup').
35
+ // Both are display artifacts, not part of the command that ran.
36
+ body = body.replace(/"'/g, "");
30
37
  // Codex displays a shell command that already contains single quotes by
31
38
  // closing and reopening the outer quote around them: -run '"^Test$'"'.
32
39
  // Decode that display-only wrapping before comparing it with the contract.
33
40
  body = body.replace(/'"'/g, "'");
41
+ // Codex may quote path arguments while displaying a command even when the
42
+ // dispatcher wrote the path bare. Absolute, home-relative and Windows paths
43
+ // are quote-safe here because a path containing whitespace remains quoted in
44
+ // both forms and is not touched by this rule.
45
+ body = body.replace(/(^|\s)['"]((?:[A-Za-z]:[\\/]|\/|\.\/|\.\.\/|~\/)[^'"\s]*)['"](?=\s|$)/g, "$1$2");
34
46
  return body.trim();
35
47
  }
36
48
 
49
+ export function commandsEquivalent(observed, expected) {
50
+ const normalizedExpected = normalizeObservedCommand(expected);
51
+ return normalizeObservedCommand(observed) === normalizedExpected;
52
+ }
53
+
37
54
  export function buildRuntimeContract({
38
55
  projectRoot,
39
56
  baseCommit,
@@ -44,6 +61,7 @@ export function buildRuntimeContract({
44
61
  writableRoots,
45
62
  context,
46
63
  contracts,
64
+ workspaceSetup = null,
47
65
  workspaceKind = "git_worktree",
48
66
  workspaceManifestSha256 = null
49
67
  }) {
@@ -61,7 +79,8 @@ export function buildRuntimeContract({
61
79
  context: (context ?? [])
62
80
  .map((entry) => ({ path: resolve(entry.path), sha256: entry.sha256 ?? null }))
63
81
  .sort((left, right) => left.path.localeCompare(right.path)),
64
- contracts: uniqueSorted(contracts)
82
+ contracts: uniqueSorted(contracts),
83
+ workspace_setup: stableValue(workspaceSetup)
65
84
  });
66
85
  }
67
86
 
@@ -88,7 +107,7 @@ export function readPreflightResult(task) {
88
107
 
89
108
  const commands = Array.isArray(task.commands) ? task.commands : [];
90
109
  const probes = metadata.probe_commands.map((command) => {
91
- const matches = commands.filter((entry) => normalizeObservedCommand(entry.command) === command);
110
+ const matches = commands.filter((entry) => commandsEquivalent(entry.command, command));
92
111
  const result = matches.at(-1) ?? null;
93
112
  return {
94
113
  command,
@@ -100,9 +119,23 @@ export function readPreflightResult(task) {
100
119
  });
101
120
  const terminal = ["completed", "failed", "cancelled", "lost"].includes(task.status);
102
121
  const failedCommands = commands.filter(commandFailed);
122
+ const probesPassed = probes.every((probe) => probe.passed);
123
+ const exitConfirmed = task.status === "completed" && task.exit_code === 0;
124
+ const reportWasInvalid = task.attention_reason === "invalid_report";
125
+ const probesProveEnvironment = probesPassed && failedCommands.length === 0;
126
+ const exitWasLost = task.status === "lost" && probesProveEnvironment;
127
+ // A preflight proves the worker environment through its command evidence.
128
+ // Its own final report and close-handler completion are useful diagnostics,
129
+ // but neither changes what those commands already proved. A completed turn
130
+ // without a recorded exit is accepted for this probe-only task; real failed,
131
+ // cancelled or unexplained-lost commands still fail below.
132
+ const workerOutcomeAcceptable = exitConfirmed
133
+ || (task.status === "completed" && task.exit_code == null)
134
+ || reportWasInvalid
135
+ || exitWasLost;
103
136
  let status = "running";
104
137
  if (terminal) {
105
- status = task.status === "completed" && task.exit_code === 0 && probes.every((probe) => probe.passed) && failedCommands.length === 0
138
+ status = workerOutcomeAcceptable && probesPassed && failedCommands.length === 0
106
139
  ? "passed"
107
140
  : "failed";
108
141
  }
@@ -112,6 +145,13 @@ export function readPreflightResult(task) {
112
145
  terminal,
113
146
  contract_hash: metadata.contract_hash,
114
147
  contract: metadata.contract,
148
+ worker_outcome: {
149
+ status: task.status,
150
+ exit_code: task.exit_code ?? null,
151
+ exit_confirmed: exitConfirmed,
152
+ report_ignored: reportWasInvalid,
153
+ missing_exit_tolerated: task.status === "completed" && task.exit_code == null || exitWasLost
154
+ },
115
155
  probes,
116
156
  failed_commands: failedCommands.map((entry) => ({
117
157
  command: entry.command,