codex-supervisor-mcp 0.8.0 → 0.9.1

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/handoff.js ADDED
@@ -0,0 +1,31 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, lstat } from "node:fs/promises";
3
+ import { isAbsolute } from "node:path";
4
+
5
+ export async function buildHandoff({ goal, todo, peers = [], contracts = [], context = [] }, { maxLines = 16, maxChars = 1800 } = {}) {
6
+ if (!Array.isArray(context) || context.length > 20 || !Array.isArray(contracts)
7
+ || contracts.some((value) => typeof value !== "string") || JSON.stringify({ context, contracts }).length > 6000) throw new Error("context and contracts exceed the 6000 character input budget");
8
+ const refs = [];
9
+ for (const entry of context) {
10
+ if (!entry || !isAbsolute(entry.path)) throw new Error("context paths must be absolute");
11
+ const info = await lstat(entry.path);
12
+ if (!info.isFile() || info.size > 5_000_000) throw new Error("context source must be a regular file of at most 5 MB");
13
+ const sha256 = createHash("sha256").update(await readFile(entry.path)).digest("hex");
14
+ if (entry.sha256 && entry.sha256 !== sha256) throw new Error(`context source changed: ${entry.path}`);
15
+ refs.push({ path: entry.path, sha256 });
16
+ }
17
+ const line = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
18
+ const candidates = ["Handoff (source refs are inputs, not write permission):", `Goal: ${line(goal)}`, `Todo: ${line(todo)}`,
19
+ ...refs.map((ref) => `Input: ${ref.path} sha256=${ref.sha256}`),
20
+ ...contracts.map((value) => `Contract: ${line(value)}`),
21
+ ...peers.map((peer) => `Peer: ${line(peer.title)} | ${line(peer.status)} | ${line(peer.last_message).slice(0, 160)}`)];
22
+ const marker = "[handoff truncated; required task/guard/acceptance follow separately]";
23
+ const lines = []; let size = 0;
24
+ for (const candidate of candidates) {
25
+ if (lines.length >= maxLines - 1 || size + candidate.length + 1 > maxChars - marker.length - 1) break;
26
+ lines.push(candidate); size += candidate.length + 1;
27
+ }
28
+ const truncated = lines.length !== candidates.length;
29
+ if (truncated) lines.push(marker);
30
+ return { text: lines.join("\n"), truncated, source_refs: refs };
31
+ }
package/src/landing.js CHANGED
@@ -8,8 +8,9 @@
8
8
  // conflict leaves nothing half-applied.
9
9
  import { execFileSync } from "node:child_process";
10
10
  import { existsSync, rmSync } from "node:fs";
11
- import { join } from "node:path";
12
- import { parsePorcelainLine, resolveWorktreeBase, worktreeRef } from "./worktree.js";
11
+ import { join, relative } from "node:path";
12
+ import { parsePorcelainLine, resolveWorktreeBase, worktreeRef, readWorktreeChanges, readWorktreeDiff } from "./worktree.js";
13
+ import { findOutsideOwnedChanges } from "./owned-changes.js";
13
14
 
14
15
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
15
16
 
@@ -80,17 +81,17 @@ function currentBranch(cwd) {
80
81
  //
81
82
  // Returns { landed: [{ sha, original, subject }], onto, head } on success;
82
83
  // otherwise { error, reason, ... } with nothing changed in the target.
83
- export function landWorker(task, { onto = null, commitMessage = null, ignoreAcceptance = false } = {}) {
84
+ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcceptance = false, allowOutsideOwned = false } = {}) {
84
85
  const target = task.project_root;
85
86
  // The dispatcher's own checks are the gate. A failed run is refused until
86
87
  // it passes; a run that was cut short is refused until it has run.
87
88
  const acceptance = task.acceptance_results ?? null;
88
89
  if (!ignoreAcceptance && acceptance) {
89
- const failing = (acceptance.checks ?? []).find((check) => check.exit_code !== 0) ?? null;
90
+ const failing = (acceptance.checks ?? []).find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out) ?? null;
90
91
  if (acceptance.passed === false) {
91
92
  return {
92
93
  error: "acceptance_failed",
93
- reason: `the worker's acceptance run failed${failing ? ` on "${failing.command.slice(0, 120)}" (exit ${failing.timed_out ? "timeout" : failing.exit_code})` : acceptance.error ? ` (${acceptance.error})` : ""}; resume the worker with the failing output and land once it passes. ignoreAcceptance: true lands anyway, only when the user said to.`,
94
+ reason: `the worker's acceptance run failed${failing ? ` on "${failing.command.slice(0, 120)}" (exit ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code)})` : acceptance.error ? ` (${acceptance.error})` : ""}; resume the worker with the failing output and land once it passes. ignoreAcceptance: true lands anyway, only when the user said to.`,
94
95
  acceptance: { status: acceptance.status, passed: false, checks: acceptance.checks ?? [], error: acceptance.error ?? null }
95
96
  };
96
97
  }
@@ -125,6 +126,14 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
125
126
 
126
127
  const base = resolveWorktreeBase(task.worktree_path, worktreeRef(task));
127
128
  if (!base) return { error: "no_base_commit", reason: "the commit this worker started from is unknown, so its commits cannot be told apart" };
129
+ if (!allowOutsideOwned) {
130
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 0 });
131
+ if (diff.error) return { error: "ownership_unverified", reason: "cannot prove the complete diff before landing", diff_error: diff.error };
132
+ const paths = [...readWorktreeChanges(task.worktree_path, worktreeRef(task)),
133
+ ...diff.files.flatMap((file) => [file.path, file.from].filter(Boolean).map((path) => join(task.worktree_path, path)))];
134
+ const { outside } = findOutsideOwnedChanges(task, [...new Set(paths)]);
135
+ if (outside.length) return { error: "outside_owned_paths", reason: "worker changes exceed declared ownedPaths; review them and obtain explicit authorization before allowing an exception", outside_paths: outside.map((entry) => relative(task.worktree_path, entry)) };
136
+ }
128
137
  let commits;
129
138
  try {
130
139
  commits = lines(git(task.worktree_path, ["rev-list", "--reverse", `${base}..HEAD`]));
@@ -302,6 +311,17 @@ export function rebaseWorktree(task, ontoCommit) {
302
311
  }
303
312
  }
304
313
 
314
+ let pending;
315
+ let alreadyLanded;
316
+ try {
317
+ const commits = lines(git(cwd, ["rev-list", "--reverse", `${base}..HEAD`]));
318
+ const newPatches = new Set(lines(git(cwd, ["cherry", ontoCommit, "HEAD", base]))
319
+ .filter((line) => line.startsWith("+ ")).map((line) => line.slice(2)));
320
+ pending = commits.filter((sha) => newPatches.has(sha));
321
+ alreadyLanded = commits.filter((sha) => !newPatches.has(sha));
322
+ } catch (error) {
323
+ return { error: "rebase_failed", reason: `could not prove which worker patches are already integrated: ${gitTail(error)}`, base_commit: base, head };
324
+ }
305
325
  const stashBefore = stashRef(cwd);
306
326
  let stashed = false;
307
327
  try {
@@ -338,14 +358,18 @@ export function rebaseWorktree(task, ontoCommit) {
338
358
  };
339
359
 
340
360
  try {
341
- git(cwd, ["rebase", "--onto", ontoCommit, base], { timeout: 10 * 60 * 1000 });
361
+ // Rebase --onto can replay a patch previously cherry-picked to main and
362
+ // conflict with main's later edits. Rebuild only the proven new patches.
363
+ git(cwd, ["reset", "-q", "--hard", ontoCommit]);
364
+ if (pending.length) git(cwd, ["cherry-pick", ...pending], { timeout: 10 * 60 * 1000 });
342
365
  } catch (error) {
343
366
  const files = conflictFiles(cwd);
344
367
  try {
345
- git(cwd, ["rebase", "--abort"]);
368
+ git(cwd, ["cherry-pick", "--abort"]);
346
369
  } catch {
347
370
  // nothing in progress to abort
348
371
  }
372
+ git(cwd, ["reset", "-q", "--hard", head]);
349
373
  const popError = restoreStash();
350
374
  return {
351
375
  error: files.length > 0 ? "rebase_conflict" : "rebase_failed",
@@ -390,5 +414,5 @@ export function rebaseWorktree(task, ontoCommit) {
390
414
  };
391
415
  }
392
416
  }
393
- return { ok: true, base_commit: ontoCommit, head: newHead, previous_head: head, replayed, stashed };
417
+ return { ok: true, base_commit: ontoCommit, head: newHead, previous_head: head, replayed, already_landed: alreadyLanded, stashed };
394
418
  }
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,12 @@ import {
25
30
  upsertSession,
26
31
  upsertTask
27
32
  } from "./task-store.js";
28
- import { readNativeGoal } from "./goal-store.js";
33
+ import { readNativeGoal, readNativeGoalState } from "./goal-store.js";
34
+ import { collectWorkerChanges } from "./worker-changes.js";
35
+ import { buildHostGoalSync } from "./prompt.js";
29
36
  import { baseBehind, readTaskChanges, readWorktreeDiff, worktreeRef } from "./worktree.js";
30
37
  import { summarizeVerification } from "./event-parser.js";
31
- import { acceptanceVerdict } from "./acceptance.js";
38
+ import { acceptanceVerdict, runAcceptance } from "./acceptance.js";
32
39
  import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
33
40
  import { approxTokenCount, truncateEventStrings, truncateMiddleChars, truncateReport } from "./truncate.js";
34
41
  import { checkForUpdate, updateNotice } from "./update-check.js";
@@ -110,7 +117,9 @@ const OVERVIEW_CAP_LEVELS = [
110
117
  { title: 40, goal: 60, action: 60, path: 60 },
111
118
  { title: 28, goal: 40, action: 40, path: 40 },
112
119
  { title: 18, goal: 24, action: 24, path: 24 },
113
- { 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 }
114
123
  ];
115
124
 
116
125
  // `current_action` is "Running <command>", and a command can be a heredoc that
@@ -156,12 +165,17 @@ function sleep(ms) {
156
165
  // the exit is recorded, or once nobody is left to record it.
157
166
  function isSettled(task) {
158
167
  if (!TERMINAL_STATUSES.has(task.status)) return false;
168
+ if (task.attention_reason === "start_failed") return true;
159
169
  if (task.status !== "completed" && task.status !== "failed") return true;
160
170
  // Acceptance is running in the supervisor process that owned the worker;
161
171
  // the codex pid is already dead, so that process is what to wait on.
162
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;
163
174
  if (task.exit_code !== null && task.exit_code !== undefined) return true;
164
- 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;
165
179
  }
166
180
 
167
181
  // Codex emits nothing while a command runs and nothing while the model
@@ -202,9 +216,9 @@ function acceptanceView(task, behind) {
202
216
  };
203
217
  if (!configured) return view;
204
218
  if (view.status === "failed") {
205
- const failing = view.checks.find((check) => check.exit_code !== 0) ?? null;
219
+ const failing = view.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out) ?? null;
206
220
  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.`
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.`
208
222
  : `acceptance could not run (${view.error ?? "unknown"}); fix that first`;
209
223
  } else if (view.status === "passed") {
210
224
  const verification = summarizeVerification(task);
@@ -244,6 +258,7 @@ function summarizeTask(task) {
244
258
  goal_objective: task.goal_objective,
245
259
  goal_token_budget: task.goal_token_budget,
246
260
  goal_status: task.goal_status,
261
+ attention_reason: task.attention_reason ?? null,
247
262
  changed_file_count: (task.changed_files ?? []).length,
248
263
  command_count: (task.commands ?? []).length,
249
264
  run_count: task.run_count ?? 0,
@@ -386,7 +401,7 @@ function buildOverview(tasks, extras = {}) {
386
401
  total: tasks.length,
387
402
  active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
388
403
  needs_attention: tasks
389
- .filter((task) => task.status === "running" && isGoalNeedingAttention(task.goal_status))
404
+ .filter((task) => isGoalNeedingAttention(task.goal_status) || task.attention_reason)
390
405
  .map((task) => task.id),
391
406
  // Terminal rows whose acceptance run failed. Kept apart from
392
407
  // needs_attention, which means "running and stuck"; this means
@@ -412,8 +427,8 @@ function acceptanceLine(task) {
412
427
  const results = task.acceptance_results;
413
428
  if (!results) return `acceptance: ${task.acceptance.length} configured, not run yet`;
414
429
  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);
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);
417
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}` : ""}`;
418
433
  }
419
434
 
@@ -471,6 +486,92 @@ function errorResult(error) {
471
486
  });
472
487
  }
473
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
+
474
575
  server.registerTool(
475
576
  "create_codex_worker",
476
577
  {
@@ -494,6 +595,14 @@ server.registerTool(
494
595
  // Empty only for a read-only worker (a verifier): it writes nothing,
495
596
  // so it owns nothing.
496
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(),
497
606
  goal: z.object({
498
607
  objective: z.string().min(1),
499
608
  tokenBudget: z.number().int().positive().optional()
@@ -505,7 +614,7 @@ server.registerTool(
505
614
  baseRef: z.string().min(1).optional(),
506
615
  // Shell commands that decide whether the work is done. The supervisor
507
616
  // 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(),
617
+ acceptance: acceptanceInput.optional(),
509
618
  acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
510
619
  }
511
620
  },
@@ -542,6 +651,14 @@ server.registerTool(
542
651
  model: z.string().optional(),
543
652
  reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
544
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(),
545
662
  goal: z
546
663
  .object({
547
664
  objective: z.string().min(1),
@@ -551,7 +668,7 @@ server.registerTool(
551
668
  baseRef: z.string().min(1).optional(),
552
669
  // Left out, the parent's acceptance commands are inherited; given, they
553
670
  // 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(),
671
+ acceptance: acceptanceInput.optional(),
555
672
  acceptanceTimeoutMs: z.number().int().min(1000).max(1800000).optional()
556
673
  }
557
674
  },
@@ -582,14 +699,15 @@ server.registerTool(
582
699
  task_id: z.string().min(1),
583
700
  prompt: z.string().min(1),
584
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(),
585
703
  // Replaces the stored acceptance commands for this and later runs; an
586
704
  // 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()
705
+ acceptance: acceptanceInput.optional()
588
706
  }
589
707
  },
590
- async ({ task_id, prompt, rebaseOnto, acceptance }) => {
708
+ async ({ task_id, prompt, rebaseOnto, acceptance, context }) => {
591
709
  try {
592
- const record = await resumeCodexWorker({ taskId: task_id, prompt, rebaseOnto: rebaseOnto ?? null, acceptance });
710
+ const record = await resumeCodexWorker({ taskId: task_id, prompt, rebaseOnto: rebaseOnto ?? null, acceptance, context });
593
711
  return textResult({ ...receipt(record), rebase: record.rebase ?? null, base_behind: baseBehind(record.project_root, record.base_commit) });
594
712
  } catch (error) {
595
713
  return errorResult(error);
@@ -655,7 +773,7 @@ server.registerTool(
655
773
  inputSchema: {
656
774
  task_ids: z.array(z.string().min(1)).min(1),
657
775
  mode: z.enum(["any", "all"]).default("all"),
658
- timeoutMinutes: z.number().int().min(1).max(360).default(2),
776
+ timeoutMinutes: z.number().int().min(1).max(360).default(1),
659
777
  timeoutMs: z.number().int().min(1000).max(21600000).optional(),
660
778
  pollMs: z.number().int().min(250).max(10000).default(1000),
661
779
  // Off by default. A wait is the call clients background and then replay
@@ -673,7 +791,7 @@ server.registerTool(
673
791
  // The smallest useful answer: one line per worker, for a caller that
674
792
  // only wants to know who is done. Everything else comes from
675
793
  // get_worker_result / get_worker_diff afterwards.
676
- compact: z.boolean().default(false)
794
+ compact: z.boolean().optional()
677
795
  }
678
796
  },
679
797
  async ({
@@ -686,18 +804,30 @@ server.registerTool(
686
804
  eventLimit,
687
805
  eventMaxChars,
688
806
  eventKinds,
689
- compact
690
- }) => {
807
+ compact: requestedCompact
808
+ }, extra) => {
809
+ const compact = requestedCompact ?? !includeEvents;
691
810
  const startedAt = Date.now();
692
811
  const effectiveTimeoutMs = timeoutMs ?? timeoutMinutes * 60 * 1000;
693
812
  let tasks = [];
813
+ const progressToken = extra?._meta?.progressToken;
814
+ let lastProgressAt = -Infinity;
694
815
 
695
816
  while (Date.now() - startedAt < effectiveTimeoutMs) {
817
+ if (extra?.signal.aborted) break;
696
818
  await reconcileDetachedActiveTasks();
697
819
  tasks = (await getTasks(task_ids)).filter(Boolean);
698
820
  const settledCount = tasks.filter(isSettled).length;
699
821
  const isDone = mode === "any" ? settledCount > 0 : settledCount === task_ids.length;
700
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
+ }
701
831
  await sleep(pollMs);
702
832
  }
703
833
 
@@ -775,6 +905,10 @@ server.registerTool(
775
905
  session_id,
776
906
  title: meta?.title ?? null,
777
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,
778
912
  count: tasks.length,
779
913
  active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
780
914
  works: tasks.map(workRow)
@@ -808,12 +942,18 @@ server.registerTool(
808
942
  inputSchema: {
809
943
  session_id: z.string().min(1),
810
944
  title: z.string().min(1).max(120).optional(),
811
- 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()
812
950
  }
813
951
  },
814
- async ({ session_id, title, note }) => {
815
- const row = await upsertSession({ id: session_id, title: title ?? null, note: note ?? null });
816
- 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); }
817
957
  }
818
958
  );
819
959
 
@@ -905,7 +1045,8 @@ server.registerTool(
905
1045
  token_budget: task.goal_token_budget,
906
1046
  goal_status: task.goal_status,
907
1047
  needs_attention: isGoalNeedingAttention(task.goal_status),
908
- native_goal: readNativeGoal(task.thread_id)
1048
+ native_goal: readNativeGoal(task.thread_id),
1049
+ native_goal_read: readNativeGoalState(task.thread_id)
909
1050
  });
910
1051
  }
911
1052
  );
@@ -976,6 +1117,11 @@ server.registerTool(
976
1117
  session_id: task.session_id ?? null,
977
1118
  worktree_path: task.worktree_path,
978
1119
  goal_status: task.goal_status,
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),
979
1125
  changed_file_count: changed.length,
980
1126
  changed_files: listFiles ? changed : undefined,
981
1127
  base_commit: task.base_commit ?? null,
@@ -1013,7 +1159,7 @@ server.registerTool(
1013
1159
  const task = await getTask(task_id);
1014
1160
  if (!task) return textResult({ error: "task_not_found", task_id });
1015
1161
  if (!task.worktree_path) {
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" });
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" });
1017
1163
  }
1018
1164
  const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars, paths: paths ?? [] });
1019
1165
  return textResult({
@@ -1022,7 +1168,8 @@ server.registerTool(
1022
1168
  status: task.status,
1023
1169
  worktree_path: task.worktree_path,
1024
1170
  branch: `codex/${task.id}`,
1025
- ...diff
1171
+ ...diff,
1172
+ external_outputs: externalOutputView(task, maxChars)
1026
1173
  });
1027
1174
  }
1028
1175
  );
@@ -1081,13 +1228,19 @@ server.registerTool(
1081
1228
  task_id: z.string().min(1),
1082
1229
  onto: z.string().min(1).optional(),
1083
1230
  commitMessage: z.string().min(1).optional(),
1084
- ignoreAcceptance: z.boolean().default(false)
1231
+ ignoreAcceptance: z.boolean().default(false),
1232
+ allowOutsideOwned: z.boolean().default(false)
1085
1233
  }
1086
1234
  },
1087
- async ({ task_id, onto, commitMessage, ignoreAcceptance }) => {
1235
+ async ({ task_id, onto, commitMessage, ignoreAcceptance, allowOutsideOwned }) => {
1088
1236
  const task = await getTask(task_id);
1089
1237
  if (!task) return textResult({ error: "task_not_found", task_id });
1090
- const outcome = landWorker(task, { onto, commitMessage: commitMessage ?? null, ignoreAcceptance });
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 });
1091
1244
  if (!outcome.error) {
1092
1245
  // Recorded so a later read knows the work is on the branch: the
1093
1246
  // board shows it, and base_behind after this is not drift.
@@ -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
+ }
package/src/prompt.js CHANGED
@@ -55,11 +55,11 @@ export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
55
55
  const commands = Array.isArray(acceptance) ? acceptance.filter(Boolean) : [];
56
56
  if (commands.length === 0) return "";
57
57
  if (resume) {
58
- return `Acceptance is unchanged; run it before you report: ${commands.join(" ; ")}`;
58
+ return `Acceptance is unchanged; run it before you report: ${commands.map((check) => typeof check === "string" ? check : JSON.stringify(check)).join(" ; ")}`;
59
59
  }
60
60
  return [
61
61
  "Acceptance: when you exit, the supervisor runs these commands in this directory and each must exit 0:",
62
- ...commands.map((command) => `- ${command}`),
62
+ ...commands.map((command) => `- ${typeof command === "string" ? command : JSON.stringify(command)}`),
63
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
64
  ].join("\n");
65
65
  }
@@ -68,16 +68,18 @@ export function buildReportPreamble({ resume = false, acceptance = null } = {})
68
68
  const acceptanceBlock = buildAcceptanceBlock(acceptance, { resume });
69
69
  const withAcceptance = (text) => (acceptanceBlock ? `${text}\n\n${acceptanceBlock}` : text);
70
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.");
71
+ return withAcceptance("Report as before using the required JSON schema: result string, verification string[] (every command you ran to check, with exit codes), not_done string[] (remaining work and risks). Under 2000 characters, no list of changed files, quote raw errors verbatim.");
72
72
  }
73
73
  return withAcceptance([
74
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
+ "Return JSON with exactly result:string, verification:string[], not_done:string[]; --output-schema enforces these fields. Cover the following content in those fields.",
76
+ "Keep each verification entry concise: command name, exit code and key evidence; avoid embedding long quoted shell source. Ensure arrays and the object are fully closed and all strings use valid JSON escaping.",
75
77
  "1. Result: what is done, in two or three sentences. Say plainly what is not done.",
76
78
  "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
79
  "3. Not done / risks: what you skipped, what you are unsure of, what the reviewer should look at first.",
78
80
  "Do not list the files you changed; the supervisor reads the diff.",
79
81
  "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."
82
+ "If the task specifies content or language, preserve it inside these JSON fields."
81
83
  ].join("\n"));
82
84
  }
83
85
 
@@ -90,3 +92,21 @@ export function withGoalPreamble(prompt, goalOptions) {
90
92
  export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null } = {}) {
91
93
  return `${withGoalPreamble(prompt, goalOptions)}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance })}`;
92
94
  }
95
+
96
+ // Claude's native /goal owns its Stop condition. MCP cannot silently replace
97
+ // it, so return a concrete current-policy condition for the host's goal UI.
98
+ // The condition references the current revision instead of copying long or
99
+ // soon-stale commands into the host's independently stored Stop hook.
100
+ export function buildHostGoalSync(session) {
101
+ const id = JSON.stringify(String(session.id));
102
+ const condition = [
103
+ `For supervisor session ${id}, read get_session_works and use its current objective, default_acceptance, approval_state and policy_revision (at least ${session.policy_revision ?? 0}).`,
104
+ "Use the latest explicit human instruction and approved failure baseline; superseded goals and checks must not be revived.",
105
+ "Stop when the current approved objective is verified and all required worker results are collected, checked and integrated as requested.",
106
+ "If approval_state is waiting_user, stop after clearly reporting the blocker, attempted checks, options and recommendation and asking for the required decision; do not auto-resume or repeat unchanged waiting reports.",
107
+ "Report the policy revision and actual evidence. A worker exit, acceptance green, push or publish alone is not proof that the whole objective is done."
108
+ ].join(" ");
109
+ return { revision: session.policy_revision ?? 0, approval_state: session.approval_state ?? "approved", condition,
110
+ claude_command: `/goal ${condition}`, requires_host_action: true,
111
+ instruction: "If a native Claude goal is active, replace its condition through /goal with this current-policy condition; ProposeGoal may propose it for host approval where available. MCP has not modified or disabled the host Stop hook." };
112
+ }