codex-supervisor-mcp 0.13.5 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/package.json +19 -63
  4. package/skills/codex-supervisor/SKILL.md +5 -4
  5. package/src/{acceptance.js → app/acceptance.js} +54 -68
  6. package/src/app/auto-cleanup.js +90 -0
  7. package/src/app/cancel.js +60 -0
  8. package/src/app/cleanup-facts.js +96 -0
  9. package/src/app/cleanup-plan.js +164 -0
  10. package/src/app/compose.js +7 -0
  11. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  12. package/src/app/dispatch.js +396 -0
  13. package/src/app/followup.js +98 -0
  14. package/src/app/land-chain.js +133 -0
  15. package/src/app/landing.js +357 -0
  16. package/src/app/ownership.js +57 -0
  17. package/src/app/rebase.js +216 -0
  18. package/src/app/restore-worktree.js +50 -0
  19. package/src/app/resume.js +181 -0
  20. package/src/app/run-state.js +26 -0
  21. package/src/app/settled.js +28 -0
  22. package/src/{side-chat.js → app/side-chat.js} +82 -265
  23. package/src/app/sse.js +20 -0
  24. package/src/app/start-run.js +77 -0
  25. package/src/app/verify-push.js +114 -0
  26. package/src/app/worktree-setup.js +176 -0
  27. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  28. package/src/domain/acceptance-spec.js +30 -0
  29. package/src/domain/cleanup-policy.js +44 -0
  30. package/src/domain/command-outcome.js +6 -0
  31. package/src/{overview-delta.js → domain/overview-delta.js} +7 -3
  32. package/src/domain/side-turn-view.js +73 -0
  33. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  34. package/src/{cleanup-hint.js → infra/cleanup-hint.js} +7 -8
  35. package/src/infra/git.js +30 -0
  36. package/src/infra/process.js +59 -0
  37. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  38. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  39. package/src/infra/store/db.js +265 -0
  40. package/src/infra/store/events.js +146 -0
  41. package/src/infra/store/facts.js +338 -0
  42. package/src/infra/store/reconcile.js +172 -0
  43. package/src/infra/store/records.js +171 -0
  44. package/src/infra/store/runner-readers.js +16 -0
  45. package/src/infra/store/schema.js +306 -0
  46. package/src/infra/store/sessions.js +138 -0
  47. package/src/infra/store/tasks.js +337 -0
  48. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  49. package/src/{auto-update.js → infra/update/auto-update.js} +3 -3
  50. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  51. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  52. package/src/{worktree.js → infra/worktree.js} +56 -41
  53. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  54. package/src/{cleanup.js → interface/bin/cleanup.js} +4 -3
  55. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  56. package/src/{setup.js → interface/bin/setup.js} +7 -6
  57. package/src/{stage.js → interface/bin/stage.js} +1 -1
  58. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  59. package/src/interface/mcp/meta.js +7 -0
  60. package/src/interface/mcp/result.js +34 -0
  61. package/src/interface/mcp/schemas.js +24 -0
  62. package/src/interface/mcp/server.js +94 -0
  63. package/src/interface/mcp/tools/delivery.js +197 -0
  64. package/src/interface/mcp/tools/dispatch.js +267 -0
  65. package/src/interface/mcp/tools/facts.js +239 -0
  66. package/src/interface/mcp/tools/overview.js +202 -0
  67. package/src/interface/mcp/tools/poll.js +58 -0
  68. package/src/interface/mcp/tools/results.js +284 -0
  69. package/src/interface/mcp/tools/review.js +135 -0
  70. package/src/interface/mcp/tools/wait.js +145 -0
  71. package/src/interface/mcp/update-state.js +34 -0
  72. package/src/interface/mcp/views/overview.js +183 -0
  73. package/src/interface/mcp/views/task.js +223 -0
  74. package/src/interface/web/app.js +226 -0
  75. package/src/interface/web/views.js +224 -0
  76. package/src/mcp-server.js +3 -2223
  77. package/src/run-host/entry.js +23 -0
  78. package/src/run-host/finalize.js +236 -0
  79. package/src/run-host/launch.js +63 -0
  80. package/src/run-host/live-run.js +73 -0
  81. package/src/run-host/outcome-facts.js +61 -0
  82. package/src/run-host/streams.js +76 -0
  83. package/src/run-host/track.js +128 -0
  84. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  85. package/src/runners/codex/chat-chunks.js +97 -0
  86. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  87. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  88. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  89. package/src/cleanup-plan.js +0 -158
  90. package/src/codex-runner.js +0 -1586
  91. package/src/landing.js +0 -507
  92. package/src/task-store.js +0 -1800
  93. package/src/web-app.js +0 -425
  94. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  95. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  96. /package/src/{prompt.js → domain/prompt.js} +0 -0
  97. /package/src/{status.js → domain/status.js} +0 -0
  98. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  99. /package/src/{truncate.js → domain/truncate.js} +0 -0
  100. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  101. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  102. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  103. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  104. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  105. /package/src/{external-output.js → infra/external-output.js} +0 -0
  106. /package/src/{handoff.js → infra/handoff.js} +0 -0
  107. /package/src/{paths.js → infra/paths.js} +0 -0
  108. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  109. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,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
+ ];
@@ -0,0 +1,239 @@
1
+ import { git } from "../../../app/land-chain.js";
2
+ import { appendTaskEvent, readTaskEventRecords } from "../../../infra/store/events.js";
3
+ import { countVerifiedFacts, getFact, getFactEffectiveState, getTaskForWorkItem, isFactRevoked, latestContextSnapshotForTask, listContextFacts, promoteCandidateFact, revokeFact } from "../../../infra/store/facts.js";
4
+ import { getArtifact, listArtifactsForTask, readArtifact } from "../../../infra/store/records.js";
5
+ import { getTask } from "../../../infra/store/tasks.js";
6
+ import { runIdFor } from "../../../infra/store/db.js";
7
+ import { clip, errorResult, textResult } from "../result.js";
8
+ import { z } from "zod";
9
+
10
+ export const getContextSnapshotMetaTool = [
11
+ "get_context_snapshot_meta",
12
+ {
13
+ title: "Get worker context snapshot metadata",
14
+ description: "Read the latest worker-only context snapshot metadata for one task. Returns fact IDs, token estimate and excluded categories, never the capsule text or raw history.",
15
+ inputSchema: { task_id: z.string().min(1) }
16
+ },
17
+ async ({ task_id }) => {
18
+ const task = await getTask(task_id);
19
+ if (!task) return textResult({ error: "task_not_found", task_id });
20
+ const snapshot = await latestContextSnapshotForTask(task_id);
21
+ if (!snapshot) return textResult({ task_id, snapshot: null });
22
+ return textResult({
23
+ task_id,
24
+ snapshot: {
25
+ id: snapshot.id,
26
+ run_id: snapshot.run_id,
27
+ recipient: snapshot.recipient,
28
+ fact_ids: JSON.parse(snapshot.fact_versions),
29
+ base_sha: snapshot.base_sha,
30
+ prompt_sha256: snapshot.prompt_sha256,
31
+ estimated_tokens: snapshot.estimated_tokens,
32
+ excluded: JSON.parse(snapshot.excluded_json),
33
+ created_at: snapshot.created_at
34
+ }
35
+ });
36
+ }
37
+ ];
38
+
39
+ export const getFactTool = [
40
+ "get_fact",
41
+ {
42
+ title: "Get one verified or candidate fact",
43
+ description: "Read one fact by ID for audit. Facts are never automatically expanded into the main thread's context.",
44
+ inputSchema: { fact_id: z.string().uuid() }
45
+ },
46
+ async ({ fact_id }) => {
47
+ const fact = await getFact(fact_id);
48
+ if (!fact) return textResult({ error: "fact_not_found", fact_id });
49
+ return textResult({ fact, effective_state: await getFactEffectiveState(fact_id) ?? fact.state });
50
+ }
51
+ ];
52
+
53
+ export const getArtifactTool = [
54
+ "get_artifact",
55
+ {
56
+ title: "Get one retained evidence artifact",
57
+ description: "Read one supervisor-managed artifact by ID for audit. This is explicit evidence retrieval and never expands a worker context capsule into the main thread.",
58
+ inputSchema: { artifact_id: z.string().uuid(), maxChars: z.number().int().min(0).max(100000).default(12000) }
59
+ },
60
+ async ({ artifact_id, maxChars }) => {
61
+ const artifact = await getArtifact(artifact_id);
62
+ if (!artifact) return textResult({ error: "artifact_not_found", artifact_id });
63
+ return textResult({ artifact: await readArtifact(artifact_id, maxChars) });
64
+ }
65
+ ];
66
+
67
+ export const promoteWorkerFactTool = [
68
+ "promote_worker_fact",
69
+ {
70
+ title: "Promote a candidate worker fact",
71
+ description: "Explicitly promote one candidate fact after main-thread review. The worker cannot call this: promotion writes a new verified fact with an audit event; repo scope requires watched paths.",
72
+ inputSchema: {
73
+ fact_id: z.string().uuid(),
74
+ scope: z.enum(["work_item", "repo_verified"]).default("work_item"),
75
+ watchedPaths: z.array(z.string().min(1)).max(100).optional(),
76
+ expiresAt: z.string().datetime().optional()
77
+ }
78
+ },
79
+ async ({ fact_id, scope, watchedPaths, expiresAt }) => {
80
+ try {
81
+ const source = await getFact(fact_id);
82
+ if (!source) return textResult({ error: "fact_not_found", fact_id });
83
+ if (await isFactRevoked(fact_id)) return textResult({ error: "fact_already_revoked", fact_id });
84
+ const task = await getTaskForWorkItem(source.work_item_id);
85
+ if (!task) return textResult({ error: "fact_task_not_found", fact_id });
86
+ const event = await appendTaskEvent(task.id, { type: "supervisor.fact_promoted", source_fact_id: fact_id, scope, watched_paths: watchedPaths ?? source.watched_paths ?? [], expires_at: expiresAt ?? null }, {
87
+ runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
88
+ });
89
+ const fact = await promoteCandidateFact({
90
+ factId: fact_id,
91
+ scopeType: scope,
92
+ watchedPaths,
93
+ expiresAt: expiresAt ?? null,
94
+ sourceEventId: event.id,
95
+ verifiedBy: "main_thread"
96
+ });
97
+ return textResult({ fact, source_fact_id: fact_id });
98
+ } catch (error) {
99
+ return errorResult(error);
100
+ }
101
+ }
102
+ ];
103
+
104
+ export const revokeWorkerFactTool = [
105
+ "revoke_worker_fact",
106
+ {
107
+ title: "Revoke a candidate or verified worker fact",
108
+ description: "Explicitly revoke one candidate or verified fact after audit. Revoked facts are excluded from search and worker capsules; the revocation is appended to the worker event log.",
109
+ inputSchema: { fact_id: z.string().uuid(), reason: z.string().min(1).max(2000) }
110
+ },
111
+ async ({ fact_id, reason }) => {
112
+ try {
113
+ const source = await getFact(fact_id);
114
+ if (!source) return textResult({ error: "fact_not_found", fact_id });
115
+ const task = await getTaskForWorkItem(source.work_item_id);
116
+ if (!task) return textResult({ error: "fact_task_not_found", fact_id });
117
+ const revoked = await revokeFact(fact_id);
118
+ await appendTaskEvent(task.id, { type: "supervisor.fact_revoked", fact_id, reason }, {
119
+ runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
120
+ });
121
+ return textResult({ fact: revoked, reason });
122
+ } catch (error) {
123
+ return errorResult(error);
124
+ }
125
+ }
126
+ ];
127
+
128
+ export const getWorkerEvidenceTool = [
129
+ "get_worker_evidence",
130
+ {
131
+ title: "Get a worker evidence index",
132
+ description: "Return bounded event metadata and retained artifact IDs for one worker. It does not return raw history, prompts or a worker context capsule; use get_artifact or get_codex_worker_events for a selected item.",
133
+ inputSchema: { task_id: z.string().min(1), limit: z.number().int().min(1).max(100).default(30) }
134
+ },
135
+ async ({ task_id, limit }) => {
136
+ const task = await getTask(task_id);
137
+ if (!task) return textResult({ error: "task_not_found", task_id });
138
+ const events = await readTaskEventRecords(task_id, limit);
139
+ const artifacts = await listArtifactsForTask(task_id, limit);
140
+ return textResult({
141
+ task_id,
142
+ events: events.map((event) => ({
143
+ id: event.id, run_id: event.run_id, type: event.event_type, actor: event.actor,
144
+ payload_sha256: event.payload_sha256, created_at: event.created_at
145
+ })),
146
+ artifacts: artifacts.map((artifact) => ({
147
+ id: artifact.id, run_id: artifact.run_id, type: artifact.type, sha256: artifact.sha256,
148
+ security_class: artifact.security_class, retention: artifact.retention, created_at: artifact.created_at
149
+ }))
150
+ });
151
+ }
152
+ ];
153
+
154
+ function decodeFactCursor(cursor, taskId, query) {
155
+ if (!cursor) return 0;
156
+ try {
157
+ const payload = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
158
+ if (payload.task_id !== taskId || payload.query !== query || !Number.isInteger(payload.offset) || payload.offset < 0) throw new Error("mismatch");
159
+ return payload.offset;
160
+ } catch {
161
+ const error = new Error("fact cursor does not match this task and query");
162
+ error.code = "invalid_fact_cursor";
163
+ throw error;
164
+ }
165
+ }
166
+
167
+ function encodeFactCursor(taskId, query, offset) {
168
+ return Buffer.from(JSON.stringify({ task_id: taskId, query, offset })).toString("base64url");
169
+ }
170
+
171
+ function factFreshForTask(task, fact) {
172
+ if (!fact.valid_for_sha || !task.base_commit) return true;
173
+ try {
174
+ git(task.project_root, ["merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit]);
175
+ return true;
176
+ } catch {
177
+ return false;
178
+ }
179
+ }
180
+
181
+ export const searchWorkerFactsTool = [
182
+ "search_worker_facts",
183
+ {
184
+ title: "Search verified worker facts in scope",
185
+ description: "Search only verified facts relevant to one task: its own work, explicit dependencies and path-matched repository facts. Returns compact summaries, coverage and a cursor; never raw events, reports, prompts or worker capsules.",
186
+ inputSchema: {
187
+ task_id: z.string().min(1),
188
+ query: z.string().max(500).default(""),
189
+ limit: z.number().int().min(1).max(50).default(20),
190
+ cursor: z.string().min(1).optional()
191
+ }
192
+ },
193
+ async ({ task_id, query, limit, cursor }) => {
194
+ const task = await getTask(task_id);
195
+ if (!task) return textResult({ error: "task_not_found", task_id });
196
+ try {
197
+ const normalizedQuery = query.trim().toLocaleLowerCase();
198
+ const offset = decodeFactCursor(cursor, task_id, normalizedQuery);
199
+ const scoped = (await listContextFacts({
200
+ taskId: task_id,
201
+ baseSha: task.base_commit ?? null,
202
+ ownedPaths: task.owned_paths ?? [],
203
+ dependencyTaskIds: task.depends_on ?? []
204
+ })).filter((fact) => factFreshForTask(task, fact));
205
+ const matching = scoped.filter((fact) => !normalizedQuery || `${fact.key}\n${JSON.stringify(fact.value)}`.toLocaleLowerCase().includes(normalizedQuery));
206
+ const page = matching.slice(offset, offset + limit);
207
+ const nextOffset = offset + page.length;
208
+ const totalVerified = await countVerifiedFacts();
209
+ return textResult({
210
+ task_id,
211
+ facts: page.map((fact) => ({
212
+ id: fact.id,
213
+ key: fact.key,
214
+ summary: clip(typeof fact.value === "string" ? fact.value : JSON.stringify(fact.value), 360),
215
+ state: fact.state,
216
+ scope: fact.scope_type,
217
+ valid_for_sha: fact.valid_for_sha ?? null,
218
+ freshness: "current",
219
+ source_refs: [
220
+ ...(fact.source_event_id ? [`event:${fact.source_event_id}`] : []),
221
+ ...(fact.source_artifact_id ? [`artifact:${fact.source_artifact_id}`] : [])
222
+ ]
223
+ })),
224
+ coverage: {
225
+ scope: "current_work+explicit_dependencies+path_matched_repo_facts",
226
+ included_count: scoped.length,
227
+ matched_count: matching.length,
228
+ omitted: [
229
+ { reason: "other_verified_scopes_excluded", count: Math.max(0, totalVerified - scoped.length) },
230
+ { reason: "candidate_and_nonverified_facts_excluded", count: null }
231
+ ]
232
+ },
233
+ next_cursor: nextOffset < matching.length ? encodeFactCursor(task_id, normalizedQuery, nextOffset) : null
234
+ });
235
+ } catch (error) {
236
+ return errorResult(error);
237
+ }
238
+ }
239
+ ];