codex-supervisor-mcp 0.13.6 → 0.14.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/README.en.md CHANGED
@@ -28,7 +28,7 @@ codex-supervisor-mcp is an MCP server. A main thread (Claude Code, Codex, or any
28
28
  | A failed run looks the same as a dead process | The state machine keeps `failed` and `lost` apart, and a failure carries its source and code |
29
29
  | A worker says it is done and is not | Dispatch with `acceptance` commands; the supervisor runs them itself after the worker exits and refuses to land on failure |
30
30
  | Changes sit on a local branch | `land_codex_worker` merges into the integration branch; `verify_delivery_push` proves the commit is on the remote |
31
- | Worktrees pile up | Only verified, pushed and clean ones are marked SAFE, and nothing is removed until you say so. Branches and evidence stay |
31
+ | Worktrees pile up | Landed or unchanged ones are removed during polling. Unlanded work is kept for 7 days, and its uncommitted edits are committed to its branch before the worktree goes. Branches and evidence stay |
32
32
 
33
33
  A worker is a `codex exec` process and `model` is passed straight through. Keep the main thread on Claude, put the workers on DeepSeek or another provider, and the bills stay separate.
34
34
 
@@ -123,7 +123,7 @@ One block of text passes between the two sessions, pasted into the main-brain se
123
123
  | | `ask_codex_worker` | Asks the worker a side question. Read-only; its thread is untouched |
124
124
  | | `land_codex_worker` | Commits on the worker's behalf and cherry-picks onto the integration branch; refuses if acceptance failed |
125
125
  | Delivery | `verify_delivery_push` | Proves the landed commit is on the remote. It verifies; it never pushes for you |
126
- | | `cleanup_plan` / `apply_cleanup` / `cleanup_history` | Sorts worktrees into SAFE / REVIEW / BLOCKED and removes only the SAFE items you pick |
126
+ | | `cleanup_plan` / `apply_cleanup` / `cleanup_history` | Shows each worktree as SAFE, REVIEW or BLOCKED with the reason. SAFE ones are removed automatically; you can also remove one right away |
127
127
  | Sessions | `get_session_works` / `search_works` | Finds a batch again, or searches history by substring |
128
128
  | | `describe_session` | Records a batch's title, objective, default acceptance and approval state |
129
129
  | Facts | `search_worker_facts` / `get_fact` | Looks up verified facts and their versions |
package/README.md CHANGED
@@ -28,7 +28,7 @@ codex-supervisor-mcp 是一个 MCP server。主线程(Claude Code、Codex 或
28
28
  | 分不清跑失败还是进程没了 | 状态机把 `failed` 和 `lost` 分开,失败带来源和错误码 |
29
29
  | worker 说做完了其实没有 | 派单带 `acceptance` 验收命令,supervisor 在 worker 退出后自己跑,不过就拒绝合入 |
30
30
  | 改动留在本地没上线 | `land_codex_worker` 合回主分支,`verify_delivery_push` 核对远端真有这笔提交 |
31
- | worktree 越堆越多 | 验收过、已推送、干净的才判 SAFE,你点头才删;分支和证据不删 |
31
+ | worktree 越堆越多 | 已合入或没有改动的在轮询时自动清;没合入的留 7 天,删之前先把未提交的改动存进它的分支。分支和证据不删 |
32
32
 
33
33
  worker 跑的是 `codex exec`,`model` 透传。主线程留在 Claude,worker 挂 DeepSeek 或别的 provider,账单分开算。
34
34
 
@@ -122,7 +122,7 @@ codex-supervisor-web # 或 npx -p codex-supervisor-mcp codex-supervisor-web
122
122
  | | `ask_codex_worker` | 旁路问它一句,只读,不动它的线程 |
123
123
  | | `land_codex_worker` | 代提交并 cherry-pick 到集成分支,验收没过就拒 |
124
124
  | 交付 | `verify_delivery_push` | 证明合入的提交已经在远端。只验证,不替你 push |
125
- | | `cleanup_plan` / `apply_cleanup` / `cleanup_history` | 给 worktree 分 SAFE / REVIEW / BLOCKED,只删你选中的 SAFE 项 |
125
+ | | `cleanup_plan` / `apply_cleanup` / `cleanup_history` | 看每个 worktree 是 SAFE、REVIEW 还是 BLOCKED 以及原因;SAFE 项平时自动清,也可以手动立刻清 |
126
126
  | session | `get_session_works` / `search_works` | 找回一批活,或按关键字搜历史 |
127
127
  | | `describe_session` | 给一批活记标题、目标、默认验收和审批状态 |
128
128
  | 事实 | `search_worker_facts` / `get_fact` | 查已验证的事实和它的版本 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-supervisor-mcp",
3
- "version": "0.13.6",
3
+ "version": "0.14.0",
4
4
  "mcpName": "io.github.zriyox/codex-supervisor-mcp",
5
5
  "type": "module",
6
6
  "description": "MCP server that dispatches and supervises parallel Codex CLI workers, one isolated Git worktree each, with a persisted work state machine.",
@@ -28,7 +28,8 @@
28
28
  "codex-supervisor-accept": "src/interface/bin/acceptance-cli.js",
29
29
  "codex-supervisor-setup": "src/interface/bin/setup.js",
30
30
  "codex-supervisor-web": "src/interface/bin/web-server.js",
31
- "codex-supervisor-stage": "src/interface/bin/stage.js"
31
+ "codex-supervisor-stage": "src/interface/bin/stage.js",
32
+ "codex-supervisor-cleanup": "src/interface/bin/cleanup.js"
32
33
  },
33
34
  "files": [
34
35
  "src",
@@ -124,10 +124,11 @@ description: 用 Codex CLI 并行做可独立验收的功能包,每路一个 G
124
124
 
125
125
  1. 主线程自己的改动要 commit 并 push。用户批准的集成分支也要在 push 后核对远端 SHA。
126
126
  2. worker 分支通常不 push。只有用户明确要求保留远端 worker 分支时再推。
127
- 3. push 后用 `verify_delivery_push` 证明 landed head 已到远端,并生成 cleanup plan。
128
- 4. `check_workers` 只提示清理,不执行删除。
129
- 5. 只有 `acceptance passed`、`push_verified`、worktree 干净、没有活跃进程/依赖、fingerprint 未变化的 SAFE item,才可用 `apply_cleanup(plan_id, item_ids)` 删除。
130
- 6. cleanup 只执行 `git worktree remove/prune`。task、run event、JSONL、artifact 和 branch 都保留。
127
+ 3. push 后用 `verify_delivery_push` 证明 landed head 已到远端。
128
+ 4. 清理是自动的:`check_workers` / `overview_delta` 会顺带删掉已合入或没有改动的 worktree,返回里的 `cleaned` 就是删了哪些。不用为清理调任何工具。
129
+ 5. 没合入的活保留 7 天;到期先把未提交改动存进 `codex/<id>` 分支再删。还想要的活在这之前 land 或 resume。
130
+ 6. worktree 被清掉后照常 `resume_codex_worker` / `land_codex_worker` / `get_worker_diff`,会自动从分支切回来。
131
+ 7. 想立刻清:`cleanup_plan` 看判定,`apply_cleanup(plan_id, item_ids)` 清 SAFE 项。branch、task、event、JSONL、artifact 永远保留。
131
132
 
132
133
  ## 常见坑
133
134
 
@@ -0,0 +1,90 @@
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 "./compose.js";
6
+ import { holdMsFrom } from "../domain/cleanup-policy.js";
7
+ import { TERMINAL_STATUSES } from "../domain/status.js";
8
+ import { scratchDir } from "../infra/paths.js";
9
+ import { runIdFor } from "../infra/store/db.js";
10
+ import { appendTaskEvent } from "../infra/store/events.js";
11
+ import { claimIdleTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
12
+ import { assessWorktree, recordRemoval, removeSafeWorktree } from "./cleanup-plan.js";
13
+ import { existsSync } from "node:fs";
14
+ import { rm } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+
17
+ const DEFAULT_INTERVAL_MS = 10 * 60 * 1000;
18
+ const SWEEP_LIMIT = 20;
19
+ let lastSweepAt = 0;
20
+
21
+ function intervalMs() {
22
+ const raw = Number(process.env.CODEX_SUPERVISOR_CLEANUP_INTERVAL_MS);
23
+ return Number.isFinite(raw) && raw >= 0 && process.env.CODEX_SUPERVISOR_CLEANUP_INTERVAL_MS !== undefined ? raw : DEFAULT_INTERVAL_MS;
24
+ }
25
+
26
+ const finishedAt = (task) => Date.parse(task.completed_at ?? task.updated_at ?? "") || 0;
27
+
28
+ async function sweepWorktree(task, tasks, now) {
29
+ const assessed = await assessWorktree(task, tasks, now);
30
+ if (assessed.verdict !== "safe") return null;
31
+ const checkpoint = await removeSafeWorktree(task, assessed.fingerprint);
32
+ // The worktree is gone whether or not the audit row can be written.
33
+ await recordRemoval(task, { actor: "auto_cleanup", checkpoint, reasons: assessed.reasons })
34
+ .catch((error) => process.stderr.write(`[codex-supervisor] removed ${task.id} but could not record it: ${error.message}\n`));
35
+ return { task_id: task.id, kind: "worktree", branch: `codex/${task.id}`, checkpoint_commit: checkpoint, reasons: assessed.reasons };
36
+ }
37
+
38
+ // A scratch directory holds a research worker's drafts; its report is in the
39
+ // store. It goes once the hold period is over.
40
+ async function sweepScratch(task, now) {
41
+ const path = join(scratchDir, task.id);
42
+ const finished = finishedAt(task);
43
+ if (!finished || now < finished + holdMsFrom(process.env.CODEX_SUPERVISOR_CLEANUP_HOLD_DAYS) || !existsSync(path)) return null;
44
+ const claim = await claimIdleTask(task.id);
45
+ if (!claim) return null;
46
+ try {
47
+ await rm(path, { recursive: true, force: true });
48
+ } finally {
49
+ await releaseTaskRun(task.id, claim);
50
+ }
51
+ await appendTaskEvent(task.id, { type: "supervisor.cleanup_removed", kind: "scratch", removed_at: new Date(now).toISOString(), retained: ["task", "events", "jsonl", "artifacts"] },
52
+ { runId: runIdFor(task.id, task.run_count ?? 1), actor: "auto_cleanup" }).catch(() => null);
53
+ return { task_id: task.id, kind: "scratch" };
54
+ }
55
+
56
+ // Returns what was removed. One failure never stops the sweep or the poll.
57
+ export async function sweepCleanup({ now = Date.now(), force = false } = {}) {
58
+ if (process.env.CODEX_SUPERVISOR_NO_AUTO_CLEANUP === "1") return [];
59
+ if (!force && now - lastSweepAt < intervalMs()) return [];
60
+ lastSweepAt = now;
61
+ let tasks;
62
+ try {
63
+ tasks = await readTasks();
64
+ } catch (error) {
65
+ // Cleanup is housekeeping; a store hiccup must not fail the poll it rides on.
66
+ process.stderr.write(`[codex-supervisor] auto cleanup skipped: ${error.message.split("\n")[0]}\n`);
67
+ return [];
68
+ }
69
+ const finished = tasks.filter((task) => TERMINAL_STATUSES.has(task.status)).sort((a, b) => finishedAt(a) - finishedAt(b));
70
+ const removed = [];
71
+ let examined = 0;
72
+ for (const task of finished) {
73
+ if (examined >= SWEEP_LIMIT) break;
74
+ try {
75
+ if (task.workspace_kind === "scratch") {
76
+ examined += 1;
77
+ const gone = await sweepScratch(task, now);
78
+ if (gone) removed.push(gone);
79
+ continue;
80
+ }
81
+ if (!task.worktree_path || !existsSync(task.worktree_path)) continue;
82
+ examined += 1;
83
+ const gone = await sweepWorktree(task, tasks, now);
84
+ if (gone) removed.push(gone);
85
+ } catch (error) {
86
+ process.stderr.write(`[codex-supervisor] auto cleanup skipped ${task.id}: ${error.message.split("\n")[0]}\n`);
87
+ }
88
+ }
89
+ return removed;
90
+ }
@@ -0,0 +1,96 @@
1
+ // Reads what the cleanup policy needs to know about one worker's worktree.
2
+ import "./compose.js";
3
+ import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "../domain/status.js";
4
+ import { gitSucceeds, runGit } from "../infra/git.js";
5
+ import { worktreesDir } from "../infra/paths.js";
6
+ import { isPidAlive } from "../infra/store/tasks.js";
7
+ import { parsePorcelainLine, resolveWorktreeBase, workspaceSetupIgnorePaths, worktreeRef } from "../infra/worktree.js";
8
+ import { lstat, realpath } from "node:fs/promises";
9
+ import { resolve } from "node:path";
10
+
11
+ // Raw output: porcelain status lines start with a significant space, and a
12
+ // quoted path would never match a setup path. Callers trim single values.
13
+ const git = (cwd, args) => runGit(cwd, args, { timeout: 15000, noOptionalLocks: true, rawPaths: true, trim: false });
14
+ const lines = (text) => text.split("\n").filter(Boolean);
15
+
16
+ function activeReason(task) {
17
+ if (task.pid && isPidAlive(task.pid)) return "worker process is still active";
18
+ if (task.run_host_pid && isPidAlive(task.run_host_pid)) return "run host process is still active";
19
+ const acceptance = task.acceptance_results;
20
+ if (acceptance?.status === "running" || (acceptance?.supervisor_pid && isPidAlive(acceptance.supervisor_pid))) return "acceptance process is still active";
21
+ return null;
22
+ }
23
+
24
+ // Null when the path is this task's managed worktree on its own branch.
25
+ async function identityProblem(task) {
26
+ if (!task.worktree_path || !task.project_root) return "no registered isolated worktree";
27
+ const path = resolve(task.worktree_path);
28
+ const managed = resolve(worktreesDir, task.id);
29
+ if (path !== managed) return "worktree is outside its managed task directory";
30
+ try {
31
+ const info = await lstat(path);
32
+ if (info.isSymbolicLink()) return "worktree is a symlink";
33
+ if (await realpath(path) !== await realpath(managed)) return "worktree realpath is unexpected";
34
+ const branch = git(path, ["symbolic-ref", "--short", "HEAD"]).trim();
35
+ if (branch !== `codex/${task.id}`) return "worktree branch ownership is unexpected";
36
+ const registered = git(task.project_root, ["worktree", "list", "--porcelain", "-z"]).split("\0").filter((line) => line.startsWith("worktree "));
37
+ const own = await realpath(path);
38
+ for (const line of registered) {
39
+ // A registration whose directory someone deleted has no realpath; it is not ours either way.
40
+ if (await realpath(line.slice(9)).catch(() => null) === own) return null;
41
+ }
42
+ return "git worktree registration is missing";
43
+ } catch (error) {
44
+ return `cleanup proof failed: ${error.message.split("\n")[0]}`;
45
+ }
46
+ }
47
+
48
+ // Paths the dispatcher linked into the worktree (node_modules and the like)
49
+ // are setup, not the worker's output.
50
+ function setupFilter(task) {
51
+ const setup = workspaceSetupIgnorePaths(task);
52
+ return (path) => !setup.some((entry) => path === entry || path.startsWith(`${entry}/`));
53
+ }
54
+
55
+ function isLanded(task) {
56
+ if (!task.landed_at || !task.landed_head) return false;
57
+ const target = task.landed_branch ? `refs/heads/${task.landed_branch}` : "HEAD";
58
+ return gitSucceeds(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, target]);
59
+ }
60
+
61
+ function worktreeState(task) {
62
+ const path = resolve(task.worktree_path);
63
+ const keep = setupFilter(task);
64
+ const status = lines(git(path, ["status", "--porcelain", "--untracked-files=all"]));
65
+ const uncommittedPaths = status.map(parsePorcelainLine).filter((entry) => entry && keep(entry));
66
+ // Without the base the worker's own commits cannot be counted, and "nothing
67
+ // to keep" could not be told from "cannot tell".
68
+ const base = resolveWorktreeBase(path, worktreeRef(task));
69
+ if (!base) throw new Error("the commit this worker started from is unknown");
70
+ const unlandedCommits = lines(git(path, ["rev-list", `${base}..HEAD`])).length;
71
+ return { uncommittedPaths, unlandedCommits, head: git(path, ["rev-parse", "HEAD"]).trim() };
72
+ }
73
+
74
+ export async function cleanupFacts(task, tasks) {
75
+ const facts = {
76
+ active: activeReason(task),
77
+ dependent: tasks.some((other) => ACTIVE_STATUSES.has(other.status) && (other.depends_on ?? []).includes(task.id)),
78
+ terminal: TERMINAL_STATUSES.has(task.status),
79
+ identity: null, landed: false, uncommitted: 0, unlandedCommits: 0, uncommittedPaths: [], head: null,
80
+ finishedAt: Date.parse(task.completed_at ?? task.updated_at ?? "") || null
81
+ };
82
+ if (facts.active || facts.dependent || !facts.terminal) return facts;
83
+ facts.identity = await identityProblem(task);
84
+ if (facts.identity) return facts;
85
+ try {
86
+ const state = worktreeState(task);
87
+ facts.landed = isLanded(task);
88
+ facts.uncommittedPaths = state.uncommittedPaths;
89
+ facts.uncommitted = state.uncommittedPaths.length;
90
+ facts.unlandedCommits = state.unlandedCommits;
91
+ facts.head = state.head;
92
+ } catch (error) {
93
+ facts.identity = `cleanup proof failed: ${error.message.split("\n")[0]}`;
94
+ }
95
+ return facts;
96
+ }
@@ -1,25 +1,30 @@
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.
3
5
  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";
6
+ import { cleanupVerdict, holdMsFrom } from "../domain/cleanup-policy.js";
7
+ import { gitSucceeds, runGit } from "../infra/git.js";
8
+ import { runSync } from "../infra/process.js";
9
+ import { runIdFor } from "../infra/store/db.js";
9
10
  import { appendTaskEvent } from "../infra/store/events.js";
10
- import { getTask, isPidAlive, readTasks } from "../infra/store/tasks.js";
11
11
  import { markCleanupPlanItemApplied, updateWorkItemDelivery } from "../infra/store/records.js";
12
- import { runIdFor } from "../infra/store/db.js";
12
+ import { claimIdleTask, getTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
13
+ import { workspaceSetupIgnorePaths } from "../infra/worktree.js";
14
+ import { cleanupFacts } from "./cleanup-facts.js";
15
+ import { identityEnv } from "./landing.js";
16
+ import { withWorktreeCreationLock } from "./worktree-setup.js";
17
+ import { createHash, randomUUID } from "node:crypto";
18
+ import { resolve } from "node:path";
13
19
 
14
20
  export const CLEANUP_PLAN_TTL_MS = 15 * 60 * 1000;
21
+ export const CLEANUP_POLICY = "keep_branch_and_evidence_checkpoint_before_removal";
22
+ const RETAINED = ["branch", "task", "events", "jsonl", "artifacts"];
15
23
 
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
- }
24
+ const git = (cwd, args, options = {}) => runGit(cwd, args, { timeout: 15000, noOptionalLocks: true, ...options });
25
+ const holdMs = () => holdMsFrom(process.env.CODEX_SUPERVISOR_CLEANUP_HOLD_DAYS);
21
26
 
22
- async function directoryBytes(path) {
27
+ function directoryBytes(path) {
23
28
  try {
24
29
  const output = runSync("du", ["-sk", path], { encoding: "utf8", timeout: 30000, stdio: ["ignore", "pipe", "ignore"] }).trim();
25
30
  const kib = Number(output.split(/\s+/)[0]);
@@ -29,98 +34,102 @@ async function directoryBytes(path) {
29
34
  }
30
35
  }
31
36
 
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 };
37
+ // A plan item is only applied to the worktree it was made for: same commit,
38
+ // same uncommitted paths.
39
+ function fingerprintOf(task, facts) {
40
+ const proof = { path: resolve(task.worktree_path), head: facts.head, uncommitted: facts.uncommittedPaths, landed: facts.landed };
41
+ return createHash("sha256").update(JSON.stringify(proof)).digest("hex");
52
42
  }
53
43
 
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
- }
44
+ export async function assessWorktree(task, tasks, now = Date.now()) {
45
+ const facts = await cleanupFacts(task, tasks);
46
+ const result = cleanupVerdict(facts, { now, holdMs: holdMs() });
47
+ return { ...result, facts, fingerprint: result.verdict === "safe" ? fingerprintOf(task, facts) : null };
90
48
  }
91
49
 
92
- export async function createCleanupPlan({ taskIds = null, projectRoot = null, now = Date.now(), revalidateRemote = true } = {}) {
50
+ export async function createCleanupPlan({ taskIds = null, projectRoot = null, now = Date.now() } = {}) {
93
51
  const tasks = await readTasks();
94
52
  const selected = tasks.filter((task) => (!taskIds || taskIds.includes(task.id)) && (!projectRoot || resolve(task.project_root) === resolve(projectRoot)));
95
53
  const items = [];
96
54
  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 });
55
+ const result = await assessWorktree(task, tasks, now);
56
+ items.push({
57
+ task_id: task.id,
58
+ verdict: result.verdict,
59
+ reasons: result.reasons,
60
+ checkpoint: result.checkpoint,
61
+ fingerprint: result.fingerprint,
62
+ reclaimable_bytes: result.verdict === "safe" ? directoryBytes(task.worktree_path) : 0,
63
+ eligible_after: result.eligible_after ?? (result.verdict === "safe" ? new Date(now).toISOString() : null)
64
+ });
100
65
  }
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
- };
66
+ const count = (value) => items.filter((item) => item.verdict === value).length;
107
67
  return {
108
68
  id: randomUUID(),
109
69
  project_root: projectRoot ? resolve(projectRoot) : null,
110
70
  generated_at: new Date(now).toISOString(),
111
71
  expires_at: new Date(now + CLEANUP_PLAN_TTL_MS).toISOString(),
112
- policy: "explicit_apply_keep_evidence_and_branch",
113
- summary,
72
+ policy: CLEANUP_POLICY,
73
+ summary: { safe: count("safe"), review: count("review"), blocked: count("blocked"), reclaimable_bytes: items.reduce((sum, item) => sum + item.reclaimable_bytes, 0) },
114
74
  items
115
75
  };
116
76
  }
117
77
 
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 */ }
78
+ // Saves the worker's uncommitted edits as one commit on its branch. Setup
79
+ // links are left out; hooks are skipped because nobody is there to answer them.
80
+ function checkpointUncommitted(task) {
81
+ const path = resolve(task.worktree_path);
82
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(path) };
83
+ const exclude = workspaceSetupIgnorePaths(task).map((entry) => `:(exclude)${entry}`);
84
+ git(path, ["add", "-A", "--", ".", ...exclude], { env });
85
+ if (gitSucceeds(path, ["diff", "--cached", "--quiet"])) return null;
86
+ git(path, ["commit", "-q", "--no-verify", "-m", `Checkpoint before worktree cleanup (${task.id})`], { env });
87
+ return git(path, ["rev-parse", "HEAD"]);
88
+ }
89
+
90
+ // Removes one worktree after proving again that it is safe and unchanged
91
+ // since it was assessed. The task is locked the way a dispatcher locks it, so
92
+ // a resume cannot start in the directory while it is being removed. Returns
93
+ // the checkpoint commit, or null.
94
+ export async function removeSafeWorktree(task, fingerprint) {
95
+ const claim = await claimIdleTask(task.id);
96
+ if (!claim) throw new Error("the task is running or held by a dispatcher; nothing was removed");
97
+ try {
98
+ const result = await assessWorktree(task, await readTasks());
99
+ if (result.verdict !== "safe") throw new Error(`worktree is no longer safe: ${result.reasons.join("; ")}`);
100
+ if (result.fingerprint !== fingerprint) throw new Error("worktree changed since cleanup plan; create a new plan");
101
+ // The same lock that creating and restoring a worktree takes.
102
+ return await withWorktreeCreationLock(task.project_root, async () => {
103
+ const checkpoint = result.checkpoint ? checkpointUncommitted(task) : null;
104
+ // What is left now is setup links and ignored build output, neither of
105
+ // which is the worker's work; a plain remove would refuse them.
106
+ git(task.project_root, ["worktree", "remove", "--force", task.worktree_path]);
107
+ try {
108
+ git(task.project_root, ["worktree", "prune"]);
109
+ } catch {
110
+ // pruning is housekeeping; the worktree is already gone
111
+ }
112
+ return checkpoint;
113
+ });
114
+ } finally {
115
+ await releaseTaskRun(task.id, claim);
116
+ }
117
+ }
118
+
119
+ export async function recordRemoval(task, { actor, planId = null, itemId = null, checkpoint = null, reasons = [] }) {
120
+ const removedAt = new Date().toISOString();
121
+ await updateWorkItemDelivery(task.id, "cleanup_removed");
122
+ await appendTaskEvent(task.id, {
123
+ type: "supervisor.cleanup_removed",
124
+ plan_id: planId,
125
+ item_id: itemId,
126
+ removed_at: removedAt,
127
+ reasons,
128
+ checkpoint_commit: checkpoint,
129
+ branch: `codex/${task.id}`,
130
+ retained: RETAINED
131
+ }, { runId: runIdFor(task.id, task.run_count ?? 1), actor });
132
+ return removedAt;
124
133
  }
125
134
 
126
135
  export async function applyCleanupPlan({ plan, itemIds, actor = "main_thread" }) {
@@ -132,26 +141,24 @@ export async function applyCleanupPlan({ plan, itemIds, actor = "main_thread" })
132
141
  const applied = [];
133
142
  const skipped = [];
134
143
  for (const item of selected) {
144
+ const skip = (reason) => skipped.push({ item_id: item.id, task_id: item.task_id, reason });
135
145
  if (item.verdict !== "safe") {
136
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: "only SAFE plan items may be applied" });
146
+ skip("only SAFE plan items may be applied");
137
147
  continue;
138
148
  }
139
149
  const task = await getTask(item.task_id);
140
150
  if (!task) {
141
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: "task no longer exists" });
151
+ skip("task no longer exists");
142
152
  continue;
143
153
  }
144
154
  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 });
155
+ const checkpoint = await removeSafeWorktree(task, item.fingerprint);
156
+ await markCleanupPlanItemApplied(item.id, actor);
157
+ const removedAt = await recordRemoval(task, { actor, planId: plan.id, itemId: item.id, checkpoint, reasons: item.reasons });
158
+ applied.push({ item_id: item.id, task_id: task.id, worktree_path: task.worktree_path, removed_at: removedAt, checkpoint_commit: checkpoint });
152
159
  } catch (error) {
153
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: error.message.split("\n")[0] });
160
+ skip(error.message.split("\n")[0]);
154
161
  }
155
162
  }
156
- return { plan_id: plan.id, applied, skipped, retained: ["branch", "task", "events", "jsonl", "artifacts"] };
163
+ return { plan_id: plan.id, applied, skipped, retained: RETAINED };
157
164
  }
@@ -1,3 +1,4 @@
1
+ import { ensureTaskWorktree } from "./restore-worktree.js";
1
2
  import "./compose.js";
2
3
  import { runGit } from "../infra/git.js";
3
4
  import { appendTaskEvent } from "../infra/store/events.js";
@@ -67,6 +68,14 @@ export async function landOneWorkerTask(taskId, options = {}) {
67
68
  if (!isSettled(task)) return { error: "worker_active", task_id: taskId, reason: "wait for this run and acceptance to settle before landing" };
68
69
  if (session?.approval_state === "waiting_user") return { error: "session_waiting_user", task_id: taskId, reason: "session requires user approval before landing" };
69
70
  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" };
71
+ // Cleanup may have removed the worktree of work that never landed; its branch brings it back.
72
+ if (!task.landed_at) {
73
+ try {
74
+ await ensureTaskWorktree(task);
75
+ } catch (error) {
76
+ return { error: error.code ?? "worktree_restore_failed", task_id: taskId, reason: error.message.split("\n")[0] };
77
+ }
78
+ }
70
79
  if (skipAlreadyLanded && task.landed_at && (!task.worktree_path || !existsSync(task.worktree_path))) {
71
80
  try {
72
81
  const targetBranch = git(task.project_root, ["symbolic-ref", "--short", "HEAD"]);
@@ -0,0 +1,50 @@
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 "./compose.js";
5
+ import { gitBin, gitSucceeds } from "../infra/git.js";
6
+ import { runToExit } from "../infra/process.js";
7
+ import { runIdFor } from "../infra/store/db.js";
8
+ import { appendTaskEvent } from "../infra/store/events.js";
9
+ import { updateWorkItemDelivery } from "../infra/store/records.js";
10
+ import { prepareWorktreeWorkspace, withWorktreeCreationLock } from "./worktree-setup.js";
11
+ import { existsSync } from "node:fs";
12
+
13
+ function deliveryStepOf(task) {
14
+ if (task.push_verified_at) return "push_verified";
15
+ return task.landed_at ? "landed" : "draft";
16
+ }
17
+
18
+ // True when a worktree was restored, false when there was nothing to do
19
+ // (already present, or the task never had one). Throws when the worktree is
20
+ // gone and cannot be brought back, so no caller carries on somewhere else.
21
+ export async function ensureTaskWorktree(task) {
22
+ if (!task.worktree_path || !task.project_root || existsSync(task.worktree_path)) return false;
23
+ const branch = `codex/${task.id}`;
24
+ if (!gitSucceeds(task.project_root, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`])) {
25
+ const error = new Error(`the worktree of ${task.id} is gone and its branch ${branch} does not exist, so it cannot be restored`);
26
+ error.code = "worktree_unrecoverable";
27
+ throw error;
28
+ }
29
+ const restored = await withWorktreeCreationLock(task.project_root, async () => {
30
+ if (existsSync(task.worktree_path)) return false;
31
+ await runToExit(gitBin(), ["-C", task.project_root, "worktree", "prune"]).catch(() => {});
32
+ await runToExit(gitBin(), ["-C", task.project_root, "worktree", "add", task.worktree_path, branch]);
33
+ return true;
34
+ });
35
+ if (!restored) return false;
36
+ const setup = task.workspace_metadata?.setup ?? null;
37
+ if (setup) {
38
+ try {
39
+ await prepareWorktreeWorkspace(setup, task.project_root, task.worktree_path, task.id);
40
+ } catch (error) {
41
+ // A worktree without its setup would look restored and fail at the first command.
42
+ await runToExit(gitBin(), ["-C", task.project_root, "worktree", "remove", "--force", task.worktree_path]).catch(() => {});
43
+ throw error;
44
+ }
45
+ }
46
+ await updateWorkItemDelivery(task.id, deliveryStepOf(task)).catch(() => null);
47
+ await appendTaskEvent(task.id, { type: "supervisor.worktree_restored", branch, restored_at: new Date().toISOString() },
48
+ { runId: runIdFor(task.id, task.run_count ?? 1), actor: "supervisor" }).catch(() => null);
49
+ return true;
50
+ }
package/src/app/resume.js CHANGED
@@ -1,3 +1,5 @@
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
5
  import { ACTIVE_STATUSES } from "../domain/status.js";
@@ -82,6 +84,20 @@ 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");
@@ -91,10 +107,11 @@ async function resumeClaimed(claimed, { prompt, rebaseOnto, acceptance }) {
91
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_codex_followup_worker 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({
@@ -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] };
@@ -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
+ }
@@ -8,7 +8,7 @@ function readyToLand(task) {
8
8
 
9
9
  function readyToClean(task, readyToCleanTaskIds = null) {
10
10
  if (readyToCleanTaskIds) return readyToCleanTaskIds.has(task.id);
11
- return task.push_verified_at && ["cleanup_eligible"].includes(task.delivery_state);
11
+ return task.delivery_state === "cleanup_eligible";
12
12
  }
13
13
 
14
14
  function attentionReason(task) {
@@ -22,7 +22,7 @@ function nextAction(task, { attention, readyToLand, readyToClean }) {
22
22
  if (attention) return "inspect the worker evidence and resolve the recorded blocker";
23
23
  if (task.delivery_state === "cleanup_eligible" && !readyToClean) return "rerun cleanup_plan; the previous cleanup proof is no longer current";
24
24
  if (readyToLand) return "review the diff and acceptance, then land the worker";
25
- if (readyToClean) return "review the cleanup plan item, then explicitly apply it";
25
+ if (readyToClean) return "nothing to do: the worktree is removed on a later poll, and its branch is kept";
26
26
  if (task.status === "completed" && !task.landed_at) return "review the worker result and decide whether to land it";
27
27
  return null;
28
28
  }
@@ -9,10 +9,10 @@ export function cleanupThreshold(raw = process.env.SUPERVISOR_CLEANUP_HINT) {
9
9
  return Number.isFinite(value) && value >= 0 ? value : DEFAULT_THRESHOLD;
10
10
  }
11
11
 
12
- // A batch that never cleans up should say so instead of quietly growing to
13
- // hundreds of worktrees. The hint only reports a count and the two commands;
14
- // deletion stays a deliberate step, because cleanup only removes worktrees that
15
- // are merged and clean and keeps dirty, unmerged, lost and failed work.
12
+ // Safe worktrees are removed automatically, so a store that still holds this
13
+ // many has work that is being kept on purpose (unlanded and inside the hold
14
+ // period, or needing review) or has automatic cleanup switched off. The hint
15
+ // reports the count and where to look.
16
16
  export async function cleanupHint({ list = readdir, root = supervisorRoot, dir = worktreesDir, threshold = cleanupThreshold() } = {}) {
17
17
  if (!threshold) return null;
18
18
  let entries;
@@ -21,10 +21,9 @@ export async function cleanupHint({ list = readdir, root = supervisorRoot, dir =
21
21
  return {
22
22
  worktrees: entries,
23
23
  threshold,
24
- command: `SUPERVISOR_HOME=${root} npm run cleanup -- --dry-run`,
24
+ command: `SUPERVISOR_HOME=${root} codex-supervisor-cleanup --dry-run`,
25
25
  apply: null,
26
- next_step: "Review the dry-run plan_id and a SAFE item id, then call apply_cleanup; CLI apply also requires --plan and --item.",
27
- note: "only acceptance-passed, push-verified, clean worktrees without active processes or dependents become SAFE; apply retains branches and evidence"
26
+ next_step: "Read the plan: REVIEW items say when they become removable. Land or resume the work you still want; apply_cleanup removes a SAFE item right away.",
27
+ note: "a worktree is SAFE once its work has landed, or has nothing to keep, or its hold period is over; uncommitted edits are saved on the worker branch first, and branches and evidence are never removed"
28
28
  };
29
29
  }
30
-
@@ -101,6 +101,23 @@ export async function updateWorkItemDelivery(taskId, deliveryState) {
101
101
  return result.changes > 0;
102
102
  }
103
103
 
104
+ // A safe item marks its work item cleanup_eligible. An item that is no longer
105
+ // safe goes back to the furthest delivery step its task row proves.
106
+ function markCleanupEligibility(dbInstance, item) {
107
+ const now = new Date().toISOString();
108
+ if (item.verdict === "safe") {
109
+ dbInstance.prepare("UPDATE work_items SET delivery_state = 'cleanup_eligible', updated_at = ? WHERE task_id = ? AND delivery_state NOT IN ('cleanup_eligible', 'cleanup_removed')")
110
+ .run(now, item.task_id);
111
+ return;
112
+ }
113
+ dbInstance.prepare(`
114
+ UPDATE work_items SET updated_at = ?, delivery_state = (
115
+ SELECT CASE WHEN push_verified_at IS NOT NULL THEN 'push_verified' WHEN landed_at IS NOT NULL THEN 'landed' ELSE 'draft' END
116
+ FROM tasks WHERE tasks.id = work_items.task_id
117
+ ) WHERE task_id = ? AND delivery_state = 'cleanup_eligible'
118
+ `).run(now, item.task_id);
119
+ }
120
+
104
121
  export async function saveCleanupPlan(plan) {
105
122
  await ensureFilesystem();
106
123
  const dbInstance = openDb();
@@ -117,13 +134,7 @@ export async function saveCleanupPlan(plan) {
117
134
  for (const item of plan.items) {
118
135
  item.id = item.id ?? randomUUID();
119
136
  insert.run(item.id, plan.id, item.task_id, item.verdict, JSON.stringify(item.reasons), item.fingerprint, item.reclaimable_bytes, item.eligible_after);
120
- if (item.verdict === "safe") {
121
- dbInstance.prepare("UPDATE work_items SET delivery_state = 'cleanup_eligible', updated_at = ? WHERE task_id = ? AND delivery_state = 'push_verified'")
122
- .run(new Date().toISOString(), item.task_id);
123
- } else {
124
- dbInstance.prepare("UPDATE work_items SET delivery_state = 'push_verified', updated_at = ? WHERE task_id = ? AND delivery_state = 'cleanup_eligible'")
125
- .run(new Date().toISOString(), item.task_id);
126
- }
137
+ markCleanupEligibility(dbInstance, item);
127
138
  }
128
139
  dbInstance.exec("COMMIT");
129
140
  } catch (error) {
@@ -192,6 +192,36 @@ export async function claimTaskRun(taskId, expectedRun) {
192
192
  });
193
193
  }
194
194
 
195
+ // The same lock a dispatcher takes before it runs a task, for work that needs
196
+ // the task to stay idle without running it (removing its worktree). Null when
197
+ // the task is running, settling, or held by a live dispatcher.
198
+ export async function claimIdleTask(taskId) {
199
+ await ensureFilesystem();
200
+ const connection = openDb();
201
+ return runWithRetry(connection, () => {
202
+ connection.exec("BEGIN IMMEDIATE");
203
+ try {
204
+ const row = connection.prepare("SELECT * FROM tasks WHERE id=?").get(taskId);
205
+ const claim = connection.prepare("SELECT * FROM run_claims WHERE task_id=?").get(taskId);
206
+ const busy = !row || ACTIVE_STATUSES.has(row.status)
207
+ || (["completed", "failed"].includes(row.status) && row.exit_code == null)
208
+ || decodeJson(row.acceptance_results, null)?.status === "running"
209
+ || (claim && isPidAlive(claim.owner_pid));
210
+ let token = null;
211
+ if (!busy) {
212
+ token = randomUUID();
213
+ connection.prepare("INSERT INTO run_claims VALUES (?,?,?) ON CONFLICT(task_id) DO UPDATE SET token=excluded.token,owner_pid=excluded.owner_pid")
214
+ .run(taskId, token, process.pid);
215
+ }
216
+ connection.exec("COMMIT");
217
+ return token;
218
+ } catch (error) {
219
+ connection.exec("ROLLBACK");
220
+ throw error;
221
+ }
222
+ });
223
+ }
224
+
195
225
  export async function releaseTaskRun(taskId, token) {
196
226
  openDb().prepare("DELETE FROM run_claims WHERE task_id=? AND token=?").run(taskId, token);
197
227
  }
@@ -29,7 +29,7 @@ function parseArgs(argv) {
29
29
  }
30
30
 
31
31
  function printHelp() {
32
- console.log(`Usage: npm run cleanup -- [options]
32
+ console.log(`Usage: codex-supervisor-cleanup [options]
33
33
 
34
34
  Options:
35
35
  --dry-run Create and print a SAFE / REVIEW / BLOCKED plan. Default.
@@ -89,7 +89,7 @@ export const verifyDeliveryPushTool = [
89
89
  "verify_delivery_push",
90
90
  {
91
91
  title: "Verify landed work reached a remote branch",
92
- description: "Fetch a remote branch and prove the worker's landed_head is reachable from it. This never pushes or deploys. A passing check records push_verified; cleanup eligibility may depend on this evidence.",
92
+ description: "Fetch a remote branch and prove the worker's landed_head is reachable from it. This never pushes or deploys. A passing check records push_verified.",
93
93
  inputSchema: {
94
94
  task_id: z.string().min(1),
95
95
  remote: z.string().min(1).default("origin"),
@@ -103,7 +103,7 @@ export const cleanupPlanTool = [
103
103
  "cleanup_plan",
104
104
  {
105
105
  title: "Plan safe worktree cleanup",
106
- description: "Classify managed worktrees as safe, review or blocked. The plan is read-only, expires after 15 minutes, estimates reclaimable bytes and never deletes branches, task rows, events, JSONL logs or artifacts.",
106
+ description: "Show why each managed worktree is safe, review or blocked. Safe worktrees (landed, or nothing to keep, or past the hold period) are removed automatically during polling, so call this to see reasons and dates or to remove one right away with apply_cleanup. Read-only; the plan expires after 15 minutes.",
107
107
  inputSchema: {
108
108
  task_ids: z.array(z.string().min(1)).max(200).optional(),
109
109
  project_root: z.string().min(1).optional()
@@ -131,7 +131,7 @@ export const applyCleanupTool = [
131
131
  "apply_cleanup",
132
132
  {
133
133
  title: "Apply a safe cleanup plan",
134
- description: "Remove only selected SAFE worktrees from an unexpired cleanup plan after a second proof check. Uses git worktree remove and prune only; retains the branch, task row, event stream, JSONL log and artifacts.",
134
+ description: "Remove selected SAFE worktrees from an unexpired cleanup plan now, after assessing them again. Uncommitted edits are committed to the worker branch first. Keeps the branch, task row, event stream, JSONL log and artifacts.",
135
135
  inputSchema: {
136
136
  plan_id: z.string().uuid(),
137
137
  item_ids: z.array(z.string().uuid()).min(1).max(200)
@@ -1,4 +1,4 @@
1
- import { createCleanupPlan } from "../../../app/cleanup-plan.js";
1
+ import { sweepCleanup } from "../../../app/auto-cleanup.js";
2
2
  import { recoverEligibleRuns } from "../../../app/resume.js";
3
3
  import { buildOverviewDelta } from "../../../domain/overview-delta.js";
4
4
  import { collectWorkerChanges } from "../../../domain/worker-changes.js";
@@ -17,7 +17,7 @@ export const overviewDeltaTool = [
17
17
  "overview_delta",
18
18
  {
19
19
  title: "Get orchestration delta",
20
- description: "Return a small cursor-based orchestration view: active, needs_attention, ready_to_land, ready_to_clean and changed task summaries. It never returns full history, prompts, diffs, events or worker capsules.",
20
+ description: "Return a small cursor-based orchestration view: active, needs_attention, ready_to_land, ready_to_clean and changed task summaries, plus `cleaned` when safe worktrees were removed on this call. It never returns full history, prompts, diffs, events or worker capsules.",
21
21
  inputSchema: { cursor: z.record(z.string(), z.string()).optional() }
22
22
  },
23
23
  async ({ cursor }) => {
@@ -25,17 +25,11 @@ export const overviewDeltaTool = [
25
25
  await reconcileDetachedActiveTasks();
26
26
  const tasks = await readTasks();
27
27
  const previous = cursor ?? await readObserverCursor(deltaObserverId);
28
- const candidateIds = tasks.filter((task) => task.delivery_state === "cleanup_eligible").map((task) => task.id);
29
- const cleanupReadiness = candidateIds.length > 0
30
- ? await createCleanupPlan({ taskIds: candidateIds, revalidateRemote: false })
31
- : null;
32
- const readyToCleanTaskIds = cleanupReadiness
33
- ? new Set(cleanupReadiness.items.filter((item) => item.verdict === "safe").map((item) => item.task_id))
34
- : new Set();
35
- const result = buildOverviewDelta(tasks, previous, { readyToCleanTaskIds });
28
+ const cleaned = await sweepCleanup();
29
+ const result = buildOverviewDelta(cleaned.length ? await readTasks() : tasks, previous);
36
30
  await writeObserverCursor(deltaObserverId, result.cursor);
37
31
  const { cursor: nextCursor, ...reply } = result;
38
- return textResult({ ...reply, next_cursor: nextCursor });
32
+ return textResult({ ...reply, next_cursor: nextCursor, ...(cleaned.length ? { cleaned } : {}) });
39
33
  });
40
34
  deltaRead = read.catch(() => {});
41
35
  return read;
@@ -43,7 +37,7 @@ export const overviewDeltaTool = [
43
37
  ];
44
38
  export const checkWorkersTool = ["check_workers", {
45
39
  title: "Check changed workers",
46
- description: "Check newly settled runs, actionable failures and active threads crossing the handoff threshold; automatically resume a dead lost/no_work first run once, except approval, authentication, permission and quota waits. Handoff reminders occur once per run and never cancel, replace or resume a live worker. Unchanged state is quiet. Call from a host-scheduled loop; it cannot wake a closed host. Set a distinct CODEX_SUPERVISOR_OBSERVER_ID per main thread to retain its cursor across restarts.",
40
+ description: "Check newly settled runs, actionable failures and active threads crossing the handoff threshold; automatically resume a dead lost/no_work first run once, except approval, authentication, permission and quota waits. Handoff reminders occur once per run and never cancel, replace or resume a live worker. Safe worktrees are removed along the way and listed under `cleaned`. Unchanged state is quiet. Call from a host-scheduled loop; it cannot wake a closed host. Set a distinct CODEX_SUPERVISOR_OBSERVER_ID per main thread to retain its cursor across restarts.",
47
41
  inputSchema: {}
48
42
  }, async () => {
49
43
  const read = observerRead.then(async () => {
@@ -54,8 +48,10 @@ export const checkWorkersTool = ["check_workers", {
54
48
  const { cursor, ...reply } = result;
55
49
  // The cleanup hint rides along without touching quiet: it is a standing fact
56
50
  // about the store, not a new worker event.
51
+ const cleaned = await sweepCleanup();
57
52
  const cleanup = await cleanupHint();
58
- return textResult({ ...reply, quiet: reply.quiet && recoveries.length === 0, recoveries, ...(cleanup ? { cleanup } : {}) });
53
+ const extras = { ...(cleaned.length ? { cleaned } : {}), ...(cleanup ? { cleanup } : {}) };
54
+ return textResult({ ...reply, quiet: reply.quiet && recoveries.length === 0, recoveries, ...extras });
59
55
  });
60
56
  observerRead = read.catch(() => {});
61
57
  return read;
@@ -1,3 +1,4 @@
1
+ import { ensureTaskWorktree } from "../../../app/restore-worktree.js";
1
2
  import { askWorker, endSideSession, latestSideTurn } from "../../../app/side-chat.js";
2
3
  import { isGoalNeedingAttention, TERMINAL_STATUSES } from "../../../domain/status.js";
3
4
  import { truncateMiddleChars, truncateReport } from "../../../domain/truncate.js";
@@ -131,6 +132,17 @@ export const getWorkerResultTool = [
131
132
  }
132
133
  ];
133
134
 
135
+ // Cleanup keeps the branch; the diff is read from a worktree cut from it
136
+ // again. Null when the worktree is there, a refusal when it cannot come back.
137
+ async function restoreRefusal(task) {
138
+ try {
139
+ await ensureTaskWorktree(task);
140
+ return null;
141
+ } catch (error) {
142
+ return textResult({ error: error.code ?? "worktree_restore_failed", task_id: task.id, reason: error.message.split("\n")[0] });
143
+ }
144
+ }
145
+
134
146
  export const getWorkerDiffTool = [
135
147
  "get_worker_diff",
136
148
  {
@@ -153,6 +165,8 @@ export const getWorkerDiffTool = [
153
165
  if (!task.worktree_path) {
154
166
  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" });
155
167
  }
168
+ const refusal = await restoreRefusal(task);
169
+ if (refusal) return refusal;
156
170
  if (!file && maxChars !== undefined) {
157
171
  const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [], ignorePaths: workspaceSetupIgnorePaths(task) });
158
172
  return textResult({