codex-supervisor-mcp 0.8.0 → 0.9.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 +40 -10
- package/README.md +40 -10
- package/package.json +10 -1
- package/skills/codex-supervisor/SKILL.md +30 -5
- package/src/acceptance-baseline.js +64 -0
- package/src/acceptance.js +264 -0
- package/src/cleanup.js +66 -19
- package/src/codex-runner.js +287 -29
- package/src/event-parser.js +4 -1
- package/src/external-output.js +29 -0
- package/src/goal-store.js +10 -7
- package/src/handoff.js +31 -0
- package/src/landing.js +32 -8
- package/src/mcp-server.js +181 -28
- package/src/owned-changes.js +27 -0
- package/src/prompt.js +24 -4
- package/src/status.js +1 -1
- package/src/task-store.js +156 -8
- package/src/tool-guard.js +66 -0
- package/src/web-app.js +2 -1
- package/src/worker-changes.js +38 -0
- package/src/worker-report.js +15 -0
- package/src/worker-report.schema.json +10 -0
- package/src/worktree.js +25 -1
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// The supervisor's own run of a worker's acceptance commands.
|
|
2
|
+
//
|
|
3
|
+
// A worker's report says what it did; its command history says what it ran.
|
|
4
|
+
// Neither says whether the work is right. The one thing a harness can check
|
|
5
|
+
// is a criterion the dispatcher wrote down: run these commands in the
|
|
6
|
+
// worktree once the worker has exited, every one must exit 0. The worker
|
|
7
|
+
// never grades its own homework here: the commands run after it is gone,
|
|
8
|
+
// in a process it did not start, and the verdict is recorded next to its
|
|
9
|
+
// report so a reviewer sees both.
|
|
10
|
+
//
|
|
11
|
+
// The commands are shell lines written by the main thread, so they run with
|
|
12
|
+
// the supervisor's own privileges, exactly as if the main thread had run
|
|
13
|
+
// them itself. That is the trust model and it is stated in the tool text.
|
|
14
|
+
import { spawn, execFileSync } from "node:child_process";
|
|
15
|
+
import { existsSync } from "node:fs";
|
|
16
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { dirname, join, isAbsolute, relative, resolve } from "node:path";
|
|
19
|
+
import { findBinaryPath } from "./bin-resolver.js";
|
|
20
|
+
import { compareFailureBaseline } from "./acceptance-baseline.js";
|
|
21
|
+
|
|
22
|
+
export const DEFAULT_ACCEPTANCE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
23
|
+
export const MAX_ACCEPTANCE_COMMANDS = 10;
|
|
24
|
+
const OUTPUT_TAIL_BYTES = 2000;
|
|
25
|
+
const KILL_GRACE_MS = 3000;
|
|
26
|
+
|
|
27
|
+
// One string or a list; blanks dropped; an empty list is "not configured".
|
|
28
|
+
export function normalizeAcceptance(value) {
|
|
29
|
+
const list = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
|
|
30
|
+
const commands = list.filter((entry) => entry != null && entry !== "").map((entry) => {
|
|
31
|
+
if (typeof entry === "string") return entry.trim();
|
|
32
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.command !== "string" || !entry.command.trim()) throw new Error("acceptance requires a command string or structured check");
|
|
33
|
+
if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("reportPath must stay inside the worktree");
|
|
34
|
+
const validation = compareFailureBaseline(entry.baseline, {
|
|
35
|
+
complete: true, identity: entry.baseline?.identity,
|
|
36
|
+
executed: [...new Set([...(entry.baseline?.required ?? []), ...(entry.baseline?.failures ?? []).map((item) => item?.test_id)])],
|
|
37
|
+
skipped: [], failures: entry.baseline?.failures
|
|
38
|
+
});
|
|
39
|
+
// Validation errors concern the contract; diff results concern actual
|
|
40
|
+
// failures, which do not exist at normalization time.
|
|
41
|
+
if (validation.errors.length) throw new Error(`invalid acceptance baseline: ${validation.errors.join("; ")}`);
|
|
42
|
+
return { command: entry.command.trim(), reportPath: entry.reportPath, baseline: structuredClone(entry.baseline) };
|
|
43
|
+
}).filter(Boolean);
|
|
44
|
+
if (commands.length === 0) return null;
|
|
45
|
+
if (commands.length > MAX_ACCEPTANCE_COMMANDS) {
|
|
46
|
+
const error = new Error(`acceptance lists ${commands.length} commands; at most ${MAX_ACCEPTANCE_COMMANDS} are run`);
|
|
47
|
+
error.code = "too_many_acceptance_commands";
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
return commands;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function readCheckEvidence(check, cwd, checkId, baseCommit) {
|
|
54
|
+
try {
|
|
55
|
+
const root = await realpath(cwd);
|
|
56
|
+
const path = resolve(cwd, check.reportPath);
|
|
57
|
+
const canonical = await realpath(path);
|
|
58
|
+
const outside = relative(root, canonical);
|
|
59
|
+
if (outside === ".." || outside.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(outside)) throw new Error("reportPath escapes the worktree");
|
|
60
|
+
const info = await lstat(path);
|
|
61
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) throw new Error("report must be a regular file of at most 1 MiB");
|
|
62
|
+
const report = JSON.parse(await readFile(path, "utf8"));
|
|
63
|
+
if (report.check_id !== checkId) throw new Error("report check_id does not belong to this check; reused evidence is invalid");
|
|
64
|
+
if (baseCommit && check.baseline.identity.base_commit !== baseCommit) throw new Error("approved baseline base_commit differs from the current run base");
|
|
65
|
+
const baseline = compareFailureBaseline(check.baseline, report);
|
|
66
|
+
return { passed: baseline.passed, baseline };
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return { passed: false, error: `acceptance evidence: ${error.message}` };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function tail(buffer) {
|
|
73
|
+
if (buffer.length <= OUTPUT_TAIL_BYTES) return buffer.toString("utf8").trim();
|
|
74
|
+
let start = buffer.length - OUTPUT_TAIL_BYTES;
|
|
75
|
+
while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) start += 1;
|
|
76
|
+
return `…${buffer.subarray(start).toString("utf8").trim()}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Kills the command and everything it started. A test runner forks its own
|
|
80
|
+
// processes; killing only the shell would leave them running in the
|
|
81
|
+
// worktree, where the next git read or land would trip over them.
|
|
82
|
+
function killTree(child) {
|
|
83
|
+
if (!child.pid) return;
|
|
84
|
+
if (process.platform === "win32") {
|
|
85
|
+
try {
|
|
86
|
+
execFileSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
|
|
87
|
+
} catch {
|
|
88
|
+
child.kill();
|
|
89
|
+
}
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
process.kill(-child.pid, "SIGTERM");
|
|
94
|
+
} catch {
|
|
95
|
+
child.kill("SIGTERM");
|
|
96
|
+
}
|
|
97
|
+
setTimeout(() => {
|
|
98
|
+
try {
|
|
99
|
+
process.kill(-child.pid, "SIGKILL");
|
|
100
|
+
} catch {
|
|
101
|
+
// already gone
|
|
102
|
+
}
|
|
103
|
+
}, KILL_GRACE_MS).unref();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function runOne(command, { cwd, env, timeoutMs, onSpawn }) {
|
|
107
|
+
return new Promise((resolveRun) => {
|
|
108
|
+
const startedAt = Date.now();
|
|
109
|
+
const chunks = [];
|
|
110
|
+
let total = 0;
|
|
111
|
+
let child;
|
|
112
|
+
try {
|
|
113
|
+
// cmd.exe and the default POSIX sh report only the last pipeline stage.
|
|
114
|
+
// Use one explicit shell contract on every platform, including Windows
|
|
115
|
+
// installations where Git's Bash is not on a GUI client's PATH.
|
|
116
|
+
let bash = "/bin/bash";
|
|
117
|
+
if (process.platform === "win32") {
|
|
118
|
+
const git = findBinaryPath("git", { env });
|
|
119
|
+
const candidates = git ? [
|
|
120
|
+
join(dirname(git), "..", "bin", "bash.exe"),
|
|
121
|
+
join(dirname(git), "..", "usr", "bin", "bash.exe"),
|
|
122
|
+
join(dirname(git), "bash.exe")
|
|
123
|
+
] : [];
|
|
124
|
+
for (const root of [env.ProgramFiles, env["ProgramFiles(x86)"], env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Programs")].filter(Boolean)) {
|
|
125
|
+
candidates.push(join(root, "Git", "bin", "bash.exe"));
|
|
126
|
+
}
|
|
127
|
+
const onPath = findBinaryPath("bash", { env });
|
|
128
|
+
// Windows' System32/WindowsApps launchers start WSL, which cannot run
|
|
129
|
+
// the worker's Windows paths and toolchain under the same contract.
|
|
130
|
+
if (onPath && !/[\\/](?:System32|WindowsApps)[\\/]/i.test(onPath)) candidates.push(onPath);
|
|
131
|
+
bash = candidates.find((candidate) => existsSync(candidate));
|
|
132
|
+
if (!bash) throw new Error("acceptance requires Git for Windows Bash; install Git for Windows or add its bin directory to PATH");
|
|
133
|
+
} else if (!existsSync(bash)) {
|
|
134
|
+
bash = findBinaryPath("bash", { env });
|
|
135
|
+
if (!bash) throw new Error("acceptance requires Bash with pipefail; install Bash or add it to PATH");
|
|
136
|
+
}
|
|
137
|
+
const shellEnv = { ...env };
|
|
138
|
+
// Non-interactive Bash reads BASH_ENV even with --noprofile/--norc. A
|
|
139
|
+
// user's startup file must not switch off the acceptance failure flags.
|
|
140
|
+
delete shellEnv.BASH_ENV;
|
|
141
|
+
delete shellEnv.ENV;
|
|
142
|
+
child = spawn(bash, ["--noprofile", "--norc", "-e", "-o", "pipefail", "-s"], {
|
|
143
|
+
cwd,
|
|
144
|
+
env: shellEnv,
|
|
145
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
146
|
+
windowsHide: true,
|
|
147
|
+
detached: process.platform !== "win32"
|
|
148
|
+
});
|
|
149
|
+
} catch (error) {
|
|
150
|
+
resolveRun({ command, exit_code: null, signal: null, duration_ms: 0, timed_out: false, output_tail: `spawn failed: ${error.message}` });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const collect = (chunk) => {
|
|
154
|
+
// Keep the pipe drained; only the tail is kept.
|
|
155
|
+
chunks.push(chunk);
|
|
156
|
+
total += chunk.length;
|
|
157
|
+
while (total - chunks[0].length > OUTPUT_TAIL_BYTES && chunks.length > 1) total -= chunks.shift().length;
|
|
158
|
+
};
|
|
159
|
+
child.stdout.on("data", collect);
|
|
160
|
+
child.stderr.on("data", collect);
|
|
161
|
+
child.stdout.on("error", () => {});
|
|
162
|
+
child.stderr.on("error", () => {});
|
|
163
|
+
let timedOut = false;
|
|
164
|
+
let killed = false;
|
|
165
|
+
let spawnError = null;
|
|
166
|
+
let spawned = false;
|
|
167
|
+
const timer = setTimeout(() => {
|
|
168
|
+
if (killed) return;
|
|
169
|
+
timedOut = true;
|
|
170
|
+
killTree(child);
|
|
171
|
+
}, timeoutMs);
|
|
172
|
+
timer.unref();
|
|
173
|
+
const kill = () => {
|
|
174
|
+
killed = true;
|
|
175
|
+
if (spawned) killTree(child);
|
|
176
|
+
};
|
|
177
|
+
let finished = false;
|
|
178
|
+
const finish = (code, signal) => {
|
|
179
|
+
if (finished) return;
|
|
180
|
+
finished = true;
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
resolveRun({
|
|
183
|
+
command,
|
|
184
|
+
exit_code: code,
|
|
185
|
+
signal: signal ?? null,
|
|
186
|
+
duration_ms: Date.now() - startedAt,
|
|
187
|
+
timed_out: timedOut,
|
|
188
|
+
cancelled: killed && !timedOut,
|
|
189
|
+
output_tail: spawnError ? `spawn failed: ${spawnError.message}` : tail(Buffer.concat(chunks))
|
|
190
|
+
});
|
|
191
|
+
};
|
|
192
|
+
child.on("error", (error) => {
|
|
193
|
+
spawnError = error;
|
|
194
|
+
finish(null, null);
|
|
195
|
+
});
|
|
196
|
+
child.on("close", (code, signal) => finish(code, signal));
|
|
197
|
+
child.stdin.on("error", () => {});
|
|
198
|
+
child.once("spawn", () => {
|
|
199
|
+
spawned = true;
|
|
200
|
+
// The shell cannot create pipeline children until this process has
|
|
201
|
+
// registered cancellation. An immediate cancel closes its script input
|
|
202
|
+
// without ever launching the command, avoiding taskkill's startup race.
|
|
203
|
+
if (killed) child.stdin.end();
|
|
204
|
+
else child.stdin.end(`${command}\n`);
|
|
205
|
+
});
|
|
206
|
+
// Register close/error handlers before exposing cancellation. Cancelling
|
|
207
|
+
// before spawn is observed is remembered and applied at the spawn event.
|
|
208
|
+
onSpawn?.(kill);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Runs every command in order and returns the verdict. `control.kill` is
|
|
213
|
+
// filled in so a cancel can stop the command that is running; `control.isCancelled`
|
|
214
|
+
// is consulted between commands.
|
|
215
|
+
export async function runAcceptance(commands, { cwd, env = process.env, timeoutMs = DEFAULT_ACCEPTANCE_TIMEOUT_MS, run = null, taskId = null, baseCommit = null, control = {} } = {}) {
|
|
216
|
+
const startedAt = new Date().toISOString();
|
|
217
|
+
if (!cwd || !existsSync(cwd)) {
|
|
218
|
+
return { status: "failed", passed: false, run, started_at: startedAt, finished_at: new Date().toISOString(), error: "cwd_missing", cwd, checks: [] };
|
|
219
|
+
}
|
|
220
|
+
const checks = [];
|
|
221
|
+
let passed = true;
|
|
222
|
+
const checkEnv = {
|
|
223
|
+
...env,
|
|
224
|
+
NO_COLOR: "1",
|
|
225
|
+
CI: env.CI ?? "1",
|
|
226
|
+
CODEX_SUPERVISOR_TASK_ID: taskId ?? "",
|
|
227
|
+
CODEX_SUPERVISOR_BASE_COMMIT: baseCommit ?? "",
|
|
228
|
+
CODEX_SUPERVISOR_RUN: run == null ? "" : String(run)
|
|
229
|
+
};
|
|
230
|
+
for (const check of normalizeAcceptance(commands) ?? []) {
|
|
231
|
+
const command = typeof check === "string" ? check : check.command;
|
|
232
|
+
if (control.isCancelled?.()) {
|
|
233
|
+
return { status: "cancelled", passed: null, run, started_at: startedAt, finished_at: new Date().toISOString(), checks };
|
|
234
|
+
}
|
|
235
|
+
const checkId = randomUUID();
|
|
236
|
+
const result = await runOne(command, {
|
|
237
|
+
cwd,
|
|
238
|
+
env: { ...checkEnv, CODEX_SUPERVISOR_CHECK_ID: checkId },
|
|
239
|
+
timeoutMs,
|
|
240
|
+
onSpawn: (kill) => {
|
|
241
|
+
control.kill = kill;
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
control.kill = null;
|
|
245
|
+
result.passed = result.exit_code === 0 && !result.timed_out && !result.cancelled;
|
|
246
|
+
if (typeof check !== "string" && result.passed) Object.assign(result, await readCheckEvidence(check, cwd, checkId, baseCommit));
|
|
247
|
+
checks.push(result);
|
|
248
|
+
if (result.cancelled) {
|
|
249
|
+
return { status: "cancelled", passed: null, run, started_at: startedAt, finished_at: new Date().toISOString(), checks };
|
|
250
|
+
}
|
|
251
|
+
if (!result.passed) {
|
|
252
|
+
passed = false;
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return { status: passed ? "passed" : "failed", passed, run, started_at: startedAt, finished_at: new Date().toISOString(), checks };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// The one-word view for a status row: what the last run concluded.
|
|
260
|
+
export function acceptanceVerdict(task) {
|
|
261
|
+
const results = task?.acceptance_results;
|
|
262
|
+
if (!results) return null;
|
|
263
|
+
return results.status ?? null;
|
|
264
|
+
}
|
package/src/cleanup.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { rm,
|
|
3
|
-
import {
|
|
2
|
+
import { rm, lstat, realpath } from "node:fs/promises";
|
|
3
|
+
import { join, resolve, relative, isAbsolute } from "node:path";
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
4
5
|
import { deleteTasks, readTasks, vacuumStore } from "./task-store.js";
|
|
5
6
|
import { runsDir, worktreesDir } from "./paths.js";
|
|
6
|
-
import { TERMINAL_STATUSES } from "./status.js";
|
|
7
|
+
import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
|
|
7
8
|
|
|
8
9
|
function parseArgs(argv) {
|
|
9
10
|
const options = {
|
|
@@ -65,7 +66,10 @@ function isDeleteCandidate(task, cutoffMs, includeFailed) {
|
|
|
65
66
|
|
|
66
67
|
async function safeDeleteFile(path, dryRun) {
|
|
67
68
|
try {
|
|
68
|
-
await
|
|
69
|
+
const rel = relative(await realpath(runsDir), await realpath(path));
|
|
70
|
+
if (rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(rel)) return false;
|
|
71
|
+
const info = await lstat(path);
|
|
72
|
+
if (!info.isFile() || info.isSymbolicLink()) return false;
|
|
69
73
|
if (!dryRun) await rm(path, { force: true });
|
|
70
74
|
return true;
|
|
71
75
|
} catch {
|
|
@@ -73,13 +77,39 @@ async function safeDeleteFile(path, dryRun) {
|
|
|
73
77
|
}
|
|
74
78
|
}
|
|
75
79
|
|
|
76
|
-
|
|
80
|
+
function git(cwd, args) {
|
|
81
|
+
return execFileSync(process.env.GIT_BIN?.trim() || "git", ["--no-optional-locks", "-C", cwd, ...args], { encoding: "utf8", timeout: 15000, stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function cleanupReason(task, tasks) {
|
|
85
|
+
if (task.status !== "completed") return "unfinished, failed or lost work is preserved";
|
|
86
|
+
if (task.acceptance_results && task.acceptance_results.passed !== true) return "acceptance is not passed";
|
|
87
|
+
if (tasks.some((other) => ACTIVE_STATUSES.has(other.status) && (other.depends_on ?? []).includes(task.id))) return "active dependent still needs this worktree";
|
|
88
|
+
if (!task.worktree_path || !task.project_root) return "no registered isolated worktree";
|
|
77
89
|
try {
|
|
78
|
-
|
|
79
|
-
if (
|
|
80
|
-
return
|
|
81
|
-
|
|
82
|
-
|
|
90
|
+
const path = resolve(task.worktree_path);
|
|
91
|
+
if (path !== resolve(worktreesDir, task.id)) return "worktree is outside its managed task directory";
|
|
92
|
+
if ((await lstat(path)).isSymbolicLink()) return "symlink worktree is preserved";
|
|
93
|
+
if (await realpath(path) !== await realpath(resolve(worktreesDir, task.id))) return "unexpected worktree path";
|
|
94
|
+
const branch = git(path, ["symbolic-ref", "--short", "HEAD"]);
|
|
95
|
+
if (branch !== `codex/${task.id}`) return "unexpected branch ownership";
|
|
96
|
+
const registrations = git(task.project_root, ["worktree", "list", "--porcelain", "-z"]).split("\0").filter((line) => line.startsWith("worktree "));
|
|
97
|
+
let registered = false;
|
|
98
|
+
for (const line of registrations) {
|
|
99
|
+
if (await realpath(line.slice(9)) === await realpath(path)) registered = true;
|
|
100
|
+
}
|
|
101
|
+
if (!registered) return "worktree registration is missing";
|
|
102
|
+
if (git(path, ["status", "--porcelain", "--untracked-files=all"])) return "dirty worktree contains uncommitted files";
|
|
103
|
+
if (git(path, ["ls-files", "--others", "--ignored", "--exclude-standard"])) return "ignored artifacts are preserved";
|
|
104
|
+
if (task.attention_reason) return `unresolved attention: ${task.attention_reason}`;
|
|
105
|
+
if (task.externalOutputs?.length || task.run_evidence?.external_outputs?.length) return "shared output evidence is preserved";
|
|
106
|
+
if (!task.landed_at || !task.base_commit) return "unlanded work is preserved";
|
|
107
|
+
// Patch equivalence covers cherry-pick landing even when ancestry differs.
|
|
108
|
+
const remaining = git(path, ["cherry", task.project_root ? git(task.project_root, ["rev-parse", "HEAD"]) : "HEAD", "HEAD", task.base_commit]);
|
|
109
|
+
if (remaining.split("\n").some((line) => line.startsWith("+"))) return "unlanded commits remain";
|
|
110
|
+
return null;
|
|
111
|
+
} catch (error) {
|
|
112
|
+
return `cleanup proof failed: ${error.message.split("\n")[0]}`;
|
|
83
113
|
}
|
|
84
114
|
}
|
|
85
115
|
|
|
@@ -91,29 +121,45 @@ if (options.help) {
|
|
|
91
121
|
|
|
92
122
|
const cutoffMs = Date.now() - options.days * 24 * 60 * 60 * 1000;
|
|
93
123
|
const tasks = await readTasks();
|
|
94
|
-
const candidates =
|
|
124
|
+
const candidates = [];
|
|
125
|
+
const skipped = [];
|
|
126
|
+
for (const task of tasks.filter((item) => isDeleteCandidate(item, cutoffMs, options.includeFailed))) {
|
|
127
|
+
const reason = await cleanupReason(task, tasks);
|
|
128
|
+
if (reason) skipped.push({ id: task.id, reason });
|
|
129
|
+
else candidates.push(task);
|
|
130
|
+
}
|
|
95
131
|
const taskIds = candidates.map((task) => task.id);
|
|
96
132
|
|
|
97
133
|
const deleted = {
|
|
98
|
-
tasks:
|
|
134
|
+
tasks: 0,
|
|
99
135
|
jsonl: 0,
|
|
100
136
|
worktrees: 0
|
|
101
137
|
};
|
|
102
138
|
|
|
139
|
+
const removedIds = [];
|
|
103
140
|
for (const task of candidates) {
|
|
141
|
+
if (!options.dryRun) {
|
|
142
|
+
const current = (await readTasks()).find((item) => item.id === task.id);
|
|
143
|
+
const reason = current ? await cleanupReason(current, await readTasks()) : "task disappeared";
|
|
144
|
+
if (reason) { skipped.push({ id: task.id, reason }); continue; }
|
|
145
|
+
try {
|
|
146
|
+
git(task.project_root, ["worktree", "remove", task.worktree_path]);
|
|
147
|
+
git(task.project_root, ["branch", "-D", `codex/${task.id}`]);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
skipped.push({ id: task.id, reason: `git cleanup failed: ${error.message.split("\n")[0]}` });
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
deleted.worktrees += 1;
|
|
104
154
|
const logPath = task.run_log ?? join(runsDir, `${task.id}.jsonl`);
|
|
105
155
|
if (await safeDeleteFile(logPath, options.dryRun)) deleted.jsonl += 1;
|
|
106
|
-
|
|
107
|
-
if (await safeDeleteDir(task.worktree_path, options.dryRun)) deleted.worktrees += 1;
|
|
108
|
-
} else {
|
|
109
|
-
const fallbackWorktree = join(worktreesDir, task.id);
|
|
110
|
-
if (await safeDeleteDir(fallbackWorktree, options.dryRun)) deleted.worktrees += 1;
|
|
111
|
-
}
|
|
156
|
+
removedIds.push(task.id);
|
|
112
157
|
}
|
|
113
158
|
|
|
114
159
|
if (!options.dryRun && taskIds.length > 0) {
|
|
115
|
-
await deleteTasks(
|
|
160
|
+
await deleteTasks(removedIds);
|
|
116
161
|
}
|
|
162
|
+
deleted.tasks = removedIds.length;
|
|
117
163
|
|
|
118
164
|
if (!options.dryRun && options.vacuum) {
|
|
119
165
|
await vacuumStore();
|
|
@@ -124,5 +170,6 @@ console.log(JSON.stringify({
|
|
|
124
170
|
keep_days: options.days,
|
|
125
171
|
cutoff: new Date(cutoffMs).toISOString(),
|
|
126
172
|
candidates: taskIds,
|
|
173
|
+
skipped,
|
|
127
174
|
deleted
|
|
128
175
|
}, null, 2));
|