codex-supervisor-mcp 0.13.4 → 0.13.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.en.md +101 -297
  2. package/README.md +99 -310
  3. package/package.json +24 -63
  4. package/src/{acceptance.js → app/acceptance.js} +54 -68
  5. package/src/app/cancel.js +60 -0
  6. package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
  7. package/src/app/compose.js +7 -0
  8. package/src/{context-compiler.js → app/context-compiler.js} +7 -13
  9. package/src/app/dispatch.js +396 -0
  10. package/src/app/followup.js +98 -0
  11. package/src/app/land-chain.js +124 -0
  12. package/src/app/landing.js +357 -0
  13. package/src/app/ownership.js +57 -0
  14. package/src/app/rebase.js +216 -0
  15. package/src/app/resume.js +164 -0
  16. package/src/app/run-state.js +26 -0
  17. package/src/app/settled.js +28 -0
  18. package/src/{side-chat.js → app/side-chat.js} +79 -266
  19. package/src/app/sse.js +20 -0
  20. package/src/app/start-run.js +77 -0
  21. package/src/app/verify-push.js +119 -0
  22. package/src/app/worktree-setup.js +176 -0
  23. package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
  24. package/src/domain/acceptance-spec.js +30 -0
  25. package/src/domain/command-outcome.js +6 -0
  26. package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
  27. package/src/domain/side-turn-view.js +73 -0
  28. package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
  29. package/src/infra/git.js +30 -0
  30. package/src/infra/process.js +59 -0
  31. package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
  32. package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
  33. package/src/infra/store/db.js +265 -0
  34. package/src/infra/store/events.js +146 -0
  35. package/src/infra/store/facts.js +338 -0
  36. package/src/infra/store/reconcile.js +172 -0
  37. package/src/infra/store/records.js +160 -0
  38. package/src/infra/store/runner-readers.js +16 -0
  39. package/src/infra/store/schema.js +306 -0
  40. package/src/infra/store/sessions.js +138 -0
  41. package/src/infra/store/tasks.js +307 -0
  42. package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
  43. package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
  44. package/src/{update-check.js → infra/update/update-check.js} +4 -4
  45. package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
  46. package/src/{worktree.js → infra/worktree.js} +57 -42
  47. package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
  48. package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
  49. package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
  50. package/src/{setup.js → interface/bin/setup.js} +9 -8
  51. package/src/{stage.js → interface/bin/stage.js} +1 -1
  52. package/src/{web-server.js → interface/bin/web-server.js} +2 -2
  53. package/src/interface/mcp/meta.js +7 -0
  54. package/src/interface/mcp/result.js +34 -0
  55. package/src/interface/mcp/schemas.js +24 -0
  56. package/src/interface/mcp/server.js +94 -0
  57. package/src/interface/mcp/tools/delivery.js +197 -0
  58. package/src/interface/mcp/tools/dispatch.js +267 -0
  59. package/src/interface/mcp/tools/facts.js +239 -0
  60. package/src/interface/mcp/tools/overview.js +202 -0
  61. package/src/interface/mcp/tools/poll.js +62 -0
  62. package/src/interface/mcp/tools/results.js +270 -0
  63. package/src/interface/mcp/tools/review.js +135 -0
  64. package/src/interface/mcp/tools/wait.js +145 -0
  65. package/src/interface/mcp/update-state.js +34 -0
  66. package/src/interface/mcp/views/overview.js +183 -0
  67. package/src/interface/mcp/views/task.js +223 -0
  68. package/src/interface/web/app.js +226 -0
  69. package/src/interface/web/views.js +224 -0
  70. package/src/mcp-server.js +3 -2223
  71. package/src/run-host/entry.js +23 -0
  72. package/src/run-host/finalize.js +236 -0
  73. package/src/run-host/launch.js +63 -0
  74. package/src/run-host/live-run.js +73 -0
  75. package/src/run-host/outcome-facts.js +61 -0
  76. package/src/run-host/streams.js +76 -0
  77. package/src/run-host/track.js +128 -0
  78. package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
  79. package/src/runners/codex/chat-chunks.js +97 -0
  80. package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
  81. package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
  82. package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
  83. package/src/codex-runner.js +0 -1586
  84. package/src/landing.js +0 -507
  85. package/src/task-store.js +0 -1800
  86. package/src/web-app.js +0 -425
  87. /package/src/{failure-class.js → domain/failure-class.js} +0 -0
  88. /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
  89. /package/src/{prompt.js → domain/prompt.js} +0 -0
  90. /package/src/{status.js → domain/status.js} +0 -0
  91. /package/src/{thread-health.js → domain/thread-health.js} +0 -0
  92. /package/src/{truncate.js → domain/truncate.js} +0 -0
  93. /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
  94. /package/src/{worker-env.js → domain/worker-env.js} +0 -0
  95. /package/src/{worker-report.js → domain/worker-report.js} +0 -0
  96. /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
  97. /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
  98. /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
  99. /package/src/{external-output.js → infra/external-output.js} +0 -0
  100. /package/src/{handoff.js → infra/handoff.js} +0 -0
  101. /package/src/{paths.js → infra/paths.js} +0 -0
  102. /package/src/{stage-store.js → infra/stage-store.js} +0 -0
  103. /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
@@ -0,0 +1,202 @@
1
+ import { buildHostGoalSync } from "../../../domain/prompt.js";
2
+ import { ACTIVE_STATUSES, TASK_STATUSES } from "../../../domain/status.js";
3
+ import { truncateEventStrings } from "../../../domain/truncate.js";
4
+ import { getSession, upsertSession } from "../../../infra/store/sessions.js";
5
+ import { getTask, readTasks, readTasksBySession, searchTasks } from "../../../infra/store/tasks.js";
6
+ import { listTaskEventKinds, readTaskEvents } from "../../../infra/store/events.js";
7
+ import { reconcileDetachedActiveTasks } from "../../../infra/store/reconcile.js";
8
+ import { packageVersion } from "../meta.js";
9
+ import { errorResult, textResult } from "../result.js";
10
+ import { acceptanceCheck } from "../schemas.js";
11
+ import { autoUpdateState, refreshUpdateState, updateField, updateState } from "../update-state.js";
12
+ import { buildOverview, workRow } from "../views/overview.js";
13
+ import { statusView, summarizeTask } from "../views/task.js";
14
+ import { z } from "zod";
15
+
16
+ export const listCodexWorkersTool = [
17
+ "list_codex_workers",
18
+ {
19
+ title: "List Codex workers",
20
+ description: "List tracked Codex workers. Defaults to active workers only.",
21
+ inputSchema: {
22
+ status: z.enum(TASK_STATUSES).optional(),
23
+ includeHistory: z.boolean().default(false),
24
+ includeDetails: z.boolean().default(false)
25
+ }
26
+ },
27
+ async ({ status, includeHistory, includeDetails } = {}) => {
28
+ await reconcileDetachedActiveTasks();
29
+ const tasks = await readTasks();
30
+ const filtered = status
31
+ ? tasks.filter((task) => task.status === status)
32
+ : includeHistory
33
+ ? tasks
34
+ : tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
35
+ return textResult(includeDetails ? filtered : filtered.map(summarizeTask));
36
+ }
37
+ ];
38
+
39
+ export const getOrchestrationOverviewTool = [
40
+ "get_orchestration_overview",
41
+ {
42
+ title: "Get orchestration overview",
43
+ description:
44
+ "Compact status table for every worker, budgeted to stay under ~2k tokens. This is the default read for an orchestrating main thread; fetch details per worker only when needed.",
45
+ inputSchema: {
46
+ status: z.enum(TASK_STATUSES).optional(),
47
+ limit: z.number().int().min(1).max(200).default(50)
48
+ }
49
+ },
50
+ async ({ status, limit } = {}) => {
51
+ await reconcileDetachedActiveTasks();
52
+ const tasks = await readTasks();
53
+ const filtered = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
54
+ // version and update ride inside the budgeted payload so approx_tokens
55
+ // still reports the real cost of the whole reply.
56
+ return textResult(
57
+ buildOverview(filtered, {
58
+ version: packageVersion,
59
+ update: updateField() ?? { update_available: false, installed_version: packageVersion, checked: updateState?.source ?? "pending" }
60
+ })
61
+ );
62
+ }
63
+ ];
64
+
65
+ export const getSessionWorksTool = [
66
+ "get_session_works",
67
+ {
68
+ title: "Get session works",
69
+ description:
70
+ "Every worker dispatched under one session_id, oldest first. This is the reconnect path: a main-thread session that died can list the whole batch it started without holding any of it in context.",
71
+ inputSchema: {
72
+ session_id: z.string().min(1)
73
+ }
74
+ },
75
+ async ({ session_id }) => {
76
+ const tasks = await readTasksBySession(session_id);
77
+ const meta = await getSession(session_id);
78
+ return textResult({
79
+ session_id,
80
+ title: meta?.title ?? null,
81
+ note: meta?.note ?? null,
82
+ objective: meta?.objective ?? null,
83
+ default_acceptance: meta?.default_acceptance ?? [],
84
+ approval_state: meta?.approval_state ?? "approved",
85
+ policy_revision: meta?.policy_revision ?? 0,
86
+ count: tasks.length,
87
+ active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
88
+ works: tasks.map(workRow)
89
+ });
90
+ }
91
+ ];
92
+
93
+ export const checkForUpdateTool = [
94
+ "check_for_update",
95
+ {
96
+ title: "Check for update",
97
+ description:
98
+ "Ask the npm registry whether a newer codex-supervisor-mcp is published, and whether the installed files match the published tarball. Returns installed and latest version, integrity check, and the install command. The same check runs on startup; call this to force a fresh one.",
99
+ inputSchema: {
100
+ force: z.boolean().default(true)
101
+ }
102
+ },
103
+ async ({ force }) => {
104
+ const result = await refreshUpdateState({ force });
105
+ if (!result) return textResult({ error: "update_check_failed" });
106
+ return textResult({ ...result, auto_update: autoUpdateState });
107
+ }
108
+ ];
109
+
110
+ export const describeSessionTool = [
111
+ "describe_session",
112
+ {
113
+ title: "Describe session",
114
+ description:
115
+ "Record what a session is about: a one-line title and an optional note. Readers of the store (the web view, get_session_works) show these instead of the bare session id. Fields you omit are kept.",
116
+ inputSchema: {
117
+ session_id: z.string().min(1),
118
+ title: z.string().min(1).max(120).optional(),
119
+ note: z.string().min(1).max(2000).optional(),
120
+ objective: z.string().min(1).max(5000).optional(),
121
+ default_acceptance: z.array(acceptanceCheck).max(10).optional(),
122
+ approval_state: z.enum(["approved", "waiting_user"]).optional(),
123
+ expected_revision: z.number().int().nonnegative().optional()
124
+ }
125
+ },
126
+ async ({ session_id, title, note, objective, default_acceptance, approval_state, expected_revision }) => {
127
+ try {
128
+ const row = await upsertSession({
129
+ id: session_id, title: title ?? null, note: note ?? null, objective,
130
+ defaultAcceptance: default_acceptance, approvalState: approval_state, expectedRevision: expected_revision
131
+ });
132
+ return textResult({ ...row, session_id, host_goal_sync: buildHostGoalSync(row) });
133
+ } catch (error) { return errorResult(error); }
134
+ }
135
+ ];
136
+
137
+ export const searchWorksTool = [
138
+ "search_works",
139
+ {
140
+ title: "Search works",
141
+ description:
142
+ "Substring search over title, goal, prompt and last message of every tracked worker, newest first. Use it to find an earlier work by keyword instead of paging through history.",
143
+ inputSchema: {
144
+ query: z.string().min(1),
145
+ limit: z.number().int().positive().max(100).default(20)
146
+ }
147
+ },
148
+ async ({ query, limit }) => {
149
+ const tasks = await searchTasks(query, limit);
150
+ return textResult({
151
+ query,
152
+ count: tasks.length,
153
+ works: tasks.map(workRow)
154
+ });
155
+ }
156
+ ];
157
+
158
+ export const getCodexWorkerStatusTool = [
159
+ "get_codex_worker_status",
160
+ {
161
+ title: "Get Codex worker status",
162
+ description:
163
+ "Read the latest normalized status for one Codex worker: lifecycle, phase, current action, changed files, goal, recent commands, and the task prompt (clipped by default). Set includePrompt to read the prompt in full, or use get_codex_worker_events for the raw stream.",
164
+ inputSchema: {
165
+ task_id: z.string().min(1),
166
+ includePrompt: z.boolean().default(false),
167
+ promptMaxChars: z.number().int().min(0).max(1000000).default(5000)
168
+ }
169
+ },
170
+ async ({ task_id, includePrompt, promptMaxChars }) => {
171
+ const task = await getTask(task_id);
172
+ if (!task) return textResult({ error: "task_not_found", task_id });
173
+ return textResult(statusView(task, { includePrompt, promptMaxChars }));
174
+ }
175
+ ];
176
+
177
+ export const getCodexWorkerEventsTool = [
178
+ "get_codex_worker_events",
179
+ {
180
+ title: "Get Codex worker events",
181
+ description:
182
+ "Read recent raw Codex JSONL events for one worker. limit, maxChars and kinds keep the read inside a context budget; maxChars truncates the middle of oversized strings the same way Codex truncates its own output.",
183
+ inputSchema: {
184
+ task_id: z.string().min(1),
185
+ limit: z.number().int().min(1).max(1000).default(100),
186
+ maxChars: z.number().int().min(0).max(1000000).optional(),
187
+ kinds: z.array(z.string().min(1)).optional()
188
+ }
189
+ },
190
+ async ({ task_id, limit, maxChars, kinds }) => {
191
+ const task = await getTask(task_id);
192
+ if (!task) return textResult({ error: "task_not_found", task_id });
193
+ const events = await readTaskEvents(task_id, limit, kinds ?? null);
194
+ const trimmed = maxChars === undefined ? events : events.map((event) => truncateEventStrings(event, maxChars));
195
+ return textResult({
196
+ task_id,
197
+ count: trimmed.length,
198
+ available_kinds: await listTaskEventKinds(task_id),
199
+ events: trimmed
200
+ });
201
+ }
202
+ ];
@@ -0,0 +1,62 @@
1
+ import { createCleanupPlan } from "../../../app/cleanup-plan.js";
2
+ import { recoverEligibleRuns } from "../../../app/resume.js";
3
+ import { buildOverviewDelta } from "../../../domain/overview-delta.js";
4
+ import { collectWorkerChanges } from "../../../domain/worker-changes.js";
5
+ import { cleanupHint } from "../../../infra/cleanup-hint.js";
6
+ import { readObserverCursor, readTasks, writeObserverCursor } from "../../../infra/store/tasks.js";
7
+ import { reconcileDetachedActiveTasks } from "../../../infra/store/reconcile.js";
8
+ import { textResult } from "../result.js";
9
+ import { randomUUID } from "node:crypto";
10
+ import { z } from "zod";
11
+
12
+ const observerId = process.env.CODEX_SUPERVISOR_OBSERVER_ID?.trim() || `mcp-${randomUUID()}`;
13
+ const deltaObserverId = process.env.CODEX_SUPERVISOR_DELTA_OBSERVER_ID?.trim() || `${observerId}:delta`;
14
+ let observerRead = Promise.resolve();
15
+ let deltaRead = Promise.resolve();
16
+ export const overviewDeltaTool = [
17
+ "overview_delta",
18
+ {
19
+ title: "Get orchestration delta",
20
+ description: "Return a small cursor-based orchestration view: active, needs_attention, ready_to_land, ready_to_clean and changed task summaries. It never returns full history, prompts, diffs, events or worker capsules.",
21
+ inputSchema: { cursor: z.record(z.string(), z.string()).optional() }
22
+ },
23
+ async ({ cursor }) => {
24
+ const read = deltaRead.then(async () => {
25
+ await reconcileDetachedActiveTasks();
26
+ const tasks = await readTasks();
27
+ const previous = cursor ?? await readObserverCursor(deltaObserverId);
28
+ const candidateIds = tasks.filter((task) => task.delivery_state === "cleanup_eligible").map((task) => task.id);
29
+ const cleanupReadiness = candidateIds.length > 0
30
+ ? await createCleanupPlan({ taskIds: candidateIds, revalidateRemote: false })
31
+ : null;
32
+ const readyToCleanTaskIds = cleanupReadiness
33
+ ? new Set(cleanupReadiness.items.filter((item) => item.verdict === "safe").map((item) => item.task_id))
34
+ : new Set();
35
+ const result = buildOverviewDelta(tasks, previous, { readyToCleanTaskIds });
36
+ await writeObserverCursor(deltaObserverId, result.cursor);
37
+ const { cursor: nextCursor, ...reply } = result;
38
+ return textResult({ ...reply, next_cursor: nextCursor });
39
+ });
40
+ deltaRead = read.catch(() => {});
41
+ return read;
42
+ }
43
+ ];
44
+ export const checkWorkersTool = ["check_workers", {
45
+ title: "Check changed workers",
46
+ description: "Check newly settled runs, actionable failures and active threads crossing the handoff threshold; automatically resume a dead lost/no_work first run once, except approval, authentication, permission and quota waits. Handoff reminders occur once per run and never cancel, replace or resume a live worker. Unchanged state is quiet. Call from a host-scheduled loop; it cannot wake a closed host. Set a distinct CODEX_SUPERVISOR_OBSERVER_ID per main thread to retain its cursor across restarts.",
47
+ inputSchema: {}
48
+ }, async () => {
49
+ const read = observerRead.then(async () => {
50
+ await reconcileDetachedActiveTasks();
51
+ const recoveries = await recoverEligibleRuns();
52
+ const result = collectWorkerChanges(await readTasks(), await readObserverCursor(observerId));
53
+ await writeObserverCursor(observerId, result.cursor);
54
+ const { cursor, ...reply } = result;
55
+ // The cleanup hint rides along without touching quiet: it is a standing fact
56
+ // about the store, not a new worker event.
57
+ const cleanup = await cleanupHint();
58
+ return textResult({ ...reply, quiet: reply.quiet && recoveries.length === 0, recoveries, ...(cleanup ? { cleanup } : {}) });
59
+ });
60
+ observerRead = read.catch(() => {});
61
+ return read;
62
+ }];
@@ -0,0 +1,270 @@
1
+ import { askWorker, endSideSession, latestSideTurn } from "../../../app/side-chat.js";
2
+ import { isGoalNeedingAttention, TERMINAL_STATUSES } from "../../../domain/status.js";
3
+ import { truncateMiddleChars, truncateReport } from "../../../domain/truncate.js";
4
+ import { getTask, recordTerminalChangedFiles } from "../../../infra/store/tasks.js";
5
+ import { readAgentMessages } from "../../../infra/store/events.js";
6
+ import { baseBehind, readTaskChanges, readWorktreeDiff, splitPatchHunks, workspaceSetupIgnorePaths, worktreeRef } from "../../../infra/worktree.js";
7
+ import { summarizeVerification } from "../../../runners/codex/event-parser.js";
8
+ import { readNativeGoal, readNativeGoalState } from "../../../runners/codex/goal-store.js";
9
+ import { textResult } from "../result.js";
10
+ import { buildWorkerSummary, externalOutputView, reportView, runEvidenceView } from "../views/overview.js";
11
+ import { acceptanceView } from "../views/task.js";
12
+ import { z } from "zod";
13
+
14
+ export const getWorkerGoalTool = [
15
+ "get_worker_goal",
16
+ {
17
+ title: "Get worker goal",
18
+ description:
19
+ "Read the goal recorded for a worker, plus the native Codex thread goal when the thread has one (status, tokens used, time used).",
20
+ inputSchema: {
21
+ task_id: z.string().min(1)
22
+ }
23
+ },
24
+ async ({ task_id }) => {
25
+ const task = await getTask(task_id);
26
+ if (!task) return textResult({ error: "task_not_found", task_id });
27
+ return textResult({
28
+ task_id,
29
+ thread_id: task.thread_id,
30
+ status: task.status,
31
+ objective: task.goal_objective,
32
+ token_budget: task.goal_token_budget,
33
+ goal_status: task.goal_status,
34
+ needs_attention: isGoalNeedingAttention(task.goal_status),
35
+ native_goal: readNativeGoal(task.thread_id),
36
+ native_goal_read: readNativeGoalState(task.thread_id)
37
+ });
38
+ }
39
+ ];
40
+
41
+ export const getWorkerSummaryTool = [
42
+ "get_worker_summary",
43
+ {
44
+ title: "Get worker summary",
45
+ description:
46
+ "One compact summary per worker: goal, status, changed files, last command, last message. Cheap enough for a main thread to read every worker at the end of a run.",
47
+ inputSchema: {
48
+ task_id: z.string().min(1)
49
+ }
50
+ },
51
+ async ({ task_id }) => {
52
+ const task = await getTask(task_id);
53
+ if (!task) return textResult({ error: "task_not_found", task_id });
54
+ const summary = buildWorkerSummary(task, readNativeGoal(task.thread_id));
55
+ // Cache the worktree diff on the row once the worker is done, so the
56
+ // overview's count stops lagging. A running row is the runner's to write.
57
+ if (TERMINAL_STATUSES.has(task.status) && summary.changed_files.length !== (task.changed_files ?? []).length) {
58
+ await recordTerminalChangedFiles(task.id, summary.changed_files);
59
+ }
60
+ return textResult(summary);
61
+ }
62
+ ];
63
+
64
+ export const getWorkerResultTool = [
65
+ "get_worker_result",
66
+ {
67
+ title: "Get worker result",
68
+ description:
69
+ "Read a worker's own final report. The overview and the wait response clip the last message; this is the door for the actual conclusion. Returns the last N agent messages (each clipped past maxChars, default 6000 bytes, with truncated: true and the full size so you can re-read it whole), the status fields that tell a real finish from a crash, verification (the commands the worker ran, their exit codes and the tail of any failing output, to hold its report against), acceptance (the supervisor's own run of the dispatch-time acceptance commands, independent of the report: configured, passed, and each check's exit code and output tail; passed: false means resume the worker with that output instead of reading its report, passed: true against a report that says blocked or not done means trust the checks and read the diff), changed_file_count, and base_behind (how many commits the project's HEAD is past the worktree's base; resume with rebaseOnto when it is not 0). includeFiles: true adds the changed_files list; get_worker_diff is the ground truth for what changed.",
70
+ inputSchema: {
71
+ task_id: z.string().min(1),
72
+ limit: z.number().int().min(1).max(20).default(1),
73
+ // Per report, UTF-8 bytes. 0 means no clipping.
74
+ maxChars: z.number().int().min(0).max(1000000).default(6000),
75
+ includeFiles: z.boolean().default(false)
76
+ }
77
+ },
78
+ async ({ task_id, limit, maxChars, includeFiles }) => {
79
+ const task = await getTask(task_id);
80
+ if (!task) return textResult({ error: "task_not_found", task_id });
81
+ let reports = await readAgentMessages(task_id, limit);
82
+ let source = "event_stream";
83
+ if (reports.length === 0 && task.last_message) {
84
+ // Older rows can predate this tool, but the task row keeps the newest
85
+ // report even when the stream query finds nothing.
86
+ reports = [task.last_message];
87
+ source = "task_row";
88
+ }
89
+ const reportBytes = reports.map((text) => Buffer.byteLength(text, "utf8"));
90
+ const clipped = maxChars === 0 ? reports : reports.map((text) => truncateReport(text, maxChars));
91
+ const truncated = clipped.some((text, index) => text !== reports[index]);
92
+ const changed = readTaskChanges(task);
93
+ const behind = task.worktree_path ? baseBehind(task.project_root, task.base_commit) : null;
94
+ // A worker that ran in place has no worktree to diff, so this list is
95
+ // the only record of what it touched; it is never hidden for those.
96
+ const listFiles = includeFiles || !task.worktree_path;
97
+ return textResult({
98
+ task_id,
99
+ title: task.title,
100
+ status: task.status,
101
+ phase: task.phase ?? null,
102
+ exit_code: task.exit_code ?? null,
103
+ thread_id: task.thread_id,
104
+ session_id: task.session_id ?? null,
105
+ workspace_kind: task.workspace_kind ?? "legacy",
106
+ worktree_path: task.worktree_path,
107
+ goal_status: task.goal_status,
108
+ attention_reason: task.attention_reason ?? null,
109
+ run_evidence: runEvidenceView(task),
110
+ structured_report: reportView(task, maxChars),
111
+ input_context: task.input_context ?? null,
112
+ external_outputs: externalOutputView(task, maxChars || 6000),
113
+ changed_file_count: changed.length,
114
+ changed_files: listFiles ? changed : undefined,
115
+ base_commit: task.base_commit ?? null,
116
+ base_behind: behind,
117
+ landed: task.landed_at ? { at: task.landed_at, head: task.landed_head ?? null } : null,
118
+ acceptance: acceptanceView(task, behind),
119
+ verification: summarizeVerification(task),
120
+ report_count: clipped.length,
121
+ report_bytes: reportBytes,
122
+ truncated,
123
+ next_step: truncated
124
+ ? `a report was clipped to ${maxChars} bytes; call again with maxChars: ${Math.max(...reportBytes)} (or 0) to read it whole`
125
+ : null,
126
+ reports: clipped,
127
+ source,
128
+ error: task.error ?? null,
129
+ completed_at: task.completed_at ?? null
130
+ });
131
+ }
132
+ ];
133
+
134
+ export const getWorkerDiffTool = [
135
+ "get_worker_diff",
136
+ {
137
+ title: "Get worker diff",
138
+ description:
139
+ "The worker's actual changes. By default this is a complete file/hunk index; request one file to page through hunks with pageSize or cursor. Supplying maxChars without file preserves the legacy bounded full-diff response. This is the ground truth to check a worker's report against.",
140
+ inputSchema: {
141
+ task_id: z.string().min(1),
142
+ maxChars: z.number().int().min(0).max(1000000).optional(),
143
+ file: z.string().min(1).optional(),
144
+ hunk: z.number().int().min(0).optional(),
145
+ pageSize: z.number().int().min(1).max(20).default(4),
146
+ cursor: z.string().min(1).optional(),
147
+ paths: z.array(z.string().min(1)).optional()
148
+ }
149
+ },
150
+ async ({ task_id, maxChars, file, hunk, pageSize, cursor, paths }) => {
151
+ const task = await getTask(task_id);
152
+ if (!task) return textResult({ error: "task_not_found", task_id });
153
+ if (!task.worktree_path) {
154
+ return textResult({ error: "no_worktree", task_id, external_outputs: externalOutputView(task, maxChars), reason: "this worker ran in place (its cwd is not a git repository or the worktree could not be created), so there is no isolated diff to read; call get_worker_result with includeFiles: true for the files it touched" });
155
+ }
156
+ if (!file && maxChars !== undefined) {
157
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [], ignorePaths: workspaceSetupIgnorePaths(task) });
158
+ return textResult({
159
+ task_id,
160
+ title: task.title,
161
+ status: task.status,
162
+ worktree_path: task.worktree_path,
163
+ branch: `codex/${task.id}`,
164
+ ...diff,
165
+ external_outputs: externalOutputView(task, maxChars)
166
+ });
167
+ }
168
+ const diffOptions = { maxChars: 10_000_000, paths: paths ?? [], ignorePaths: workspaceSetupIgnorePaths(task) };
169
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), diffOptions);
170
+ if (diff.error) return textResult({ ...diff, task_id });
171
+ const files = diff.files.map((entry) => {
172
+ const parsed = splitPatchHunks(entry);
173
+ const { path, status, from, additions, deletions } = entry;
174
+ return { path, status, from, additions, deletions, hunk_count: parsed.hunks.length };
175
+ });
176
+ const base = {
177
+ task_id,
178
+ title: task.title,
179
+ status: task.status,
180
+ worktree_path: task.worktree_path,
181
+ branch: `codex/${task.id}`,
182
+ ...diff,
183
+ files,
184
+ external_outputs: externalOutputView(task, maxChars || 6000)
185
+ };
186
+ if (!file) return textResult({ ...base, summary_only: true, next_step: "choose files[].path, then request file plus hunk or cursor" });
187
+ const selected = diff.files.find((entry) => entry.path === file);
188
+ if (!selected) return textResult({ error: "diff_file_not_found", task_id, file, files });
189
+ const parsed = splitPatchHunks(selected);
190
+ let offset = 0;
191
+ if (cursor) {
192
+ try {
193
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
194
+ if (value.task_id !== task_id || value.file !== file || !Number.isInteger(value.offset) || value.offset < 0) throw new Error("mismatch");
195
+ offset = value.offset;
196
+ } catch {
197
+ return textResult({ error: "invalid_diff_cursor", task_id, file });
198
+ }
199
+ }
200
+ if (hunk !== undefined) offset = hunk;
201
+ if (offset >= parsed.hunks.length) return textResult({ error: "diff_hunk_not_found", task_id, file, hunk: offset, hunk_count: parsed.hunks.length });
202
+ let remaining = maxChars ?? 24000;
203
+ const hunks = [];
204
+ for (let index = offset; index < parsed.hunks.length && hunks.length < pageSize; index += 1) {
205
+ if (remaining <= 0) break;
206
+ const item = parsed.hunks[index];
207
+ const patchText = item.patch.length > remaining ? truncateMiddleChars(item.patch, remaining) : item.patch;
208
+ hunks.push({ ...item, patch: patchText, truncated: patchText.length < item.patch.length });
209
+ remaining -= patchText.length;
210
+ }
211
+ const nextOffset = offset + hunks.length;
212
+ const nextCursor = nextOffset < parsed.hunks.length
213
+ ? Buffer.from(JSON.stringify({ task_id, file, offset: nextOffset })).toString("base64url")
214
+ : null;
215
+ return textResult({
216
+ ...base,
217
+ file: {
218
+ path: selected.path, status: selected.status, from: selected.from,
219
+ additions: selected.additions, deletions: selected.deletions, hunk_count: parsed.hunks.length
220
+ },
221
+ hunks,
222
+ next_cursor: nextCursor,
223
+ summary_only: false
224
+ });
225
+ }
226
+ ];
227
+
228
+ export const askCodexWorkerTool = [
229
+ "ask_codex_worker",
230
+ {
231
+ title: "Ask a worker on the side",
232
+ description:
233
+ "Ask a finished or running worker a question without touching its thread: the worker's Codex thread is forked once into a read-only side session (like Codex's own /btw), the question is asked there, and later questions resume that fork. The fork carries everything the worker saw and did, so 'why did you change X' or 'where is Y handled' costs one short answer instead of a read of the event stream. The fork has no network and no MCP tools and is told so; it answers from its context and the worktree. Once the worker has been resumed, the next question automatically takes a new fork from the updated thread (refreshed: \"worker_resumed\"); fresh: true forces a new fork. Changes still go through resume_codex_worker. Without a question it returns the latest side turn (for an answer that outran timeoutMs). end: true deletes the fork.",
234
+ inputSchema: {
235
+ task_id: z.string().min(1),
236
+ question: z.string().min(1).optional(),
237
+ timeoutMs: z.number().int().min(1000).max(600000).default(110000),
238
+ maxChars: z.number().int().min(0).max(1000000).default(8000),
239
+ fresh: z.boolean().default(false),
240
+ end: z.boolean().default(false)
241
+ }
242
+ },
243
+ async ({ task_id, question, timeoutMs, maxChars, fresh, end }) => {
244
+ const task = await getTask(task_id);
245
+ if (!task) return textResult({ error: "task_not_found", task_id });
246
+ const clipAnswer = (state) => {
247
+ if (state?.turn?.answer && maxChars !== undefined) state.turn.answer = truncateMiddleChars(state.turn.answer, maxChars);
248
+ return state;
249
+ };
250
+ if (end) {
251
+ const ended = await endSideSession(task_id);
252
+ return textResult({ task_id, ...ended });
253
+ }
254
+ if (!question) {
255
+ return textResult({ task_id, ...clipAnswer(await latestSideTurn(task_id)) });
256
+ }
257
+ try {
258
+ const state = clipAnswer(await askWorker({ task, question, timeoutMs, fresh }));
259
+ const next = state.timed_out
260
+ ? `The side turn is still running; call ask_codex_worker again with only task_id to read the answer when it lands.`
261
+ : null;
262
+ return textResult({ task_id, ...state, next_step: next });
263
+ } catch (error) {
264
+ if (error.code === "busy") {
265
+ return textResult({ task_id, error: "busy", reason: error.message, ...clipAnswer(await latestSideTurn(task_id)) });
266
+ }
267
+ return textResult({ task_id, error: error.code ?? "side_turn_failed", reason: error.message });
268
+ }
269
+ }
270
+ ];
@@ -0,0 +1,135 @@
1
+ import { createCodexWorker } from "../../../app/dispatch.js";
2
+ import { appendTaskEvent } from "../../../infra/store/events.js";
3
+ import { createReviewAssignment, getReviewByVerifierTask, recordJsonArtifact, recordReviewFinding, resolveReviewFinding } from "../../../infra/store/records.js";
4
+ import { getTask } from "../../../infra/store/tasks.js";
5
+ import { runIdFor } from "../../../infra/store/db.js";
6
+ import { errorResult, textResult } from "../result.js";
7
+ import { isSettled } from "../../../app/settled.js";
8
+ import { receipt } from "../views/task.js";
9
+ import { createHash } from "node:crypto";
10
+ import { z } from "zod";
11
+
12
+ export const createIndependentVerifierTool = [
13
+ "create_independent_verifier",
14
+ {
15
+ title: "Create an independent read-only verifier",
16
+ description: "Create a fresh read-only verifier for one settled worker. It receives the target objective and current worktree path, never the target report or candidate facts, has no network and cannot dispatch workers. The review relation is persisted for later finding and resolution.",
17
+ inputSchema: { task_id: z.string().min(1), title: z.string().min(1).max(120).optional() }
18
+ },
19
+ async ({ task_id, title }) => {
20
+ try {
21
+ const subject = await getTask(task_id);
22
+ if (!subject) return textResult({ error: "task_not_found", task_id });
23
+ if (!isSettled(subject)) return textResult({ error: "review_subject_active", task_id, reason: "wait for the worker and any acceptance to settle before independent review" });
24
+ const sourceRoot = subject.worktree_path ?? subject.project_root;
25
+ const verifier = await createCodexWorker({
26
+ title: title ?? `Independent review: ${subject.title ?? subject.id}`,
27
+ task: [
28
+ "Independently verify the target worker's objective from the current source tree and Git state.",
29
+ `Target task ID: ${subject.id}`,
30
+ `Target objective: ${subject.goal_objective ?? subject.title ?? "unspecified"}`,
31
+ `Inspect root: ${sourceRoot}`,
32
+ "Do not trust or request the target worker's report. Do not inspect candidate facts. Do not edit files, use network, create workers or call MCP tools.",
33
+ "Return whether the stated objective is met, the exact evidence you inspected, and any unresolved gap."
34
+ ].join("\n"),
35
+ cwd: sourceRoot,
36
+ workspaceKind: "read_only_in_place",
37
+ sandbox: "read-only",
38
+ ownedPaths: [],
39
+ networkAccess: false,
40
+ goal: { objective: `Independently verify worker ${subject.id} without relying on its self-report` }
41
+ });
42
+ const fingerprint = createHash("sha256").update(JSON.stringify({
43
+ task_id: subject.id,
44
+ run: subject.run_count ?? 0,
45
+ base_sha: subject.base_commit ?? null,
46
+ worktree: sourceRoot,
47
+ updated_at: subject.updated_at ?? null,
48
+ changed_files: subject.changed_files ?? []
49
+ })).digest("hex");
50
+ const review = await createReviewAssignment({
51
+ subjectTaskId: subject.id,
52
+ verifierTaskId: verifier.id,
53
+ subjectRunId: runIdFor(subject.id, subject.run_count ?? 1),
54
+ subjectBaseSha: subject.base_commit ?? null,
55
+ subjectFingerprint: fingerprint
56
+ });
57
+ return textResult({ ...receipt(verifier), review });
58
+ } catch (error) {
59
+ return errorResult(error);
60
+ }
61
+ }
62
+ ];
63
+
64
+ export const recordIndependentFindingTool = [
65
+ "record_independent_finding",
66
+ {
67
+ title: "Record an independent verifier finding",
68
+ description: "After a verifier settles, record its passes/fails/inconclusive verdict with a concise reason. The supervisor stores a retained finding artifact and appends an event to the reviewed worker; this does not change the reviewed worker's delivery state automatically.",
69
+ inputSchema: { verifier_task_id: z.string().min(1), verdict: z.enum(["passes", "fails", "inconclusive"]), reason: z.string().min(1).max(4000) }
70
+ },
71
+ async ({ verifier_task_id, verdict, reason }) => {
72
+ try {
73
+ const review = await getReviewByVerifierTask(verifier_task_id);
74
+ if (!review) return textResult({ error: "review_not_found", verifier_task_id });
75
+ if (review.status !== "pending") return textResult({ error: "review_not_pending", verifier_task_id, status: review.status });
76
+ const verifier = await getTask(verifier_task_id);
77
+ if (!verifier || !isSettled(verifier)) return textResult({ error: "verifier_not_settled", verifier_task_id });
78
+ const subject = await getTask(review.subject_task_id);
79
+ if (!subject) return textResult({ error: "review_subject_not_found", task_id: review.subject_task_id });
80
+ const artifact = await recordJsonArtifact({
81
+ runId: runIdFor(verifier.id, verifier.run_count ?? 1),
82
+ type: "independent_review_finding",
83
+ value: {
84
+ review_id: review.id, subject_task_id: subject.id, verifier_task_id, verdict, reason,
85
+ verifier_run: verifier.run_count ?? 1, recorded_at: new Date().toISOString()
86
+ },
87
+ securityClass: "internal"
88
+ });
89
+ const event = await appendTaskEvent(subject.id, { type: "supervisor.independent_finding", review_id: review.id, verifier_task_id, verdict, reason, artifact_id: artifact.id }, {
90
+ runId: review.subject_run_id ?? runIdFor(subject.id, subject.run_count ?? 1), actor: "main_thread"
91
+ });
92
+ const recorded = await recordReviewFinding({
93
+ verifierTaskId: verifier_task_id, verdict, reason, evidenceArtifactId: artifact.id, findingEventId: event.id
94
+ });
95
+ return textResult({ review: recorded, artifact_id: artifact.id });
96
+ } catch (error) {
97
+ return errorResult(error);
98
+ }
99
+ }
100
+ ];
101
+
102
+ export const resolveIndependentFindingTool = [
103
+ "resolve_independent_finding",
104
+ {
105
+ title: "Resolve an independent verifier finding",
106
+ description: "Record how a previously recorded independent finding was resolved. This is an audit transition only; it does not hide the finding or alter worker code.",
107
+ inputSchema: { verifier_task_id: z.string().min(1), resolution: z.string().min(1).max(4000) }
108
+ },
109
+ async ({ verifier_task_id, resolution }) => {
110
+ try {
111
+ const review = await resolveReviewFinding({ verifierTaskId: verifier_task_id, resolution });
112
+ if (!review) return textResult({ error: "review_not_recorded", verifier_task_id });
113
+ const subject = await getTask(review.subject_task_id);
114
+ if (subject) await appendTaskEvent(subject.id, { type: "supervisor.independent_finding_resolved", review_id: review.id, verifier_task_id, resolution }, {
115
+ runId: review.subject_run_id ?? runIdFor(subject.id, subject.run_count ?? 1), actor: "main_thread"
116
+ });
117
+ return textResult({ review });
118
+ } catch (error) {
119
+ return errorResult(error);
120
+ }
121
+ }
122
+ ];
123
+
124
+ export const getIndependentReviewTool = [
125
+ "get_independent_review",
126
+ {
127
+ title: "Get one independent review relation",
128
+ description: "Read the persisted subject/verifier/finding/resolution relation for a verifier task. Use get_artifact for the retained finding evidence.",
129
+ inputSchema: { verifier_task_id: z.string().min(1) }
130
+ },
131
+ async ({ verifier_task_id }) => {
132
+ const review = await getReviewByVerifierTask(verifier_task_id);
133
+ return textResult(review ? { review } : { error: "review_not_found", verifier_task_id });
134
+ }
135
+ ];