codex-supervisor-mcp 0.8.0 → 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/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
+ }
package/src/worktree.js CHANGED
@@ -11,9 +11,10 @@
11
11
  // so the committed part is read as `git diff --name-only <base> HEAD`, where
12
12
  // base is the commit the worktree was created from.
13
13
  import { execFileSync } from "node:child_process";
14
- import { existsSync, readFileSync } from "node:fs";
14
+ import { existsSync, readFileSync, lstatSync } from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import { truncateMiddleChars } from "./truncate.js";
17
+ import { createHash } from "node:crypto";
17
18
 
18
19
  const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
19
20
 
@@ -212,6 +213,29 @@ export function readTaskChanges(task) {
212
213
  return mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path, worktreeRef(task)));
213
214
  }
214
215
 
216
+ // Compare output at this run's start/end, rather than treating the previous
217
+ // run's committed or uncommitted work as fresh evidence. If the bounded read
218
+ // cannot prove the full state, leave the fingerprint unknown.
219
+ export function snapshotTaskOutput(task) {
220
+ const diff = readWorktreeDiff(task.worktree_path, worktreeRef(task), { maxChars: 2_000_000 });
221
+ if (diff.error || diff.truncated_files > 0 || diff.files.some((file) => file.patch == null)) return null;
222
+ try {
223
+ let remaining = 2_000_000;
224
+ const files = diff.files.map((file) => {
225
+ let content = "deleted";
226
+ if (file.status !== "deleted") {
227
+ const path = join(task.worktree_path, file.path);
228
+ const info = lstatSync(path);
229
+ if (!info.isFile() || info.size > remaining) throw new Error("unknown output");
230
+ remaining -= info.size;
231
+ content = createHash("sha256").update(readFileSync(path)).digest("hex");
232
+ }
233
+ return { path: file.path, from: file.from, status: file.status, patch: file.patch, content };
234
+ });
235
+ return createHash("sha256").update(JSON.stringify(files)).digest("hex");
236
+ } catch { return null; }
237
+ }
238
+
215
239
  // How far the project has moved since the worktree was cut. Compared with
216
240
  // the project directory's HEAD, which is the branch the main thread
217
241
  // integrates on. contains_base false means the base was rewritten (an