codex-supervisor-mcp 0.7.2 → 0.8.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 +33 -29
- package/README.md +33 -29
- package/package.json +3 -2
- package/skills/codex-supervisor/SKILL.md +14 -7
- package/src/codex-runner.js +136 -15
- package/src/event-parser.js +64 -9
- package/src/landing.js +222 -4
- package/src/mcp-server.js +159 -26
- package/src/prompt.js +60 -7
- package/src/task-store.js +40 -2
- package/src/truncate.js +13 -0
- package/src/web-app.js +2 -0
- package/src/worktree.js +28 -0
- package/web/dist/assets/{index-CqG_XY9n.js → index-fJQbspTY.js} +1 -1
- package/web/dist/index.html +1 -1
package/src/codex-runner.js
CHANGED
|
@@ -13,13 +13,18 @@ import {
|
|
|
13
13
|
upsertTask
|
|
14
14
|
} from "./task-store.js";
|
|
15
15
|
import { applyCodexEvent } from "./event-parser.js";
|
|
16
|
-
import { TERMINAL_STATUSES } from "./status.js";
|
|
16
|
+
import { ACTIVE_STATUSES, TERMINAL_STATUSES } from "./status.js";
|
|
17
17
|
import { worktreesDir } from "./paths.js";
|
|
18
|
-
import {
|
|
18
|
+
import { frameWorkerPrompt } from "./prompt.js";
|
|
19
19
|
import { readTaskChanges } from "./worktree.js";
|
|
20
|
+
import { rebaseWorktree } from "./landing.js";
|
|
21
|
+
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance, runAcceptance } from "./acceptance.js";
|
|
22
|
+
import { appendFile } from "node:fs/promises";
|
|
20
23
|
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
21
24
|
|
|
22
25
|
const processes = new Map();
|
|
26
|
+
// taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
|
|
27
|
+
const acceptanceRuns = new Map();
|
|
23
28
|
const cancelledTasks = new Set();
|
|
24
29
|
const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
|
|
25
30
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
@@ -241,6 +246,10 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
|
|
|
241
246
|
error: null,
|
|
242
247
|
current_action: null,
|
|
243
248
|
current_command: null,
|
|
249
|
+
// A resumed row still carries the last event of the run that ended;
|
|
250
|
+
// idle time for this run counts from now.
|
|
251
|
+
last_event_at: now,
|
|
252
|
+
last_event_type: null,
|
|
244
253
|
run_count: (record.run_count ?? 0) + 1,
|
|
245
254
|
updated_at: now
|
|
246
255
|
};
|
|
@@ -352,7 +361,49 @@ async function startTrackedRun({ record, args, prompt, logPath, spawnOptions = {
|
|
|
352
361
|
next.error = `codex worker was killed by signal ${signal} before writing a terminal event`;
|
|
353
362
|
}
|
|
354
363
|
if (status === "cancelled") next.error = null;
|
|
355
|
-
|
|
364
|
+
|
|
365
|
+
// Acceptance runs after the worker is gone, in two writes. The first
|
|
366
|
+
// records the terminal status with exit_code still null and the run
|
|
367
|
+
// marked as this process's, so a wait keeps waiting and reconcile
|
|
368
|
+
// (which sees a dead codex pid) leaves the row alone; the second
|
|
369
|
+
// records exit_code and the verdict. changed_files is read before the
|
|
370
|
+
// checks run so build output they leave behind is not counted as the
|
|
371
|
+
// worker's.
|
|
372
|
+
const acceptance = Array.isArray(live.acceptance) && live.acceptance.length > 0 ? live.acceptance : null;
|
|
373
|
+
if (acceptance && (status === "completed" || status === "failed")) {
|
|
374
|
+
const control = { kill: null, cancelled: false, isCancelled: () => control.cancelled };
|
|
375
|
+
acceptanceRuns.set(record.id, control);
|
|
376
|
+
await persist({
|
|
377
|
+
...next,
|
|
378
|
+
exit_code: null,
|
|
379
|
+
signal: null,
|
|
380
|
+
current_action: "Running acceptance",
|
|
381
|
+
acceptance_results: { status: "running", passed: null, run: live.run_count, supervisor_pid: process.pid, started_at: finishedAt }
|
|
382
|
+
});
|
|
383
|
+
const results = await runAcceptance(acceptance, {
|
|
384
|
+
cwd: record.cwd,
|
|
385
|
+
timeoutMs: live.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS,
|
|
386
|
+
run: live.run_count,
|
|
387
|
+
control
|
|
388
|
+
});
|
|
389
|
+
acceptanceRuns.delete(record.id);
|
|
390
|
+
const event = { type: "supervisor.acceptance", ...results };
|
|
391
|
+
await appendTaskEvent(record.id, event).catch(() => {});
|
|
392
|
+
await appendFile(logPath, `${JSON.stringify(event)}\n`).catch(() => {});
|
|
393
|
+
const failing = results.checks.find((check) => check.exit_code !== 0);
|
|
394
|
+
await persist({
|
|
395
|
+
...next,
|
|
396
|
+
acceptance_results: results,
|
|
397
|
+
current_action: results.status === "passed"
|
|
398
|
+
? "Completed, acceptance passed"
|
|
399
|
+
: results.status === "failed"
|
|
400
|
+
? `Acceptance failed: ${failing ? `${failing.command.slice(0, 80)} exit ${failing.exit_code ?? (failing.timed_out ? "timeout" : "?")}` : results.error ?? "see acceptance_results"}`
|
|
401
|
+
: next.current_action,
|
|
402
|
+
updated_at: new Date().toISOString()
|
|
403
|
+
});
|
|
404
|
+
} else {
|
|
405
|
+
await persist(acceptance ? { ...next, acceptance_results: null } : next);
|
|
406
|
+
}
|
|
356
407
|
cancelledTasks.delete(record.id);
|
|
357
408
|
});
|
|
358
409
|
|
|
@@ -405,15 +456,18 @@ export async function createCodexWorker({
|
|
|
405
456
|
dependsOn = [],
|
|
406
457
|
followupOf = null,
|
|
407
458
|
useWorktree = true,
|
|
408
|
-
baseRef = null
|
|
459
|
+
baseRef = null,
|
|
460
|
+
acceptance = null,
|
|
461
|
+
acceptanceTimeoutMs = null
|
|
409
462
|
}) {
|
|
410
463
|
if (!task || typeof task !== "string") throw new Error("task is required");
|
|
464
|
+
const acceptanceCommands = normalizeAcceptance(acceptance);
|
|
411
465
|
if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
|
|
412
466
|
if (!allowedReasoningEfforts.has(reasoningEffort)) {
|
|
413
467
|
throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
|
|
414
468
|
}
|
|
415
|
-
if (!Array.isArray(ownedPaths) || ownedPaths.length === 0) {
|
|
416
|
-
throw new Error("ownedPaths is required and must list at least one path this worker is allowed to write");
|
|
469
|
+
if (!Array.isArray(ownedPaths) || (ownedPaths.length === 0 && sandbox !== "read-only")) {
|
|
470
|
+
throw new Error("ownedPaths is required and must list at least one path this worker is allowed to write (an empty list is allowed only for a read-only worker)");
|
|
417
471
|
}
|
|
418
472
|
const validatedGoal = validateGoal(goal);
|
|
419
473
|
|
|
@@ -460,6 +514,9 @@ export async function createCodexWorker({
|
|
|
460
514
|
run_count: 0,
|
|
461
515
|
worktree_path: worktreePath,
|
|
462
516
|
base_commit: worktree.baseCommit,
|
|
517
|
+
acceptance: acceptanceCommands,
|
|
518
|
+
acceptance_timeout_ms: acceptanceCommands ? (acceptanceTimeoutMs ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
|
|
519
|
+
acceptance_results: null,
|
|
463
520
|
prompt: task,
|
|
464
521
|
changed_files: [],
|
|
465
522
|
commands: [],
|
|
@@ -474,10 +531,10 @@ export async function createCodexWorker({
|
|
|
474
531
|
const started = await startTrackedRun({
|
|
475
532
|
record,
|
|
476
533
|
args,
|
|
477
|
-
prompt:
|
|
534
|
+
prompt: frameWorkerPrompt(task, {
|
|
478
535
|
objective: validatedGoal.objective,
|
|
479
536
|
tokenBudget: validatedGoal.tokenBudget
|
|
480
|
-
}),
|
|
537
|
+
}, { acceptance: acceptanceCommands }),
|
|
481
538
|
logPath: record.run_log
|
|
482
539
|
});
|
|
483
540
|
await upsertTask(started.record);
|
|
@@ -487,15 +544,66 @@ export async function createCodexWorker({
|
|
|
487
544
|
// Continue the *same* Codex session. The worktree, thread id, ownership and
|
|
488
545
|
// goal are all inherited from the original task, and the row is reused so one
|
|
489
546
|
// logical piece of work stays one row.
|
|
490
|
-
|
|
547
|
+
//
|
|
548
|
+
// `rebaseOnto` names a ref, resolved in the project directory (HEAD, main, a
|
|
549
|
+
// sha): the worktree is moved onto it first so the worker continues on
|
|
550
|
+
// current code, and base_commit is recorded before the worker starts so a
|
|
551
|
+
// spawn failure cannot leave the row describing the old base. A rebase that
|
|
552
|
+
// does not go through puts the worktree back and throws with the file list;
|
|
553
|
+
// the worker is not started. Refused while the worker is still running.
|
|
554
|
+
export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined }) {
|
|
491
555
|
if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
|
|
492
|
-
|
|
556
|
+
let task = await getTask(taskId);
|
|
493
557
|
if (!task) throw new Error(`task not found: ${taskId}`);
|
|
558
|
+
// `acceptance` replaces the stored commands when given; an empty list
|
|
559
|
+
// clears them. Left out, the stored commands stay.
|
|
560
|
+
if (acceptance !== undefined) {
|
|
561
|
+
const commands = normalizeAcceptance(acceptance);
|
|
562
|
+
task = {
|
|
563
|
+
...task,
|
|
564
|
+
acceptance: commands,
|
|
565
|
+
acceptance_timeout_ms: commands ? (task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
|
|
566
|
+
updated_at: new Date().toISOString()
|
|
567
|
+
};
|
|
568
|
+
await upsertTask(task);
|
|
569
|
+
}
|
|
494
570
|
if (!task.thread_id) {
|
|
495
571
|
throw new Error(
|
|
496
572
|
`task ${taskId} 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.`
|
|
497
573
|
);
|
|
498
574
|
}
|
|
575
|
+
let rebase = null;
|
|
576
|
+
if (rebaseOnto) {
|
|
577
|
+
if (ACTIVE_STATUSES.has(task.status) || processes.has(task.id)) {
|
|
578
|
+
const error = new Error(`task ${taskId} is still ${task.status}; wait for it to settle (or cancel it) before rebasing its worktree`);
|
|
579
|
+
error.code = "worker_active";
|
|
580
|
+
throw error;
|
|
581
|
+
}
|
|
582
|
+
if (!task.worktree_path) {
|
|
583
|
+
const error = new Error(`task ${taskId} ran in place and has no worktree to rebase`);
|
|
584
|
+
error.code = "no_worktree";
|
|
585
|
+
throw error;
|
|
586
|
+
}
|
|
587
|
+
let ontoCommit;
|
|
588
|
+
try {
|
|
589
|
+
ontoCommit = resolveCommit(task.project_root, rebaseOnto);
|
|
590
|
+
} catch {
|
|
591
|
+
const error = new Error(`rebaseOnto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
|
|
592
|
+
error.code = "invalid_rebase_onto";
|
|
593
|
+
throw error;
|
|
594
|
+
}
|
|
595
|
+
rebase = rebaseWorktree(task, ontoCommit);
|
|
596
|
+
if (rebase.error) {
|
|
597
|
+
const error = new Error(rebase.reason);
|
|
598
|
+
error.code = rebase.error;
|
|
599
|
+
error.details = rebase;
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
if (!rebase.noop && rebase.base_commit !== task.base_commit) {
|
|
603
|
+
task = { ...task, base_commit: rebase.base_commit, updated_at: new Date().toISOString() };
|
|
604
|
+
await upsertTask(task);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
499
607
|
|
|
500
608
|
const cwd = (await exists(task.cwd)) ? task.cwd : task.project_root;
|
|
501
609
|
const args = ["exec", "resume", "--json"];
|
|
@@ -509,15 +617,15 @@ export async function resumeCodexWorker({ taskId, prompt }) {
|
|
|
509
617
|
const started = await startTrackedRun({
|
|
510
618
|
record: { ...task, resumed_from: task.resumed_from ?? task.id },
|
|
511
619
|
args,
|
|
512
|
-
prompt:
|
|
620
|
+
prompt: frameWorkerPrompt(prompt, {
|
|
513
621
|
objective: task.goal_objective ?? task.title ?? task.id,
|
|
514
622
|
resume: true
|
|
515
|
-
}),
|
|
623
|
+
}, { acceptance: task.acceptance }),
|
|
516
624
|
logPath: task.run_log,
|
|
517
625
|
spawnOptions: { cwd }
|
|
518
626
|
});
|
|
519
627
|
await upsertTask(started.record);
|
|
520
|
-
return started.record;
|
|
628
|
+
return rebase ? { ...started.record, rebase } : started.record;
|
|
521
629
|
}
|
|
522
630
|
|
|
523
631
|
// `powershell` by name is not always on PATH for a process a GUI client
|
|
@@ -607,6 +715,12 @@ function terminatePid(pid) {
|
|
|
607
715
|
}
|
|
608
716
|
|
|
609
717
|
export async function cancelCodexWorker(taskId) {
|
|
718
|
+
const acceptance = acceptanceRuns.get(taskId);
|
|
719
|
+
if (acceptance) {
|
|
720
|
+
acceptance.cancelled = true;
|
|
721
|
+
acceptance.kill?.();
|
|
722
|
+
return { cancelled: true, via: "acceptance", pid: null };
|
|
723
|
+
}
|
|
610
724
|
const child = processes.get(taskId);
|
|
611
725
|
if (child) {
|
|
612
726
|
cancelledTasks.add(taskId);
|
|
@@ -649,7 +763,9 @@ export async function createFollowupWorker({
|
|
|
649
763
|
reasoningEffort,
|
|
650
764
|
ownedPaths,
|
|
651
765
|
goal,
|
|
652
|
-
baseRef
|
|
766
|
+
baseRef,
|
|
767
|
+
acceptance,
|
|
768
|
+
acceptanceTimeoutMs
|
|
653
769
|
}) {
|
|
654
770
|
const parent = await getTask(taskId);
|
|
655
771
|
if (!parent) throw new Error(`task not found: ${taskId}`);
|
|
@@ -693,6 +809,11 @@ export async function createFollowupWorker({
|
|
|
693
809
|
dependsOn: [parent.id],
|
|
694
810
|
followupOf: parent.id,
|
|
695
811
|
useWorktree: true,
|
|
696
|
-
baseRef: baseRef ?? null
|
|
812
|
+
baseRef: baseRef ?? null,
|
|
813
|
+
// Inherited unless given; the follow-up runs in a fresh worktree cut
|
|
814
|
+
// from the project HEAD, so the parent's checks only pass there once
|
|
815
|
+
// the parent's work has landed.
|
|
816
|
+
acceptance: acceptance === undefined ? parent.acceptance : acceptance,
|
|
817
|
+
acceptanceTimeoutMs: acceptanceTimeoutMs ?? parent.acceptance_timeout_ms ?? null
|
|
697
818
|
});
|
|
698
819
|
}
|
package/src/event-parser.js
CHANGED
|
@@ -125,15 +125,17 @@ export function applyCodexEvent(task, event) {
|
|
|
125
125
|
const command = inferCommand(item);
|
|
126
126
|
next.phase = "command";
|
|
127
127
|
next.current_command = null;
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
128
|
+
const exitCode = item?.exit_code ?? item?.exitCode ?? null;
|
|
129
|
+
const status = item?.status ?? "completed";
|
|
130
|
+
const entry = { command, exit_code: exitCode, status, completed_at: now };
|
|
131
|
+
// The tail of a failing command's output is the one piece of evidence
|
|
132
|
+
// a reviewer needs to tell "the build is broken" from "the network was
|
|
133
|
+
// down". Only failures keep it: the commands column is one row cell.
|
|
134
|
+
if (commandFailed(entry)) {
|
|
135
|
+
const tail = outputTail(item?.aggregated_output ?? item?.output ?? null);
|
|
136
|
+
if (tail) entry.output_tail = tail;
|
|
137
|
+
}
|
|
138
|
+
next.commands = [...(next.commands ?? []), entry];
|
|
137
139
|
return next;
|
|
138
140
|
}
|
|
139
141
|
if (itemType === "file_change") {
|
|
@@ -204,3 +206,56 @@ function errorText(value) {
|
|
|
204
206
|
}
|
|
205
207
|
return String(value);
|
|
206
208
|
}
|
|
209
|
+
|
|
210
|
+
const OUTPUT_TAIL_BYTES = 300;
|
|
211
|
+
|
|
212
|
+
function outputTail(output) {
|
|
213
|
+
if (typeof output !== "string" || !output) return null;
|
|
214
|
+
const buf = Buffer.from(output, "utf8");
|
|
215
|
+
if (buf.length <= OUTPUT_TAIL_BYTES) return output.trim() || null;
|
|
216
|
+
// Cut on a character boundary: drop bytes until the slice decodes cleanly.
|
|
217
|
+
let start = buf.length - OUTPUT_TAIL_BYTES;
|
|
218
|
+
while (start < buf.length && (buf[start] & 0xc0) === 0x80) start += 1;
|
|
219
|
+
return `…${buf.subarray(start).toString("utf8").trim()}`;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// A sandbox-refused command can come back with no exit code at all, only a
|
|
223
|
+
// failed status, so both are failure.
|
|
224
|
+
export function commandFailed(entry) {
|
|
225
|
+
if (!entry) return false;
|
|
226
|
+
if (entry.status === "failed") return true;
|
|
227
|
+
return entry.exit_code !== null && entry.exit_code !== undefined && entry.exit_code !== 0;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function clipText(value, max) {
|
|
231
|
+
const text = String(value ?? "");
|
|
232
|
+
return text.length > max ? `${text.slice(0, max)}…` : text;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// What the worker actually ran, condensed for a reviewer to hold its report
|
|
236
|
+
// against: a worker that says "tests pass" with commands_run 0, or that ends
|
|
237
|
+
// on a failing command and calls the work done, is caught here without
|
|
238
|
+
// reading the event stream. The commands list accumulates across resumes,
|
|
239
|
+
// so runs says how many turns it covers.
|
|
240
|
+
export function summarizeVerification(task, { limit = 10, clip = 160 } = {}) {
|
|
241
|
+
const commands = Array.isArray(task?.commands) ? task.commands : [];
|
|
242
|
+
const failed = commands.filter(commandFailed);
|
|
243
|
+
const last = commands[commands.length - 1] ?? null;
|
|
244
|
+
return {
|
|
245
|
+
runs: task?.run_count ?? 0,
|
|
246
|
+
commands_run: commands.length,
|
|
247
|
+
failed_count: failed.length,
|
|
248
|
+
last_exit_code: last ? (last.exit_code ?? null) : null,
|
|
249
|
+
last_command_failed: commandFailed(last),
|
|
250
|
+
failed: failed.slice(-limit).map((entry) => ({
|
|
251
|
+
command: clipText(entry.command, clip),
|
|
252
|
+
exit_code: entry.exit_code ?? null,
|
|
253
|
+
output_tail: entry.output_tail ?? null
|
|
254
|
+
})),
|
|
255
|
+
last: commands.slice(-limit).map((entry) => ({
|
|
256
|
+
command: clipText(entry.command, clip),
|
|
257
|
+
exit_code: entry.exit_code ?? null,
|
|
258
|
+
failed: commandFailed(entry)
|
|
259
|
+
}))
|
|
260
|
+
};
|
|
261
|
+
}
|
package/src/landing.js
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
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";
|
|
10
|
+
import { existsSync, rmSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
11
12
|
import { parsePorcelainLine, resolveWorktreeBase, worktreeRef } from "./worktree.js";
|
|
12
13
|
|
|
13
14
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
@@ -19,7 +20,7 @@ const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
|
19
20
|
// directory. An identity git already has is used untouched.
|
|
20
21
|
const FALLBACK_IDENTITY = { name: "codex-supervisor", email: "codex-supervisor@localhost" };
|
|
21
22
|
const identityCache = new Map();
|
|
22
|
-
function identityEnv(cwd) {
|
|
23
|
+
export function identityEnv(cwd) {
|
|
23
24
|
if (identityCache.has(cwd)) return identityCache.get(cwd);
|
|
24
25
|
let name = "";
|
|
25
26
|
let email = "";
|
|
@@ -79,8 +80,28 @@ function currentBranch(cwd) {
|
|
|
79
80
|
//
|
|
80
81
|
// Returns { landed: [{ sha, original, subject }], onto, head } on success;
|
|
81
82
|
// otherwise { error, reason, ... } with nothing changed in the target.
|
|
82
|
-
export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
83
|
+
export function landWorker(task, { onto = null, commitMessage = null, ignoreAcceptance = false } = {}) {
|
|
83
84
|
const target = task.project_root;
|
|
85
|
+
// The dispatcher's own checks are the gate. A failed run is refused until
|
|
86
|
+
// it passes; a run that was cut short is refused until it has run.
|
|
87
|
+
const acceptance = task.acceptance_results ?? null;
|
|
88
|
+
if (!ignoreAcceptance && acceptance) {
|
|
89
|
+
const failing = (acceptance.checks ?? []).find((check) => check.exit_code !== 0) ?? null;
|
|
90
|
+
if (acceptance.passed === false) {
|
|
91
|
+
return {
|
|
92
|
+
error: "acceptance_failed",
|
|
93
|
+
reason: `the worker's acceptance run failed${failing ? ` on "${failing.command.slice(0, 120)}" (exit ${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.`,
|
|
94
|
+
acceptance: { status: acceptance.status, passed: false, checks: acceptance.checks ?? [], error: acceptance.error ?? null }
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
if (acceptance.status === "running" || acceptance.status === "interrupted" || acceptance.status === "cancelled") {
|
|
98
|
+
return {
|
|
99
|
+
error: "acceptance_not_run",
|
|
100
|
+
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.`,
|
|
101
|
+
acceptance: { status: acceptance.status, passed: null }
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
84
105
|
if (!task.worktree_path || !existsSync(task.worktree_path)) {
|
|
85
106
|
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
107
|
}
|
|
@@ -124,6 +145,30 @@ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
|
124
145
|
commits.push(committedForWorker);
|
|
125
146
|
uncommitted = [];
|
|
126
147
|
}
|
|
148
|
+
// Commits whose patch is already on the target (a previous land, or the
|
|
149
|
+
// main thread cherry-picked by hand) are skipped by patch id; picking
|
|
150
|
+
// them again produces an empty commit and git stops with an error.
|
|
151
|
+
const targetHead = git(target, ["rev-parse", "HEAD"]).trim();
|
|
152
|
+
let alreadyLanded = [];
|
|
153
|
+
if (commits.length > 0) {
|
|
154
|
+
try {
|
|
155
|
+
const workerHead = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
|
|
156
|
+
const pending = new Set(lines(git(target, ["rev-list", "--cherry-pick", "--right-only", `${targetHead}...${workerHead}`])));
|
|
157
|
+
alreadyLanded = commits.filter((sha) => !pending.has(sha));
|
|
158
|
+
commits = commits.filter((sha) => pending.has(sha));
|
|
159
|
+
} catch {
|
|
160
|
+
// comparison failed; try to land everything and let the pick decide
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (commits.length === 0 && alreadyLanded.length > 0) {
|
|
164
|
+
return {
|
|
165
|
+
error: "nothing_to_land",
|
|
166
|
+
reason: `every commit on this worker's branch is already on ${branch} (landed before, by patch); nothing new to land`,
|
|
167
|
+
already_landed: alreadyLanded,
|
|
168
|
+
uncommitted,
|
|
169
|
+
base_commit: base
|
|
170
|
+
};
|
|
171
|
+
}
|
|
127
172
|
if (commits.length === 0) {
|
|
128
173
|
return {
|
|
129
174
|
error: "nothing_to_land",
|
|
@@ -135,7 +180,7 @@ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
|
135
180
|
};
|
|
136
181
|
}
|
|
137
182
|
|
|
138
|
-
const before =
|
|
183
|
+
const before = targetHead;
|
|
139
184
|
try {
|
|
140
185
|
git(target, ["cherry-pick", "--allow-empty-message", ...commits], { timeout: 10 * 60 * 1000 });
|
|
141
186
|
} catch (error) {
|
|
@@ -170,7 +215,180 @@ export function landWorker(task, { onto = null, commitMessage = null } = {}) {
|
|
|
170
215
|
base_commit: base,
|
|
171
216
|
head: landed.at(-1) ?? before,
|
|
172
217
|
landed: landed.map((sha, index) => ({ sha, original: commits[index] ?? null, subject: subjectOf.get(sha) ?? null })),
|
|
218
|
+
already_landed: alreadyLanded,
|
|
173
219
|
committed_for_worker: committedForWorker,
|
|
174
220
|
uncommitted
|
|
175
221
|
};
|
|
176
222
|
}
|
|
223
|
+
|
|
224
|
+
function gitTail(error) {
|
|
225
|
+
return `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-4).join("\n") || error.message.split("\n")[0];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function conflictFiles(cwd) {
|
|
229
|
+
try {
|
|
230
|
+
return lines(git(cwd, ["diff", "--name-only", "--diff-filter=U"]));
|
|
231
|
+
} catch {
|
|
232
|
+
return [];
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function stashRef(cwd) {
|
|
237
|
+
try {
|
|
238
|
+
return git(cwd, ["rev-parse", "-q", "--verify", "refs/stash"]).trim() || null;
|
|
239
|
+
} catch {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function operationInProgress(cwd) {
|
|
245
|
+
for (const marker of ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", "MERGE_HEAD"]) {
|
|
246
|
+
try {
|
|
247
|
+
const path = git(cwd, ["rev-parse", "--git-path", marker]).trim();
|
|
248
|
+
if (path && existsSync(path.startsWith("/") || /^[A-Za-z]:/.test(path) ? path : join(cwd, path))) return marker;
|
|
249
|
+
} catch {
|
|
250
|
+
// not a repo; the caller reports that
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Moves a worker's worktree onto a newer commit of the project before the
|
|
257
|
+
// worker is resumed. The worktree was cut from base_commit when the worker
|
|
258
|
+
// was dispatched; by the time it is sent back for a fix the project's branch
|
|
259
|
+
// has often moved on, and a worker that keeps editing the old base does
|
|
260
|
+
// work that cannot land.
|
|
261
|
+
//
|
|
262
|
+
// Exactly the worker's own commits are replayed: `git rebase --onto <onto>
|
|
263
|
+
// <base>`, never a plain rebase, whose merge-base start would also replay
|
|
264
|
+
// the project's own commits when the base was rewritten. Edits the worker
|
|
265
|
+
// left uncommitted (every workspace-write worker: the sandbox keeps .git
|
|
266
|
+
// read-only) are stashed around the rebase, untracked files included.
|
|
267
|
+
//
|
|
268
|
+
// Nothing is left half done. A conflict in the replay aborts the rebase; a
|
|
269
|
+
// conflict when the stash comes back resets the branch to where it was and
|
|
270
|
+
// pops the stash there, which cannot conflict. Either way the worktree is as
|
|
271
|
+
// it was and the caller gets the file list.
|
|
272
|
+
//
|
|
273
|
+
// Returns { ok: true, noop: true, base_commit, head } when onto is already in
|
|
274
|
+
// the branch's history, { ok: true, base_commit: onto, head, replayed,
|
|
275
|
+
// stashed } after a real rebase, or { error, reason, files?, git?,
|
|
276
|
+
// base_commit, head } with nothing changed.
|
|
277
|
+
export function rebaseWorktree(task, ontoCommit) {
|
|
278
|
+
const cwd = task.worktree_path;
|
|
279
|
+
if (!cwd || !existsSync(cwd)) {
|
|
280
|
+
return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing to rebase" };
|
|
281
|
+
}
|
|
282
|
+
const base = resolveWorktreeBase(cwd, worktreeRef(task));
|
|
283
|
+
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" };
|
|
284
|
+
const inProgress = operationInProgress(cwd);
|
|
285
|
+
if (inProgress) {
|
|
286
|
+
return { error: "rebase_in_progress", reason: `${cwd} has a ${inProgress} in progress; finish or abort it first`, base_commit: base };
|
|
287
|
+
}
|
|
288
|
+
let head;
|
|
289
|
+
try {
|
|
290
|
+
head = git(cwd, ["rev-parse", "HEAD"]).trim();
|
|
291
|
+
} catch (error) {
|
|
292
|
+
return { error: "no_worktree", reason: `${cwd} has no resolvable HEAD: ${gitTail(error)}`, base_commit: base };
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
git(cwd, ["merge-base", "--is-ancestor", ontoCommit, "HEAD"]);
|
|
296
|
+
// onto is already behind or at this branch: a rebase would move the
|
|
297
|
+
// worker's commits backwards. Nothing to do and base stays.
|
|
298
|
+
return { ok: true, noop: true, base_commit: base, head };
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.status !== 1) {
|
|
301
|
+
return { error: "rebase_failed", reason: `could not compare ${ontoCommit} with HEAD: ${gitTail(error)}`, git: gitTail(error), base_commit: base, head };
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const stashBefore = stashRef(cwd);
|
|
306
|
+
let stashed = false;
|
|
307
|
+
try {
|
|
308
|
+
git(cwd, ["stash", "push", "--include-untracked", "-q", "-m", "codex-supervisor: rebase"]);
|
|
309
|
+
} catch (error) {
|
|
310
|
+
return { error: "rebase_failed", reason: `could not stash the worker's uncommitted edits: ${gitTail(error)}`, git: gitTail(error), base_commit: base, head };
|
|
311
|
+
}
|
|
312
|
+
// "No local changes to save" also exits 0, so the stash ref decides.
|
|
313
|
+
stashed = stashRef(cwd) !== stashBefore;
|
|
314
|
+
|
|
315
|
+
// A pop that fails has already written the stash's untracked files back
|
|
316
|
+
// into the worktree, and reset --hard does not touch untracked files, so
|
|
317
|
+
// the next pop would stop on "already exists". Those files are the
|
|
318
|
+
// stash's third parent; they are removed before the pop that restores
|
|
319
|
+
// them for good.
|
|
320
|
+
const removeStashedUntracked = () => {
|
|
321
|
+
let paths = [];
|
|
322
|
+
try {
|
|
323
|
+
paths = lines(git(cwd, ["ls-tree", "-r", "--name-only", "refs/stash^3"]));
|
|
324
|
+
} catch {
|
|
325
|
+
return; // the stash carries no untracked files
|
|
326
|
+
}
|
|
327
|
+
for (const path of paths) rmSync(join(cwd, path), { force: true });
|
|
328
|
+
};
|
|
329
|
+
const restoreStash = () => {
|
|
330
|
+
if (!stashed) return null;
|
|
331
|
+
try {
|
|
332
|
+
removeStashedUntracked();
|
|
333
|
+
git(cwd, ["stash", "pop", "-q"]);
|
|
334
|
+
return null;
|
|
335
|
+
} catch (error) {
|
|
336
|
+
return gitTail(error);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
try {
|
|
341
|
+
git(cwd, ["rebase", "--onto", ontoCommit, base], { timeout: 10 * 60 * 1000 });
|
|
342
|
+
} catch (error) {
|
|
343
|
+
const files = conflictFiles(cwd);
|
|
344
|
+
try {
|
|
345
|
+
git(cwd, ["rebase", "--abort"]);
|
|
346
|
+
} catch {
|
|
347
|
+
// nothing in progress to abort
|
|
348
|
+
}
|
|
349
|
+
const popError = restoreStash();
|
|
350
|
+
return {
|
|
351
|
+
error: files.length > 0 ? "rebase_conflict" : "rebase_failed",
|
|
352
|
+
reason: files.length > 0
|
|
353
|
+
? `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)" : ""}`
|
|
354
|
+
: `the rebase failed; the worktree is back as it was${popError ? " (but its stash could not be restored: run git stash pop there)" : ""}`,
|
|
355
|
+
files,
|
|
356
|
+
git: gitTail(error),
|
|
357
|
+
base_commit: base,
|
|
358
|
+
head
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
const newHead = git(cwd, ["rev-parse", "HEAD"]).trim();
|
|
362
|
+
let replayed = 0;
|
|
363
|
+
try {
|
|
364
|
+
replayed = lines(git(cwd, ["rev-list", `${ontoCommit}..HEAD`])).length;
|
|
365
|
+
} catch {
|
|
366
|
+
// reported as 0
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (stashed) {
|
|
370
|
+
try {
|
|
371
|
+
git(cwd, ["stash", "pop", "-q"]);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
// The replay succeeded but the worker's uncommitted edits do not fit
|
|
374
|
+
// the new base. Back to the old base, where the same stash pops clean.
|
|
375
|
+
const files = conflictFiles(cwd);
|
|
376
|
+
const tail = gitTail(error);
|
|
377
|
+
try {
|
|
378
|
+
git(cwd, ["reset", "-q", "--hard", head]);
|
|
379
|
+
} catch {
|
|
380
|
+
// fall through; the stash is still there
|
|
381
|
+
}
|
|
382
|
+
const popError = restoreStash();
|
|
383
|
+
return {
|
|
384
|
+
error: "stash_conflict",
|
|
385
|
+
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`,
|
|
386
|
+
files,
|
|
387
|
+
git: tail,
|
|
388
|
+
base_commit: base,
|
|
389
|
+
head
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return { ok: true, base_commit: ontoCommit, head: newHead, previous_head: head, replayed, stashed };
|
|
394
|
+
}
|