codex-supervisor-mcp 0.13.4 → 0.13.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.en.md +101 -297
  2. package/README.md +99 -310
  3. package/package.json +24 -63
  4. package/src/{acceptance.js → app/acceptance.js} +54 -68
  5. package/src/app/cancel.js +60 -0
  6. package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
  7. package/src/app/compose.js +7 -0
  8. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  9. package/src/app/dispatch.js +396 -0
  10. package/src/app/followup.js +98 -0
  11. package/src/app/land-chain.js +124 -0
  12. package/src/app/landing.js +357 -0
  13. package/src/app/ownership.js +57 -0
  14. package/src/app/rebase.js +216 -0
  15. package/src/app/resume.js +164 -0
  16. package/src/app/run-state.js +26 -0
  17. package/src/app/settled.js +28 -0
  18. package/src/{side-chat.js → app/side-chat.js} +79 -266
  19. package/src/app/sse.js +20 -0
  20. package/src/app/start-run.js +77 -0
  21. package/src/app/verify-push.js +119 -0
  22. package/src/app/worktree-setup.js +176 -0
  23. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  24. package/src/domain/acceptance-spec.js +30 -0
  25. package/src/domain/command-outcome.js +6 -0
  26. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  27. package/src/domain/side-turn-view.js +73 -0
  28. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  29. package/src/infra/git.js +30 -0
  30. package/src/infra/process.js +59 -0
  31. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  32. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  33. package/src/infra/store/db.js +265 -0
  34. package/src/infra/store/events.js +146 -0
  35. package/src/infra/store/facts.js +338 -0
  36. package/src/infra/store/reconcile.js +172 -0
  37. package/src/infra/store/records.js +160 -0
  38. package/src/infra/store/runner-readers.js +16 -0
  39. package/src/infra/store/schema.js +306 -0
  40. package/src/infra/store/sessions.js +138 -0
  41. package/src/infra/store/tasks.js +307 -0
  42. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  43. package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
  44. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  45. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  46. package/src/{worktree.js → infra/worktree.js} +57 -42
  47. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  48. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  49. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  50. package/src/{setup.js → interface/bin/setup.js} +9 -8
  51. package/src/{stage.js → interface/bin/stage.js} +1 -1
  52. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  53. package/src/interface/mcp/meta.js +7 -0
  54. package/src/interface/mcp/result.js +34 -0
  55. package/src/interface/mcp/schemas.js +24 -0
  56. package/src/interface/mcp/server.js +94 -0
  57. package/src/interface/mcp/tools/delivery.js +197 -0
  58. package/src/interface/mcp/tools/dispatch.js +267 -0
  59. package/src/interface/mcp/tools/facts.js +239 -0
  60. package/src/interface/mcp/tools/overview.js +202 -0
  61. package/src/interface/mcp/tools/poll.js +62 -0
  62. package/src/interface/mcp/tools/results.js +270 -0
  63. package/src/interface/mcp/tools/review.js +135 -0
  64. package/src/interface/mcp/tools/wait.js +145 -0
  65. package/src/interface/mcp/update-state.js +34 -0
  66. package/src/interface/mcp/views/overview.js +183 -0
  67. package/src/interface/mcp/views/task.js +223 -0
  68. package/src/interface/web/app.js +226 -0
  69. package/src/interface/web/views.js +224 -0
  70. package/src/mcp-server.js +3 -2223
  71. package/src/run-host/entry.js +23 -0
  72. package/src/run-host/finalize.js +236 -0
  73. package/src/run-host/launch.js +63 -0
  74. package/src/run-host/live-run.js +73 -0
  75. package/src/run-host/outcome-facts.js +61 -0
  76. package/src/run-host/streams.js +76 -0
  77. package/src/run-host/track.js +128 -0
  78. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  79. package/src/runners/codex/chat-chunks.js +97 -0
  80. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  81. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  82. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  83. package/src/codex-runner.js +0 -1586
  84. package/src/landing.js +0 -507
  85. package/src/task-store.js +0 -1800
  86. package/src/web-app.js +0 -425
  87. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  88. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  89. /package/src/{prompt.js → domain/prompt.js} +0 -0
  90. /package/src/{status.js → domain/status.js} +0 -0
  91. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  92. /package/src/{truncate.js → domain/truncate.js} +0 -0
  93. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  94. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  95. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  96. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  97. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  98. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  99. /package/src/{external-output.js → infra/external-output.js} +0 -0
  100. /package/src/{handoff.js → infra/handoff.js} +0 -0
  101. /package/src/{paths.js → infra/paths.js} +0 -0
  102. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  103. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -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
+ }
@@ -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,124 @@
1
+ import "./compose.js";
2
+ import { runGit } from "../infra/git.js";
3
+ import { appendTaskEvent } from "../infra/store/events.js";
4
+ import { getSession } from "../infra/store/sessions.js";
5
+ import { getTask, upsertTask } from "../infra/store/tasks.js";
6
+ import { getWorkItemForTask, recordFact } from "../infra/store/facts.js";
7
+ import { runIdFor } from "../infra/store/db.js";
8
+ import { updateWorkItemDelivery } from "../infra/store/records.js";
9
+ import { isSettled } from "./settled.js";
10
+ import { landWorker } from "./landing.js";
11
+ import { existsSync } from "node:fs";
12
+
13
+ export const git = (cwd, args) => runGit(cwd, args, { timeout: 60000 });
14
+
15
+ async function recordWorkerLanded(task, { head, branch, target, source = "git_land", alreadyLanded = [] }) {
16
+ const now = new Date().toISOString();
17
+ const landed = { ...task, landed_at: now, landed_head: head ?? null, landed_branch: branch ?? null, updated_at: now };
18
+ await upsertTask(landed);
19
+ await updateWorkItemDelivery(task.id, "landed");
20
+ const event = await appendTaskEvent(task.id, {
21
+ type: "supervisor.landed",
22
+ head: head ?? null,
23
+ branch: branch ?? null,
24
+ target: target ?? null,
25
+ source,
26
+ already_landed: alreadyLanded,
27
+ landed_at: now
28
+ }, { runId: runIdFor(task.id, task.run_count ?? 1), actor: "supervisor" });
29
+ const workItem = await getWorkItemForTask(task.id);
30
+ if (workItem && head) {
31
+ await recordFact({
32
+ workItemId: workItem.id,
33
+ scopeType: "work_item",
34
+ scopeId: workItem.id,
35
+ key: "landed",
36
+ value: { head, branch: branch ?? null, source },
37
+ state: "verified",
38
+ sourceEventId: event.id,
39
+ validForSha: head,
40
+ watchedPaths: task.owned_paths ?? [],
41
+ verifiedBy: `supervisor.${source}`
42
+ });
43
+ await recordFact({
44
+ workItemId: workItem.id,
45
+ scopeType: "dependency",
46
+ scopeId: workItem.id,
47
+ key: "landed_delivery_summary",
48
+ value: { task_id: task.id, landed_head: head, branch: branch ?? null, acceptance: task.acceptance_results?.passed === true ? "passed" : "not_configured_or_not_passed", source },
49
+ state: "verified",
50
+ sourceEventId: event.id,
51
+ validForSha: head,
52
+ watchedPaths: task.owned_paths ?? [],
53
+ verifiedBy: `supervisor.${source}`
54
+ });
55
+ }
56
+ return { landed, event };
57
+ }
58
+
59
+ export async function landOneWorkerTask(taskId, options = {}) {
60
+ const { onto = null, commitMessage = null, ignoreAcceptance = false, allowOutsideOwned = false, skipAlreadyLanded = false } = options;
61
+ const task = await getTask(taskId);
62
+ if (!task) return { error: "task_not_found", task_id: taskId };
63
+ if (task.workspace_kind && task.workspace_kind !== "legacy" && task.workspace_kind !== "git_worktree") {
64
+ 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` };
65
+ }
66
+ const session = task.session_id ? await getSession(task.session_id) : null;
67
+ if (!isSettled(task)) return { error: "worker_active", task_id: taskId, reason: "wait for this run and acceptance to settle before landing" };
68
+ if (session?.approval_state === "waiting_user") return { error: "session_waiting_user", task_id: taskId, reason: "session requires user approval before landing" };
69
+ 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" };
70
+ if (skipAlreadyLanded && task.landed_at && (!task.worktree_path || !existsSync(task.worktree_path))) {
71
+ try {
72
+ const targetBranch = git(task.project_root, ["symbolic-ref", "--short", "HEAD"]);
73
+ if (onto && onto !== targetBranch) return { error: "wrong_branch", task_id: taskId, current_branch: targetBranch };
74
+ if (!ignoreAcceptance && task.acceptance?.length && task.acceptance_results?.passed !== true) {
75
+ return { error: "acceptance_not_run", task_id: taskId };
76
+ }
77
+ git(task.project_root, ["merge-base", "--is-ancestor", task.landed_head, "HEAD"]);
78
+ 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 };
79
+ } catch {
80
+ 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" };
81
+ }
82
+ }
83
+ const outcome = landWorker(task, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned });
84
+ if (outcome.error === "nothing_to_land" && outcome.already_landed?.length > 0
85
+ && (outcome.uncommitted ?? []).length === 0) {
86
+ const alreadyRecorded = task.landed_at && task.landed_head === outcome.matched_head;
87
+ if (!alreadyRecorded && outcome.matched_head) {
88
+ await recordWorkerLanded(task, {
89
+ head: outcome.matched_head,
90
+ branch: outcome.onto,
91
+ target: outcome.target,
92
+ source: "patch_equivalent",
93
+ alreadyLanded: outcome.already_landed
94
+ });
95
+ }
96
+ return {
97
+ task_id: taskId,
98
+ title: task.title,
99
+ status: task.status,
100
+ branch: `codex/${task.id}`,
101
+ ...outcome,
102
+ skipped: "already_in_target",
103
+ lifecycle_recorded: !alreadyRecorded && Boolean(outcome.matched_head)
104
+ };
105
+ }
106
+ if (outcome.error) return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
107
+ await recordWorkerLanded(task, { head: outcome.head, branch: outcome.onto, target: outcome.target, alreadyLanded: outcome.already_landed ?? [] });
108
+ return { task_id: taskId, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome };
109
+ }
110
+
111
+ export async function followupChainIds(taskId) {
112
+ const ids = [];
113
+ const seen = new Set();
114
+ let current = taskId;
115
+ for (;;) {
116
+ if (seen.has(current)) throw new Error(`followup cycle detected at ${current}`);
117
+ seen.add(current);
118
+ const task = await getTask(current);
119
+ if (!task) throw new Error(`task not found: ${current}`);
120
+ ids.unshift(current);
121
+ if (!task.followup_of) return ids;
122
+ current = task.followup_of;
123
+ }
124
+ }