codex-supervisor-mcp 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/landing.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { execFileSync } from "node:child_process";
10
10
  import { existsSync, rmSync } from "node:fs";
11
11
  import { join, relative } from "node:path";
12
- import { parsePorcelainLine, resolveWorktreeBase, worktreeRef, readWorktreeChanges, readWorktreeDiff } from "./worktree.js";
12
+ import { filterWorkspaceSetupChanges, parsePorcelainLine, resolveWorktreeBase, worktreeRef, readWorktreeChanges, readWorktreeDiff, workspaceSetupIgnorePaths } from "./worktree.js";
13
13
  import { findOutsideOwnedChanges } from "./owned-changes.js";
14
14
 
15
15
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
@@ -70,6 +70,16 @@ function currentBranch(cwd) {
70
70
  return name || null;
71
71
  }
72
72
 
73
+ function hasStagedChanges(cwd) {
74
+ try {
75
+ git(cwd, ["diff", "--cached", "--quiet"]);
76
+ return false;
77
+ } catch (error) {
78
+ if (error.status === 1) return true;
79
+ throw error;
80
+ }
81
+ }
82
+
73
83
  // Lands task's commits onto the current branch of its dispatch directory
74
84
  // (task.project_root: the row's cwd is the worktree the worker ran in).
75
85
  // `onto`, when given, must name that branch: it is a guard, not a switch.
@@ -127,9 +137,9 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
127
137
  const base = resolveWorktreeBase(task.worktree_path, worktreeRef(task));
128
138
  if (!base) return { error: "no_base_commit", reason: "the commit this worker started from is unknown, so its commits cannot be told apart" };
129
139
  if (!allowOutsideOwned) {
130
- const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 0 });
140
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 0, ignorePaths: workspaceSetupIgnorePaths(task) });
131
141
  if (diff.error) return { error: "ownership_unverified", reason: "cannot prove the complete diff before landing", diff_error: diff.error };
132
- const paths = [...readWorktreeChanges(task.worktree_path, worktreeRef(task)),
142
+ const paths = [...filterWorkspaceSetupChanges(task, readWorktreeChanges(task.worktree_path, worktreeRef(task))),
133
143
  ...diff.files.flatMap((file) => [file.path, file.from].filter(Boolean).map((path) => join(task.worktree_path, path)))];
134
144
  const { outside } = findOutsideOwnedChanges(task, [...new Set(paths)]);
135
145
  if (outside.length) return { error: "outside_owned_paths", reason: "worker changes exceed declared ownedPaths; review them and obtain explicit authorization before allowing an exception", outside_paths: outside.map((entry) => relative(task.worktree_path, entry)) };
@@ -144,15 +154,22 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
144
154
  let committedForWorker = null;
145
155
  if (uncommitted.length > 0 && commitMessage) {
146
156
  try {
147
- git(task.worktree_path, ["add", "-A"]);
148
- git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
157
+ if (allowOutsideOwned) git(task.worktree_path, ["add", "-A"]);
158
+ else {
159
+ const owned = findOutsideOwnedChanges(task, []).mapping.map((entry) => relative(task.worktree_path, entry.worker));
160
+ if (owned.length === 0) return { error: "outside_owned_paths", reason: "the worker left uncommitted changes but owns no landable path" };
161
+ git(task.worktree_path, ["add", "-A", "--", ...owned]);
162
+ }
163
+ if (hasStagedChanges(task.worktree_path)) {
164
+ git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
165
+ committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
166
+ commits.push(committedForWorker);
167
+ }
168
+ uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
149
169
  } catch (error) {
150
170
  const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-3).join("\n");
151
171
  return { error: "commit_failed", reason: `could not commit the worker's uncommitted edits in ${task.worktree_path}: ${tail || error.message.split("\n")[0]}`, uncommitted };
152
172
  }
153
- committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
154
- commits.push(committedForWorker);
155
- uncommitted = [];
156
173
  }
157
174
  // Commits whose patch is already on the target (a previous land, or the
158
175
  // main thread cherry-picked by hand) are skipped by patch id; picking
package/src/mcp-server.js CHANGED
@@ -16,6 +16,8 @@ import {
16
16
  getSession,
17
17
  getArtifact,
18
18
  getFact,
19
+ getFactEffectiveState,
20
+ isFactRevoked,
19
21
  getReviewByVerifierTask,
20
22
  getTaskForWorkItem,
21
23
  getWorkItemForTask,
@@ -57,10 +59,13 @@ import {
57
59
  import { readNativeGoal, readNativeGoalState } from "./goal-store.js";
58
60
  import { collectWorkerChanges } from "./worker-changes.js";
59
61
  import { buildHostGoalSync } from "./prompt.js";
60
- import { baseBehind, readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
62
+ import { baseBehind, readTaskChanges, readWorktreeDiff, splitPatchHunks, workspaceSetupIgnorePaths, worktreeRef } from "./worktree.js";
61
63
  import { summarizeVerification } from "./event-parser.js";
62
64
  import { readPreflightResult } from "./worker-preflight.js";
63
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";
64
69
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
65
70
  import { approxTokenCount, truncateEventStrings, truncateMiddleChars, truncateReport } from "./truncate.js";
66
71
  import { checkForUpdate, updateNotice } from "./update-check.js";
@@ -202,11 +207,14 @@ function sleep(ms) {
202
207
  function isSettled(task) {
203
208
  if (!TERMINAL_STATUSES.has(task.status)) return false;
204
209
  if (task.attention_reason === "start_failed") return true;
210
+ if (task.guard_policy?.preflight && readPreflightResult(task).status === "passed") return true;
205
211
  if (task.status !== "completed" && task.status !== "failed") return true;
206
212
  // Acceptance is running in the supervisor process that owned the worker;
207
213
  // the codex pid is already dead, so that process is what to wait on.
208
214
  if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
209
- 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
+ }
210
218
  if (task.exit_code !== null && task.exit_code !== undefined) return true;
211
219
  // A dead Codex pid does not prove that its owner's close handler finished
212
220
  // draining the stream and writing the exit status. Leave the half-written
@@ -223,12 +231,44 @@ function isSettled(task) {
223
231
  const LIVE_COMMAND_PREVIEW_CHARS = 120;
224
232
  function liveness(task) {
225
233
  if (!ACTIVE_STATUSES.has(task.status)) {
226
- 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
+ };
227
244
  }
228
245
  const since = Date.parse(task.last_event_at ?? task.started_at ?? "");
229
246
  const idle = Number.isFinite(since) ? Math.max(0, Math.floor((Date.now() - since) / 1000)) : null;
230
247
  const command = task.current_command ? clip(task.current_command, LIVE_COMMAND_PREVIEW_CHARS) : null;
231
- 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
+ };
232
272
  }
233
273
 
234
274
  // The acceptance verdict as get_worker_result reports it, with the one
@@ -295,7 +335,10 @@ function summarizeTask(task) {
295
335
  goal_objective: task.goal_objective,
296
336
  goal_token_budget: task.goal_token_budget,
297
337
  goal_status: task.goal_status,
338
+ goal_tokens_used: task.goal_tokens_used ?? null,
339
+ thread_health: threadHealth(task),
298
340
  attention_reason: task.attention_reason ?? null,
341
+ failure: classifyFailure(task),
299
342
  changed_file_count: (task.changed_files ?? []).length,
300
343
  command_count: (task.commands ?? []).length,
301
344
  run_count: task.run_count ?? 0,
@@ -372,6 +415,7 @@ function receipt(task) {
372
415
  goal_objective: task.goal_objective,
373
416
  goal_token_budget: task.goal_token_budget,
374
417
  error: task.error ?? null,
418
+ failure: classifyFailure(task),
375
419
  run_count: task.run_count ?? 0,
376
420
  run_log: task.run_log,
377
421
  created_at: task.created_at,
@@ -380,6 +424,7 @@ function receipt(task) {
380
424
  }
381
425
 
382
426
  function overviewRow(task, caps) {
427
+ const live = liveness(task);
383
428
  return {
384
429
  id: task.id,
385
430
  title: clip(task.title, caps.title),
@@ -388,9 +433,13 @@ function overviewRow(task, caps) {
388
433
  goal: clip(task.goal_objective, caps.goal),
389
434
  goal_status: task.goal_status ?? null,
390
435
  last_action: clip(task.current_action, caps.action),
391
- idle_seconds: liveness(task).idle_seconds,
436
+ idle_seconds: live.idle_seconds,
392
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 } : {}),
393
440
  acceptance: acceptanceVerdict(task),
441
+ ...(classifyFailure(task)?.code ? { failure_code: classifyFailure(task).code } : {}),
442
+ ...(threadHealth(task).state === "handoff_recommended" ? { handoff_recommended: true } : {}),
394
443
  changed_files: (task.changed_files ?? []).length,
395
444
  depends_on: task.depends_on ?? [],
396
445
  owned_paths: (task.owned_paths ?? []).map((entry) => clip(entry, caps.path))
@@ -520,6 +569,7 @@ function errorResult(error) {
520
569
  error: error.code ?? "error",
521
570
  message: error.message,
522
571
  ...(error.conflicts ? { conflicts: error.conflicts } : {}),
572
+ ...(error.details?.preflight ? { preflight: error.details.preflight } : {}),
523
573
  ...(error.details ? { files: error.details.files ?? [], git: error.details.git ?? null, base_commit: error.details.base_commit ?? null, head: error.details.head ?? null } : {})
524
574
  });
525
575
  }
@@ -562,6 +612,14 @@ const acceptanceCheck = z.union([
562
612
  }).strict()
563
613
  ]);
564
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();
565
623
 
566
624
  const observerId = process.env.CODEX_SUPERVISOR_OBSERVER_ID?.trim() || `mcp-${randomUUID()}`;
567
625
  const deltaObserverId = process.env.CODEX_SUPERVISOR_DELTA_OBSERVER_ID?.trim() || `${observerId}:delta`;
@@ -668,6 +726,7 @@ server.registerTool(
668
726
  baseRef: z.string().min(1).optional(),
669
727
  workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
670
728
  inPlaceAuthorization: z.string().min(1).max(2000).optional(),
729
+ workspaceSetup: workspaceSetupInput.optional(),
671
730
  probeCommands: z.array(z.string().min(1)).min(1).max(20)
672
731
  }
673
732
  },
@@ -755,6 +814,7 @@ server.registerTool(
755
814
  baseRef: z.string().min(1).optional(),
756
815
  workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
757
816
  inPlaceAuthorization: z.string().min(1).max(2000).optional(),
817
+ workspaceSetup: workspaceSetupInput.optional(),
758
818
  // A successful preflight_codex_worker task id. When present, this worker
759
819
  // is refused unless base commit and the complete runtime contract match.
760
820
  preflight_id: z.string().min(1).optional(),
@@ -809,6 +869,7 @@ server.registerTool(
809
869
  maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
810
870
  workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
811
871
  inPlaceAuthorization: z.string().min(1).max(2000).optional(),
872
+ workspaceSetup: workspaceSetupInput.optional(),
812
873
  goal: z
813
874
  .object({
814
875
  objective: z.string().min(1),
@@ -926,6 +987,7 @@ server.registerTool(
926
987
  timeoutMinutes: z.number().int().min(1).max(360).default(1),
927
988
  timeoutMs: z.number().int().min(1000).max(21600000).optional(),
928
989
  pollMs: z.number().int().min(250).max(10000).default(1000),
990
+ emitProgress: z.boolean().default(false),
929
991
  // Off by default. A wait is the call clients background and then replay
930
992
  // as a notification, so its payload has to stay small; ten events per
931
993
  // worker was the bulk of it. Ask for events explicitly, or read
@@ -950,6 +1012,7 @@ server.registerTool(
950
1012
  timeoutMinutes,
951
1013
  timeoutMs,
952
1014
  pollMs,
1015
+ emitProgress,
953
1016
  includeEvents,
954
1017
  eventLimit,
955
1018
  eventMaxChars,
@@ -963,15 +1026,16 @@ server.registerTool(
963
1026
  const progressToken = extra?._meta?.progressToken;
964
1027
  let lastProgressAt = -Infinity;
965
1028
 
1029
+ let clientCancelled = false;
966
1030
  while (Date.now() - startedAt < effectiveTimeoutMs) {
967
- if (extra?.signal.aborted) break;
1031
+ if (extra?.signal.aborted) { clientCancelled = true; break; }
968
1032
  await reconcileDetachedActiveTasks();
969
1033
  tasks = (await getTasks(task_ids)).filter(Boolean);
970
1034
  const settledCount = tasks.filter(isSettled).length;
971
1035
  const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
972
1036
  if (isDone) break;
973
1037
  const elapsed = Date.now() - startedAt;
974
- if (progressToken != null && elapsed - lastProgressAt >= 30000) {
1038
+ if (emitProgress && progressToken != null && elapsed - lastProgressAt >= 30000) {
975
1039
  await extra.sendNotification({ method: "notifications/progress", params: {
976
1040
  progressToken, progress: elapsed, total: effectiveTimeoutMs,
977
1041
  message: `${settledCount}/${task_ids.length} workers settled; wait budget only`
@@ -1008,6 +1072,7 @@ server.registerTool(
1008
1072
  mode,
1009
1073
  timed_out: timedOut,
1010
1074
  still_running: timedOut,
1075
+ termination_reason: clientCancelled ? "client_cancelled" : timedOut ? "budget_exhausted" : "settled",
1011
1076
  next_step: timedOut
1012
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.`
1013
1078
  : null,
@@ -1030,7 +1095,7 @@ server.registerTool(
1030
1095
  exit_code: task.exit_code ?? null,
1031
1096
  changed_file_count: readTaskChanges(task).length,
1032
1097
  acceptance: acceptanceVerdict(task),
1033
- ...liveness(task),
1098
+ ...compactLiveness(task),
1034
1099
  updated_at: task.updated_at ?? null
1035
1100
  }))
1036
1101
  : summaries
@@ -1212,7 +1277,8 @@ server.registerTool(
1212
1277
  },
1213
1278
  async ({ fact_id }) => {
1214
1279
  const fact = await getFact(fact_id);
1215
- return textResult(fact ? { fact } : { error: "fact_not_found", fact_id });
1280
+ if (!fact) return textResult({ error: "fact_not_found", fact_id });
1281
+ return textResult({ fact, effective_state: await getFactEffectiveState(fact_id) ?? fact.state });
1216
1282
  }
1217
1283
  );
1218
1284
 
@@ -1246,6 +1312,7 @@ server.registerTool(
1246
1312
  try {
1247
1313
  const source = await getFact(fact_id);
1248
1314
  if (!source) return textResult({ error: "fact_not_found", fact_id });
1315
+ if (await isFactRevoked(fact_id)) return textResult({ error: "fact_already_revoked", fact_id });
1249
1316
  const task = await getTaskForWorkItem(source.work_item_id);
1250
1317
  if (!task) return textResult({ error: "fact_task_not_found", fact_id });
1251
1318
  const event = await appendTaskEvent(task.id, { type: "supervisor.fact_promoted", source_fact_id: fact_id, scope, watched_paths: watchedPaths ?? source.watched_paths ?? [], expires_at: expiresAt ?? null }, {
@@ -1642,28 +1709,86 @@ server.registerTool(
1642
1709
  {
1643
1710
  title: "Get worker diff",
1644
1711
  description:
1645
- "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.",
1646
1713
  inputSchema: {
1647
1714
  task_id: z.string().min(1),
1648
- 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(),
1649
1720
  paths: z.array(z.string().min(1)).optional()
1650
1721
  }
1651
1722
  },
1652
- async ({ task_id, maxChars, paths }) => {
1723
+ async ({ task_id, maxChars, file, hunk, pageSize, cursor, paths }) => {
1653
1724
  const task = await getTask(task_id);
1654
1725
  if (!task) return textResult({ error: "task_not_found", task_id });
1655
1726
  if (!task.worktree_path) {
1656
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" });
1657
1728
  }
1658
- const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [] });
1659
- 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 = {
1660
1748
  task_id,
1661
1749
  title: task.title,
1662
1750
  status: task.status,
1663
1751
  worktree_path: task.worktree_path,
1664
1752
  branch: `codex/${task.id}`,
1665
1753
  ...diff,
1666
- 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
1667
1792
  });
1668
1793
  }
1669
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} Shell verification 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
@@ -1,6 +1,10 @@
1
1
  import { lstatSync, realpathSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { dirname, isAbsolute, posix, resolve, win32 } from "node:path";
4
+
5
+ function pathJoin(platform, ...parts) {
6
+ return (platform === "win32" ? win32 : posix).join(...parts);
7
+ }
4
8
 
5
9
  // Codex refuses a writable root that contains a symlink component: the worker
6
10
  // does not merely lose that directory, every command in it fails with
@@ -72,12 +76,24 @@ export const TOOLCHAIN_CACHE_DIRS = [
72
76
  export const EXPLICIT_ONLY_DIRS = [".ssh", ".gnupg", ".config", ".aws", ".docker", ".kube", ".netrc", ".git-credentials", "Library/Keychains"];
73
77
  function osCacheCandidates({ env, platform, home }) {
74
78
  if (platform === "win32") return [env.LOCALAPPDATA];
75
- return [env.XDG_CACHE_HOME, platform === "darwin" ? join(home, "Library", "Caches") : null, join(home, ".cache")];
79
+ return [env.XDG_CACHE_HOME, platform === "darwin" ? pathJoin(platform, home, "Library", "Caches") : null, pathJoin(platform, home, ".cache")];
80
+ }
81
+
82
+ function goBuildCacheCandidate({ env, platform, home }) {
83
+ const configured = env.GOCACHE?.trim();
84
+ if (configured && configured !== "off") return configured;
85
+ if (platform === "win32") return env.LOCALAPPDATA ? win32.join(env.LOCALAPPDATA, "go-build") : null;
86
+ if (platform === "darwin") return pathJoin(platform, home, "Library", "Caches", "go-build");
87
+ return pathJoin(platform, env.XDG_CACHE_HOME?.trim() || pathJoin(platform, home, ".cache"), "go-build");
76
88
  }
77
89
 
78
90
  export function cacheRoots({ env = process.env, platform = process.platform, home = homedir(), resolveRoot = resolveWritableRoot, includeToolchain = true } = {}) {
79
91
  if (/^(1|true|yes)$/i.test((env.SUPERVISOR_NO_AUTO_CACHE_ROOTS ?? "").trim())) return [];
80
- const candidates = [...osCacheCandidates({ env, platform, home }), ...(includeToolchain ? TOOLCHAIN_CACHE_DIRS.map((dir) => join(home, dir)) : [])];
92
+ const candidates = [
93
+ ...osCacheCandidates({ env, platform, home }),
94
+ goBuildCacheCandidate({ env, platform, home }),
95
+ ...(includeToolchain ? TOOLCHAIN_CACHE_DIRS.map((dir) => pathJoin(platform, home, dir)) : [])
96
+ ];
81
97
  const roots = [];
82
98
  for (const candidate of candidates) {
83
99
  if (!candidate?.trim()) continue;
@@ -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`);