agent-supervisor-mcp 0.0.0-stage → 2.0.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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +208 -0
  3. package/README.md +206 -2
  4. package/package.json +76 -4
  5. package/skills/agent-supervisor/SKILL.md +139 -0
  6. package/src/app/acceptance.js +263 -0
  7. package/src/app/auto-cleanup.js +91 -0
  8. package/src/app/cancel.js +57 -0
  9. package/src/app/cleanup-facts.js +101 -0
  10. package/src/app/cleanup-plan.js +166 -0
  11. package/src/app/compose.js +17 -0
  12. package/src/app/context-compiler.js +83 -0
  13. package/src/app/dispatch.js +398 -0
  14. package/src/app/followup.js +104 -0
  15. package/src/app/land-chain.js +134 -0
  16. package/src/app/landing.js +357 -0
  17. package/src/app/ownership.js +57 -0
  18. package/src/app/rebase.js +216 -0
  19. package/src/app/restore-worktree.js +51 -0
  20. package/src/app/resume.js +179 -0
  21. package/src/app/run-state.js +26 -0
  22. package/src/app/settled.js +28 -0
  23. package/src/app/side-chat.js +370 -0
  24. package/src/app/sse.js +20 -0
  25. package/src/app/start-run.js +77 -0
  26. package/src/app/verify-push.js +114 -0
  27. package/src/app/worktree-setup.js +218 -0
  28. package/src/domain/acceptance-baseline.js +65 -0
  29. package/src/domain/acceptance-spec.js +30 -0
  30. package/src/domain/cleanup-policy.js +44 -0
  31. package/src/domain/command-outcome.js +6 -0
  32. package/src/domain/failure-class.js +63 -0
  33. package/src/domain/owned-changes.js +27 -0
  34. package/src/domain/prompt.js +161 -0
  35. package/src/domain/side-turn-view.js +73 -0
  36. package/src/domain/status.js +50 -0
  37. package/src/domain/thread-health.js +33 -0
  38. package/src/domain/truncate.js +148 -0
  39. package/src/domain/worker-branch.js +6 -0
  40. package/src/domain/worker-changes.js +58 -0
  41. package/src/domain/worker-env.js +14 -0
  42. package/src/domain/worker-preflight.js +167 -0
  43. package/src/domain/worker-report.js +85 -0
  44. package/src/domain/worker-report.schema.json +10 -0
  45. package/src/infra/bin-resolver.js +287 -0
  46. package/src/infra/cleanup-hint.js +29 -0
  47. package/src/infra/crash-guard.js +44 -0
  48. package/src/infra/external-output.js +29 -0
  49. package/src/infra/git.js +61 -0
  50. package/src/infra/handoff.js +38 -0
  51. package/src/infra/paths.js +34 -0
  52. package/src/infra/process.js +59 -0
  53. package/src/infra/sandbox-roots.js +106 -0
  54. package/src/infra/skill-sync.js +109 -0
  55. package/src/infra/stage-store.js +39 -0
  56. package/src/infra/store/db.js +265 -0
  57. package/src/infra/store/event-body.js +82 -0
  58. package/src/infra/store/events.js +149 -0
  59. package/src/infra/store/facts.js +338 -0
  60. package/src/infra/store/reconcile.js +173 -0
  61. package/src/infra/store/records.js +171 -0
  62. package/src/infra/store/runner-readers.js +16 -0
  63. package/src/infra/store/schema.js +306 -0
  64. package/src/infra/store/sessions.js +138 -0
  65. package/src/infra/store/tasks.js +351 -0
  66. package/src/infra/update/auto-update-worker.js +186 -0
  67. package/src/infra/update/auto-update.js +143 -0
  68. package/src/infra/update/update-check.js +246 -0
  69. package/src/infra/workspace-kind.js +165 -0
  70. package/src/infra/worktree.js +361 -0
  71. package/src/interface/bin/acceptance-cli.js +62 -0
  72. package/src/interface/bin/cleanup.js +81 -0
  73. package/src/interface/bin/monitor.jsx +301 -0
  74. package/src/interface/bin/setup.js +342 -0
  75. package/src/interface/bin/stage.js +17 -0
  76. package/src/interface/bin/web-server.js +53 -0
  77. package/src/interface/mcp/handlers/delivery.js +165 -0
  78. package/src/interface/mcp/handlers/dispatch.js +236 -0
  79. package/src/interface/mcp/handlers/facts.js +204 -0
  80. package/src/interface/mcp/handlers/overview.js +106 -0
  81. package/src/interface/mcp/handlers/results.js +262 -0
  82. package/src/interface/mcp/handlers/review.js +115 -0
  83. package/src/interface/mcp/handlers/wait.js +141 -0
  84. package/src/interface/mcp/meta.js +7 -0
  85. package/src/interface/mcp/result.js +34 -0
  86. package/src/interface/mcp/schemas.js +24 -0
  87. package/src/interface/mcp/server.js +64 -0
  88. package/src/interface/mcp/tools/deliver.js +48 -0
  89. package/src/interface/mcp/tools/dispatch.js +90 -0
  90. package/src/interface/mcp/tools/optional.js +57 -0
  91. package/src/interface/mcp/tools/read.js +115 -0
  92. package/src/interface/mcp/tools/run.js +57 -0
  93. package/src/interface/mcp/tools/shapes.js +67 -0
  94. package/src/interface/mcp/tools/track.js +84 -0
  95. package/src/interface/mcp/update-state.js +34 -0
  96. package/src/interface/mcp/views/overview.js +183 -0
  97. package/src/interface/mcp/views/task.js +224 -0
  98. package/src/interface/web/app.js +226 -0
  99. package/src/interface/web/views.js +227 -0
  100. package/src/mcp-server.js +4 -0
  101. package/src/run-host/entry.js +26 -0
  102. package/src/run-host/finalize.js +243 -0
  103. package/src/run-host/launch.js +49 -0
  104. package/src/run-host/live-run.js +76 -0
  105. package/src/run-host/outcome-facts.js +61 -0
  106. package/src/run-host/streams.js +102 -0
  107. package/src/run-host/track.js +132 -0
  108. package/src/runners/claude/adapter.js +118 -0
  109. package/src/runners/claude/events.js +100 -0
  110. package/src/runners/claude/tool-guard.js +48 -0
  111. package/src/runners/codex/adapter.js +157 -0
  112. package/src/runners/codex/chat-chunks.js +97 -0
  113. package/src/runners/codex/event-parser.js +266 -0
  114. package/src/runners/codex/goal-store.js +54 -0
  115. package/src/runners/codex/mcp-config.js +39 -0
  116. package/src/runners/codex/tool-guard.js +184 -0
  117. package/src/runners/contract-check.js +82 -0
  118. package/src/runners/contract.js +53 -0
  119. package/src/runners/registry.js +45 -0
  120. package/web/dist/assets/index-D-A2xlpx.js +154 -0
  121. package/web/dist/assets/index-f8esISCp.css +2 -0
  122. package/web/dist/index.html +15 -0
@@ -0,0 +1,166 @@
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 { branchOf } from "../domain/worker-branch.js";
6
+ import "./compose.js";
7
+ import { cleanupVerdict, holdMsFrom } from "../domain/cleanup-policy.js";
8
+ import { gitSucceedsAsync, runGitAsync } from "../infra/git.js";
9
+ import { runFile } from "../infra/process.js";
10
+ import { runIdFor } from "../infra/store/db.js";
11
+ import { appendTaskEvent } from "../infra/store/events.js";
12
+ import { markCleanupPlanItemApplied, updateWorkItemDelivery } from "../infra/store/records.js";
13
+ import { claimIdleTask, getTask, readTasks, releaseTaskRun } from "../infra/store/tasks.js";
14
+ import { workspaceSetupIgnorePaths } from "../infra/worktree.js";
15
+ import { cleanupFacts } from "./cleanup-facts.js";
16
+ import { identityEnv } from "./landing.js";
17
+ import { withWorktreeCreationLock } from "./worktree-setup.js";
18
+ import { createHash, randomUUID } from "node:crypto";
19
+ import { resolve } from "node:path";
20
+
21
+ export const CLEANUP_PLAN_TTL_MS = 15 * 60 * 1000;
22
+ export const CLEANUP_POLICY = "keep_branch_and_evidence_checkpoint_before_removal";
23
+ const RETAINED = ["branch", "task", "events", "jsonl", "artifacts"];
24
+
25
+ const git = (cwd, args, options = {}) => runGitAsync(cwd, args, { timeout: 15000, noOptionalLocks: true, ...options });
26
+ const holdMs = () => holdMsFrom(process.env.AGENT_SUPERVISOR_CLEANUP_HOLD_DAYS);
27
+
28
+ // The size is a hint for the reader of a plan. Where du is missing or slow
29
+ // the answer is 0, never a failed plan.
30
+ function directoryBytes(path) {
31
+ return new Promise((resolveSize) => {
32
+ runFile("du", ["-sk", path], { encoding: "utf8", timeout: 30000 }, (error, stdout) => {
33
+ const kib = error ? NaN : Number(stdout.trim().split(/\s+/)[0]);
34
+ resolveSize(Number.isFinite(kib) ? kib * 1024 : 0);
35
+ });
36
+ });
37
+ }
38
+
39
+ // A plan item is only applied to the worktree it was made for: same commit,
40
+ // same uncommitted paths.
41
+ function fingerprintOf(task, facts) {
42
+ const proof = { path: resolve(task.worktree_path), head: facts.head, uncommitted: facts.uncommittedPaths, landed: facts.landed };
43
+ return createHash("sha256").update(JSON.stringify(proof)).digest("hex");
44
+ }
45
+
46
+ export async function assessWorktree(task, tasks, now = Date.now()) {
47
+ const facts = await cleanupFacts(task, tasks);
48
+ const result = cleanupVerdict(facts, { now, holdMs: holdMs() });
49
+ return { ...result, facts, fingerprint: result.verdict === "safe" ? fingerprintOf(task, facts) : null };
50
+ }
51
+
52
+ export async function createCleanupPlan({ taskIds = null, projectRoot = null, now = Date.now() } = {}) {
53
+ const tasks = await readTasks();
54
+ const selected = tasks.filter((task) => (!taskIds || taskIds.includes(task.id)) && (!projectRoot || resolve(task.project_root) === resolve(projectRoot)));
55
+ const items = [];
56
+ for (const task of selected) {
57
+ const result = await assessWorktree(task, tasks, now);
58
+ items.push({
59
+ task_id: task.id,
60
+ verdict: result.verdict,
61
+ reasons: result.reasons,
62
+ checkpoint: result.checkpoint,
63
+ fingerprint: result.fingerprint,
64
+ reclaimable_bytes: result.verdict === "safe" ? await directoryBytes(task.worktree_path) : 0,
65
+ eligible_after: result.eligible_after ?? (result.verdict === "safe" ? new Date(now).toISOString() : null)
66
+ });
67
+ }
68
+ const count = (value) => items.filter((item) => item.verdict === value).length;
69
+ return {
70
+ id: randomUUID(),
71
+ project_root: projectRoot ? resolve(projectRoot) : null,
72
+ generated_at: new Date(now).toISOString(),
73
+ expires_at: new Date(now + CLEANUP_PLAN_TTL_MS).toISOString(),
74
+ policy: CLEANUP_POLICY,
75
+ summary: { safe: count("safe"), review: count("review"), blocked: count("blocked"), reclaimable_bytes: items.reduce((sum, item) => sum + item.reclaimable_bytes, 0) },
76
+ items
77
+ };
78
+ }
79
+
80
+ // Saves the worker's uncommitted edits as one commit on its branch. Setup
81
+ // links are left out; hooks are skipped because nobody is there to answer them.
82
+ async function checkpointUncommitted(task) {
83
+ const path = resolve(task.worktree_path);
84
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true", ...identityEnv(path) };
85
+ const exclude = workspaceSetupIgnorePaths(task).map((entry) => `:(exclude)${entry}`);
86
+ await git(path, ["add", "-A", "--", ".", ...exclude], { env });
87
+ if (await gitSucceedsAsync(path, ["diff", "--cached", "--quiet"])) return null;
88
+ await git(path, ["commit", "-q", "--no-verify", "-m", `Checkpoint before worktree cleanup (${task.id})`], { env });
89
+ return git(path, ["rev-parse", "HEAD"]);
90
+ }
91
+
92
+ // Removes one worktree after proving again that it is safe and unchanged
93
+ // since it was assessed. The task is locked the way a dispatcher locks it, so
94
+ // a resume cannot start in the directory while it is being removed. Returns
95
+ // the checkpoint commit, or null.
96
+ export async function removeSafeWorktree(task, fingerprint) {
97
+ const claim = await claimIdleTask(task.id);
98
+ if (!claim) throw new Error("the task is running or held by a dispatcher; nothing was removed");
99
+ try {
100
+ const result = await assessWorktree(task, await readTasks());
101
+ if (result.verdict !== "safe") throw new Error(`worktree is no longer safe: ${result.reasons.join("; ")}`);
102
+ if (result.fingerprint !== fingerprint) throw new Error("worktree changed since cleanup plan; create a new plan");
103
+ // The same lock that creating and restoring a worktree takes.
104
+ return await withWorktreeCreationLock(task.project_root, async () => {
105
+ const checkpoint = result.checkpoint ? await checkpointUncommitted(task) : null;
106
+ // What is left now is setup links and ignored build output, neither of
107
+ // which is the worker's work; a plain remove would refuse them.
108
+ await git(task.project_root, ["worktree", "remove", "--force", task.worktree_path]);
109
+ try {
110
+ await git(task.project_root, ["worktree", "prune"]);
111
+ } catch {
112
+ // pruning is housekeeping; the worktree is already gone
113
+ }
114
+ return checkpoint;
115
+ });
116
+ } finally {
117
+ await releaseTaskRun(task.id, claim);
118
+ }
119
+ }
120
+
121
+ export async function recordRemoval(task, { actor, planId = null, itemId = null, checkpoint = null, reasons = [] }) {
122
+ const removedAt = new Date().toISOString();
123
+ await updateWorkItemDelivery(task.id, "cleanup_removed");
124
+ await appendTaskEvent(task.id, {
125
+ type: "supervisor.cleanup_removed",
126
+ plan_id: planId,
127
+ item_id: itemId,
128
+ removed_at: removedAt,
129
+ reasons,
130
+ checkpoint_commit: checkpoint,
131
+ branch: branchOf(task),
132
+ retained: RETAINED
133
+ }, { runId: runIdFor(task.id, task.run_count ?? 1), actor });
134
+ return removedAt;
135
+ }
136
+
137
+ export async function applyCleanupPlan({ plan, itemIds, actor = "main_thread" }) {
138
+ if (Date.parse(plan.expires_at) <= Date.now()) {
139
+ return { error: "cleanup_plan_expired", plan_id: plan.id, expires_at: plan.expires_at };
140
+ }
141
+ const selected = plan.items.filter((item) => itemIds.includes(item.id));
142
+ if (selected.length !== itemIds.length) return { error: "cleanup_plan_item_not_found", plan_id: plan.id };
143
+ const applied = [];
144
+ const skipped = [];
145
+ for (const item of selected) {
146
+ const skip = (reason) => skipped.push({ item_id: item.id, task_id: item.task_id, reason });
147
+ if (item.verdict !== "safe") {
148
+ skip("only SAFE plan items may be applied");
149
+ continue;
150
+ }
151
+ const task = await getTask(item.task_id);
152
+ if (!task) {
153
+ skip("task no longer exists");
154
+ continue;
155
+ }
156
+ try {
157
+ const checkpoint = await removeSafeWorktree(task, item.fingerprint);
158
+ await markCleanupPlanItemApplied(item.id, actor);
159
+ const removedAt = await recordRemoval(task, { actor, planId: plan.id, itemId: item.id, checkpoint, reasons: item.reasons });
160
+ applied.push({ item_id: item.id, task_id: task.id, worktree_path: task.worktree_path, removed_at: removedAt, checkpoint_commit: checkpoint });
161
+ } catch (error) {
162
+ skip(error.message.split("\n")[0]);
163
+ }
164
+ }
165
+ return { plan_id: plan.id, applied, skipped, retained: RETAINED };
166
+ }
@@ -0,0 +1,17 @@
1
+ // Composition root: wires the runners into the layers that may not import them.
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 { DEFAULT_RUNNER, runnerNames, getRunner } from "../runners/registry.js";
6
+
7
+ // A row names its runner. One whose runner is not loaded in this process, or
8
+ // has no native goal, simply has none to show.
9
+ function nativeGoal(threadId, runnerName = DEFAULT_RUNNER) {
10
+ const name = runnerName ?? DEFAULT_RUNNER;
11
+ if (!runnerNames().includes(name)) return null;
12
+ const runner = getRunner(name);
13
+ return runner.capabilities.native_goal ? runner.nativeGoal(threadId) : null;
14
+ }
15
+
16
+ // Stored events are in the supervisor's vocabulary whatever CLI produced them.
17
+ registerRunnerReaders({ nativeGoal, agentMessage: extractAgentMessage });
@@ -0,0 +1,83 @@
1
+ import { branchOf } from "../domain/worker-branch.js";
2
+ import { gitSucceeds } from "../infra/git.js";
3
+ import "./compose.js";
4
+ import { buildHandoff } from "../infra/handoff.js";
5
+ import { approxTokenCount } from "../domain/truncate.js";
6
+ import { createContextSnapshot, listContextFacts } from "../infra/store/facts.js";
7
+ import { runIdFor } from "../infra/store/db.js";
8
+
9
+ const MAX_CONTEXT_TOKENS = 1500;
10
+
11
+ function factAppliesToBase(task, fact) {
12
+ if (!fact.valid_for_sha || fact.valid_for_sha === task.base_commit) return true;
13
+ return gitSucceeds(task.project_root, ["merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit]);
14
+ }
15
+
16
+ function clip(value, max = 360) {
17
+ const text = typeof value === "string" ? value : JSON.stringify(value);
18
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
19
+ }
20
+
21
+ function addWithinBudget(lines, line) {
22
+ const next = [...lines, line].join("\n");
23
+ return approxTokenCount(next) <= MAX_CONTEXT_TOKENS ? next.split("\n") : lines;
24
+ }
25
+
26
+ // Produces the only shared context a regular worker receives. It deliberately
27
+ // has no session peer lookup: session_id groups a batch and policy, not memory.
28
+ export async function compileWorkerContext(task, { attempt }) {
29
+ const handoff = await buildHandoff({
30
+ goal: task.goal_objective,
31
+ todo: task.title,
32
+ contracts: task.input_context?.contracts ?? [],
33
+ context: task.input_context?.context ?? []
34
+ }, { maxLines: 12, maxChars: 1200 });
35
+ const facts = (await listContextFacts({
36
+ taskId: task.id,
37
+ baseSha: task.base_commit ?? null,
38
+ ownedPaths: task.owned_paths ?? [],
39
+ dependencyTaskIds: task.depends_on ?? []
40
+ })).filter((fact) => factAppliesToBase(task, fact));
41
+ let lines = [
42
+ "Worker context capsule. This is scoped execution context, not a transcript and not authorization to expand work.",
43
+ "L0 identity:",
44
+ `- task_id: ${task.id}`,
45
+ `- run_id: ${runIdFor(task.id, attempt)}`,
46
+ `- project_root: ${task.project_root}`,
47
+ `- base_sha: ${task.base_commit ?? "unknown"}`,
48
+ `- branch: ${task.worktree_path ? branchOf(task) : "not applicable (in-place workspace)"}`,
49
+ `- worktree: ${task.worktree_path ?? task.cwd}`,
50
+ `- owned_paths: ${JSON.stringify(task.owned_paths ?? [])}`,
51
+ `- acceptance_source: ${Array.isArray(task.acceptance) && task.acceptance.length > 0 ? "dispatch or session policy; commands stay outside this capsule" : "no acceptance configured"}`,
52
+ "L1 task:",
53
+ `- objective: ${task.goal_objective ?? task.title ?? "unspecified"}`
54
+ ];
55
+ if (handoff.text) lines = addWithinBudget(lines, handoff.text);
56
+ const usedFacts = [];
57
+ if (facts.length > 0) lines = addWithinBudget(lines, "Verified facts:");
58
+ for (const fact of facts) {
59
+ const scope = fact.scope_type === "dependency" ? "dependency" : fact.scope_type;
60
+ const candidate = `- [${scope}:${fact.key}] ${clip(fact.value)}`;
61
+ const next = addWithinBudget(lines, candidate);
62
+ if (next === lines) break;
63
+ lines = next;
64
+ usedFacts.push(fact.id);
65
+ }
66
+ lines = addWithinBudget(lines, "Evidence on demand only: raw events, full diff, historical reports and artifacts are excluded from this capsule.");
67
+ const text = lines.join("\n");
68
+ const snapshot = await createContextSnapshot({
69
+ runId: runIdFor(task.id, attempt),
70
+ factIds: usedFacts,
71
+ baseSha: task.base_commit ?? null,
72
+ prompt: text,
73
+ estimatedTokens: approxTokenCount(text),
74
+ excluded: {
75
+ session_peers: "never automatic",
76
+ raw_events: "on demand",
77
+ reports: "on demand",
78
+ artifacts: "on demand",
79
+ candidate_facts: "never automatic"
80
+ }
81
+ });
82
+ return { text, snapshot, sourceRefs: handoff.source_refs, contentHash: handoff.content_hash, factCount: usedFacts.length };
83
+ }
@@ -0,0 +1,398 @@
1
+ import { newWorkerBranch } from "../domain/worker-branch.js";
2
+ import { failedStart } from "./run-state.js";
3
+ import "./compose.js";
4
+ import { frameWorkerPrompt } from "../domain/prompt.js";
5
+ import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, runtimeContractHash } from "../domain/worker-preflight.js";
6
+ import { captureExternalOutputs } from "../infra/external-output.js";
7
+ import { gitBin, gitSucceeds } from "../infra/git.js";
8
+ import { buildHandoff } from "../infra/handoff.js";
9
+ import { runToExit } from "../infra/process.js";
10
+ import { resolveWritableRoot } from "../infra/sandbox-roots.js";
11
+ import { getSession, upsertSession } from "../infra/store/sessions.js";
12
+ import { getTask, reserveTaskOwnership, taskRunPath, upsertTask } from "../infra/store/tasks.js";
13
+ import { isGitCheckout, prepareWorkspace } from "../infra/workspace-kind.js";
14
+ import { assertWorkspaceAllowed } from "../runners/contract.js";
15
+ import { DEFAULT_RUNNER, loadRunner } from "../runners/registry.js";
16
+ import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, isArtifactOnlyAcceptance, normalizeAcceptance } from "./acceptance.js";
17
+ import { findOwnershipConflicts, normalizeOwnedPaths, ownershipConflictError } from "./ownership.js";
18
+ import { allowedReasoningEfforts } from "./run-state.js";
19
+ import { startTrackedRun } from "./start-run.js";
20
+ import { ensureWorktree, invalidBaseRefError, normalizeWorkspaceSetup, prepareWorktreeWorkspace, requireDependencySetup, withWorktreeCreationLock } from "./worktree-setup.js";
21
+ import { randomUUID } from "node:crypto";
22
+ import { rm } from "node:fs/promises";
23
+ import { isAbsolute, resolve } from "node:path";
24
+
25
+ function validateGoal(goal) {
26
+ if (!goal || typeof goal !== "object" || typeof goal.objective !== "string" || goal.objective.trim() === "") {
27
+ throw new Error("goal.objective is required");
28
+ }
29
+ const tokenBudget = goal.tokenBudget ?? goal.token_budget ?? null;
30
+ if (tokenBudget !== null && (!Number.isInteger(tokenBudget) || tokenBudget <= 0)) {
31
+ throw new Error("goal.token_budget must be a positive integer when provided");
32
+ }
33
+ return { objective: goal.objective, tokenBudget };
34
+ }
35
+
36
+ function dependencyError(code, message, details = {}) {
37
+ const error = new Error(message);
38
+ error.code = code;
39
+ error.details = details;
40
+ return error;
41
+ }
42
+
43
+ function containsCommit(cwd, ancestor, descendant) {
44
+ return gitSucceeds(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]);
45
+ }
46
+
47
+ async function validateDependencies(dependsOn, projectRoot, baseCommit) {
48
+ const dependencyIds = [...new Set(dependsOn ?? [])];
49
+ for (const dependencyId of dependencyIds) {
50
+ const dependency = await getTask(dependencyId);
51
+ if (!dependency) {
52
+ throw dependencyError("dependency_not_found", `dependency ${dependencyId} does not exist`, { dependency_id: dependencyId });
53
+ }
54
+ if (resolve(dependency.project_root) !== resolve(projectRoot)) {
55
+ throw dependencyError("dependency_project_mismatch", `dependency ${dependencyId} belongs to a different project root`, {
56
+ dependency_id: dependencyId,
57
+ dependency_project_root: dependency.project_root,
58
+ project_root: projectRoot
59
+ });
60
+ }
61
+ if (dependency.status !== "completed" || dependency.exit_code !== 0 || dependency.attention_reason) {
62
+ throw dependencyError("dependency_not_ready", `dependency ${dependencyId} is not successfully settled`, {
63
+ dependency_id: dependencyId,
64
+ status: dependency.status,
65
+ exit_code: dependency.exit_code ?? null,
66
+ attention_reason: dependency.attention_reason ?? null
67
+ });
68
+ }
69
+ if (Array.isArray(dependency.acceptance) && dependency.acceptance.length > 0 && dependency.acceptance_results?.passed !== true) {
70
+ throw dependencyError("dependency_not_ready", `dependency ${dependencyId} has not passed acceptance`, {
71
+ dependency_id: dependencyId,
72
+ acceptance: dependency.acceptance_results?.status ?? null
73
+ });
74
+ }
75
+ if (!dependency.landed_at || !dependency.landed_head) {
76
+ throw dependencyError("dependency_not_landed", `dependency ${dependencyId} must be landed before a dependent worker starts`, {
77
+ dependency_id: dependencyId,
78
+ landed_at: dependency.landed_at ?? null
79
+ });
80
+ }
81
+ if (!baseCommit || !containsCommit(projectRoot, dependency.landed_head, baseCommit)) {
82
+ throw dependencyError("dependency_base_mismatch", `worker base does not contain landed dependency ${dependencyId}; use the integrated branch or a newer workspace.base_ref`, {
83
+ dependency_id: dependencyId,
84
+ dependency_head: dependency.landed_head,
85
+ base_commit: baseCommit ?? null
86
+ });
87
+ }
88
+ }
89
+ }
90
+
91
+ function coded(code, message, details = undefined) {
92
+ return Object.assign(new Error(message), { code }, details === undefined ? {} : { details });
93
+ }
94
+
95
+ const DISPATCH_DEFAULTS = {
96
+ runner: DEFAULT_RUNNER, sessionId: null, sessionTitle: null, sessionNote: null, sandbox: "workspace-write", model: null, reasoningEffort: "high",
97
+ skipGitRepoCheck: true, dependsOn: [], followupOf: null, workspaceKind: null, inPlaceAuthorization: null, workspaceSetup: null,
98
+ baseRef: null, preflightId: null, preflight: null, acceptance: null, acceptanceTimeoutMs: null, forbid: [], allowedCommands: [],
99
+ context: [], contracts: [], externalOutputs: [], networkAccess: false, writableRoots: [], maxRunMs: null, maxTotalMs: null
100
+ };
101
+
102
+ // An explicit undefined means "not given", the same as leaving the key out.
103
+ function withDispatchDefaults(input) {
104
+ const given = Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined));
105
+ return { ...DISPATCH_DEFAULTS, ...given };
106
+ }
107
+
108
+ // Everything that can be refused before anything is created on disk. The
109
+ // order of the checks is the order callers see the errors in.
110
+ async function validateDispatch(input) {
111
+ const { task, acceptance, cwd, reasoningEffort, ownedPaths, goal, context, contracts, externalOutputs, sandbox } = input;
112
+ const { networkAccess, writableRoots, maxRunMs, maxTotalMs, forbid, allowedCommands, baseRef, preflight } = input;
113
+ if (!task || typeof task !== "string") throw new Error("task is required");
114
+ const acceptanceCommands = normalizeAcceptance(acceptance);
115
+ if (!cwd || typeof cwd !== "string") throw new Error("cwd is required");
116
+ if (!allowedReasoningEfforts.has(reasoningEffort)) {
117
+ throw new Error(`unsupported reasoning_effort: ${reasoningEffort}`);
118
+ }
119
+ if (!Array.isArray(ownedPaths)) {
120
+ throw new Error("owned_paths 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)");
121
+ }
122
+ if (ownedPaths.length > 0 && acceptanceCommands?.length && acceptanceCommands.every(isArtifactOnlyAcceptance)) {
123
+ throw new Error("a write worker cannot use only file-existence acceptance; add a real test, endpoint probe or structured execution evidence");
124
+ }
125
+ const validatedGoal = validateGoal(goal);
126
+ await buildHandoff({ context, contracts });
127
+ await captureExternalOutputs(externalOutputs, { checkBaseline: true });
128
+ if (externalOutputs.length && !acceptanceCommands?.length) throw new Error("shared outputs require explicit acceptance commands");
129
+ if (externalOutputs.length && sandbox === "read-only") throw new Error("a read-only worker cannot declare writable shared outputs");
130
+ if (networkAccess && sandbox === "danger-full-access") throw new Error("sandbox.network_access is only for the sandboxed workers");
131
+ 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 sandbox.network_access: true and owned_paths: []");
132
+ if (!Array.isArray(writableRoots) || writableRoots.length > 20 || writableRoots.some((root) => typeof root !== "string" || !isAbsolute(root))) {
133
+ throw new Error("sandbox.writable_roots must be a list of at most 20 absolute paths");
134
+ }
135
+ if (writableRoots.length && sandbox !== "workspace-write") throw new Error("sandbox.writable_roots is only configurable for workspace-write workers");
136
+ // Codex refuses a writable root with a symlink component and then fails every
137
+ // command in the worker, so a declared root is stored resolved. Passing the
138
+ // alias would look fine in the receipt and break the run.
139
+ const resolvedWritableRoots = [];
140
+ for (const root of writableRoots) {
141
+ const resolved = resolveWritableRoot(root);
142
+ if (resolved.error) throw new Error(`sandbox.writable_roots entry is unusable: ${root} (${resolved.error}); pass an existing directory whose path has no symlink component`);
143
+ resolvedWritableRoots.push(resolved.path);
144
+ }
145
+ 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");
146
+ for (const [name, values] of Object.entries({ forbid, allowedCommands })) {
147
+ 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`);
148
+ }
149
+ if (baseRef && !isGitCheckout(cwd)) throw invalidBaseRefError(cwd, baseRef);
150
+ if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
151
+ || preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
152
+ throw new Error("preflight.probe_commands must be a nonempty list of shell commands");
153
+ }
154
+ return { acceptanceCommands, validatedGoal, resolvedWritableRoots };
155
+ }
156
+
157
+ async function claimWorkspace(input, id, acceptanceCommands) {
158
+ const { cwd, workspaceKind, sandbox, ownedPaths, networkAccess, externalOutputs, inPlaceAuthorization, preflight, workspaceSetup } = input;
159
+ const workspace = await prepareWorkspace({
160
+ cwd,
161
+ workspaceKind,
162
+ sandbox,
163
+ ownedPaths,
164
+ networkAccess,
165
+ acceptance: acceptanceCommands,
166
+ externalOutputs,
167
+ inPlaceAuthorization,
168
+ taskId: id,
169
+ isPreflight: Boolean(preflight)
170
+ });
171
+ const projectRoot = workspace.sourceRoot;
172
+ const normalizedOwnedPaths = normalizeOwnedPaths([...ownedPaths, ...externalOutputs.map((entry) => entry.path)], projectRoot);
173
+ const normalizedWorkspaceSetup = normalizeWorkspaceSetup(workspaceSetup, projectRoot);
174
+ if (normalizedWorkspaceSetup && workspace.kind !== "git_worktree") throw new Error("workspace.setup is only supported for git_worktree workers");
175
+ assertWorkspaceAllowed(input.runner, input.confined, workspace.kind);
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", newWorkerBranch(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", "workspace.kind 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, runner: input.runner
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: input.runner,
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
+ branch: worktreePath ? newWorkerBranch(id) : null
281
+ },
282
+ sandbox,
283
+ model,
284
+ reasoning_effort: reasoningEffort,
285
+ skip_git_repo_check: skipGitRepoCheck,
286
+ followup_of: followupOf,
287
+ resumed_from: null,
288
+ session_id: sessionId ?? null,
289
+ thread_id: null,
290
+ owned_paths: normalizedOwnedPaths,
291
+ guard_policy: {
292
+ ...guardPolicy,
293
+ ...(preflightMetadata ? { preflight: preflightMetadata } : {}),
294
+ ...(preflightId ? { preflight_source_id: preflightId } : {}),
295
+ workspace: {
296
+ kind: workspace.kind,
297
+ source_root: workspace.sourceRoot,
298
+ execution_root: effectiveCwd,
299
+ manifest_paths: workspace.manifestPaths,
300
+ before_manifest_sha256: workspace.beforeManifest?.sha256 ?? null
301
+ }
302
+ },
303
+ input_context: { context, contracts },
304
+ depends_on: Array.isArray(dependsOn) ? dependsOn : [],
305
+ goal_objective: validatedGoal.objective,
306
+ goal_token_budget: validatedGoal.tokenBudget,
307
+ goal_status: null,
308
+ goal_tokens_used: null,
309
+ goal_time_used_seconds: null,
310
+ goal_updated_at: null,
311
+ run_count: 0,
312
+ worktree_path: worktreePath,
313
+ base_commit: worktree.baseCommit,
314
+ acceptance: combinedAcceptance,
315
+ acceptance_local: acceptanceCommands,
316
+ session_policy_revision: session?.policy_revision ?? null,
317
+ acceptance_timeout_ms: combinedAcceptance ? (acceptanceTimeoutMs ?? DEFAULT_ACCEPTANCE_TIMEOUT_MS) : null,
318
+ acceptance_results: null,
319
+ prompt: task,
320
+ changed_files: [],
321
+ commands: [],
322
+ created_at: new Date().toISOString(),
323
+ updated_at: new Date().toISOString(),
324
+ run_log: taskRunPath(id)
325
+ };
326
+ return record;
327
+ }
328
+
329
+ async function assertPreflightMatches(preflightId, runtimeContract) {
330
+ const preflightTask = await getTask(preflightId);
331
+ const preflightResult = readPreflightResult(preflightTask);
332
+ if (preflightResult.status !== "passed") {
333
+ throw coded("preflight_not_passed", `preflight ${preflightId} is ${preflightResult.status}; wait for its probes to pass before dispatching this worker`, preflightResult);
334
+ }
335
+ const contractHash = runtimeContractHash(runtimeContract);
336
+ if (preflightResult.contract_hash === contractHash) return;
337
+ throw coded("preflight_mismatch", `preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing workspace.base_ref, sandbox, owned_paths, commands, context, contracts, network or writable roots`, {
338
+ preflight_id: preflightId,
339
+ expected_contract_hash: contractHash,
340
+ actual_contract_hash: preflightResult.contract_hash,
341
+ preflight: { expected_contract: runtimeContract, actual_contract: preflightResult.contract }
342
+ });
343
+ }
344
+
345
+ // Dependencies, the preflight contract and the path reservation. A refusal
346
+ // here removes the worktree and scratch directory made for this dispatch.
347
+ async function admitWorker(record, { dependsOn, preflightId }, { workspace, projectRoot, worktree, runtimeContract }) {
348
+ try {
349
+ await validateDependencies(dependsOn, projectRoot, worktree.baseCommit);
350
+ if (preflightId) await assertPreflightMatches(preflightId, runtimeContract);
351
+ await reserveTaskOwnership(record);
352
+ } catch (error) {
353
+ if (worktree.path) await discardWorktree(projectRoot, worktree.path, record.id);
354
+ if (workspace.scratchPath) await rm(workspace.scratchPath, { recursive: true, force: true }).catch(() => {});
355
+ throw error;
356
+ }
357
+ }
358
+
359
+ export async function createCodexWorker(rawInput) {
360
+ const runner = await loadRunner(rawInput.runner ?? DEFAULT_RUNNER);
361
+ const input = { ...withDispatchDefaults(rawInput), runner: runner.name, confined: runner.capabilities.os_sandbox };
362
+ const { acceptanceCommands, validatedGoal, resolvedWritableRoots } = await validateDispatch(input);
363
+ const id = `${runner.name}-${Date.now()}-${randomUUID().slice(0, 8)}`;
364
+ const place = await claimWorkspace(input, id, acceptanceCommands);
365
+ const { session, combinedAcceptance } = await sessionPolicy(input, acceptanceCommands);
366
+ requireDependencySetup({ kind: place.workspace.kind, projectRoot: place.projectRoot, setup: place.normalizedWorkspaceSetup,
367
+ commands: [...(combinedAcceptance ?? []), ...(input.preflight?.probeCommands ?? [])] });
368
+ const worktree = await createWorkerWorktree(place, id, input.baseRef);
369
+ const effectiveCwd = worktree.path ?? place.workspace.executionCwd;
370
+ const guard = buildGuard(input, place, worktree, resolvedWritableRoots);
371
+ const record = buildRecord(input, { id, ...place, worktree, effectiveCwd, ...guard, validatedGoal, combinedAcceptance, acceptanceCommands, session });
372
+ await admitWorker(record, input, { ...place, worktree, runtimeContract: guard.runtimeContract });
373
+
374
+ const { sandbox, model, reasoningEffort, skipGitRepoCheck, task } = input;
375
+ const args = runner.startArgs({ cwd: effectiveCwd, sandbox, model, reasoningEffort, skipGitRepoCheck });
376
+ const job = {
377
+ record,
378
+ args,
379
+ prompt: frameWorkerPrompt(task, {
380
+ objective: validatedGoal.objective,
381
+ tokenBudget: validatedGoal.tokenBudget
382
+ }, { acceptance: combinedAcceptance, outputSchema: true, nativeGoal: runner.capabilities.native_goal }),
383
+ logPath: record.run_log,
384
+ outputSchema: true,
385
+ // --cd tells Codex where the agent works. The shell/tool process must also
386
+ // inherit the worktree as its OS cwd: otherwise a login shell may restore
387
+ // the project directory and relative probes read the wrong checkout.
388
+ spawnOptions: { cwd: effectiveCwd }
389
+ };
390
+ try {
391
+ return (await startTrackedRun(job)).record;
392
+ } catch (error) {
393
+ // The row is reserved as queued, which blocks its paths for every later
394
+ // dispatch. A start that threw never ran, so the row is closed as failed.
395
+ await upsertTask(failedStart(job.record, `dispatch failed before the worker started: ${error.message}`).record).catch(() => {});
396
+ throw error;
397
+ }
398
+ }