codex-supervisor-mcp 0.13.5 → 0.13.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/package.json +18 -63
  2. package/src/{acceptance.js → app/acceptance.js} +54 -68
  3. package/src/app/cancel.js +60 -0
  4. package/src/{cleanup-plan.js → app/cleanup-plan.js} +11 -12
  5. package/src/app/compose.js +7 -0
  6. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  7. package/src/app/dispatch.js +396 -0
  8. package/src/app/followup.js +98 -0
  9. package/src/app/land-chain.js +124 -0
  10. package/src/app/landing.js +357 -0
  11. package/src/app/ownership.js +57 -0
  12. package/src/app/rebase.js +216 -0
  13. package/src/app/resume.js +164 -0
  14. package/src/app/run-state.js +26 -0
  15. package/src/app/settled.js +28 -0
  16. package/src/{side-chat.js → app/side-chat.js} +79 -265
  17. package/src/app/sse.js +20 -0
  18. package/src/app/start-run.js +77 -0
  19. package/src/app/verify-push.js +119 -0
  20. package/src/app/worktree-setup.js +176 -0
  21. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  22. package/src/domain/acceptance-spec.js +30 -0
  23. package/src/domain/command-outcome.js +6 -0
  24. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  25. package/src/domain/side-turn-view.js +73 -0
  26. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  27. package/src/infra/git.js +30 -0
  28. package/src/infra/process.js +59 -0
  29. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  30. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  31. package/src/infra/store/db.js +265 -0
  32. package/src/infra/store/events.js +146 -0
  33. package/src/infra/store/facts.js +338 -0
  34. package/src/infra/store/reconcile.js +172 -0
  35. package/src/infra/store/records.js +160 -0
  36. package/src/infra/store/runner-readers.js +16 -0
  37. package/src/infra/store/schema.js +306 -0
  38. package/src/infra/store/sessions.js +138 -0
  39. package/src/infra/store/tasks.js +307 -0
  40. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  41. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  42. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  43. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  44. package/src/{worktree.js → infra/worktree.js} +56 -41
  45. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  46. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  47. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  48. package/src/{setup.js → interface/bin/setup.js} +7 -6
  49. package/src/{stage.js → interface/bin/stage.js} +1 -1
  50. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  51. package/src/interface/mcp/meta.js +7 -0
  52. package/src/interface/mcp/result.js +34 -0
  53. package/src/interface/mcp/schemas.js +24 -0
  54. package/src/interface/mcp/server.js +94 -0
  55. package/src/interface/mcp/tools/delivery.js +197 -0
  56. package/src/interface/mcp/tools/dispatch.js +267 -0
  57. package/src/interface/mcp/tools/facts.js +239 -0
  58. package/src/interface/mcp/tools/overview.js +202 -0
  59. package/src/interface/mcp/tools/poll.js +62 -0
  60. package/src/interface/mcp/tools/results.js +270 -0
  61. package/src/interface/mcp/tools/review.js +135 -0
  62. package/src/interface/mcp/tools/wait.js +145 -0
  63. package/src/interface/mcp/update-state.js +34 -0
  64. package/src/interface/mcp/views/overview.js +183 -0
  65. package/src/interface/mcp/views/task.js +223 -0
  66. package/src/interface/web/app.js +226 -0
  67. package/src/interface/web/views.js +224 -0
  68. package/src/mcp-server.js +3 -2223
  69. package/src/run-host/entry.js +23 -0
  70. package/src/run-host/finalize.js +236 -0
  71. package/src/run-host/launch.js +63 -0
  72. package/src/run-host/live-run.js +73 -0
  73. package/src/run-host/outcome-facts.js +61 -0
  74. package/src/run-host/streams.js +76 -0
  75. package/src/run-host/track.js +128 -0
  76. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  77. package/src/runners/codex/chat-chunks.js +97 -0
  78. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  79. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  80. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  81. package/src/codex-runner.js +0 -1586
  82. package/src/landing.js +0 -507
  83. package/src/task-store.js +0 -1800
  84. package/src/web-app.js +0 -425
  85. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  86. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  87. /package/src/{prompt.js → domain/prompt.js} +0 -0
  88. /package/src/{status.js → domain/status.js} +0 -0
  89. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  90. /package/src/{truncate.js → domain/truncate.js} +0 -0
  91. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  92. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  93. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  94. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  95. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  96. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  97. /package/src/{external-output.js → infra/external-output.js} +0 -0
  98. /package/src/{handoff.js → infra/handoff.js} +0 -0
  99. /package/src/{paths.js → infra/paths.js} +0 -0
  100. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  101. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // Entry for `codex-supervisor-web`. Decides which store to open, then starts
3
- // the board (web-app.js).
3
+ // the board (web/app.js).
4
4
  //
5
5
  // codex-supervisor-web # http://127.0.0.1:7877
6
6
  // SUPERVISOR_WEB_PORT=8080 codex-supervisor-web
@@ -45,5 +45,5 @@ if (!process.env.SUPERVISOR_HOME?.trim()) {
45
45
 
46
46
  // paths.js reads SUPERVISOR_HOME when it is first imported, so the import
47
47
  // has to come after the detection above.
48
- const { startWebServer } = await import("./web-app.js");
48
+ const { startWebServer } = await import("../web/app.js");
49
49
  startWebServer({ storeOrigin });
@@ -0,0 +1,7 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ // Report the real package version. This string had drifted to 0.4.0 while the
4
+ // package shipped 0.5.x, so the handshake named a version nobody was running.
5
+ export const packageVersion = JSON.parse(
6
+ readFileSync(new URL("../../../package.json", import.meta.url), "utf8")
7
+ ).version;
@@ -0,0 +1,34 @@
1
+ export function textResult(value) {
2
+ return {
3
+ content: [
4
+ {
5
+ type: "text",
6
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
7
+ }
8
+ ]
9
+ };
10
+ }
11
+
12
+ export function clip(value, maxChars) {
13
+ if (value === null || value === undefined) return null;
14
+ const text = String(value);
15
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
16
+ }
17
+
18
+ export function sleep(ms) {
19
+ return new Promise((resolve) => setTimeout(resolve, ms));
20
+ }
21
+
22
+ function errorDetails(details) {
23
+ return { files: details.files ?? [], git: details.git ?? null, base_commit: details.base_commit ?? null, head: details.head ?? null };
24
+ }
25
+
26
+ export function errorResult(error) {
27
+ return textResult({
28
+ error: error.code ?? "error",
29
+ message: error.message,
30
+ ...(error.conflicts ? { conflicts: error.conflicts } : {}),
31
+ ...(error.details?.preflight ? { preflight: error.details.preflight } : {}),
32
+ ...(error.details ? errorDetails(error.details) : {})
33
+ });
34
+ }
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+
3
+ const acceptanceFailureRecord = z.object({
4
+ test_id: z.string().min(1), kind: z.enum(["failure", "error"]), signature: z.string().min(1)
5
+ }).strict();
6
+ export const acceptanceCheck = z.union([
7
+ z.string().min(1),
8
+ z.object({
9
+ command: z.string().min(1), reportPath: z.string().min(1),
10
+ baseline: z.object({
11
+ identity: z.object({ base_commit: z.string().min(1) }).catchall(z.string().min(1)),
12
+ failures: z.array(acceptanceFailureRecord), required: z.array(z.string().min(1))
13
+ }).strict()
14
+ }).strict()
15
+ ]);
16
+ export const acceptanceInput = z.union([z.string().min(1), z.array(acceptanceCheck).max(10)]);
17
+ export const workspaceSetupInput = z.object({
18
+ links: z.array(z.object({
19
+ path: z.string().min(1),
20
+ source: z.string().min(1)
21
+ }).strict()).max(20).optional(),
22
+ submodules: z.boolean().optional(),
23
+ commands: z.array(z.string().min(1)).max(20).optional()
24
+ }).strict();
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ import "../../app/compose.js";
3
+ import { syncSkills } from "../../infra/skill-sync.js";
4
+ import { packageVersion } from "./meta.js";
5
+ import { refreshUpdateState, UPDATE_RECHECK_MS } from "./update-state.js";
6
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+
9
+ import { overviewDeltaTool, checkWorkersTool } from "./tools/poll.js";
10
+ import { checkAcceptanceTool, preflightCodexWorkerTool, getWorkerPreflightTool, createCodexWorkerTool, createCodexFollowupWorkerTool, resumeCodexWorkerTool } from "./tools/dispatch.js";
11
+ import { listCodexWorkersTool, getOrchestrationOverviewTool, getSessionWorksTool, checkForUpdateTool, describeSessionTool, searchWorksTool, getCodexWorkerStatusTool, getCodexWorkerEventsTool } from "./tools/overview.js";
12
+ import { waitCodexWorkersTool } from "./tools/wait.js";
13
+ import { getContextSnapshotMetaTool, getFactTool, getArtifactTool, promoteWorkerFactTool, revokeWorkerFactTool, getWorkerEvidenceTool, searchWorkerFactsTool } from "./tools/facts.js";
14
+ import { createIndependentVerifierTool, recordIndependentFindingTool, resolveIndependentFindingTool, getIndependentReviewTool } from "./tools/review.js";
15
+ import { getWorkerGoalTool, getWorkerSummaryTool, getWorkerResultTool, getWorkerDiffTool, askCodexWorkerTool } from "./tools/results.js";
16
+ import { landCodexWorkerTool, verifyDeliveryPushTool, cleanupPlanTool, applyCleanupTool, cleanupHistoryTool, cancelCodexWorkerTool } from "./tools/delivery.js";
17
+
18
+ const server = new McpServer({
19
+ name: "codex-supervisor",
20
+ version: packageVersion
21
+ });
22
+
23
+ refreshUpdateState();
24
+ setInterval(() => refreshUpdateState({ force: true }), UPDATE_RECHECK_MS).unref();
25
+
26
+ // The skill describes this tool surface, so it moves with the server: a
27
+ // server fetched by `npx -y codex-supervisor-mcp@latest` never ran postinstall,
28
+ // and a global install only synced the skill on the day it was installed.
29
+ // Runs in the background; a client that cannot write its skill directory
30
+ // only costs a line on stderr.
31
+ if (!process.env.CODEX_SUPERVISOR_SKIP_SKILL_SYNC) {
32
+ syncSkills()
33
+ .then((result) => {
34
+ const changed = [...result.installed, ...result.updated];
35
+ if (changed.length > 0) {
36
+ process.stderr.write(
37
+ `[codex-supervisor] skill synced for ${changed.join(", ")}; a session that already loaded the skill keeps the old text until it loads it again\n`
38
+ );
39
+ }
40
+ for (const failure of result.failed) {
41
+ process.stderr.write(`[codex-supervisor] skill sync failed: ${failure}\n`);
42
+ }
43
+ })
44
+ .catch((error) => {
45
+ process.stderr.write(`[codex-supervisor] skill sync failed: ${error.message}\n`);
46
+ });
47
+ }
48
+
49
+ // Registration order is part of the contract: tools/list returns it.
50
+ const TOOLS = [
51
+ overviewDeltaTool,
52
+ checkWorkersTool,
53
+ checkAcceptanceTool,
54
+ preflightCodexWorkerTool,
55
+ getWorkerPreflightTool,
56
+ createCodexWorkerTool,
57
+ createCodexFollowupWorkerTool,
58
+ resumeCodexWorkerTool,
59
+ listCodexWorkersTool,
60
+ getOrchestrationOverviewTool,
61
+ waitCodexWorkersTool,
62
+ getSessionWorksTool,
63
+ checkForUpdateTool,
64
+ describeSessionTool,
65
+ searchWorksTool,
66
+ getCodexWorkerStatusTool,
67
+ getCodexWorkerEventsTool,
68
+ getContextSnapshotMetaTool,
69
+ getFactTool,
70
+ getArtifactTool,
71
+ promoteWorkerFactTool,
72
+ revokeWorkerFactTool,
73
+ getWorkerEvidenceTool,
74
+ searchWorkerFactsTool,
75
+ createIndependentVerifierTool,
76
+ recordIndependentFindingTool,
77
+ resolveIndependentFindingTool,
78
+ getIndependentReviewTool,
79
+ getWorkerGoalTool,
80
+ getWorkerSummaryTool,
81
+ getWorkerResultTool,
82
+ getWorkerDiffTool,
83
+ askCodexWorkerTool,
84
+ landCodexWorkerTool,
85
+ verifyDeliveryPushTool,
86
+ cleanupPlanTool,
87
+ applyCleanupTool,
88
+ cleanupHistoryTool,
89
+ cancelCodexWorkerTool
90
+ ];
91
+ for (const tool of TOOLS) server.registerTool(...tool);
92
+
93
+ const transport = new StdioServerTransport();
94
+ await server.connect(transport);
@@ -0,0 +1,197 @@
1
+ import { verifyDeliveryPush } from "../../../app/verify-push.js";
2
+ import { applyCleanupPlan, createCleanupPlan } from "../../../app/cleanup-plan.js";
3
+ import { followupChainIds, git, landOneWorkerTask } from "../../../app/land-chain.js";
4
+ import { cancelCodexWorker } from "../../../app/cancel.js";
5
+ import { ACTIVE_STATUSES } from "../../../domain/status.js";
6
+ import { getCleanupPlan, readCleanupHistory, saveCleanupPlan } from "../../../infra/store/records.js";
7
+ import { getTask, upsertTask } from "../../../infra/store/tasks.js";
8
+ import { errorResult, textResult } from "../result.js";
9
+ import { z } from "zod";
10
+
11
+ export const landCodexWorkerTool = [
12
+ "land_codex_worker",
13
+ {
14
+ title: "Land a worker's commits",
15
+ description:
16
+ "Cherry-pick the commits a worker made on its codex/<taskId> branch onto the current branch of the directory it was dispatched from. The target must be clean and is never switched to another branch; `onto` is a guard that names the branch you expect to be on. A conflict aborts the cherry-pick, lists the files, and leaves the target as it was. A worker in the workspace-write sandbox cannot commit (Codex keeps .git read-only there): pass commitMessage and its uncommitted edits are committed as one commit on its branch first, then landed. Without commitMessage uncommitted edits are reported, not landed. includeFollowupParents lands an unlanded followup chain root-first; commitMessages supplies a per-task checkpoint message when an ancestor has uncommitted edits. Check the work first with get_worker_result and get_worker_diff; land once it passes. A malformed report summary is attention, not a separate landing veto when the same run's acceptance passed and the reviewed diff is sound. Refuses with acceptance_failed while the worker's last acceptance run failed (and acceptance_not_run while one is running or was interrupted): resume it with the failing output, land once it passes. ignoreAcceptance: true lands anyway; use it only when the user said to land regardless.",
17
+ inputSchema: {
18
+ task_id: z.string().min(1),
19
+ onto: z.string().min(1).optional(),
20
+ commitMessage: z.string().min(1).optional(),
21
+ includeFollowupParents: z.boolean().default(false),
22
+ commitMessages: z.record(z.string(), z.string().min(1)).optional(),
23
+ ignoreAcceptance: z.boolean().default(false),
24
+ allowOutsideOwned: z.boolean().default(false)
25
+ }
26
+ },
27
+ async ({ task_id, onto, commitMessage, includeFollowupParents, commitMessages, ignoreAcceptance, allowOutsideOwned }) => {
28
+ if (!includeFollowupParents) {
29
+ const task = await getTask(task_id);
30
+ if (task?.followup_of) {
31
+ let ids;
32
+ try { ids = await followupChainIds(task_id); }
33
+ catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
34
+ const unlanded = [];
35
+ for (const id of ids.slice(0, -1)) {
36
+ const ancestor = await getTask(id);
37
+ if (ancestor) {
38
+ try {
39
+ if (!ancestor.landed_at || !ancestor.landed_head) throw new Error("parent not landed");
40
+ git(task.project_root, ["merge-base", "--is-ancestor", ancestor.landed_head, "HEAD"]);
41
+ } catch { unlanded.push(id); }
42
+ }
43
+ }
44
+ if (unlanded.length) {
45
+ return textResult({
46
+ error: "followup_parents_not_landed",
47
+ task_id,
48
+ unlanded,
49
+ reason: "this follow-up starts from its parent branch; landing only the leaf would integrate a partial chain. Use includeFollowupParents: true after reviewing every task's acceptance and diff."
50
+ });
51
+ }
52
+ }
53
+ return textResult(await landOneWorkerTask(task_id, { onto, commitMessage, ignoreAcceptance, allowOutsideOwned }));
54
+ }
55
+ let ids;
56
+ try { ids = await followupChainIds(task_id); }
57
+ catch (error) { return textResult({ error: "invalid_followup_chain", task_id, reason: error.message }); }
58
+ const chain = [];
59
+ for (const id of ids) {
60
+ let result;
61
+ try { result = await landOneWorkerTask(id, {
62
+ onto,
63
+ commitMessage: commitMessages?.[id] ?? (id === task_id ? commitMessage : null),
64
+ ignoreAcceptance: id === task_id && ignoreAcceptance,
65
+ allowOutsideOwned: id === task_id && allowOutsideOwned,
66
+ skipAlreadyLanded: true
67
+ }); } catch (error) {
68
+ result = { task_id: id, error: "landing_failed", reason: error.message };
69
+ }
70
+ if (id !== task_id && result.error === "nothing_to_land"
71
+ && (result.uncommitted ?? []).length === 0 && !(result.already_landed?.length)) {
72
+ chain.push({ ...result, error: null, skipped: "no_changes" });
73
+ continue;
74
+ }
75
+ if (result.skipped === "already_in_target" && (result.uncommitted ?? []).length === 0) {
76
+ chain.push({ ...result, error: null, skipped: "already_in_target" });
77
+ continue;
78
+ }
79
+ chain.push(result);
80
+ if (result.error) {
81
+ return textResult({ error: "followup_chain_land_failed", task_id, failed_task_id: id, chain });
82
+ }
83
+ }
84
+ return textResult({ task_id, chain });
85
+ }
86
+ ];
87
+
88
+ export const verifyDeliveryPushTool = [
89
+ "verify_delivery_push",
90
+ {
91
+ title: "Verify landed work reached a remote branch",
92
+ description: "Fetch a remote branch and prove the worker's landed_head is reachable from it. This never pushes or deploys. A passing check records push_verified; cleanup eligibility may depend on this evidence.",
93
+ inputSchema: {
94
+ task_id: z.string().min(1),
95
+ remote: z.string().min(1).default("origin"),
96
+ branch: z.string().min(1).optional()
97
+ }
98
+ },
99
+ async ({ task_id, remote, branch }) => textResult(await verifyDeliveryPush({ taskId: task_id, remote, branch }))
100
+ ];
101
+
102
+ export const cleanupPlanTool = [
103
+ "cleanup_plan",
104
+ {
105
+ title: "Plan safe worktree cleanup",
106
+ description: "Classify managed worktrees as safe, review or blocked. The plan is read-only, expires after 15 minutes, estimates reclaimable bytes and never deletes branches, task rows, events, JSONL logs or artifacts.",
107
+ inputSchema: {
108
+ task_ids: z.array(z.string().min(1)).max(200).optional(),
109
+ project_root: z.string().min(1).optional()
110
+ }
111
+ },
112
+ async ({ task_ids, project_root }) => {
113
+ try {
114
+ const plan = await createCleanupPlan({ taskIds: task_ids ?? null, projectRoot: project_root ?? null });
115
+ await saveCleanupPlan(plan);
116
+ return textResult({
117
+ plan_id: plan.id,
118
+ generated_at: plan.generated_at,
119
+ expires_at: plan.expires_at,
120
+ policy: plan.policy,
121
+ summary: plan.summary,
122
+ items: plan.items
123
+ });
124
+ } catch (error) {
125
+ return errorResult(error);
126
+ }
127
+ }
128
+ ];
129
+
130
+ export const applyCleanupTool = [
131
+ "apply_cleanup",
132
+ {
133
+ title: "Apply a safe cleanup plan",
134
+ description: "Remove only selected SAFE worktrees from an unexpired cleanup plan after a second proof check. Uses git worktree remove and prune only; retains the branch, task row, event stream, JSONL log and artifacts.",
135
+ inputSchema: {
136
+ plan_id: z.string().uuid(),
137
+ item_ids: z.array(z.string().uuid()).min(1).max(200)
138
+ }
139
+ },
140
+ async ({ plan_id, item_ids }) => {
141
+ const plan = await getCleanupPlan(plan_id);
142
+ if (!plan) return textResult({ error: "cleanup_plan_not_found", plan_id });
143
+ if (Date.parse(plan.expires_at) <= Date.now()) return textResult({ error: "cleanup_plan_expired", plan_id, expires_at: plan.expires_at });
144
+ return textResult(await applyCleanupPlan({ plan, itemIds: item_ids, actor: "main_thread" }));
145
+ }
146
+ ];
147
+
148
+ export const cleanupHistoryTool = [
149
+ "cleanup_history",
150
+ {
151
+ title: "Read cleanup history",
152
+ description: "Read cleanup plan decisions and applied worktree removals, including safe/review/blocked reasons. This is audit history, not a delete command.",
153
+ inputSchema: { task_id: z.string().min(1).optional(), limit: z.number().int().min(1).max(500).default(100) }
154
+ },
155
+ async ({ task_id, limit }) => textResult({ items: await readCleanupHistory(task_id ?? null, limit) })
156
+ ];
157
+
158
+ export const cancelCodexWorkerTool = [
159
+ "cancel_codex_worker",
160
+ {
161
+ title: "Cancel Codex worker",
162
+ description:
163
+ "Terminate a running Codex worker. Uses the in-process handle when available, otherwise the pid recorded on disk so a different MCP session can still cancel it.",
164
+ inputSchema: {
165
+ task_id: z.string().min(1)
166
+ }
167
+ },
168
+ async ({ task_id }) => {
169
+ const now = new Date().toISOString();
170
+ const task = await getTask(task_id);
171
+ // The marker is persisted before the signal is sent so the process that
172
+ // owns the worker reports "cancelled" instead of "lost" when it exits.
173
+ if (task && ACTIVE_STATUSES.has(task.status)) {
174
+ await upsertTask({ ...task, cancel_requested_at: now, updated_at: now });
175
+ }
176
+ const result = await cancelCodexWorker(task_id);
177
+ // A cancel that stopped an acceptance run leaves the worker's own
178
+ // terminal status in place; the exit handler records the verdict.
179
+ if (result.cancelled && task && result.via !== "acceptance") {
180
+ // The run host may have written the terminal row while the signal was
181
+ // being delivered. Read the row again and only close one that is still
182
+ // open; writing the earlier snapshot back would undo that final write.
183
+ const current = await getTask(task_id);
184
+ if (current && ACTIVE_STATUSES.has(current.status)) {
185
+ await upsertTask({
186
+ ...current,
187
+ status: "cancelled",
188
+ phase: null,
189
+ cancel_requested_at: now,
190
+ updated_at: now,
191
+ completed_at: current.completed_at ?? now
192
+ });
193
+ }
194
+ }
195
+ return textResult(result);
196
+ }
197
+ ];
@@ -0,0 +1,267 @@
1
+ import { runAcceptance } from "../../../app/acceptance.js";
2
+ import { createCodexWorker } from "../../../app/dispatch.js";
3
+ import { createFollowupWorker } from "../../../app/followup.js";
4
+ import { resumeCodexWorker } from "../../../app/resume.js";
5
+ import { readPreflightResult } from "../../../domain/worker-preflight.js";
6
+ import { runGit } from "../../../infra/git.js";
7
+ import { getTask } from "../../../infra/store/tasks.js";
8
+ import { baseBehind } from "../../../infra/worktree.js";
9
+ import { errorResult, textResult } from "../result.js";
10
+ import { acceptanceInput, workspaceSetupInput } from "../schemas.js";
11
+ import { withUpdate } from "../update-state.js";
12
+ import { receipt } from "../views/task.js";
13
+ import { randomUUID } from "node:crypto";
14
+ import { z } from "zod";
15
+
16
+ export const checkAcceptanceTool = [
17
+ "check_acceptance",
18
+ {
19
+ title: "Check acceptance commands",
20
+ description: "Run explicitly supplied acceptance commands in the requested project before dispatch. This executes the commands with supervisor privileges and can have their side effects; it creates no worker and does not prove worker completion. Structured checks require fresh execution evidence, while failure-count greps are flagged as insufficient baseline evidence.",
21
+ inputSchema: {
22
+ cwd: z.string().min(1), acceptance: acceptanceInput,
23
+ baseRef: z.string().min(1).optional(), timeoutMs: z.number().int().min(1000).max(1800000).default(600000)
24
+ }
25
+ },
26
+ async ({ cwd, acceptance, baseRef = "HEAD", timeoutMs }) => {
27
+ let base;
28
+ try {
29
+ base = runGit(cwd, ["rev-parse", "--verify", `${baseRef}^{commit}`], { timeout: 10000 });
30
+ } catch {
31
+ return textResult({ error: "invalid_base_ref", phase: "preflight", reason: `baseRef does not resolve in ${cwd}`, proves_worker_completion: false });
32
+ }
33
+ try {
34
+ const commands = Array.isArray(acceptance) ? acceptance : [acceptance];
35
+ const warnings = commands.filter((check) => typeof check === "string" && /(?:failures|errors)\s*=\s*\d/.test(check)).map(() => "failure-count checks do not prove baseline test identities or required execution; use structured evidence");
36
+ const result = await runAcceptance(commands, { cwd, timeoutMs, baseCommit: base, taskId: `preflight-${randomUUID()}` });
37
+ return textResult({ ...result, phase: "preflight", base_commit: base, proves_worker_completion: false, warnings });
38
+ } catch (error) {
39
+ return errorResult(error);
40
+ }
41
+ }
42
+ ];
43
+
44
+ export const preflightCodexWorkerTool = [
45
+ "preflight_codex_worker",
46
+ {
47
+ title: "Preflight Codex worker environment",
48
+ description:
49
+ "Launch a short-lived Codex probe worker in the same base commit, sandbox, guard, network and writable-root configuration intended for a later write worker. The probe must run every requested command in the actual worker environment. Read get_worker_preflight after it settles, then pass its task_id as create_codex_worker.preflight_id; a changed runtime contract is refused.",
50
+ inputSchema: {
51
+ title: z.string().optional(),
52
+ cwd: z.string().min(1),
53
+ sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
54
+ model: z.string().optional(),
55
+ reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
56
+ skipGitRepoCheck: z.boolean().default(true),
57
+ ownedPaths: z.array(z.string().min(1)),
58
+ forbid: z.array(z.string().min(1)).max(100).optional(),
59
+ allowedCommands: z.array(z.string().min(1)).max(100).optional(),
60
+ context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
61
+ contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
62
+ networkAccess: z.boolean().default(false),
63
+ writableRoots: z.array(z.string().min(1)).max(20).optional(),
64
+ maxRunMs: z.number().int().min(1000).max(86400000).optional(),
65
+ maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
66
+ baseRef: z.string().min(1).optional(),
67
+ workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
68
+ inPlaceAuthorization: z.string().min(1).max(2000).optional(),
69
+ workspaceSetup: workspaceSetupInput.optional(),
70
+ probeCommands: z.array(z.string().min(1)).min(1).max(20)
71
+ }
72
+ },
73
+ async (input) => {
74
+ try {
75
+ const task = [
76
+ "Runtime environment preflight. Do not edit files, create files, install packages, dispatch workers or call MCP tools.",
77
+ "Run every command below exactly once, in the listed order, without wrapping it in another shell command.",
78
+ "If any command is denied, missing, times out or exits nonzero, stop and quote the raw error under Not done / risks.",
79
+ "Commands:",
80
+ ...input.probeCommands.map((command) => `- ${command}`)
81
+ ].join("\n");
82
+ const record = await createCodexWorker({
83
+ ...input,
84
+ title: input.title ? `Preflight: ${input.title}` : "Runtime environment preflight",
85
+ task,
86
+ goal: { objective: `Prove the requested Codex worker runtime environment before dispatching ${input.title ?? "the dependent worker"}` },
87
+ acceptance: null,
88
+ preflight: { probeCommands: input.probeCommands }
89
+ });
90
+ return textResult(withUpdate({ ...receipt(record), preflight: { status: "running", probe_commands: input.probeCommands } }));
91
+ } catch (error) {
92
+ return errorResult(error);
93
+ }
94
+ }
95
+ ];
96
+
97
+ export const getWorkerPreflightTool = [
98
+ "get_worker_preflight",
99
+ {
100
+ title: "Get worker preflight result",
101
+ description: "Read whether a preflight probe ran every required command successfully in the tracked worker environment, plus the immutable runtime contract hash required by create_codex_worker.preflight_id.",
102
+ inputSchema: { task_id: z.string().min(1) }
103
+ },
104
+ async ({ task_id }) => {
105
+ const task = await getTask(task_id);
106
+ if (!task) return textResult({ error: "task_not_found", task_id });
107
+ return textResult(readPreflightResult(task));
108
+ }
109
+ ];
110
+
111
+ export const createCodexWorkerTool = [
112
+ "create_codex_worker",
113
+ {
114
+ title: "Create Codex worker",
115
+ description:
116
+ "Launch a Codex CLI worker with codex exec --json and track its events. workspaceKind controls where it runs: Git work writes only in an isolated git_worktree; read_only_in_place cannot write or use network; scratch writes only under SUPERVISOR_HOME and never lands; in_place_write is only for an explicitly authorized non-Git directory with ownedPaths and acceptance. A non-Git worker may never write the user directory by default. ownedPaths reserves files a landable worker may write; reading is never exclusive. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them after Codex exits, and workers run the same contract with codex-supervisor-accept. In a Git package project, acceptance using local JavaScript tooling requires workspaceSetup so node_modules and generated prepare files exist before dispatch. The worker's sandbox may write its execution directory, the temp directory and the OS cache directory; a toolchain whose cache lives elsewhere needs writableRoots, a list of existing absolute directories.",
117
+ inputSchema: {
118
+ title: z.string().optional(),
119
+ task: z.string().min(1),
120
+ cwd: z.string().min(1),
121
+ session_id: z.string().min(1).optional(),
122
+ // What this batch is about, in one line, so a reader of the store sees
123
+ // "给 12 个接口补单测" instead of a bare session id. Set it on
124
+ // the first dispatch of a session; later dispatches may omit it.
125
+ session_title: z.string().min(1).max(120).optional(),
126
+ session_note: z.string().min(1).max(2000).optional(),
127
+ sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
128
+ model: z.string().optional(),
129
+ reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
130
+ skipGitRepoCheck: z.boolean().default(true),
131
+ // Empty is the promise that nothing lands: a read-only verifier, or a
132
+ // research worker that reads, fetches and reports but merges nothing.
133
+ ownedPaths: z.array(z.string().min(1)),
134
+ forbid: z.array(z.string().min(1)).max(100).optional(),
135
+ allowedCommands: z.array(z.string().min(1)).max(100).optional(),
136
+ context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
137
+ contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
138
+ externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
139
+ networkAccess: z.boolean().default(false),
140
+ // Extra absolute directories the sandbox may write. The OS cache
141
+ // directory is already writable; this is for toolchains that keep a
142
+ // cache somewhere else (~/.m2, ~/.gradle, a vendored mirror).
143
+ writableRoots: z.array(z.string().min(1)).max(20).optional(),
144
+ maxRunMs: z.number().int().min(1000).max(86400000).optional(),
145
+ maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
146
+ goal: z.object({
147
+ objective: z.string().min(1),
148
+ tokenBudget: z.number().int().positive().optional()
149
+ }),
150
+ dependsOn: z.array(z.string().min(1)).optional(),
151
+ // Which commit the worktree is cut from. Defaults to the repository's
152
+ // HEAD; pass a branch, tag or sha to build on work that is not on the
153
+ // main line yet (for example another worker's codex/<id> branch).
154
+ baseRef: z.string().min(1).optional(),
155
+ workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
156
+ inPlaceAuthorization: z.string().min(1).max(2000).optional(),
157
+ workspaceSetup: workspaceSetupInput.optional(),
158
+ // A successful preflight_codex_worker task id. When present, this worker
159
+ // is refused unless base commit and the complete runtime contract match.
160
+ preflight_id: z.string().min(1).optional(),
161
+ // Shell commands that decide whether the work is done. The supervisor
162
+ // runs them in the worktree after codex exits; each must exit 0.
163
+ acceptance: acceptanceInput.optional(),
164
+ acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
165
+ }
166
+ },
167
+ async (input) => {
168
+ try {
169
+ const record = await createCodexWorker({
170
+ ...input,
171
+ preflightId: input.preflight_id ?? null,
172
+ sessionId: input.session_id ?? null,
173
+ sessionTitle: input.session_title ?? null,
174
+ sessionNote: input.session_note ?? null
175
+ });
176
+ return textResult(withUpdate(receipt(record)));
177
+ } catch (error) {
178
+ return errorResult(error);
179
+ }
180
+ }
181
+ ];
182
+
183
+ export const createCodexFollowupWorkerTool = [
184
+ "create_codex_followup_worker",
185
+ {
186
+ title: "Create Codex follow-up worker",
187
+ description:
188
+ "Start a NEW Codex session seeded with the previous worker's prompt, status, and recent events. Unlanded parents contribute their current codex/<parent> checkpoint; landed parents use the current target HEAD. Explicit baseRef overrides either; uncommitted parent edits are not copied. To continue the same session instead, use resume_codex_worker.",
189
+ inputSchema: {
190
+ task_id: z.string().min(1),
191
+ followup_prompt: z.string().min(1),
192
+ session_id: z.string().min(1).optional(),
193
+ session_title: z.string().min(1).max(120).optional(),
194
+ session_note: z.string().min(1).max(2000).optional(),
195
+ title: z.string().optional(),
196
+ cwd: z.string().optional(),
197
+ sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).optional(),
198
+ model: z.string().optional(),
199
+ reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
200
+ ownedPaths: z.array(z.string().min(1)).optional(),
201
+ forbid: z.array(z.string().min(1)).max(100).optional(),
202
+ allowedCommands: z.array(z.string().min(1)).max(100).optional(),
203
+ context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
204
+ contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
205
+ externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
206
+ networkAccess: z.boolean().optional(),
207
+ writableRoots: z.array(z.string().min(1)).max(20).optional(),
208
+ maxRunMs: z.number().int().min(1000).max(86400000).optional(),
209
+ maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
210
+ workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
211
+ inPlaceAuthorization: z.string().min(1).max(2000).optional(),
212
+ workspaceSetup: workspaceSetupInput.optional(),
213
+ goal: z
214
+ .object({
215
+ objective: z.string().min(1),
216
+ tokenBudget: z.number().int().positive().optional()
217
+ })
218
+ .optional(),
219
+ baseRef: z.string().min(1).optional(),
220
+ // Left out, the parent's acceptance commands are inherited; given, they
221
+ // replace them, and an empty list clears them.
222
+ acceptance: acceptanceInput.optional(),
223
+ acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
224
+ }
225
+ },
226
+ async ({ task_id, followup_prompt, session_id, session_title, session_note, ...options }) => {
227
+ try {
228
+ const record = await createFollowupWorker({
229
+ taskId: task_id,
230
+ followupPrompt: followup_prompt,
231
+ sessionId: session_id ?? null,
232
+ sessionTitle: session_title ?? null,
233
+ sessionNote: session_note ?? null,
234
+ ...options
235
+ });
236
+ return textResult(receipt(record));
237
+ } catch (error) {
238
+ return errorResult(error);
239
+ }
240
+ }
241
+ ];
242
+
243
+ export const resumeCodexWorkerTool = [
244
+ "resume_codex_worker",
245
+ {
246
+ title: "Resume Codex worker",
247
+ description:
248
+ "Continue the SAME Codex session for an existing worker via `codex exec resume <thread_id>`. Works from a different MCP process or a fresh client session as long as the task recorded a thread_id. The worktree stays on the commit it was cut from unless rebaseOnto names a ref (resolved in the project directory, e.g. HEAD or main): uncommitted edits are stashed, the worker's own commits are replayed onto it, the stash comes back and base_commit moves, so the worker continues on current code. A conflict in either step puts the worktree back as it was, lists the files and does not start the worker. The receipt carries base_behind: how many commits the project's HEAD is past the worktree's base. acceptance replaces the worker's acceptance commands when the ones given at dispatch were wrong; the supervisor runs them again after this run.",
249
+ inputSchema: {
250
+ task_id: z.string().min(1),
251
+ prompt: z.string().min(1),
252
+ rebaseOnto: z.string().min(1).optional(),
253
+ context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
254
+ // Replaces the stored acceptance commands for this and later runs; an
255
+ // empty list clears them. Left out, the stored commands stay.
256
+ acceptance: acceptanceInput.optional()
257
+ }
258
+ },
259
+ async ({ task_id, prompt, rebaseOnto, acceptance, context }) => {
260
+ try {
261
+ const record = await resumeCodexWorker({ taskId: task_id, prompt, rebaseOnto: rebaseOnto ?? null, acceptance, context });
262
+ return textResult({ ...receipt(record), rebase: record.rebase ?? null, base_behind: baseBehind(record.project_root, record.base_commit) });
263
+ } catch (error) {
264
+ return errorResult(error);
265
+ }
266
+ }
267
+ ];