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
@@ -0,0 +1,91 @@
1
+ // Removes safe worktrees and expired scratch directories without being asked.
2
+ // It rides on the polling tools, so a batch that is never cleaned up by hand
3
+ // does not grow without bound. A sweep is throttled and bounded: it must never
4
+ // make a poll slow.
5
+ import { branchOf } from "../domain/worker-branch.js";
6
+ import "./compose.js";
7
+ import { holdMsFrom } from "../domain/cleanup-policy.js";
8
+ import { TERMINAL_STATUSES } from "../domain/status.js";
9
+ import { scratchDir } from "../infra/paths.js";
10
+ import { runIdFor } from "../infra/store/db.js";
11
+ import { appendTaskEvent } from "../infra/store/events.js";
12
+ import { claimIdleTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
13
+ import { assessWorktree, recordRemoval, removeSafeWorktree } from "./cleanup-plan.js";
14
+ import { existsSync } from "node:fs";
15
+ import { rm } from "node:fs/promises";
16
+ import { join } from "node:path";
17
+
18
+ const DEFAULT_INTERVAL_MS = 10 * 60 * 1000;
19
+ const SWEEP_LIMIT = 20;
20
+ let lastSweepAt = 0;
21
+
22
+ function intervalMs() {
23
+ const raw = Number(process.env.AGENT_SUPERVISOR_CLEANUP_INTERVAL_MS);
24
+ return Number.isFinite(raw) && raw >= 0 && process.env.AGENT_SUPERVISOR_CLEANUP_INTERVAL_MS !== undefined ? raw : DEFAULT_INTERVAL_MS;
25
+ }
26
+
27
+ const finishedAt = (task) => Date.parse(task.completed_at ?? task.updated_at ?? "") || 0;
28
+
29
+ async function sweepWorktree(task, tasks, now) {
30
+ const assessed = await assessWorktree(task, tasks, now);
31
+ if (assessed.verdict !== "safe") return null;
32
+ const checkpoint = await removeSafeWorktree(task, assessed.fingerprint);
33
+ // The worktree is gone whether or not the audit row can be written.
34
+ await recordRemoval(task, { actor: "auto_cleanup", checkpoint, reasons: assessed.reasons })
35
+ .catch((error) => process.stderr.write(`[codex-supervisor] removed ${task.id} but could not record it: ${error.message}\n`));
36
+ return { task_id: task.id, kind: "worktree", branch: branchOf(task), checkpoint_commit: checkpoint, reasons: assessed.reasons };
37
+ }
38
+
39
+ // A scratch directory holds a research worker's drafts; its report is in the
40
+ // store. It goes once the hold period is over.
41
+ async function sweepScratch(task, now) {
42
+ const path = join(scratchDir, task.id);
43
+ const finished = finishedAt(task);
44
+ if (!finished || now < finished + holdMsFrom(process.env.AGENT_SUPERVISOR_CLEANUP_HOLD_DAYS) || !existsSync(path)) return null;
45
+ const claim = await claimIdleTask(task.id);
46
+ if (!claim) return null;
47
+ try {
48
+ await rm(path, { recursive: true, force: true });
49
+ } finally {
50
+ await releaseTaskRun(task.id, claim);
51
+ }
52
+ await appendTaskEvent(task.id, { type: "supervisor.cleanup_removed", kind: "scratch", removed_at: new Date(now).toISOString(), retained: ["task", "events", "jsonl", "artifacts"] },
53
+ { runId: runIdFor(task.id, task.run_count ?? 1), actor: "auto_cleanup" }).catch(() => null);
54
+ return { task_id: task.id, kind: "scratch" };
55
+ }
56
+
57
+ // Returns what was removed. One failure never stops the sweep or the poll.
58
+ export async function sweepCleanup({ now = Date.now(), force = false } = {}) {
59
+ if (process.env.AGENT_SUPERVISOR_NO_AUTO_CLEANUP === "1") return [];
60
+ if (!force && now - lastSweepAt < intervalMs()) return [];
61
+ lastSweepAt = now;
62
+ let tasks;
63
+ try {
64
+ tasks = await readTasks();
65
+ } catch (error) {
66
+ // Cleanup is housekeeping; a store hiccup must not fail the poll it rides on.
67
+ process.stderr.write(`[codex-supervisor] auto cleanup skipped: ${error.message.split("\n")[0]}\n`);
68
+ return [];
69
+ }
70
+ const finished = tasks.filter((task) => TERMINAL_STATUSES.has(task.status)).sort((a, b) => finishedAt(a) - finishedAt(b));
71
+ const removed = [];
72
+ let examined = 0;
73
+ for (const task of finished) {
74
+ if (examined >= SWEEP_LIMIT) break;
75
+ try {
76
+ if (task.workspace_kind === "scratch") {
77
+ examined += 1;
78
+ const gone = await sweepScratch(task, now);
79
+ if (gone) removed.push(gone);
80
+ continue;
81
+ }
82
+ if (!task.worktree_path || !existsSync(task.worktree_path)) continue;
83
+ examined += 1;
84
+ const gone = await sweepWorktree(task, tasks, now);
85
+ if (gone) removed.push(gone);
86
+ } catch (error) {
87
+ process.stderr.write(`[codex-supervisor] auto cleanup skipped ${task.id}: ${error.message.split("\n")[0]}\n`);
88
+ }
89
+ }
90
+ return removed;
91
+ }
@@ -0,0 +1,99 @@
1
+ // Reads what the cleanup policy needs to know about one worker's worktree.
2
+ import { branchOf } from "../domain/worker-branch.js";
3
+ import "./compose.js";
4
+ import { ACTIVE_STATUSES, TERMINAL_STATUSES, runIsOver } from "../domain/status.js";
5
+ import { gitSucceeds, runGit } from "../infra/git.js";
6
+ import { worktreesDir } from "../infra/paths.js";
7
+ import { isPidAlive } from "../infra/store/tasks.js";
8
+ import { parsePorcelainLine, resolveWorktreeBase, workspaceSetupIgnorePaths, worktreeRef } from "../infra/worktree.js";
9
+ import { lstat, realpath } from "node:fs/promises";
10
+ import { resolve } from "node:path";
11
+
12
+ // Raw output: porcelain status lines start with a significant space, and a
13
+ // quoted path would never match a setup path. Callers trim single values.
14
+ const git = (cwd, args) => runGit(cwd, args, { timeout: 15000, noOptionalLocks: true, rawPaths: true, trim: false });
15
+ const lines = (text) => text.split("\n").filter(Boolean);
16
+
17
+ function activeReason(task) {
18
+ // Once the run is over its pids may belong to anyone.
19
+ const settled = runIsOver(task);
20
+ if (!settled && task.pid && isPidAlive(task.pid)) return "worker process is still active";
21
+ if (!settled && task.run_host_pid && isPidAlive(task.run_host_pid)) return "run host process is still active";
22
+ const acceptance = task.acceptance_results;
23
+ if (acceptance?.status === "running" || (acceptance?.supervisor_pid && isPidAlive(acceptance.supervisor_pid))) return "acceptance process is still active";
24
+ return null;
25
+ }
26
+
27
+ // Null when the path is this task's managed worktree on its own branch.
28
+ async function identityProblem(task) {
29
+ if (!task.worktree_path || !task.project_root) return "no registered isolated worktree";
30
+ const path = resolve(task.worktree_path);
31
+ const managed = resolve(worktreesDir, task.id);
32
+ if (path !== managed) return "worktree is outside its managed task directory";
33
+ try {
34
+ const info = await lstat(path);
35
+ if (info.isSymbolicLink()) return "worktree is a symlink";
36
+ if (await realpath(path) !== await realpath(managed)) return "worktree realpath is unexpected";
37
+ const branch = git(path, ["symbolic-ref", "--short", "HEAD"]).trim();
38
+ if (branch !== branchOf(task)) return "worktree branch ownership is unexpected";
39
+ const registered = git(task.project_root, ["worktree", "list", "--porcelain", "-z"]).split("\0").filter((line) => line.startsWith("worktree "));
40
+ const own = await realpath(path);
41
+ for (const line of registered) {
42
+ // A registration whose directory someone deleted has no realpath; it is not ours either way.
43
+ if (await realpath(line.slice(9)).catch(() => null) === own) return null;
44
+ }
45
+ return "git worktree registration is missing";
46
+ } catch (error) {
47
+ return `cleanup proof failed: ${error.message.split("\n")[0]}`;
48
+ }
49
+ }
50
+
51
+ // Paths the dispatcher linked into the worktree (node_modules and the like)
52
+ // are setup, not the worker's output.
53
+ function setupFilter(task) {
54
+ const setup = workspaceSetupIgnorePaths(task);
55
+ return (path) => !setup.some((entry) => path === entry || path.startsWith(`${entry}/`));
56
+ }
57
+
58
+ function isLanded(task) {
59
+ if (!task.landed_at || !task.landed_head) return false;
60
+ const target = task.landed_branch ? `refs/heads/${task.landed_branch}` : "HEAD";
61
+ return gitSucceeds(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, target]);
62
+ }
63
+
64
+ function worktreeState(task) {
65
+ const path = resolve(task.worktree_path);
66
+ const keep = setupFilter(task);
67
+ const status = lines(git(path, ["status", "--porcelain", "--untracked-files=all"]));
68
+ const uncommittedPaths = status.map(parsePorcelainLine).filter((entry) => entry && keep(entry));
69
+ // Without the base the worker's own commits cannot be counted, and "nothing
70
+ // to keep" could not be told from "cannot tell".
71
+ const base = resolveWorktreeBase(path, worktreeRef(task));
72
+ if (!base) throw new Error("the commit this worker started from is unknown");
73
+ const unlandedCommits = lines(git(path, ["rev-list", `${base}..HEAD`])).length;
74
+ return { uncommittedPaths, unlandedCommits, head: git(path, ["rev-parse", "HEAD"]).trim() };
75
+ }
76
+
77
+ export async function cleanupFacts(task, tasks) {
78
+ const facts = {
79
+ active: activeReason(task),
80
+ dependent: tasks.some((other) => ACTIVE_STATUSES.has(other.status) && (other.depends_on ?? []).includes(task.id)),
81
+ terminal: TERMINAL_STATUSES.has(task.status),
82
+ identity: null, landed: false, uncommitted: 0, unlandedCommits: 0, uncommittedPaths: [], head: null,
83
+ finishedAt: Date.parse(task.completed_at ?? task.updated_at ?? "") || null
84
+ };
85
+ if (facts.active || facts.dependent || !facts.terminal) return facts;
86
+ facts.identity = await identityProblem(task);
87
+ if (facts.identity) return facts;
88
+ try {
89
+ const state = worktreeState(task);
90
+ facts.landed = isLanded(task);
91
+ facts.uncommittedPaths = state.uncommittedPaths;
92
+ facts.uncommitted = state.uncommittedPaths.length;
93
+ facts.unlandedCommits = state.unlandedCommits;
94
+ facts.head = state.head;
95
+ } catch (error) {
96
+ facts.identity = `cleanup proof failed: ${error.message.split("\n")[0]}`;
97
+ }
98
+ return facts;
99
+ }
@@ -1,25 +1,31 @@
1
- import { runGit } from "../infra/git.js";
2
- import { runSync } from "../infra/process.js";
1
+ // Plans and performs worktree cleanup. A plan classifies each worktree as
2
+ // safe, review or blocked; applying one removes only safe worktrees, after
3
+ // saving any uncommitted edits as a checkpoint commit on the worker's branch.
4
+ // Branches, task rows, events, logs and artifacts are never removed.
5
+ import { branchOf } from "../domain/worker-branch.js";
3
6
  import "./compose.js";
4
- import { createHash, randomUUID } from "node:crypto";
5
- import { lstat, realpath } from "node:fs/promises";
6
- import { resolve } from "node:path";
7
- import { ACTIVE_STATUSES } from "../domain/status.js";
8
- import { worktreesDir } from "../infra/paths.js";
7
+ import { cleanupVerdict, holdMsFrom } from "../domain/cleanup-policy.js";
8
+ import { gitSucceeds, runGit } from "../infra/git.js";
9
+ import { runSync } from "../infra/process.js";
10
+ import { runIdFor } from "../infra/store/db.js";
9
11
  import { appendTaskEvent } from "../infra/store/events.js";
10
- import { getTask, isPidAlive, readTasks } from "../infra/store/tasks.js";
11
12
  import { markCleanupPlanItemApplied, updateWorkItemDelivery } from "../infra/store/records.js";
12
- import { runIdFor } from "../infra/store/db.js";
13
+ import { claimIdleTask, getTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
14
+ import { workspaceSetupIgnorePaths } from "../infra/worktree.js";
15
+ import { cleanupFacts } from "./cleanup-facts.js";
16
+ import { identityEnv } from "./landing.js";
17
+ import { withWorktreeCreationLock } from "./worktree-setup.js";
18
+ import { createHash, randomUUID } from "node:crypto";
19
+ import { resolve } from "node:path";
13
20
 
14
21
  export const CLEANUP_PLAN_TTL_MS = 15 * 60 * 1000;
22
+ export const CLEANUP_POLICY = "keep_branch_and_evidence_checkpoint_before_removal";
23
+ const RETAINED = ["branch", "task", "events", "jsonl", "artifacts"];
15
24
 
16
- const git = (cwd, args) => runGit(cwd, args, { timeout: 15000, noOptionalLocks: true });
17
-
18
- function hash(value) {
19
- return createHash("sha256").update(value).digest("hex");
20
- }
25
+ const git = (cwd, args, options = {}) => runGit(cwd, args, { timeout: 15000, noOptionalLocks: true, ...options });
26
+ const holdMs = () => holdMsFrom(process.env.AGENT_SUPERVISOR_CLEANUP_HOLD_DAYS);
21
27
 
22
- async function directoryBytes(path) {
28
+ function directoryBytes(path) {
23
29
  try {
24
30
  const output = runSync("du", ["-sk", path], { encoding: "utf8", timeout: 30000, stdio: ["ignore", "pipe", "ignore"] }).trim();
25
31
  const kib = Number(output.split(/\s+/)[0]);
@@ -29,98 +35,102 @@ async function directoryBytes(path) {
29
35
  }
30
36
  }
31
37
 
32
- function remoteProof(task, { fetch = false } = {}) {
33
- if (!task.push_remote || !task.push_branch || !task.push_remote_head) {
34
- return { error: "remote delivery proof is incomplete; rerun verify_delivery_push" };
35
- }
36
- let remoteHead = task.push_remote_head;
37
- if (fetch) {
38
- try {
39
- git(task.project_root, ["remote", "get-url", task.push_remote]);
40
- git(task.project_root, ["fetch", "--no-tags", task.push_remote, `refs/heads/${task.push_branch}`]);
41
- remoteHead = git(task.project_root, ["rev-parse", "FETCH_HEAD"]);
42
- } catch (error) {
43
- return { error: `remote delivery proof could not be refreshed: ${error.message.split("\n")[0]}` };
44
- }
45
- }
46
- try {
47
- git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, remoteHead]);
48
- } catch {
49
- return { error: "landed head is no longer reachable from the remote branch" };
50
- }
51
- return { remoteHead };
38
+ // A plan item is only applied to the worktree it was made for: same commit,
39
+ // same uncommitted paths.
40
+ function fingerprintOf(task, facts) {
41
+ const proof = { path: resolve(task.worktree_path), head: facts.head, uncommitted: facts.uncommittedPaths, landed: facts.landed };
42
+ return createHash("sha256").update(JSON.stringify(proof)).digest("hex");
52
43
  }
53
44
 
54
- async function taskVerdict(task, tasks, { revalidateRemote = false } = {}) {
55
- if (task.status !== "completed") return { verdict: "blocked", reasons: ["worker is unfinished, failed, cancelled or lost"] };
56
- if (task.acceptance_results?.passed !== true) return { verdict: "blocked", reasons: ["acceptance is not explicitly passed"] };
57
- if (task.pid && isPidAlive(task.pid)) return { verdict: "blocked", reasons: ["worker process is still active"] };
58
- if (task.run_host_pid && isPidAlive(task.run_host_pid)) return { verdict: "blocked", reasons: ["run host process is still active"] };
59
- if (task.acceptance_results?.status === "running" || (task.acceptance_results?.supervisor_pid && isPidAlive(task.acceptance_results.supervisor_pid))) return { verdict: "blocked", reasons: ["acceptance process is still active"] };
60
- if (tasks.some((other) => ACTIVE_STATUSES.has(other.status) && (other.depends_on ?? []).includes(task.id))) return { verdict: "blocked", reasons: ["an active dependent still needs this work"] };
61
- if (!task.worktree_path || !task.project_root) return { verdict: "review", reasons: ["no registered isolated worktree"] };
62
- if (!task.landed_at || !task.landed_head) return { verdict: "blocked", reasons: ["work has not been landed"] };
63
- if (!task.push_verified_at) return { verdict: "blocked", reasons: ["remote delivery has not been verified"] };
64
- const delivery = remoteProof(task, { fetch: revalidateRemote });
65
- if (delivery.error) return { verdict: "blocked", reasons: [delivery.error] };
66
- try {
67
- const path = resolve(task.worktree_path);
68
- if (path !== resolve(worktreesDir, task.id)) return { verdict: "review", reasons: ["worktree is outside its managed task directory"] };
69
- const info = await lstat(path);
70
- if (info.isSymbolicLink()) return { verdict: "review", reasons: ["worktree is a symlink"] };
71
- if (await realpath(path) !== await realpath(resolve(worktreesDir, task.id))) return { verdict: "review", reasons: ["worktree realpath is unexpected"] };
72
- const branch = git(path, ["symbolic-ref", "--short", "HEAD"]);
73
- if (branch !== `codex/${task.id}`) return { verdict: "review", reasons: ["worktree branch ownership is unexpected"] };
74
- const registrations = git(task.project_root, ["worktree", "list", "--porcelain", "-z"]).split("\0").filter((line) => line.startsWith("worktree "));
75
- let registered = false;
76
- for (const line of registrations) if (await realpath(line.slice(9)) === await realpath(path)) registered = true;
77
- if (!registered) return { verdict: "review", reasons: ["git worktree registration is missing"] };
78
- if (git(path, ["status", "--porcelain", "--untracked-files=all"])) return { verdict: "blocked", reasons: ["worktree has uncommitted or untracked files"] };
79
- if (git(path, ["ls-files", "--others", "--ignored", "--exclude-standard"])) return { verdict: "blocked", reasons: ["worktree has ignored artifacts"] };
80
- if (task.attention_reason) return { verdict: "blocked", reasons: [`unresolved attention: ${task.attention_reason}`] };
81
- if (task.run_evidence?.external_outputs?.length) return { verdict: "blocked", reasons: ["shared output evidence is retained"] };
82
- return {
83
- verdict: "safe",
84
- reasons: ["acceptance passed", "landed", "remote delivery verified", "worktree clean", "no active dependent"],
85
- fingerprint: hash(JSON.stringify({ path, branch, head: git(path, ["rev-parse", "HEAD"]), landed: task.landed_head, push: { remote: task.push_remote, branch: task.push_branch, head: delivery.remoteHead } }))
86
- };
87
- } catch (error) {
88
- return { verdict: "review", reasons: [`cleanup proof failed: ${error.message.split("\n")[0]}`] };
89
- }
45
+ export async function assessWorktree(task, tasks, now = Date.now()) {
46
+ const facts = await cleanupFacts(task, tasks);
47
+ const result = cleanupVerdict(facts, { now, holdMs: holdMs() });
48
+ return { ...result, facts, fingerprint: result.verdict === "safe" ? fingerprintOf(task, facts) : null };
90
49
  }
91
50
 
92
- export async function createCleanupPlan({ taskIds = null, projectRoot = null, now = Date.now(), revalidateRemote = true } = {}) {
51
+ export async function createCleanupPlan({ taskIds = null, projectRoot = null, now = Date.now() } = {}) {
93
52
  const tasks = await readTasks();
94
53
  const selected = tasks.filter((task) => (!taskIds || taskIds.includes(task.id)) && (!projectRoot || resolve(task.project_root) === resolve(projectRoot)));
95
54
  const items = [];
96
55
  for (const task of selected) {
97
- const result = await taskVerdict(task, tasks, { revalidateRemote });
98
- const bytes = result.verdict === "safe" ? await directoryBytes(task.worktree_path) : 0;
99
- items.push({ task_id: task.id, verdict: result.verdict, reasons: result.reasons, fingerprint: result.fingerprint ?? null, reclaimable_bytes: bytes, eligible_after: result.verdict === "safe" ? new Date(now).toISOString() : null });
56
+ const result = await assessWorktree(task, tasks, now);
57
+ items.push({
58
+ task_id: task.id,
59
+ verdict: result.verdict,
60
+ reasons: result.reasons,
61
+ checkpoint: result.checkpoint,
62
+ fingerprint: result.fingerprint,
63
+ reclaimable_bytes: result.verdict === "safe" ? directoryBytes(task.worktree_path) : 0,
64
+ eligible_after: result.eligible_after ?? (result.verdict === "safe" ? new Date(now).toISOString() : null)
65
+ });
100
66
  }
101
- const summary = {
102
- safe: items.filter((item) => item.verdict === "safe").length,
103
- review: items.filter((item) => item.verdict === "review").length,
104
- blocked: items.filter((item) => item.verdict === "blocked").length,
105
- reclaimable_bytes: items.reduce((sum, item) => sum + item.reclaimable_bytes, 0)
106
- };
67
+ const count = (value) => items.filter((item) => item.verdict === value).length;
107
68
  return {
108
69
  id: randomUUID(),
109
70
  project_root: projectRoot ? resolve(projectRoot) : null,
110
71
  generated_at: new Date(now).toISOString(),
111
72
  expires_at: new Date(now + CLEANUP_PLAN_TTL_MS).toISOString(),
112
- policy: "explicit_apply_keep_evidence_and_branch",
113
- summary,
73
+ policy: CLEANUP_POLICY,
74
+ summary: { safe: count("safe"), review: count("review"), blocked: count("blocked"), reclaimable_bytes: items.reduce((sum, item) => sum + item.reclaimable_bytes, 0) },
114
75
  items
115
76
  };
116
77
  }
117
78
 
118
- export async function removePlannedWorktree(task, fingerprint) {
119
- const result = await taskVerdict(task, await readTasks(), { revalidateRemote: true });
120
- if (result.verdict !== "safe") throw new Error(`worktree is no longer safe: ${result.reasons.join("; ")}`);
121
- if (result.fingerprint !== fingerprint) throw new Error("worktree changed since cleanup plan; create a new plan");
122
- git(task.project_root, ["worktree", "remove", task.worktree_path]);
123
- try { git(task.project_root, ["worktree", "prune"]); } catch { /* best effort */ }
79
+ // Saves the worker's uncommitted edits as one commit on its branch. Setup
80
+ // links are left out; hooks are skipped because nobody is there to answer them.
81
+ function checkpointUncommitted(task) {
82
+ const path = resolve(task.worktree_path);
83
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(path) };
84
+ const exclude = workspaceSetupIgnorePaths(task).map((entry) => `:(exclude)${entry}`);
85
+ git(path, ["add", "-A", "--", ".", ...exclude], { env });
86
+ if (gitSucceeds(path, ["diff", "--cached", "--quiet"])) return null;
87
+ git(path, ["commit", "-q", "--no-verify", "-m", `Checkpoint before worktree cleanup (${task.id})`], { env });
88
+ return git(path, ["rev-parse", "HEAD"]);
89
+ }
90
+
91
+ // Removes one worktree after proving again that it is safe and unchanged
92
+ // since it was assessed. The task is locked the way a dispatcher locks it, so
93
+ // a resume cannot start in the directory while it is being removed. Returns
94
+ // the checkpoint commit, or null.
95
+ export async function removeSafeWorktree(task, fingerprint) {
96
+ const claim = await claimIdleTask(task.id);
97
+ if (!claim) throw new Error("the task is running or held by a dispatcher; nothing was removed");
98
+ try {
99
+ const result = await assessWorktree(task, await readTasks());
100
+ if (result.verdict !== "safe") throw new Error(`worktree is no longer safe: ${result.reasons.join("; ")}`);
101
+ if (result.fingerprint !== fingerprint) throw new Error("worktree changed since cleanup plan; create a new plan");
102
+ // The same lock that creating and restoring a worktree takes.
103
+ return await withWorktreeCreationLock(task.project_root, async () => {
104
+ const checkpoint = result.checkpoint ? checkpointUncommitted(task) : null;
105
+ // What is left now is setup links and ignored build output, neither of
106
+ // which is the worker's work; a plain remove would refuse them.
107
+ git(task.project_root, ["worktree", "remove", "--force", task.worktree_path]);
108
+ try {
109
+ git(task.project_root, ["worktree", "prune"]);
110
+ } catch {
111
+ // pruning is housekeeping; the worktree is already gone
112
+ }
113
+ return checkpoint;
114
+ });
115
+ } finally {
116
+ await releaseTaskRun(task.id, claim);
117
+ }
118
+ }
119
+
120
+ export async function recordRemoval(task, { actor, planId = null, itemId = null, checkpoint = null, reasons = [] }) {
121
+ const removedAt = new Date().toISOString();
122
+ await updateWorkItemDelivery(task.id, "cleanup_removed");
123
+ await appendTaskEvent(task.id, {
124
+ type: "supervisor.cleanup_removed",
125
+ plan_id: planId,
126
+ item_id: itemId,
127
+ removed_at: removedAt,
128
+ reasons,
129
+ checkpoint_commit: checkpoint,
130
+ branch: branchOf(task),
131
+ retained: RETAINED
132
+ }, { runId: runIdFor(task.id, task.run_count ?? 1), actor });
133
+ return removedAt;
124
134
  }
125
135
 
126
136
  export async function applyCleanupPlan({ plan, itemIds, actor = "main_thread" }) {
@@ -132,26 +142,24 @@ export async function applyCleanupPlan({ plan, itemIds, actor = "main_thread" })
132
142
  const applied = [];
133
143
  const skipped = [];
134
144
  for (const item of selected) {
145
+ const skip = (reason) => skipped.push({ item_id: item.id, task_id: item.task_id, reason });
135
146
  if (item.verdict !== "safe") {
136
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: "only SAFE plan items may be applied" });
147
+ skip("only SAFE plan items may be applied");
137
148
  continue;
138
149
  }
139
150
  const task = await getTask(item.task_id);
140
151
  if (!task) {
141
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: "task no longer exists" });
152
+ skip("task no longer exists");
142
153
  continue;
143
154
  }
144
155
  try {
145
- await removePlannedWorktree(task, item.fingerprint);
146
- const now = await markCleanupPlanItemApplied(item.id, actor);
147
- await updateWorkItemDelivery(task.id, "cleanup_removed");
148
- await appendTaskEvent(task.id, { type: "supervisor.cleanup_removed", plan_id: plan.id, item_id: item.id, removed_at: now, retained: ["branch", "task", "events", "jsonl", "artifacts"] }, {
149
- runId: runIdFor(task.id, task.run_count ?? 1), actor
150
- });
151
- applied.push({ item_id: item.id, task_id: task.id, worktree_path: task.worktree_path, removed_at: now });
156
+ const checkpoint = await removeSafeWorktree(task, item.fingerprint);
157
+ await markCleanupPlanItemApplied(item.id, actor);
158
+ const removedAt = await recordRemoval(task, { actor, planId: plan.id, itemId: item.id, checkpoint, reasons: item.reasons });
159
+ applied.push({ item_id: item.id, task_id: task.id, worktree_path: task.worktree_path, removed_at: removedAt, checkpoint_commit: checkpoint });
152
160
  } catch (error) {
153
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: error.message.split("\n")[0] });
161
+ skip(error.message.split("\n")[0]);
154
162
  }
155
163
  }
156
- return { plan_id: plan.id, applied, skipped, retained: ["branch", "task", "events", "jsonl", "artifacts"] };
164
+ return { plan_id: plan.id, applied, skipped, retained: RETAINED };
157
165
  }
@@ -1,3 +1,4 @@
1
+ import { branchOf } from "../domain/worker-branch.js";
1
2
  import { gitSucceeds } from "../infra/git.js";
2
3
  import "./compose.js";
3
4
  import { buildHandoff } from "../infra/handoff.js";
@@ -44,7 +45,7 @@ export async function compileWorkerContext(task, { attempt }) {
44
45
  `- run_id: ${runIdFor(task.id, attempt)}`,
45
46
  `- project_root: ${task.project_root}`,
46
47
  `- base_sha: ${task.base_commit ?? "unknown"}`,
47
- `- branch: ${task.worktree_path ? `codex/${task.id}` : "not applicable (in-place workspace)"}`,
48
+ `- branch: ${task.worktree_path ? branchOf(task) : "not applicable (in-place workspace)"}`,
48
49
  `- worktree: ${task.worktree_path ?? task.cwd}`,
49
50
  `- owned_paths: ${JSON.stringify(task.owned_paths ?? [])}`,
50
51
  `- acceptance_source: ${Array.isArray(task.acceptance) && task.acceptance.length > 0 ? "dispatch or session policy; commands stay outside this capsule" : "no acceptance configured"}`,
@@ -1,3 +1,4 @@
1
+ import { newWorkerBranch } from "../domain/worker-branch.js";
1
2
  import { failedStart } from "./run-state.js";
2
3
  import "./compose.js";
3
4
  import { frameWorkerPrompt } from "../domain/prompt.js";
@@ -26,7 +27,7 @@ function validateGoal(goal) {
26
27
  }
27
28
  const tokenBudget = goal.tokenBudget ?? goal.token_budget ?? null;
28
29
  if (tokenBudget !== null && (!Number.isInteger(tokenBudget) || tokenBudget <= 0)) {
29
- throw new Error("goal.tokenBudget must be a positive integer when provided");
30
+ throw new Error("goal.token_budget must be a positive integer when provided");
30
31
  }
31
32
  return { objective: goal.objective, tokenBudget };
32
33
  }
@@ -77,7 +78,7 @@ async function validateDependencies(dependsOn, projectRoot, baseCommit) {
77
78
  });
78
79
  }
79
80
  if (!baseCommit || !containsCommit(projectRoot, dependency.landed_head, baseCommit)) {
80
- throw dependencyError("dependency_base_mismatch", `worker base does not contain landed dependency ${dependencyId}; use the integrated branch or a newer baseRef`, {
81
+ throw dependencyError("dependency_base_mismatch", `worker base does not contain landed dependency ${dependencyId}; use the integrated branch or a newer workspace.base_ref`, {
81
82
  dependency_id: dependencyId,
82
83
  dependency_head: dependency.landed_head,
83
84
  base_commit: baseCommit ?? null
@@ -115,10 +116,10 @@ async function validateDispatch(input) {
115
116
  const acceptanceCommands = normalizeAcceptance(acceptance);
116
117
  if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
117
118
  if (!allowedReasoningEfforts.has(reasoningEffort)) {
118
- throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
119
+ throw new Error(`unsupported reasoning_effort: ${reasoningEffort}`);
119
120
  }
120
121
  if (!Array.isArray(ownedPaths)) {
121
- throw new Error("ownedPaths is required; pass an empty list only for a worker that must never land a change (a read-only verifier, or a research worker that reads and reports)");
122
+ throw new Error("owned_paths is required; pass an empty list only for a worker that must never land a change (a read-only verifier, or a research worker that reads and reports)");
122
123
  }
123
124
  if (ownedPaths.length > 0 && acceptanceCommands?.length && acceptanceCommands.every(isArtifactOnlyAcceptance)) {
124
125
  throw new Error("a write worker cannot use only file-existence acceptance; add a real test, endpoint probe or structured execution evidence");
@@ -128,19 +129,19 @@ async function validateDispatch(input) {
128
129
  await captureExternalOutputs(externalOutputs, { checkBaseline: true });
129
130
  if (externalOutputs.length && !acceptanceCommands?.length) throw new Error("shared outputs require explicit acceptance commands");
130
131
  if (externalOutputs.length && sandbox === "read-only") throw new Error("a read-only worker cannot declare writable shared outputs");
131
- if (networkAccess && sandbox === "danger-full-access") throw new Error("networkAccess is only for the sandboxed workers");
132
- if (networkAccess && sandbox === "read-only") throw new Error("the read-only sandbox has no network (a fetch there fails on DNS even with network_access); for a worker that must fetch, use sandbox \"workspace-write\" with networkAccess: true and ownedPaths: []");
132
+ if (networkAccess && sandbox === "danger-full-access") throw new Error("sandbox.network_access is only for the sandboxed workers");
133
+ if (networkAccess && sandbox === "read-only") throw new Error("the read-only sandbox has no network (a fetch there fails on DNS even with network_access); for a worker that must fetch, use sandbox \"workspace-write\" with sandbox.network_access: true and owned_paths: []");
133
134
  if (!Array.isArray(writableRoots) || writableRoots.length > 20 || writableRoots.some((root) => typeof root !== "string" || !isAbsolute(root))) {
134
- throw new Error("writableRoots must be a list of at most 20 absolute paths");
135
+ throw new Error("sandbox.writable_roots must be a list of at most 20 absolute paths");
135
136
  }
136
- if (writableRoots.length && sandbox !== "workspace-write") throw new Error("writableRoots is only configurable for workspace-write workers");
137
+ if (writableRoots.length && sandbox !== "workspace-write") throw new Error("sandbox.writable_roots is only configurable for workspace-write workers");
137
138
  // Codex refuses a writable root with a symlink component and then fails every
138
139
  // command in the worker, so a declared root is stored resolved. Passing the
139
140
  // alias would look fine in the receipt and break the run.
140
141
  const resolvedWritableRoots = [];
141
142
  for (const root of writableRoots) {
142
143
  const resolved = resolveWritableRoot(root);
143
- if (resolved.error) throw new Error(`writableRoots entry is unusable: ${root} (${resolved.error}); pass an existing directory whose path has no symlink component`);
144
+ if (resolved.error) throw new Error(`sandbox.writable_roots entry is unusable: ${root} (${resolved.error}); pass an existing directory whose path has no symlink component`);
144
145
  resolvedWritableRoots.push(resolved.path);
145
146
  }
146
147
  for (const value of [maxRunMs, maxTotalMs]) if (value !== null && (!Number.isInteger(value) || value < 1000)) throw new Error("time limits must be integer milliseconds of at least 1000");
@@ -150,7 +151,7 @@ async function validateDispatch(input) {
150
151
  if (baseRef && !isGitCheckout(cwd)) throw invalidBaseRefError(cwd, baseRef);
151
152
  if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
152
153
  || preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
153
- throw new Error("preflight.probeCommands must be a nonempty list of shell commands");
154
+ throw new Error("preflight.probe_commands must be a nonempty list of shell commands");
154
155
  }
155
156
  return { acceptanceCommands, validatedGoal, resolvedWritableRoots };
156
157
  }
@@ -172,7 +173,7 @@ async function claimWorkspace(input, id, acceptanceCommands) {
172
173
  const projectRoot = workspace.sourceRoot;
173
174
  const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
174
175
  const normalizedWorkspaceSetup = normalizeWorkspaceSetup(workspaceSetup, projectRoot);
175
- if (normalizedWorkspaceSetup && workspace.kind !== "git_worktree") throw new Error("workspaceSetup is only supported for git_worktree workers");
176
+ if (normalizedWorkspaceSetup && workspace.kind !== "git_worktree") throw new Error("workspace.setup is only supported for git_worktree workers");
176
177
  const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
177
178
  if (conflicts.length > 0) throw ownershipConflictError(conflicts);
178
179
  return { workspace, projectRoot, normalizedOwnedPaths, normalizedWorkspaceSetup };
@@ -192,7 +193,7 @@ async function sessionPolicy({ sessionId, sessionTitle, sessionNote }, acceptanc
192
193
  // model edits. Remove it normally; never force-remove user work.
193
194
  async function discardWorktree(projectRoot, worktreePath, id) {
194
195
  await runToExit(gitBin(), ["-C", projectRoot, "worktree", "remove", worktreePath]).catch(() => {});
195
- await runToExit(gitBin(), ["-C", projectRoot, "branch", "-D", `codex/${id}`]).catch(() => {});
196
+ await runToExit(gitBin(), ["-C", projectRoot, "branch", "-D", newWorkerBranch(id)]).catch(() => {});
196
197
  }
197
198
 
198
199
  async function createWorkerWorktree({ workspace, projectRoot, normalizedWorkspaceSetup }, id, baseRef) {
@@ -200,7 +201,7 @@ async function createWorkerWorktree({ workspace, projectRoot, normalizedWorkspac
200
201
  ? await withWorktreeCreationLock(projectRoot, () => ensureWorktree(projectRoot, id, baseRef))
201
202
  : { path: null, baseCommit: null };
202
203
  if (workspace.kind === "git_worktree" && !worktree.path) {
203
- throw coded("git_worktree_unavailable", "workspaceKind git_worktree could not create an isolated worktree; use read_only_in_place for a non-writing inspection or initialize and commit the repository first");
204
+ throw coded("git_worktree_unavailable", "workspace.kind git_worktree could not create an isolated worktree; use read_only_in_place for a non-writing inspection or initialize and commit the repository first");
204
205
  }
205
206
  if (normalizedWorkspaceSetup) {
206
207
  try {
@@ -276,7 +277,8 @@ function buildRecord(input, parts) {
276
277
  in_place_authorization: workspace.kind === "in_place_write" ? String(inPlaceAuthorization).trim() : null,
277
278
  landable: workspace.landable,
278
279
  cleanable: workspace.cleanable,
279
- setup: normalizedWorkspaceSetup
280
+ setup: normalizedWorkspaceSetup,
281
+ branch: worktreePath ? newWorkerBranch(id) : null
280
282
  },
281
283
  sandbox,
282
284
  model,
@@ -333,7 +335,7 @@ async function assertPreflightMatches(preflightId, runtimeContract) {
333
335
  }
334
336
  const contractHash = runtimeContractHash(runtimeContract);
335
337
  if (preflightResult.contract_hash === contractHash) return;
336
- throw coded("preflight_mismatch", `preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing baseRef, sandbox, ownedPaths, commands, context, contracts, network or writable roots`, {
338
+ throw coded("preflight_mismatch", `preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing workspace.base_ref, sandbox, owned_paths, commands, context, contracts, network or writable roots`, {
337
339
  preflight_id: preflightId,
338
340
  expected_contract_hash: contractHash,
339
341
  actual_contract_hash: preflightResult.contract_hash,
@@ -1,3 +1,4 @@
1
+ import { branchOf } from "../domain/worker-branch.js";
1
2
  import "./compose.js";
2
3
  import { readTaskEvents } from "../infra/store/events.js";
3
4
  import { getTask } from "../infra/store/tasks.js";
@@ -10,10 +11,10 @@ import { resolveCommit } from "./worktree-setup.js";
10
11
  function followupBaseRef(parent, baseRef) {
11
12
  if (baseRef || parent.landed_at || !parent.project_root || !parent.worktree_path) return baseRef ?? null;
12
13
  try {
13
- resolveCommit(parent.project_root, `codex/${parent.id}`);
14
- return `codex/${parent.id}`;
14
+ resolveCommit(parent.project_root, branchOf(parent));
15
+ return branchOf(parent);
15
16
  } catch {
16
- const error = new Error(`parent checkpoint codex/${parent.id} is unavailable; restore it or choose an explicit baseRef`);
17
+ const error = new Error(`parent checkpoint ${branchOf(parent)} is unavailable; restore it or choose an explicit workspace.base_ref`);
17
18
  error.code = "followup_checkpoint_missing";
18
19
  throw error;
19
20
  }
@@ -90,7 +91,7 @@ export async function createFollowupWorker(options) {
90
91
  workspaceSetup: workspaceSetup ?? parent.workspace_metadata?.setup ?? null,
91
92
  baseRef: inheritedBaseRef,
92
93
  // Inherited unless given; the follow-up runs in a fresh worktree cut
93
- // from the parent's codex/<parent> branch, so checks that depend on the
94
+ // from the parent's branch, so checks that depend on the
94
95
  // parent checkpoint are valid before the parent has landed on the target.
95
96
  acceptance: acceptance === undefined ? inheritedAcceptance : acceptance,
96
97
  acceptanceTimeoutMs: acceptanceTimeoutMs ?? parent.acceptance_timeout_ms ?? null