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,164 @@
1
+ // Plans and performs worktree cleanup. A plan classifies each worktree as
2
+ // safe, review or blocked; applying one removes only safe worktrees, after
3
+ // saving any uncommitted edits as a checkpoint commit on the worker's branch.
4
+ // Branches, task rows, events, logs and artifacts are never removed.
5
+ import "./compose.js";
6
+ import { cleanupVerdict, holdMsFrom } from "../domain/cleanup-policy.js";
7
+ import { gitSucceeds, runGit } from "../infra/git.js";
8
+ import { runSync } from "../infra/process.js";
9
+ import { runIdFor } from "../infra/store/db.js";
10
+ import { appendTaskEvent } from "../infra/store/events.js";
11
+ import { markCleanupPlanItemApplied, updateWorkItemDelivery } from "../infra/store/records.js";
12
+ import { claimIdleTask, getTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
13
+ import { workspaceSetupIgnorePaths } from "../infra/worktree.js";
14
+ import { cleanupFacts } from "./cleanup-facts.js";
15
+ import { identityEnv } from "./landing.js";
16
+ import { withWorktreeCreationLock } from "./worktree-setup.js";
17
+ import { createHash, randomUUID } from "node:crypto";
18
+ import { resolve } from "node:path";
19
+
20
+ export const CLEANUP_PLAN_TTL_MS = 15 * 60 * 1000;
21
+ export const CLEANUP_POLICY = "keep_branch_and_evidence_checkpoint_before_removal";
22
+ const RETAINED = ["branch", "task", "events", "jsonl", "artifacts"];
23
+
24
+ const git = (cwd, args, options = {}) => runGit(cwd, args, { timeout: 15000, noOptionalLocks: true, ...options });
25
+ const holdMs = () => holdMsFrom(process.env.CODEX_SUPERVISOR_CLEANUP_HOLD_DAYS);
26
+
27
+ function directoryBytes(path) {
28
+ try {
29
+ const output = runSync("du", ["-sk", path], { encoding: "utf8", timeout: 30000, stdio: ["ignore", "pipe", "ignore"] }).trim();
30
+ const kib = Number(output.split(/\s+/)[0]);
31
+ return Number.isFinite(kib) ? kib * 1024 : 0;
32
+ } catch {
33
+ return 0;
34
+ }
35
+ }
36
+
37
+ // A plan item is only applied to the worktree it was made for: same commit,
38
+ // same uncommitted paths.
39
+ function fingerprintOf(task, facts) {
40
+ const proof = { path: resolve(task.worktree_path), head: facts.head, uncommitted: facts.uncommittedPaths, landed: facts.landed };
41
+ return createHash("sha256").update(JSON.stringify(proof)).digest("hex");
42
+ }
43
+
44
+ export async function assessWorktree(task, tasks, now = Date.now()) {
45
+ const facts = await cleanupFacts(task, tasks);
46
+ const result = cleanupVerdict(facts, { now, holdMs: holdMs() });
47
+ return { ...result, facts, fingerprint: result.verdict === "safe" ? fingerprintOf(task, facts) : null };
48
+ }
49
+
50
+ export async function createCleanupPlan({ taskIds = null, projectRoot = null, now = Date.now() } = {}) {
51
+ const tasks = await readTasks();
52
+ const selected = tasks.filter((task) => (!taskIds || taskIds.includes(task.id)) && (!projectRoot || resolve(task.project_root) === resolve(projectRoot)));
53
+ const items = [];
54
+ for (const task of selected) {
55
+ const result = await assessWorktree(task, tasks, now);
56
+ items.push({
57
+ task_id: task.id,
58
+ verdict: result.verdict,
59
+ reasons: result.reasons,
60
+ checkpoint: result.checkpoint,
61
+ fingerprint: result.fingerprint,
62
+ reclaimable_bytes: result.verdict === "safe" ? directoryBytes(task.worktree_path) : 0,
63
+ eligible_after: result.eligible_after ?? (result.verdict === "safe" ? new Date(now).toISOString() : null)
64
+ });
65
+ }
66
+ const count = (value) => items.filter((item) => item.verdict === value).length;
67
+ return {
68
+ id: randomUUID(),
69
+ project_root: projectRoot ? resolve(projectRoot) : null,
70
+ generated_at: new Date(now).toISOString(),
71
+ expires_at: new Date(now + CLEANUP_PLAN_TTL_MS).toISOString(),
72
+ policy: CLEANUP_POLICY,
73
+ summary: { safe: count("safe"), review: count("review"), blocked: count("blocked"), reclaimable_bytes: items.reduce((sum, item) => sum + item.reclaimable_bytes, 0) },
74
+ items
75
+ };
76
+ }
77
+
78
+ // Saves the worker's uncommitted edits as one commit on its branch. Setup
79
+ // links are left out; hooks are skipped because nobody is there to answer them.
80
+ function checkpointUncommitted(task) {
81
+ const path = resolve(task.worktree_path);
82
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(path) };
83
+ const exclude = workspaceSetupIgnorePaths(task).map((entry) => `:(exclude)${entry}`);
84
+ git(path, ["add", "-A", "--", ".", ...exclude], { env });
85
+ if (gitSucceeds(path, ["diff", "--cached", "--quiet"])) return null;
86
+ git(path, ["commit", "-q", "--no-verify", "-m", `Checkpoint before worktree cleanup (${task.id})`], { env });
87
+ return git(path, ["rev-parse", "HEAD"]);
88
+ }
89
+
90
+ // Removes one worktree after proving again that it is safe and unchanged
91
+ // since it was assessed. The task is locked the way a dispatcher locks it, so
92
+ // a resume cannot start in the directory while it is being removed. Returns
93
+ // the checkpoint commit, or null.
94
+ export async function removeSafeWorktree(task, fingerprint) {
95
+ const claim = await claimIdleTask(task.id);
96
+ if (!claim) throw new Error("the task is running or held by a dispatcher; nothing was removed");
97
+ try {
98
+ const result = await assessWorktree(task, await readTasks());
99
+ if (result.verdict !== "safe") throw new Error(`worktree is no longer safe: ${result.reasons.join("; ")}`);
100
+ if (result.fingerprint !== fingerprint) throw new Error("worktree changed since cleanup plan; create a new plan");
101
+ // The same lock that creating and restoring a worktree takes.
102
+ return await withWorktreeCreationLock(task.project_root, async () => {
103
+ const checkpoint = result.checkpoint ? checkpointUncommitted(task) : null;
104
+ // What is left now is setup links and ignored build output, neither of
105
+ // which is the worker's work; a plain remove would refuse them.
106
+ git(task.project_root, ["worktree", "remove", "--force", task.worktree_path]);
107
+ try {
108
+ git(task.project_root, ["worktree", "prune"]);
109
+ } catch {
110
+ // pruning is housekeeping; the worktree is already gone
111
+ }
112
+ return checkpoint;
113
+ });
114
+ } finally {
115
+ await releaseTaskRun(task.id, claim);
116
+ }
117
+ }
118
+
119
+ export async function recordRemoval(task, { actor, planId = null, itemId = null, checkpoint = null, reasons = [] }) {
120
+ const removedAt = new Date().toISOString();
121
+ await updateWorkItemDelivery(task.id, "cleanup_removed");
122
+ await appendTaskEvent(task.id, {
123
+ type: "supervisor.cleanup_removed",
124
+ plan_id: planId,
125
+ item_id: itemId,
126
+ removed_at: removedAt,
127
+ reasons,
128
+ checkpoint_commit: checkpoint,
129
+ branch: `codex/${task.id}`,
130
+ retained: RETAINED
131
+ }, { runId: runIdFor(task.id, task.run_count ?? 1), actor });
132
+ return removedAt;
133
+ }
134
+
135
+ export async function applyCleanupPlan({ plan, itemIds, actor = "main_thread" }) {
136
+ if (Date.parse(plan.expires_at) <= Date.now()) {
137
+ return { error: "cleanup_plan_expired", plan_id: plan.id, expires_at: plan.expires_at };
138
+ }
139
+ const selected = plan.items.filter((item) => itemIds.includes(item.id));
140
+ if (selected.length !== itemIds.length) return { error: "cleanup_plan_item_not_found", plan_id: plan.id };
141
+ const applied = [];
142
+ const skipped = [];
143
+ for (const item of selected) {
144
+ const skip = (reason) => skipped.push({ item_id: item.id, task_id: item.task_id, reason });
145
+ if (item.verdict !== "safe") {
146
+ skip("only SAFE plan items may be applied");
147
+ continue;
148
+ }
149
+ const task = await getTask(item.task_id);
150
+ if (!task) {
151
+ skip("task no longer exists");
152
+ continue;
153
+ }
154
+ try {
155
+ const checkpoint = await removeSafeWorktree(task, item.fingerprint);
156
+ await markCleanupPlanItemApplied(item.id, actor);
157
+ const removedAt = await recordRemoval(task, { actor, planId: plan.id, itemId: item.id, checkpoint, reasons: item.reasons });
158
+ applied.push({ item_id: item.id, task_id: task.id, worktree_path: task.worktree_path, removed_at: removedAt, checkpoint_commit: checkpoint });
159
+ } catch (error) {
160
+ skip(error.message.split("\n")[0]);
161
+ }
162
+ }
163
+ return { plan_id: plan.id, applied, skipped, retained: RETAINED };
164
+ }
@@ -0,0 +1,7 @@
1
+ // Composition root: wires the runner into the layers that may not import it.
2
+ // Every process entry imports this before it touches the store.
3
+ import { registerRunnerReaders } from "../infra/store/runner-readers.js";
4
+ import { extractAgentMessage } from "../runners/codex/event-parser.js";
5
+ import { readNativeGoal } from "../runners/codex/goal-store.js";
6
+
7
+ registerRunnerReaders({ nativeGoal: readNativeGoal, agentMessage: extractAgentMessage });
@@ -1,21 +1,15 @@
1
- import { buildHandoff } from "./handoff.js";
2
- import { execFileSync } from "node:child_process";
3
- import { approxTokenCount } from "./truncate.js";
4
- import { createContextSnapshot, listContextFacts, runIdFor } from "./task-store.js";
1
+ import { gitSucceeds } from "../infra/git.js";
2
+ import "./compose.js";
3
+ import { buildHandoff } from "../infra/handoff.js";
4
+ import { approxTokenCount } from "../domain/truncate.js";
5
+ import { createContextSnapshot, listContextFacts } from "../infra/store/facts.js";
6
+ import { runIdFor } from "../infra/store/db.js";
5
7
 
6
8
  const MAX_CONTEXT_TOKENS = 1500;
7
9
 
8
10
  function factAppliesToBase(task, fact) {
9
11
  if (!fact.valid_for_sha || fact.valid_for_sha === task.base_commit) return true;
10
- try {
11
- execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", task.project_root, "merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit], {
12
- stdio: "ignore",
13
- timeout: 15000
14
- });
15
- return true;
16
- } catch {
17
- return false;
18
- }
12
+ return gitSucceeds(task.project_root, ["merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit]);
19
13
  }
20
14
 
21
15
  function clip(value, max = 360) {
@@ -0,0 +1,396 @@
1
+ import { failedStart } from "./run-state.js";
2
+ import "./compose.js";
3
+ import { frameWorkerPrompt } from "../domain/prompt.js";
4
+ import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, runtimeContractHash } from "../domain/worker-preflight.js";
5
+ import { captureExternalOutputs } from "../infra/external-output.js";
6
+ import { gitBin, gitSucceeds } from "../infra/git.js";
7
+ import { buildHandoff } from "../infra/handoff.js";
8
+ import { runToExit } from "../infra/process.js";
9
+ import { resolveWritableRoot } from "../infra/sandbox-roots.js";
10
+ import { getSession, upsertSession } from "../infra/store/sessions.js";
11
+ import { getTask, reserveTaskOwnership, taskRunPath, upsertTask } from "../infra/store/tasks.js";
12
+ import { isGitCheckout, prepareWorkspace } from "../infra/workspace-kind.js";
13
+ import { codexRunner } from "../runners/codex/adapter.js";
14
+ import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, isArtifactOnlyAcceptance, normalizeAcceptance } from "./acceptance.js";
15
+ import { findOwnershipConflicts, normalizeOwnedPaths, ownershipConflictError } from "./ownership.js";
16
+ import { allowedReasoningEfforts } from "./run-state.js";
17
+ import { startTrackedRun } from "./start-run.js";
18
+ import { ensureWorktree, invalidBaseRefError, normalizeWorkspaceSetup, prepareWorktreeWorkspace, requireDependencySetup, withWorktreeCreationLock } from "./worktree-setup.js";
19
+ import { randomUUID } from "node:crypto";
20
+ import { rm } from "node:fs/promises";
21
+ import { isAbsolute, resolve } from "node:path";
22
+
23
+ function validateGoal(goal) {
24
+ if (!goal || typeof goal !== "object" || typeof goal.objective !== "string" || goal.objective.trim() === "") {
25
+ throw new Error("goal.objective is required");
26
+ }
27
+ const tokenBudget = goal.tokenBudget ?? goal.token_budget ?? null;
28
+ if (tokenBudget !== null && (!Number.isInteger(tokenBudget) || tokenBudget <= 0)) {
29
+ throw new Error("goal.tokenBudget must be a positive integer when provided");
30
+ }
31
+ return { objective: goal.objective, tokenBudget };
32
+ }
33
+
34
+ function dependencyError(code, message, details = {}) {
35
+ const error = new Error(message);
36
+ error.code = code;
37
+ error.details = details;
38
+ return error;
39
+ }
40
+
41
+ function containsCommit(cwd, ancestor, descendant) {
42
+ return gitSucceeds(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]);
43
+ }
44
+
45
+ async function validateDependencies(dependsOn, projectRoot, baseCommit) {
46
+ const dependencyIds = [...new Set(dependsOn ?? [])];
47
+ for (const dependencyId of dependencyIds) {
48
+ const dependency = await getTask(dependencyId);
49
+ if (!dependency) {
50
+ throw dependencyError("dependency_not_found", `dependency ${dependencyId} does not exist`, { dependency_id: dependencyId });
51
+ }
52
+ if (resolve(dependency.project_root) !== resolve(projectRoot)) {
53
+ throw dependencyError("dependency_project_mismatch", `dependency ${dependencyId} belongs to a different project root`, {
54
+ dependency_id: dependencyId,
55
+ dependency_project_root: dependency.project_root,
56
+ project_root: projectRoot
57
+ });
58
+ }
59
+ if (dependency.status !== "completed" || dependency.exit_code !== 0 || dependency.attention_reason) {
60
+ throw dependencyError("dependency_not_ready", `dependency ${dependencyId} is not successfully settled`, {
61
+ dependency_id: dependencyId,
62
+ status: dependency.status,
63
+ exit_code: dependency.exit_code ?? null,
64
+ attention_reason: dependency.attention_reason ?? null
65
+ });
66
+ }
67
+ if (Array.isArray(dependency.acceptance) && dependency.acceptance.length > 0 && dependency.acceptance_results?.passed !== true) {
68
+ throw dependencyError("dependency_not_ready", `dependency ${dependencyId} has not passed acceptance`, {
69
+ dependency_id: dependencyId,
70
+ acceptance: dependency.acceptance_results?.status ?? null
71
+ });
72
+ }
73
+ if (!dependency.landed_at || !dependency.landed_head) {
74
+ throw dependencyError("dependency_not_landed", `dependency ${dependencyId} must be landed before a dependent worker starts`, {
75
+ dependency_id: dependencyId,
76
+ landed_at: dependency.landed_at ?? null
77
+ });
78
+ }
79
+ if (!baseCommit || !containsCommit(projectRoot, dependency.landed_head, baseCommit)) {
80
+ throw dependencyError("dependency_base_mismatch", `worker base does not contain landed dependency ${dependencyId}; use the integrated branch or a newer baseRef`, {
81
+ dependency_id: dependencyId,
82
+ dependency_head: dependency.landed_head,
83
+ base_commit: baseCommit ?? null
84
+ });
85
+ }
86
+ }
87
+ }
88
+
89
+ function coded(code, message, details = undefined) {
90
+ const error = new Error(message);
91
+ error.code = code;
92
+ if (details !== undefined) error.details = details;
93
+ return error;
94
+ }
95
+
96
+ const DISPATCH_DEFAULTS = {
97
+ sessionId: null, sessionTitle: null, sessionNote: null, sandbox: "workspace-write", model: null, reasoningEffort: "high",
98
+ skipGitRepoCheck: true, dependsOn: [], followupOf: null, workspaceKind: null, inPlaceAuthorization: null, workspaceSetup: null,
99
+ baseRef: null, preflightId: null, preflight: null, acceptance: null, acceptanceTimeoutMs: null, forbid: [], allowedCommands: [],
100
+ context: [], contracts: [], externalOutputs: [], networkAccess: false, writableRoots: [], maxRunMs: null, maxTotalMs: null
101
+ };
102
+
103
+ // An explicit undefined means "not given", the same as leaving the key out.
104
+ function withDispatchDefaults(input) {
105
+ const given = Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
106
+ return { ...DISPATCH_DEFAULTS, ...given };
107
+ }
108
+
109
+ // Everything that can be refused before anything is created on disk. The
110
+ // order of the checks is the order callers see the errors in.
111
+ async function validateDispatch(input) {
112
+ const { task, acceptance, cwd, reasoningEffort, ownedPaths, goal, context, contracts, externalOutputs, sandbox } = input;
113
+ const { networkAccess, writableRoots, maxRunMs, maxTotalMs, forbid, allowedCommands, baseRef, preflight } = input;
114
+ if (!task || typeof task !== "string") throw new Error("task is required");
115
+ const acceptanceCommands = normalizeAcceptance(acceptance);
116
+ if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
117
+ if (!allowedReasoningEfforts.has(reasoningEffort)) {
118
+ throw new Error(`unsupported reasoningEffort: ${reasoningEffort}`);
119
+ }
120
+ if (!Array.isArray(ownedPaths)) {
121
+ throw new Error("ownedPaths is required; pass an empty list only for a worker that must never land a change (a read-only verifier, or a research worker that reads and reports)");
122
+ }
123
+ if (ownedPaths.length > 0 && acceptanceCommands?.length && acceptanceCommands.every(isArtifactOnlyAcceptance)) {
124
+ throw new Error("a write worker cannot use only file-existence acceptance; add a real test, endpoint probe or structured execution evidence");
125
+ }
126
+ const validatedGoal = validateGoal(goal);
127
+ await buildHandoff({ context, contracts });
128
+ await captureExternalOutputs(externalOutputs, { checkBaseline: true });
129
+ if (externalOutputs.length && !acceptanceCommands?.length) throw new Error("shared outputs require explicit acceptance commands");
130
+ if (externalOutputs.length && sandbox === "read-only") throw new Error("a read-only worker cannot declare writable shared outputs");
131
+ if (networkAccess && sandbox === "danger-full-access") throw new Error("networkAccess is only for the sandboxed workers");
132
+ if (networkAccess && sandbox === "read-only") throw new Error("the read-only sandbox has no network (a fetch there fails on DNS even with network_access); for a worker that must fetch, use sandbox \"workspace-write\" with networkAccess: true and ownedPaths: []");
133
+ if (!Array.isArray(writableRoots) || writableRoots.length > 20 || writableRoots.some((root) => typeof root !== "string" || !isAbsolute(root))) {
134
+ throw new Error("writableRoots must be a list of at most 20 absolute paths");
135
+ }
136
+ if (writableRoots.length && sandbox !== "workspace-write") throw new Error("writableRoots is only configurable for workspace-write workers");
137
+ // Codex refuses a writable root with a symlink component and then fails every
138
+ // command in the worker, so a declared root is stored resolved. Passing the
139
+ // alias would look fine in the receipt and break the run.
140
+ const resolvedWritableRoots = [];
141
+ for (const root of writableRoots) {
142
+ const resolved = resolveWritableRoot(root);
143
+ if (resolved.error) throw new Error(`writableRoots entry is unusable: ${root} (${resolved.error}); pass an existing directory whose path has no symlink component`);
144
+ resolvedWritableRoots.push(resolved.path);
145
+ }
146
+ for (const value of [maxRunMs, maxTotalMs]) if (value !== null && (!Number.isInteger(value) || value < 1000)) throw new Error("time limits must be integer milliseconds of at least 1000");
147
+ for (const [name, values] of Object.entries({ forbid, allowedCommands })) {
148
+ if (!Array.isArray(values) || values.length > 100 || values.some((value) => typeof value !== "string" || !value.trim())) throw new Error(`${name} must be a list of at most 100 nonempty strings`);
149
+ }
150
+ if (baseRef && !isGitCheckout(cwd)) throw invalidBaseRefError(cwd, baseRef);
151
+ if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
152
+ || preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
153
+ throw new Error("preflight.probeCommands must be a nonempty list of shell commands");
154
+ }
155
+ return { acceptanceCommands, validatedGoal, resolvedWritableRoots };
156
+ }
157
+
158
+ async function claimWorkspace(input, id, acceptanceCommands) {
159
+ const { cwd, workspaceKind, sandbox, ownedPaths, networkAccess, externalOutputs, inPlaceAuthorization, preflight, workspaceSetup } = input;
160
+ const workspace = await prepareWorkspace({
161
+ cwd,
162
+ workspaceKind,
163
+ sandbox,
164
+ ownedPaths,
165
+ networkAccess,
166
+ acceptance: acceptanceCommands,
167
+ externalOutputs,
168
+ inPlaceAuthorization,
169
+ taskId: id,
170
+ isPreflight: Boolean(preflight)
171
+ });
172
+ const projectRoot = workspace.sourceRoot;
173
+ const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
174
+ const normalizedWorkspaceSetup = normalizeWorkspaceSetup(workspaceSetup, projectRoot);
175
+ if (normalizedWorkspaceSetup && workspace.kind !== "git_worktree") throw new Error("workspaceSetup is only supported for git_worktree workers");
176
+ const conflicts = await findOwnershipConflicts(normalizedOwnedPaths);
177
+ if (conflicts.length > 0) throw ownershipConflictError(conflicts);
178
+ return { workspace, projectRoot, normalizedOwnedPaths, normalizedWorkspaceSetup };
179
+ }
180
+
181
+ async function sessionPolicy({ sessionId, sessionTitle, sessionNote }, acceptanceCommands) {
182
+ if (sessionId && (sessionTitle || sessionNote)) {
183
+ await upsertSession({ id: sessionId, title: sessionTitle, note: sessionNote });
184
+ }
185
+ const session = sessionId ? await getSession(sessionId) : null;
186
+ if (session?.approval_state === "waiting_user") throw coded("session_waiting_user", "session is waiting for user approval; do not dispatch or auto-resume");
187
+ const combinedAcceptance = normalizeAcceptance([...(session?.default_acceptance ?? []), ...(acceptanceCommands ?? [])]);
188
+ return { session, combinedAcceptance };
189
+ }
190
+
191
+ // This checkout belongs to a dispatch that never started and contains no
192
+ // model edits. Remove it normally; never force-remove user work.
193
+ async function discardWorktree(projectRoot, worktreePath, id) {
194
+ await runToExit(gitBin(), ["-C", projectRoot, "worktree", "remove", worktreePath]).catch(() => {});
195
+ await runToExit(gitBin(), ["-C", projectRoot, "branch", "-D", `codex/${id}`]).catch(() => {});
196
+ }
197
+
198
+ async function createWorkerWorktree({ workspace, projectRoot, normalizedWorkspaceSetup }, id, baseRef) {
199
+ const worktree = workspace.kind === "git_worktree"
200
+ ? await withWorktreeCreationLock(projectRoot, () => ensureWorktree(projectRoot, id, baseRef))
201
+ : { path: null, baseCommit: null };
202
+ if (workspace.kind === "git_worktree" && !worktree.path) {
203
+ throw coded("git_worktree_unavailable", "workspaceKind git_worktree could not create an isolated worktree; use read_only_in_place for a non-writing inspection or initialize and commit the repository first");
204
+ }
205
+ if (normalizedWorkspaceSetup) {
206
+ try {
207
+ await prepareWorktreeWorkspace(normalizedWorkspaceSetup, projectRoot, worktree.path, id);
208
+ } catch (error) {
209
+ await discardWorktree(projectRoot, worktree.path, id);
210
+ throw error;
211
+ }
212
+ }
213
+ return worktree;
214
+ }
215
+
216
+ function buildGuard(input, place, worktree, resolvedWritableRoots) {
217
+ const { forbid, allowedCommands, preflight, externalOutputs, networkAccess, maxRunMs, maxTotalMs, sandbox, context, contracts } = input;
218
+ const { workspace, projectRoot, normalizedOwnedPaths, normalizedWorkspaceSetup } = place;
219
+ const guardPolicy = {
220
+ forbid,
221
+ // Probe commands need enough permission to prove the worker environment,
222
+ // but they are not part of the target worker's executable contract. Keep
223
+ // them in this preflight run's guard only so the final worker can reuse the
224
+ // exact contract its dispatcher declared.
225
+ allowedCommands: [...new Set([
226
+ ...allowedCommands,
227
+ ...(preflight?.probeCommands ?? [])
228
+ ])],
229
+ externalOutputs,
230
+ networkAccess,
231
+ writableRoots: [...new Set(resolvedWritableRoots)],
232
+ maxRunMs,
233
+ maxTotalMs,
234
+ workspaceKind: workspace.kind
235
+ };
236
+ const runtimeContract = buildRuntimeContract({
237
+ projectRoot,
238
+ baseCommit: worktree.baseCommit,
239
+ sandbox,
240
+ ownedPaths: normalizedOwnedPaths,
241
+ allowedCommands,
242
+ networkAccess,
243
+ writableRoots: guardPolicy.writableRoots,
244
+ context,
245
+ contracts,
246
+ workspaceSetup: normalizedWorkspaceSetup,
247
+ workspaceKind: workspace.kind,
248
+ workspaceManifestSha256: workspace.beforeManifest?.sha256 ?? null
249
+ });
250
+ const preflightMetadata = preflight
251
+ ? createPreflightMetadata(runtimeContract, preflight.probeCommands)
252
+ : null;
253
+ return { guardPolicy, runtimeContract, preflightMetadata };
254
+ }
255
+
256
+ function buildRecord(input, parts) {
257
+ const { title, task, inPlaceAuthorization, sandbox, model, reasoningEffort, skipGitRepoCheck, followupOf, sessionId } = input;
258
+ const { context, contracts, dependsOn, preflightId, acceptanceTimeoutMs } = input;
259
+ const { id, workspace, projectRoot, normalizedOwnedPaths, normalizedWorkspaceSetup, worktree, effectiveCwd } = parts;
260
+ const { guardPolicy, preflightMetadata, validatedGoal, combinedAcceptance, acceptanceCommands, session } = parts;
261
+ const worktreePath = worktree.path;
262
+ const record = {
263
+ id,
264
+ title: title || task.split("\n").find(Boolean)?.slice(0, 80) || "Codex worker",
265
+ worker: "codex",
266
+ status: "queued",
267
+ phase: null,
268
+ cwd: effectiveCwd,
269
+ project_root: projectRoot,
270
+ workspace_kind: workspace.kind,
271
+ workspace_metadata: {
272
+ source_root: workspace.sourceRoot,
273
+ execution_root: effectiveCwd,
274
+ manifest_paths: workspace.manifestPaths,
275
+ before_manifest: workspace.beforeManifest,
276
+ in_place_authorization: workspace.kind === "in_place_write" ? String(inPlaceAuthorization).trim() : null,
277
+ landable: workspace.landable,
278
+ cleanable: workspace.cleanable,
279
+ setup: normalizedWorkspaceSetup
280
+ },
281
+ sandbox,
282
+ model,
283
+ reasoning_effort: reasoningEffort,
284
+ skip_git_repo_check: skipGitRepoCheck,
285
+ followup_of: followupOf,
286
+ resumed_from: null,
287
+ session_id: sessionId ?? null,
288
+ thread_id: null,
289
+ owned_paths: normalizedOwnedPaths,
290
+ guard_policy: {
291
+ ...guardPolicy,
292
+ ...(preflightMetadata ? { preflight: preflightMetadata } : {}),
293
+ ...(preflightId ? { preflight_source_id: preflightId } : {}),
294
+ workspace: {
295
+ kind: workspace.kind,
296
+ source_root: workspace.sourceRoot,
297
+ execution_root: effectiveCwd,
298
+ manifest_paths: workspace.manifestPaths,
299
+ before_manifest_sha256: workspace.beforeManifest?.sha256 ?? null
300
+ }
301
+ },
302
+ input_context: { context, contracts },
303
+ depends_on: Array.isArray(dependsOn) ? dependsOn : [],
304
+ goal_objective: validatedGoal.objective,
305
+ goal_token_budget: validatedGoal.tokenBudget,
306
+ goal_status: null,
307
+ goal_tokens_used: null,
308
+ goal_time_used_seconds: null,
309
+ goal_updated_at: null,
310
+ run_count: 0,
311
+ worktree_path: worktreePath,
312
+ base_commit: worktree.baseCommit,
313
+ acceptance: combinedAcceptance,
314
+ acceptance_local: acceptanceCommands,
315
+ session_policy_revision: session?.policy_revision ?? null,
316
+ acceptance_timeout_ms: combinedAcceptance ? (acceptanceTimeoutMs ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
317
+ acceptance_results: null,
318
+ prompt: task,
319
+ changed_files: [],
320
+ commands: [],
321
+ created_at: new Date().toISOString(),
322
+ updated_at: new Date().toISOString(),
323
+ run_log: taskRunPath(id)
324
+ };
325
+ return record;
326
+ }
327
+
328
+ async function assertPreflightMatches(preflightId, runtimeContract) {
329
+ const preflightTask = await getTask(preflightId);
330
+ const preflightResult = readPreflightResult(preflightTask);
331
+ if (preflightResult.status !== "passed") {
332
+ throw coded("preflight_not_passed", `preflight ${preflightId} is ${preflightResult.status}; wait for its probes to pass before dispatching this worker`, preflightResult);
333
+ }
334
+ const contractHash = runtimeContractHash(runtimeContract);
335
+ if (preflightResult.contract_hash === contractHash) return;
336
+ throw coded("preflight_mismatch", `preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing baseRef, sandbox, ownedPaths, commands, context, contracts, network or writable roots`, {
337
+ preflight_id: preflightId,
338
+ expected_contract_hash: contractHash,
339
+ actual_contract_hash: preflightResult.contract_hash,
340
+ preflight: { expected_contract: runtimeContract, actual_contract: preflightResult.contract }
341
+ });
342
+ }
343
+
344
+ // Dependencies, the preflight contract and the path reservation. A refusal
345
+ // here removes the worktree and scratch directory made for this dispatch.
346
+ async function admitWorker(record, { dependsOn, preflightId }, { workspace, projectRoot, worktree, runtimeContract }) {
347
+ try {
348
+ await validateDependencies(dependsOn, projectRoot, worktree.baseCommit);
349
+ if (preflightId) await assertPreflightMatches(preflightId, runtimeContract);
350
+ await reserveTaskOwnership(record);
351
+ } catch (error) {
352
+ if (worktree.path) await discardWorktree(projectRoot, worktree.path, record.id);
353
+ if (workspace.scratchPath) await rm(workspace.scratchPath, { recursive: true, force: true }).catch(() => {});
354
+ throw error;
355
+ }
356
+ }
357
+
358
+ export async function createCodexWorker(rawInput) {
359
+ const input = withDispatchDefaults(rawInput);
360
+ const { acceptanceCommands, validatedGoal, resolvedWritableRoots } = await validateDispatch(input);
361
+ const id = `codex-${Date.now()}-${randomUUID().slice(0, 8)}`;
362
+ const place = await claimWorkspace(input, id, acceptanceCommands);
363
+ const { session, combinedAcceptance } = await sessionPolicy(input, acceptanceCommands);
364
+ requireDependencySetup({ kind: place.workspace.kind, projectRoot: place.projectRoot, setup: place.normalizedWorkspaceSetup,
365
+ commands: [...(combinedAcceptance ?? []), ...(input.preflight?.probeCommands ?? [])] });
366
+ const worktree = await createWorkerWorktree(place, id, input.baseRef);
367
+ const effectiveCwd = worktree.path ?? place.workspace.executionCwd;
368
+ const guard = buildGuard(input, place, worktree, resolvedWritableRoots);
369
+ const record = buildRecord(input, { id, ...place, worktree, effectiveCwd, ...guard, validatedGoal, combinedAcceptance, acceptanceCommands, session });
370
+ await admitWorker(record, input, { ...place, worktree, runtimeContract: guard.runtimeContract });
371
+
372
+ const { sandbox, model, reasoningEffort, skipGitRepoCheck, task } = input;
373
+ const args = codexRunner.startArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
374
+ const job = {
375
+ record,
376
+ args,
377
+ prompt: frameWorkerPrompt(task, {
378
+ objective: validatedGoal.objective,
379
+ tokenBudget: validatedGoal.tokenBudget
380
+ }, { acceptance: combinedAcceptance, outputSchema: true }),
381
+ logPath: record.run_log,
382
+ outputSchema: true,
383
+ // --cd tells Codex where the agent works. The shell/tool process must also
384
+ // inherit the worktree as its OS cwd: otherwise a login shell may restore
385
+ // the project directory and relative probes read the wrong checkout.
386
+ spawnOptions: { cwd: effectiveCwd }
387
+ };
388
+ try {
389
+ return (await startTrackedRun(job)).record;
390
+ } catch (error) {
391
+ // The row is reserved as queued, which blocks its paths for every later
392
+ // dispatch. A start that threw never ran, so the row is closed as failed.
393
+ await upsertTask(failedStart(job.record, `dispatch failed before the worker started: ${error.message}`).record).catch(() => {});
394
+ throw error;
395
+ }
396
+ }