codex-supervisor-mcp 0.13.5 → 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 +2 -2
- package/README.md +2 -2
- package/package.json +19 -63
- package/skills/codex-supervisor/SKILL.md +5 -4
- package/src/{acceptance.js → app/acceptance.js} +54 -68
- package/src/app/auto-cleanup.js +90 -0
- package/src/app/cancel.js +60 -0
- package/src/app/cleanup-facts.js +96 -0
- package/src/app/cleanup-plan.js +164 -0
- package/src/app/compose.js +7 -0
- package/src/{context-compiler.js → app/context-compiler.js} +7 -13
- package/src/app/dispatch.js +396 -0
- package/src/app/followup.js +98 -0
- package/src/app/land-chain.js +133 -0
- package/src/app/landing.js +357 -0
- package/src/app/ownership.js +57 -0
- package/src/app/rebase.js +216 -0
- package/src/app/restore-worktree.js +50 -0
- package/src/app/resume.js +181 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/{side-chat.js → app/side-chat.js} +82 -265
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +114 -0
- package/src/app/worktree-setup.js +176 -0
- package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/cleanup-policy.js +44 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/{overview-delta.js → domain/overview-delta.js} +7 -3
- package/src/domain/side-turn-view.js +73 -0
- package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
- package/src/{cleanup-hint.js → infra/cleanup-hint.js} +7 -8
- package/src/infra/git.js +30 -0
- package/src/infra/process.js +59 -0
- package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
- package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/events.js +146 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +172 -0
- package/src/infra/store/records.js +171 -0
- package/src/infra/store/runner-readers.js +16 -0
- package/src/infra/store/schema.js +306 -0
- package/src/infra/store/sessions.js +138 -0
- package/src/infra/store/tasks.js +337 -0
- package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
- package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
- package/src/{update-check.js → infra/update/update-check.js} +4 -4
- package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
- package/src/{worktree.js → infra/worktree.js} +56 -41
- package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
- package/src/{cleanup.js → interface/bin/cleanup.js} +4 -3
- package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
- package/src/{setup.js → interface/bin/setup.js} +7 -6
- package/src/{stage.js → interface/bin/stage.js} +1 -1
- package/src/{web-server.js → interface/bin/web-server.js} +2 -2
- package/src/interface/mcp/meta.js +7 -0
- package/src/interface/mcp/result.js +34 -0
- package/src/interface/mcp/schemas.js +24 -0
- package/src/interface/mcp/server.js +94 -0
- package/src/interface/mcp/tools/delivery.js +197 -0
- package/src/interface/mcp/tools/dispatch.js +267 -0
- package/src/interface/mcp/tools/facts.js +239 -0
- package/src/interface/mcp/tools/overview.js +202 -0
- package/src/interface/mcp/tools/poll.js +58 -0
- package/src/interface/mcp/tools/results.js +284 -0
- package/src/interface/mcp/tools/review.js +135 -0
- package/src/interface/mcp/tools/wait.js +145 -0
- package/src/interface/mcp/update-state.js +34 -0
- package/src/interface/mcp/views/overview.js +183 -0
- package/src/interface/mcp/views/task.js +223 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +224 -0
- package/src/mcp-server.js +3 -2223
- package/src/run-host/entry.js +23 -0
- package/src/run-host/finalize.js +236 -0
- package/src/run-host/launch.js +63 -0
- package/src/run-host/live-run.js +73 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +76 -0
- package/src/run-host/track.js +128 -0
- package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
- package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
- package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
- package/src/cleanup-plan.js +0 -158
- package/src/codex-runner.js +0 -1586
- package/src/landing.js +0 -507
- package/src/task-store.js +0 -1800
- package/src/web-app.js +0 -425
- /package/src/{failure-class.js → domain/failure-class.js} +0 -0
- /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
- /package/src/{prompt.js → domain/prompt.js} +0 -0
- /package/src/{status.js → domain/status.js} +0 -0
- /package/src/{thread-health.js → domain/thread-health.js} +0 -0
- /package/src/{truncate.js → domain/truncate.js} +0 -0
- /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
- /package/src/{worker-env.js → domain/worker-env.js} +0 -0
- /package/src/{worker-report.js → domain/worker-report.js} +0 -0
- /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
- /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
- /package/src/{external-output.js → infra/external-output.js} +0 -0
- /package/src/{handoff.js → infra/handoff.js} +0 -0
- /package/src/{paths.js → infra/paths.js} +0 -0
- /package/src/{stage-store.js → infra/stage-store.js} +0 -0
- /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Moving a worker's worktree onto a newer base before it continues: stash its
|
|
2
|
+
// uncommitted edits, replay only the commits that are not on the new base yet,
|
|
3
|
+
// put the edits back. Any failure leaves the worktree as it was.
|
|
4
|
+
import { resolveWorktreeBase, worktreeRef } from "../infra/worktree.js";
|
|
5
|
+
import { git, gitTail, lines } from "./landing.js";
|
|
6
|
+
import { existsSync, rmSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
function conflictFiles(cwd) {
|
|
10
|
+
try {
|
|
11
|
+
return lines(git(cwd, ["diff", "--name-only", "--diff-filter=U"]));
|
|
12
|
+
} catch {
|
|
13
|
+
return [];
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function stashRef(cwd) {
|
|
18
|
+
try {
|
|
19
|
+
return git(cwd, ["rev-parse", "-q", "--verify", "refs/stash"]).trim() || null;
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function operationInProgress(cwd) {
|
|
26
|
+
for (const marker of ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", "MERGE_HEAD"]) {
|
|
27
|
+
try {
|
|
28
|
+
const path = git(cwd, ["rev-parse", "--git-path", marker]).trim();
|
|
29
|
+
if (path && existsSync(path.startsWith("/") || /^[A-Za-z]:/.test(path) ? path : join(cwd, path))) return marker;
|
|
30
|
+
} catch {
|
|
31
|
+
// not a repo; the caller reports that
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Moves a worker's worktree onto a newer commit of the project before the
|
|
38
|
+
// worker is resumed. The worktree was cut from base_commit when the worker
|
|
39
|
+
// was dispatched; by the time it is sent back for a fix the project's branch
|
|
40
|
+
// has often moved on, and a worker that keeps editing the old base does
|
|
41
|
+
// work that cannot land.
|
|
42
|
+
//
|
|
43
|
+
// Exactly the worker's own commits are replayed: `git rebase --onto <onto>
|
|
44
|
+
// <base>`, never a plain rebase, whose merge-base start would also replay
|
|
45
|
+
// the project's own commits when the base was rewritten. Edits the worker
|
|
46
|
+
// left uncommitted (every workspace-write worker: the sandbox keeps .git
|
|
47
|
+
// read-only) are stashed around the rebase, untracked files included.
|
|
48
|
+
//
|
|
49
|
+
// Nothing is left half done. A conflict in the replay aborts the rebase; a
|
|
50
|
+
// conflict when the stash comes back resets the branch to where it was and
|
|
51
|
+
// pops the stash there, which cannot conflict. Either way the worktree is as
|
|
52
|
+
// it was and the caller gets the file list.
|
|
53
|
+
//
|
|
54
|
+
// Returns { ok: true, noop: true, base_commit, head } when onto is already in
|
|
55
|
+
// the branch's history, { ok: true, base_commit: onto, head, replayed,
|
|
56
|
+
// stashed } after a real rebase, or { error, reason, files?, git?,
|
|
57
|
+
// base_commit, head } with nothing changed.
|
|
58
|
+
// A pop that fails has already written the stash's untracked files back
|
|
59
|
+
// into the worktree, and reset --hard does not touch untracked files, so
|
|
60
|
+
// the next pop would stop on "already exists". Those files are the
|
|
61
|
+
// stash's third parent; they are removed before the pop that restores
|
|
62
|
+
// them for good.
|
|
63
|
+
function removeStashedUntracked(cwd) {
|
|
64
|
+
let paths;
|
|
65
|
+
try {
|
|
66
|
+
paths = lines(git(cwd, ["ls-tree", "-r", "--name-only", "refs/stash^3"]));
|
|
67
|
+
} catch {
|
|
68
|
+
return; // the stash carries no untracked files
|
|
69
|
+
}
|
|
70
|
+
for (const path of paths) rmSync(join(cwd, path), { force: true });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Null when the stash is back (or there was none), otherwise git's complaint.
|
|
74
|
+
function restoreStash(cwd, stashed) {
|
|
75
|
+
if (!stashed) return null;
|
|
76
|
+
try {
|
|
77
|
+
removeStashedUntracked(cwd);
|
|
78
|
+
git(cwd, ["stash", "pop", "-q"]);
|
|
79
|
+
return null;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
return gitTail(error);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Where the worktree stands, or the reason it cannot be rebased, or a no-op
|
|
86
|
+
// when the new base is already behind it.
|
|
87
|
+
function rebaseStart(task, ontoCommit) {
|
|
88
|
+
const cwd = task.worktree_path;
|
|
89
|
+
if (!cwd || !existsSync(cwd)) {
|
|
90
|
+
return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing to rebase" };
|
|
91
|
+
}
|
|
92
|
+
const base = resolveWorktreeBase(cwd, worktreeRef(task));
|
|
93
|
+
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" };
|
|
94
|
+
const inProgress = operationInProgress(cwd);
|
|
95
|
+
if (inProgress) {
|
|
96
|
+
return { error: "rebase_in_progress", reason: `${cwd} has a ${inProgress} in progress; finish or abort it first`, base_commit: base };
|
|
97
|
+
}
|
|
98
|
+
let head;
|
|
99
|
+
try {
|
|
100
|
+
head = git(cwd, ["rev-parse", "HEAD"]).trim();
|
|
101
|
+
} catch (error) {
|
|
102
|
+
return { error: "no_worktree", reason: `${cwd} has no resolvable HEAD: ${gitTail(error)}`, base_commit: base };
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
git(cwd, ["merge-base", "--is-ancestor", ontoCommit, "HEAD"]);
|
|
106
|
+
// onto is already behind or at this branch: a rebase would move the
|
|
107
|
+
// worker's commits backwards. Nothing to do and base stays.
|
|
108
|
+
return { ok: true, noop: true, base_commit: base, head };
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error.status !== 1) {
|
|
111
|
+
return { error: "rebase_failed", reason: `could not compare ${ontoCommit} with HEAD: ${gitTail(error)}`, git: gitTail(error), base_commit: base, head };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return { cwd, base, head };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function splitByPatch(cwd, base, ontoCommit, head) {
|
|
118
|
+
try {
|
|
119
|
+
const commits = lines(git(cwd, ["rev-list", "--reverse", `${base}..HEAD`]));
|
|
120
|
+
const newPatches = new Set(lines(git(cwd, ["cherry", ontoCommit, "HEAD", base]))
|
|
121
|
+
.filter((line) => line.startsWith("+ ")).map((line) => line.slice(2)));
|
|
122
|
+
return { pending: commits.filter((sha) => newPatches.has(sha)), alreadyLanded: commits.filter((sha) => !newPatches.has(sha)) };
|
|
123
|
+
} catch (error) {
|
|
124
|
+
return { error: "rebase_failed", reason: `could not prove which worker patches are already integrated: ${gitTail(error)}`, base_commit: base, head };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function stashEdits(cwd, base, head) {
|
|
129
|
+
const stashBefore = stashRef(cwd);
|
|
130
|
+
try {
|
|
131
|
+
git(cwd, ["stash", "push", "--include-untracked", "-q", "-m", "codex-supervisor: rebase"]);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
return { error: "rebase_failed", reason: `could not stash the worker's uncommitted edits: ${gitTail(error)}`, git: gitTail(error), base_commit: base, head };
|
|
134
|
+
}
|
|
135
|
+
// "No local changes to save" also exits 0, so the stash ref decides.
|
|
136
|
+
return { stashed: stashRef(cwd) !== stashBefore };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Rebase --onto can replay a patch previously cherry-picked to main and
|
|
140
|
+
// conflict with main's later edits. Rebuild only the proven new patches.
|
|
141
|
+
function replayPending({ cwd, base, head }, ontoCommit, pending, stashed) {
|
|
142
|
+
try {
|
|
143
|
+
git(cwd, ["reset", "-q", "--hard", ontoCommit]);
|
|
144
|
+
if (pending.length) git(cwd, ["cherry-pick", ...pending], { timeout: 10 * 60 * 1000 });
|
|
145
|
+
return null;
|
|
146
|
+
} catch (error) {
|
|
147
|
+
const files = conflictFiles(cwd);
|
|
148
|
+
try {
|
|
149
|
+
git(cwd, ["cherry-pick", "--abort"]);
|
|
150
|
+
} catch {
|
|
151
|
+
// nothing in progress to abort
|
|
152
|
+
}
|
|
153
|
+
git(cwd, ["reset", "-q", "--hard", head]);
|
|
154
|
+
const popError = restoreStash(cwd, stashed);
|
|
155
|
+
return {
|
|
156
|
+
error: files.length > 0 ? "rebase_conflict" : "rebase_failed",
|
|
157
|
+
reason: files.length > 0
|
|
158
|
+
? `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)" : ""}`
|
|
159
|
+
: `the rebase failed; the worktree is back as it was${popError ? " (but its stash could not be restored: run git stash pop there)" : ""}`,
|
|
160
|
+
files,
|
|
161
|
+
git: gitTail(error),
|
|
162
|
+
base_commit: base,
|
|
163
|
+
head
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The replay succeeded; put the uncommitted edits back. If they do not fit the
|
|
169
|
+
// new base, go back to the old base, where the same stash pops clean.
|
|
170
|
+
function popOntoNewBase({ cwd, base, head }, ontoCommit) {
|
|
171
|
+
try {
|
|
172
|
+
git(cwd, ["stash", "pop", "-q"]);
|
|
173
|
+
return null;
|
|
174
|
+
} catch (error) {
|
|
175
|
+
const files = conflictFiles(cwd);
|
|
176
|
+
const tail = gitTail(error);
|
|
177
|
+
try {
|
|
178
|
+
git(cwd, ["reset", "-q", "--hard", head]);
|
|
179
|
+
} catch {
|
|
180
|
+
// fall through; the stash is still there
|
|
181
|
+
}
|
|
182
|
+
const popError = restoreStash(cwd, true);
|
|
183
|
+
return {
|
|
184
|
+
error: "stash_conflict",
|
|
185
|
+
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`,
|
|
186
|
+
files,
|
|
187
|
+
git: tail,
|
|
188
|
+
base_commit: base,
|
|
189
|
+
head
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function rebaseWorktree(task, ontoCommit) {
|
|
195
|
+
const start = rebaseStart(task, ontoCommit);
|
|
196
|
+
if (start.error || start.noop) return start;
|
|
197
|
+
const { cwd, base, head } = start;
|
|
198
|
+
const split = splitByPatch(cwd, base, ontoCommit, head);
|
|
199
|
+
if (split.error) return split;
|
|
200
|
+
const stash = stashEdits(cwd, base, head);
|
|
201
|
+
if (stash.error) return stash;
|
|
202
|
+
const { stashed } = stash;
|
|
203
|
+
|
|
204
|
+
const failed = replayPending(start, ontoCommit, split.pending, stashed);
|
|
205
|
+
if (failed) return failed;
|
|
206
|
+
const newHead = git(cwd, ["rev-parse", "HEAD"]).trim();
|
|
207
|
+
let replayed = 0;
|
|
208
|
+
try {
|
|
209
|
+
replayed = lines(git(cwd, ["rev-list", `${ontoCommit}..HEAD`])).length;
|
|
210
|
+
} catch {
|
|
211
|
+
// reported as 0
|
|
212
|
+
}
|
|
213
|
+
const stashConflict = stashed ? popOntoNewBase(start, ontoCommit) : null;
|
|
214
|
+
if (stashConflict) return stashConflict;
|
|
215
|
+
return { ok: true, base_commit: ontoCommit, head: newHead, previous_head: head, replayed, already_landed: split.alreadyLanded, stashed };
|
|
216
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { ensureTaskWorktree } from "./restore-worktree.js";
|
|
3
|
+
import "./compose.js";
|
|
4
|
+
import { frameWorkerPrompt } from "../domain/prompt.js";
|
|
5
|
+
import { ACTIVE_STATUSES } from "../domain/status.js";
|
|
6
|
+
import { buildHandoff } from "../infra/handoff.js";
|
|
7
|
+
import { appendTaskEvent } from "../infra/store/events.js";
|
|
8
|
+
import { getSession } from "../infra/store/sessions.js";
|
|
9
|
+
import { claimTaskRun, getTask, readTasks, releaseTaskRun, upsertTask } from "../infra/store/tasks.js";
|
|
10
|
+
import { codexRunner } from "../runners/codex/adapter.js";
|
|
11
|
+
import { readNativeGoalState } from "../runners/codex/goal-store.js";
|
|
12
|
+
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance } from "./acceptance.js";
|
|
13
|
+
import { isPidAlive } from "./cancel.js";
|
|
14
|
+
import { rebaseWorktree } from "./rebase.js";
|
|
15
|
+
import { processes } from "./run-state.js";
|
|
16
|
+
import { startTrackedRun } from "./start-run.js";
|
|
17
|
+
import { exists, resolveCommit } from "./worktree-setup.js";
|
|
18
|
+
import { appendFile } from "node:fs/promises";
|
|
19
|
+
|
|
20
|
+
// Continue the *same* Codex session. The worktree, thread id, ownership and
|
|
21
|
+
// goal are all inherited from the original task, and the row is reused so one
|
|
22
|
+
// logical piece of work stays one row.
|
|
23
|
+
//
|
|
24
|
+
// `rebaseOnto` names a ref, resolved in the project directory (HEAD, main, a
|
|
25
|
+
// sha): the worktree is moved onto it first so the worker continues on
|
|
26
|
+
// current code, and base_commit is recorded before the worker starts so a
|
|
27
|
+
// spawn failure cannot leave the row describing the old base. A rebase that
|
|
28
|
+
// does not go through puts the worktree back and throws with the file list;
|
|
29
|
+
// the worker is not started. Refused while the worker is still running.
|
|
30
|
+
function coded(code, message, details = undefined) {
|
|
31
|
+
const error = new Error(message);
|
|
32
|
+
error.code = code;
|
|
33
|
+
if (details !== undefined) error.details = details;
|
|
34
|
+
return error;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// `acceptance` replaces the stored commands when given; an empty list
|
|
38
|
+
// clears them. Left out, the stored commands stay.
|
|
39
|
+
async function refreshAcceptance(task, session, acceptance) {
|
|
40
|
+
const inheritedAcceptance = task.session_policy_revision == null ? task.acceptance : task.acceptance_local;
|
|
41
|
+
const localAcceptance = acceptance === undefined ? inheritedAcceptance : normalizeAcceptance(acceptance);
|
|
42
|
+
if (acceptance === undefined && !session) return task;
|
|
43
|
+
const commands = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(localAcceptance ?? [])]);
|
|
44
|
+
const updated = {
|
|
45
|
+
...task,
|
|
46
|
+
acceptance: commands,
|
|
47
|
+
acceptance_local: localAcceptance,
|
|
48
|
+
session_policy_revision: session?.policy_revision ?? null,
|
|
49
|
+
acceptance_timeout_ms: commands ? (task.acceptance_timeout_ms ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
|
|
50
|
+
updated_at: new Date().toISOString()
|
|
51
|
+
};
|
|
52
|
+
await upsertTask(updated);
|
|
53
|
+
return updated;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Moves the worktree onto a newer base before the worker continues. A conflict
|
|
57
|
+
// is thrown back with the details and no worker is started.
|
|
58
|
+
async function rebaseBeforeResume(task, rebaseOnto) {
|
|
59
|
+
if (ACTIVE_STATUSES.has(task.status) || processes.has(task.id)) {
|
|
60
|
+
throw coded("worker_active", `task ${task.id} is still ${task.status}; wait for it to settle (or cancel it) before rebasing its worktree`);
|
|
61
|
+
}
|
|
62
|
+
if (!task.worktree_path) throw coded("no_worktree", `task ${task.id} ran in place and has no worktree to rebase`);
|
|
63
|
+
let ontoCommit;
|
|
64
|
+
try {
|
|
65
|
+
ontoCommit = resolveCommit(task.project_root, rebaseOnto);
|
|
66
|
+
} catch {
|
|
67
|
+
throw coded("invalid_rebase_onto", `rebaseOnto "${rebaseOnto}" does not resolve to a commit in ${task.project_root}`);
|
|
68
|
+
}
|
|
69
|
+
const rebase = rebaseWorktree(task, ontoCommit);
|
|
70
|
+
if (rebase.error) throw coded(rebase.error, rebase.reason, rebase);
|
|
71
|
+
if (rebase.noop || rebase.base_commit === task.base_commit) return { task, rebase };
|
|
72
|
+
const moved = { ...task, base_commit: rebase.base_commit, updated_at: new Date().toISOString() };
|
|
73
|
+
await upsertTask(moved);
|
|
74
|
+
return { task: moved, rebase };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Only a thread with no native goal, or one explicitly stored as complete,
|
|
78
|
+
// can safely resume with a structured output schema. Paused, blocked,
|
|
79
|
+
// usage-limited and budget-limited goals are not complete; Codex can still
|
|
80
|
+
// activate their goal turn and reject the incompatible schema.
|
|
81
|
+
function resumeAllowsOutputSchema(threadId) {
|
|
82
|
+
const goalRead = readNativeGoalState(threadId);
|
|
83
|
+
return ["missing_goal", "missing_database"].includes(goalRead.state)
|
|
84
|
+
|| (goalRead.state === "available" && goalRead.goal?.storage_status === "complete");
|
|
85
|
+
}
|
|
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
|
+
|
|
101
|
+
async function resumeClaimed(claimed, { prompt, rebaseOnto, acceptance }) {
|
|
102
|
+
const session = claimed.session_id ? await getSession(claimed.session_id) : null;
|
|
103
|
+
if (session?.approval_state === "waiting_user") throw coded("session_waiting_user", "session is waiting for user approval; do not resume");
|
|
104
|
+
let task = await refreshAcceptance(claimed, session, acceptance);
|
|
105
|
+
if (!task.thread_id) {
|
|
106
|
+
throw new Error(
|
|
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.`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
await ensureTaskWorktree(task);
|
|
111
|
+
let rebase = null;
|
|
112
|
+
if (rebaseOnto) ({ task, rebase } = await rebaseBeforeResume(task, rebaseOnto));
|
|
113
|
+
|
|
114
|
+
const cwd = await resumeCwd(task);
|
|
115
|
+
const args = codexRunner.resumeArgs(task);
|
|
116
|
+
const outputSchema = resumeAllowsOutputSchema(task.thread_id);
|
|
117
|
+
const started = await startTrackedRun({
|
|
118
|
+
record: { ...task, resumed_from: task.resumed_from ?? task.id },
|
|
119
|
+
args,
|
|
120
|
+
prompt: frameWorkerPrompt(prompt, {
|
|
121
|
+
objective: task.goal_objective ?? task.title ?? task.id,
|
|
122
|
+
resume: true
|
|
123
|
+
}, { acceptance: task.acceptance, outputSchema }),
|
|
124
|
+
logPath: task.run_log,
|
|
125
|
+
outputSchema,
|
|
126
|
+
spawnOptions: { cwd }
|
|
127
|
+
});
|
|
128
|
+
return rebase ? { ...started.record, rebase } : started.record;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function resumeCodexWorker({ taskId, prompt, rebaseOnto = null, acceptance = undefined, context = undefined }) {
|
|
132
|
+
if (!prompt || typeof prompt !== "string") throw new Error("prompt is required");
|
|
133
|
+
let task = await getTask(taskId);
|
|
134
|
+
if (!task) throw new Error(`task not found: ${taskId}`);
|
|
135
|
+
if (task.guard_policy?.maxTotalMs && Date.now() - Date.parse(task.created_at) >= task.guard_policy.maxTotalMs) {
|
|
136
|
+
throw coded("time_quota_exceeded", "total time quota exceeded; inspect partial work and explicitly dispatch a revised budget");
|
|
137
|
+
}
|
|
138
|
+
if (context !== undefined) {
|
|
139
|
+
await buildHandoff({ context });
|
|
140
|
+
task = { ...task, input_context: { ...task.input_context, context } };
|
|
141
|
+
}
|
|
142
|
+
const claim = await claimTaskRun(taskId, task.run_count ?? 0);
|
|
143
|
+
if (!claim) throw coded("worker_active", `task ${taskId} is active or already claimed by another dispatcher; wait for it to settle`);
|
|
144
|
+
try {
|
|
145
|
+
return await resumeClaimed(task, { prompt, rebaseOnto, acceptance });
|
|
146
|
+
} finally {
|
|
147
|
+
await releaseTaskRun(taskId, claim);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function recoverEligibleRuns() {
|
|
152
|
+
const recovered = [];
|
|
153
|
+
for (const task of await readTasks()) {
|
|
154
|
+
if (task.guard_policy?.preflight) continue;
|
|
155
|
+
if ((task.run_count ?? 0) !== 1 || !task.thread_id
|
|
156
|
+
|| !(task.run_evidence?.run === 1 || (task.run_host_pid && task.started_at)) || !task.guard_policy
|
|
157
|
+
|| !(task.status === "lost" || task.attention_reason === "no_work" || task.attention_reason === "invalid_report")
|
|
158
|
+
|| ["blocked", "paused", "budget_limited", "usage_limited"].includes(task.goal_status)
|
|
159
|
+
|| /401|403|unauthori[sz]ed|not logged|permission denied|approval|rate.?limit|429/i.test(task.error ?? "")
|
|
160
|
+
|| /time_limit|quota/.test(`${task.attention_reason ?? ""} ${task.error ?? ""}`)
|
|
161
|
+
|| await isPidAlive(task.pid) || await isPidAlive(task.run_host_pid)) continue;
|
|
162
|
+
const session = task.session_id ? await getSession(task.session_id) : null;
|
|
163
|
+
if (session?.approval_state === "waiting_user") continue;
|
|
164
|
+
try {
|
|
165
|
+
const result = await resumeCodexWorker({ taskId: task.id,
|
|
166
|
+
prompt: task.attention_reason === "invalid_report"
|
|
167
|
+
? "Your run finished, but the final message was not the required bare JSON report. Do not redo the work and do not edit files: reply with ONLY the JSON object with result (string), verification (string[]) and not_done (string[]), describing what you already did. No code fences, nothing before or after it."
|
|
168
|
+
: `One automatic recovery after ${task.attention_reason ?? task.status}. Original task: ${task.prompt}\nContinue from files already present; do not repeat completed edits. Make concrete progress, run declared checks, and report remaining blockers accurately. This is the only automatic retry.` });
|
|
169
|
+
const event = { type: "supervisor.recovery", automatic: true, from_run: 1, to_run: result.run_count,
|
|
170
|
+
reason: task.attention_reason ?? task.status, started_at: new Date().toISOString() };
|
|
171
|
+
await appendTaskEvent(task.id, event);
|
|
172
|
+
await appendFile(task.run_log, `${JSON.stringify(event)}\n`);
|
|
173
|
+
recovered.push({ id: task.id, run: result.run_count, reason: event.reason });
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (!["worker_active", "session_waiting_user"].includes(error.code)) {
|
|
176
|
+
await appendTaskEvent(task.id, { type: "supervisor.recovery_refused", reason: error.code ?? "resume_failed" });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return recovered;
|
|
181
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
|
|
2
|
+
export const processes = new Map();
|
|
3
|
+
// taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
|
|
4
|
+
export const acceptanceRuns = new Map();
|
|
5
|
+
export const cancelledTasks = new Set();
|
|
6
|
+
export const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
7
|
+
export const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
export const RUN_HOST_STARTUP_TIMEOUT_MS = process.platform === "win32" ? 120000 : 30000;
|
|
9
|
+
export const WORKTREE_LOCK_TIMEOUT_MS = 120000;
|
|
10
|
+
|
|
11
|
+
export function failedStart(record, reason) {
|
|
12
|
+
const now = new Date().toISOString();
|
|
13
|
+
return {
|
|
14
|
+
ok: false,
|
|
15
|
+
record: {
|
|
16
|
+
...record,
|
|
17
|
+
status: "failed",
|
|
18
|
+
phase: null,
|
|
19
|
+
pid: null,
|
|
20
|
+
error: reason,
|
|
21
|
+
attention_reason: "start_failed",
|
|
22
|
+
completed_at: now,
|
|
23
|
+
updated_at: now
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import "./compose.js";
|
|
2
|
+
import { readPreflightResult } from "../domain/worker-preflight.js";
|
|
3
|
+
import { TERMINAL_STATUSES } from "../domain/status.js";
|
|
4
|
+
import { isPidAlive } from "../infra/store/tasks.js";
|
|
5
|
+
|
|
6
|
+
// A terminal status is written in two steps. Codex's turn.completed event
|
|
7
|
+
// flips status to completed while the process is still alive and exit_code is
|
|
8
|
+
// still null; the process exit then writes exit_code. A wait that returned on
|
|
9
|
+
// the first step handed the caller a snapshot with exit_code: null, and the
|
|
10
|
+
// next read said 0 - two answers for one worker. A row counts as settled once
|
|
11
|
+
// the exit is recorded, or once nobody is left to record it.
|
|
12
|
+
export function isSettled(task) {
|
|
13
|
+
if (!TERMINAL_STATUSES.has(task.status)) return false;
|
|
14
|
+
if (task.attention_reason === "start_failed") return true;
|
|
15
|
+
if (task.guard_policy?.preflight && readPreflightResult(task).status === "passed") return true;
|
|
16
|
+
if (task.status !== "completed" && task.status !== "failed") return true;
|
|
17
|
+
// Acceptance is running in the supervisor process that owned the worker;
|
|
18
|
+
// the codex pid is already dead, so that process is what to wait on.
|
|
19
|
+
if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
|
|
20
|
+
if (["interrupted", "cancelled"].includes(task.acceptance_results?.status)) {
|
|
21
|
+
return task.exit_code !== null && task.exit_code !== undefined;
|
|
22
|
+
}
|
|
23
|
+
if (task.exit_code !== null && task.exit_code !== undefined) return true;
|
|
24
|
+
// A dead Codex pid does not prove that its owner's close handler finished
|
|
25
|
+
// draining the stream and writing the exit status. Leave the half-written
|
|
26
|
+
// row for reconciliation after a short grace period, never return it.
|
|
27
|
+
return false;
|
|
28
|
+
}
|