codex-supervisor-mcp 0.7.3 → 0.9.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.
package/src/mcp-server.js CHANGED
@@ -1,10 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs";
3
+ import { execFileSync } from "node:child_process";
4
+ import { randomUUID } from "node:crypto";
3
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
7
  import { z } from "zod";
6
8
  import {
7
9
  cancelCodexWorker,
10
+ recoverEligibleRuns,
8
11
  createCodexWorker,
9
12
  createFollowupWorker,
10
13
  resumeCodexWorker
@@ -18,6 +21,8 @@ import {
18
21
  readAgentMessages,
19
22
  readTaskEvents,
20
23
  readTasks,
24
+ readObserverCursor,
25
+ writeObserverCursor,
21
26
  readTasksBySession,
22
27
  reconcileDetachedActiveTasks,
23
28
  recordTerminalChangedFiles,
@@ -25,10 +30,14 @@ import {
25
30
  upsertSession,
26
31
  upsertTask
27
32
  } from "./task-store.js";
28
- import { readNativeGoal } from "./goal-store.js";
29
- import { readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
33
+ import { readNativeGoal, readNativeGoalState } from "./goal-store.js";
34
+ import { collectWorkerChanges } from "./worker-changes.js";
35
+ import { buildHostGoalSync } from "./prompt.js";
36
+ import { baseBehind, readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
37
+ import { summarizeVerification } from "./event-parser.js";
38
+ import { acceptanceVerdict, runAcceptance } from "./acceptance.js";
30
39
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
31
- import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
40
+ import { approxTokenCount, truncateEventStrings, truncateMiddleChars, truncateReport } from "./truncate.js";
32
41
  import { checkForUpdate, updateNotice } from "./update-check.js";
33
42
  import { syncSkills } from "./skill-sync.js";
34
43
  import { maybeAutoUpdate } from "./auto-update.js";
@@ -108,7 +117,9 @@ const OVERVIEW_CAP_LEVELS = [
108
117
  { title: 40, goal: 60, action: 60, path: 60 },
109
118
  { title: 28, goal: 40, action: 40, path: 40 },
110
119
  { title: 18, goal: 24, action: 24, path: 24 },
111
- { title: 12, goal: 16, action: 16, path: 16 }
120
+ { title: 12, goal: 16, action: 16, path: 16 },
121
+ { title: 8, goal: 8, action: 8, path: 8 },
122
+ { title: 0, goal: 0, action: 0, path: 0 }
112
123
  ];
113
124
 
114
125
  // `current_action` is "Running <command>", and a command can be a heredoc that
@@ -154,9 +165,76 @@ function sleep(ms) {
154
165
  // the exit is recorded, or once nobody is left to record it.
155
166
  function isSettled(task) {
156
167
  if (!TERMINAL_STATUSES.has(task.status)) return false;
168
+ if (task.attention_reason === "start_failed") return true;
157
169
  if (task.status !== "completed" && task.status !== "failed") return true;
170
+ // Acceptance is running in the supervisor process that owned the worker;
171
+ // the codex pid is already dead, so that process is what to wait on.
172
+ if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
173
+ if (["interrupted", "cancelled"].includes(task.acceptance_results?.status)) return true;
158
174
  if (task.exit_code !== null && task.exit_code !== undefined) return true;
159
- return !isPidAlive(task.pid);
175
+ // A dead Codex pid does not prove that its owner's close handler finished
176
+ // draining the stream and writing the exit status. Leave the half-written
177
+ // row for reconciliation after a short grace period, never return it.
178
+ return false;
179
+ }
180
+
181
+ // Codex emits nothing while a command runs and nothing while the model
182
+ // thinks, so a snapshot that has not moved for ten minutes looks the same
183
+ // either way. These three fields tell them apart: current_command is set
184
+ // from the command's item.started until its item.completed, so a long idle
185
+ // with a command is a long command, and a long idle without one is the model
186
+ // (or a stuck process, which reconcile turns into lost on its own).
187
+ const LIVE_COMMAND_PREVIEW_CHARS = 120;
188
+ function liveness(task) {
189
+ if (!ACTIVE_STATUSES.has(task.status)) {
190
+ return { idle_seconds: null, command_running: false, current_command: null };
191
+ }
192
+ const since = Date.parse(task.last_event_at ?? task.started_at ?? "");
193
+ const idle = Number.isFinite(since) ? Math.max(0, Math.floor((Date.now() - since) / 1000)) : null;
194
+ const command = task.current_command ? clip(task.current_command, LIVE_COMMAND_PREVIEW_CHARS) : null;
195
+ return { idle_seconds: idle, command_running: Boolean(task.current_command), current_command: command };
196
+ }
197
+
198
+ // The acceptance verdict as get_worker_result reports it, with the one
199
+ // contradiction a tool can see spelled out: checks passed, worker says
200
+ // otherwise (the "it was never built" case, where it was).
201
+ function acceptanceView(task, behind) {
202
+ const configured = Array.isArray(task.acceptance) && task.acceptance.length > 0;
203
+ const results = task.acceptance_results ?? null;
204
+ const view = {
205
+ configured,
206
+ commands: configured ? task.acceptance : [],
207
+ status: results?.status ?? null,
208
+ passed: results?.passed ?? null,
209
+ run: results?.run ?? null,
210
+ checks: results?.checks ?? [],
211
+ error: results?.error ?? null,
212
+ // Drift matters only before the work is landed: once it is on the
213
+ // branch, the branch having moved is expected.
214
+ stale: Boolean(results && behind && behind.behind > 0 && !(task.landed_at && task.landed_at >= (results.finished_at ?? ""))),
215
+ next_step: null
216
+ };
217
+ if (!configured) return view;
218
+ if (view.status === "failed") {
219
+ const failing = view.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out) ?? null;
220
+ view.next_step = failing
221
+ ? `acceptance failed: ${clip(failing.command, 120)} failed ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "by timeout" : `exit ${failing.exit_code}`)}; resume the worker with checks[].output_tail in the prompt, or fix it yourself. Do not land until it passes.`
222
+ : `acceptance could not run (${view.error ?? "unknown"}); fix that first`;
223
+ } else if (view.status === "passed") {
224
+ const verification = summarizeVerification(task);
225
+ const workerSaysNo = task.status === "failed" || isGoalNeedingAttention(task.goal_status) || verification.last_command_failed;
226
+ if (workerSaysNo) view.next_step = "the checks passed but the worker reports otherwise; trust the checks and read the diff";
227
+ else if (view.stale) view.next_step = "the checks passed on the old base and the project has moved since; resume with rebaseOnto to re-run them on current code before landing";
228
+ } else if (view.status === "running") {
229
+ view.next_step = "acceptance is still running in the supervisor; wait_codex_workers returns when it is done";
230
+ } else if (view.status === "interrupted") {
231
+ view.next_step = "the supervisor exited while running acceptance; resume the worker (or cancel and redispatch) to run it again";
232
+ } else if (view.status === "cancelled") {
233
+ view.next_step = "acceptance was cancelled; resume the worker to run it again";
234
+ } else if (view.status === null) {
235
+ view.next_step = "acceptance has not run yet for this worker";
236
+ }
237
+ return view;
160
238
  }
161
239
 
162
240
  function summarizeTask(task) {
@@ -180,10 +258,15 @@ function summarizeTask(task) {
180
258
  goal_objective: task.goal_objective,
181
259
  goal_token_budget: task.goal_token_budget,
182
260
  goal_status: task.goal_status,
261
+ attention_reason: task.attention_reason ?? null,
183
262
  changed_file_count: (task.changed_files ?? []).length,
184
263
  command_count: (task.commands ?? []).length,
185
264
  run_count: task.run_count ?? 0,
265
+ acceptance: acceptanceVerdict(task),
266
+ landed_at: task.landed_at ?? null,
186
267
  current_action: clip(task.current_action, ACTION_PREVIEW_CHARS),
268
+ ...liveness(task),
269
+ last_event_at: task.last_event_at ?? null,
187
270
  last_event_type: task.last_event_type,
188
271
  last_message: clip(task.last_message, 400),
189
272
  notices: clip(task.notices, 400),
@@ -267,6 +350,9 @@ function overviewRow(task, caps) {
267
350
  goal: clip(task.goal_objective, caps.goal),
268
351
  goal_status: task.goal_status ?? null,
269
352
  last_action: clip(task.current_action, caps.action),
353
+ idle_seconds: liveness(task).idle_seconds,
354
+ command_running: Boolean(task.current_command) && ACTIVE_STATUSES.has(task.status),
355
+ acceptance: acceptanceVerdict(task),
270
356
  changed_files: (task.changed_files ?? []).length,
271
357
  depends_on: task.depends_on ?? [],
272
358
  owned_paths: (task.owned_paths ?? []).map((entry) => clip(entry, caps.path))
@@ -315,8 +401,12 @@ function buildOverview(tasks, extras = {}) {
315
401
  total: tasks.length,
316
402
  active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
317
403
  needs_attention: tasks
318
- .filter((task) => task.status === "running" && isGoalNeedingAttention(task.goal_status))
404
+ .filter((task) => isGoalNeedingAttention(task.goal_status) || task.attention_reason)
319
405
  .map((task) => task.id),
406
+ // Terminal rows whose acceptance run failed. Kept apart from
407
+ // needs_attention, which means "running and stuck"; this means
408
+ // "finished and wrong", and the next step is a resume with the output.
409
+ acceptance_failed: tasks.filter((task) => task.acceptance_results?.passed === false).map((task) => task.id),
320
410
  workers: tasks.map((task) => overviewRow(task, caps))
321
411
  };
322
412
  const bytes = settleTokenCount(payload);
@@ -332,6 +422,16 @@ function buildOverview(tasks, extras = {}) {
332
422
  return payload;
333
423
  }
334
424
 
425
+ function acceptanceLine(task) {
426
+ if (!Array.isArray(task.acceptance) || task.acceptance.length === 0) return "acceptance: none configured";
427
+ const results = task.acceptance_results;
428
+ if (!results) return `acceptance: ${task.acceptance.length} configured, not run yet`;
429
+ const ran = results.checks?.length ?? 0;
430
+ const ok = (results.checks ?? []).filter((check) => check.passed !== false && check.exit_code === 0 && !check.timed_out).length;
431
+ const failing = (results.checks ?? []).find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
432
+ return `acceptance: ${results.status}, ${ok}/${task.acceptance.length} passed (${ran} ran)${failing ? `, first failure: ${clip(failing.command, 80)} exit ${failing.timed_out ? "timeout" : failing.exit_code}` : ""}`;
433
+ }
434
+
335
435
  function buildWorkerSummary(task, nativeGoal) {
336
436
  // Read the worktree too: a worker that edits via shell commands emits no
337
437
  // file_change events, so the checkout is the authoritative diff.
@@ -345,6 +445,7 @@ function buildWorkerSummary(task, nativeGoal) {
345
445
  : "codex goal: none recorded for this thread",
346
446
  `changed files (${changed.length}): ${changed.slice(0, 10).join(", ") || "-"}`,
347
447
  `last command: ${commands.at(-1)?.command ?? "-"}`,
448
+ acceptanceLine(task),
348
449
  `last action: ${clip(task.current_action, ACTION_PREVIEW_CHARS) ?? "-"}`,
349
450
  `runs: ${task.run_count ?? 0}${task.resumed_from ? `, resumed from ${task.resumed_from}` : ""}`,
350
451
  task.error ? `error: ${task.error}` : null
@@ -380,16 +481,103 @@ function errorResult(error) {
380
481
  return textResult({
381
482
  error: error.code ?? "error",
382
483
  message: error.message,
383
- ...(error.conflicts ? { conflicts: error.conflicts } : {})
484
+ ...(error.conflicts ? { conflicts: error.conflicts } : {}),
485
+ ...(error.details ? { files: error.details.files ?? [], git: error.details.git ?? null, base_commit: error.details.base_commit ?? null, head: error.details.head ?? null } : {})
384
486
  });
385
487
  }
386
488
 
489
+ function externalOutputView(task, maxChars = 6000) {
490
+ const outputs = task.run_evidence?.external_outputs ?? [];
491
+ const perContent = Math.floor(maxChars / Math.max(1, outputs.length * 2));
492
+ return outputs.map((entry) => ({ ...entry, before: { ...entry.before, content: clip(entry.before.content, perContent) },
493
+ after: { ...entry.after, content: clip(entry.after.content, perContent) } }));
494
+ }
495
+
496
+ function reportView(task, maxChars) {
497
+ const value = task.run_evidence?.structured_report;
498
+ if (!value) return { format: "legacy_text", valid: null };
499
+ if (!value.valid || !maxChars) return value;
500
+ const report = value.report;
501
+ const perEntry = Math.floor(maxChars / Math.max(1, 2 + report.verification.length + report.not_done.length));
502
+ return { ...value, report: { result: clip(report.result, perEntry * 2),
503
+ verification: report.verification.map((entry) => clip(entry, perEntry)),
504
+ not_done: report.not_done.map((entry) => clip(entry, perEntry)) } };
505
+ }
506
+
507
+ function runEvidenceView(task) {
508
+ if (!task.run_evidence) return null;
509
+ const { structured_report, external_outputs, ...evidence } = task.run_evidence;
510
+ return { ...evidence, external_changed_count: (external_outputs ?? []).filter((entry) => entry.changed).length };
511
+ }
512
+
513
+ const acceptanceFailureRecord = z.object({
514
+ test_id: z.string().min(1), kind: z.enum(["failure", "error"]), signature: z.string().min(1)
515
+ }).strict();
516
+ const acceptanceCheck = z.union([
517
+ z.string().min(1),
518
+ z.object({
519
+ command: z.string().min(1), reportPath: z.string().min(1),
520
+ baseline: z.object({
521
+ identity: z.object({ base_commit: z.string().min(1) }).catchall(z.string().min(1)),
522
+ failures: z.array(acceptanceFailureRecord), required: z.array(z.string().min(1))
523
+ }).strict()
524
+ }).strict()
525
+ ]);
526
+ const acceptanceInput = z.union([z.string().min(1), z.array(acceptanceCheck).max(10)]);
527
+
528
+ const observerId = process.env.CODEX_SUPERVISOR_OBSERVER_ID?.trim() || `mcp-${randomUUID()}`;
529
+ let observerRead = Promise.resolve();
530
+ server.registerTool("check_workers", {
531
+ title: "Check changed workers",
532
+ description: "Check newly settled runs and actionable failures; automatically resume a dead lost/no_work first run once, except approval, authentication, permission and quota waits. Returns recovery receipts; 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.",
533
+ inputSchema: {}
534
+ }, async () => {
535
+ const read = observerRead.then(async () => {
536
+ await reconcileDetachedActiveTasks();
537
+ const recoveries = await recoverEligibleRuns();
538
+ const result = collectWorkerChanges(await readTasks(), await readObserverCursor(observerId));
539
+ await writeObserverCursor(observerId, result.cursor);
540
+ const { cursor, ...reply } = result;
541
+ return textResult({ ...reply, quiet: reply.quiet && recoveries.length === 0, recoveries });
542
+ });
543
+ observerRead = read.catch(() => {});
544
+ return read;
545
+ });
546
+
547
+ server.registerTool(
548
+ "check_acceptance",
549
+ {
550
+ title: "Check acceptance commands",
551
+ 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.",
552
+ inputSchema: {
553
+ cwd: z.string().min(1), acceptance: acceptanceInput,
554
+ baseRef: z.string().min(1).optional(), timeoutMs: z.number().int().min(1000).max(1800000).default(600000)
555
+ }
556
+ },
557
+ async ({ cwd, acceptance, baseRef = "HEAD", timeoutMs }) => {
558
+ let base;
559
+ try {
560
+ base = execFileSync("git", ["-C", cwd, "rev-parse", "--verify", `${baseRef}^{commit}`], { encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "pipe"] }).trim();
561
+ } catch {
562
+ return textResult({ error: "invalid_base_ref", phase: "preflight", reason: `baseRef does not resolve in ${cwd}`, proves_worker_completion: false });
563
+ }
564
+ try {
565
+ const commands = Array.isArray(acceptance) ? acceptance : [acceptance];
566
+ 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");
567
+ const result = await runAcceptance(commands, { cwd, timeoutMs, baseCommit: base, taskId: `preflight-${randomUUID()}` });
568
+ return textResult({ ...result, phase: "preflight", base_commit: base, proves_worker_completion: false, warnings });
569
+ } catch (error) {
570
+ return errorResult(error);
571
+ }
572
+ }
573
+ );
574
+
387
575
  server.registerTool(
388
576
  "create_codex_worker",
389
577
  {
390
578
  title: "Create Codex worker",
391
579
  description:
392
- "Launch a Codex CLI worker with codex exec --json and track its events. ownedPaths and goal are required: ownedPaths reserves the files this worker may write, goal records what the worker is for.",
580
+ "Launch a Codex CLI worker with codex exec --json and track its events. ownedPaths and goal are required: ownedPaths reserves the files this worker may write (empty only for a read-only verifier), goal records what the worker is for. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them in the worker's worktree after codex exits, each must exit 0, and the worker sees them in its prompt so it can run them first. Write the check for this step (a test file, a file that must exist, an endpoint that must answer), not the whole suite; a check on another machine goes through ssh. They run with the supervisor's own privileges, as if you ran them yourself. The verdict shows as acceptance on wait, the overview and get_worker_result, and land_codex_worker refuses while it is failed.",
393
581
  inputSchema: {
394
582
  title: z.string().optional(),
395
583
  task: z.string().min(1),
@@ -404,7 +592,17 @@ server.registerTool(
404
592
  model: z.string().optional(),
405
593
  reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
406
594
  skipGitRepoCheck: z.boolean().default(true),
407
- ownedPaths: z.array(z.string().min(1)).min(1),
595
+ // Empty only for a read-only worker (a verifier): it writes nothing,
596
+ // so it owns nothing.
597
+ ownedPaths: z.array(z.string().min(1)),
598
+ forbid: z.array(z.string().min(1)).max(100).optional(),
599
+ allowedCommands: z.array(z.string().min(1)).max(100).optional(),
600
+ context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
601
+ contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
602
+ externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
603
+ networkAccess: z.boolean().default(false),
604
+ maxRunMs: z.number().int().min(1000).max(86400000).optional(),
605
+ maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
408
606
  goal: z.object({
409
607
  objective: z.string().min(1),
410
608
  tokenBudget: z.number().int().positive().optional()
@@ -413,7 +611,11 @@ server.registerTool(
413
611
  // Which commit the worktree is cut from. Defaults to the repository's
414
612
  // HEAD; pass a branch, tag or sha to build on work that is not on the
415
613
  // main line yet (for example another worker's codex/<id> branch).
416
- baseRef: z.string().min(1).optional()
614
+ baseRef: z.string().min(1).optional(),
615
+ // Shell commands that decide whether the work is done. The supervisor
616
+ // runs them in the worktree after codex exits; each must exit 0.
617
+ acceptance: acceptanceInput.optional(),
618
+ acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
417
619
  }
418
620
  },
419
621
  async (input) => {
@@ -449,13 +651,25 @@ server.registerTool(
449
651
  model: z.string().optional(),
450
652
  reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
451
653
  ownedPaths: z.array(z.string().min(1)).optional(),
654
+ forbid: z.array(z.string().min(1)).max(100).optional(),
655
+ allowedCommands: z.array(z.string().min(1)).max(100).optional(),
656
+ context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
657
+ contracts: z.array(z.string().min(1).max(2000)).max(20).optional(),
658
+ externalOutputs: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
659
+ networkAccess: z.boolean().optional(),
660
+ maxRunMs: z.number().int().min(1000).max(86400000).optional(),
661
+ maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
452
662
  goal: z
453
663
  .object({
454
664
  objective: z.string().min(1),
455
665
  tokenBudget: z.number().int().positive().optional()
456
666
  })
457
667
  .optional(),
458
- baseRef: z.string().min(1).optional()
668
+ baseRef: z.string().min(1).optional(),
669
+ // Left out, the parent's acceptance commands are inherited; given, they
670
+ // replace them, and an empty list clears them.
671
+ acceptance: acceptanceInput.optional(),
672
+ acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
459
673
  }
460
674
  },
461
675
  async ({ task_id, followup_prompt, session_id, session_title, session_note, ...options }) => {
@@ -480,16 +694,21 @@ server.registerTool(
480
694
  {
481
695
  title: "Resume Codex worker",
482
696
  description:
483
- "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.",
697
+ "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.",
484
698
  inputSchema: {
485
699
  task_id: z.string().min(1),
486
- prompt: z.string().min(1)
700
+ prompt: z.string().min(1),
701
+ rebaseOnto: z.string().min(1).optional(),
702
+ context: z.array(z.object({ path: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional() })).max(20).optional(),
703
+ // Replaces the stored acceptance commands for this and later runs; an
704
+ // empty list clears them. Left out, the stored commands stay.
705
+ acceptance: acceptanceInput.optional()
487
706
  }
488
707
  },
489
- async ({ task_id, prompt }) => {
708
+ async ({ task_id, prompt, rebaseOnto, acceptance, context }) => {
490
709
  try {
491
- const record = await resumeCodexWorker({ taskId: task_id, prompt });
492
- return textResult(receipt(record));
710
+ const record = await resumeCodexWorker({ taskId: task_id, prompt, rebaseOnto: rebaseOnto ?? null, acceptance, context });
711
+ return textResult({ ...receipt(record), rebase: record.rebase ?? null, base_behind: baseBehind(record.project_root, record.base_commit) });
493
712
  } catch (error) {
494
713
  return errorResult(error);
495
714
  }
@@ -550,11 +769,11 @@ server.registerTool(
550
769
  {
551
770
  title: "Wait for Codex workers",
552
771
  description:
553
- "Block until selected Codex workers reach a terminal status, then return summaries. The wait budget bounds this call, not the workers: when it runs out you get a progress snapshot and the workers keep running, so call this again with the same task_ids to keep waiting. Keep the budget under your client's MCP tool timeout, or the client kills the call instead of the wait returning.",
772
+ "Block until selected Codex workers reach a terminal status, then return summaries. The wait budget bounds this call, not the workers: when it runs out you get a progress snapshot and the workers keep running, so call this again with the same task_ids to keep waiting. Keep the budget under your client's MCP tool timeout, or the client kills the call instead of the wait returning. compact: true returns one line per worker: status, phase, exit_code, changed_file_count, acceptance (passed / failed / null when none was configured or it did not run), plus idle_seconds since the last Codex event of this run, command_running and current_command. Codex emits nothing while a command runs or while the model thinks, so a long idle with command_running: true is a long command and a long idle without it is thinking (or a process that reconcile will report as lost).",
554
773
  inputSchema: {
555
774
  task_ids: z.array(z.string().min(1)).min(1),
556
775
  mode: z.enum(["any", "all"]).default("all"),
557
- timeoutMinutes: z.number().int().min(1).max(360).default(2),
776
+ timeoutMinutes: z.number().int().min(1).max(360).default(1),
558
777
  timeoutMs: z.number().int().min(1000).max(21600000).optional(),
559
778
  pollMs: z.number().int().min(250).max(10000).default(1000),
560
779
  // Off by default. A wait is the call clients background and then replay
@@ -572,7 +791,7 @@ server.registerTool(
572
791
  // The smallest useful answer: one line per worker, for a caller that
573
792
  // only wants to know who is done. Everything else comes from
574
793
  // get_worker_result / get_worker_diff afterwards.
575
- compact: z.boolean().default(false)
794
+ compact: z.boolean().optional()
576
795
  }
577
796
  },
578
797
  async ({
@@ -585,18 +804,30 @@ server.registerTool(
585
804
  eventLimit,
586
805
  eventMaxChars,
587
806
  eventKinds,
588
- compact
589
- }) => {
807
+ compact: requestedCompact
808
+ }, extra) => {
809
+ const compact = requestedCompact ?? !includeEvents;
590
810
  const startedAt = Date.now();
591
811
  const effectiveTimeoutMs = timeoutMs ?? timeoutMinutes * 60 * 1000;
592
812
  let tasks = [];
813
+ const progressToken = extra?._meta?.progressToken;
814
+ let lastProgressAt = -Infinity;
593
815
 
594
816
  while (Date.now() - startedAt < effectiveTimeoutMs) {
817
+ if (extra?.signal.aborted) break;
595
818
  await reconcileDetachedActiveTasks();
596
819
  tasks = (await getTasks(task_ids)).filter(Boolean);
597
820
  const settledCount = tasks.filter(isSettled).length;
598
821
  const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
599
822
  if (isDone) break;
823
+ const elapsed = Date.now() - startedAt;
824
+ if (progressToken != null && elapsed - lastProgressAt >= 30000) {
825
+ await extra.sendNotification({ method: "notifications/progress", params: {
826
+ progressToken, progress: elapsed, total: effectiveTimeoutMs,
827
+ message: `${settledCount}/${task_ids.length} workers settled; wait budget only`
828
+ } }).catch(() => {});
829
+ lastProgressAt = elapsed;
830
+ }
600
831
  await sleep(pollMs);
601
832
  }
602
833
 
@@ -639,6 +870,7 @@ server.registerTool(
639
870
  cancelled_count: tasks.filter((task) => task.status === "cancelled").length,
640
871
  lost_count: tasks.filter((task) => task.status === "lost").length,
641
872
  active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
873
+ acceptance_failed_count: tasks.filter((task) => task.acceptance_results?.passed === false).length,
642
874
  workers: compact
643
875
  ? tasks.map((task) => ({
644
876
  id: task.id,
@@ -647,6 +879,8 @@ server.registerTool(
647
879
  phase: task.phase ?? null,
648
880
  exit_code: task.exit_code ?? null,
649
881
  changed_file_count: readTaskChanges(task).length,
882
+ acceptance: acceptanceVerdict(task),
883
+ ...liveness(task),
650
884
  updated_at: task.updated_at ?? null
651
885
  }))
652
886
  : summaries
@@ -671,6 +905,10 @@ server.registerTool(
671
905
  session_id,
672
906
  title: meta?.title ?? null,
673
907
  note: meta?.note ?? null,
908
+ objective: meta?.objective ?? null,
909
+ default_acceptance: meta?.default_acceptance ?? [],
910
+ approval_state: meta?.approval_state ?? "approved",
911
+ policy_revision: meta?.policy_revision ?? 0,
674
912
  count: tasks.length,
675
913
  active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
676
914
  works: tasks.map(workRow)
@@ -704,12 +942,18 @@ server.registerTool(
704
942
  inputSchema: {
705
943
  session_id: z.string().min(1),
706
944
  title: z.string().min(1).max(120).optional(),
707
- note: z.string().min(1).max(2000).optional()
945
+ note: z.string().min(1).max(2000).optional(),
946
+ objective: z.string().min(1).max(5000).optional(),
947
+ default_acceptance: z.array(acceptanceCheck).max(10).optional(),
948
+ approval_state: z.enum(["approved", "waiting_user"]).optional(),
949
+ expected_revision: z.number().int().nonnegative().optional()
708
950
  }
709
951
  },
710
- async ({ session_id, title, note }) => {
711
- const row = await upsertSession({ id: session_id, title: title ?? null, note: note ?? null });
712
- return textResult({ session_id, title: row?.title ?? null, note: row?.note ?? null, updated_at: row?.updated_at ?? null });
952
+ async ({ session_id, title, note, objective, default_acceptance, approval_state, expected_revision }) => {
953
+ try {
954
+ const row = await upsertSession({ id: session_id, title: title ?? null, note: note ?? null, objective, defaultAcceptance: default_acceptance, approvalState: approval_state, expectedRevision: expected_revision });
955
+ return textResult({ ...row, session_id, host_goal_sync: buildHostGoalSync(row) });
956
+ } catch (error) { return errorResult(error); }
713
957
  }
714
958
  );
715
959
 
@@ -801,7 +1045,8 @@ server.registerTool(
801
1045
  token_budget: task.goal_token_budget,
802
1046
  goal_status: task.goal_status,
803
1047
  needs_attention: isGoalNeedingAttention(task.goal_status),
804
- native_goal: readNativeGoal(task.thread_id)
1048
+ native_goal: readNativeGoal(task.thread_id),
1049
+ native_goal_read: readNativeGoalState(task.thread_id)
805
1050
  });
806
1051
  }
807
1052
  );
@@ -834,14 +1079,16 @@ server.registerTool(
834
1079
  {
835
1080
  title: "Get worker result",
836
1081
  description:
837
- "Read a worker's own final report in full. The overview and the wait response clip the last message so a batch stays inside a context budget; this is the door for the actual conclusion. Returns the last N agent messages plus the status fields needed to tell a real finish from a crash.",
1082
+ "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.",
838
1083
  inputSchema: {
839
1084
  task_id: z.string().min(1),
840
1085
  limit: z.number().int().min(1).max(20).default(1),
841
- maxChars: z.number().int().min(0).max(1000000).optional()
1086
+ // Per report, UTF-8 bytes. 0 means no clipping.
1087
+ maxChars: z.number().int().min(0).max(1000000).default(6000),
1088
+ includeFiles: z.boolean().default(false)
842
1089
  }
843
1090
  },
844
- async ({ task_id, limit, maxChars }) => {
1091
+ async ({ task_id, limit, maxChars, includeFiles }) => {
845
1092
  const task = await getTask(task_id);
846
1093
  if (!task) return textResult({ error: "task_not_found", task_id });
847
1094
  let reports = await readAgentMessages(task_id, limit);
@@ -852,8 +1099,14 @@ server.registerTool(
852
1099
  reports = [task.last_message];
853
1100
  source = "task_row";
854
1101
  }
855
- const truncated = maxChars === undefined ? reports : reports.map((text) => truncateMiddleChars(text, maxChars));
1102
+ const reportBytes = reports.map((text) => Buffer.byteLength(text, "utf8"));
1103
+ const clipped = maxChars === 0 ? reports : reports.map((text) => truncateReport(text, maxChars));
1104
+ const truncated = clipped.some((text, index) => text !== reports[index]);
856
1105
  const changed = readTaskChanges(task);
1106
+ const behind = task.worktree_path ? baseBehind(task.project_root, task.base_commit) : null;
1107
+ // A worker that ran in place has no worktree to diff, so this list is
1108
+ // the only record of what it touched; it is never hidden for those.
1109
+ const listFiles = includeFiles || !task.worktree_path;
857
1110
  return textResult({
858
1111
  task_id,
859
1112
  title: task.title,
@@ -864,9 +1117,25 @@ server.registerTool(
864
1117
  session_id: task.session_id ?? null,
865
1118
  worktree_path: task.worktree_path,
866
1119
  goal_status: task.goal_status,
867
- changed_files: changed,
868
- report_count: truncated.length,
869
- reports: truncated,
1120
+ attention_reason: task.attention_reason ?? null,
1121
+ run_evidence: runEvidenceView(task),
1122
+ structured_report: reportView(task, maxChars),
1123
+ input_context: task.input_context ?? null,
1124
+ external_outputs: externalOutputView(task, maxChars || 6000),
1125
+ changed_file_count: changed.length,
1126
+ changed_files: listFiles ? changed : undefined,
1127
+ base_commit: task.base_commit ?? null,
1128
+ base_behind: behind,
1129
+ landed: task.landed_at ? { at: task.landed_at, head: task.landed_head ?? null } : null,
1130
+ acceptance: acceptanceView(task, behind),
1131
+ verification: summarizeVerification(task),
1132
+ report_count: clipped.length,
1133
+ report_bytes: reportBytes,
1134
+ truncated,
1135
+ next_step: truncated
1136
+ ? `a report was clipped to ${maxChars} bytes; call again with maxChars: ${Math.max(...reportBytes)} (or 0) to read it whole`
1137
+ : null,
1138
+ reports: clipped,
870
1139
  source,
871
1140
  error: task.error ?? null,
872
1141
  completed_at: task.completed_at ?? null
@@ -890,7 +1159,7 @@ server.registerTool(
890
1159
  const task = await getTask(task_id);
891
1160
  if (!task) return textResult({ error: "task_not_found", task_id });
892
1161
  if (!task.worktree_path) {
893
- return textResult({ error: "no_worktree", task_id, 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; look at changed_files from get_worker_result instead" });
1162
+ 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" });
894
1163
  }
895
1164
  const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [] });
896
1165
  return textResult({
@@ -899,7 +1168,8 @@ server.registerTool(
899
1168
  status: task.status,
900
1169
  worktree_path: task.worktree_path,
901
1170
  branch: `codex/${task.id}`,
902
- ...diff
1171
+ ...diff,
1172
+ external_outputs: externalOutputView(task, maxChars)
903
1173
  });
904
1174
  }
905
1175
  );
@@ -953,17 +1223,31 @@ server.registerTool(
953
1223
  {
954
1224
  title: "Land a worker's commits",
955
1225
  description:
956
- "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. Check the work first with get_worker_result and get_worker_diff; land once it passes.",
1226
+ "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. Check the work first with get_worker_result and get_worker_diff; land once it passes. 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.",
957
1227
  inputSchema: {
958
1228
  task_id: z.string().min(1),
959
1229
  onto: z.string().min(1).optional(),
960
- commitMessage: z.string().min(1).optional()
1230
+ commitMessage: z.string().min(1).optional(),
1231
+ ignoreAcceptance: z.boolean().default(false),
1232
+ allowOutsideOwned: z.boolean().default(false)
961
1233
  }
962
1234
  },
963
- async ({ task_id, onto, commitMessage }) => {
1235
+ async ({ task_id, onto, commitMessage, ignoreAcceptance, allowOutsideOwned }) => {
964
1236
  const task = await getTask(task_id);
965
1237
  if (!task) return textResult({ error: "task_not_found", task_id });
966
- return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...landWorker(task, { onto, commitMessage: commitMessage ?? null }) });
1238
+ const session = task.session_id ? await getSession(task.session_id) : null;
1239
+ if (task.attention_reason === "invalid_report") return textResult({ error: "invalid_report", task_id, reason: task.error });
1240
+ if (!isSettled(task)) return textResult({ error: "worker_active", task_id, reason: "wait for this run and acceptance to settle before landing" });
1241
+ if (session?.approval_state === "waiting_user") return textResult({ error: "session_waiting_user", task_id, reason: "session requires user approval before landing" });
1242
+ if (session && task.session_policy_revision !== session.policy_revision) return textResult({ error: "session_policy_stale", task_id, current_revision: session.policy_revision, checked_revision: task.session_policy_revision, reason: "requirements changed; resume with the current objective and rerun acceptance before landing" });
1243
+ const outcome = landWorker(task, { onto, commitMessage: commitMessage ?? null, ignoreAcceptance, allowOutsideOwned });
1244
+ if (!outcome.error) {
1245
+ // Recorded so a later read knows the work is on the branch: the
1246
+ // board shows it, and base_behind after this is not drift.
1247
+ const now = new Date().toISOString();
1248
+ await upsertTask({ ...task, landed_at: now, landed_head: outcome.head ?? null, updated_at: now });
1249
+ }
1250
+ return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome });
967
1251
  }
968
1252
  );
969
1253
 
@@ -986,7 +1270,9 @@ server.registerTool(
986
1270
  await upsertTask({ ...task, cancel_requested_at: now, updated_at: now });
987
1271
  }
988
1272
  const result = await cancelCodexWorker(task_id);
989
- if (result.cancelled && task) {
1273
+ // A cancel that stopped an acceptance run leaves the worker's own
1274
+ // terminal status in place; the exit handler records the verdict.
1275
+ if (result.cancelled && task && result.via !== "acceptance") {
990
1276
  await upsertTask({
991
1277
  ...task,
992
1278
  status: "cancelled",
@@ -0,0 +1,27 @@
1
+ import path from "node:path";
2
+
3
+ // Ownership is declared relative to the project but edits live in the worker
4
+ // checkout. Segment comparisons reject sibling prefixes and parent traversal.
5
+ export function findOutsideOwnedChanges(task, changes, { platform = process.platform } = {}) {
6
+ const p = platform === "win32" ? path.win32 : path.posix;
7
+ const fold = (value) => platform === "win32" ? value.toLowerCase() : value;
8
+ const root = p.resolve(task.project_root);
9
+ const worktree = p.resolve(task.worktree_path ?? task.cwd ?? task.project_root);
10
+ const within = (base, file) => {
11
+ const rel = p.relative(fold(base), fold(file));
12
+ return rel !== ".." && !rel.startsWith(`..${p.sep}`) && !p.isAbsolute(rel);
13
+ };
14
+ const mapping = (task.owned_paths ?? []).flatMap((entry) => {
15
+ const absolute = p.resolve(root, entry);
16
+ if (!within(root, absolute)) return [];
17
+ return [{ declared: entry, worker: p.resolve(worktree, p.relative(root, absolute)) }];
18
+ });
19
+ const owned = [];
20
+ const outside = [];
21
+ for (const change of changes) {
22
+ const absolute = p.resolve(worktree, change);
23
+ const allowed = within(worktree, absolute) && mapping.some((entry) => within(entry.worker, absolute));
24
+ (allowed ? owned : outside).push(change);
25
+ }
26
+ return { owned, outside, mapping };
27
+ }