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/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,69 @@ 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.map((check) => typeof check === "string" ? check : JSON.stringify(check)).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) => `- ${typeof command === "string" ? command : JSON.stringify(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 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
+ }
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
+ "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.",
77
+ "1. Result: what is done, in two or three sentences. Say plainly what is not done.",
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.",
79
+ "3. Not done / risks: what you skipped, what you are unsure of, what the reviewer should look at first.",
80
+ "Do not list the files you changed; the supervisor reads the diff.",
81
+ "Never call a failure an environment problem without quoting the raw error verbatim.",
82
+ "If the task specifies content or language, preserve it inside these JSON fields."
83
+ ].join("\n"));
84
+ }
85
+
36
86
  export function withGoalPreamble(prompt, goalOptions) {
37
87
  const preamble = buildGoalPreamble(goalOptions);
38
88
  return preamble ? `${preamble}\n\n${prompt}` : prompt;
39
89
  }
90
+
91
+ // The whole frame: goal in front, task text, report format at the end.
92
+ export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null } = {}) {
93
+ return `${withGoalPreamble(prompt, goalOptions)}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance })}`;
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
+ }
package/src/status.js CHANGED
@@ -33,5 +33,5 @@ export function mapGoalStatus(nativeStatus) {
33
33
  // A goal that is not finished but is not progressing on its own.
34
34
  export function isGoalNeedingAttention(nativeStatus) {
35
35
  const key = String(nativeStatus ?? "").replace(/_/g, "").toLowerCase();
36
- return key === "blocked" || key === "paused";
36
+ return ["blocked", "paused", "usagelimited", "budgetlimited"].includes(key);
37
37
  }
package/src/task-store.js CHANGED
@@ -4,12 +4,20 @@ import { DatabaseSync } from "node:sqlite";
4
4
  import { dataDir, dbPath, runsDir } from "./paths.js";
5
5
  import { extractAgentMessage } from "./event-parser.js";
6
6
  import { ACTIVE_STATUSES, PHASES, TERMINAL_STATUSES } from "./status.js";
7
+ import { readNativeGoal } from "./goal-store.js";
8
+ import { normalizeAcceptance } from "./acceptance.js";
9
+ import { randomUUID } from "node:crypto";
7
10
 
8
11
  let db;
9
12
 
10
13
  // Columns added after v1. Kept in one place so the legacy rebuild and the
11
14
  // fresh CREATE TABLE cannot drift apart.
12
15
  const POST_V1_COLUMNS = [
16
+ ["run_host_pid", "INTEGER"],
17
+ ["attention_reason", "TEXT"],
18
+ ["run_evidence", "TEXT"],
19
+ ["guard_policy", "TEXT"],
20
+ ["input_context", "TEXT"],
13
21
  ["resumed_from", "TEXT"],
14
22
  ["thread_id", "TEXT"],
15
23
  ["owned_paths", "TEXT NOT NULL DEFAULT '[]'"],
@@ -24,7 +32,14 @@ const POST_V1_COLUMNS = [
24
32
  ["cancel_requested_at", "TEXT"],
25
33
  ["notices", "TEXT"],
26
34
  ["session_id", "TEXT"],
27
- ["base_commit", "TEXT"]
35
+ ["base_commit", "TEXT"],
36
+ ["acceptance", "TEXT"],
37
+ ["acceptance_local", "TEXT"],
38
+ ["session_policy_revision", "INTEGER"],
39
+ ["acceptance_timeout_ms", "INTEGER"],
40
+ ["acceptance_results", "TEXT"],
41
+ ["landed_at", "TEXT"],
42
+ ["landed_head", "TEXT"]
28
43
  ];
29
44
 
30
45
  const TASKS_DDL = `
@@ -48,6 +63,11 @@ const TASKS_DDL = `
48
63
  started_at TEXT,
49
64
  completed_at TEXT,
50
65
  pid INTEGER,
66
+ run_host_pid INTEGER,
67
+ attention_reason TEXT,
68
+ run_evidence TEXT,
69
+ guard_policy TEXT,
70
+ input_context TEXT,
51
71
  exit_code INTEGER,
52
72
  signal TEXT,
53
73
  stderr_tail TEXT,
@@ -74,6 +94,13 @@ const TASKS_DDL = `
74
94
  notices TEXT,
75
95
  worktree_path TEXT,
76
96
  base_commit TEXT,
97
+ acceptance TEXT,
98
+ acceptance_local TEXT,
99
+ session_policy_revision INTEGER,
100
+ acceptance_timeout_ms INTEGER,
101
+ acceptance_results TEXT,
102
+ landed_at TEXT,
103
+ landed_head TEXT,
77
104
  run_log TEXT NOT NULL
78
105
  );
79
106
  `;
@@ -81,12 +108,12 @@ const TASKS_DDL = `
81
108
  const TASK_COLUMNS = [
82
109
  "id", "title", "worker", "status", "phase", "cwd", "project_root", "sandbox", "model",
83
110
  "reasoning_effort", "skip_git_repo_check", "prompt", "changed_files", "commands",
84
- "created_at", "updated_at", "started_at", "completed_at", "pid", "exit_code", "signal",
111
+ "created_at", "updated_at", "started_at", "completed_at", "pid", "run_host_pid", "attention_reason", "run_evidence", "guard_policy", "input_context", "exit_code", "signal",
85
112
  "stderr_tail", "last_event_at", "last_event_type", "last_message", "current_action",
86
113
  "current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
87
114
  "depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
88
115
  "goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
89
- "notices", "worktree_path", "base_commit", "run_log"
116
+ "notices", "worktree_path", "base_commit", "acceptance", "acceptance_local", "session_policy_revision", "acceptance_timeout_ms", "acceptance_results", "landed_at", "landed_head", "run_log"
90
117
  ];
91
118
 
92
119
  function tableColumns(dbInstance, tableName) {
@@ -231,6 +258,14 @@ function initializeSchema(dbInstance) {
231
258
  dbInstance.exec(TASK_EVENTS_INDEX_DDL);
232
259
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
233
260
  dbInstance.exec(SESSIONS_DDL);
261
+ for (const [name, definition] of [
262
+ ["objective", "TEXT"], ["default_acceptance", "TEXT"],
263
+ ["approval_state", "TEXT NOT NULL DEFAULT 'approved'"], ["policy_revision", "INTEGER NOT NULL DEFAULT 0"]
264
+ ]) {
265
+ if (!tableColumns(dbInstance, "sessions").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE sessions ADD COLUMN ${name} ${definition}`);
266
+ }
267
+ dbInstance.exec("CREATE TABLE IF NOT EXISTS observer_cursors (id TEXT PRIMARY KEY, cursor TEXT NOT NULL, updated_at TEXT NOT NULL)");
268
+ dbInstance.exec("CREATE TABLE IF NOT EXISTS run_claims (task_id TEXT PRIMARY KEY, token TEXT NOT NULL, owner_pid INTEGER NOT NULL)");
234
269
  dbInstance.exec(SIDE_DDL);
235
270
  // Rows written before 0.7.1 have no worker_run_count: the fork is then
236
271
 
@@ -286,6 +321,7 @@ function decodeJson(value, fallback) {
286
321
 
287
322
  function rowToTask(row) {
288
323
  if (!row) return null;
324
+ const nativeGoal = readNativeGoal(row.thread_id);
289
325
  return {
290
326
  ...row,
291
327
  skip_git_repo_check: Boolean(row.skip_git_repo_check),
@@ -293,13 +329,20 @@ function rowToTask(row) {
293
329
  commands: decodeJson(row.commands, []),
294
330
  owned_paths: decodeJson(row.owned_paths, []),
295
331
  depends_on: decodeJson(row.depends_on, []),
332
+ acceptance: decodeJson(row.acceptance, null),
333
+ acceptance_local: decodeJson(row.acceptance_local, null),
334
+ acceptance_results: decodeJson(row.acceptance_results, null),
335
+ run_evidence: decodeJson(row.run_evidence, null),
336
+ guard_policy: decodeJson(row.guard_policy, null),
337
+ input_context: decodeJson(row.input_context, null),
296
338
  pid: row.pid ?? null,
297
339
  exit_code: row.exit_code ?? null,
298
340
  phase: row.phase ?? null,
299
341
  goal_token_budget: row.goal_token_budget ?? null,
300
- goal_tokens_used: row.goal_tokens_used ?? null,
301
- goal_time_used_seconds: row.goal_time_used_seconds ?? null,
302
- goal_status: row.goal_status ?? null
342
+ goal_status: nativeGoal?.storage_status ?? row.goal_status ?? null,
343
+ goal_tokens_used: nativeGoal?.tokens_used ?? row.goal_tokens_used ?? null,
344
+ goal_time_used_seconds: nativeGoal?.time_used_seconds ?? row.goal_time_used_seconds ?? null,
345
+ goal_updated_at: nativeGoal?.updated_at ?? row.goal_updated_at ?? null
303
346
  };
304
347
  }
305
348
 
@@ -341,9 +384,41 @@ function neverStarted(task, now = Date.now()) {
341
384
  return now - created > NEVER_STARTED_GRACE_MS;
342
385
  }
343
386
 
387
+ // A terminal row whose acceptance run was cut short: the MCP process that
388
+ // was running the checks is gone. Left alone it would read as "running"
389
+ // forever and land would treat it as never run.
390
+ async function reconcileInterruptedAcceptance() {
391
+ const tasks = await readTasks();
392
+ const interrupted = tasks.filter((task) =>
393
+ TERMINAL_STATUSES.has(task.status)
394
+ && task.acceptance_results?.status === "running"
395
+ && !isPidAlive(task.acceptance_results.supervisor_pid));
396
+ for (const task of interrupted) {
397
+ const now = new Date().toISOString();
398
+ await writeTask({
399
+ ...task,
400
+ acceptance_results: { ...task.acceptance_results, status: "interrupted", passed: null, finished_at: now },
401
+ current_action: "Acceptance interrupted: the supervisor process exited while running the checks",
402
+ updated_at: now
403
+ });
404
+ }
405
+ return interrupted;
406
+ }
407
+
344
408
  export async function reconcileDetachedActiveTasks() {
409
+ await reconcileInterruptedAcceptance();
410
+ const incomplete = (await readTasks()).filter((task) =>
411
+ ["completed", "failed"].includes(task.status) && task.exit_code == null && task.started_at
412
+ && !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid) && !task.acceptance_results
413
+ && Date.now() - Date.parse(task.updated_at) > 5000);
414
+ for (const task of incomplete) {
415
+ await writeTask({ ...task, status: "lost", phase: null,
416
+ error: "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
417
+ updated_at: new Date().toISOString() });
418
+ }
345
419
  const tasks = await readActiveTasks();
346
- const staleTasks = tasks.filter((task) => (task.pid && !isPidAlive(task.pid)) || neverStarted(task));
420
+ const staleTasks = tasks.filter((task) => !isPidAlive(task.run_host_pid)
421
+ && ((task.pid && !isPidAlive(task.pid)) || neverStarted(task)));
347
422
  for (const task of staleTasks) {
348
423
  const now = new Date().toISOString();
349
424
  const vanished = Boolean(task.pid);
@@ -367,6 +442,10 @@ export async function reconcileDetachedActiveTasks() {
367
442
 
368
443
  export async function writeTask(task) {
369
444
  await ensureFilesystem();
445
+ return writeTaskNow(task);
446
+ }
447
+
448
+ function writeTaskNow(task) {
370
449
  const placeholders = TASK_COLUMNS.map((name) => `@${name}`).join(", ");
371
450
  const updates = TASK_COLUMNS
372
451
  .filter((name) => name !== "id" && name !== "created_at")
@@ -386,6 +465,14 @@ export async function writeTask(task) {
386
465
  params.commands = encodeJson(task.commands);
387
466
  params.owned_paths = encodeJson(task.owned_paths);
388
467
  params.depends_on = encodeJson(task.depends_on);
468
+ // JSON columns: node:sqlite refuses to bind an array or object, and a
469
+ // refused bind drops the whole row update.
470
+ params.acceptance = task.acceptance ? JSON.stringify(task.acceptance) : null;
471
+ params.acceptance_local = task.acceptance_local ? JSON.stringify(task.acceptance_local) : null;
472
+ params.acceptance_results = task.acceptance_results ? JSON.stringify(task.acceptance_results) : null;
473
+ params.run_evidence = task.run_evidence ? JSON.stringify(task.run_evidence) : null;
474
+ params.guard_policy = task.guard_policy ? JSON.stringify(task.guard_policy) : null;
475
+ params.input_context = task.input_context ? JSON.stringify(task.input_context) : null;
389
476
  params.run_count = task.run_count ?? 0;
390
477
  params.phase = task.phase ?? null;
391
478
 
@@ -393,6 +480,35 @@ export async function writeTask(task) {
393
480
  return task;
394
481
  }
395
482
 
483
+ function checkOwnership(taskId, incoming) {
484
+ const normalized = (value) => process.platform === "win32" ? value.replace(/\\/g, "/").toLowerCase() : value;
485
+ const overlaps = (left, right) => {
486
+ const a=normalized(left).replace(/\/$/,""),b=normalized(right).replace(/\/$/,"");
487
+ return a===b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
488
+ };
489
+ const conflicts = [];
490
+ const pending = openDb().prepare("SELECT t.id,t.title,t.status,t.owned_paths,t.acceptance_results,t.started_at,t.exit_code,c.owner_pid FROM tasks t LEFT JOIN run_claims c ON c.task_id=t.id WHERE t.id<>? AND (c.owner_pid IS NOT NULL OR status IN ('queued','running') OR json_extract(acceptance_results,'$.status')='running' OR (status IN ('completed','failed') AND started_at IS NOT NULL AND exit_code IS NULL AND acceptance_results IS NULL))").all(taskId);
491
+ for (const row of pending) {
492
+ const settling = decodeJson(row.acceptance_results,null)?.status === "running"
493
+ || (["completed","failed"].includes(row.status) && row.started_at && row.exit_code == null && !row.acceptance_results);
494
+ if (row.owner_pid && !ACTIVE_STATUSES.has(row.status) && !settling && !isPidAlive(row.owner_pid)) continue;
495
+ const paths=decodeJson(row.owned_paths,[]);
496
+ const matching=incoming.flatMap(path=>paths.filter(other=>overlaps(path,other)).map(other=>({incoming:path,existing:other})));
497
+ if(matching.length)conflicts.push({task_id:row.id,title:row.title,status:row.status,overlapping_paths:matching});
498
+ }
499
+ if(conflicts.length){const error=new Error("ownedPaths overlap with an active worker claimed by another dispatcher");error.code="ownership_conflict";error.conflicts=conflicts;throw error;}
500
+ }
501
+
502
+ export async function reserveTaskOwnership(task) {
503
+ await ensureFilesystem();
504
+ const connection=openDb();
505
+ return runWithRetry(connection,()=>{
506
+ connection.exec("BEGIN IMMEDIATE");
507
+ try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task);connection.exec("COMMIT");return task; }
508
+ catch(error){connection.exec("ROLLBACK");throw error;}
509
+ });
510
+ }
511
+
396
512
  export async function upsertTask(task) {
397
513
  await writeTask(task);
398
514
  return task;
@@ -404,6 +520,49 @@ export async function getTask(taskId) {
404
520
  return rowToTask(row);
405
521
  }
406
522
 
523
+ // Compare and claim under one write lock before rebase or spawning. A claim
524
+ // whose dispatcher died can be replaced; a different run cannot be resumed
525
+ // using an earlier snapshot, even when both dispatchers read it together.
526
+ export async function claimTaskRun(taskId, expectedRun) {
527
+ await ensureFilesystem();
528
+ const connection = openDb();
529
+ return runWithRetry(connection, () => {
530
+ connection.exec("BEGIN IMMEDIATE");
531
+ try {
532
+ const row = connection.prepare("SELECT * FROM tasks WHERE id=?").get(taskId);
533
+ const claim = connection.prepare("SELECT * FROM run_claims WHERE task_id=?").get(taskId);
534
+ const busy = !row || row.run_count !== expectedRun || ACTIVE_STATUSES.has(row.status)
535
+ || (["completed", "failed"].includes(row.status) && row.exit_code == null)
536
+ || decodeJson(row.acceptance_results, null)?.status === "running"
537
+ || (claim && isPidAlive(claim.owner_pid));
538
+ let token = null;
539
+ if (!busy) {
540
+ checkOwnership(taskId,decodeJson(row.owned_paths,[]));
541
+ token = randomUUID();
542
+ connection.prepare("INSERT INTO run_claims VALUES (?,?,?) ON CONFLICT(task_id) DO UPDATE SET token=excluded.token,owner_pid=excluded.owner_pid")
543
+ .run(taskId, token, process.pid);
544
+ }
545
+ connection.exec("COMMIT");
546
+ return token;
547
+ } catch (error) { connection.exec("ROLLBACK"); throw error; }
548
+ });
549
+ }
550
+
551
+ export async function releaseTaskRun(taskId, token) {
552
+ openDb().prepare("DELETE FROM run_claims WHERE task_id=? AND token=?").run(taskId, token);
553
+ }
554
+
555
+ export async function readObserverCursor(observerId) {
556
+ await ensureFilesystem();
557
+ return decodeJson(openDb().prepare("SELECT cursor FROM observer_cursors WHERE id=?").get(observerId)?.cursor, {});
558
+ }
559
+
560
+ export async function writeObserverCursor(observerId, cursor) {
561
+ await ensureFilesystem();
562
+ runWithRetry(openDb(), () => openDb().prepare("INSERT INTO observer_cursors VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET cursor=excluded.cursor,updated_at=excluded.updated_at")
563
+ .run(observerId, JSON.stringify(cursor), new Date().toISOString()));
564
+ }
565
+
407
566
  // Keyword search over the fields that describe what a work was for and how it
408
567
  // ended. Substring match, newest first. Deliberately not full-text and not
409
568
  // vector search: at this scale a LIKE scan over a few hundred rows is faster
@@ -445,7 +604,7 @@ export async function recordTerminalChangedFiles(taskId, changedFiles) {
445
604
  return result.changes > 0;
446
605
  }
447
606
 
448
- export async function upsertSession({ id, title = null, note = null }) {
607
+ export async function upsertSession({ id, title = null, note = null, objective, defaultAcceptance, approvalState, expectedRevision }) {
449
608
  if (!id) throw new Error("session id is required");
450
609
  await ensureFilesystem();
451
610
  const now = new Date().toISOString();
@@ -460,12 +619,39 @@ export async function upsertSession({ id, title = null, note = null }) {
460
619
  updated_at = excluded.updated_at
461
620
  `)
462
621
  .run({ id, title: title ?? null, note: note ?? null, now });
622
+ if (objective !== undefined || defaultAcceptance !== undefined || approvalState !== undefined || expectedRevision !== undefined) {
623
+ const acceptance = defaultAcceptance === undefined ? undefined : normalizeAcceptance(defaultAcceptance) ?? [];
624
+ if (objective !== undefined && (typeof objective !== "string" || !objective.trim())) throw new Error("session objective must be nonempty");
625
+ if (approvalState !== undefined && !["approved", "waiting_user"].includes(approvalState)) throw new Error("invalid session approval state");
626
+ runWithRetry(openDb(), () => {
627
+ const store = openDb();
628
+ store.exec("BEGIN IMMEDIATE");
629
+ try {
630
+ const before = store.prepare("SELECT * FROM sessions WHERE id=?").get(id);
631
+ if (expectedRevision !== undefined && expectedRevision !== before.policy_revision) {
632
+ const error = new Error(`session policy changed; current revision is ${before.policy_revision}`);
633
+ error.code = "session_policy_conflict";
634
+ throw error;
635
+ }
636
+ const policy = {
637
+ objective: objective ?? before.objective,
638
+ acceptance: acceptance === undefined ? before.default_acceptance : JSON.stringify(acceptance),
639
+ approval: approvalState ?? before.approval_state
640
+ };
641
+ const changed = policy.objective !== before.objective || policy.acceptance !== before.default_acceptance || policy.approval !== before.approval_state;
642
+ store.prepare("UPDATE sessions SET objective=?,default_acceptance=?,approval_state=?,policy_revision=?,updated_at=? WHERE id=?")
643
+ .run(policy.objective, policy.acceptance, policy.approval, before.policy_revision + (changed ? 1 : 0), now, id);
644
+ store.exec("COMMIT");
645
+ } catch (error) { store.exec("ROLLBACK"); throw error; }
646
+ });
647
+ }
463
648
  return getSession(id);
464
649
  }
465
650
 
466
651
  export async function getSession(sessionId) {
467
652
  await ensureFilesystem();
468
- return openDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId) ?? null;
653
+ const row = openDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
654
+ return row ? { ...row, default_acceptance: decodeJson(row.default_acceptance, []) } : null;
469
655
  }
470
656
 
471
657
  export async function readSessions() {
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync, existsSync } from "node:fs";
3
+ import { resolve, dirname, relative, isAbsolute } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ function canonical(path) {
7
+ const suffix = [];
8
+ let parent = resolve(path);
9
+ while (!existsSync(parent)) {
10
+ const next = dirname(parent);
11
+ if (next === parent) throw new Error("path has no existing ancestor");
12
+ suffix.unshift(relative(next, parent)); parent = next;
13
+ }
14
+ return resolve(realpathSync(parent), ...suffix);
15
+ }
16
+
17
+ function inside(path, owner) {
18
+ const part = relative(owner, path);
19
+ return !isAbsolute(part) && part !== ".." && !part.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`);
20
+ }
21
+
22
+ export function evaluateToolUse(event, policy) {
23
+ const deny = (reason) => ({ allow: false, reason });
24
+ if (!policy || !Array.isArray(policy.ownedPaths) || !policy.cwd) return deny("missing supervisor guard policy");
25
+ const tool = event.tool_name;
26
+ const input = event.tool_input;
27
+ const command = typeof input === "string" ? input : input?.command;
28
+ if (tool === "Bash") {
29
+ if (typeof command !== "string") return deny("invalid shell input");
30
+ const normalized = command.replace(/\\\r?\n/g, "").replace(/\s+/g, " ").trim();
31
+ for (const forbidden of policy.forbid ?? []) {
32
+ if (normalized.toLowerCase().includes(forbidden.toLowerCase())) return deny(`forbidden command: ${forbidden}`);
33
+ }
34
+ // Validation lines are a dispatcher's explicit executable contract, just
35
+ // like acceptance. They can have side effects and are never inferred from
36
+ // the model's own report. Arbitrary shell programs are not path sandboxes.
37
+ if ((policy.allowedCommands ?? []).some((entry) => entry.trim() === command.trim())) return { allow: true, reason: "declared validation command" };
38
+ if (!/[;&|<>`$()\n\r]/.test(command) && !/--(?:pre|ext-diff|output|exec)(?:=|\s|$)/.test(command)
39
+ && /^(?:pwd|ls|cat|head|tail|rg|wc|git (?:status|diff|show|log|rev-parse))(?:\s|$)/.test(command.trim())) return { allow: true, reason: "read command" };
40
+ return deny("undeclared shell command; use apply_patch for edits or a declared validation command");
41
+ }
42
+ if (tool === "apply_patch") {
43
+ if (typeof command !== "string" || !command.startsWith("*** Begin Patch")) return deny("invalid patch input");
44
+ const paths = [...command.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)].map((match) => match[1]);
45
+ if (!paths.length) return deny("patch has no recognized file paths");
46
+ try {
47
+ const owners = policy.ownedPaths.map(canonical);
48
+ for (const path of paths) {
49
+ const target = canonical(resolve(event.cwd ?? policy.cwd, path));
50
+ if (!owners.some((owner) => inside(target, owner))) return deny(`outside ownedPaths: ${path}`);
51
+ }
52
+ } catch (error) { return deny(`cannot prove patch ownership: ${error.message}`); }
53
+ return { allow: true, reason: "owned patch" };
54
+ }
55
+ return { allow: true, reason: "tool is outside the Bash/apply_patch policy" };
56
+ }
57
+
58
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
59
+ let input = "";
60
+ for await (const chunk of process.stdin) input += chunk;
61
+ let decision;
62
+ try { decision = evaluateToolUse(JSON.parse(input), JSON.parse(process.env.CODEX_SUPERVISOR_GUARD_POLICY ?? "null")); }
63
+ catch (error) { decision = { allow: false, reason: `invalid supervisor guard input: ${error.message}` }; }
64
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse",
65
+ permissionDecision: decision.allow ? "allow" : "deny", permissionDecisionReason: decision.reason } }) + "\n");
66
+ }
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,
@@ -416,7 +418,8 @@ export function startWebServer({ storeOrigin = "default" } = {}) {
416
418
  });
417
419
 
418
420
  server.listen(port, host, () => {
419
- process.stdout.write(`codex-supervisor web view on http://${host}:${port}\n store: ${supervisorRoot} (${storeOrigin})\n`);
421
+ const boundPort = server.address().port;
422
+ process.stdout.write(`codex-supervisor web view on http://${host}:${boundPort}\n store: ${supervisorRoot} (${storeOrigin})\n`);
420
423
  });
421
424
  return server;
422
425
  }
@@ -0,0 +1,38 @@
1
+ import { TERMINAL_STATUSES, isGoalNeedingAttention } from "./status.js";
2
+
3
+ // Cursors belong to observers, not workers. A resumed run gets a new receipt;
4
+ // old acceptance cannot produce a current-run completion or failure notice.
5
+ export function collectWorkerChanges(tasks, cursor = {}) {
6
+ const next = {};
7
+ const transitions = [];
8
+ const attention = [];
9
+ for (const task of tasks) {
10
+ const acceptance = task.acceptance_results?.run === task.run_count ? task.acceptance_results : null;
11
+ let reason = null;
12
+ if (isGoalNeedingAttention(task.goal_status)) reason = `goal_${task.goal_status}`;
13
+ else if (task.attention_reason) reason = task.attention_reason;
14
+ else if (acceptance?.passed === false) reason = "acceptance_failed";
15
+ else if (["interrupted", "cancelled"].includes(acceptance?.status)) reason = `acceptance_${acceptance.status}`;
16
+ else if (TERMINAL_STATUSES.has(task.status) && acceptance?.status !== "running" &&
17
+ (!["completed", "failed"].includes(task.status) || task.exit_code != null)) reason = task.status;
18
+ if (!reason) {
19
+ if (cursor[task.id]) next[task.id] = cursor[task.id];
20
+ continue;
21
+ }
22
+ const fingerprint = JSON.stringify([task.run_count, reason, task.goal_status, acceptance?.status, task.landed_head]);
23
+ next[task.id] = fingerprint;
24
+ if (cursor[task.id] === fingerprint) continue;
25
+ const needsAttention = !["completed", "cancelled"].includes(reason);
26
+ const receipt = {
27
+ id: task.id, title: task.title ?? task.id, run: task.run_count, status: task.status,
28
+ reason, next_step: {
29
+ tool: needsAttention ? "get_worker_result" : "get_worker_diff",
30
+ arguments: { task_id: task.id },
31
+ instruction: needsAttention ? "Read the failure or goal evidence before deciding whether to resume; user approval waits must not auto-resume." : "Read the result and diff, then decide whether to land. Completion is not proof of correctness."
32
+ }
33
+ };
34
+ transitions.push(receipt);
35
+ if (needsAttention) attention.push(receipt);
36
+ }
37
+ return { quiet: transitions.length === 0, transitions, attention, cursor: next };
38
+ }
@@ -0,0 +1,15 @@
1
+ import { fileURLToPath } from "node:url";
2
+ export const workerReportSchemaPath = fileURLToPath(new URL("./worker-report.schema.json", import.meta.url));
3
+
4
+ export function parseWorkerReport(text) {
5
+ try {
6
+ const value = JSON.parse(text);
7
+ if (!value || typeof value !== "object" || Array.isArray(value)
8
+ || Object.keys(value).sort().join(",") !== "not_done,result,verification"
9
+ || typeof value.result !== "string" || !Array.isArray(value.verification) || !Array.isArray(value.not_done)
10
+ || [...value.verification, ...value.not_done].some((entry) => typeof entry !== "string")) {
11
+ throw new Error("report must contain result:string, verification:string[], not_done:string[] only");
12
+ }
13
+ return { format: "json_schema", valid: true, report: value };
14
+ } catch (error) { return { format: "json_schema", valid: false, error: error.message }; }
15
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "type": "object",
3
+ "additionalProperties": false,
4
+ "required": ["result", "verification", "not_done"],
5
+ "properties": {
6
+ "result": {"type": "string"},
7
+ "verification": {"type": "array", "items": {"type": "string"}},
8
+ "not_done": {"type": "array", "items": {"type": "string"}}
9
+ }
10
+ }