codex-supervisor-mcp 0.9.7 → 0.10.3

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,12 @@
1
1
  import { mkdir } from "node:fs/promises";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
  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
7
  import { readNativeGoal } from "./goal-store.js";
8
8
  import { normalizeAcceptance } from "./acceptance.js";
9
- import { randomUUID } from "node:crypto";
9
+ import { createHash, randomUUID } from "node:crypto";
10
10
 
11
11
  let db;
12
12
 
@@ -39,7 +39,11 @@ const POST_V1_COLUMNS = [
39
39
  ["acceptance_timeout_ms", "INTEGER"],
40
40
  ["acceptance_results", "TEXT"],
41
41
  ["landed_at", "TEXT"],
42
- ["landed_head", "TEXT"]
42
+ ["landed_head", "TEXT"],
43
+ ["landed_branch", "TEXT"],
44
+ ["push_verified_at", "TEXT"],
45
+ ["push_remote", "TEXT"],
46
+ ["push_branch", "TEXT"]
43
47
  ];
44
48
 
45
49
  const TASKS_DDL = `
@@ -101,6 +105,10 @@ const TASKS_DDL = `
101
105
  acceptance_results TEXT,
102
106
  landed_at TEXT,
103
107
  landed_head TEXT,
108
+ landed_branch TEXT,
109
+ push_verified_at TEXT,
110
+ push_remote TEXT,
111
+ push_branch TEXT,
104
112
  run_log TEXT NOT NULL
105
113
  );
106
114
  `;
@@ -113,7 +121,7 @@ const TASK_COLUMNS = [
113
121
  "current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
114
122
  "depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
115
123
  "goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
116
- "notices", "worktree_path", "base_commit", "acceptance", "acceptance_local", "session_policy_revision", "acceptance_timeout_ms", "acceptance_results", "landed_at", "landed_head", "run_log"
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"
117
125
  ];
118
126
 
119
127
  function tableColumns(dbInstance, tableName) {
@@ -172,10 +180,13 @@ const TASK_EVENTS_DDL = `
172
180
  CREATE TABLE IF NOT EXISTS task_events (
173
181
  id INTEGER PRIMARY KEY AUTOINCREMENT,
174
182
  task_id TEXT NOT NULL,
183
+ run_id TEXT,
175
184
  seq INTEGER NOT NULL,
176
185
  created_at TEXT NOT NULL,
186
+ actor TEXT NOT NULL DEFAULT 'legacy',
177
187
  event_type TEXT NOT NULL,
178
- payload TEXT NOT NULL
188
+ payload TEXT NOT NULL,
189
+ payload_sha256 TEXT
179
190
  );
180
191
  `;
181
192
 
@@ -185,6 +196,107 @@ const TASK_EVENTS_INDEX_DDL =
185
196
  const TASKS_SESSION_INDEX_DDL =
186
197
  "CREATE INDEX IF NOT EXISTS idx_tasks_session ON tasks(session_id);";
187
198
 
199
+ const CONTROL_DDL = `
200
+ CREATE TABLE IF NOT EXISTS repos (
201
+ id TEXT PRIMARY KEY,
202
+ canonical_remote TEXT,
203
+ root TEXT NOT NULL UNIQUE,
204
+ default_branch TEXT,
205
+ created_at TEXT NOT NULL,
206
+ updated_at TEXT NOT NULL
207
+ );
208
+ CREATE TABLE IF NOT EXISTS work_items (
209
+ id TEXT PRIMARY KEY,
210
+ repo_id TEXT NOT NULL,
211
+ task_id TEXT NOT NULL UNIQUE,
212
+ parent_work_item_id TEXT,
213
+ objective TEXT,
214
+ owner TEXT,
215
+ delivery_state TEXT NOT NULL DEFAULT 'draft',
216
+ created_at TEXT NOT NULL,
217
+ updated_at TEXT NOT NULL
218
+ );
219
+ CREATE INDEX IF NOT EXISTS idx_work_items_repo ON work_items(repo_id, created_at);
220
+ CREATE TABLE IF NOT EXISTS runs (
221
+ id TEXT PRIMARY KEY,
222
+ task_id TEXT NOT NULL,
223
+ work_item_id TEXT NOT NULL,
224
+ attempt INTEGER NOT NULL,
225
+ codex_thread_id TEXT,
226
+ worktree_path TEXT,
227
+ branch TEXT,
228
+ base_sha TEXT,
229
+ run_status TEXT NOT NULL,
230
+ started_at TEXT NOT NULL,
231
+ finished_at TEXT,
232
+ UNIQUE(task_id, attempt)
233
+ );
234
+ CREATE INDEX IF NOT EXISTS idx_runs_work_item ON runs(work_item_id, attempt);
235
+ CREATE TABLE IF NOT EXISTS facts (
236
+ id TEXT PRIMARY KEY,
237
+ work_item_id TEXT NOT NULL,
238
+ scope_type TEXT NOT NULL,
239
+ scope_id TEXT NOT NULL,
240
+ key TEXT NOT NULL,
241
+ value_json TEXT NOT NULL,
242
+ state TEXT NOT NULL,
243
+ source_event_id INTEGER,
244
+ valid_for_sha TEXT,
245
+ watched_paths TEXT NOT NULL DEFAULT '[]',
246
+ expires_at TEXT,
247
+ supersedes_id TEXT,
248
+ created_at TEXT NOT NULL,
249
+ verified_at TEXT
250
+ );
251
+ CREATE INDEX IF NOT EXISTS idx_facts_scope ON facts(scope_type, scope_id, state);
252
+ CREATE TABLE IF NOT EXISTS artifacts (
253
+ id TEXT PRIMARY KEY,
254
+ run_id TEXT NOT NULL,
255
+ type TEXT NOT NULL,
256
+ uri TEXT NOT NULL,
257
+ sha256 TEXT,
258
+ security_class TEXT NOT NULL DEFAULT 'internal',
259
+ retention TEXT NOT NULL DEFAULT 'permanent',
260
+ created_at TEXT NOT NULL
261
+ );
262
+ CREATE INDEX IF NOT EXISTS idx_artifacts_run ON artifacts(run_id, created_at);
263
+ CREATE TABLE IF NOT EXISTS context_snapshots (
264
+ id TEXT PRIMARY KEY,
265
+ run_id TEXT NOT NULL,
266
+ recipient TEXT NOT NULL,
267
+ fact_versions TEXT NOT NULL DEFAULT '[]',
268
+ base_sha TEXT,
269
+ prompt_sha256 TEXT NOT NULL,
270
+ estimated_tokens INTEGER NOT NULL,
271
+ excluded_json TEXT NOT NULL DEFAULT '{}',
272
+ created_at TEXT NOT NULL
273
+ );
274
+ CREATE INDEX IF NOT EXISTS idx_context_snapshots_run ON context_snapshots(run_id, created_at);
275
+ CREATE TABLE IF NOT EXISTS cleanup_plans (
276
+ id TEXT PRIMARY KEY,
277
+ project_root TEXT,
278
+ generated_at TEXT NOT NULL,
279
+ expires_at TEXT NOT NULL,
280
+ policy TEXT NOT NULL,
281
+ summary_json TEXT NOT NULL
282
+ );
283
+ CREATE TABLE IF NOT EXISTS cleanup_plan_items (
284
+ id TEXT PRIMARY KEY,
285
+ plan_id TEXT NOT NULL,
286
+ task_id TEXT NOT NULL,
287
+ verdict TEXT NOT NULL,
288
+ reasons_json TEXT NOT NULL,
289
+ fingerprint TEXT,
290
+ reclaimable_bytes INTEGER NOT NULL DEFAULT 0,
291
+ eligible_after TEXT,
292
+ applied_at TEXT,
293
+ applied_by TEXT,
294
+ UNIQUE(plan_id, task_id)
295
+ );
296
+ CREATE INDEX IF NOT EXISTS idx_cleanup_plan_items_plan ON cleanup_plan_items(plan_id, verdict);
297
+ CREATE INDEX IF NOT EXISTS idx_cleanup_plan_items_task ON cleanup_plan_items(task_id, applied_at);
298
+ `;
299
+
188
300
  // A session is a string on each task row; this table is what a session is
189
301
  // *about*. A main thread sets it once per batch, so a reader sees "给 12
190
302
  // 个接口补单测" instead of a bare id.
@@ -255,8 +367,20 @@ function initializeSchema(dbInstance) {
255
367
  if (columns.length === 0) dbInstance.exec(TASKS_DDL);
256
368
  else migrateTasksTable(dbInstance, columns);
257
369
  dbInstance.exec(TASK_EVENTS_DDL);
370
+ for (const [name, definition] of [
371
+ ["run_id", "TEXT"],
372
+ ["actor", "TEXT NOT NULL DEFAULT 'legacy'"],
373
+ ["payload_sha256", "TEXT"]
374
+ ]) {
375
+ if (!tableColumns(dbInstance, "task_events").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE task_events ADD COLUMN ${name} ${definition}`);
376
+ }
377
+ dbInstance.exec("UPDATE task_events SET actor = 'legacy' WHERE actor IS NULL");
258
378
  dbInstance.exec(TASK_EVENTS_INDEX_DDL);
259
379
  dbInstance.exec(TASKS_SESSION_INDEX_DDL);
380
+ 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 '[]'");
383
+ }
260
384
  dbInstance.exec(SESSIONS_DDL);
261
385
  for (const [name, definition] of [
262
386
  ["objective", "TEXT"], ["default_acceptance", "TEXT"],
@@ -276,6 +400,7 @@ function initializeSchema(dbInstance) {
276
400
  dbInstance.exec("ALTER TABLE side_sessions ADD COLUMN worker_run_count INTEGER;");
277
401
 
278
402
  }
403
+ backfillControlRecords(dbInstance);
279
404
  dbInstance.exec("COMMIT;");
280
405
  } catch (error) {
281
406
  try {
@@ -288,6 +413,55 @@ function initializeSchema(dbInstance) {
288
413
  });
289
414
  }
290
415
 
416
+ function stableId(prefix, value) {
417
+ return `${prefix}-${createHash("sha256").update(String(value)).digest("hex").slice(0, 24)}`;
418
+ }
419
+
420
+ function repoIdForRoot(root) {
421
+ return stableId("repo", resolve(root));
422
+ }
423
+
424
+ function workItemIdForTask(taskId) {
425
+ return `work-${taskId}`;
426
+ }
427
+
428
+ export function runIdFor(taskId, attempt) {
429
+ return `run-${taskId}-${attempt}`;
430
+ }
431
+
432
+ function ensureControlRecords(dbInstance, task) {
433
+ if (!task?.id || !task.project_root) return;
434
+ const now = new Date().toISOString();
435
+ const root = resolve(task.project_root);
436
+ const repoId = repoIdForRoot(root);
437
+ const workItemId = workItemIdForTask(task.id);
438
+ dbInstance.prepare(`
439
+ INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
440
+ VALUES (@id, NULL, @root, NULL, @now, @now)
441
+ ON CONFLICT(root) DO UPDATE SET updated_at = excluded.updated_at
442
+ `).run({ id: repoId, root, now });
443
+ dbInstance.prepare(`
444
+ INSERT INTO work_items (id, repo_id, task_id, parent_work_item_id, objective, owner, delivery_state, created_at, updated_at)
445
+ VALUES (@id, @repo_id, @task_id, NULL, @objective, NULL, @delivery_state, @now, @now)
446
+ ON CONFLICT(task_id) DO UPDATE SET
447
+ objective = COALESCE(excluded.objective, work_items.objective),
448
+ delivery_state = CASE WHEN work_items.delivery_state = 'draft' THEN excluded.delivery_state ELSE work_items.delivery_state END,
449
+ updated_at = excluded.updated_at
450
+ `).run({
451
+ id: workItemId,
452
+ repo_id: repoId,
453
+ task_id: task.id,
454
+ objective: task.goal_objective ?? task.title ?? null,
455
+ delivery_state: task.landed_at ? "landed" : "draft",
456
+ now
457
+ });
458
+ }
459
+
460
+ function backfillControlRecords(dbInstance) {
461
+ const rows = dbInstance.prepare("SELECT id,title,project_root,goal_objective,landed_at FROM tasks").all();
462
+ for (const row of rows) ensureControlRecords(dbInstance, row);
463
+ }
464
+
291
465
  function openDb() {
292
466
  if (db) return db;
293
467
  db = new DatabaseSync(dbPath);
@@ -477,6 +651,7 @@ function writeTaskNow(task) {
477
651
  params.phase = task.phase ?? null;
478
652
 
479
653
  stmt.run(params);
654
+ ensureControlRecords(openDb(), task);
480
655
  return task;
481
656
  }
482
657
 
@@ -752,14 +927,62 @@ export function taskRunPath(taskId) {
752
927
  return join(runsDir, `${taskId}.jsonl`);
753
928
  }
754
929
 
755
- export async function appendTaskEvent(taskId, event) {
930
+ export async function ensureRunRecord(task, attempt) {
756
931
  await ensureFilesystem();
932
+ if (!task?.id || !Number.isInteger(attempt) || attempt < 1) throw new Error("run record requires a task and positive attempt");
757
933
  const dbInstance = openDb();
758
- const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
934
+ ensureControlRecords(dbInstance, task);
935
+ const now = new Date().toISOString();
936
+ const id = runIdFor(task.id, attempt);
759
937
  dbInstance.prepare(`
760
- INSERT INTO task_events (task_id, seq, created_at, event_type, payload)
761
- VALUES (?, ?, ?, ?, ?)
762
- `).run(taskId, nextSeqRow.seq, new Date().toISOString(), event.type ?? "unknown", JSON.stringify(event));
938
+ INSERT INTO runs (id, task_id, work_item_id, attempt, codex_thread_id, worktree_path, branch, base_sha, run_status, started_at, finished_at)
939
+ VALUES (@id, @task_id, @work_item_id, @attempt, @codex_thread_id, @worktree_path, @branch, @base_sha, 'running', @started_at, NULL)
940
+ ON CONFLICT(task_id, attempt) DO UPDATE SET
941
+ codex_thread_id = COALESCE(excluded.codex_thread_id, runs.codex_thread_id),
942
+ worktree_path = COALESCE(excluded.worktree_path, runs.worktree_path),
943
+ base_sha = COALESCE(excluded.base_sha, runs.base_sha)
944
+ `).run({
945
+ id,
946
+ task_id: task.id,
947
+ work_item_id: workItemIdForTask(task.id),
948
+ attempt,
949
+ codex_thread_id: task.thread_id ?? null,
950
+ worktree_path: task.worktree_path ?? null,
951
+ branch: task.worktree_path ? `codex/${task.id}` : null,
952
+ base_sha: task.base_commit ?? null,
953
+ started_at: now
954
+ });
955
+ return id;
956
+ }
957
+
958
+ export async function completeRunRecord(task, attempt) {
959
+ await ensureFilesystem();
960
+ if (!task?.id || !Number.isInteger(attempt) || attempt < 1) return;
961
+ const now = task.completed_at ?? new Date().toISOString();
962
+ openDb().prepare(`
963
+ UPDATE runs SET codex_thread_id = @codex_thread_id,
964
+ run_status = @run_status, finished_at = @finished_at
965
+ WHERE task_id = @task_id AND attempt = @attempt
966
+ `).run({
967
+ task_id: task.id,
968
+ attempt,
969
+ codex_thread_id: task.thread_id ?? null,
970
+ run_status: task.status ?? "unknown",
971
+ finished_at: now
972
+ });
973
+ }
974
+
975
+ export async function appendTaskEvent(taskId, event, { runId = null, actor = "supervisor" } = {}) {
976
+ await ensureFilesystem();
977
+ const dbInstance = openDb();
978
+ const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
979
+ const payload = JSON.stringify(event);
980
+ const result = dbInstance.prepare(`
981
+ INSERT INTO task_events (task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256)
982
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
983
+ `).run(taskId, runId, nextSeqRow.seq, new Date().toISOString(), actor, event.type ?? "unknown", payload,
984
+ createHash("sha256").update(payload).digest("hex"));
985
+ return { id: Number(result.lastInsertRowid), run_id: runId, actor };
763
986
  }
764
987
 
765
988
  export async function readTaskEvents(taskId, limit = 100, kinds = null) {
@@ -780,6 +1003,192 @@ export async function readTaskEvents(taskId, limit = 100, kinds = null) {
780
1003
  return rows.reverse().map((row) => JSON.parse(row.payload));
781
1004
  }
782
1005
 
1006
+ export async function readTaskEventRecords(taskId, limit = 100) {
1007
+ await ensureFilesystem();
1008
+ const rows = openDb().prepare(`
1009
+ SELECT id, task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256
1010
+ FROM task_events WHERE task_id = ? ORDER BY seq DESC LIMIT ?
1011
+ `).all(taskId, limit);
1012
+ return rows.reverse().map((row) => ({
1013
+ ...row,
1014
+ event: JSON.parse(row.payload)
1015
+ }));
1016
+ }
1017
+
1018
+ export async function getWorkItemForTask(taskId) {
1019
+ await ensureFilesystem();
1020
+ return openDb().prepare("SELECT * FROM work_items WHERE task_id = ?").get(taskId) ?? null;
1021
+ }
1022
+
1023
+ export async function recordFact({
1024
+ workItemId,
1025
+ scopeType,
1026
+ scopeId,
1027
+ key,
1028
+ value,
1029
+ state = "candidate",
1030
+ sourceEventId = null,
1031
+ validForSha = null,
1032
+ watchedPaths = [],
1033
+ expiresAt = null,
1034
+ supersedesId = null,
1035
+ verifiedAt = null
1036
+ }) {
1037
+ await ensureFilesystem();
1038
+ if (!workItemId || !scopeType || !scopeId || !key) throw new Error("fact requires workItemId, scopeType, scopeId and key");
1039
+ if (!["candidate", "verified", "expired", "revoked"].includes(state)) throw new Error("invalid fact state");
1040
+ if (!Array.isArray(watchedPaths) || watchedPaths.some((path) => typeof path !== "string")) throw new Error("watchedPaths must be a string list");
1041
+ const now = new Date().toISOString();
1042
+ const id = randomUUID();
1043
+ 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)
1046
+ `).run({
1047
+ id,
1048
+ work_item_id: workItemId,
1049
+ scope_type: scopeType,
1050
+ scope_id: scopeId,
1051
+ key,
1052
+ value_json: JSON.stringify(value),
1053
+ state,
1054
+ source_event_id: sourceEventId,
1055
+ valid_for_sha: validForSha,
1056
+ watched_paths: JSON.stringify(watchedPaths.map((path) => resolve(path))),
1057
+ expires_at: expiresAt,
1058
+ supersedes_id: supersedesId,
1059
+ created_at: now,
1060
+ verified_at: verifiedAt ?? (state === "verified" ? now : null)
1061
+ });
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 };
1063
+ }
1064
+
1065
+ function pathsOverlap(left, right) {
1066
+ const normalize = (path) => process.platform === "win32" ? path.replace(/\\/g, "/").toLowerCase() : path;
1067
+ const a = normalize(left).replace(/\/$/, "");
1068
+ const b = normalize(right).replace(/\/$/, "");
1069
+ return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
1070
+ }
1071
+
1072
+ export async function listContextFacts({ taskId, baseSha, ownedPaths = [], dependencyTaskIds = [] }) {
1073
+ await ensureFilesystem();
1074
+ const workItem = await getWorkItemForTask(taskId);
1075
+ if (!workItem) return [];
1076
+ const dependencyItems = dependencyTaskIds.length === 0
1077
+ ? []
1078
+ : openDb().prepare(`SELECT id FROM work_items WHERE task_id IN (${dependencyTaskIds.map(() => "?").join(",")})`).all(...dependencyTaskIds).map((row) => row.id);
1079
+ const rows = openDb().prepare("SELECT * FROM facts WHERE state = 'verified' ORDER BY created_at ASC").all();
1080
+ const now = Date.now();
1081
+ return rows.filter((row) => {
1082
+ if (row.expires_at && Date.parse(row.expires_at) <= now) return false;
1083
+ if (row.scope_type === "work_item") return row.scope_id === workItem.id;
1084
+ if (row.scope_type === "dependency") return dependencyItems.includes(row.scope_id);
1085
+ if (row.scope_type !== "repo_verified" || row.scope_id !== workItem.repo_id) return false;
1086
+ const watched = decodeJson(row.watched_paths, []);
1087
+ 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
+ }));
1093
+ }
1094
+
1095
+ export async function createContextSnapshot({ runId, recipient = "worker", factIds = [], baseSha = null, prompt, estimatedTokens, excluded = {} }) {
1096
+ await ensureFilesystem();
1097
+ if (!runId || typeof prompt !== "string") throw new Error("context snapshot requires runId and prompt");
1098
+ const now = new Date().toISOString();
1099
+ const id = randomUUID();
1100
+ openDb().prepare(`
1101
+ INSERT INTO context_snapshots (id, run_id, recipient, fact_versions, base_sha, prompt_sha256, estimated_tokens, excluded_json, created_at)
1102
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1103
+ `).run(id, runId, recipient, JSON.stringify(factIds), baseSha,
1104
+ createHash("sha256").update(prompt).digest("hex"), estimatedTokens, JSON.stringify(excluded), now);
1105
+ return { id, run_id: runId, recipient, fact_versions: factIds, base_sha: baseSha, estimated_tokens: estimatedTokens, created_at: now };
1106
+ }
1107
+
1108
+ export async function latestContextSnapshotForTask(taskId) {
1109
+ await ensureFilesystem();
1110
+ return openDb().prepare(`
1111
+ SELECT s.* FROM context_snapshots s JOIN runs r ON r.id = s.run_id
1112
+ WHERE r.task_id = ? ORDER BY s.created_at DESC LIMIT 1
1113
+ `).get(taskId) ?? null;
1114
+ }
1115
+
1116
+ export async function getFact(factId) {
1117
+ await ensureFilesystem();
1118
+ const row = openDb().prepare("SELECT * FROM facts WHERE id = ?").get(factId);
1119
+ if (!row) return null;
1120
+ return {
1121
+ ...row,
1122
+ value: decodeJson(row.value_json, null),
1123
+ watched_paths: decodeJson(row.watched_paths, [])
1124
+ };
1125
+ }
1126
+
1127
+ export async function updateWorkItemDelivery(taskId, deliveryState) {
1128
+ await ensureFilesystem();
1129
+ if (!["draft", "verified", "landed", "push_verified", "cleanup_eligible", "cleanup_removed", "needs_attention"].includes(deliveryState)) {
1130
+ throw new Error("invalid delivery state");
1131
+ }
1132
+ const result = openDb().prepare("UPDATE work_items SET delivery_state = ?, updated_at = ? WHERE task_id = ?")
1133
+ .run(deliveryState, new Date().toISOString(), taskId);
1134
+ return result.changes > 0;
1135
+ }
1136
+
1137
+ export async function saveCleanupPlan(plan) {
1138
+ await ensureFilesystem();
1139
+ const dbInstance = openDb();
1140
+ dbInstance.exec("BEGIN IMMEDIATE");
1141
+ try {
1142
+ dbInstance.prepare(`
1143
+ INSERT INTO cleanup_plans (id, project_root, generated_at, expires_at, policy, summary_json)
1144
+ VALUES (?, ?, ?, ?, ?, ?)
1145
+ `).run(plan.id, plan.project_root, plan.generated_at, plan.expires_at, plan.policy, JSON.stringify(plan.summary));
1146
+ const insert = dbInstance.prepare(`
1147
+ INSERT INTO cleanup_plan_items (id, plan_id, task_id, verdict, reasons_json, fingerprint, reclaimable_bytes, eligible_after, applied_at, applied_by)
1148
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)
1149
+ `);
1150
+ for (const item of plan.items) {
1151
+ item.id = item.id ?? randomUUID();
1152
+ insert.run(item.id, plan.id, item.task_id, item.verdict, JSON.stringify(item.reasons), item.fingerprint, item.reclaimable_bytes, item.eligible_after);
1153
+ if (item.verdict === "safe") {
1154
+ dbInstance.prepare("UPDATE work_items SET delivery_state = 'cleanup_eligible', updated_at = ? WHERE task_id = ? AND delivery_state = 'push_verified'")
1155
+ .run(new Date().toISOString(), item.task_id);
1156
+ }
1157
+ }
1158
+ dbInstance.exec("COMMIT");
1159
+ } catch (error) {
1160
+ dbInstance.exec("ROLLBACK");
1161
+ throw error;
1162
+ }
1163
+ }
1164
+
1165
+ export async function getCleanupPlan(planId) {
1166
+ await ensureFilesystem();
1167
+ const plan = openDb().prepare("SELECT * FROM cleanup_plans WHERE id = ?").get(planId);
1168
+ if (!plan) return null;
1169
+ const items = openDb().prepare("SELECT * FROM cleanup_plan_items WHERE plan_id = ? ORDER BY task_id").all(planId).map((item) => ({
1170
+ ...item,
1171
+ reasons: decodeJson(item.reasons_json, [])
1172
+ }));
1173
+ return { ...plan, summary: decodeJson(plan.summary_json, {}), items };
1174
+ }
1175
+
1176
+ export async function markCleanupPlanItemApplied(itemId, actor = "main_thread") {
1177
+ await ensureFilesystem();
1178
+ const now = new Date().toISOString();
1179
+ openDb().prepare("UPDATE cleanup_plan_items SET applied_at = ?, applied_by = ? WHERE id = ? AND applied_at IS NULL")
1180
+ .run(now, actor, itemId);
1181
+ return now;
1182
+ }
1183
+
1184
+ export async function readCleanupHistory(taskId = null, limit = 100) {
1185
+ await ensureFilesystem();
1186
+ const rows = taskId
1187
+ ? openDb().prepare(`SELECT i.*, p.generated_at, p.expires_at, p.policy FROM cleanup_plan_items i JOIN cleanup_plans p ON p.id = i.plan_id WHERE i.task_id = ? ORDER BY p.generated_at DESC LIMIT ?`).all(taskId, limit)
1188
+ : openDb().prepare(`SELECT i.*, p.generated_at, p.expires_at, p.policy FROM cleanup_plan_items i JOIN cleanup_plans p ON p.id = i.plan_id ORDER BY p.generated_at DESC LIMIT ?`).all(limit);
1189
+ return rows.map((row) => ({ ...row, reasons: decodeJson(row.reasons_json, []) }));
1190
+ }
1191
+
783
1192
  export async function listTaskEventKinds(taskId) {
784
1193
  await ensureFilesystem();
785
1194
  return openDb().prepare(`
@@ -0,0 +1,111 @@
1
+ import { createHash } from "node:crypto";
2
+ import { resolve } from "node:path";
3
+ import { commandFailed } from "./event-parser.js";
4
+
5
+ export const PREFLIGHT_VERSION = 1;
6
+
7
+ function stableValue(value) {
8
+ if (Array.isArray(value)) return value.map(stableValue);
9
+ if (value && typeof value === "object") {
10
+ return Object.fromEntries(
11
+ Object.keys(value)
12
+ .sort()
13
+ .map((key) => [key, stableValue(value[key])])
14
+ );
15
+ }
16
+ return value;
17
+ }
18
+
19
+ function uniqueSorted(values) {
20
+ return [...new Set((values ?? []).map((value) => String(value)))].sort();
21
+ }
22
+
23
+ export function normalizeObservedCommand(command) {
24
+ const text = String(command ?? "").trim();
25
+ const wrapped = text.match(/^(?:[^\s]+\/)?(?:zsh|bash|sh)\s+-l?c\s+(['"])([\s\S]*)\1$/);
26
+ return wrapped ? wrapped[2].trim() : text;
27
+ }
28
+
29
+ export function buildRuntimeContract({
30
+ projectRoot,
31
+ baseCommit,
32
+ sandbox,
33
+ ownedPaths,
34
+ allowedCommands,
35
+ networkAccess,
36
+ writableRoots,
37
+ context,
38
+ contracts
39
+ }) {
40
+ return stableValue({
41
+ version: PREFLIGHT_VERSION,
42
+ project_root: resolve(projectRoot),
43
+ base_commit: baseCommit ?? null,
44
+ sandbox,
45
+ owned_paths: uniqueSorted(ownedPaths),
46
+ allowed_commands: uniqueSorted(allowedCommands),
47
+ network_access: networkAccess === true,
48
+ writable_roots: uniqueSorted(writableRoots),
49
+ context: (context ?? [])
50
+ .map((entry) => ({ path: resolve(entry.path), sha256: entry.sha256 ?? null }))
51
+ .sort((left, right) => left.path.localeCompare(right.path)),
52
+ contracts: uniqueSorted(contracts)
53
+ });
54
+ }
55
+
56
+ export function runtimeContractHash(contract) {
57
+ return createHash("sha256").update(JSON.stringify(stableValue(contract))).digest("hex");
58
+ }
59
+
60
+ export function createPreflightMetadata(contract, probeCommands) {
61
+ const commands = uniqueSorted(probeCommands);
62
+ if (commands.length === 0) throw new Error("preflight requires at least one probe command");
63
+ return {
64
+ version: PREFLIGHT_VERSION,
65
+ contract,
66
+ contract_hash: runtimeContractHash(contract),
67
+ probe_commands: commands
68
+ };
69
+ }
70
+
71
+ export function readPreflightResult(task) {
72
+ const metadata = task?.guard_policy?.preflight;
73
+ if (!metadata?.contract_hash || !Array.isArray(metadata.probe_commands)) {
74
+ return { error: "not_a_preflight", status: "unknown" };
75
+ }
76
+
77
+ const commands = Array.isArray(task.commands) ? task.commands : [];
78
+ const probes = metadata.probe_commands.map((command) => {
79
+ const matches = commands.filter((entry) => normalizeObservedCommand(entry.command) === command);
80
+ const result = matches.at(-1) ?? null;
81
+ return {
82
+ command,
83
+ executed: Boolean(result),
84
+ exit_code: result?.exit_code ?? null,
85
+ status: result?.status ?? null,
86
+ passed: Boolean(result) && !commandFailed(result)
87
+ };
88
+ });
89
+ const terminal = ["completed", "failed", "cancelled", "lost"].includes(task.status);
90
+ const failedCommands = commands.filter(commandFailed);
91
+ let status = "running";
92
+ if (terminal) {
93
+ status = task.status === "completed" && task.exit_code === 0 && probes.every((probe) => probe.passed) && failedCommands.length === 0
94
+ ? "passed"
95
+ : "failed";
96
+ }
97
+ return {
98
+ task_id: task.id,
99
+ status,
100
+ terminal,
101
+ contract_hash: metadata.contract_hash,
102
+ contract: metadata.contract,
103
+ probes,
104
+ failed_commands: failedCommands.map((entry) => ({
105
+ command: entry.command,
106
+ exit_code: entry.exit_code ?? null,
107
+ status: entry.status ?? null,
108
+ output_tail: entry.output_tail ?? null
109
+ }))
110
+ };
111
+ }