codex-supervisor-mcp 0.13.5 → 0.13.6

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.
Files changed (101) hide show
  1. package/package.json +18 -63
  2. package/src/{acceptance.js → app/acceptance.js} +54 -68
  3. package/src/app/cancel.js +60 -0
  4. package/src/{cleanup-plan.js → app/cleanup-plan.js} +11 -12
  5. package/src/app/compose.js +7 -0
  6. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  7. package/src/app/dispatch.js +396 -0
  8. package/src/app/followup.js +98 -0
  9. package/src/app/land-chain.js +124 -0
  10. package/src/app/landing.js +357 -0
  11. package/src/app/ownership.js +57 -0
  12. package/src/app/rebase.js +216 -0
  13. package/src/app/resume.js +164 -0
  14. package/src/app/run-state.js +26 -0
  15. package/src/app/settled.js +28 -0
  16. package/src/{side-chat.js → app/side-chat.js} +79 -265
  17. package/src/app/sse.js +20 -0
  18. package/src/app/start-run.js +77 -0
  19. package/src/app/verify-push.js +119 -0
  20. package/src/app/worktree-setup.js +176 -0
  21. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  22. package/src/domain/acceptance-spec.js +30 -0
  23. package/src/domain/command-outcome.js +6 -0
  24. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  25. package/src/domain/side-turn-view.js +73 -0
  26. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  27. package/src/infra/git.js +30 -0
  28. package/src/infra/process.js +59 -0
  29. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  30. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  31. package/src/infra/store/db.js +265 -0
  32. package/src/infra/store/events.js +146 -0
  33. package/src/infra/store/facts.js +338 -0
  34. package/src/infra/store/reconcile.js +172 -0
  35. package/src/infra/store/records.js +160 -0
  36. package/src/infra/store/runner-readers.js +16 -0
  37. package/src/infra/store/schema.js +306 -0
  38. package/src/infra/store/sessions.js +138 -0
  39. package/src/infra/store/tasks.js +307 -0
  40. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  41. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  42. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  43. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  44. package/src/{worktree.js → infra/worktree.js} +56 -41
  45. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  46. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  47. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  48. package/src/{setup.js → interface/bin/setup.js} +7 -6
  49. package/src/{stage.js → interface/bin/stage.js} +1 -1
  50. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  51. package/src/interface/mcp/meta.js +7 -0
  52. package/src/interface/mcp/result.js +34 -0
  53. package/src/interface/mcp/schemas.js +24 -0
  54. package/src/interface/mcp/server.js +94 -0
  55. package/src/interface/mcp/tools/delivery.js +197 -0
  56. package/src/interface/mcp/tools/dispatch.js +267 -0
  57. package/src/interface/mcp/tools/facts.js +239 -0
  58. package/src/interface/mcp/tools/overview.js +202 -0
  59. package/src/interface/mcp/tools/poll.js +62 -0
  60. package/src/interface/mcp/tools/results.js +270 -0
  61. package/src/interface/mcp/tools/review.js +135 -0
  62. package/src/interface/mcp/tools/wait.js +145 -0
  63. package/src/interface/mcp/update-state.js +34 -0
  64. package/src/interface/mcp/views/overview.js +183 -0
  65. package/src/interface/mcp/views/task.js +223 -0
  66. package/src/interface/web/app.js +226 -0
  67. package/src/interface/web/views.js +224 -0
  68. package/src/mcp-server.js +3 -2223
  69. package/src/run-host/entry.js +23 -0
  70. package/src/run-host/finalize.js +236 -0
  71. package/src/run-host/launch.js +63 -0
  72. package/src/run-host/live-run.js +73 -0
  73. package/src/run-host/outcome-facts.js +61 -0
  74. package/src/run-host/streams.js +76 -0
  75. package/src/run-host/track.js +128 -0
  76. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  77. package/src/runners/codex/chat-chunks.js +97 -0
  78. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  79. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  80. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  81. package/src/codex-runner.js +0 -1586
  82. package/src/landing.js +0 -507
  83. package/src/task-store.js +0 -1800
  84. package/src/web-app.js +0 -425
  85. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  86. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  87. /package/src/{prompt.js → domain/prompt.js} +0 -0
  88. /package/src/{status.js → domain/status.js} +0 -0
  89. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  90. /package/src/{truncate.js → domain/truncate.js} +0 -0
  91. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  92. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  93. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  94. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  95. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  96. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  97. /package/src/{external-output.js → infra/external-output.js} +0 -0
  98. /package/src/{handoff.js → infra/handoff.js} +0 -0
  99. /package/src/{paths.js → infra/paths.js} +0 -0
  100. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  101. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,357 @@
1
+ // Landing a worker's commits where they were dispatched from.
2
+ //
3
+ // A worker commits on codex/<taskId> inside its own worktree. Getting that
4
+ // work onto the branch the main thread integrates on used to be the main
5
+ // thread's job, one cherry-pick per step, dozens of times per batch. This
6
+ // does the same thing with the same guard rails a careful person would use:
7
+ // the target must be clean, it is never switched to another branch, and a
8
+ // conflict leaves nothing half-applied.
9
+ import { findOutsideOwnedChanges } from "../domain/owned-changes.js";
10
+ import { runGit } from "../infra/git.js";
11
+ import { filterWorkspaceSetupChanges, parsePorcelainLine, readWorktreeChanges, readWorktreeDiff, resolveWorktreeBase, workspaceSetupIgnorePaths, worktreeRef } from "../infra/worktree.js";
12
+ import { existsSync } from "node:fs";
13
+ import { join, relative } from "node:path";
14
+
15
+ const PATCH_ID_MAX_BUFFER = 256 * 1024 * 1024;
16
+
17
+ // A commit needs a committer. On a machine where git has no user.name or
18
+ // user.email (CI runners, a fresh box, a GUI-launched MCP with no HOME
19
+ // config), cherry-pick and commit both die with "empty ident name", so a
20
+ // stand-in identity is supplied through the environment for that one
21
+ // directory. An identity git already has is used untouched.
22
+ const FALLBACK_IDENTITY = { name: "codex-supervisor", email: "codex-supervisor@localhost" };
23
+ const identityCache = new Map();
24
+
25
+ export function identityEnv(cwd) {
26
+ if (identityCache.has(cwd)) return identityCache.get(cwd);
27
+ let name = "";
28
+ let email = "";
29
+ try {
30
+ name = runGit(cwd, ["config", "user.name"], { stderr: "ignore", timeout: 10000 });
31
+ } catch {
32
+ // unset
33
+ }
34
+ try {
35
+ email = runGit(cwd, ["config", "user.email"], { stderr: "ignore", timeout: 10000 });
36
+ } catch {
37
+ // unset
38
+ }
39
+ const env = {};
40
+ if (!name || !email) {
41
+ env.GIT_AUTHOR_NAME = name || FALLBACK_IDENTITY.name;
42
+ env.GIT_AUTHOR_EMAIL = email || FALLBACK_IDENTITY.email;
43
+ env.GIT_COMMITTER_NAME = name || FALLBACK_IDENTITY.name;
44
+ env.GIT_COMMITTER_EMAIL = email || FALLBACK_IDENTITY.email;
45
+ }
46
+ identityCache.set(cwd, env);
47
+ return env;
48
+ }
49
+
50
+ export function git(cwd, args, { timeout = 60000, input = null, maxBuffer = 1024 * 1024, encoding = "utf8" } = {}) {
51
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(cwd) };
52
+ return runGit(cwd, args, { timeout, input, maxBuffer, encoding, env, rawPaths: true, trim: false });
53
+ }
54
+
55
+ export function lines(output) {
56
+ return output.split("\n").map((line) => line.trim()).filter(Boolean);
57
+ }
58
+
59
+ // Porcelain lines carry their status in the first two columns, so they must
60
+ // not be trimmed before parsing.
61
+ function porcelainPaths(output) {
62
+ return output.split("\n").filter((line) => line.length > 3).map(parsePorcelainLine).filter(Boolean);
63
+ }
64
+
65
+ function patchIdsInRange(cwd, range) {
66
+ const patches = git(cwd, ["log", "--no-merges", "--format=commit %H", "--patch", "--binary", range], {
67
+ timeout: 2 * 60 * 1000,
68
+ encoding: "buffer",
69
+ maxBuffer: PATCH_ID_MAX_BUFFER
70
+ });
71
+ const output = git(cwd, ["patch-id", "--stable"], {
72
+ input: patches,
73
+ timeout: 2 * 60 * 1000,
74
+ maxBuffer: PATCH_ID_MAX_BUFFER
75
+ });
76
+ const ids = new Map();
77
+ for (const line of lines(output)) {
78
+ const [id, sha] = line.split(/\s+/);
79
+ if (id && sha && !/^0+$/.test(id)) ids.set(sha, id);
80
+ }
81
+ return ids;
82
+ }
83
+
84
+ // `git rev-list --cherry-pick` proves an original worker commit is not
85
+ // pending, but it does not name the target-side commit that carried the same
86
+ // patch. Lifecycle fields need that target-side SHA: using the target's
87
+ // current HEAD would point at unrelated later work and make cleanup/push
88
+ // verification lie.
89
+ function matchAlreadyLanded(cwd, target, targetHead, base, originals, workerHead) {
90
+ if (originals.length === 0) return { matches: [], complete: true, head: null };
91
+ const targetOrder = lines(git(target, ["rev-list", `${base}..${targetHead}`]));
92
+ const targetCommits = new Set(targetOrder);
93
+ const needsPatchIds = originals.some((original) => !targetCommits.has(original));
94
+ const targetByPatch = new Map([...(needsPatchIds ? patchIdsInRange(target, `${base}..${targetHead}`) : [])]
95
+ .map(([sha, id]) => [id, sha]));
96
+ const originalPatches = needsPatchIds ? patchIdsInRange(cwd, `${base}..${workerHead}`) : new Map();
97
+ const matches = originals.flatMap((original) => {
98
+ if (targetCommits.has(original)) return [{ original, target: original }];
99
+ const id = originalPatches.get(original);
100
+ const matched = id ? targetByPatch.get(id) : null;
101
+ return matched ? [{ original, target: matched }] : [];
102
+ });
103
+ const matchedTargets = new Set(matches.map((match) => match.target));
104
+ const head = targetOrder.find((sha) => matchedTargets.has(sha)) ?? null;
105
+ const complete = matches.length === originals.length && matches.every((match) => {
106
+ if (match.target === head) return true;
107
+ try { git(target, ["merge-base", "--is-ancestor", match.target, head]); return true; }
108
+ catch { return false; }
109
+ });
110
+ return { matches, complete, head: complete ? head : null };
111
+ }
112
+
113
+ function currentBranch(cwd) {
114
+ const name = git(cwd, ["symbolic-ref", "--short", "-q", "HEAD"]).trim();
115
+ return name || null;
116
+ }
117
+
118
+ function hasStagedChanges(cwd) {
119
+ try {
120
+ git(cwd, ["diff", "--cached", "--quiet"]);
121
+ return false;
122
+ } catch (error) {
123
+ if (error.status === 1) return true;
124
+ throw error;
125
+ }
126
+ }
127
+
128
+ // Lands task's commits onto the current branch of its dispatch directory
129
+ // (task.project_root: the row's cwd is the worktree the worker ran in).
130
+ // `onto`, when given, must name that branch: it is a guard, not a switch.
131
+ //
132
+ // `commitMessage` commits what the worker left uncommitted in its worktree
133
+ // first, as one commit on codex/<id>. A worker in Codex's workspace-write
134
+ // sandbox cannot commit at all (the sandbox keeps .git read-only), so this
135
+ // is how "one step, one commit" is kept without giving workers full access.
136
+ //
137
+ // Returns { landed: [{ sha, original, subject }], onto, head } on success;
138
+ // otherwise { error, reason, ... } with nothing changed in the target.
139
+ // The dispatcher's own checks are the gate. A failed run is refused until
140
+ // it passes; a run that was cut short is refused until it has run.
141
+ function acceptanceRefusal(task) {
142
+ const acceptance = task.acceptance_results ?? null;
143
+ if (!acceptance) return null;
144
+ const failing = (acceptance.checks ?? []).find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out) ?? null;
145
+ if (acceptance.passed === false) {
146
+ return {
147
+ error: "acceptance_failed",
148
+ 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.`,
149
+ acceptance: { status: acceptance.status, passed: false, checks: acceptance.checks ?? [], error: acceptance.error ?? null }
150
+ };
151
+ }
152
+ if (acceptance.status === "running" || acceptance.status === "interrupted" || acceptance.status === "cancelled") {
153
+ return {
154
+ error: "acceptance_not_run",
155
+ 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.`,
156
+ acceptance: { status: acceptance.status, passed: null }
157
+ };
158
+ }
159
+ return null;
160
+ }
161
+
162
+ // The integration checkout must exist, be on the expected branch and be clean.
163
+ function targetState(task, onto) {
164
+ const target = task.project_root;
165
+ if (!task.worktree_path || !existsSync(task.worktree_path)) {
166
+ return { error: "no_worktree", reason: "this worker has no worktree (it ran in place), so there is nothing on a codex/ branch to land" };
167
+ }
168
+ if (!target || !existsSync(target)) {
169
+ return { error: "no_target", reason: `the directory the worker was dispatched from (${target}) no longer exists` };
170
+ }
171
+ let branch;
172
+ try {
173
+ branch = currentBranch(target);
174
+ } catch (error) {
175
+ return { error: "no_target", reason: `${target} is not a git checkout: ${error.message.split("\n")[0]}` };
176
+ }
177
+ if (!branch) return { error: "detached_target", reason: `${target} has a detached HEAD; check out the branch you integrate on first` };
178
+ if (onto && onto !== branch) {
179
+ return { error: "wrong_branch", reason: `${target} is on ${branch}, not ${onto}; this tool never switches branches for you`, current_branch: branch };
180
+ }
181
+ const dirty = porcelainPaths(git(target, ["status", "--porcelain", "--untracked-files=no"]));
182
+ if (dirty.length > 0) {
183
+ return { error: "dirty_target", reason: `${target} has uncommitted changes; commit or stash them before landing`, dirty_files: dirty };
184
+ }
185
+ return { branch };
186
+ }
187
+
188
+ function ownershipRefusal(task) {
189
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 0, ignorePaths: workspaceSetupIgnorePaths(task) });
190
+ if (diff.error) return { error: "ownership_unverified", reason: "cannot prove the complete diff before landing", diff_error: diff.error };
191
+ const paths = [...filterWorkspaceSetupChanges(task, readWorktreeChanges(task.worktree_path, worktreeRef(task))),
192
+ ...diff.files.flatMap((file) => [file.path, file.from].filter(Boolean).map((path) => join(task.worktree_path, path)))];
193
+ const { outside } = findOutsideOwnedChanges(task, [...new Set(paths)]);
194
+ 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)) };
195
+ return null;
196
+ }
197
+
198
+ // Commits the worker's uncommitted edits as one commit when a message is
199
+ // given. A workspace-write worker cannot commit: its sandbox keeps .git
200
+ // read-only.
201
+ function commitForWorker(task, commits, { commitMessage, allowOutsideOwned }) {
202
+ let uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
203
+ let committedForWorker = null;
204
+ if (uncommitted.length === 0 || !commitMessage) return { uncommitted, committedForWorker };
205
+ try {
206
+ if (allowOutsideOwned) git(task.worktree_path, ["add", "-A"]);
207
+ else {
208
+ const owned = findOutsideOwnedChanges(task, []).mapping.map((entry) => relative(task.worktree_path, entry.worker));
209
+ if (owned.length === 0) return { error: "outside_owned_paths", reason: "the worker left uncommitted changes but owns no landable path" };
210
+ git(task.worktree_path, ["add", "-A", "--", ...owned]);
211
+ }
212
+ if (hasStagedChanges(task.worktree_path)) {
213
+ git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
214
+ committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
215
+ commits.push(committedForWorker);
216
+ }
217
+ uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
218
+ } catch (error) {
219
+ const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-3).join("\n");
220
+ return { error: "commit_failed", reason: `could not commit the worker's uncommitted edits in ${task.worktree_path}: ${tail || error.message.split("\n")[0]}`, uncommitted };
221
+ }
222
+ return { uncommitted, committedForWorker };
223
+ }
224
+
225
+ // Commits whose patch is already on the target (a previous land, or the
226
+ // main thread cherry-picked by hand) are skipped by patch id; picking
227
+ // them again produces an empty commit and git stops with an error.
228
+ function splitAlreadyLanded(task, target, targetHead, base, commits) {
229
+ const proof = { pending: commits, alreadyLanded: [], matches: [], matchedHead: null, matchComplete: true, matchError: null };
230
+ if (commits.length === 0) return proof;
231
+ try {
232
+ const workerHead = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
233
+ const pending = new Set(lines(git(target, ["rev-list", "--cherry-pick", "--right-only", `${targetHead}...${workerHead}`])));
234
+ proof.alreadyLanded = commits.filter((sha) => !pending.has(sha));
235
+ proof.pending = commits.filter((sha) => pending.has(sha));
236
+ try {
237
+ ({ matches: proof.matches, complete: proof.matchComplete, head: proof.matchedHead } = matchAlreadyLanded(
238
+ task.worktree_path, target, targetHead, base, proof.alreadyLanded, workerHead
239
+ ));
240
+ } catch (error) {
241
+ proof.matchComplete = false;
242
+ proof.matchError = gitTail(error);
243
+ }
244
+ } catch (error) {
245
+ return { error: "landing_proof_failed", reason: "could not prove which worker commits remain unlanded", match_error: gitTail(error) };
246
+ }
247
+ return proof;
248
+ }
249
+
250
+ function nothingToLand(proof, { branch, target, uncommitted, base }) {
251
+ if (proof.pending.length > 0) return null;
252
+ if (proof.alreadyLanded.length > 0) {
253
+ return {
254
+ error: "nothing_to_land",
255
+ reason: `every commit on this worker's branch is already on ${branch} (landed before, by patch); nothing new to land`,
256
+ already_landed: proof.alreadyLanded,
257
+ already_landed_matches: proof.matches,
258
+ matched_head: proof.matchedHead,
259
+ match_error: proof.matchError,
260
+ match_complete: proof.matchComplete,
261
+ onto: branch,
262
+ target,
263
+ uncommitted,
264
+ base_commit: base
265
+ };
266
+ }
267
+ return {
268
+ error: "nothing_to_land",
269
+ reason: uncommitted.length > 0
270
+ ? "the worker made no commits on its branch (a workspace-write worker cannot: the sandbox keeps .git read-only); pass commitMessage to commit its edits as one commit and land that"
271
+ : "the worker made no commits and left no edits on its branch",
272
+ uncommitted,
273
+ base_commit: base
274
+ };
275
+ }
276
+
277
+ // Cherry-picks onto the target; a conflict aborts and leaves the target where it was.
278
+ function cherryPick(target, commits, { base, uncommitted }) {
279
+ try {
280
+ git(target, ["cherry-pick", "--allow-empty-message", ...commits], { timeout: 10 * 60 * 1000 });
281
+ return null;
282
+ } catch (error) {
283
+ let conflicts = [];
284
+ try {
285
+ conflicts = lines(git(target, ["diff", "--name-only", "--diff-filter=U"]));
286
+ } catch {
287
+ // no conflict list, still abort
288
+ }
289
+ try {
290
+ git(target, ["cherry-pick", "--abort"]);
291
+ } catch {
292
+ // nothing in progress to abort
293
+ }
294
+ const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-4).join("\n");
295
+ return {
296
+ error: "conflict",
297
+ reason: conflicts.length > 0 ? `cherry-pick stopped on a conflict; ${target} was reset to where it was` : `cherry-pick failed; ${target} was reset to where it was`,
298
+ conflicts,
299
+ git: tail,
300
+ base_commit: base,
301
+ commits,
302
+ uncommitted
303
+ };
304
+ }
305
+ }
306
+
307
+ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcceptance = false, allowOutsideOwned = false } = {}) {
308
+ const target = task.project_root;
309
+ const refused = ignoreAcceptance ? null : acceptanceRefusal(task);
310
+ if (refused) return refused;
311
+ const state = targetState(task, onto);
312
+ if (state.error) return state;
313
+ const { branch } = state;
314
+
315
+ const base = resolveWorktreeBase(task.worktree_path, worktreeRef(task));
316
+ if (!base) return { error: "no_base_commit", reason: "the commit this worker started from is unknown, so its commits cannot be told apart" };
317
+ const outside = allowOutsideOwned ? null : ownershipRefusal(task);
318
+ if (outside) return outside;
319
+ let commits;
320
+ try {
321
+ commits = lines(git(task.worktree_path, ["rev-list", "--reverse", `${base}..HEAD`]));
322
+ } catch (error) {
323
+ return { error: "no_base_commit", reason: `the base ${base} no longer resolves in the worktree: ${error.message.split("\n")[0]}` };
324
+ }
325
+ const committed = commitForWorker(task, commits, { commitMessage, allowOutsideOwned });
326
+ if (committed.error) return committed;
327
+ const { uncommitted, committedForWorker } = committed;
328
+
329
+ const targetHead = git(target, ["rev-parse", "HEAD"]).trim();
330
+ const proof = splitAlreadyLanded(task, target, targetHead, base, commits);
331
+ if (proof.error) return proof;
332
+ const nothing = nothingToLand(proof, { branch, target, uncommitted, base });
333
+ if (nothing) return nothing;
334
+ const conflict = cherryPick(target, proof.pending, { base, uncommitted });
335
+ if (conflict) return conflict;
336
+
337
+ const landed = lines(git(target, ["rev-list", "--reverse", `${targetHead}..HEAD`]));
338
+ const subjects = lines(git(target, ["log", "--format=%H%x09%s", `${targetHead}..HEAD`]));
339
+ const subjectOf = new Map(subjects.map((line) => line.split("\t")).map(([sha, subject]) => [sha, subject]));
340
+ return {
341
+ onto: branch,
342
+ target,
343
+ base_commit: base,
344
+ head: landed.at(-1) ?? targetHead,
345
+ landed: landed.map((sha, index) => ({ sha, original: proof.pending[index] ?? null, subject: subjectOf.get(sha) ?? null })),
346
+ already_landed: proof.alreadyLanded,
347
+ already_landed_matches: proof.matches,
348
+ match_error: proof.matchError,
349
+ match_complete: proof.matchComplete,
350
+ committed_for_worker: committedForWorker,
351
+ uncommitted
352
+ };
353
+ }
354
+
355
+ export function gitTail(error) {
356
+ return `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-4).join("\n") || error.message.split("\n")[0];
357
+ }
@@ -0,0 +1,57 @@
1
+ import "./compose.js";
2
+ import { readActiveTasks } from "../infra/store/tasks.js";
3
+ import { resolve, sep } from "node:path";
4
+
5
+ export function normalizeOwnedPaths(ownedPaths, projectRoot) {
6
+ if (!Array.isArray(ownedPaths)) return [];
7
+ return Array.from(new Set(ownedPaths.map((entry) => resolve(projectRoot, String(entry).trim()))));
8
+ }
9
+
10
+ function pathOverlaps(left, right) {
11
+ // Windows paths are case-insensitive and may mix separators, so compare on a
12
+ // normalized form there. macOS and Linux keep the exact previous comparison -
13
+ // a backslash is a legal filename character on those platforms.
14
+ const windows = process.platform === "win32";
15
+ const normalize = (value) => (windows ? value.replace(/[\\/]+/g, sep).toLowerCase() : value);
16
+ const mine = normalize(left);
17
+ const theirs = normalize(right);
18
+ if (mine === theirs) return true;
19
+ const minePrefix = mine.endsWith(sep) ? mine : `${mine}${sep}`;
20
+ const theirsPrefix = theirs.endsWith(sep) ? theirs : `${theirs}${sep}`;
21
+ return minePrefix.startsWith(theirsPrefix) || theirsPrefix.startsWith(minePrefix);
22
+ }
23
+
24
+ // Two workers claiming overlapping paths will collide when their branches are
25
+ // merged, so the second dispatch is refused before any worktree is created.
26
+ export async function findOwnershipConflicts(ownedPaths, { excludeTaskId = null } = {}) {
27
+ if (!ownedPaths || ownedPaths.length === 0) return [];
28
+ const activeTasks = await readActiveTasks();
29
+ const conflicts = [];
30
+ for (const task of activeTasks) {
31
+ if (task.id === excludeTaskId) continue;
32
+ const theirs = Array.isArray(task.owned_paths) ? task.owned_paths : [];
33
+ const overlap = [];
34
+ for (const mine of ownedPaths) {
35
+ for (const other of theirs) {
36
+ if (pathOverlaps(mine, other)) overlap.push({ incoming: mine, existing: other });
37
+ }
38
+ }
39
+ if (overlap.length > 0) {
40
+ conflicts.push({
41
+ task_id: task.id,
42
+ title: task.title,
43
+ status: task.status,
44
+ overlapping_paths: overlap
45
+ });
46
+ }
47
+ }
48
+ return conflicts;
49
+ }
50
+
51
+ export function ownershipConflictError(conflicts) {
52
+ const owners = conflicts.map((conflict) => conflict.task_id).join(", ");
53
+ const error = new Error(`ownedPaths overlap with active worker(s): ${owners}`);
54
+ error.code = "ownership_conflict";
55
+ error.conflicts = conflicts;
56
+ return error;
57
+ }
@@ -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
+ }