codex-supervisor-mcp 0.7.2 → 0.8.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
@@ -26,9 +26,11 @@ import {
26
26
  upsertTask
27
27
  } from "./task-store.js";
28
28
  import { readNativeGoal } from "./goal-store.js";
29
- import { readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
29
+ import { baseBehind, readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
30
+ import { summarizeVerification } from "./event-parser.js";
31
+ import { acceptanceVerdict } from "./acceptance.js";
30
32
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
31
- import { approxTokenCount, truncateEventStrings, truncateMiddleChars } from "./truncate.js";
33
+ import { approxTokenCount, truncateEventStrings, truncateMiddleChars, truncateReport } from "./truncate.js";
32
34
  import { checkForUpdate, updateNotice } from "./update-check.js";
33
35
  import { syncSkills } from "./skill-sync.js";
34
36
  import { maybeAutoUpdate } from "./auto-update.js";
@@ -155,10 +157,72 @@ function sleep(ms) {
155
157
  function isSettled(task) {
156
158
  if (!TERMINAL_STATUSES.has(task.status)) return false;
157
159
  if (task.status !== "completed" && task.status !== "failed") return true;
160
+ // Acceptance is running in the supervisor process that owned the worker;
161
+ // the codex pid is already dead, so that process is what to wait on.
162
+ if (task.acceptance_results?.status === "running") return !isPidAlive(task.acceptance_results.supervisor_pid);
158
163
  if (task.exit_code !== null && task.exit_code !== undefined) return true;
159
164
  return !isPidAlive(task.pid);
160
165
  }
161
166
 
167
+ // Codex emits nothing while a command runs and nothing while the model
168
+ // thinks, so a snapshot that has not moved for ten minutes looks the same
169
+ // either way. These three fields tell them apart: current_command is set
170
+ // from the command's item.started until its item.completed, so a long idle
171
+ // with a command is a long command, and a long idle without one is the model
172
+ // (or a stuck process, which reconcile turns into lost on its own).
173
+ const LIVE_COMMAND_PREVIEW_CHARS = 120;
174
+ function liveness(task) {
175
+ if (!ACTIVE_STATUSES.has(task.status)) {
176
+ return { idle_seconds: null, command_running: false, current_command: null };
177
+ }
178
+ const since = Date.parse(task.last_event_at ?? task.started_at ?? "");
179
+ const idle = Number.isFinite(since) ? Math.max(0, Math.floor((Date.now() - since) / 1000)) : null;
180
+ const command = task.current_command ? clip(task.current_command, LIVE_COMMAND_PREVIEW_CHARS) : null;
181
+ return { idle_seconds: idle, command_running: Boolean(task.current_command), current_command: command };
182
+ }
183
+
184
+ // The acceptance verdict as get_worker_result reports it, with the one
185
+ // contradiction a tool can see spelled out: checks passed, worker says
186
+ // otherwise (the "it was never built" case, where it was).
187
+ function acceptanceView(task, behind) {
188
+ const configured = Array.isArray(task.acceptance) && task.acceptance.length > 0;
189
+ const results = task.acceptance_results ?? null;
190
+ const view = {
191
+ configured,
192
+ commands: configured ? task.acceptance : [],
193
+ status: results?.status ?? null,
194
+ passed: results?.passed ?? null,
195
+ run: results?.run ?? null,
196
+ checks: results?.checks ?? [],
197
+ error: results?.error ?? null,
198
+ // Drift matters only before the work is landed: once it is on the
199
+ // branch, the branch having moved is expected.
200
+ stale: Boolean(results && behind && behind.behind > 0 && !(task.landed_at && task.landed_at >= (results.finished_at ?? ""))),
201
+ next_step: null
202
+ };
203
+ if (!configured) return view;
204
+ if (view.status === "failed") {
205
+ const failing = view.checks.find((check) => check.exit_code !== 0) ?? null;
206
+ view.next_step = failing
207
+ ? `acceptance failed: ${clip(failing.command, 120)} exited ${failing.timed_out ? "by timeout" : failing.exit_code}; resume the worker with checks[].output_tail in the prompt, or fix it yourself. Do not land until it passes.`
208
+ : `acceptance could not run (${view.error ?? "unknown"}); fix that first`;
209
+ } else if (view.status === "passed") {
210
+ const verification = summarizeVerification(task);
211
+ const workerSaysNo = task.status === "failed" || isGoalNeedingAttention(task.goal_status) || verification.last_command_failed;
212
+ if (workerSaysNo) view.next_step = "the checks passed but the worker reports otherwise; trust the checks and read the diff";
213
+ 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";
214
+ } else if (view.status === "running") {
215
+ view.next_step = "acceptance is still running in the supervisor; wait_codex_workers returns when it is done";
216
+ } else if (view.status === "interrupted") {
217
+ view.next_step = "the supervisor exited while running acceptance; resume the worker (or cancel and redispatch) to run it again";
218
+ } else if (view.status === "cancelled") {
219
+ view.next_step = "acceptance was cancelled; resume the worker to run it again";
220
+ } else if (view.status === null) {
221
+ view.next_step = "acceptance has not run yet for this worker";
222
+ }
223
+ return view;
224
+ }
225
+
162
226
  function summarizeTask(task) {
163
227
  return {
164
228
  id: task.id,
@@ -183,7 +247,11 @@ function summarizeTask(task) {
183
247
  changed_file_count: (task.changed_files ?? []).length,
184
248
  command_count: (task.commands ?? []).length,
185
249
  run_count: task.run_count ?? 0,
250
+ acceptance: acceptanceVerdict(task),
251
+ landed_at: task.landed_at ?? null,
186
252
  current_action: clip(task.current_action, ACTION_PREVIEW_CHARS),
253
+ ...liveness(task),
254
+ last_event_at: task.last_event_at ?? null,
187
255
  last_event_type: task.last_event_type,
188
256
  last_message: clip(task.last_message, 400),
189
257
  notices: clip(task.notices, 400),
@@ -267,6 +335,9 @@ function overviewRow(task, caps) {
267
335
  goal: clip(task.goal_objective, caps.goal),
268
336
  goal_status: task.goal_status ?? null,
269
337
  last_action: clip(task.current_action, caps.action),
338
+ idle_seconds: liveness(task).idle_seconds,
339
+ command_running: Boolean(task.current_command) && ACTIVE_STATUSES.has(task.status),
340
+ acceptance: acceptanceVerdict(task),
270
341
  changed_files: (task.changed_files ?? []).length,
271
342
  depends_on: task.depends_on ?? [],
272
343
  owned_paths: (task.owned_paths ?? []).map((entry) => clip(entry, caps.path))
@@ -317,6 +388,10 @@ function buildOverview(tasks, extras = {}) {
317
388
  needs_attention: tasks
318
389
  .filter((task) => task.status === "running" && isGoalNeedingAttention(task.goal_status))
319
390
  .map((task) => task.id),
391
+ // Terminal rows whose acceptance run failed. Kept apart from
392
+ // needs_attention, which means "running and stuck"; this means
393
+ // "finished and wrong", and the next step is a resume with the output.
394
+ acceptance_failed: tasks.filter((task) => task.acceptance_results?.passed === false).map((task) => task.id),
320
395
  workers: tasks.map((task) => overviewRow(task, caps))
321
396
  };
322
397
  const bytes = settleTokenCount(payload);
@@ -332,6 +407,16 @@ function buildOverview(tasks, extras = {}) {
332
407
  return payload;
333
408
  }
334
409
 
410
+ function acceptanceLine(task) {
411
+ if (!Array.isArray(task.acceptance) || task.acceptance.length === 0) return "acceptance: none configured";
412
+ const results = task.acceptance_results;
413
+ if (!results) return `acceptance: ${task.acceptance.length} configured, not run yet`;
414
+ const ran = results.checks?.length ?? 0;
415
+ const ok = (results.checks ?? []).filter((check) => check.exit_code === 0).length;
416
+ const failing = (results.checks ?? []).find((check) => check.exit_code !== 0);
417
+ 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}` : ""}`;
418
+ }
419
+
335
420
  function buildWorkerSummary(task, nativeGoal) {
336
421
  // Read the worktree too: a worker that edits via shell commands emits no
337
422
  // file_change events, so the checkout is the authoritative diff.
@@ -345,6 +430,7 @@ function buildWorkerSummary(task, nativeGoal) {
345
430
  : "codex goal: none recorded for this thread",
346
431
  `changed files (${changed.length}): ${changed.slice(0, 10).join(", ") || "-"}`,
347
432
  `last command: ${commands.at(-1)?.command ?? "-"}`,
433
+ acceptanceLine(task),
348
434
  `last action: ${clip(task.current_action, ACTION_PREVIEW_CHARS) ?? "-"}`,
349
435
  `runs: ${task.run_count ?? 0}${task.resumed_from ? `, resumed from ${task.resumed_from}` : ""}`,
350
436
  task.error ? `error: ${task.error}` : null
@@ -380,7 +466,8 @@ function errorResult(error) {
380
466
  return textResult({
381
467
  error: error.code ?? "error",
382
468
  message: error.message,
383
- ...(error.conflicts ? { conflicts: error.conflicts } : {})
469
+ ...(error.conflicts ? { conflicts: error.conflicts } : {}),
470
+ ...(error.details ? { files: error.details.files ?? [], git: error.details.git ?? null, base_commit: error.details.base_commit ?? null, head: error.details.head ?? null } : {})
384
471
  });
385
472
  }
386
473
 
@@ -389,7 +476,7 @@ server.registerTool(
389
476
  {
390
477
  title: "Create Codex worker",
391
478
  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.",
479
+ "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
480
  inputSchema: {
394
481
  title: z.string().optional(),
395
482
  task: z.string().min(1),
@@ -404,7 +491,9 @@ server.registerTool(
404
491
  model: z.string().optional(),
405
492
  reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
406
493
  skipGitRepoCheck: z.boolean().default(true),
407
- ownedPaths: z.array(z.string().min(1)).min(1),
494
+ // Empty only for a read-only worker (a verifier): it writes nothing,
495
+ // so it owns nothing.
496
+ ownedPaths: z.array(z.string().min(1)),
408
497
  goal: z.object({
409
498
  objective: z.string().min(1),
410
499
  tokenBudget: z.number().int().positive().optional()
@@ -413,7 +502,11 @@ server.registerTool(
413
502
  // Which commit the worktree is cut from. Defaults to the repository's
414
503
  // HEAD; pass a branch, tag or sha to build on work that is not on the
415
504
  // main line yet (for example another worker's codex/<id> branch).
416
- baseRef: z.string().min(1).optional()
505
+ baseRef: z.string().min(1).optional(),
506
+ // Shell commands that decide whether the work is done. The supervisor
507
+ // runs them in the worktree after codex exits; each must exit 0.
508
+ acceptance: z.union([z.string().min(1), z.array(z.string().min(1)).max(10)]).optional(),
509
+ acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
417
510
  }
418
511
  },
419
512
  async (input) => {
@@ -455,7 +548,11 @@ server.registerTool(
455
548
  tokenBudget: z.number().int().positive().optional()
456
549
  })
457
550
  .optional(),
458
- baseRef: z.string().min(1).optional()
551
+ baseRef: z.string().min(1).optional(),
552
+ // Left out, the parent's acceptance commands are inherited; given, they
553
+ // replace them, and an empty list clears them.
554
+ acceptance: z.union([z.string().min(1), z.array(z.string().min(1)).max(10)]).optional(),
555
+ acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
459
556
  }
460
557
  },
461
558
  async ({ task_id, followup_prompt, session_id, session_title, session_note, ...options }) => {
@@ -480,16 +577,20 @@ server.registerTool(
480
577
  {
481
578
  title: "Resume Codex worker",
482
579
  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.",
580
+ "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
581
  inputSchema: {
485
582
  task_id: z.string().min(1),
486
- prompt: z.string().min(1)
583
+ prompt: z.string().min(1),
584
+ rebaseOnto: z.string().min(1).optional(),
585
+ // Replaces the stored acceptance commands for this and later runs; an
586
+ // empty list clears them. Left out, the stored commands stay.
587
+ acceptance: z.union([z.string().min(1), z.array(z.string().min(1)).max(10)]).optional()
487
588
  }
488
589
  },
489
- async ({ task_id, prompt }) => {
590
+ async ({ task_id, prompt, rebaseOnto, acceptance }) => {
490
591
  try {
491
- const record = await resumeCodexWorker({ taskId: task_id, prompt });
492
- return textResult(receipt(record));
592
+ const record = await resumeCodexWorker({ taskId: task_id, prompt, rebaseOnto: rebaseOnto ?? null, acceptance });
593
+ return textResult({ ...receipt(record), rebase: record.rebase ?? null, base_behind: baseBehind(record.project_root, record.base_commit) });
493
594
  } catch (error) {
494
595
  return errorResult(error);
495
596
  }
@@ -550,7 +651,7 @@ server.registerTool(
550
651
  {
551
652
  title: "Wait for Codex workers",
552
653
  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.",
654
+ "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
655
  inputSchema: {
555
656
  task_ids: z.array(z.string().min(1)).min(1),
556
657
  mode: z.enum(["any", "all"]).default("all"),
@@ -639,6 +740,7 @@ server.registerTool(
639
740
  cancelled_count: tasks.filter((task) => task.status === "cancelled").length,
640
741
  lost_count: tasks.filter((task) => task.status === "lost").length,
641
742
  active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
743
+ acceptance_failed_count: tasks.filter((task) => task.acceptance_results?.passed === false).length,
642
744
  workers: compact
643
745
  ? tasks.map((task) => ({
644
746
  id: task.id,
@@ -647,6 +749,8 @@ server.registerTool(
647
749
  phase: task.phase ?? null,
648
750
  exit_code: task.exit_code ?? null,
649
751
  changed_file_count: readTaskChanges(task).length,
752
+ acceptance: acceptanceVerdict(task),
753
+ ...liveness(task),
650
754
  updated_at: task.updated_at ?? null
651
755
  }))
652
756
  : summaries
@@ -834,14 +938,16 @@ server.registerTool(
834
938
  {
835
939
  title: "Get worker result",
836
940
  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.",
941
+ "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
942
  inputSchema: {
839
943
  task_id: z.string().min(1),
840
944
  limit: z.number().int().min(1).max(20).default(1),
841
- maxChars: z.number().int().min(0).max(1000000).optional()
945
+ // Per report, UTF-8 bytes. 0 means no clipping.
946
+ maxChars: z.number().int().min(0).max(1000000).default(6000),
947
+ includeFiles: z.boolean().default(false)
842
948
  }
843
949
  },
844
- async ({ task_id, limit, maxChars }) => {
950
+ async ({ task_id, limit, maxChars, includeFiles }) => {
845
951
  const task = await getTask(task_id);
846
952
  if (!task) return textResult({ error: "task_not_found", task_id });
847
953
  let reports = await readAgentMessages(task_id, limit);
@@ -852,8 +958,14 @@ server.registerTool(
852
958
  reports = [task.last_message];
853
959
  source = "task_row";
854
960
  }
855
- const truncated = maxChars === undefined ? reports : reports.map((text) => truncateMiddleChars(text, maxChars));
961
+ const reportBytes = reports.map((text) => Buffer.byteLength(text, "utf8"));
962
+ const clipped = maxChars === 0 ? reports : reports.map((text) => truncateReport(text, maxChars));
963
+ const truncated = clipped.some((text, index) => text !== reports[index]);
856
964
  const changed = readTaskChanges(task);
965
+ const behind = task.worktree_path ? baseBehind(task.project_root, task.base_commit) : null;
966
+ // A worker that ran in place has no worktree to diff, so this list is
967
+ // the only record of what it touched; it is never hidden for those.
968
+ const listFiles = includeFiles || !task.worktree_path;
857
969
  return textResult({
858
970
  task_id,
859
971
  title: task.title,
@@ -864,9 +976,20 @@ server.registerTool(
864
976
  session_id: task.session_id ?? null,
865
977
  worktree_path: task.worktree_path,
866
978
  goal_status: task.goal_status,
867
- changed_files: changed,
868
- report_count: truncated.length,
869
- reports: truncated,
979
+ changed_file_count: changed.length,
980
+ changed_files: listFiles ? changed : undefined,
981
+ base_commit: task.base_commit ?? null,
982
+ base_behind: behind,
983
+ landed: task.landed_at ? { at: task.landed_at, head: task.landed_head ?? null } : null,
984
+ acceptance: acceptanceView(task, behind),
985
+ verification: summarizeVerification(task),
986
+ report_count: clipped.length,
987
+ report_bytes: reportBytes,
988
+ truncated,
989
+ next_step: truncated
990
+ ? `a report was clipped to ${maxChars} bytes; call again with maxChars: ${Math.max(...reportBytes)} (or 0) to read it whole`
991
+ : null,
992
+ reports: clipped,
870
993
  source,
871
994
  error: task.error ?? null,
872
995
  completed_at: task.completed_at ?? null
@@ -890,7 +1013,7 @@ server.registerTool(
890
1013
  const task = await getTask(task_id);
891
1014
  if (!task) return textResult({ error: "task_not_found", task_id });
892
1015
  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" });
1016
+ 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; call get_worker_result with includeFiles: true for the files it touched" });
894
1017
  }
895
1018
  const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [] });
896
1019
  return textResult({
@@ -953,17 +1076,25 @@ server.registerTool(
953
1076
  {
954
1077
  title: "Land a worker's commits",
955
1078
  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.",
1079
+ "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
1080
  inputSchema: {
958
1081
  task_id: z.string().min(1),
959
1082
  onto: z.string().min(1).optional(),
960
- commitMessage: z.string().min(1).optional()
1083
+ commitMessage: z.string().min(1).optional(),
1084
+ ignoreAcceptance: z.boolean().default(false)
961
1085
  }
962
1086
  },
963
- async ({ task_id, onto, commitMessage }) => {
1087
+ async ({ task_id, onto, commitMessage, ignoreAcceptance }) => {
964
1088
  const task = await getTask(task_id);
965
1089
  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 }) });
1090
+ const outcome = landWorker(task, { onto, commitMessage: commitMessage ?? null, ignoreAcceptance });
1091
+ if (!outcome.error) {
1092
+ // Recorded so a later read knows the work is on the branch: the
1093
+ // board shows it, and base_behind after this is not drift.
1094
+ const now = new Date().toISOString();
1095
+ await upsertTask({ ...task, landed_at: now, landed_head: outcome.head ?? null, updated_at: now });
1096
+ }
1097
+ return textResult({ task_id, title: task.title, status: task.status, branch: `codex/${task.id}`, ...outcome });
967
1098
  }
968
1099
  );
969
1100
 
@@ -986,7 +1117,9 @@ server.registerTool(
986
1117
  await upsertTask({ ...task, cancel_requested_at: now, updated_at: now });
987
1118
  }
988
1119
  const result = await cancelCodexWorker(task_id);
989
- if (result.cancelled && task) {
1120
+ // A cancel that stopped an acceptance run leaves the worker's own
1121
+ // terminal status in place; the exit handler records the verdict.
1122
+ if (result.cancelled && task && result.via !== "acceptance") {
990
1123
  await upsertTask({
991
1124
  ...task,
992
1125
  status: "cancelled",
package/src/prompt.js CHANGED
@@ -1,12 +1,23 @@
1
- // Worker prompt framing.
1
+ // Worker prompt framing: what goes around the task text.
2
2
  //
3
- // Codex exposes goal tools (create_goal / get_goal / update_goal) to every
4
- // thread, but the model does not create a goal on its own. A worker therefore
5
- // starts with no native goal unless we ask for one, which is why the supervisor
6
- // prepends this block instead of only recording the goal on its own side.
3
+ // Goal preamble, in front. Codex exposes goal tools (create_goal / get_goal /
4
+ // update_goal) to every thread, but the model does not create a goal on its
5
+ // own. A worker therefore starts with no native goal unless we ask for one,
6
+ // which is why the supervisor prepends this block instead of only recording
7
+ // the goal on its own side. create_goal fails when an unfinished goal already
8
+ // exists, so the resume path must not ask for one: that thread already has
9
+ // its goal.
7
10
  //
8
- // create_goal fails when an unfinished goal already exists, so the resume path
9
- // must not ask for one: that thread already has its goal.
11
+ // Report format, at the end. A worker's last message is what the supervisor
12
+ // reads back through get_worker_result. Left to itself a worker narrates
13
+ // the whole run and lists every file it touched, and one real report ran to
14
+ // four thousand tokens with the conclusion buried in the middle. The format
15
+ // asks for the three things a reviewer checks and nothing else: the result,
16
+ // the commands that prove it, and what was left out. Files are not listed
17
+ // because the supervisor reads the diff. It goes after the task text because
18
+ // a format instruction at the end of a long prompt is the one that is
19
+ // followed, and because "the task's own format wins" has to come after the
20
+ // task.
10
21
 
11
22
  function oneLine(value) {
12
23
  return String(value ?? "").replace(/\s+/g, " ").trim();
@@ -33,7 +44,49 @@ export function buildGoalPreamble({ objective, tokenBudget = null, resume = fals
33
44
  ].join("\n");
34
45
  }
35
46
 
47
+ export const REPORT_SECTIONS = ["Result", "Verification", "Not done / risks"];
48
+
49
+ // The acceptance commands are shown to the worker. Hiding them would not
50
+ // stop a worker from gaming a check (it can see the tests in the tree
51
+ // anyway) and would stop it from running them before it reports, which is
52
+ // the cheapest fix loop there is. The supervisor runs them again after the
53
+ // worker exits regardless of what the worker says.
54
+ export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
55
+ const commands = Array.isArray(acceptance) ? acceptance.filter(Boolean) : [];
56
+ if (commands.length === 0) return "";
57
+ if (resume) {
58
+ return `Acceptance is unchanged; run it before you report: ${commands.join(" ; ")}`;
59
+ }
60
+ return [
61
+ "Acceptance: when you exit, the supervisor runs these commands in this directory and each must exit 0:",
62
+ ...commands.map((command) => `- ${command}`),
63
+ "Run them yourself before you report and put their exit codes under Verification. Do not edit what they test to make them pass; if a check is wrong, say why under Not done / risks."
64
+ ].join("\n");
65
+ }
66
+
67
+ export function buildReportPreamble({ resume = false, acceptance = null } = {}) {
68
+ const acceptanceBlock = buildAcceptanceBlock(acceptance, { resume });
69
+ const withAcceptance = (text) => (acceptanceBlock ? `${text}\n\n${acceptanceBlock}` : text);
70
+ if (resume) {
71
+ return withAcceptance("Report as before: Result / Verification (every command you ran to check, with exit codes) / Not done and risks. Under 2000 characters, no list of changed files, quote raw errors verbatim.");
72
+ }
73
+ return withAcceptance([
74
+ "Final report (your last message), under 2000 characters, in the language of the task. Quoted command output does not count toward the limit.",
75
+ "1. Result: what is done, in two or three sentences. Say plainly what is not done.",
76
+ "2. Verification: every command you ran to check the work, its exit code, and the output lines that prove the result. Write \"not verified\" if you ran none.",
77
+ "3. Not done / risks: what you skipped, what you are unsure of, what the reviewer should look at first.",
78
+ "Do not list the files you changed; the supervisor reads the diff.",
79
+ "Never call a failure an environment problem without quoting the raw error verbatim.",
80
+ "If the task above specifies its own report format, use that format and still cover the three points."
81
+ ].join("\n"));
82
+ }
83
+
36
84
  export function withGoalPreamble(prompt, goalOptions) {
37
85
  const preamble = buildGoalPreamble(goalOptions);
38
86
  return preamble ? `${preamble}\n\n${prompt}` : prompt;
39
87
  }
88
+
89
+ // The whole frame: goal in front, task text, report format at the end.
90
+ export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null } = {}) {
91
+ return `${withGoalPreamble(prompt, goalOptions)}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance })}`;
92
+ }
package/src/task-store.js CHANGED
@@ -24,7 +24,12 @@ const POST_V1_COLUMNS = [
24
24
  ["cancel_requested_at", "TEXT"],
25
25
  ["notices", "TEXT"],
26
26
  ["session_id", "TEXT"],
27
- ["base_commit", "TEXT"]
27
+ ["base_commit", "TEXT"],
28
+ ["acceptance", "TEXT"],
29
+ ["acceptance_timeout_ms", "INTEGER"],
30
+ ["acceptance_results", "TEXT"],
31
+ ["landed_at", "TEXT"],
32
+ ["landed_head", "TEXT"]
28
33
  ];
29
34
 
30
35
  const TASKS_DDL = `
@@ -74,6 +79,11 @@ const TASKS_DDL = `
74
79
  notices TEXT,
75
80
  worktree_path TEXT,
76
81
  base_commit TEXT,
82
+ acceptance TEXT,
83
+ acceptance_timeout_ms INTEGER,
84
+ acceptance_results TEXT,
85
+ landed_at TEXT,
86
+ landed_head TEXT,
77
87
  run_log TEXT NOT NULL
78
88
  );
79
89
  `;
@@ -86,7 +96,7 @@ const TASK_COLUMNS = [
86
96
  "current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
87
97
  "depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
88
98
  "goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
89
- "notices", "worktree_path", "base_commit", "run_log"
99
+ "notices", "worktree_path", "base_commit", "acceptance", "acceptance_timeout_ms", "acceptance_results", "landed_at", "landed_head", "run_log"
90
100
  ];
91
101
 
92
102
  function tableColumns(dbInstance, tableName) {
@@ -293,6 +303,8 @@ function rowToTask(row) {
293
303
  commands: decodeJson(row.commands, []),
294
304
  owned_paths: decodeJson(row.owned_paths, []),
295
305
  depends_on: decodeJson(row.depends_on, []),
306
+ acceptance: decodeJson(row.acceptance, null),
307
+ acceptance_results: decodeJson(row.acceptance_results, null),
296
308
  pid: row.pid ?? null,
297
309
  exit_code: row.exit_code ?? null,
298
310
  phase: row.phase ?? null,
@@ -341,7 +353,29 @@ function neverStarted(task, now = Date.now()) {
341
353
  return now - created > NEVER_STARTED_GRACE_MS;
342
354
  }
343
355
 
356
+ // A terminal row whose acceptance run was cut short: the MCP process that
357
+ // was running the checks is gone. Left alone it would read as "running"
358
+ // forever and land would treat it as never run.
359
+ async function reconcileInterruptedAcceptance() {
360
+ const tasks = await readTasks();
361
+ const interrupted = tasks.filter((task) =>
362
+ TERMINAL_STATUSES.has(task.status)
363
+ && task.acceptance_results?.status === "running"
364
+ && !isPidAlive(task.acceptance_results.supervisor_pid));
365
+ for (const task of interrupted) {
366
+ const now = new Date().toISOString();
367
+ await writeTask({
368
+ ...task,
369
+ acceptance_results: { ...task.acceptance_results, status: "interrupted", passed: null, finished_at: now },
370
+ current_action: "Acceptance interrupted: the supervisor process exited while running the checks",
371
+ updated_at: now
372
+ });
373
+ }
374
+ return interrupted;
375
+ }
376
+
344
377
  export async function reconcileDetachedActiveTasks() {
378
+ await reconcileInterruptedAcceptance();
345
379
  const tasks = await readActiveTasks();
346
380
  const staleTasks = tasks.filter((task) => (task.pid && !isPidAlive(task.pid)) || neverStarted(task));
347
381
  for (const task of staleTasks) {
@@ -386,6 +420,10 @@ export async function writeTask(task) {
386
420
  params.commands = encodeJson(task.commands);
387
421
  params.owned_paths = encodeJson(task.owned_paths);
388
422
  params.depends_on = encodeJson(task.depends_on);
423
+ // JSON columns: node:sqlite refuses to bind an array or object, and a
424
+ // refused bind drops the whole row update.
425
+ params.acceptance = task.acceptance ? JSON.stringify(task.acceptance) : null;
426
+ params.acceptance_results = task.acceptance_results ? JSON.stringify(task.acceptance_results) : null;
389
427
  params.run_count = task.run_count ?? 0;
390
428
  params.phase = task.phase ?? null;
391
429
 
package/src/truncate.js CHANGED
@@ -93,6 +93,19 @@ export function truncateMiddleChars(s, maxBytes) {
93
93
  return truncateWithByteEstimate(s, maxBytes, false);
94
94
  }
95
95
 
96
+ // A worker's report leads with its conclusion and ends with what it left
97
+ // out, so a clipped report keeps most of the head and some of the tail
98
+ // instead of an even split, which cut exactly the verification section out
99
+ // of a three-part report.
100
+ export function truncateReport(s, maxBytes, headShare = 0.7) {
101
+ if (s === "") return s;
102
+ const totalBytes = Buffer.byteLength(s, "utf8");
103
+ if (maxBytes <= 0 || totalBytes <= maxBytes) return s;
104
+ const head = Math.floor(maxBytes * headShare);
105
+ const { removedChars, before, after } = splitString(s, head, maxBytes - head);
106
+ return `${before}\n${formatTruncationMarker(false, removedChars)}\n${after}`;
107
+ }
108
+
96
109
  export function truncateMiddleWithTokenBudget(s, maxTokens) {
97
110
  if (s === "") return { text: "", originalTokenCount: null };
98
111
  if (maxTokens > 0 && Buffer.byteLength(s, "utf8") <= approxBytesForTokens(maxTokens)) {
package/src/web-app.js CHANGED
@@ -82,6 +82,8 @@ function workerRow(task) {
82
82
  current_action: clip(task.current_action, 300),
83
83
  last_message: clip(task.last_message, 400),
84
84
  changed_file_count: liveChangeCount(task),
85
+ acceptance: task.acceptance_results?.status ?? null,
86
+ landed_at: task.landed_at ?? null,
85
87
  command_count: (task.commands ?? []).length,
86
88
  error: task.error ?? null,
87
89
  exit_code: task.exit_code ?? null,
package/src/worktree.js CHANGED
@@ -211,3 +211,31 @@ export function worktreeRef(task) {
211
211
  export function readTaskChanges(task) {
212
212
  return mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path, worktreeRef(task)));
213
213
  }
214
+
215
+ // How far the project has moved since the worktree was cut. Compared with
216
+ // the project directory's HEAD, which is the branch the main thread
217
+ // integrates on. contains_base false means the base was rewritten (an
218
+ // amend or a rebase on the main branch) and the count is of a history the
219
+ // base is not in; every git error is reported as null, never as 0.
220
+ export function baseBehind(projectRoot, baseCommit) {
221
+ if (!projectRoot || !baseCommit || !existsSync(projectRoot)) return { behind: null, contains_base: null, ref: null };
222
+ let ref = null;
223
+ try {
224
+ ref = git(projectRoot, ["symbolic-ref", "--short", "-q", "HEAD"]).trim() || "HEAD";
225
+ } catch {
226
+ ref = "HEAD";
227
+ }
228
+ try {
229
+ const behind = Number(git(projectRoot, ["rev-list", "--count", `${baseCommit}..HEAD`]).trim());
230
+ let containsBase = true;
231
+ try {
232
+ git(projectRoot, ["merge-base", "--is-ancestor", baseCommit, "HEAD"]);
233
+ } catch (error) {
234
+ if (error.status === 1) containsBase = false;
235
+ else return { behind: null, contains_base: null, ref };
236
+ }
237
+ return { behind: Number.isFinite(behind) ? behind : null, contains_base: containsBase, ref };
238
+ } catch {
239
+ return { behind: null, contains_base: null, ref };
240
+ }
241
+ }