codex-supervisor-mcp 0.10.2 → 0.11.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,12 +1,14 @@
1
- import { mkdir } from "node:fs/promises";
2
- import { join, resolve } from "node:path";
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { join, relative, resolve } from "node:path";
3
3
  import { DatabaseSync } from "node:sqlite";
4
- import { dataDir, dbPath, runsDir } from "./paths.js";
4
+ import { execFileSync } from "node:child_process";
5
+ import { artifactsDir, dataDir, dbPath, runsDir } from "./paths.js";
5
6
  import { extractAgentMessage } from "./event-parser.js";
6
7
  import { ACTIVE_STATUSES, PHASES, TERMINAL_STATUSES } from "./status.js";
7
8
  import { readNativeGoal } from "./goal-store.js";
8
9
  import { normalizeAcceptance } from "./acceptance.js";
9
10
  import { createHash, randomUUID } from "node:crypto";
11
+ import { captureWorkspaceManifest } from "./workspace-kind.js";
10
12
 
11
13
  let db;
12
14
 
@@ -43,7 +45,13 @@ const POST_V1_COLUMNS = [
43
45
  ["landed_branch", "TEXT"],
44
46
  ["push_verified_at", "TEXT"],
45
47
  ["push_remote", "TEXT"],
46
- ["push_branch", "TEXT"]
48
+ ["push_branch", "TEXT"],
49
+ ["push_remote_head", "TEXT"]
50
+ ];
51
+
52
+ const TASK_EXTRA_COLUMNS = [
53
+ ["workspace_kind", "TEXT NOT NULL DEFAULT 'legacy'"],
54
+ ["workspace_metadata", "TEXT"]
47
55
  ];
48
56
 
49
57
  const TASKS_DDL = `
@@ -55,6 +63,8 @@ const TASKS_DDL = `
55
63
  phase TEXT,
56
64
  cwd TEXT NOT NULL,
57
65
  project_root TEXT NOT NULL,
66
+ workspace_kind TEXT NOT NULL DEFAULT 'legacy',
67
+ workspace_metadata TEXT,
58
68
  sandbox TEXT NOT NULL,
59
69
  model TEXT,
60
70
  reasoning_effort TEXT NOT NULL DEFAULT 'high',
@@ -109,19 +119,20 @@ const TASKS_DDL = `
109
119
  push_verified_at TEXT,
110
120
  push_remote TEXT,
111
121
  push_branch TEXT,
122
+ push_remote_head TEXT,
112
123
  run_log TEXT NOT NULL
113
124
  );
114
125
  `;
115
126
 
116
127
  const TASK_COLUMNS = [
117
- "id", "title", "worker", "status", "phase", "cwd", "project_root", "sandbox", "model",
128
+ "id", "title", "worker", "status", "phase", "cwd", "project_root", "workspace_kind", "workspace_metadata", "sandbox", "model",
118
129
  "reasoning_effort", "skip_git_repo_check", "prompt", "changed_files", "commands",
119
130
  "created_at", "updated_at", "started_at", "completed_at", "pid", "run_host_pid", "attention_reason", "run_evidence", "guard_policy", "input_context", "exit_code", "signal",
120
131
  "stderr_tail", "last_event_at", "last_event_type", "last_message", "current_action",
121
132
  "current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
122
133
  "depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
123
134
  "goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
124
- "notices", "worktree_path", "base_commit", "acceptance", "acceptance_local", "session_policy_revision", "acceptance_timeout_ms", "acceptance_results", "landed_at", "landed_head", "landed_branch", "push_verified_at", "push_remote", "push_branch", "run_log"
135
+ "notices", "worktree_path", "base_commit", "acceptance", "acceptance_local", "session_policy_revision", "acceptance_timeout_ms", "acceptance_results", "landed_at", "landed_head", "landed_branch", "push_verified_at", "push_remote", "push_branch", "push_remote_head", "run_log"
125
136
  ];
126
137
 
127
138
  function tableColumns(dbInstance, tableName) {
@@ -143,8 +154,9 @@ function migrateTasksTable(dbInstance, columns) {
143
154
 
144
155
  const selectExpression = (name) => {
145
156
  if (legacyNames.has(name)) return name;
146
- const definition = POST_V1_COLUMNS.find(([columnName]) => columnName === name);
157
+ const definition = [...POST_V1_COLUMNS, ...TASK_EXTRA_COLUMNS].find(([columnName]) => columnName === name);
147
158
  if (definition && definition[1].includes("DEFAULT '[]'")) return "'[]'";
159
+ if (definition && definition[1].includes("DEFAULT 'legacy'")) return "'legacy'";
148
160
  if (definition && definition[1].includes("DEFAULT 0")) return "0";
149
161
  return "NULL";
150
162
  };
@@ -241,12 +253,16 @@ const CONTROL_DDL = `
241
253
  value_json TEXT NOT NULL,
242
254
  state TEXT NOT NULL,
243
255
  source_event_id INTEGER,
256
+ source_artifact_id TEXT,
244
257
  valid_for_sha TEXT,
258
+ valid_for_content_hash TEXT,
259
+ valid_for_manifest_hash TEXT,
245
260
  watched_paths TEXT NOT NULL DEFAULT '[]',
246
261
  expires_at TEXT,
247
262
  supersedes_id TEXT,
248
263
  created_at TEXT NOT NULL,
249
- verified_at TEXT
264
+ verified_at TEXT,
265
+ verified_by TEXT
250
266
  );
251
267
  CREATE INDEX IF NOT EXISTS idx_facts_scope ON facts(scope_type, scope_id, state);
252
268
  CREATE TABLE IF NOT EXISTS artifacts (
@@ -260,6 +276,25 @@ const CONTROL_DDL = `
260
276
  created_at TEXT NOT NULL
261
277
  );
262
278
  CREATE INDEX IF NOT EXISTS idx_artifacts_run ON artifacts(run_id, created_at);
279
+ CREATE TABLE IF NOT EXISTS review_findings (
280
+ id TEXT PRIMARY KEY,
281
+ subject_task_id TEXT NOT NULL,
282
+ verifier_task_id TEXT NOT NULL UNIQUE,
283
+ subject_run_id TEXT,
284
+ subject_base_sha TEXT,
285
+ subject_fingerprint TEXT,
286
+ status TEXT NOT NULL,
287
+ verdict TEXT,
288
+ reason TEXT,
289
+ evidence_artifact_id TEXT,
290
+ finding_event_id INTEGER,
291
+ resolved_at TEXT,
292
+ resolved_by TEXT,
293
+ resolution TEXT,
294
+ created_at TEXT NOT NULL,
295
+ updated_at TEXT NOT NULL
296
+ );
297
+ CREATE INDEX IF NOT EXISTS idx_review_findings_subject ON review_findings(subject_task_id, created_at);
263
298
  CREATE TABLE IF NOT EXISTS context_snapshots (
264
299
  id TEXT PRIMARY KEY,
265
300
  run_id TEXT NOT NULL,
@@ -377,9 +412,18 @@ function initializeSchema(dbInstance) {
377
412
  dbInstance.exec("UPDATE task_events SET actor = 'legacy' WHERE actor IS NULL");
378
413
  dbInstance.exec(TASK_EVENTS_INDEX_DDL);
379
414
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
415
+ for (const [name, definition] of TASK_EXTRA_COLUMNS) {
416
+ if (!tableColumns(dbInstance, "tasks").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE tasks ADD COLUMN ${name} ${definition}`);
417
+ }
380
418
  dbInstance.exec(CONTROL_DDL);
381
- if (!tableColumns(dbInstance, "facts").some((column) => column.name === "watched_paths")) {
382
- dbInstance.exec("ALTER TABLE facts ADD COLUMN watched_paths TEXT NOT NULL DEFAULT '[]'");
419
+ for (const [name, definition] of [
420
+ ["watched_paths", "TEXT NOT NULL DEFAULT '[]'"],
421
+ ["source_artifact_id", "TEXT"],
422
+ ["valid_for_content_hash", "TEXT"],
423
+ ["valid_for_manifest_hash", "TEXT"],
424
+ ["verified_by", "TEXT"]
425
+ ]) {
426
+ if (!tableColumns(dbInstance, "facts").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE facts ADD COLUMN ${name} ${definition}`);
383
427
  }
384
428
  dbInstance.exec(SESSIONS_DDL);
385
429
  for (const [name, definition] of [
@@ -478,6 +522,7 @@ function openDb() {
478
522
  async function ensureFilesystem() {
479
523
  await mkdir(dataDir, { recursive: true });
480
524
  await mkdir(runsDir, { recursive: true });
525
+ await mkdir(artifactsDir, { recursive: true });
481
526
  }
482
527
 
483
528
  function encodeJson(value) {
@@ -498,6 +543,7 @@ function rowToTask(row) {
498
543
  const nativeGoal = readNativeGoal(row.thread_id);
499
544
  return {
500
545
  ...row,
546
+ workspace_kind: row.workspace_kind ?? "legacy",
501
547
  skip_git_repo_check: Boolean(row.skip_git_repo_check),
502
548
  changed_files: decodeJson(row.changed_files, []),
503
549
  commands: decodeJson(row.commands, []),
@@ -509,6 +555,7 @@ function rowToTask(row) {
509
555
  run_evidence: decodeJson(row.run_evidence, null),
510
556
  guard_policy: decodeJson(row.guard_policy, null),
511
557
  input_context: decodeJson(row.input_context, null),
558
+ workspace_metadata: decodeJson(row.workspace_metadata, null),
512
559
  pid: row.pid ?? null,
513
560
  exit_code: row.exit_code ?? null,
514
561
  phase: row.phase ?? null,
@@ -634,6 +681,7 @@ function writeTaskNow(task) {
634
681
  const params = {};
635
682
  for (const name of TASK_COLUMNS) params[name] = task[name] ?? null;
636
683
  params.reasoning_effort = task.reasoning_effort ?? "high";
684
+ params.workspace_kind = task.workspace_kind ?? "legacy";
637
685
  params.skip_git_repo_check = task.skip_git_repo_check ? 1 : 0;
638
686
  params.changed_files = encodeJson(task.changed_files);
639
687
  params.commands = encodeJson(task.commands);
@@ -647,6 +695,7 @@ function writeTaskNow(task) {
647
695
  params.run_evidence = task.run_evidence ? JSON.stringify(task.run_evidence) : null;
648
696
  params.guard_policy = task.guard_policy ? JSON.stringify(task.guard_policy) : null;
649
697
  params.input_context = task.input_context ? JSON.stringify(task.input_context) : null;
698
+ params.workspace_metadata = task.workspace_metadata ? JSON.stringify(task.workspace_metadata) : null;
650
699
  params.run_count = task.run_count ?? 0;
651
700
  params.phase = task.phase ?? null;
652
701
 
@@ -1028,11 +1077,15 @@ export async function recordFact({
1028
1077
  value,
1029
1078
  state = "candidate",
1030
1079
  sourceEventId = null,
1080
+ sourceArtifactId = null,
1031
1081
  validForSha = null,
1082
+ validForContentHash = null,
1083
+ validForManifestHash = null,
1032
1084
  watchedPaths = [],
1033
1085
  expiresAt = null,
1034
1086
  supersedesId = null,
1035
- verifiedAt = null
1087
+ verifiedAt = null,
1088
+ verifiedBy = null
1036
1089
  }) {
1037
1090
  await ensureFilesystem();
1038
1091
  if (!workItemId || !scopeType || !scopeId || !key) throw new Error("fact requires workItemId, scopeType, scopeId and key");
@@ -1041,8 +1094,8 @@ export async function recordFact({
1041
1094
  const now = new Date().toISOString();
1042
1095
  const id = randomUUID();
1043
1096
  openDb().prepare(`
1044
- INSERT INTO facts (id, work_item_id, scope_type, scope_id, key, value_json, state, source_event_id, valid_for_sha, watched_paths, expires_at, supersedes_id, created_at, verified_at)
1045
- VALUES (@id, @work_item_id, @scope_type, @scope_id, @key, @value_json, @state, @source_event_id, @valid_for_sha, @watched_paths, @expires_at, @supersedes_id, @created_at, @verified_at)
1097
+ INSERT INTO facts (id, work_item_id, scope_type, scope_id, key, value_json, state, source_event_id, source_artifact_id, valid_for_sha, valid_for_content_hash, valid_for_manifest_hash, watched_paths, expires_at, supersedes_id, created_at, verified_at, verified_by)
1098
+ VALUES (@id, @work_item_id, @scope_type, @scope_id, @key, @value_json, @state, @source_event_id, @source_artifact_id, @valid_for_sha, @valid_for_content_hash, @valid_for_manifest_hash, @watched_paths, @expires_at, @supersedes_id, @created_at, @verified_at, @verified_by)
1046
1099
  `).run({
1047
1100
  id,
1048
1101
  work_item_id: workItemId,
@@ -1052,14 +1105,18 @@ export async function recordFact({
1052
1105
  value_json: JSON.stringify(value),
1053
1106
  state,
1054
1107
  source_event_id: sourceEventId,
1108
+ source_artifact_id: sourceArtifactId,
1055
1109
  valid_for_sha: validForSha,
1110
+ valid_for_content_hash: validForContentHash,
1111
+ valid_for_manifest_hash: validForManifestHash,
1056
1112
  watched_paths: JSON.stringify(watchedPaths.map((path) => resolve(path))),
1057
1113
  expires_at: expiresAt,
1058
1114
  supersedes_id: supersedesId,
1059
1115
  created_at: now,
1060
- verified_at: verifiedAt ?? (state === "verified" ? now : null)
1116
+ verified_at: verifiedAt ?? (state === "verified" ? now : null),
1117
+ verified_by: verifiedBy ?? (state === "verified" ? "supervisor" : null)
1061
1118
  });
1062
- return { id, work_item_id: workItemId, scope_type: scopeType, scope_id: scopeId, key, value, state, valid_for_sha: validForSha, watched_paths: watchedPaths, created_at: now };
1119
+ return { id, work_item_id: workItemId, scope_type: scopeType, scope_id: scopeId, key, value, state, source_event_id: sourceEventId, source_artifact_id: sourceArtifactId, valid_for_sha: validForSha, valid_for_content_hash: validForContentHash, valid_for_manifest_hash: validForManifestHash, watched_paths: watchedPaths, supersedes_id: supersedesId, verified_by: verifiedBy ?? (state === "verified" ? "supervisor" : null), created_at: now };
1063
1120
  }
1064
1121
 
1065
1122
  function pathsOverlap(left, right) {
@@ -1069,27 +1126,94 @@ function pathsOverlap(left, right) {
1069
1126
  return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
1070
1127
  }
1071
1128
 
1129
+ function git(cwd, args) {
1130
+ return execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", cwd, ...args], {
1131
+ encoding: "utf8",
1132
+ timeout: 15000,
1133
+ stdio: ["ignore", "pipe", "ignore"]
1134
+ }).trim();
1135
+ }
1136
+
1137
+ function shaCoversBase(projectRoot, validForSha, baseSha) {
1138
+ if (!validForSha || !baseSha) return true;
1139
+ try {
1140
+ git(projectRoot, ["merge-base", "--is-ancestor", validForSha, baseSha]);
1141
+ return true;
1142
+ } catch {
1143
+ return false;
1144
+ }
1145
+ }
1146
+
1147
+ function watchedPathsChanged(projectRoot, validForSha, baseSha, watchedPaths) {
1148
+ if (!validForSha || !baseSha || watchedPaths.length === 0) return false;
1149
+ try {
1150
+ const relativePaths = watchedPaths.map((path) => relative(projectRoot, path)).filter((path) => path && !path.startsWith(".."));
1151
+ if (relativePaths.length === 0) return true;
1152
+ return Boolean(git(projectRoot, ["diff", "--name-only", validForSha, baseSha, "--", ...relativePaths]));
1153
+ } catch {
1154
+ return true;
1155
+ }
1156
+ }
1157
+
1158
+ async function currentWorkspaceManifest(task) {
1159
+ const metadata = task.workspace_metadata;
1160
+ if (!metadata?.source_root || !Array.isArray(metadata.manifest_paths) || metadata.manifest_paths.length === 0) return null;
1161
+ try {
1162
+ return await captureWorkspaceManifest(metadata.source_root, metadata.manifest_paths);
1163
+ } catch {
1164
+ return null;
1165
+ }
1166
+ }
1167
+
1168
+ function markFactExpired(id) {
1169
+ openDb().prepare("UPDATE facts SET state = 'expired' WHERE id = ? AND state = 'verified'").run(id);
1170
+ }
1171
+
1072
1172
  export async function listContextFacts({ taskId, baseSha, ownedPaths = [], dependencyTaskIds = [] }) {
1073
1173
  await ensureFilesystem();
1074
1174
  const workItem = await getWorkItemForTask(taskId);
1075
1175
  if (!workItem) return [];
1176
+ const task = await getTask(taskId);
1177
+ if (!task) return [];
1076
1178
  const dependencyItems = dependencyTaskIds.length === 0
1077
1179
  ? []
1078
1180
  : openDb().prepare(`SELECT id FROM work_items WHERE task_id IN (${dependencyTaskIds.map(() => "?").join(",")})`).all(...dependencyTaskIds).map((row) => row.id);
1079
1181
  const rows = openDb().prepare("SELECT * FROM facts WHERE state = 'verified' ORDER BY created_at ASC").all();
1080
1182
  const now = Date.now();
1081
- return rows.filter((row) => {
1082
- if (row.expires_at && Date.parse(row.expires_at) <= now) return false;
1183
+ const workspaceManifest = await currentWorkspaceManifest(task);
1184
+ const visible = [];
1185
+ for (const row of rows) {
1186
+ if (row.expires_at && Date.parse(row.expires_at) <= now) {
1187
+ markFactExpired(row.id);
1188
+ continue;
1189
+ }
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);
1193
+ continue;
1194
+ }
1195
+ if (row.valid_for_manifest_hash && (!workspaceManifest || workspaceManifest.sha256 !== row.valid_for_manifest_hash)) {
1196
+ markFactExpired(row.id);
1197
+ continue;
1198
+ }
1199
+ const included = (() => {
1083
1200
  if (row.scope_type === "work_item") return row.scope_id === workItem.id;
1084
1201
  if (row.scope_type === "dependency") return dependencyItems.includes(row.scope_id);
1085
1202
  if (row.scope_type !== "repo_verified" || row.scope_id !== workItem.repo_id) return false;
1086
- const watched = decodeJson(row.watched_paths, []);
1087
1203
  return watched.length > 0 && watched.some((path) => ownedPaths.some((owned) => pathsOverlap(path, owned)));
1088
- }).map((row) => ({
1089
- ...row,
1090
- value: decodeJson(row.value_json, null),
1091
- watched_paths: decodeJson(row.watched_paths, [])
1092
- }));
1204
+ })();
1205
+ if (included) visible.push({
1206
+ ...row,
1207
+ value: decodeJson(row.value_json, null),
1208
+ watched_paths: watched
1209
+ });
1210
+ }
1211
+ return visible;
1212
+ }
1213
+
1214
+ export async function countVerifiedFacts() {
1215
+ await ensureFilesystem();
1216
+ return openDb().prepare("SELECT COUNT(*) AS count FROM facts WHERE state = 'verified'").get().count;
1093
1217
  }
1094
1218
 
1095
1219
  export async function createContextSnapshot({ runId, recipient = "worker", factIds = [], baseSha = null, prompt, estimatedTokens, excluded = {} }) {
@@ -1124,6 +1248,140 @@ export async function getFact(factId) {
1124
1248
  };
1125
1249
  }
1126
1250
 
1251
+ export async function getTaskForWorkItem(workItemId) {
1252
+ await ensureFilesystem();
1253
+ return openDb().prepare("SELECT * FROM tasks WHERE id = (SELECT task_id FROM work_items WHERE id = ?)").get(workItemId) ?? null;
1254
+ }
1255
+
1256
+ export async function promoteCandidateFact({ factId, scopeType = "work_item", watchedPaths = null, expiresAt = null, sourceEventId = null, verifiedBy = "main_thread" }) {
1257
+ await ensureFilesystem();
1258
+ const source = await getFact(factId);
1259
+ if (!source) throw new Error(`fact not found: ${factId}`);
1260
+ if (source.state !== "candidate") {
1261
+ const error = new Error(`only candidate facts may be promoted; ${factId} is ${source.state}`);
1262
+ error.code = "fact_not_candidate";
1263
+ throw error;
1264
+ }
1265
+ if (!['work_item', 'repo_verified'].includes(scopeType)) throw new Error("promotion scope must be work_item or repo_verified");
1266
+ const workItem = openDb().prepare("SELECT * FROM work_items WHERE id = ?").get(source.work_item_id);
1267
+ if (!workItem) throw new Error(`work item not found for fact: ${factId}`);
1268
+ const paths = watchedPaths ?? source.watched_paths ?? [];
1269
+ if (scopeType === "repo_verified" && paths.length === 0) {
1270
+ const error = new Error("repo_verified promotion requires watchedPaths so unrelated work cannot inherit it");
1271
+ error.code = "repo_fact_requires_paths";
1272
+ throw error;
1273
+ }
1274
+ return recordFact({
1275
+ workItemId: source.work_item_id,
1276
+ scopeType,
1277
+ scopeId: scopeType === "repo_verified" ? workItem.repo_id : workItem.id,
1278
+ key: source.key,
1279
+ value: source.value,
1280
+ state: "verified",
1281
+ sourceEventId,
1282
+ sourceArtifactId: source.source_artifact_id ?? null,
1283
+ validForSha: source.valid_for_sha ?? null,
1284
+ validForContentHash: source.valid_for_content_hash ?? null,
1285
+ validForManifestHash: source.valid_for_manifest_hash ?? null,
1286
+ watchedPaths: paths,
1287
+ expiresAt: expiresAt ?? source.expires_at ?? null,
1288
+ supersedesId: source.id,
1289
+ verifiedBy
1290
+ });
1291
+ }
1292
+
1293
+ export async function revokeFact(factId) {
1294
+ await ensureFilesystem();
1295
+ const source = await getFact(factId);
1296
+ 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" };
1299
+ }
1300
+
1301
+ export async function recordJsonArtifact({ runId, type, value, securityClass = "internal", retention = "permanent" }) {
1302
+ await ensureFilesystem();
1303
+ if (!runId || !type) throw new Error("artifact requires runId and type");
1304
+ const id = randomUUID();
1305
+ const content = JSON.stringify(value, null, 2);
1306
+ const sha256 = createHash("sha256").update(content).digest("hex");
1307
+ const path = join(artifactsDir, `${id}.json`);
1308
+ await writeFile(path, content, { encoding: "utf8", mode: 0o600 });
1309
+ const now = new Date().toISOString();
1310
+ openDb().prepare(`
1311
+ INSERT INTO artifacts (id, run_id, type, uri, sha256, security_class, retention, created_at)
1312
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1313
+ `).run(id, runId, type, path, sha256, securityClass, retention, now);
1314
+ return { id, run_id: runId, type, uri: path, sha256, security_class: securityClass, retention, created_at: now };
1315
+ }
1316
+
1317
+ export async function getArtifact(artifactId) {
1318
+ await ensureFilesystem();
1319
+ return openDb().prepare("SELECT * FROM artifacts WHERE id = ?").get(artifactId) ?? null;
1320
+ }
1321
+
1322
+ export async function readArtifact(artifactId, maxChars = 12000) {
1323
+ const artifact = await getArtifact(artifactId);
1324
+ if (!artifact) return null;
1325
+ if (!artifact.uri.startsWith(`${artifactsDir}/`)) return { ...artifact, content: null, reason: "artifact_uri_not_managed" };
1326
+ let content;
1327
+ try {
1328
+ content = await readFile(artifact.uri, "utf8");
1329
+ } catch (error) {
1330
+ return { ...artifact, content: null, reason: `artifact_unreadable: ${error.code ?? error.message}` };
1331
+ }
1332
+ const truncated = content.length > maxChars;
1333
+ return { ...artifact, content: truncated ? `${content.slice(0, maxChars)}…` : content, truncated };
1334
+ }
1335
+
1336
+ export async function listArtifactsForTask(taskId, limit = 50) {
1337
+ await ensureFilesystem();
1338
+ return openDb().prepare(`
1339
+ SELECT a.* FROM artifacts a JOIN runs r ON r.id = a.run_id
1340
+ WHERE r.task_id = ? ORDER BY a.created_at DESC LIMIT ?
1341
+ `).all(taskId, limit);
1342
+ }
1343
+
1344
+ export async function createReviewAssignment({ subjectTaskId, verifierTaskId, subjectRunId = null, subjectBaseSha = null, subjectFingerprint = null }) {
1345
+ await ensureFilesystem();
1346
+ const now = new Date().toISOString();
1347
+ const id = randomUUID();
1348
+ openDb().prepare(`
1349
+ INSERT INTO review_findings (id, subject_task_id, verifier_task_id, subject_run_id, subject_base_sha, subject_fingerprint, status, created_at, updated_at)
1350
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)
1351
+ `).run(id, subjectTaskId, verifierTaskId, subjectRunId, subjectBaseSha, subjectFingerprint, now, now);
1352
+ return { id, subject_task_id: subjectTaskId, verifier_task_id: verifierTaskId, subject_run_id: subjectRunId, subject_base_sha: subjectBaseSha, subject_fingerprint: subjectFingerprint, status: "pending", created_at: now, updated_at: now };
1353
+ }
1354
+
1355
+ export async function getReviewByVerifierTask(verifierTaskId) {
1356
+ await ensureFilesystem();
1357
+ return openDb().prepare("SELECT * FROM review_findings WHERE verifier_task_id = ?").get(verifierTaskId) ?? null;
1358
+ }
1359
+
1360
+ export async function recordReviewFinding({ verifierTaskId, verdict, reason, evidenceArtifactId = null, findingEventId = null }) {
1361
+ await ensureFilesystem();
1362
+ if (!['passes', 'fails', 'inconclusive'].includes(verdict)) throw new Error("review verdict must be passes, fails or inconclusive");
1363
+ const now = new Date().toISOString();
1364
+ const result = openDb().prepare(`
1365
+ UPDATE review_findings
1366
+ SET status = 'recorded', verdict = ?, reason = ?, evidence_artifact_id = ?, finding_event_id = ?, updated_at = ?
1367
+ WHERE verifier_task_id = ? AND status = 'pending'
1368
+ `).run(verdict, reason, evidenceArtifactId, findingEventId, now, verifierTaskId);
1369
+ if (result.changes === 0) return null;
1370
+ return getReviewByVerifierTask(verifierTaskId);
1371
+ }
1372
+
1373
+ export async function resolveReviewFinding({ verifierTaskId, resolution, resolvedBy = 'main_thread' }) {
1374
+ await ensureFilesystem();
1375
+ const now = new Date().toISOString();
1376
+ const result = openDb().prepare(`
1377
+ UPDATE review_findings
1378
+ SET status = 'resolved', resolution = ?, resolved_at = ?, resolved_by = ?, updated_at = ?
1379
+ WHERE verifier_task_id = ? AND status = 'recorded'
1380
+ `).run(resolution, now, resolvedBy, now, verifierTaskId);
1381
+ if (result.changes === 0) return null;
1382
+ return getReviewByVerifierTask(verifierTaskId);
1383
+ }
1384
+
1127
1385
  export async function updateWorkItemDelivery(taskId, deliveryState) {
1128
1386
  await ensureFilesystem();
1129
1387
  if (!["draft", "verified", "landed", "push_verified", "cleanup_eligible", "cleanup_removed", "needs_attention"].includes(deliveryState)) {
@@ -1153,6 +1411,9 @@ export async function saveCleanupPlan(plan) {
1153
1411
  if (item.verdict === "safe") {
1154
1412
  dbInstance.prepare("UPDATE work_items SET delivery_state = 'cleanup_eligible', updated_at = ? WHERE task_id = ? AND delivery_state = 'push_verified'")
1155
1413
  .run(new Date().toISOString(), item.task_id);
1414
+ } else {
1415
+ dbInstance.prepare("UPDATE work_items SET delivery_state = 'push_verified', updated_at = ? WHERE task_id = ? AND delivery_state = 'cleanup_eligible'")
1416
+ .run(new Date().toISOString(), item.task_id);
1156
1417
  }
1157
1418
  }
1158
1419
  dbInstance.exec("COMMIT");
@@ -35,7 +35,9 @@ export function buildRuntimeContract({
35
35
  networkAccess,
36
36
  writableRoots,
37
37
  context,
38
- contracts
38
+ contracts,
39
+ workspaceKind = "git_worktree",
40
+ workspaceManifestSha256 = null
39
41
  }) {
40
42
  return stableValue({
41
43
  version: PREFLIGHT_VERSION,
@@ -46,6 +48,8 @@ export function buildRuntimeContract({
46
48
  allowed_commands: uniqueSorted(allowedCommands),
47
49
  network_access: networkAccess === true,
48
50
  writable_roots: uniqueSorted(writableRoots),
51
+ workspace_kind: workspaceKind,
52
+ workspace_manifest_sha256: workspaceManifestSha256,
49
53
  context: (context ?? [])
50
54
  .map((entry) => ({ path: resolve(entry.path), sha256: entry.sha256 ?? null }))
51
55
  .sort((left, right) => left.path.localeCompare(right.path)),
@@ -0,0 +1,167 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream, existsSync } from "node:fs";
3
+ import { lstat, mkdir, readdir, readlink, rm } from "node:fs/promises";
4
+ import { execFileSync } from "node:child_process";
5
+ import { join, relative, resolve } from "node:path";
6
+ import { scratchDir } from "./paths.js";
7
+
8
+ export const WORKSPACE_KINDS = ["git_worktree", "read_only_in_place", "scratch", "in_place_write"];
9
+ const MAX_MANIFEST_ENTRIES = 20000;
10
+
11
+ function workspaceError(code, message) {
12
+ const error = new Error(message);
13
+ error.code = code;
14
+ return error;
15
+ }
16
+
17
+ function isInside(root, path) {
18
+ const rel = relative(root, path);
19
+ return rel === "" || (!rel.startsWith("..") && !rel.includes(`..${process.platform === "win32" ? "\\" : "/"}`));
20
+ }
21
+
22
+ export function isGitCheckout(cwd) {
23
+ try {
24
+ return execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", cwd, "rev-parse", "--is-inside-work-tree"], {
25
+ encoding: "utf8",
26
+ stdio: ["ignore", "pipe", "ignore"],
27
+ timeout: 15000
28
+ }).trim() === "true";
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ function selectedKind({ sourceRoot, workspaceKind, sandbox }) {
35
+ if (workspaceKind != null && !WORKSPACE_KINDS.includes(workspaceKind)) {
36
+ throw workspaceError("invalid_workspace_kind", `workspaceKind must be one of ${WORKSPACE_KINDS.join(", ")}`);
37
+ }
38
+ if (workspaceKind) return workspaceKind;
39
+ if (isGitCheckout(sourceRoot)) return "git_worktree";
40
+ if (sandbox === "read-only") return "read_only_in_place";
41
+ throw workspaceError("workspace_kind_required", "a non-Git worker that can write must declare workspaceKind: scratch or in_place_write; the supervisor never writes a user directory by default");
42
+ }
43
+
44
+ function validateKind({ kind, sourceRoot, sandbox, ownedPaths, networkAccess, acceptance, externalOutputs, inPlaceAuthorization, isPreflight }) {
45
+ if (kind === "git_worktree") {
46
+ if (!isGitCheckout(sourceRoot)) throw workspaceError("git_worktree_requires_git", "workspaceKind git_worktree requires a Git checkout with a resolvable commit; use read_only_in_place, scratch or explicitly authorized in_place_write for a non-Git directory");
47
+ return;
48
+ }
49
+ if (kind === "read_only_in_place") {
50
+ if (sandbox !== "read-only" || ownedPaths.length !== 0 || networkAccess) {
51
+ throw workspaceError("invalid_read_only_workspace", "read_only_in_place requires sandbox read-only, ownedPaths: [] and networkAccess: false");
52
+ }
53
+ if (externalOutputs.length) throw workspaceError("invalid_read_only_workspace", "read_only_in_place cannot declare externalOutputs");
54
+ return;
55
+ }
56
+ if (kind === "scratch") {
57
+ if (sandbox !== "workspace-write" || ownedPaths.length !== 0) {
58
+ throw workspaceError("invalid_scratch_workspace", "scratch requires sandbox workspace-write and ownedPaths: []; it never lands project changes");
59
+ }
60
+ if (externalOutputs.length) throw workspaceError("invalid_scratch_workspace", "scratch cannot write externalOutputs; keep generated material inside the supervisor scratch directory");
61
+ return;
62
+ }
63
+ if (isGitCheckout(sourceRoot)) {
64
+ throw workspaceError("in_place_write_requires_non_git", "in_place_write is only for an explicitly authorized non-Git directory; use git_worktree for a Git checkout");
65
+ }
66
+ if (sandbox !== "workspace-write" || ownedPaths.length === 0 || !String(inPlaceAuthorization ?? "").trim()) {
67
+ throw workspaceError("invalid_in_place_workspace", "in_place_write requires sandbox workspace-write, nonempty ownedPaths and an explicit inPlaceAuthorization");
68
+ }
69
+ if (!isPreflight && (!Array.isArray(acceptance) || acceptance.length === 0)) {
70
+ throw workspaceError("in_place_acceptance_required", "in_place_write requires explicit acceptance; file changes in a user directory cannot be accepted by worker exit status alone");
71
+ }
72
+ for (const path of ownedPaths) {
73
+ if (!isInside(sourceRoot, resolve(sourceRoot, path))) {
74
+ throw workspaceError("in_place_path_outside_root", `in_place_write ownedPath escapes the authorized source root: ${path}`);
75
+ }
76
+ }
77
+ }
78
+
79
+ async function sha256File(path) {
80
+ const hash = createHash("sha256");
81
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
82
+ return hash.digest("hex");
83
+ }
84
+
85
+ async function manifestEntry(root, absolute, entries) {
86
+ if (entries.length >= MAX_MANIFEST_ENTRIES) {
87
+ throw workspaceError("workspace_manifest_too_large", `workspace manifest exceeds ${MAX_MANIFEST_ENTRIES} entries; narrow the declared in-place paths before dispatching`);
88
+ }
89
+ const path = relative(root, absolute) || ".";
90
+ let info;
91
+ try {
92
+ info = await lstat(absolute);
93
+ } catch (error) {
94
+ if (error.code === "ENOENT") {
95
+ entries.push({ path, type: "missing" });
96
+ return;
97
+ }
98
+ throw error;
99
+ }
100
+ if (info.isFile()) {
101
+ entries.push({ path, type: "file", bytes: info.size, sha256: await sha256File(absolute) });
102
+ return;
103
+ }
104
+ if (info.isSymbolicLink()) {
105
+ entries.push({ path, type: "symlink", target: await readlink(absolute) });
106
+ return;
107
+ }
108
+ if (info.isDirectory()) {
109
+ entries.push({ path, type: "directory" });
110
+ const children = await readdir(absolute);
111
+ for (const child of children.sort((left, right) => left.localeCompare(right))) {
112
+ await manifestEntry(root, join(absolute, child), entries);
113
+ }
114
+ return;
115
+ }
116
+ entries.push({ path, type: "other" });
117
+ }
118
+
119
+ export async function captureWorkspaceManifest(sourceRoot, paths) {
120
+ const root = resolve(sourceRoot);
121
+ const entries = [];
122
+ for (const path of [...new Set(paths.map((path) => resolve(root, path)))].sort((left, right) => left.localeCompare(right))) {
123
+ await manifestEntry(root, path, entries);
124
+ }
125
+ const canonical = JSON.stringify(entries);
126
+ return {
127
+ algorithm: "sha256",
128
+ root,
129
+ paths: paths.map((path) => resolve(root, path)),
130
+ entry_count: entries.length,
131
+ sha256: createHash("sha256").update(canonical).digest("hex"),
132
+ entries
133
+ };
134
+ }
135
+
136
+ export async function prepareWorkspace({ cwd, workspaceKind = null, sandbox, ownedPaths, networkAccess, acceptance, externalOutputs = [], inPlaceAuthorization = null, taskId, isPreflight = false }) {
137
+ const sourceRoot = resolve(cwd);
138
+ if (!existsSync(sourceRoot)) throw workspaceError("workspace_source_missing", `workspace source directory does not exist: ${sourceRoot}`);
139
+ const kind = selectedKind({ sourceRoot, workspaceKind, sandbox });
140
+ validateKind({ kind, sourceRoot, sandbox, ownedPaths, networkAccess, acceptance, externalOutputs, inPlaceAuthorization, isPreflight });
141
+ if (kind !== "scratch") {
142
+ const manifestPaths = kind === "in_place_write" ? ownedPaths : [];
143
+ return {
144
+ kind,
145
+ sourceRoot,
146
+ executionCwd: sourceRoot,
147
+ manifestPaths,
148
+ beforeManifest: manifestPaths.length ? await captureWorkspaceManifest(sourceRoot, manifestPaths) : null,
149
+ landable: kind === "git_worktree",
150
+ cleanable: kind === "git_worktree"
151
+ };
152
+ }
153
+ const executionCwd = join(scratchDir, taskId);
154
+ await mkdir(scratchDir, { recursive: true });
155
+ await rm(executionCwd, { recursive: true, force: true });
156
+ await mkdir(executionCwd, { recursive: true });
157
+ return {
158
+ kind,
159
+ sourceRoot,
160
+ executionCwd,
161
+ manifestPaths: [],
162
+ beforeManifest: null,
163
+ landable: false,
164
+ cleanable: false,
165
+ scratchPath: executionCwd
166
+ };
167
+ }