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/setup.js CHANGED
@@ -12,7 +12,7 @@
12
12
  import { execFile } from "node:child_process";
13
13
  import { existsSync, readdirSync } from "node:fs";
14
14
  import { homedir } from "node:os";
15
- import { dirname, join } from "node:path";
15
+ import { basename, dirname, isAbsolute, join } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { promisify } from "node:util";
18
18
  import {
@@ -42,7 +42,7 @@ const CLIENTS = [
42
42
  {
43
43
  ...SKILL_ROOTS.claude,
44
44
  binary: "claude",
45
- binEnv: null,
45
+ binEnv: "CLAUDE_BIN",
46
46
  npmEntry: { pkg: "@anthropic-ai/claude-code", bin: "bin/claude.exe" }
47
47
  },
48
48
  { ...SKILL_ROOTS.agents, binary: null },
@@ -151,7 +151,9 @@ function versionManagerBinDirs() {
151
151
  // instead (see bin-resolver.js).
152
152
  function locateClient(binary) {
153
153
  if (!binary) return null;
154
- const path = findBinaryPath(binary, {
154
+ const client = CLIENTS.find((entry) => entry.binary === binary);
155
+ const configured = client?.binEnv && process.env[client.binEnv]?.trim();
156
+ const path = findBinaryPath(configured || binary, {
155
157
  extraDirs: [...EXTRA_BIN_DIRS, ...versionManagerBinDirs()]
156
158
  });
157
159
  if (!path) return null;
@@ -167,25 +169,34 @@ function selectClients(options) {
167
169
  return CLIENTS.filter((client) => {
168
170
  if (options.targets && !options.targets.includes(client.id)) return false;
169
171
  if (client.binary && locateClient(client.binary)) return true;
170
- return existsSync(client.skillRoot);
172
+ return existsSync(client.skillRoot) || (client.binary && existsSync(dirname(client.skillRoot)));
171
173
  });
172
174
  }
173
175
 
174
- async function mcpAlreadyRegistered(target, options) {
175
- if (options.dryRun) return false;
176
+ async function registeredMcp(target, client) {
176
177
  try {
177
- await runClient(target, ["mcp", "get", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
178
- return true;
179
- } catch {
180
- return false;
178
+ const { stdout } = await runClient(target, ["mcp", "get", MCP_NAME, ...(client.id === "codex" ? ["--json"] : [])], { timeout: CLIENT_TIMEOUT_MS });
179
+ if (client.id === "codex") {
180
+ const value = JSON.parse(stdout);
181
+ const transport = value.transport ?? value;
182
+ return { command: transport.command, args: transport.args ?? [], env: transport.env ?? {}, cwd: transport.cwd, enabled: value.enabled !== false, userScope: true };
183
+ }
184
+ const command = stdout.match(/^\s*Command: (.+)$/m)?.[1]?.trim();
185
+ const args = stdout.match(/^\s*Args: (.*)$/m)?.[1]?.trim();
186
+ const environment = stdout.split(/\n[ \t]*Environment:[ \t]*\r?\n/)[1]?.split(/(?:^|\n)[ \t]*To remove/)[0]?.trim();
187
+ return { command, args: args ? [args] : [], env: environment ? { custom: true } : {}, enabled: !/Status:.*Disabled/i.test(stdout), userScope: /Scope: User config/.test(stdout) };
188
+ } catch (error) {
189
+ const message = `${error.stdout ?? ""}${error.stderr ?? ""}${error.message}`;
190
+ if (/not found|no mcp server|could not find|does not exist/i.test(message)) return null;
191
+ throw new Error(`cannot read ${client.label} MCP registration: ${error.message.split("\n")[0]}`);
181
192
  }
182
193
  }
183
194
 
184
195
  async function registerMcp(client, options, log, warn) {
185
196
  const target = locateClient(client.binary);
186
197
  if (!target) {
187
- log(`mcp ${client.label}: skipped (no ${client.binary} found)`);
188
- return "skipped";
198
+ warn(`mcp ${client.label}: no ${client.binary} CLI found; install it or set ${client.binEnv} to its executable, then run "codex-supervisor-setup"`);
199
+ return "failed";
189
200
  }
190
201
  if (target.shim) {
191
202
  warn(
@@ -193,9 +204,21 @@ async function registerMcp(client, options, log, warn) {
193
204
  );
194
205
  return "failed";
195
206
  }
196
- if (await mcpAlreadyRegistered(target, options)) {
197
- log(`mcp ${client.label}: already registered`);
198
- return "unchanged";
207
+ let previous;
208
+ try { previous = options.dryRun ? null : await registeredMcp(target, client); }
209
+ catch (error) { warn(`mcp ${client.label}: ${error.message}`); return "failed"; }
210
+ if (previous) {
211
+ const same = previous.userScope && previous.command === process.execPath && previous.args.length === 1 && previous.args[0] === serverEntry;
212
+ if (same && previous.enabled) { log(`mcp ${client.label}: already registered at this installation`); return "unchanged"; }
213
+ const managed = previous.userScope && previous.enabled && !previous.cwd && Object.keys(previous.env).length === 0
214
+ && ["node", "node.exe"].includes(basename(previous.command ?? "").toLowerCase())
215
+ && previous.args.length === 1 && isAbsolute(previous.args[0])
216
+ && /(?:^|[\\/])codex-supervisor-mcp[\\/]src[\\/]mcp-server\.js$/.test(previous.args[0])
217
+ && (/[\\/]node_modules[\\/]/.test(previous.args[0]) || !existsSync(previous.args[0]));
218
+ if (!managed) {
219
+ warn(`mcp ${client.label}: existing custom, disabled or project registration preserved; inspect "${client.binary} mcp get ${MCP_NAME}" before replacing it`);
220
+ return "failed";
221
+ }
199
222
  }
200
223
 
201
224
  const args =
@@ -204,14 +227,25 @@ async function registerMcp(client, options, log, warn) {
204
227
  : ["mcp", "add", MCP_NAME, "--", process.execPath, serverEntry];
205
228
 
206
229
  if (options.dryRun) {
230
+ if (previous) log(`mcp ${client.label}: would repair stale package registration`);
207
231
  log(`mcp ${client.label}: would run ${client.binary} ${args.join(" ")}`);
208
232
  return "would-register";
209
233
  }
210
234
  try {
235
+ if (previous) await runClient(target, client.id === "claude" ? ["mcp", "remove", "-s", "user", MCP_NAME] : ["mcp", "remove", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS });
211
236
  await runClient(target, args, { timeout: CLIENT_TIMEOUT_MS });
212
- log(`mcp ${client.label}: registered`);
237
+ const actual = await registeredMcp(target, client);
238
+ if (!actual || actual.command !== process.execPath || actual.args.length !== 1 || actual.args[0] !== serverEntry || !actual.enabled) throw new Error("registration command succeeded but read-back does not match this package");
239
+ log(`mcp ${client.label}: ${previous ? "repaired" : "registered"}`);
213
240
  return "registered";
214
241
  } catch (error) {
242
+ if (previous) {
243
+ try {
244
+ await runClient(target, client.id === "claude" ? ["mcp", "remove", "-s", "user", MCP_NAME] : ["mcp", "remove", MCP_NAME], { timeout: CLIENT_TIMEOUT_MS }).catch(() => {});
245
+ const restore = client.id === "claude" ? ["mcp", "add", "-s", "user", MCP_NAME, "--", previous.command, ...previous.args] : ["mcp", "add", MCP_NAME, "--", previous.command, ...previous.args];
246
+ await runClient(target, restore, { timeout: CLIENT_TIMEOUT_MS });
247
+ } catch (restoreError) { warn(`mcp ${client.label}: restoring the original registration failed (${restoreError.message.split("\n")[0]})`); }
248
+ }
215
249
  warn(
216
250
  `mcp ${client.label}: registration failed (${error.message.split("\n")[0]}) ` +
217
251
  `- run "codex-supervisor-setup" once ${client.label} is working`
@@ -240,27 +274,31 @@ async function main() {
240
274
  const log = options.quiet ? () => {} : (line) => console.log(line);
241
275
  const warn = (line) => console.error(line);
242
276
  const clients = selectClients(options);
277
+ const missingTargets = options.targets?.filter((id) => !clients.some((client) => client.id === id)) ?? [];
278
+ if (missingTargets.length) warn(`setup: requested client(s) not detected: ${missingTargets.join(", ")}; install the CLI or set CLAUDE_BIN / CODEX_BIN`);
243
279
 
244
280
  if (clients.length === 0) {
245
- log("setup: no Claude Code / Codex client detected; nothing to do");
246
- return 0;
281
+ warn("setup: no Claude Code / Codex client detected; MCP was not registered. Install a client, then run codex-supervisor-setup.");
282
+ return options.targets?.length && !options.auto ? 1 : 0;
247
283
  }
248
284
 
249
285
  log(`setup: ${options.dryRun ? "dry run against" : "configuring"} ${clients.map((client) => client.label).join(", ")}`);
250
286
 
287
+ let failures = missingTargets.length;
251
288
  if (options.skills) {
252
289
  for (const client of clients) {
253
- await installSkill(client, options, log);
290
+ try { await installSkill(client, options, log); }
291
+ catch (error) { failures += 1; warn(`skill ${client.label}: install failed (${error.message.split("\n")[0]}); MCP registration will still be attempted`); }
254
292
  }
255
293
  }
256
294
  if (options.mcp) {
257
295
  for (const client of clients.filter((client) => client.binary)) {
258
- await registerMcp(client, options, log, warn);
296
+ if (await registerMcp(client, options, log, warn) === "failed") failures += 1;
259
297
  }
260
298
  }
261
299
 
262
- log("setup: done");
263
- return 0;
300
+ log(failures ? `setup: ${failures} setup step(s) require repair` : "setup: done");
301
+ return failures && !options.auto ? 1 : 0;
264
302
  }
265
303
 
266
304
  try {
package/src/skill-sync.js CHANGED
@@ -18,9 +18,9 @@ export const skillSource = join(packageRoot, "skills", SKILL_NAME, "SKILL.md");
18
18
  export function skillRoots() {
19
19
  const home = homedir();
20
20
  return {
21
- claude: { id: "claude", label: "Claude Code", skillRoot: join(home, ".claude", "skills") },
21
+ claude: { id: "claude", label: "Claude Code", skillRoot: join(process.env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude"), "skills") },
22
22
  agents: { id: "agents", label: "~/.agents", skillRoot: join(home, ".agents", "skills") },
23
- codex: { id: "codex", label: "Codex", skillRoot: join(home, ".codex", "skills") }
23
+ codex: { id: "codex", label: "Codex", skillRoot: join(process.env.CODEX_HOME?.trim() || join(home, ".codex"), "skills") }
24
24
  };
25
25
  }
26
26
 
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 '[]'"],
@@ -26,6 +34,8 @@ const POST_V1_COLUMNS = [
26
34
  ["session_id", "TEXT"],
27
35
  ["base_commit", "TEXT"],
28
36
  ["acceptance", "TEXT"],
37
+ ["acceptance_local", "TEXT"],
38
+ ["session_policy_revision", "INTEGER"],
29
39
  ["acceptance_timeout_ms", "INTEGER"],
30
40
  ["acceptance_results", "TEXT"],
31
41
  ["landed_at", "TEXT"],
@@ -53,6 +63,11 @@ const TASKS_DDL = `
53
63
  started_at TEXT,
54
64
  completed_at TEXT,
55
65
  pid INTEGER,
66
+ run_host_pid INTEGER,
67
+ attention_reason TEXT,
68
+ run_evidence TEXT,
69
+ guard_policy TEXT,
70
+ input_context TEXT,
56
71
  exit_code INTEGER,
57
72
  signal TEXT,
58
73
  stderr_tail TEXT,
@@ -80,6 +95,8 @@ const TASKS_DDL = `
80
95
  worktree_path TEXT,
81
96
  base_commit TEXT,
82
97
  acceptance TEXT,
98
+ acceptance_local TEXT,
99
+ session_policy_revision INTEGER,
83
100
  acceptance_timeout_ms INTEGER,
84
101
  acceptance_results TEXT,
85
102
  landed_at TEXT,
@@ -91,12 +108,12 @@ const TASKS_DDL = `
91
108
  const TASK_COLUMNS = [
92
109
  "id", "title", "worker", "status", "phase", "cwd", "project_root", "sandbox", "model",
93
110
  "reasoning_effort", "skip_git_repo_check", "prompt", "changed_files", "commands",
94
- "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",
95
112
  "stderr_tail", "last_event_at", "last_event_type", "last_message", "current_action",
96
113
  "current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
97
114
  "depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
98
115
  "goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
99
- "notices", "worktree_path", "base_commit", "acceptance", "acceptance_timeout_ms", "acceptance_results", "landed_at", "landed_head", "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"
100
117
  ];
101
118
 
102
119
  function tableColumns(dbInstance, tableName) {
@@ -241,6 +258,14 @@ function initializeSchema(dbInstance) {
241
258
  dbInstance.exec(TASK_EVENTS_INDEX_DDL);
242
259
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
243
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)");
244
269
  dbInstance.exec(SIDE_DDL);
245
270
  // Rows written before 0.7.1 have no worker_run_count: the fork is then
246
271
 
@@ -296,6 +321,7 @@ function decodeJson(value, fallback) {
296
321
 
297
322
  function rowToTask(row) {
298
323
  if (!row) return null;
324
+ const nativeGoal = readNativeGoal(row.thread_id);
299
325
  return {
300
326
  ...row,
301
327
  skip_git_repo_check: Boolean(row.skip_git_repo_check),
@@ -304,14 +330,19 @@ function rowToTask(row) {
304
330
  owned_paths: decodeJson(row.owned_paths, []),
305
331
  depends_on: decodeJson(row.depends_on, []),
306
332
  acceptance: decodeJson(row.acceptance, null),
333
+ acceptance_local: decodeJson(row.acceptance_local, null),
307
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),
308
338
  pid: row.pid ?? null,
309
339
  exit_code: row.exit_code ?? null,
310
340
  phase: row.phase ?? null,
311
341
  goal_token_budget: row.goal_token_budget ?? null,
312
- goal_tokens_used: row.goal_tokens_used ?? null,
313
- goal_time_used_seconds: row.goal_time_used_seconds ?? null,
314
- 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
315
346
  };
316
347
  }
317
348
 
@@ -376,8 +407,18 @@ async function reconcileInterruptedAcceptance() {
376
407
 
377
408
  export async function reconcileDetachedActiveTasks() {
378
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
+ }
379
419
  const tasks = await readActiveTasks();
380
- 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)));
381
422
  for (const task of staleTasks) {
382
423
  const now = new Date().toISOString();
383
424
  const vanished = Boolean(task.pid);
@@ -401,6 +442,10 @@ export async function reconcileDetachedActiveTasks() {
401
442
 
402
443
  export async function writeTask(task) {
403
444
  await ensureFilesystem();
445
+ return writeTaskNow(task);
446
+ }
447
+
448
+ function writeTaskNow(task) {
404
449
  const placeholders = TASK_COLUMNS.map((name) => `@${name}`).join(", ");
405
450
  const updates = TASK_COLUMNS
406
451
  .filter((name) => name !== "id" && name !== "created_at")
@@ -423,7 +468,11 @@ export async function writeTask(task) {
423
468
  // JSON columns: node:sqlite refuses to bind an array or object, and a
424
469
  // refused bind drops the whole row update.
425
470
  params.acceptance = task.acceptance ? JSON.stringify(task.acceptance) : null;
471
+ params.acceptance_local = task.acceptance_local ? JSON.stringify(task.acceptance_local) : null;
426
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;
427
476
  params.run_count = task.run_count ?? 0;
428
477
  params.phase = task.phase ?? null;
429
478
 
@@ -431,6 +480,35 @@ export async function writeTask(task) {
431
480
  return task;
432
481
  }
433
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
+
434
512
  export async function upsertTask(task) {
435
513
  await writeTask(task);
436
514
  return task;
@@ -442,6 +520,49 @@ export async function getTask(taskId) {
442
520
  return rowToTask(row);
443
521
  }
444
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
+
445
566
  // Keyword search over the fields that describe what a work was for and how it
446
567
  // ended. Substring match, newest first. Deliberately not full-text and not
447
568
  // vector search: at this scale a LIKE scan over a few hundred rows is faster
@@ -483,7 +604,7 @@ export async function recordTerminalChangedFiles(taskId, changedFiles) {
483
604
  return result.changes > 0;
484
605
  }
485
606
 
486
- export async function upsertSession({ id, title = null, note = null }) {
607
+ export async function upsertSession({ id, title = null, note = null, objective, defaultAcceptance, approvalState, expectedRevision }) {
487
608
  if (!id) throw new Error("session id is required");
488
609
  await ensureFilesystem();
489
610
  const now = new Date().toISOString();
@@ -498,12 +619,39 @@ export async function upsertSession({ id, title = null, note = null }) {
498
619
  updated_at = excluded.updated_at
499
620
  `)
500
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
+ }
501
648
  return getSession(id);
502
649
  }
503
650
 
504
651
  export async function getSession(sessionId) {
505
652
  await ensureFilesystem();
506
- 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;
507
655
  }
508
656
 
509
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/web-app.js CHANGED
@@ -418,7 +418,8 @@ export function startWebServer({ storeOrigin = "default" } = {}) {
418
418
  });
419
419
 
420
420
  server.listen(port, host, () => {
421
- 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`);
422
423
  });
423
424
  return server;
424
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
+ }