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
@@ -9,7 +9,7 @@
9
9
  // codex-supervisor-setup --target claude --force
10
10
  //
11
11
  // Set CODEX_SUPERVISOR_SKIP_SETUP=1 to opt out of the automatic run.
12
- import { execFile } from "node:child_process";
12
+ import { runFile } from "../../infra/process.js";
13
13
  import { existsSync, readdirSync } from "node:fs";
14
14
  import { homedir } from "node:os";
15
15
  import { basename, dirname, isAbsolute, join } from "node:path";
@@ -20,13 +20,13 @@ import {
20
20
  findBinaryPath,
21
21
  resolveCommand,
22
22
  shimMessage
23
- } from "./bin-resolver.js";
23
+ } from "../../infra/bin-resolver.js";
24
24
 
25
- const run = promisify(execFile);
25
+ const run = promisify(runFile);
26
26
 
27
- import { installSkill, skillRoots } from "./skill-sync.js";
27
+ import { installSkill, skillRoots } from "../../infra/skill-sync.js";
28
28
 
29
- const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
29
+ const packageRoot = fileURLToPath(new URL("../../..", import.meta.url)).replace(/[\\/]$/, "");
30
30
  const serverEntry = join(packageRoot, "src", "mcp-server.js");
31
31
 
32
32
  const MCP_NAME = "codex-supervisor";
@@ -132,7 +132,7 @@ function versionManagerBinDirs() {
132
132
  const dirs = [];
133
133
  for (const [root, suffix] of VERSION_MANAGER_ROOTS) {
134
134
  if (!existsSync(root)) continue;
135
- let entries = [];
135
+ let entries;
136
136
  try {
137
137
  entries = readdirSync(root);
138
138
  } catch {
@@ -179,7 +179,8 @@ async function registeredMcp(target, client) {
179
179
  if (client.id === "codex") {
180
180
  const value = JSON.parse(stdout);
181
181
  const transport = value.transport ?? value;
182
- return { command: transport.command, args: transport.args ?? [], env: transport.env ?? {}, cwd: transport.cwd, enabled: value.enabled !== false, userScope: true };
182
+ const { command, args = [], env = {}, cwd } = transport;
183
+ return { command, args: args ?? [], env: env ?? {}, cwd, enabled: value.enabled !== false, userScope: true };
183
184
  }
184
185
  const command = stdout.match(/^\s*Command: (.+)$/m)?.[1]?.trim();
185
186
  const args = stdout.match(/^\s*Args: (.*)$/m)?.[1]?.trim();
@@ -188,7 +189,7 @@ async function registeredMcp(target, client) {
188
189
  } catch (error) {
189
190
  const message = `${error.stdout ?? ""}${error.stderr ?? ""}${error.message}`;
190
191
  if (/not found|no mcp server|could not find|does not exist/i.test(message)) return null;
191
- throw new Error(`cannot read ${client.label} MCP registration: ${error.message.split("\n")[0]}`);
192
+ throw new Error(`cannot read ${client.label} MCP registration: ${error.message.split("\n")[0]}`, { cause: error });
192
193
  }
193
194
  }
194
195
 
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { writeStage } from "./stage-store.js";
2
+ import { writeStage } from "../../infra/stage-store.js";
3
3
 
4
4
  const argv = process.argv.slice(2);
5
5
  let taskId = process.env.CODEX_SUPERVISOR_TASK_ID;
@@ -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
+ ];