codex-supervisor-mcp 0.7.3 → 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 +51 -17
- package/README.md +51 -17
- package/package.json +10 -1
- package/skills/codex-supervisor/SKILL.md +43 -11
- package/src/acceptance-baseline.js +64 -0
- package/src/acceptance.js +264 -0
- package/src/cleanup.js +66 -19
- package/src/codex-runner.js +410 -31
- package/src/event-parser.js +68 -10
- package/src/external-output.js +29 -0
- package/src/goal-store.js +10 -7
- package/src/handoff.js +31 -0
- package/src/landing.js +247 -5
- package/src/mcp-server.js +326 -40
- package/src/owned-changes.js +27 -0
- package/src/prompt.js +80 -7
- package/src/status.js +1 -1
- package/src/task-store.js +195 -9
- package/src/tool-guard.js +66 -0
- package/src/truncate.js +13 -0
- package/src/web-app.js +4 -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 +53 -1
- package/web/dist/assets/{index-CqG_XY9n.js → index-fJQbspTY.js} +1 -1
- package/web/dist/index.html +1 -1
package/src/event-parser.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// Invariant: status is the lifecycle and is only ever assigned queued /
|
|
4
4
|
// running / completed / failed / cancelled / lost. Progress details go to
|
|
5
5
|
// phase, which is only meaningful while the work is running.
|
|
6
|
+
import { parseWorkerReport } from "./worker-report.js";
|
|
6
7
|
|
|
7
8
|
function getEventType(event) {
|
|
8
9
|
return event.type ?? event.event ?? event.msg?.type ?? "unknown";
|
|
@@ -17,7 +18,9 @@ function inferCommand(item) {
|
|
|
17
18
|
}
|
|
18
19
|
|
|
19
20
|
function inferAgentMessage(item) {
|
|
20
|
-
|
|
21
|
+
const raw = item?.text ?? item?.message ?? item?.content ?? item?.output_text ?? null;
|
|
22
|
+
const parsed = parseWorkerReport(raw);
|
|
23
|
+
return parsed.valid ? parsed.report.result : raw;
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
// The stored event stream is raw Codex JSONL, so reading a worker's own report
|
|
@@ -125,15 +128,17 @@ export function applyCodexEvent(task, event) {
|
|
|
125
128
|
const command = inferCommand(item);
|
|
126
129
|
next.phase = "command";
|
|
127
130
|
next.current_command = null;
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
131
|
+
const exitCode = item?.exit_code ?? item?.exitCode ?? null;
|
|
132
|
+
const status = item?.status ?? "completed";
|
|
133
|
+
const entry = { command, exit_code: exitCode, status, completed_at: now };
|
|
134
|
+
// The tail of a failing command's output is the one piece of evidence
|
|
135
|
+
// a reviewer needs to tell "the build is broken" from "the network was
|
|
136
|
+
// down". Only failures keep it: the commands column is one row cell.
|
|
137
|
+
if (commandFailed(entry)) {
|
|
138
|
+
const tail = outputTail(item?.aggregated_output ?? item?.output ?? null);
|
|
139
|
+
if (tail) entry.output_tail = tail;
|
|
140
|
+
}
|
|
141
|
+
next.commands = [...(next.commands ?? []), entry];
|
|
137
142
|
return next;
|
|
138
143
|
}
|
|
139
144
|
if (itemType === "file_change") {
|
|
@@ -204,3 +209,56 @@ function errorText(value) {
|
|
|
204
209
|
}
|
|
205
210
|
return String(value);
|
|
206
211
|
}
|
|
212
|
+
|
|
213
|
+
const OUTPUT_TAIL_BYTES = 300;
|
|
214
|
+
|
|
215
|
+
function outputTail(output) {
|
|
216
|
+
if (typeof output !== "string" || !output) return null;
|
|
217
|
+
const buf = Buffer.from(output, "utf8");
|
|
218
|
+
if (buf.length <= OUTPUT_TAIL_BYTES) return output.trim() || null;
|
|
219
|
+
// Cut on a character boundary: drop bytes until the slice decodes cleanly.
|
|
220
|
+
let start = buf.length - OUTPUT_TAIL_BYTES;
|
|
221
|
+
while (start < buf.length && (buf[start] & 0xc0) === 0x80) start += 1;
|
|
222
|
+
return `…${buf.subarray(start).toString("utf8").trim()}`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// A sandbox-refused command can come back with no exit code at all, only a
|
|
226
|
+
// failed status, so both are failure.
|
|
227
|
+
export function commandFailed(entry) {
|
|
228
|
+
if (!entry) return false;
|
|
229
|
+
if (entry.status === "failed") return true;
|
|
230
|
+
return entry.exit_code !== null && entry.exit_code !== undefined && entry.exit_code !== 0;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function clipText(value, max) {
|
|
234
|
+
const text = String(value ?? "");
|
|
235
|
+
return text.length > max ? `${text.slice(0, max)}…` : text;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// What the worker actually ran, condensed for a reviewer to hold its report
|
|
239
|
+
// against: a worker that says "tests pass" with commands_run 0, or that ends
|
|
240
|
+
// on a failing command and calls the work done, is caught here without
|
|
241
|
+
// reading the event stream. The commands list accumulates across resumes,
|
|
242
|
+
// so runs says how many turns it covers.
|
|
243
|
+
export function summarizeVerification(task, { limit = 10, clip = 160 } = {}) {
|
|
244
|
+
const commands = Array.isArray(task?.commands) ? task.commands : [];
|
|
245
|
+
const failed = commands.filter(commandFailed);
|
|
246
|
+
const last = commands[commands.length - 1] ?? null;
|
|
247
|
+
return {
|
|
248
|
+
runs: task?.run_count ?? 0,
|
|
249
|
+
commands_run: commands.length,
|
|
250
|
+
failed_count: failed.length,
|
|
251
|
+
last_exit_code: last ? (last.exit_code ?? null) : null,
|
|
252
|
+
last_command_failed: commandFailed(last),
|
|
253
|
+
failed: failed.slice(-limit).map((entry) => ({
|
|
254
|
+
command: clipText(entry.command, clip),
|
|
255
|
+
exit_code: entry.exit_code ?? null,
|
|
256
|
+
output_tail: entry.output_tail ?? null
|
|
257
|
+
})),
|
|
258
|
+
last: commands.slice(-limit).map((entry) => ({
|
|
259
|
+
command: clipText(entry.command, clip),
|
|
260
|
+
exit_code: entry.exit_code ?? null,
|
|
261
|
+
failed: commandFailed(entry)
|
|
262
|
+
}))
|
|
263
|
+
};
|
|
264
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, dirname } from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
export async function captureExternalOutputs(declarations, { checkBaseline = false } = {}) {
|
|
6
|
+
if (!Array.isArray(declarations) || declarations.length > 20) throw new Error("externalOutputs must contain at most 20 files");
|
|
7
|
+
const captured = [];
|
|
8
|
+
for (const entry of declarations) {
|
|
9
|
+
if (!entry || !isAbsolute(entry.path)) throw new Error("externalOutputs must use absolute file paths");
|
|
10
|
+
let info;
|
|
11
|
+
try { info = await lstat(entry.path); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
12
|
+
let snapshot = { path: entry.path, exists: false, sha256: null, content: null, truncated: false };
|
|
13
|
+
if (info) {
|
|
14
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 1_000_000) throw new Error("external output must be a regular file of at most 1 MB");
|
|
15
|
+
const bytes = await readFile(entry.path);
|
|
16
|
+
snapshot = { ...snapshot, exists: true, canonical_path: await realpath(entry.path), sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
17
|
+
content: bytes.includes(0) ? null : bytes.subarray(0, 3000).toString("utf8"), truncated: bytes.length > 3000 };
|
|
18
|
+
} else { snapshot.canonical_parent = await realpath(dirname(entry.path)); }
|
|
19
|
+
if (checkBaseline && entry.sha256 && snapshot.sha256 !== entry.sha256) throw new Error(`external output baseline changed: ${entry.path}`);
|
|
20
|
+
captured.push(snapshot);
|
|
21
|
+
}
|
|
22
|
+
return captured;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function compareExternalOutputs(before, after) {
|
|
26
|
+
return before.map((old, index) => ({ path: old.path, before: old, after: after[index],
|
|
27
|
+
changed: old.exists !== after[index]?.exists || old.sha256 !== after[index]?.sha256,
|
|
28
|
+
integration: "shared_file_already_written_not_cherry_pick" }));
|
|
29
|
+
}
|
package/src/goal-store.js
CHANGED
|
@@ -13,8 +13,9 @@ function toCamelCase(status) {
|
|
|
13
13
|
return String(status).replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
export function
|
|
17
|
-
if (!threadId
|
|
16
|
+
export function readNativeGoalState(threadId) {
|
|
17
|
+
if (!threadId) return { state: "no_thread", goal: null };
|
|
18
|
+
if (!existsSync(goalsDbPath)) return { state: "missing_database", goal: null };
|
|
18
19
|
let db;
|
|
19
20
|
try {
|
|
20
21
|
db = new DatabaseSync(goalsDbPath, { readOnly: true });
|
|
@@ -25,8 +26,8 @@ export function readNativeGoal(threadId) {
|
|
|
25
26
|
FROM thread_goals
|
|
26
27
|
WHERE thread_id = ?
|
|
27
28
|
`).get(threadId);
|
|
28
|
-
if (!row) return null;
|
|
29
|
-
return {
|
|
29
|
+
if (!row) return { state: "missing_goal", goal: null };
|
|
30
|
+
return { state: "available", goal: {
|
|
30
31
|
objective: row.objective,
|
|
31
32
|
status: toCamelCase(row.status),
|
|
32
33
|
storage_status: row.status,
|
|
@@ -36,11 +37,11 @@ export function readNativeGoal(threadId) {
|
|
|
36
37
|
time_used_seconds: row.time_used_seconds ?? 0,
|
|
37
38
|
created_at: row.created_at_ms ? new Date(row.created_at_ms).toISOString() : null,
|
|
38
39
|
updated_at: row.updated_at_ms ? new Date(row.updated_at_ms).toISOString() : null
|
|
39
|
-
};
|
|
40
|
-
} catch {
|
|
40
|
+
} };
|
|
41
|
+
} catch (error) {
|
|
41
42
|
// A locked or half-migrated Codex database must never break a supervisor
|
|
42
43
|
// call; the supervisor goal is still returned by the caller.
|
|
43
|
-
return null;
|
|
44
|
+
return { state: /locked|busy/i.test(error.message) ? "locked" : "read_error", goal: null, error: error.message };
|
|
44
45
|
} finally {
|
|
45
46
|
try {
|
|
46
47
|
db?.close();
|
|
@@ -49,3 +50,5 @@ export function readNativeGoal(threadId) {
|
|
|
49
50
|
}
|
|
50
51
|
}
|
|
51
52
|
}
|
|
53
|
+
|
|
54
|
+
export function readNativeGoal(threadId) { return readNativeGoalState(threadId).goal; }
|
package/src/handoff.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFile, lstat } from "node:fs/promises";
|
|
3
|
+
import { isAbsolute } from "node:path";
|
|
4
|
+
|
|
5
|
+
export async function buildHandoff({ goal, todo, peers = [], contracts = [], context = [] }, { maxLines = 16, maxChars = 1800 } = {}) {
|
|
6
|
+
if (!Array.isArray(context) || context.length > 20 || !Array.isArray(contracts)
|
|
7
|
+
|| contracts.some((value) => typeof value !== "string") || JSON.stringify({ context, contracts }).length > 6000) throw new Error("context and contracts exceed the 6000 character input budget");
|
|
8
|
+
const refs = [];
|
|
9
|
+
for (const entry of context) {
|
|
10
|
+
if (!entry || !isAbsolute(entry.path)) throw new Error("context paths must be absolute");
|
|
11
|
+
const info = await lstat(entry.path);
|
|
12
|
+
if (!info.isFile() || info.size > 5_000_000) throw new Error("context source must be a regular file of at most 5 MB");
|
|
13
|
+
const sha256 = createHash("sha256").update(await readFile(entry.path)).digest("hex");
|
|
14
|
+
if (entry.sha256 && entry.sha256 !== sha256) throw new Error(`context source changed: ${entry.path}`);
|
|
15
|
+
refs.push({ path: entry.path, sha256 });
|
|
16
|
+
}
|
|
17
|
+
const line = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
|
|
18
|
+
const candidates = ["Handoff (source refs are inputs, not write permission):", `Goal: ${line(goal)}`, `Todo: ${line(todo)}`,
|
|
19
|
+
...refs.map((ref) => `Input: ${ref.path} sha256=${ref.sha256}`),
|
|
20
|
+
...contracts.map((value) => `Contract: ${line(value)}`),
|
|
21
|
+
...peers.map((peer) => `Peer: ${line(peer.title)} | ${line(peer.status)} | ${line(peer.last_message).slice(0, 160)}`)];
|
|
22
|
+
const marker = "[handoff truncated; required task/guard/acceptance follow separately]";
|
|
23
|
+
const lines = []; let size = 0;
|
|
24
|
+
for (const candidate of candidates) {
|
|
25
|
+
if (lines.length >= maxLines - 1 || size + candidate.length + 1 > maxChars - marker.length - 1) break;
|
|
26
|
+
lines.push(candidate); size += candidate.length + 1;
|
|
27
|
+
}
|
|
28
|
+
const truncated = lines.length !== candidates.length;
|
|
29
|
+
if (truncated) lines.push(marker);
|
|
30
|
+
return { text: lines.join("\n"), truncated, source_refs: refs };
|
|
31
|
+
}
|
package/src/landing.js
CHANGED
|
@@ -7,8 +7,10 @@
|
|
|
7
7
|
// the target must be clean, it is never switched to another branch, and a
|
|
8
8
|
// conflict leaves nothing half-applied.
|
|
9
9
|
import { execFileSync } from "node:child_process";
|
|
10
|
-
import { existsSync } from "node:fs";
|
|
11
|
-
import {
|
|
10
|
+
import { existsSync, rmSync } from "node:fs";
|
|
11
|
+
import { join, relative } from "node:path";
|
|
12
|
+
import { parsePorcelainLine, resolveWorktreeBase, worktreeRef, readWorktreeChanges, readWorktreeDiff } from "./worktree.js";
|
|
13
|
+
import { findOutsideOwnedChanges } from "./owned-changes.js";
|
|
12
14
|
|
|
13
15
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
14
16
|
|
|
@@ -19,7 +21,7 @@ const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
|
19
21
|
// directory. An identity git already has is used untouched.
|
|
20
22
|
const FALLBACK_IDENTITY = { name: "codex-supervisor", email: "codex-supervisor@localhost" };
|
|
21
23
|
const identityCache = new Map();
|
|
22
|
-
function identityEnv(cwd) {
|
|
24
|
+
export function identityEnv(cwd) {
|
|
23
25
|
if (identityCache.has(cwd)) return identityCache.get(cwd);
|
|
24
26
|
let name = "";
|
|
25
27
|
let email = "";
|
|
@@ -79,8 +81,28 @@ function currentBranch(cwd) {
|
|
|
79
81
|
//
|
|
80
82
|
// Returns { landed: [{ sha, original, subject }], onto, head } on success;
|
|
81
83
|
// otherwise { error, reason, ... } with nothing changed in the target.
|
|
82
|
-
export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
84
|
+
export function landWorker(task, { onto = null, commitMessage = null, ignoreAcceptance = false, allowOutsideOwned = false } = {}) {
|
|
83
85
|
const target = task.project_root;
|
|
86
|
+
// The dispatcher's own checks are the gate. A failed run is refused until
|
|
87
|
+
// it passes; a run that was cut short is refused until it has run.
|
|
88
|
+
const acceptance = task.acceptance_results ?? null;
|
|
89
|
+
if (!ignoreAcceptance && acceptance) {
|
|
90
|
+
const failing = (acceptance.checks ?? []).find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out) ?? null;
|
|
91
|
+
if (acceptance.passed === false) {
|
|
92
|
+
return {
|
|
93
|
+
error: "acceptance_failed",
|
|
94
|
+
reason: `the worker's acceptance run failed${failing ? ` on "${failing.command.slice(0, 120)}" (exit ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code)})` : acceptance.error ? ` (${acceptance.error})` : ""}; resume the worker with the failing output and land once it passes. ignoreAcceptance: true lands anyway, only when the user said to.`,
|
|
95
|
+
acceptance: { status: acceptance.status, passed: false, checks: acceptance.checks ?? [], error: acceptance.error ?? null }
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
if (acceptance.status === "running" || acceptance.status === "interrupted" || acceptance.status === "cancelled") {
|
|
99
|
+
return {
|
|
100
|
+
error: "acceptance_not_run",
|
|
101
|
+
reason: `the worker's acceptance is ${acceptance.status}; wait for it (or resume the worker to run it again) before landing. ignoreAcceptance: true lands anyway, only when the user said to.`,
|
|
102
|
+
acceptance: { status: acceptance.status, passed: null }
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
84
106
|
if (!task.worktree_path || !existsSync(task.worktree_path)) {
|
|
85
107
|
return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing on a codex/ branch to land" };
|
|
86
108
|
}
|
|
@@ -104,6 +126,14 @@ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
|
104
126
|
|
|
105
127
|
const base = resolveWorktreeBase(task.worktree_path, worktreeRef(task));
|
|
106
128
|
if (!base) return { error: "no_base_commit", reason: "the commit this worker started from is unknown, so its commits cannot be told apart" };
|
|
129
|
+
if (!allowOutsideOwned) {
|
|
130
|
+
const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 0 });
|
|
131
|
+
if (diff.error) return { error: "ownership_unverified", reason: "cannot prove the complete diff before landing", diff_error: diff.error };
|
|
132
|
+
const paths = [...readWorktreeChanges(task.worktree_path, worktreeRef(task)),
|
|
133
|
+
...diff.files.flatMap((file) => [file.path, file.from].filter(Boolean).map((path) => join(task.worktree_path, path)))];
|
|
134
|
+
const { outside } = findOutsideOwnedChanges(task, [...new Set(paths)]);
|
|
135
|
+
if (outside.length) return { error: "outside_owned_paths", reason: "worker changes exceed declared ownedPaths; review them and obtain explicit authorization before allowing an exception", outside_paths: outside.map((entry) => relative(task.worktree_path, entry)) };
|
|
136
|
+
}
|
|
107
137
|
let commits;
|
|
108
138
|
try {
|
|
109
139
|
commits = lines(git(task.worktree_path, ["rev-list", "--reverse", `${base}..HEAD`]));
|
|
@@ -124,6 +154,30 @@ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
|
124
154
|
commits.push(committedForWorker);
|
|
125
155
|
uncommitted = [];
|
|
126
156
|
}
|
|
157
|
+
// Commits whose patch is already on the target (a previous land, or the
|
|
158
|
+
// main thread cherry-picked by hand) are skipped by patch id; picking
|
|
159
|
+
// them again produces an empty commit and git stops with an error.
|
|
160
|
+
const targetHead = git(target, ["rev-parse", "HEAD"]).trim();
|
|
161
|
+
let alreadyLanded = [];
|
|
162
|
+
if (commits.length > 0) {
|
|
163
|
+
try {
|
|
164
|
+
const workerHead = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
|
|
165
|
+
const pending = new Set(lines(git(target, ["rev-list", "--cherry-pick", "--right-only", `${targetHead}...${workerHead}`])));
|
|
166
|
+
alreadyLanded = commits.filter((sha) => !pending.has(sha));
|
|
167
|
+
commits = commits.filter((sha) => pending.has(sha));
|
|
168
|
+
} catch {
|
|
169
|
+
// comparison failed; try to land everything and let the pick decide
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (commits.length === 0 && alreadyLanded.length > 0) {
|
|
173
|
+
return {
|
|
174
|
+
error: "nothing_to_land",
|
|
175
|
+
reason: `every commit on this worker's branch is already on ${branch} (landed before, by patch); nothing new to land`,
|
|
176
|
+
already_landed: alreadyLanded,
|
|
177
|
+
uncommitted,
|
|
178
|
+
base_commit: base
|
|
179
|
+
};
|
|
180
|
+
}
|
|
127
181
|
if (commits.length === 0) {
|
|
128
182
|
return {
|
|
129
183
|
error: "nothing_to_land",
|
|
@@ -135,7 +189,7 @@ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
|
135
189
|
};
|
|
136
190
|
}
|
|
137
191
|
|
|
138
|
-
const before =
|
|
192
|
+
const before = targetHead;
|
|
139
193
|
try {
|
|
140
194
|
git(target, ["cherry-pick", "--allow-empty-message", ...commits], { timeout: 10 * 60 * 1000 });
|
|
141
195
|
} catch (error) {
|
|
@@ -170,7 +224,195 @@ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
|
170
224
|
base_commit: base,
|
|
171
225
|
head: landed.at(-1) ?? before,
|
|
172
226
|
landed: landed.map((sha, index) => ({ sha, original: commits[index] ?? null, subject: subjectOf.get(sha) ?? null })),
|
|
227
|
+
already_landed: alreadyLanded,
|
|
173
228
|
committed_for_worker: committedForWorker,
|
|
174
229
|
uncommitted
|
|
175
230
|
};
|
|
176
231
|
}
|
|
232
|
+
|
|
233
|
+
function gitTail(error) {
|
|
234
|
+
return `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-4).join("\n") || error.message.split("\n")[0];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function conflictFiles(cwd) {
|
|
238
|
+
try {
|
|
239
|
+
return lines(git(cwd, ["diff", "--name-only", "--diff-filter=U"]));
|
|
240
|
+
} catch {
|
|
241
|
+
return [];
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function stashRef(cwd) {
|
|
246
|
+
try {
|
|
247
|
+
return git(cwd, ["rev-parse", "-q", "--verify", "refs/stash"]).trim() || null;
|
|
248
|
+
} catch {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function operationInProgress(cwd) {
|
|
254
|
+
for (const marker of ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", "MERGE_HEAD"]) {
|
|
255
|
+
try {
|
|
256
|
+
const path = git(cwd, ["rev-parse", "--git-path", marker]).trim();
|
|
257
|
+
if (path && existsSync(path.startsWith("/") || /^[A-Za-z]:/.test(path) ? path : join(cwd, path))) return marker;
|
|
258
|
+
} catch {
|
|
259
|
+
// not a repo; the caller reports that
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Moves a worker's worktree onto a newer commit of the project before the
|
|
266
|
+
// worker is resumed. The worktree was cut from base_commit when the worker
|
|
267
|
+
// was dispatched; by the time it is sent back for a fix the project's branch
|
|
268
|
+
// has often moved on, and a worker that keeps editing the old base does
|
|
269
|
+
// work that cannot land.
|
|
270
|
+
//
|
|
271
|
+
// Exactly the worker's own commits are replayed: `git rebase --onto <onto>
|
|
272
|
+
// <base>`, never a plain rebase, whose merge-base start would also replay
|
|
273
|
+
// the project's own commits when the base was rewritten. Edits the worker
|
|
274
|
+
// left uncommitted (every workspace-write worker: the sandbox keeps .git
|
|
275
|
+
// read-only) are stashed around the rebase, untracked files included.
|
|
276
|
+
//
|
|
277
|
+
// Nothing is left half done. A conflict in the replay aborts the rebase; a
|
|
278
|
+
// conflict when the stash comes back resets the branch to where it was and
|
|
279
|
+
// pops the stash there, which cannot conflict. Either way the worktree is as
|
|
280
|
+
// it was and the caller gets the file list.
|
|
281
|
+
//
|
|
282
|
+
// Returns { ok: true, noop: true, base_commit, head } when onto is already in
|
|
283
|
+
// the branch's history, { ok: true, base_commit: onto, head, replayed,
|
|
284
|
+
// stashed } after a real rebase, or { error, reason, files?, git?,
|
|
285
|
+
// base_commit, head } with nothing changed.
|
|
286
|
+
export function rebaseWorktree(task, ontoCommit) {
|
|
287
|
+
const cwd = task.worktree_path;
|
|
288
|
+
if (!cwd || !existsSync(cwd)) {
|
|
289
|
+
return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing to rebase" };
|
|
290
|
+
}
|
|
291
|
+
const base = resolveWorktreeBase(cwd, worktreeRef(task));
|
|
292
|
+
if (!base) return { error: "no_base_commit", reason: "the commit this worker started from is unknown, so its own commits cannot be told apart for the replay" };
|
|
293
|
+
const inProgress = operationInProgress(cwd);
|
|
294
|
+
if (inProgress) {
|
|
295
|
+
return { error: "rebase_in_progress", reason: `${cwd} has a ${inProgress} in progress; finish or abort it first`, base_commit: base };
|
|
296
|
+
}
|
|
297
|
+
let head;
|
|
298
|
+
try {
|
|
299
|
+
head = git(cwd, ["rev-parse", "HEAD"]).trim();
|
|
300
|
+
} catch (error) {
|
|
301
|
+
return { error: "no_worktree", reason: `${cwd} has no resolvable HEAD: ${gitTail(error)}`, base_commit: base };
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
git(cwd, ["merge-base", "--is-ancestor", ontoCommit, "HEAD"]);
|
|
305
|
+
// onto is already behind or at this branch: a rebase would move the
|
|
306
|
+
// worker's commits backwards. Nothing to do and base stays.
|
|
307
|
+
return { ok: true, noop: true, base_commit: base, head };
|
|
308
|
+
} catch (error) {
|
|
309
|
+
if (error.status !== 1) {
|
|
310
|
+
return { error: "rebase_failed", reason: `could not compare ${ontoCommit} with HEAD: ${gitTail(error)}`, git: gitTail(error), base_commit: base, head };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
let pending;
|
|
315
|
+
let alreadyLanded;
|
|
316
|
+
try {
|
|
317
|
+
const commits = lines(git(cwd, ["rev-list", "--reverse", `${base}..HEAD`]));
|
|
318
|
+
const newPatches = new Set(lines(git(cwd, ["cherry", ontoCommit, "HEAD", base]))
|
|
319
|
+
.filter((line) => line.startsWith("+ ")).map((line) => line.slice(2)));
|
|
320
|
+
pending = commits.filter((sha) => newPatches.has(sha));
|
|
321
|
+
alreadyLanded = commits.filter((sha) => !newPatches.has(sha));
|
|
322
|
+
} catch (error) {
|
|
323
|
+
return { error: "rebase_failed", reason: `could not prove which worker patches are already integrated: ${gitTail(error)}`, base_commit: base, head };
|
|
324
|
+
}
|
|
325
|
+
const stashBefore = stashRef(cwd);
|
|
326
|
+
let stashed = false;
|
|
327
|
+
try {
|
|
328
|
+
git(cwd, ["stash", "push", "--include-untracked", "-q", "-m", "codex-supervisor: rebase"]);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
return { error: "rebase_failed", reason: `could not stash the worker's uncommitted edits: ${gitTail(error)}`, git: gitTail(error), base_commit: base, head };
|
|
331
|
+
}
|
|
332
|
+
// "No local changes to save" also exits 0, so the stash ref decides.
|
|
333
|
+
stashed = stashRef(cwd) !== stashBefore;
|
|
334
|
+
|
|
335
|
+
// A pop that fails has already written the stash's untracked files back
|
|
336
|
+
// into the worktree, and reset --hard does not touch untracked files, so
|
|
337
|
+
// the next pop would stop on "already exists". Those files are the
|
|
338
|
+
// stash's third parent; they are removed before the pop that restores
|
|
339
|
+
// them for good.
|
|
340
|
+
const removeStashedUntracked = () => {
|
|
341
|
+
let paths = [];
|
|
342
|
+
try {
|
|
343
|
+
paths = lines(git(cwd, ["ls-tree", "-r", "--name-only", "refs/stash^3"]));
|
|
344
|
+
} catch {
|
|
345
|
+
return; // the stash carries no untracked files
|
|
346
|
+
}
|
|
347
|
+
for (const path of paths) rmSync(join(cwd, path), { force: true });
|
|
348
|
+
};
|
|
349
|
+
const restoreStash = () => {
|
|
350
|
+
if (!stashed) return null;
|
|
351
|
+
try {
|
|
352
|
+
removeStashedUntracked();
|
|
353
|
+
git(cwd, ["stash", "pop", "-q"]);
|
|
354
|
+
return null;
|
|
355
|
+
} catch (error) {
|
|
356
|
+
return gitTail(error);
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
try {
|
|
361
|
+
// Rebase --onto can replay a patch previously cherry-picked to main and
|
|
362
|
+
// conflict with main's later edits. Rebuild only the proven new patches.
|
|
363
|
+
git(cwd, ["reset", "-q", "--hard", ontoCommit]);
|
|
364
|
+
if (pending.length) git(cwd, ["cherry-pick", ...pending], { timeout: 10 * 60 * 1000 });
|
|
365
|
+
} catch (error) {
|
|
366
|
+
const files = conflictFiles(cwd);
|
|
367
|
+
try {
|
|
368
|
+
git(cwd, ["cherry-pick", "--abort"]);
|
|
369
|
+
} catch {
|
|
370
|
+
// nothing in progress to abort
|
|
371
|
+
}
|
|
372
|
+
git(cwd, ["reset", "-q", "--hard", head]);
|
|
373
|
+
const popError = restoreStash();
|
|
374
|
+
return {
|
|
375
|
+
error: files.length > 0 ? "rebase_conflict" : "rebase_failed",
|
|
376
|
+
reason: files.length > 0
|
|
377
|
+
? `replaying the worker's commits onto ${ontoCommit.slice(0, 12)} hit a conflict; the worktree is back as it was${popError ? " (but its stash could not be restored: run git stash pop there)" : ""}`
|
|
378
|
+
: `the rebase failed; the worktree is back as it was${popError ? " (but its stash could not be restored: run git stash pop there)" : ""}`,
|
|
379
|
+
files,
|
|
380
|
+
git: gitTail(error),
|
|
381
|
+
base_commit: base,
|
|
382
|
+
head
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
const newHead = git(cwd, ["rev-parse", "HEAD"]).trim();
|
|
386
|
+
let replayed = 0;
|
|
387
|
+
try {
|
|
388
|
+
replayed = lines(git(cwd, ["rev-list", `${ontoCommit}..HEAD`])).length;
|
|
389
|
+
} catch {
|
|
390
|
+
// reported as 0
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
if (stashed) {
|
|
394
|
+
try {
|
|
395
|
+
git(cwd, ["stash", "pop", "-q"]);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
// The replay succeeded but the worker's uncommitted edits do not fit
|
|
398
|
+
// the new base. Back to the old base, where the same stash pops clean.
|
|
399
|
+
const files = conflictFiles(cwd);
|
|
400
|
+
const tail = gitTail(error);
|
|
401
|
+
try {
|
|
402
|
+
git(cwd, ["reset", "-q", "--hard", head]);
|
|
403
|
+
} catch {
|
|
404
|
+
// fall through; the stash is still there
|
|
405
|
+
}
|
|
406
|
+
const popError = restoreStash();
|
|
407
|
+
return {
|
|
408
|
+
error: "stash_conflict",
|
|
409
|
+
reason: `the worker's uncommitted edits conflict with ${ontoCommit.slice(0, 12)}; the worktree is back as it was${popError ? " (but its stash could not be restored: run git stash pop there)" : ""}. Commit them first (land_codex_worker with commitMessage) so the conflict is in a commit that can be resolved, or redispatch from the new commit with baseRef`,
|
|
410
|
+
files,
|
|
411
|
+
git: tail,
|
|
412
|
+
base_commit: base,
|
|
413
|
+
head
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return { ok: true, base_commit: ontoCommit, head: newHead, previous_head: head, replayed, already_landed: alreadyLanded, stashed };
|
|
418
|
+
}
|