codex-supervisor-mcp 0.13.6 → 1.0.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.
Files changed (67) hide show
  1. package/README.en.md +35 -46
  2. package/README.md +35 -46
  3. package/package.json +3 -2
  4. package/skills/codex-supervisor/SKILL.md +86 -89
  5. package/src/app/acceptance.js +5 -5
  6. package/src/app/auto-cleanup.js +91 -0
  7. package/src/app/cleanup-facts.js +99 -0
  8. package/src/app/cleanup-plan.js +108 -100
  9. package/src/app/context-compiler.js +2 -1
  10. package/src/app/dispatch.js +17 -15
  11. package/src/app/followup.js +5 -4
  12. package/src/app/land-chain.js +14 -4
  13. package/src/app/landing.js +8 -8
  14. package/src/app/ownership.js +1 -1
  15. package/src/app/rebase.js +1 -1
  16. package/src/app/restore-worktree.js +51 -0
  17. package/src/app/resume.js +24 -6
  18. package/src/app/side-chat.js +3 -0
  19. package/src/app/verify-push.js +2 -7
  20. package/src/app/worktree-setup.js +15 -14
  21. package/src/domain/acceptance-spec.js +1 -1
  22. package/src/domain/cleanup-policy.js +44 -0
  23. package/src/domain/failure-class.js +2 -2
  24. package/src/domain/prompt.js +7 -7
  25. package/src/domain/status.js +9 -0
  26. package/src/domain/thread-health.js +2 -2
  27. package/src/domain/worker-branch.js +6 -0
  28. package/src/domain/worker-changes.js +3 -3
  29. package/src/infra/cleanup-hint.js +7 -8
  30. package/src/infra/external-output.js +2 -2
  31. package/src/infra/sandbox-roots.js +1 -1
  32. package/src/infra/store/events.js +2 -1
  33. package/src/infra/store/reconcile.js +4 -3
  34. package/src/infra/store/records.js +18 -7
  35. package/src/infra/store/tasks.js +31 -1
  36. package/src/infra/update/auto-update-worker.js +3 -3
  37. package/src/infra/update/auto-update.js +4 -4
  38. package/src/infra/update/update-check.js +3 -3
  39. package/src/infra/workspace-kind.js +8 -8
  40. package/src/infra/worktree.js +4 -3
  41. package/src/interface/bin/acceptance-cli.js +4 -4
  42. package/src/interface/bin/cleanup.js +1 -1
  43. package/src/interface/bin/monitor.jsx +6 -6
  44. package/src/interface/bin/setup.js +3 -3
  45. package/src/interface/bin/stage.js +2 -2
  46. package/src/interface/mcp/{tools → handlers}/delivery.js +30 -62
  47. package/src/interface/mcp/handlers/dispatch.js +233 -0
  48. package/src/interface/mcp/{tools → handlers}/facts.js +30 -65
  49. package/src/interface/mcp/handlers/overview.js +103 -0
  50. package/src/interface/mcp/{tools → handlers}/results.js +45 -60
  51. package/src/interface/mcp/{tools → handlers}/review.js +16 -36
  52. package/src/interface/mcp/{tools → handlers}/wait.js +8 -14
  53. package/src/interface/mcp/server.js +18 -51
  54. package/src/interface/mcp/tools/deliver.js +48 -0
  55. package/src/interface/mcp/tools/dispatch.js +78 -257
  56. package/src/interface/mcp/tools/optional.js +57 -0
  57. package/src/interface/mcp/tools/read.js +115 -0
  58. package/src/interface/mcp/tools/run.js +57 -0
  59. package/src/interface/mcp/tools/shapes.js +66 -0
  60. package/src/interface/mcp/tools/track.js +84 -0
  61. package/src/interface/mcp/views/task.js +8 -7
  62. package/src/interface/web/views.js +2 -1
  63. package/src/run-host/launch.js +7 -7
  64. package/src/runners/codex/tool-guard.js +6 -6
  65. package/src/domain/overview-delta.js +0 -77
  66. package/src/interface/mcp/tools/overview.js +0 -202
  67. package/src/interface/mcp/tools/poll.js +0 -62
@@ -1,3 +1,5 @@
1
+ import { branchOf } from "../domain/worker-branch.js";
2
+ import { ensureTaskWorktree } from "./restore-worktree.js";
1
3
  import "./compose.js";
2
4
  import { runGit } from "../infra/git.js";
3
5
  import { appendTaskEvent } from "../infra/store/events.js";
@@ -67,6 +69,14 @@ export async function landOneWorkerTask(taskId, options = {}) {
67
69
  if (!isSettled(task)) return { error: "worker_active", task_id: taskId, reason: "wait for this run and acceptance to settle before landing" };
68
70
  if (session?.approval_state === "waiting_user") return { error: "session_waiting_user", task_id: taskId, reason: "session requires user approval before landing" };
69
71
  if (session && task.session_policy_revision !== session.policy_revision) return { error: "session_policy_stale", task_id: taskId, current_revision: session.policy_revision, checked_revision: task.session_policy_revision, reason: "requirements changed; resume with the current objective and rerun acceptance before landing" };
72
+ // Cleanup may have removed the worktree of work that never landed; its branch brings it back.
73
+ if (!task.landed_at) {
74
+ try {
75
+ await ensureTaskWorktree(task);
76
+ } catch (error) {
77
+ return { error: error.code ?? "worktree_restore_failed", task_id: taskId, reason: error.message.split("\n")[0] };
78
+ }
79
+ }
70
80
  if (skipAlreadyLanded && task.landed_at && (!task.worktree_path || !existsSync(task.worktree_path))) {
71
81
  try {
72
82
  const targetBranch = git(task.project_root, ["symbolic-ref", "--short", "HEAD"]);
@@ -75,7 +85,7 @@ export async function landOneWorkerTask(taskId, options = {}) {
75
85
  return { error: "acceptance_not_run", task_id: taskId };
76
86
  }
77
87
  git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, "HEAD"]);
78
- return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, skipped: "already_landed", landed_at: task.landed_at, landed_head: task.landed_head };
88
+ return { task_id: taskId, title: task.title, status: task.status, branch: branchOf(task), skipped: "already_landed", landed_at: task.landed_at, landed_head: task.landed_head };
79
89
  } catch {
80
90
  return { error: "landed_commit_unreachable", task_id: taskId, reason: "the removed ancestor worktree cannot be skipped without proving its landed commit is on the current target" };
81
91
  }
@@ -97,15 +107,15 @@ export async function landOneWorkerTask(taskId, options = {}) {
97
107
  task_id: taskId,
98
108
  title: task.title,
99
109
  status: task.status,
100
- branch: `codex/${task.id}`,
110
+ branch: branchOf(task),
101
111
  ...outcome,
102
112
  skipped: "already_in_target",
103
113
  lifecycle_recorded: !alreadyRecorded && Boolean(outcome.matched_head)
104
114
  };
105
115
  }
106
- if (outcome.error) return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
116
+ if (outcome.error) return { task_id: taskId, title: task.title, status: task.status, branch: branchOf(task), ...outcome };
107
117
  await recordWorkerLanded(task, { head: outcome.head, branch: outcome.onto, target: outcome.target, alreadyLanded: outcome.already_landed ?? [] });
108
- return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
118
+ return { task_id: taskId, title: task.title, status: task.status, branch: branchOf(task), ...outcome };
109
119
  }
110
120
 
111
121
  export async function followupChainIds(taskId) {
@@ -1,6 +1,6 @@
1
1
  // Landing a worker's commits where they were dispatched from.
2
2
  //
3
- // A worker commits on codex/<taskId> inside its own worktree. Getting that
3
+ // A worker's commits live on its own branch inside its own worktree. Getting that
4
4
  // work onto the branch the main thread integrates on used to be the main
5
5
  // thread's job, one cherry-pick per step, dozens of times per batch. This
6
6
  // does the same thing with the same guard rails a careful person would use:
@@ -129,8 +129,8 @@ function hasStagedChanges(cwd) {
129
129
  // (task.project_root: the row's cwd is the worktree the worker ran in).
130
130
  // `onto`, when given, must name that branch: it is a guard, not a switch.
131
131
  //
132
- // `commitMessage` commits what the worker left uncommitted in its worktree
133
- // first, as one commit on codex/<id>. A worker in Codex's workspace-write
132
+ // `commit_message` commits what the worker left uncommitted in its worktree
133
+ // first, as one commit on its branch. A worker in Codex's workspace-write
134
134
  // sandbox cannot commit at all (the sandbox keeps .git read-only), so this
135
135
  // is how "one step, one commit" is kept without giving workers full access.
136
136
  //
@@ -145,14 +145,14 @@ function acceptanceRefusal(task) {
145
145
  if (acceptance.passed === false) {
146
146
  return {
147
147
  error: "acceptance_failed",
148
- reason: `the worker's acceptance run failed${failing ? ` on "${failing.command.slice(0, 120)}" (exit ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code)})` : acceptance.error ? ` (${acceptance.error})` : ""}; resume the worker with the failing output and land once it passes. ignoreAcceptance: true lands anyway, only when the user said to.`,
148
+ reason: `the worker's acceptance run failed${failing ? ` on "${failing.command.slice(0, 120)}" (exit ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code)})` : acceptance.error ? ` (${acceptance.error})` : ""}; resume the worker with the failing output and land once it passes. ignore_acceptance: true lands anyway, only when the user said to.`,
149
149
  acceptance: { status: acceptance.status, passed: false, checks: acceptance.checks ?? [], error: acceptance.error ?? null }
150
150
  };
151
151
  }
152
152
  if (acceptance.status === "running" || acceptance.status === "interrupted" || acceptance.status === "cancelled") {
153
153
  return {
154
154
  error: "acceptance_not_run",
155
- reason: `the worker's acceptance is ${acceptance.status}; wait for it (or resume the worker to run it again) before landing. ignoreAcceptance: true lands anyway, only when the user said to.`,
155
+ reason: `the worker's acceptance is ${acceptance.status}; wait for it (or resume the worker to run it again) before landing. ignore_acceptance: true lands anyway, only when the user said to.`,
156
156
  acceptance: { status: acceptance.status, passed: null }
157
157
  };
158
158
  }
@@ -163,7 +163,7 @@ function acceptanceRefusal(task) {
163
163
  function targetState(task, onto) {
164
164
  const target = task.project_root;
165
165
  if (!task.worktree_path || !existsSync(task.worktree_path)) {
166
- return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing on a codex/ branch to land" };
166
+ return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is no worker branch to land" };
167
167
  }
168
168
  if (!target || !existsSync(target)) {
169
169
  return { error: "no_target", reason: `the directory the worker was dispatched from (${target}) no longer exists` };
@@ -191,7 +191,7 @@ function ownershipRefusal(task) {
191
191
  const paths = [...filterWorkspaceSetupChanges(task, readWorktreeChanges(task.worktree_path, worktreeRef(task))),
192
192
  ...diff.files.flatMap((file) => [file.path, file.from].filter(Boolean).map((path) => join(task.worktree_path, path)))];
193
193
  const { outside } = findOutsideOwnedChanges(task, [...new Set(paths)]);
194
- 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)) };
194
+ if (outside.length) return { error: "outside_owned_paths", reason: "worker changes exceed declared owned_paths; review them and obtain explicit authorization before allowing an exception", outside_paths: outside.map((entry) => relative(task.worktree_path, entry)) };
195
195
  return null;
196
196
  }
197
197
 
@@ -267,7 +267,7 @@ function nothingToLand(proof, { branch, target, uncommitted, base }) {
267
267
  return {
268
268
  error: "nothing_to_land",
269
269
  reason: uncommitted.length > 0
270
- ? "the worker made no commits on its branch (a workspace-write worker cannot: the sandbox keeps .git read-only); pass commitMessage to commit its edits as one commit and land that"
270
+ ? "the worker made no commits on its branch (a workspace-write worker cannot: the sandbox keeps .git read-only); pass commit_message to commit its edits as one commit and land that"
271
271
  : "the worker made no commits and left no edits on its branch",
272
272
  uncommitted,
273
273
  base_commit: base
@@ -50,7 +50,7 @@ export async function findOwnershipConflicts(ownedPaths, { excludeTaskId = null
50
50
 
51
51
  export function ownershipConflictError(conflicts) {
52
52
  const owners = conflicts.map((conflict) => conflict.task_id).join(", ");
53
- const error = new Error(`ownedPaths overlap with active worker(s): ${owners}`);
53
+ const error = new Error(`owned_paths overlap with active worker(s): ${owners}`);
54
54
  error.code = "ownership_conflict";
55
55
  error.conflicts = conflicts;
56
56
  return error;
package/src/app/rebase.js CHANGED
@@ -182,7 +182,7 @@ function popOntoNewBase({ cwd, base, head }, ontoCommit) {
182
182
  const popError = restoreStash(cwd, true);
183
183
  return {
184
184
  error: "stash_conflict",
185
- reason: `the worker's uncommitted edits conflict with ${ontoCommit.slice(0, 12)}; the worktree is back as it was${popError ? " (but its stash could not be restored: run git stash pop there)" : ""}. Commit them first (land_codex_worker with commitMessage) so the conflict is in a commit that can be resolved, or redispatch from the new commit with baseRef`,
185
+ reason: `the worker's uncommitted edits conflict with ${ontoCommit.slice(0, 12)}; the worktree is back as it was${popError ? " (but its stash could not be restored: run git stash pop there)" : ""}. Commit them first (land_worker with commit_message) so the conflict is in a commit that can be resolved, or redispatch from the new commit with workspace.base_ref`,
186
186
  files,
187
187
  git: tail,
188
188
  base_commit: base,
@@ -0,0 +1,51 @@
1
+ // A cleaned-up worker keeps its branch. When the main thread comes back to it
2
+ // (to resume or land), the worktree is cut again from that branch, with the
3
+ // same setup links, so cleanup never closes the door on unfinished work.
4
+ import { branchOf } from "../domain/worker-branch.js";
5
+ import "./compose.js";
6
+ import { gitBin, gitSucceeds } from "../infra/git.js";
7
+ import { runToExit } from "../infra/process.js";
8
+ import { runIdFor } from "../infra/store/db.js";
9
+ import { appendTaskEvent } from "../infra/store/events.js";
10
+ import { updateWorkItemDelivery } from "../infra/store/records.js";
11
+ import { prepareWorktreeWorkspace, withWorktreeCreationLock } from "./worktree-setup.js";
12
+ import { existsSync } from "node:fs";
13
+
14
+ function deliveryStepOf(task) {
15
+ if (task.push_verified_at) return "push_verified";
16
+ return task.landed_at ? "landed" : "draft";
17
+ }
18
+
19
+ // True when a worktree was restored, false when there was nothing to do
20
+ // (already present, or the task never had one). Throws when the worktree is
21
+ // gone and cannot be brought back, so no caller carries on somewhere else.
22
+ export async function ensureTaskWorktree(task) {
23
+ if (!task.worktree_path || !task.project_root || existsSync(task.worktree_path)) return false;
24
+ const branch = branchOf(task);
25
+ if (!gitSucceeds(task.project_root, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`])) {
26
+ const error = new Error(`the worktree of ${task.id} is gone and its branch ${branch} does not exist, so it cannot be restored`);
27
+ error.code = "worktree_unrecoverable";
28
+ throw error;
29
+ }
30
+ const restored = await withWorktreeCreationLock(task.project_root, async () => {
31
+ if (existsSync(task.worktree_path)) return false;
32
+ await runToExit(gitBin(), ["-C", task.project_root, "worktree", "prune"]).catch(() => {});
33
+ await runToExit(gitBin(), ["-C", task.project_root, "worktree", "add", task.worktree_path, branch]);
34
+ return true;
35
+ });
36
+ if (!restored) return false;
37
+ const setup = task.workspace_metadata?.setup ?? null;
38
+ if (setup) {
39
+ try {
40
+ await prepareWorktreeWorkspace(setup, task.project_root, task.worktree_path, task.id);
41
+ } catch (error) {
42
+ // A worktree without its setup would look restored and fail at the first command.
43
+ await runToExit(gitBin(), ["-C", task.project_root, "worktree", "remove", "--force", task.worktree_path]).catch(() => {});
44
+ throw error;
45
+ }
46
+ }
47
+ await updateWorkItemDelivery(task.id, deliveryStepOf(task)).catch(() => null);
48
+ await appendTaskEvent(task.id, { type: "supervisor.worktree_restored", branch, restored_at: new Date().toISOString() },
49
+ { runId: runIdFor(task.id, task.run_count ?? 1), actor: "supervisor" }).catch(() => null);
50
+ return true;
51
+ }
package/src/app/resume.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { mkdir } from "node:fs/promises";
2
+ import { ensureTaskWorktree } from "./restore-worktree.js";
1
3
  import "./compose.js";
2
4
  import { frameWorkerPrompt } from "../domain/prompt.js";
3
- import { ACTIVE_STATUSES } from "../domain/status.js";
5
+ import { ACTIVE_STATUSES, runIsOver } from "../domain/status.js";
4
6
  import { buildHandoff } from "../infra/handoff.js";
5
7
  import { appendTaskEvent } from "../infra/store/events.js";
6
8
  import { getSession } from "../infra/store/sessions.js";
@@ -19,7 +21,7 @@ import { appendFile } from "node:fs/promises";
19
21
  // goal are all inherited from the original task, and the row is reused so one
20
22
  // logical piece of work stays one row.
21
23
  //
22
- // `rebaseOnto` names a ref, resolved in the project directory (HEAD, main, a
24
+ // `rebase_onto` names a ref, resolved in the project directory (HEAD, main, a
23
25
  // sha): the worktree is moved onto it first so the worker continues on
24
26
  // current code, and base_commit is recorded before the worker starts so a
25
27
  // spawn failure cannot leave the row describing the old base. A rebase that
@@ -62,7 +64,7 @@ async function rebaseBeforeResume(task, rebaseOnto) {
62
64
  try {
63
65
  ontoCommit = resolveCommit(task.project_root, rebaseOnto);
64
66
  } catch {
65
- throw coded("invalid_rebase_onto", `rebaseOnto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
67
+ throw coded("invalid_rebase_onto", `rebase_onto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
66
68
  }
67
69
  const rebase = rebaseWorktree(task, ontoCommit);
68
70
  if (rebase.error) throw coded(rebase.error, rebase.reason, rebase);
@@ -82,19 +84,34 @@ function resumeAllowsOutputSchema(threadId) {
82
84
  || (goalRead.state === "available" && goalRead.goal?.storage_status === "complete");
83
85
  }
84
86
 
87
+ // Where a resumed worker runs. It is the directory it ran in before, and never
88
+ // a stand-in: falling back to the project root would let a worker that was
89
+ // confined to a scratch directory or a worktree write into the source tree.
90
+ async function resumeCwd(task) {
91
+ if (await exists(task.cwd)) return task.cwd;
92
+ if (task.workspace_kind === "scratch") {
93
+ // Cleanup removes an idle scratch directory. Its drafts are gone, its
94
+ // report is in the store; the worker continues in an empty one.
95
+ await mkdir(task.cwd, { recursive: true });
96
+ return task.cwd;
97
+ }
98
+ throw coded("workspace_missing", `the directory task ${task.id} ran in (${task.cwd}) no longer exists; dispatch a new worker instead of resuming`);
99
+ }
100
+
85
101
  async function resumeClaimed(claimed, { prompt, rebaseOnto, acceptance }) {
86
102
  const session = claimed.session_id ? await getSession(claimed.session_id) : null;
87
103
  if (session?.approval_state === "waiting_user") throw coded("session_waiting_user", "session is waiting for user approval; do not resume");
88
104
  let task = await refreshAcceptance(claimed, session, acceptance);
89
105
  if (!task.thread_id) {
90
106
  throw new Error(
91
- `task ${task.id} has no Codex thread_id recorded. Only workers created by this version of codex-supervisor-mcp can be resumed; use create_codex_followup_worker otherwise.`
107
+ `task ${task.id} has no Codex thread_id recorded. Only workers created by this version of codex-supervisor-mcp can be resumed; use create_worker with followup_of otherwise.`
92
108
  );
93
109
  }
110
+ await ensureTaskWorktree(task);
94
111
  let rebase = null;
95
112
  if (rebaseOnto) ({ task, rebase } = await rebaseBeforeResume(task, rebaseOnto));
96
113
 
97
- const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
114
+ const cwd = await resumeCwd(task);
98
115
  const args = codexRunner.resumeArgs(task);
99
116
  const outputSchema = resumeAllowsOutputSchema(task.thread_id);
100
117
  const started = await startTrackedRun({
@@ -141,7 +158,8 @@ export async function recoverEligibleRuns() {
141
158
  || ["blocked", "paused", "budget_limited", "usage_limited"].includes(task.goal_status)
142
159
  || /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
143
160
  || /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
144
- || await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)) continue;
161
+ // Once the run is over its pids may belong to anyone.
162
+ || (!runIsOver(task) && (await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)))) continue;
145
163
  const session = task.session_id ? await getSession(task.session_id) : null;
146
164
  if (session?.approval_state === "waiting_user") continue;
147
165
  try {
@@ -22,6 +22,7 @@
22
22
  // turn failed / timed out / stopped error on the turn, session still usable
23
23
  // board restarted mid-turn ........ turn marked interrupted
24
24
  // session ended ................... fork deleted, history cleared
25
+ import { ensureTaskWorktree } from "./restore-worktree.js";
25
26
  import "./compose.js";
26
27
  import { answerOf, partsFromChunks, turnView } from "../domain/side-turn-view.js";
27
28
  import { closeSideSession, getSideSession, insertSideTurn, interruptRunningSideTurns, openSideSession, readSideTurns, setSideSessionFork, updateSideTurn } from "../infra/store/sessions.js";
@@ -243,6 +244,8 @@ export async function runSideTurn({ task, text, res = null, fresh = false }) {
243
244
  if (target.error) throw Object.assign(new Error(target.error), { code: "codex_missing" });
244
245
 
245
246
  const { session, refreshed } = await prepareSideSession(task, { fresh });
247
+ // The fork reads the worker's files; a cleaned-up worktree comes back from its branch.
248
+ await ensureTaskWorktree(task);
246
249
  const child = startSideChild(target, task, session);
247
250
  const live = await openLiveTurn(task, text, child);
248
251
  if (res) {
@@ -4,13 +4,11 @@ import "./compose.js";
4
4
  import { runGit } from "../infra/git.js";
5
5
  import { appendTaskEvent } from "../infra/store/events.js";
6
6
  import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
7
- import { recordJsonArtifact, saveCleanupPlan, updateWorkItemDelivery } from "../infra/store/records.js";
7
+ import { recordJsonArtifact, updateWorkItemDelivery } from "../infra/store/records.js";
8
8
  import { getTask, upsertTask } from "../infra/store/tasks.js";
9
9
  import { runIdFor } from "../infra/store/db.js";
10
- import { createCleanupPlan } from "./cleanup-plan.js";
11
10
 
12
11
  const git = (cwd, args) => runGit(cwd, args, { timeout: 60000 });
13
- const CLEANUP_NEXT_STEP = "Review SAFE items, then call apply_cleanup with their item IDs; cleanup is never automatic.";
14
12
 
15
13
  async function recordPushFacts(task, proof, { eventId, artifactId }) {
16
14
  const workItem = await getWorkItemForTask(task.id);
@@ -101,8 +99,6 @@ export async function verifyDeliveryPush({ taskId, remote, branch }) {
101
99
  };
102
100
  }
103
101
  const { now, artifact } = await recordPushVerified(task, { remote, branch: targetBranch, remoteHead });
104
- const cleanupPlan = await createCleanupPlan({ taskIds: [taskId] });
105
- await saveCleanupPlan(cleanupPlan);
106
102
  return {
107
103
  task_id: taskId,
108
104
  remote,
@@ -110,8 +106,7 @@ export async function verifyDeliveryPush({ taskId, remote, branch }) {
110
106
  landed_head: task.landed_head,
111
107
  remote_head: remoteHead,
112
108
  artifact_id: artifact.id,
113
- push_verified_at: now,
114
- cleanup_plan: { id: cleanupPlan.id, summary: cleanupPlan.summary, expires_at: cleanupPlan.expires_at, next_step: CLEANUP_NEXT_STEP }
109
+ push_verified_at: now
115
110
  };
116
111
  } catch (error) {
117
112
  return { error: "push_verification_failed", task_id: taskId, remote, branch: targetBranch, reason: error.message.split("\n")[0] };
@@ -1,3 +1,4 @@
1
+ import { newWorkerBranch } from "../domain/worker-branch.js";
1
2
  import { gitBin, runGit } from "../infra/git.js";
2
3
  import { worktreesDir } from "../infra/paths.js";
3
4
  import { runToExit } from "../infra/process.js";
@@ -30,15 +31,15 @@ export function resolveCommit(cwd, ref) {
30
31
  }
31
32
 
32
33
  export function invalidBaseRefError(cwd, baseRef) {
33
- const error = new Error(`baseRef "${baseRef}" does not resolve to a commit in ${cwd}`);
34
+ const error = new Error(`workspace.base_ref "${baseRef}" does not resolve to a commit in ${cwd}`);
34
35
  error.code = "invalid_base_ref";
35
36
  return error;
36
37
  }
37
38
 
38
- // The worktree is cut from baseRef when given, else from the repository's
39
+ // The worktree is cut from workspace.base_ref when given, else from the repository's
39
40
  // HEAD. The resolved commit is recorded on the task: it is what
40
41
  // readWorktreeChanges diffs against, so committed work stays visible. An
41
- // explicit baseRef that does not resolve is an error, not a silent fallback
42
+ // explicit workspace.base_ref that does not resolve is an error, not a silent fallback
42
43
  // to HEAD - the caller asked for a specific baseline for a reason.
43
44
  export async function ensureWorktree(cwd, taskId, baseRef = null) {
44
45
  const taskWorktreeDir = join(worktreesDir, taskId);
@@ -61,7 +62,7 @@ export async function ensureWorktree(cwd, taskId, baseRef = null) {
61
62
  }
62
63
  try {
63
64
  await rm(taskWorktreeDir, { recursive: true, force: true });
64
- const branch = `codex/${taskId}`;
65
+ const branch = newWorkerBranch(taskId);
65
66
  await runToExit(gitBin(), ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, baseCommit]);
66
67
  await runToExit(gitBin(), ["-C", taskWorktreeDir, "switch", "-c", branch]);
67
68
  return { path: taskWorktreeDir, baseCommit };
@@ -79,16 +80,16 @@ function insidePath(parent, child) {
79
80
 
80
81
  export function normalizeWorkspaceSetup(value, projectRoot) {
81
82
  if (value == null) return null;
82
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspaceSetup must be an object");
83
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspace.setup must be an object");
83
84
  const links = (value.links ?? []).map((entry) => {
84
85
  if (!entry || typeof entry.path !== "string" || !entry.path.trim()
85
- || typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspaceSetup.links requires path and source");
86
+ || typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspace.setup.links requires path and source");
86
87
  const path = entry.path.trim();
87
- if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspaceSetup link path must stay inside the worktree: ${path}`);
88
+ if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspace.setup link path must stay inside the worktree: ${path}`);
88
89
  return { path, source: resolve(projectRoot, entry.source.trim()) };
89
90
  });
90
91
  const commands = (value.commands ?? []).map((command) => String(command).trim()).filter(Boolean);
91
- if (links.length > 20 || commands.length > 20) throw new Error("workspaceSetup accepts at most 20 links and 20 commands");
92
+ if (links.length > 20 || commands.length > 20) throw new Error("workspace.setup accepts at most 20 links and 20 commands");
92
93
  const submodules = value.submodules === true;
93
94
  return links.length || submodules || commands.length ? { links, submodules, commands } : null;
94
95
  }
@@ -99,7 +100,7 @@ export function requireDependencySetup({ kind, projectRoot, setup, commands }) {
99
100
  if (kind !== "git_worktree" || setup || !existsSync(join(projectRoot, "package.json"))) return;
100
101
  const commandText = (commands ?? []).map((check) => typeof check === "string" ? check : check?.command).filter(Boolean).join("\n");
101
102
  if (!JS_DEPENDENCY_COMMAND.test(commandText)) return;
102
- const error = new Error("workspace_setup_required: this JavaScript acceptance uses local project tooling, but the new worktree has no node_modules or generated prepare files; pass workspaceSetup with dependency links and prepare commands (the same setup must be used by preflight)");
103
+ const error = new Error("workspace_setup_required: this JavaScript acceptance uses local project tooling, but the new worktree has no node_modules or generated prepare files; pass workspace.setup with dependency links and prepare commands (the same setup must be used by preflight)");
103
104
  error.code = "workspace_setup_required";
104
105
  throw error;
105
106
  }
@@ -107,15 +108,15 @@ export function requireDependencySetup({ kind, projectRoot, setup, commands }) {
107
108
  export async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
108
109
  if (!setup) return;
109
110
  for (const link of setup.links) {
110
- if (!existsSync(link.source)) throw new Error(`workspaceSetup link source does not exist: ${link.source}`);
111
+ if (!existsSync(link.source)) throw new Error(`workspace.setup link source does not exist: ${link.source}`);
111
112
  const destination = resolve(worktreePath, link.path);
112
- if (!insidePath(worktreePath, destination)) throw new Error(`workspaceSetup link escapes the worktree: ${link.path}`);
113
+ if (!insidePath(worktreePath, destination)) throw new Error(`workspace.setup link escapes the worktree: ${link.path}`);
113
114
  await mkdir(dirname(destination), { recursive: true });
114
115
  if (existsSync(destination)) {
115
116
  const existing = await lstat(destination);
116
- if (!existing.isSymbolicLink()) throw new Error(`workspaceSetup link destination already exists: ${link.path}`);
117
+ if (!existing.isSymbolicLink()) throw new Error(`workspace.setup link destination already exists: ${link.path}`);
117
118
  const [actual, expected] = await Promise.all([realpath(destination), realpath(link.source)]);
118
- if (actual !== expected) throw new Error(`workspaceSetup link destination points elsewhere: ${link.path}`);
119
+ if (actual !== expected) throw new Error(`workspace.setup link destination points elsewhere: ${link.path}`);
119
120
  continue;
120
121
  }
121
122
  const sourceInfo = await stat(link.source);
@@ -131,7 +132,7 @@ export async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath,
131
132
  const result = await runAcceptance(setup.commands, { cwd: worktreePath, taskId, timeoutMs: DEFAULT_ACCEPTANCE_TIMEOUT_MS });
132
133
  if (!result.passed) {
133
134
  const failing = result.checks.find((check) => !check.passed);
134
- throw new Error(`workspaceSetup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
135
+ throw new Error(`workspace.setup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
135
136
  }
136
137
  }
137
138
  }
@@ -9,7 +9,7 @@ export function normalizeAcceptance(value) {
9
9
  const commands = list.filter((entry) => entry != null && entry !== "").map((entry) => {
10
10
  if (typeof entry === "string") return entry.trim();
11
11
  if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.command !== "string" || !entry.command.trim()) throw new Error("acceptance requires a command string or structured check");
12
- if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("reportPath must stay inside the worktree");
12
+ if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("report_path must stay inside the worktree");
13
13
  const validation = compareFailureBaseline(entry.baseline, {
14
14
  complete: true, identity: entry.baseline?.identity,
15
15
  executed: [...new Set([...(entry.baseline?.required ?? []), ...(entry.baseline?.failures ?? []).map((item) => item?.test_id)])],
@@ -0,0 +1,44 @@
1
+ // When a worker's worktree may be removed.
2
+ //
3
+ // The worker's branch is never deleted, so commits are never at risk. The only
4
+ // thing a removal can lose is uncommitted edits, and those are saved as a
5
+ // checkpoint commit on the branch first. What the policy protects is therefore
6
+ // convenience, not data: work that has not landed keeps its worktree for a
7
+ // while so it can still be inspected, resumed and landed in place.
8
+
9
+ export const DEFAULT_HOLD_DAYS = 7;
10
+
11
+ export function holdMsFrom(raw) {
12
+ if (raw === undefined || raw === null || raw === "") return DEFAULT_HOLD_DAYS * 86400000;
13
+ const days = Number(raw);
14
+ return Number.isFinite(days) && days >= 0 ? days * 86400000 : DEFAULT_HOLD_DAYS * 86400000;
15
+ }
16
+
17
+ const verdict = (value, reasons, extra = {}) => ({ verdict: value, reasons, checkpoint: false, eligible_after: null, ...extra });
18
+
19
+ // facts: { active, dependent, terminal, identity, landed, uncommitted, unlandedCommits, finishedAt }
20
+ // active / identity are a reason string or null; finishedAt is epoch ms or null.
21
+ export function cleanupVerdict(facts, { now, holdMs }) {
22
+ if (facts.active) return verdict("blocked", [facts.active]);
23
+ if (facts.dependent) return verdict("blocked", ["an active dependent still needs this work"]);
24
+ if (!facts.terminal) return verdict("blocked", ["worker has not finished"]);
25
+ if (facts.identity) return verdict("review", [facts.identity]);
26
+
27
+ const unlanded = !facts.landed && facts.unlandedCommits > 0;
28
+ if (facts.uncommitted === 0 && !unlanded) {
29
+ return verdict("safe", facts.landed ? ["landed on the target branch", "worktree clean"] : ["no changes to keep"]);
30
+ }
31
+ const what = [
32
+ unlanded ? `${facts.unlandedCommits} commit(s) not landed` : null,
33
+ facts.uncommitted > 0 ? `${facts.uncommitted} uncommitted path(s)` : null
34
+ ].filter(Boolean).join(", ");
35
+ const eligibleAt = (facts.finishedAt ?? now) + holdMs;
36
+ const eligibleAfter = new Date(eligibleAt).toISOString();
37
+ if (now < eligibleAt) {
38
+ return verdict("review", [`${what}; kept until ${eligibleAfter}, then saved on the worker branch and removed`], { eligible_after: eligibleAfter });
39
+ }
40
+ return verdict("safe", [`${what}; the hold period is over`, "everything is kept on the worker branch"], {
41
+ checkpoint: facts.uncommitted > 0,
42
+ eligible_after: eligibleAfter
43
+ });
44
+ }
@@ -16,8 +16,8 @@ export function classifyFailure(task) {
16
16
  if (provider) return provider;
17
17
  if (/did not record the process exit/i.test(error)) return { source: "supervisor_process", code: "exit_unrecorded", retryable: true };
18
18
  if (attention === "start_failed") return { source: "supervisor_process", code: "start_failed", retryable: true };
19
- if (/^workspaceSetup command failed:/i.test(error)) return { source: "workspace_setup", code: "setup_command_failed", retryable: true };
20
- if (/^workspaceSetup link /i.test(error)) return { source: "workspace_setup", code: "setup_link_failed", retryable: true };
19
+ if (/^workspace\.setup command failed:/i.test(error)) return { source: "workspace_setup", code: "setup_command_failed", retryable: true };
20
+ if (/^workspace\.setup link /i.test(error)) return { source: "workspace_setup", code: "setup_link_failed", retryable: true };
21
21
  if (attention === "invalid_report" || /Invalid final worker report/i.test(error)) return { source: "model_output", code: "invalid_report", retryable: true };
22
22
  if (task.acceptance_results?.passed === false) return { source: "acceptance", code: "acceptance_failed", retryable: true };
23
23
  if (attention === "no_work" || attention === "two_stall") return { source: "worker_progress", code: attention, retryable: false };
@@ -9,7 +9,7 @@
9
9
  // its goal.
10
10
  //
11
11
  // Report format, at the end. A worker's last message is what the supervisor
12
- // reads back through get_worker_result. Left to itself a worker narrates
12
+ // reads back through get_worker (include result). Left to itself a worker narrates
13
13
  // the whole run and lists every file it touched, and one real report ran to
14
14
  // four thousand tokens with the conclusion buried in the middle. The format
15
15
  // asks for the three things a reviewer checks and nothing else: the result,
@@ -51,11 +51,11 @@ export const REPORT_SECTIONS = ["Result", "Verification", "Not done / risks"];
51
51
 
52
52
  // The first thing a worker reads, and the only place the run's write boundary
53
53
  // is stated. A worker is not always an editor: a read-only one can only read,
54
- // and one with no ownedPaths lands nothing, so both are told what their shell
54
+ // and one with no owned_paths lands nothing, so both are told what their shell
55
55
  // may do instead of being told to use apply_patch they cannot use.
56
56
  export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands = [], forbid = [], networkAccess = false, workspaceKind = null } = {}) {
57
57
  const forbidden = JSON.stringify(forbid);
58
- 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.';
58
+ const stage = 'For a long gate, checkpoint phases with node "$AGENT_SUPERVISOR_STAGE_CLI" "gate:s3" --detail "current check"; stage text is visible to status/overview/wait and must not contain secrets.';
59
59
  if (sandbox === "read-only") {
60
60
  return [
61
61
  "Runtime supervisor guard: this is a read-only task.",
@@ -70,7 +70,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
70
70
  ? "Its execution directory is a supervisor-managed scratch directory, not the user's source directory"
71
71
  : "Its worktree is a scratch copy";
72
72
  return [
73
- "Runtime supervisor guard: this worker lands nothing: no ownedPaths means nothing it writes is ever merged into the project.",
73
+ "Runtime supervisor guard: this worker lands nothing: no owned_paths means nothing it writes is ever merged into the project.",
74
74
  `${location}, so the shell is unrestricted apart from the red lines; keep notes and downloads inside it.`,
75
75
  networkAccess ? "Network is available." : "There is no network in this sandbox; ask for it instead of retrying a failing fetch.",
76
76
  `Forbidden: ${forbidden}.`,
@@ -83,7 +83,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
83
83
  // about it instead of stalling on a tool it does not have.
84
84
  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.";
85
85
  const delivery = sandbox === "workspace-write" && (!workspaceKind || workspaceKind === "git_worktree")
86
- ? "Do not run git add, git commit or git commit --amend: the dispatcher commits reviewed edits with land_codex_worker({commitMessage}). Leave your edits uncommitted; clean status and commit-count checks belong after landing. If the task or acceptance requires a self-commit or a clean edited worktree, report the contract conflict instead of bypassing the guard."
86
+ ? "Do not run git add, git commit or git commit --amend: the dispatcher commits reviewed edits with land_worker({commit_message}). Leave your edits uncommitted; clean status and commit-count checks belong after landing. If the task or acceptance requires a self-commit or a clean edited worktree, report the contract conflict instead of bypassing the guard."
87
87
  : "";
88
88
  return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} ${delivery} 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}`;
89
89
  }
@@ -96,7 +96,7 @@ export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands =
96
96
  export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
97
97
  const commands = Array.isArray(acceptance) ? acceptance.filter(Boolean) : [];
98
98
  if (commands.length === 0) return "";
99
- const runner = 'Run node "$CODEX_SUPERVISOR_ACCEPTANCE_CLI" to execute this exact contract through the supervisor\'s non-interactive Bash with errexit and pipefail. Do not retype the commands in zsh; the interactive shell is not the acceptance shell.';
99
+ const runner = 'Run node "$AGENT_SUPERVISOR_ACCEPTANCE_CLI" to execute this exact contract through the supervisor\'s non-interactive Bash with errexit and pipefail. Do not retype the commands in zsh; the interactive shell is not the acceptance shell.';
100
100
  if (resume) {
101
101
  return ["Acceptance is unchanged.", runner, `Commands: ${commands.map((check) => typeof check === "string" ? check : JSON.stringify(check)).join(" ; ")}`].join("\n");
102
102
  }
@@ -145,7 +145,7 @@ export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null, outp
145
145
  export function buildHostGoalSync(session) {
146
146
  const id = JSON.stringify(String(session.id));
147
147
  const condition = [
148
- `For supervisor session ${id}, read get_session_works and use its current objective, default_acceptance, approval_state and policy_revision (at least ${session.policy_revision ?? 0}).`,
148
+ `For supervisor session ${id}, read find_works and use its current objective, default_acceptance, approval_state and policy_revision (at least ${session.policy_revision ?? 0}).`,
149
149
  "Use the latest explicit human instruction and approved failure baseline; superseded goals and checks must not be revived.",
150
150
  "Stop when the current approved objective is verified and all required worker results are collected, checked and integrated as requested.",
151
151
  "If approval_state is waiting_user, stop after clearly reporting the blocker, attempted checks, options and recommendation and asking for the required decision; do not auto-resume or repeat unchanged waiting reports.",
@@ -35,3 +35,12 @@ export function isGoalNeedingAttention(nativeStatus) {
35
35
  const key = String(nativeStatus ?? "").replace(/_/g, "").toLowerCase();
36
36
  return ["blocked", "paused", "usagelimited", "budgetlimited"].includes(key);
37
37
  }
38
+
39
+ // True once nothing of a worker's last run can still be running: its exit
40
+ // code is recorded (the last thing a run host writes), or the row was marked
41
+ // lost (done only after both processes were seen gone). From then on the pids
42
+ // on the row are history. The system hands them to other processes, on
43
+ // Windows within seconds, and a live stranger must not read as a live worker.
44
+ export function runIsOver(task) {
45
+ return task.status === "lost" || (TERMINAL_STATUSES.has(task.status) && task.exit_code != null);
46
+ }
@@ -2,7 +2,7 @@ const DEFAULT_HANDOFF_TOKEN_THRESHOLD = 300000;
2
2
  const LONG_THREAD_RATIO = 0.75;
3
3
 
4
4
  export function handoffTokenThreshold(env = process.env) {
5
- const raw = env.CODEX_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD;
5
+ const raw = env.AGENT_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD;
6
6
  if (raw == null || raw === "") return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
7
7
  const value = Number(raw);
8
8
  if (!Number.isFinite(value) || value < 0) return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
@@ -18,7 +18,7 @@ export function threadHealth(task, { threshold = handoffTokenThreshold() } = {})
18
18
  state: "handoff_recommended",
19
19
  threshold,
20
20
  tokens_used: tokens,
21
- next_step: "Start a fresh 1000-1500-token handoff with create_codex_followup_worker; keep this thread as evidence"
21
+ next_step: "Start a fresh 1000-1500-token handoff with create_worker with followup_of; keep this thread as evidence"
22
22
  };
23
23
  }
24
24
  if (tokens >= Math.floor(threshold * LONG_THREAD_RATIO)) {
@@ -0,0 +1,6 @@
1
+ // The branch a worker's commits live on. Workers dispatched before 1.0 used
2
+ // codex/<id>; their rows carry no branch name, so that is the fallback, and
3
+ // they can still be resumed, landed and restored.
4
+ export const newWorkerBranch = (taskId) => `worker/${taskId}`;
5
+
6
+ export const branchOf = (task) => task.workspace_metadata?.branch ?? `codex/${task.id}`;
@@ -20,7 +20,7 @@ export function collectWorkerChanges(tasks, cursor = {}) {
20
20
  id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
21
21
  reason: "handoff_recommended", tokens_used: health.tokens_used, threshold: health.threshold,
22
22
  next_step: {
23
- tool: "get_codex_worker_status", arguments: { task_id: task.id },
23
+ tool: "get_worker", arguments: { task_id: task.id, include: ["status"] },
24
24
  instruction: "Inspect the live command and stage. Let this bounded step settle or explicitly cancel it before preparing a reviewed checkpoint and a fresh follow-up; do not launch a duplicate while it is active."
25
25
  }
26
26
  };
@@ -46,8 +46,8 @@ export function collectWorkerChanges(tasks, cursor = {}) {
46
46
  const receipt = {
47
47
  id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
48
48
  reason, next_step: {
49
- tool: needsAttention ? "get_worker_result" : "get_worker_diff",
50
- arguments: { task_id: task.id },
49
+ tool: needsAttention ? "get_worker" : "get_worker_diff",
50
+ arguments: needsAttention ? { task_id: task.id, include: ["result"] } : { task_id: task.id },
51
51
  instruction: needsAttention ? "Read the failure or goal evidence before deciding whether to resume; user approval waits must not auto-resume." : "Read the result and diff, then decide whether to land. Completion is not proof of correctness."
52
52
  }
53
53
  };