codex-supervisor-mcp 0.11.0 → 0.12.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
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
2
- import { join, relative, resolve } from "node:path";
2
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { DatabaseSync } from "node:sqlite";
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { artifactsDir, dataDir, dbPath, runsDir } from "./paths.js";
@@ -9,6 +9,8 @@ import { readNativeGoal } from "./goal-store.js";
9
9
  import { normalizeAcceptance } from "./acceptance.js";
10
10
  import { createHash, randomUUID } from "node:crypto";
11
11
  import { captureWorkspaceManifest } from "./workspace-kind.js";
12
+ import { buildHandoff } from "./handoff.js";
13
+ import { readPreflightResult } from "./worker-preflight.js";
12
14
 
13
15
  let db;
14
16
 
@@ -265,6 +267,7 @@ const CONTROL_DDL = `
265
267
  verified_by TEXT
266
268
  );
267
269
  CREATE INDEX IF NOT EXISTS idx_facts_scope ON facts(scope_type, scope_id, state);
270
+ CREATE INDEX IF NOT EXISTS idx_facts_supersedes ON facts(supersedes_id, state);
268
271
  CREATE TABLE IF NOT EXISTS artifacts (
269
272
  id TEXT PRIMARY KEY,
270
273
  run_id TEXT NOT NULL,
@@ -465,6 +468,34 @@ function repoIdForRoot(root) {
465
468
  return stableId("repo", resolve(root));
466
469
  }
467
470
 
471
+ function canonicalizeRemote(value) {
472
+ let raw = String(value ?? "").trim();
473
+ if (!raw) return null;
474
+ const scp = raw.match(/^((?:[^@/:\s]+@)?)([^:/\s]+):(.+)$/);
475
+ if (scp && !raw.includes("://")) raw = `ssh://${scp[1]}${scp[2]}/${scp[3]}`;
476
+ try {
477
+ const parsed = new URL(raw);
478
+ if (parsed.protocol === "file:") {
479
+ const path = resolve(decodeURIComponent(parsed.pathname)).replace(/\.git$/i, "");
480
+ return `file://${path}`;
481
+ }
482
+ if (!parsed.hostname || !["ssh:", "https:", "http:"].includes(parsed.protocol)) return null;
483
+ const path = decodeURIComponent(parsed.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
484
+ if (!path) return null;
485
+ return `${parsed.protocol}//${parsed.hostname.toLowerCase()}${parsed.port ? `:${parsed.port}` : ""}/${path}`;
486
+ } catch {
487
+ return isAbsolute(raw) ? `file://${resolve(raw).replace(/\.git$/i, "")}` : null;
488
+ }
489
+ }
490
+
491
+ function canonicalRemoteForRoot(root) {
492
+ try {
493
+ return canonicalizeRemote(git(root, ["remote", "get-url", "origin"]));
494
+ } catch {
495
+ return null;
496
+ }
497
+ }
498
+
468
499
  function workItemIdForTask(taskId) {
469
500
  return `work-${taskId}`;
470
501
  }
@@ -473,24 +504,26 @@ export function runIdFor(taskId, attempt) {
473
504
  return `run-${taskId}-${attempt}`;
474
505
  }
475
506
 
476
- function ensureControlRecords(dbInstance, task) {
507
+ function ensureControlRecords(dbInstance, task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
477
508
  if (!task?.id || !task.project_root) return;
478
509
  const now = new Date().toISOString();
479
510
  const root = resolve(task.project_root);
480
511
  const repoId = repoIdForRoot(root);
481
512
  const workItemId = workItemIdForTask(task.id);
482
- dbInstance.prepare(`
483
- INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
484
- VALUES (@id, NULL, @root, NULL, @now, @now)
485
- ON CONFLICT(root) DO UPDATE SET updated_at = excluded.updated_at
486
- `).run({ id: repoId, root, now });
513
+ const repo = dbInstance.prepare("SELECT id FROM repos WHERE root = ?").get(root);
514
+ if (!repo || refreshRepo) {
515
+ const resolvedRemote = canonicalRemote === undefined ? canonicalRemoteForRoot(root) : canonicalRemote;
516
+ dbInstance.prepare(`
517
+ INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
518
+ VALUES (@id, @canonical_remote, @root, NULL, @now, @now)
519
+ ON CONFLICT(root) DO UPDATE SET canonical_remote = excluded.canonical_remote, updated_at = excluded.updated_at
520
+ `).run({ id: repoId, canonical_remote: resolvedRemote, root, now });
521
+ }
522
+ const workItem = dbInstance.prepare("SELECT id FROM work_items WHERE task_id = ?").get(task.id);
523
+ if (workItem) return;
487
524
  dbInstance.prepare(`
488
525
  INSERT INTO work_items (id, repo_id, task_id, parent_work_item_id, objective, owner, delivery_state, created_at, updated_at)
489
526
  VALUES (@id, @repo_id, @task_id, NULL, @objective, NULL, @delivery_state, @now, @now)
490
- ON CONFLICT(task_id) DO UPDATE SET
491
- objective = COALESCE(excluded.objective, work_items.objective),
492
- delivery_state = CASE WHEN work_items.delivery_state = 'draft' THEN excluded.delivery_state ELSE work_items.delivery_state END,
493
- updated_at = excluded.updated_at
494
527
  `).run({
495
528
  id: workItemId,
496
529
  repo_id: repoId,
@@ -502,7 +535,12 @@ function ensureControlRecords(dbInstance, task) {
502
535
  }
503
536
 
504
537
  function backfillControlRecords(dbInstance) {
505
- const rows = dbInstance.prepare("SELECT id,title,project_root,goal_objective,landed_at FROM tasks").all();
538
+ const rows = dbInstance.prepare(`
539
+ SELECT t.id,t.title,t.project_root,t.goal_objective,t.landed_at
540
+ FROM tasks AS t
541
+ LEFT JOIN work_items AS w ON w.task_id = t.id
542
+ WHERE w.task_id IS NULL
543
+ `).all();
506
544
  for (const row of rows) ensureControlRecords(dbInstance, row);
507
545
  }
508
546
 
@@ -630,11 +668,17 @@ export async function reconcileDetachedActiveTasks() {
630
668
  await reconcileInterruptedAcceptance();
631
669
  const incomplete = (await readTasks()).filter((task) =>
632
670
  ["completed", "failed"].includes(task.status) && task.exit_code == null && task.started_at
633
- && !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid) && !task.acceptance_results
671
+ && !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid)
672
+ && (!task.acceptance_results || ["interrupted", "cancelled"].includes(task.acceptance_results.status))
634
673
  && Date.now() - Date.parse(task.updated_at) > 5000);
635
674
  for (const task of incomplete) {
636
675
  await writeTask({ ...task, status: "lost", phase: null,
637
- error: "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
676
+ error: task.acceptance_results?.status === "interrupted"
677
+ ? "Worker ended but its supervisor did not record the process exit before acceptance; resume this run"
678
+ : "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
679
+ current_action: task.acceptance_results?.status === "interrupted"
680
+ ? "Acceptance interrupted: worker process exit was not recorded; resume this run"
681
+ : "Resume required: process exit was not recorded",
638
682
  updated_at: new Date().toISOString() });
639
683
  }
640
684
  const tasks = await readActiveTasks();
@@ -663,10 +707,10 @@ export async function reconcileDetachedActiveTasks() {
663
707
 
664
708
  export async function writeTask(task) {
665
709
  await ensureFilesystem();
666
- return writeTaskNow(task);
710
+ return runWithRetry(openDb(), () => writeTaskNow(task));
667
711
  }
668
712
 
669
- function writeTaskNow(task) {
713
+ function writeTaskNow(task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
670
714
  const placeholders = TASK_COLUMNS.map((name) => `@${name}`).join(", ");
671
715
  const updates = TASK_COLUMNS
672
716
  .filter((name) => name !== "id" && name !== "created_at")
@@ -700,7 +744,7 @@ function writeTaskNow(task) {
700
744
  params.phase = task.phase ?? null;
701
745
 
702
746
  stmt.run(params);
703
- ensureControlRecords(openDb(), task);
747
+ ensureControlRecords(openDb(), task, { refreshRepo, canonicalRemote });
704
748
  return task;
705
749
  }
706
750
 
@@ -711,11 +755,17 @@ function checkOwnership(taskId, incoming) {
711
755
  return a===b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
712
756
  };
713
757
  const conflicts = [];
714
- 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);
758
+ const pending = openDb().prepare("SELECT t.id,t.title,t.status,t.owned_paths,t.acceptance_results,t.started_at,t.exit_code,t.guard_policy,t.commands,t.attention_reason,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);
715
759
  for (const row of pending) {
716
760
  const settling = decodeJson(row.acceptance_results,null)?.status === "running"
717
761
  || (["completed","failed"].includes(row.status) && row.started_at && row.exit_code == null && !row.acceptance_results);
718
762
  if (row.owner_pid && !ACTIVE_STATUSES.has(row.status) && !settling && !isPidAlive(row.owner_pid)) continue;
763
+ const preflightTask = {
764
+ ...row,
765
+ guard_policy: decodeJson(row.guard_policy, null),
766
+ commands: decodeJson(row.commands, [])
767
+ };
768
+ if (preflightTask.guard_policy?.preflight && readPreflightResult(preflightTask).status === "passed") continue;
719
769
  const paths=decodeJson(row.owned_paths,[]);
720
770
  const matching=incoming.flatMap(path=>paths.filter(other=>overlaps(path,other)).map(other=>({incoming:path,existing:other})));
721
771
  if(matching.length)conflicts.push({task_id:row.id,title:row.title,status:row.status,overlapping_paths:matching});
@@ -725,10 +775,11 @@ function checkOwnership(taskId, incoming) {
725
775
 
726
776
  export async function reserveTaskOwnership(task) {
727
777
  await ensureFilesystem();
778
+ const canonicalRemote = task?.project_root ? canonicalRemoteForRoot(resolve(task.project_root)) : null;
728
779
  const connection=openDb();
729
780
  return runWithRetry(connection,()=>{
730
781
  connection.exec("BEGIN IMMEDIATE");
731
- try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task);connection.exec("COMMIT");return task; }
782
+ try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task, { refreshRepo: true, canonicalRemote });connection.exec("COMMIT");return task; }
732
783
  catch(error){connection.exec("ROLLBACK");throw error;}
733
784
  });
734
785
  }
@@ -980,35 +1031,38 @@ export async function ensureRunRecord(task, attempt) {
980
1031
  await ensureFilesystem();
981
1032
  if (!task?.id || !Number.isInteger(attempt) || attempt < 1) throw new Error("run record requires a task and positive attempt");
982
1033
  const dbInstance = openDb();
983
- ensureControlRecords(dbInstance, task);
984
- const now = new Date().toISOString();
985
- const id = runIdFor(task.id, attempt);
986
- dbInstance.prepare(`
1034
+ return runWithRetry(dbInstance, () => {
1035
+ ensureControlRecords(dbInstance, task);
1036
+ const now = new Date().toISOString();
1037
+ const id = runIdFor(task.id, attempt);
1038
+ dbInstance.prepare(`
987
1039
  INSERT INTO runs (id, task_id, work_item_id, attempt, codex_thread_id, worktree_path, branch, base_sha, run_status, started_at, finished_at)
988
1040
  VALUES (@id, @task_id, @work_item_id, @attempt, @codex_thread_id, @worktree_path, @branch, @base_sha, 'running', @started_at, NULL)
989
1041
  ON CONFLICT(task_id, attempt) DO UPDATE SET
990
1042
  codex_thread_id = COALESCE(excluded.codex_thread_id, runs.codex_thread_id),
991
1043
  worktree_path = COALESCE(excluded.worktree_path, runs.worktree_path),
992
1044
  base_sha = COALESCE(excluded.base_sha, runs.base_sha)
993
- `).run({
994
- id,
995
- task_id: task.id,
996
- work_item_id: workItemIdForTask(task.id),
997
- attempt,
998
- codex_thread_id: task.thread_id ?? null,
999
- worktree_path: task.worktree_path ?? null,
1000
- branch: task.worktree_path ? `codex/${task.id}` : null,
1001
- base_sha: task.base_commit ?? null,
1002
- started_at: now
1045
+ `).run({
1046
+ id,
1047
+ task_id: task.id,
1048
+ work_item_id: workItemIdForTask(task.id),
1049
+ attempt,
1050
+ codex_thread_id: task.thread_id ?? null,
1051
+ worktree_path: task.worktree_path ?? null,
1052
+ branch: task.worktree_path ? `codex/${task.id}` : null,
1053
+ base_sha: task.base_commit ?? null,
1054
+ started_at: now
1055
+ });
1056
+ return id;
1003
1057
  });
1004
- return id;
1005
1058
  }
1006
1059
 
1007
1060
  export async function completeRunRecord(task, attempt) {
1008
1061
  await ensureFilesystem();
1009
1062
  if (!task?.id || !Number.isInteger(attempt) || attempt < 1) return;
1010
1063
  const now = task.completed_at ?? new Date().toISOString();
1011
- openDb().prepare(`
1064
+ const dbInstance = openDb();
1065
+ runWithRetry(dbInstance, () => dbInstance.prepare(`
1012
1066
  UPDATE runs SET codex_thread_id = @codex_thread_id,
1013
1067
  run_status = @run_status, finished_at = @finished_at
1014
1068
  WHERE task_id = @task_id AND attempt = @attempt
@@ -1018,20 +1072,39 @@ export async function completeRunRecord(task, attempt) {
1018
1072
  codex_thread_id: task.thread_id ?? null,
1019
1073
  run_status: task.status ?? "unknown",
1020
1074
  finished_at: now
1021
- });
1075
+ }));
1022
1076
  }
1023
1077
 
1024
- export async function appendTaskEvent(taskId, event, { runId = null, actor = "supervisor" } = {}) {
1078
+ export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor" } = {}) {
1025
1079
  await ensureFilesystem();
1080
+ if (!Array.isArray(events) || events.length === 0) return [];
1026
1081
  const dbInstance = openDb();
1027
- const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
1028
- const payload = JSON.stringify(event);
1029
- const result = dbInstance.prepare(`
1082
+ return runWithRetry(dbInstance, () => {
1083
+ dbInstance.exec("BEGIN IMMEDIATE");
1084
+ try {
1085
+ const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
1086
+ const insert = dbInstance.prepare(`
1030
1087
  INSERT INTO task_events (task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256)
1031
1088
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1032
- `).run(taskId, runId, nextSeqRow.seq, new Date().toISOString(), actor, event.type ?? "unknown", payload,
1033
- createHash("sha256").update(payload).digest("hex"));
1034
- return { id: Number(result.lastInsertRowid), run_id: runId, actor };
1089
+ `);
1090
+ const createdAt = new Date().toISOString();
1091
+ const records = events.map((event, index) => {
1092
+ const payload = JSON.stringify(event);
1093
+ const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", payload,
1094
+ createHash("sha256").update(payload).digest("hex"));
1095
+ return { id: Number(result.lastInsertRowid), run_id: runId, actor };
1096
+ });
1097
+ dbInstance.exec("COMMIT");
1098
+ return records;
1099
+ } catch (error) {
1100
+ dbInstance.exec("ROLLBACK");
1101
+ throw error;
1102
+ }
1103
+ });
1104
+ }
1105
+
1106
+ export async function appendTaskEvent(taskId, event, options = {}) {
1107
+ return (await appendTaskEvents(taskId, [event], options))[0];
1035
1108
  }
1036
1109
 
1037
1110
  export async function readTaskEvents(taskId, limit = 100, kinds = null) {
@@ -1109,7 +1182,7 @@ export async function recordFact({
1109
1182
  valid_for_sha: validForSha,
1110
1183
  valid_for_content_hash: validForContentHash,
1111
1184
  valid_for_manifest_hash: validForManifestHash,
1112
- watched_paths: JSON.stringify(watchedPaths.map((path) => resolve(path))),
1185
+ watched_paths: JSON.stringify(watchedPaths.map((path) => isAbsolute(path) ? resolve(path) : path)),
1113
1186
  expires_at: expiresAt,
1114
1187
  supersedes_id: supersedesId,
1115
1188
  created_at: now,
@@ -1126,6 +1199,15 @@ function pathsOverlap(left, right) {
1126
1199
  return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
1127
1200
  }
1128
1201
 
1202
+ function repoRelativePaths(projectRoot, paths) {
1203
+ return (paths ?? []).flatMap((path) => {
1204
+ if (typeof path !== "string" || !path.trim()) return [];
1205
+ const candidate = isAbsolute(path) ? relative(projectRoot, path) : path;
1206
+ const normalized = candidate.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
1207
+ return !normalized || normalized === ".." || normalized.startsWith("../") ? [] : [normalized];
1208
+ });
1209
+ }
1210
+
1129
1211
  function git(cwd, args) {
1130
1212
  return execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", cwd, ...args], {
1131
1213
  encoding: "utf8",
@@ -1147,7 +1229,7 @@ function shaCoversBase(projectRoot, validForSha, baseSha) {
1147
1229
  function watchedPathsChanged(projectRoot, validForSha, baseSha, watchedPaths) {
1148
1230
  if (!validForSha || !baseSha || watchedPaths.length === 0) return false;
1149
1231
  try {
1150
- const relativePaths = watchedPaths.map((path) => relative(projectRoot, path)).filter((path) => path && !path.startsWith(".."));
1232
+ const relativePaths = repoRelativePaths(projectRoot, watchedPaths);
1151
1233
  if (relativePaths.length === 0) return true;
1152
1234
  return Boolean(git(projectRoot, ["diff", "--name-only", validForSha, baseSha, "--", ...relativePaths]));
1153
1235
  } catch {
@@ -1165,8 +1247,26 @@ async function currentWorkspaceManifest(task) {
1165
1247
  }
1166
1248
  }
1167
1249
 
1250
+ async function currentContextContentHash(task) {
1251
+ const context = task.input_context?.context ?? [];
1252
+ if (!Array.isArray(context) || context.length === 0) return null;
1253
+ try {
1254
+ return (await buildHandoff({ context }, { maxLines: 1, maxChars: 1 })).content_hash;
1255
+ } catch {
1256
+ return null;
1257
+ }
1258
+ }
1259
+
1168
1260
  function markFactExpired(id) {
1169
- openDb().prepare("UPDATE facts SET state = 'expired' WHERE id = ? AND state = 'verified'").run(id);
1261
+ openDb().prepare(`
1262
+ INSERT INTO facts (id, work_item_id, scope_type, scope_id, key, value_json, state, source_event_id, source_artifact_id,
1263
+ valid_for_sha, valid_for_content_hash, valid_for_manifest_hash, watched_paths, expires_at, supersedes_id, created_at, verified_at, verified_by)
1264
+ SELECT ?, source.work_item_id, source.scope_type, source.scope_id, source.key, source.value_json, 'expired', source.source_event_id, source.source_artifact_id,
1265
+ source.valid_for_sha, source.valid_for_content_hash, source.valid_for_manifest_hash, source.watched_paths, source.expires_at, source.id, ?, source.verified_at, source.verified_by
1266
+ FROM facts AS source
1267
+ WHERE source.id = ? AND source.state = 'verified'
1268
+ AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = source.id AND transition.state IN ('expired', 'revoked'))
1269
+ `).run(randomUUID(), new Date().toISOString(), id);
1170
1270
  }
1171
1271
 
1172
1272
  export async function listContextFacts({ taskId, baseSha, ownedPaths = [], dependencyTaskIds = [] }) {
@@ -1178,31 +1278,45 @@ export async function listContextFacts({ taskId, baseSha, ownedPaths = [], depen
1178
1278
  const dependencyItems = dependencyTaskIds.length === 0
1179
1279
  ? []
1180
1280
  : openDb().prepare(`SELECT id FROM work_items WHERE task_id IN (${dependencyTaskIds.map(() => "?").join(",")})`).all(...dependencyTaskIds).map((row) => row.id);
1181
- const rows = openDb().prepare("SELECT * FROM facts WHERE state = 'verified' ORDER BY created_at ASC").all();
1281
+ const rows = openDb().prepare(`
1282
+ SELECT facts.* FROM facts
1283
+ WHERE state = 'verified'
1284
+ AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
1285
+ ORDER BY created_at ASC
1286
+ `).all();
1182
1287
  const now = Date.now();
1183
1288
  const workspaceManifest = await currentWorkspaceManifest(task);
1289
+ const contextContentHash = await currentContextContentHash(task);
1290
+ const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
1291
+ const canonicalRemote = repo?.canonical_remote ?? null;
1292
+ const ownedRelative = repoRelativePaths(task.project_root, ownedPaths);
1184
1293
  const visible = [];
1185
1294
  for (const row of rows) {
1295
+ const watched = decodeJson(row.watched_paths, []);
1296
+ const watchedRelative = repoRelativePaths(task.project_root, watched);
1297
+ const included = row.scope_type === "work_item" ? row.scope_id === workItem.id
1298
+ : row.scope_type === "dependency" ? dependencyItems.includes(row.scope_id)
1299
+ : row.scope_type === "repo_verified" && canonicalRemote && row.scope_id === canonicalRemote
1300
+ && watchedRelative.length > 0 && watchedRelative.some((path) => ownedRelative.some((owned) => pathsOverlap(path, owned)));
1301
+ if (!included) continue;
1186
1302
  if (row.expires_at && Date.parse(row.expires_at) <= now) {
1187
1303
  markFactExpired(row.id);
1188
1304
  continue;
1189
1305
  }
1190
- const watched = decodeJson(row.watched_paths, []);
1191
- if (!shaCoversBase(task.project_root, row.valid_for_sha, baseSha) || watchedPathsChanged(task.project_root, row.valid_for_sha, baseSha, watched)) {
1192
- markFactExpired(row.id);
1306
+ if (!shaCoversBase(task.project_root, row.valid_for_sha, baseSha)) continue;
1307
+ if (watchedPathsChanged(task.project_root, row.valid_for_sha, baseSha, watchedRelative)) {
1308
+ if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
1193
1309
  continue;
1194
1310
  }
1195
1311
  if (row.valid_for_manifest_hash && (!workspaceManifest || workspaceManifest.sha256 !== row.valid_for_manifest_hash)) {
1196
- markFactExpired(row.id);
1312
+ if (row.scope_type === "work_item" && row.scope_id === workItem.id && workspaceManifest) markFactExpired(row.id);
1313
+ continue;
1314
+ }
1315
+ if (row.valid_for_content_hash && contextContentHash !== row.valid_for_content_hash) {
1316
+ if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
1197
1317
  continue;
1198
1318
  }
1199
- const included = (() => {
1200
- if (row.scope_type === "work_item") return row.scope_id === workItem.id;
1201
- if (row.scope_type === "dependency") return dependencyItems.includes(row.scope_id);
1202
- if (row.scope_type !== "repo_verified" || row.scope_id !== workItem.repo_id) return false;
1203
- return watched.length > 0 && watched.some((path) => ownedPaths.some((owned) => pathsOverlap(path, owned)));
1204
- })();
1205
- if (included) visible.push({
1319
+ visible.push({
1206
1320
  ...row,
1207
1321
  value: decodeJson(row.value_json, null),
1208
1322
  watched_paths: watched
@@ -1213,7 +1327,11 @@ export async function listContextFacts({ taskId, baseSha, ownedPaths = [], depen
1213
1327
 
1214
1328
  export async function countVerifiedFacts() {
1215
1329
  await ensureFilesystem();
1216
- return openDb().prepare("SELECT COUNT(*) AS count FROM facts WHERE state = 'verified'").get().count;
1330
+ return openDb().prepare(`
1331
+ SELECT COUNT(*) AS count FROM facts
1332
+ WHERE state = 'verified'
1333
+ AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
1334
+ `).get().count;
1217
1335
  }
1218
1336
 
1219
1337
  export async function createContextSnapshot({ runId, recipient = "worker", factIds = [], baseSha = null, prompt, estimatedTokens, excluded = {} }) {
@@ -1253,10 +1371,29 @@ export async function getTaskForWorkItem(workItemId) {
1253
1371
  return openDb().prepare("SELECT * FROM tasks WHERE id = (SELECT task_id FROM work_items WHERE id = ?)").get(workItemId) ?? null;
1254
1372
  }
1255
1373
 
1374
+ export async function isFactRevoked(factId) {
1375
+ await ensureFilesystem();
1376
+ return Boolean(openDb().prepare("SELECT 1 FROM facts WHERE supersedes_id = ? AND state = 'revoked'").get(factId));
1377
+ }
1378
+
1379
+ export async function getFactEffectiveState(factId) {
1380
+ await ensureFilesystem();
1381
+ const transition = openDb().prepare(`
1382
+ SELECT state FROM facts WHERE supersedes_id = ? AND state IN ('revoked', 'expired')
1383
+ ORDER BY CASE state WHEN 'revoked' THEN 0 ELSE 1 END, created_at DESC LIMIT 1
1384
+ `).get(factId);
1385
+ return transition?.state ?? null;
1386
+ }
1387
+
1256
1388
  export async function promoteCandidateFact({ factId, scopeType = "work_item", watchedPaths = null, expiresAt = null, sourceEventId = null, verifiedBy = "main_thread" }) {
1257
1389
  await ensureFilesystem();
1258
1390
  const source = await getFact(factId);
1259
1391
  if (!source) throw new Error(`fact not found: ${factId}`);
1392
+ if (await isFactRevoked(factId)) {
1393
+ const error = new Error(`fact ${factId} is already revoked`);
1394
+ error.code = "fact_already_revoked";
1395
+ throw error;
1396
+ }
1260
1397
  if (source.state !== "candidate") {
1261
1398
  const error = new Error(`only candidate facts may be promoted; ${factId} is ${source.state}`);
1262
1399
  error.code = "fact_not_candidate";
@@ -1265,16 +1402,30 @@ export async function promoteCandidateFact({ factId, scopeType = "work_item", wa
1265
1402
  if (!['work_item', 'repo_verified'].includes(scopeType)) throw new Error("promotion scope must be work_item or repo_verified");
1266
1403
  const workItem = openDb().prepare("SELECT * FROM work_items WHERE id = ?").get(source.work_item_id);
1267
1404
  if (!workItem) throw new Error(`work item not found for fact: ${factId}`);
1405
+ const sourceTask = await getTaskForWorkItem(workItem.id);
1268
1406
  const paths = watchedPaths ?? source.watched_paths ?? [];
1407
+ const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
1408
+ const canonicalRemote = repo?.canonical_remote ?? null;
1409
+ const normalizedRepoPaths = sourceTask ? repoRelativePaths(sourceTask.project_root, paths) : [];
1269
1410
  if (scopeType === "repo_verified" && paths.length === 0) {
1270
1411
  const error = new Error("repo_verified promotion requires watchedPaths so unrelated work cannot inherit it");
1271
1412
  error.code = "repo_fact_requires_paths";
1272
1413
  throw error;
1273
1414
  }
1415
+ if (scopeType === "repo_verified" && !canonicalRemote) {
1416
+ const error = new Error("repo_verified promotion requires a canonical origin remote; facts from an unrecognized or missing remote stay work-scoped");
1417
+ error.code = "repo_fact_requires_canonical_remote";
1418
+ throw error;
1419
+ }
1420
+ if (scopeType === "repo_verified" && normalizedRepoPaths.length === 0) {
1421
+ const error = new Error("repo_verified watchedPaths must stay inside the repository root");
1422
+ error.code = "repo_fact_paths_outside_root";
1423
+ throw error;
1424
+ }
1274
1425
  return recordFact({
1275
1426
  workItemId: source.work_item_id,
1276
1427
  scopeType,
1277
- scopeId: scopeType === "repo_verified" ? workItem.repo_id : workItem.id,
1428
+ scopeId: scopeType === "repo_verified" ? canonicalRemote : workItem.id,
1278
1429
  key: source.key,
1279
1430
  value: source.value,
1280
1431
  state: "verified",
@@ -1283,7 +1434,7 @@ export async function promoteCandidateFact({ factId, scopeType = "work_item", wa
1283
1434
  validForSha: source.valid_for_sha ?? null,
1284
1435
  validForContentHash: source.valid_for_content_hash ?? null,
1285
1436
  validForManifestHash: source.valid_for_manifest_hash ?? null,
1286
- watchedPaths: paths,
1437
+ watchedPaths: scopeType === "repo_verified" ? normalizedRepoPaths : paths,
1287
1438
  expiresAt: expiresAt ?? source.expires_at ?? null,
1288
1439
  supersedesId: source.id,
1289
1440
  verifiedBy
@@ -1294,8 +1445,33 @@ export async function revokeFact(factId) {
1294
1445
  await ensureFilesystem();
1295
1446
  const source = await getFact(factId);
1296
1447
  if (!source) return null;
1297
- openDb().prepare("UPDATE facts SET state = 'revoked' WHERE id = ? AND state IN ('candidate', 'verified')").run(factId);
1298
- return { ...source, state: "revoked" };
1448
+ if (!["candidate", "verified"].includes(source.state)) {
1449
+ const error = new Error(`only candidate or verified facts may be revoked; ${factId} is ${source.state}`);
1450
+ error.code = "fact_not_revocable";
1451
+ throw error;
1452
+ }
1453
+ if (await isFactRevoked(factId)) {
1454
+ const error = new Error(`fact ${factId} is already revoked`);
1455
+ error.code = "fact_already_revoked";
1456
+ throw error;
1457
+ }
1458
+ return recordFact({
1459
+ workItemId: source.work_item_id,
1460
+ scopeType: source.scope_type,
1461
+ scopeId: source.scope_id,
1462
+ key: source.key,
1463
+ value: source.value,
1464
+ state: "revoked",
1465
+ sourceEventId: source.source_event_id,
1466
+ sourceArtifactId: source.source_artifact_id,
1467
+ validForSha: source.valid_for_sha,
1468
+ validForContentHash: source.valid_for_content_hash,
1469
+ validForManifestHash: source.valid_for_manifest_hash,
1470
+ watchedPaths: source.watched_paths,
1471
+ expiresAt: source.expires_at,
1472
+ supersedesId: source.id,
1473
+ verifiedBy: "main_thread"
1474
+ });
1299
1475
  }
1300
1476
 
1301
1477
  export async function recordJsonArtifact({ runId, type, value, securityClass = "internal", retention = "permanent" }) {
@@ -1322,7 +1498,10 @@ export async function getArtifact(artifactId) {
1322
1498
  export async function readArtifact(artifactId, maxChars = 12000) {
1323
1499
  const artifact = await getArtifact(artifactId);
1324
1500
  if (!artifact) return null;
1325
- if (!artifact.uri.startsWith(`${artifactsDir}/`)) return { ...artifact, content: null, reason: "artifact_uri_not_managed" };
1501
+ const artifactPath = relative(artifactsDir, resolve(artifact.uri));
1502
+ if (!artifactPath || artifactPath === ".." || artifactPath.startsWith(`..${sep}`) || isAbsolute(artifactPath)) {
1503
+ return { ...artifact, content: null, reason: "artifact_uri_not_managed" };
1504
+ }
1326
1505
  let content;
1327
1506
  try {
1328
1507
  content = await readFile(artifact.uri, "utf8");
@@ -0,0 +1,33 @@
1
+ const DEFAULT_HANDOFF_TOKEN_THRESHOLD = 300000;
2
+ const LONG_THREAD_RATIO = 0.75;
3
+
4
+ export function handoffTokenThreshold(env = process.env) {
5
+ const raw = env.CODEX_SUPERVISOR_HANDOFF_TOKEN_THRESHOLD;
6
+ if (raw == null || raw === "") return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
7
+ const value = Number(raw);
8
+ if (!Number.isFinite(value) || value < 0) return DEFAULT_HANDOFF_TOKEN_THRESHOLD;
9
+ return value;
10
+ }
11
+
12
+ export function threadHealth(task, { threshold = handoffTokenThreshold() } = {}) {
13
+ if (threshold === 0) return { state: "disabled", threshold: 0, tokens_used: task?.goal_tokens_used ?? 0, next_step: null };
14
+ const tokens = Number(task?.goal_tokens_used ?? 0);
15
+ if (!Number.isFinite(tokens) || tokens <= 0) return { state: "ok", threshold, tokens_used: 0, next_step: null };
16
+ if (tokens >= threshold) {
17
+ return {
18
+ state: "handoff_recommended",
19
+ threshold,
20
+ tokens_used: tokens,
21
+ next_step: "Start a fresh 1000-1500-token handoff with create_codex_followup_worker; keep this thread as evidence"
22
+ };
23
+ }
24
+ if (tokens >= Math.floor(threshold * LONG_THREAD_RATIO)) {
25
+ return {
26
+ state: "getting_long",
27
+ threshold,
28
+ tokens_used: tokens,
29
+ next_step: "Finish this bounded step, then create a follow-up worker instead of extending the thread"
30
+ };
31
+ }
32
+ return { state: "ok", threshold, tokens_used: tokens, next_step: null };
33
+ }
@@ -0,0 +1,14 @@
1
+ import { delimiter, dirname } from "node:path";
2
+
3
+ // Codex may wrap a shell command as either `zsh -lc` or `zsh -c`. The latter
4
+ // does not load the user's login profile, so a Homebrew or version-manager
5
+ // Node directory can disappear even though the supervisor itself is running
6
+ // under that exact executable. Put the current Node directory first and keep
7
+ // the inherited PATH for every other toolchain.
8
+ export function withWorkerToolPath(env, execPath = process.execPath, pathDelimiter = delimiter) {
9
+ const nodeDir = dirname(execPath);
10
+ const inherited = env.PATH ?? env.Path ?? "";
11
+ const parts = inherited.split(pathDelimiter).filter((part) => part && part !== nodeDir);
12
+ const value = [nodeDir, ...parts].join(pathDelimiter);
13
+ return { ...env, PATH: value, ...(process.platform === "win32" ? { Path: value } : {}) };
14
+ }