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.
Files changed (109) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/package.json +19 -63
  4. package/skills/codex-supervisor/SKILL.md +5 -4
  5. package/src/{acceptance.js → app/acceptance.js} +54 -68
  6. package/src/app/auto-cleanup.js +90 -0
  7. package/src/app/cancel.js +60 -0
  8. package/src/app/cleanup-facts.js +96 -0
  9. package/src/app/cleanup-plan.js +164 -0
  10. package/src/app/compose.js +7 -0
  11. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  12. package/src/app/dispatch.js +396 -0
  13. package/src/app/followup.js +98 -0
  14. package/src/app/land-chain.js +133 -0
  15. package/src/app/landing.js +357 -0
  16. package/src/app/ownership.js +57 -0
  17. package/src/app/rebase.js +216 -0
  18. package/src/app/restore-worktree.js +50 -0
  19. package/src/app/resume.js +181 -0
  20. package/src/app/run-state.js +26 -0
  21. package/src/app/settled.js +28 -0
  22. package/src/{side-chat.js → app/side-chat.js} +82 -265
  23. package/src/app/sse.js +20 -0
  24. package/src/app/start-run.js +77 -0
  25. package/src/app/verify-push.js +114 -0
  26. package/src/app/worktree-setup.js +176 -0
  27. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  28. package/src/domain/acceptance-spec.js +30 -0
  29. package/src/domain/cleanup-policy.js +44 -0
  30. package/src/domain/command-outcome.js +6 -0
  31. package/src/{overview-delta.js → domain/overview-delta.js} +7 -3
  32. package/src/domain/side-turn-view.js +73 -0
  33. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  34. package/src/{cleanup-hint.js → infra/cleanup-hint.js} +7 -8
  35. package/src/infra/git.js +30 -0
  36. package/src/infra/process.js +59 -0
  37. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  38. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  39. package/src/infra/store/db.js +265 -0
  40. package/src/infra/store/events.js +146 -0
  41. package/src/infra/store/facts.js +338 -0
  42. package/src/infra/store/reconcile.js +172 -0
  43. package/src/infra/store/records.js +171 -0
  44. package/src/infra/store/runner-readers.js +16 -0
  45. package/src/infra/store/schema.js +306 -0
  46. package/src/infra/store/sessions.js +138 -0
  47. package/src/infra/store/tasks.js +337 -0
  48. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  49. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  50. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  51. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  52. package/src/{worktree.js → infra/worktree.js} +56 -41
  53. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  54. package/src/{cleanup.js → interface/bin/cleanup.js} +4 -3
  55. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  56. package/src/{setup.js → interface/bin/setup.js} +7 -6
  57. package/src/{stage.js → interface/bin/stage.js} +1 -1
  58. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  59. package/src/interface/mcp/meta.js +7 -0
  60. package/src/interface/mcp/result.js +34 -0
  61. package/src/interface/mcp/schemas.js +24 -0
  62. package/src/interface/mcp/server.js +94 -0
  63. package/src/interface/mcp/tools/delivery.js +197 -0
  64. package/src/interface/mcp/tools/dispatch.js +267 -0
  65. package/src/interface/mcp/tools/facts.js +239 -0
  66. package/src/interface/mcp/tools/overview.js +202 -0
  67. package/src/interface/mcp/tools/poll.js +58 -0
  68. package/src/interface/mcp/tools/results.js +284 -0
  69. package/src/interface/mcp/tools/review.js +135 -0
  70. package/src/interface/mcp/tools/wait.js +145 -0
  71. package/src/interface/mcp/update-state.js +34 -0
  72. package/src/interface/mcp/views/overview.js +183 -0
  73. package/src/interface/mcp/views/task.js +223 -0
  74. package/src/interface/web/app.js +226 -0
  75. package/src/interface/web/views.js +224 -0
  76. package/src/mcp-server.js +3 -2223
  77. package/src/run-host/entry.js +23 -0
  78. package/src/run-host/finalize.js +236 -0
  79. package/src/run-host/launch.js +63 -0
  80. package/src/run-host/live-run.js +73 -0
  81. package/src/run-host/outcome-facts.js +61 -0
  82. package/src/run-host/streams.js +76 -0
  83. package/src/run-host/track.js +128 -0
  84. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  85. package/src/runners/codex/chat-chunks.js +97 -0
  86. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  87. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  88. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  89. package/src/cleanup-plan.js +0 -158
  90. package/src/codex-runner.js +0 -1586
  91. package/src/landing.js +0 -507
  92. package/src/task-store.js +0 -1800
  93. package/src/web-app.js +0 -425
  94. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  95. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  96. /package/src/{prompt.js → domain/prompt.js} +0 -0
  97. /package/src/{status.js → domain/status.js} +0 -0
  98. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  99. /package/src/{truncate.js → domain/truncate.js} +0 -0
  100. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  101. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  102. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  103. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  104. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  105. /package/src/{external-output.js → infra/external-output.js} +0 -0
  106. /package/src/{handoff.js → infra/handoff.js} +0 -0
  107. /package/src/{paths.js → infra/paths.js} +0 -0
  108. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  109. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,98 @@
1
+ import "./compose.js";
2
+ import { readTaskEvents } from "../infra/store/events.js";
3
+ import { getTask } from "../infra/store/tasks.js";
4
+ import { createCodexWorker } from "./dispatch.js";
5
+ import { resolveCommit } from "./worktree-setup.js";
6
+
7
+ // A follow-up starts from the parent's branch while the parent has not landed,
8
+ // so commits made there are present. Uncommitted parent edits stay in the
9
+ // parent worktree and are deliberately not smuggled across task boundaries.
10
+ function followupBaseRef(parent, baseRef) {
11
+ if (baseRef || parent.landed_at || !parent.project_root || !parent.worktree_path) return baseRef ?? null;
12
+ try {
13
+ resolveCommit(parent.project_root, `codex/${parent.id}`);
14
+ return `codex/${parent.id}`;
15
+ } catch {
16
+ const error = new Error(`parent checkpoint codex/${parent.id} is unavailable; restore it or choose an explicit baseRef`);
17
+ error.code = "followup_checkpoint_missing";
18
+ throw error;
19
+ }
20
+ }
21
+
22
+ function followupTaskText(parent, recentEvents, followupPrompt) {
23
+ return [
24
+ "You are continuing a previous Codex worker run.",
25
+ "",
26
+ `Parent task ID: ${parent.id}`,
27
+ `Parent status: ${parent.status}`,
28
+ `Parent title: ${parent.title}`,
29
+ "",
30
+ "Parent prompt:",
31
+ parent.prompt,
32
+ "",
33
+ "Parent recent summary:",
34
+ `- current_action: ${parent.current_action ?? "-"}`,
35
+ `- current_command: ${parent.current_command ?? "-"}`,
36
+ `- changed_files: ${(parent.changed_files ?? []).join(", ") || "-"}`,
37
+ `- last_message: ${parent.last_message ?? "-"}`,
38
+ "",
39
+ "Parent recent events:",
40
+ ...recentEvents.map((event) => `- ${JSON.stringify(event)}`),
41
+ "",
42
+ "Follow-up instruction:",
43
+ followupPrompt
44
+ ].join("\n");
45
+ }
46
+
47
+ // The guard and context a follow-up inherits from its parent unless given.
48
+ function inheritedPolicy(parent, given) {
49
+ const guard = parent.guard_policy;
50
+ return {
51
+ forbid: given.forbid ?? guard?.forbid ?? [],
52
+ allowedCommands: given.allowedCommands ?? guard?.allowedCommands ?? [],
53
+ context: given.context ?? parent.input_context?.context ?? [],
54
+ contracts: given.contracts ?? parent.input_context?.contracts ?? [],
55
+ externalOutputs: given.externalOutputs ?? guard?.externalOutputs ?? [],
56
+ networkAccess: given.networkAccess ?? guard?.networkAccess ?? false,
57
+ writableRoots: given.writableRoots ?? guard?.writableRoots ?? [],
58
+ maxRunMs: given.maxRunMs ?? guard?.maxRunMs ?? null,
59
+ maxTotalMs: given.maxTotalMs ?? guard?.maxTotalMs ?? null
60
+ };
61
+ }
62
+
63
+ export async function createFollowupWorker(options) {
64
+ const { taskId, followupPrompt, sessionId = null, sessionTitle = null, sessionNote = null, title, cwd, sandbox, model, reasoningEffort } = options;
65
+ const { ownedPaths, goal, baseRef, acceptance, acceptanceTimeoutMs, workspaceKind, inPlaceAuthorization, workspaceSetup } = options;
66
+ const parent = await getTask(taskId);
67
+ if (!parent) throw new Error(`task not found: ${taskId}`);
68
+ const inheritedBaseRef = followupBaseRef(parent, baseRef);
69
+ const recentEvents = await readTaskEvents(taskId, 20);
70
+ const inheritedAcceptance = parent.session_policy_revision == null ? parent.acceptance : parent.acceptance_local;
71
+
72
+ return createCodexWorker({
73
+ title: title ?? `Follow-up for ${parent.id}`,
74
+ task: followupTaskText(parent, recentEvents, followupPrompt),
75
+ sessionId: sessionId ?? parent.session_id ?? null,
76
+ sessionTitle,
77
+ sessionNote,
78
+ cwd: cwd ?? parent.project_root ?? parent.cwd,
79
+ sandbox: sandbox ?? parent.sandbox,
80
+ model: model ?? parent.model,
81
+ reasoningEffort: reasoningEffort ?? parent.reasoning_effort ?? "high",
82
+ skipGitRepoCheck: parent.skip_git_repo_check,
83
+ ownedPaths: ownedPaths ?? parent.owned_paths,
84
+ ...inheritedPolicy(parent, options),
85
+ goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
86
+ dependsOn: [],
87
+ followupOf: parent.id,
88
+ workspaceKind: workspaceKind ?? (parent.workspace_kind === "legacy" ? null : parent.workspace_kind),
89
+ inPlaceAuthorization: inPlaceAuthorization ?? parent.workspace_metadata?.in_place_authorization ?? null,
90
+ workspaceSetup: workspaceSetup ?? parent.workspace_metadata?.setup ?? null,
91
+ baseRef: inheritedBaseRef,
92
+ // Inherited unless given; the follow-up runs in a fresh worktree cut
93
+ // from the parent's codex/<parent> branch, so checks that depend on the
94
+ // parent checkpoint are valid before the parent has landed on the target.
95
+ acceptance: acceptance === undefined ? inheritedAcceptance : acceptance,
96
+ acceptanceTimeoutMs: acceptanceTimeoutMs ?? parent.acceptance_timeout_ms ?? null
97
+ });
98
+ }
@@ -0,0 +1,133 @@
1
+ import { ensureTaskWorktree } from "./restore-worktree.js";
2
+ import "./compose.js";
3
+ import { runGit } from "../infra/git.js";
4
+ import { appendTaskEvent } from "../infra/store/events.js";
5
+ import { getSession } from "../infra/store/sessions.js";
6
+ import { getTask, upsertTask } from "../infra/store/tasks.js";
7
+ import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
8
+ import { runIdFor } from "../infra/store/db.js";
9
+ import { updateWorkItemDelivery } from "../infra/store/records.js";
10
+ import { isSettled } from "./settled.js";
11
+ import { landWorker } from "./landing.js";
12
+ import { existsSync } from "node:fs";
13
+
14
+ export const git = (cwd, args) => runGit(cwd, args, { timeout: 60000 });
15
+
16
+ async function recordWorkerLanded(task, { head, branch, target, source = "git_land", alreadyLanded = [] }) {
17
+ const now = new Date().toISOString();
18
+ const landed = { ...task, landed_at: now, landed_head: head ?? null, landed_branch: branch ?? null, updated_at: now };
19
+ await upsertTask(landed);
20
+ await updateWorkItemDelivery(task.id, "landed");
21
+ const event = await appendTaskEvent(task.id, {
22
+ type: "supervisor.landed",
23
+ head: head ?? null,
24
+ branch: branch ?? null,
25
+ target: target ?? null,
26
+ source,
27
+ already_landed: alreadyLanded,
28
+ landed_at: now
29
+ }, { runId: runIdFor(task.id, task.run_count ?? 1), actor: "supervisor" });
30
+ const workItem = await getWorkItemForTask(task.id);
31
+ if (workItem && head) {
32
+ await recordFact({
33
+ workItemId: workItem.id,
34
+ scopeType: "work_item",
35
+ scopeId: workItem.id,
36
+ key: "landed",
37
+ value: { head, branch: branch ?? null, source },
38
+ state: "verified",
39
+ sourceEventId: event.id,
40
+ validForSha: head,
41
+ watchedPaths: task.owned_paths ?? [],
42
+ verifiedBy: `supervisor.${source}`
43
+ });
44
+ await recordFact({
45
+ workItemId: workItem.id,
46
+ scopeType: "dependency",
47
+ scopeId: workItem.id,
48
+ key: "landed_delivery_summary",
49
+ value: { task_id: task.id, landed_head: head, branch: branch ?? null, acceptance: task.acceptance_results?.passed === true ? "passed" : "not_configured_or_not_passed", source },
50
+ state: "verified",
51
+ sourceEventId: event.id,
52
+ validForSha: head,
53
+ watchedPaths: task.owned_paths ?? [],
54
+ verifiedBy: `supervisor.${source}`
55
+ });
56
+ }
57
+ return { landed, event };
58
+ }
59
+
60
+ export async function landOneWorkerTask(taskId, options = {}) {
61
+ const { onto = null, commitMessage = null, ignoreAcceptance = false, allowOutsideOwned = false, skipAlreadyLanded = false } = options;
62
+ const task = await getTask(taskId);
63
+ if (!task) return { error: "task_not_found", task_id: taskId };
64
+ if (task.workspace_kind && task.workspace_kind !== "legacy" && task.workspace_kind !== "git_worktree") {
65
+ return { error: "workspace_kind_not_landable", task_id: taskId, workspace_kind: task.workspace_kind, reason: `${task.workspace_kind} does not create a Git worktree and cannot be landed` };
66
+ }
67
+ const session = task.session_id ? await getSession(task.session_id) : null;
68
+ if (!isSettled(task)) return { error: "worker_active", task_id: taskId, reason: "wait for this run and acceptance to settle before landing" };
69
+ if (session?.approval_state === "waiting_user") return { error: "session_waiting_user", task_id: taskId, reason: "session requires user approval before landing" };
70
+ if (session && task.session_policy_revision !== session.policy_revision) return { error: "session_policy_stale", task_id: taskId, current_revision: session.policy_revision, checked_revision: task.session_policy_revision, reason: "requirements changed; resume with the current objective and rerun acceptance before landing" };
71
+ // Cleanup may have removed the worktree of work that never landed; its branch brings it back.
72
+ if (!task.landed_at) {
73
+ try {
74
+ await ensureTaskWorktree(task);
75
+ } catch (error) {
76
+ return { error: error.code ?? "worktree_restore_failed", task_id: taskId, reason: error.message.split("\n")[0] };
77
+ }
78
+ }
79
+ if (skipAlreadyLanded && task.landed_at && (!task.worktree_path || !existsSync(task.worktree_path))) {
80
+ try {
81
+ const targetBranch = git(task.project_root, ["symbolic-ref", "--short", "HEAD"]);
82
+ if (onto && onto !== targetBranch) return { error: "wrong_branch", task_id: taskId, current_branch: targetBranch };
83
+ if (!ignoreAcceptance && task.acceptance?.length && task.acceptance_results?.passed !== true) {
84
+ return { error: "acceptance_not_run", task_id: taskId };
85
+ }
86
+ git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, "HEAD"]);
87
+ return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, skipped: "already_landed", landed_at: task.landed_at, landed_head: task.landed_head };
88
+ } catch {
89
+ return { error: "landed_commit_unreachable", task_id: taskId, reason: "the removed ancestor worktree cannot be skipped without proving its landed commit is on the current target" };
90
+ }
91
+ }
92
+ const outcome = landWorker(task, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned });
93
+ if (outcome.error === "nothing_to_land" && outcome.already_landed?.length > 0
94
+ && (outcome.uncommitted ?? []).length === 0) {
95
+ const alreadyRecorded = task.landed_at && task.landed_head === outcome.matched_head;
96
+ if (!alreadyRecorded && outcome.matched_head) {
97
+ await recordWorkerLanded(task, {
98
+ head: outcome.matched_head,
99
+ branch: outcome.onto,
100
+ target: outcome.target,
101
+ source: "patch_equivalent",
102
+ alreadyLanded: outcome.already_landed
103
+ });
104
+ }
105
+ return {
106
+ task_id: taskId,
107
+ title: task.title,
108
+ status: task.status,
109
+ branch: `codex/${task.id}`,
110
+ ...outcome,
111
+ skipped: "already_in_target",
112
+ lifecycle_recorded: !alreadyRecorded && Boolean(outcome.matched_head)
113
+ };
114
+ }
115
+ if (outcome.error) return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
116
+ await recordWorkerLanded(task, { head: outcome.head, branch: outcome.onto, target: outcome.target, alreadyLanded: outcome.already_landed ?? [] });
117
+ return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
118
+ }
119
+
120
+ export async function followupChainIds(taskId) {
121
+ const ids = [];
122
+ const seen = new Set();
123
+ let current = taskId;
124
+ for (;;) {
125
+ if (seen.has(current)) throw new Error(`followup cycle detected at ${current}`);
126
+ seen.add(current);
127
+ const task = await getTask(current);
128
+ if (!task) throw new Error(`task not found: ${current}`);
129
+ ids.unshift(current);
130
+ if (!task.followup_of) return ids;
131
+ current = task.followup_of;
132
+ }
133
+ }
@@ -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
+ }