codex-supervisor-mcp 0.10.3 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +25 -7
- package/README.md +26 -17
- package/package.json +3 -1
- package/skills/codex-supervisor/SKILL.md +22 -15
- package/src/cleanup-hint.js +3 -2
- package/src/cleanup-plan.js +67 -7
- package/src/cleanup.js +48 -40
- package/src/codex-runner.js +219 -120
- package/src/context-compiler.js +3 -1
- package/src/handoff.js +9 -1
- package/src/landing.js +16 -4
- package/src/mcp-server.js +383 -37
- package/src/overview-delta.js +37 -5
- package/src/paths.js +2 -0
- package/src/prompt.js +6 -3
- package/src/runner-adapter.js +100 -0
- package/src/sandbox-roots.js +19 -3
- package/src/side-chat.js +10 -38
- package/src/task-store.js +494 -67
- package/src/worker-preflight.js +15 -3
- package/src/workspace-kind.js +167 -0
package/src/task-store.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
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 { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
3
|
import { DatabaseSync } from "node:sqlite";
|
|
4
|
-
import {
|
|
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";
|
|
12
|
+
import { buildHandoff } from "./handoff.js";
|
|
10
13
|
|
|
11
14
|
let db;
|
|
12
15
|
|
|
@@ -43,7 +46,13 @@ const POST_V1_COLUMNS = [
|
|
|
43
46
|
["landed_branch", "TEXT"],
|
|
44
47
|
["push_verified_at", "TEXT"],
|
|
45
48
|
["push_remote", "TEXT"],
|
|
46
|
-
["push_branch", "TEXT"]
|
|
49
|
+
["push_branch", "TEXT"],
|
|
50
|
+
["push_remote_head", "TEXT"]
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
const TASK_EXTRA_COLUMNS = [
|
|
54
|
+
["workspace_kind", "TEXT NOT NULL DEFAULT 'legacy'"],
|
|
55
|
+
["workspace_metadata", "TEXT"]
|
|
47
56
|
];
|
|
48
57
|
|
|
49
58
|
const TASKS_DDL = `
|
|
@@ -55,6 +64,8 @@ const TASKS_DDL = `
|
|
|
55
64
|
phase TEXT,
|
|
56
65
|
cwd TEXT NOT NULL,
|
|
57
66
|
project_root TEXT NOT NULL,
|
|
67
|
+
workspace_kind TEXT NOT NULL DEFAULT 'legacy',
|
|
68
|
+
workspace_metadata TEXT,
|
|
58
69
|
sandbox TEXT NOT NULL,
|
|
59
70
|
model TEXT,
|
|
60
71
|
reasoning_effort TEXT NOT NULL DEFAULT 'high',
|
|
@@ -109,19 +120,20 @@ const TASKS_DDL = `
|
|
|
109
120
|
push_verified_at TEXT,
|
|
110
121
|
push_remote TEXT,
|
|
111
122
|
push_branch TEXT,
|
|
123
|
+
push_remote_head TEXT,
|
|
112
124
|
run_log TEXT NOT NULL
|
|
113
125
|
);
|
|
114
126
|
`;
|
|
115
127
|
|
|
116
128
|
const TASK_COLUMNS = [
|
|
117
|
-
"id", "title", "worker", "status", "phase", "cwd", "project_root", "sandbox", "model",
|
|
129
|
+
"id", "title", "worker", "status", "phase", "cwd", "project_root", "workspace_kind", "workspace_metadata", "sandbox", "model",
|
|
118
130
|
"reasoning_effort", "skip_git_repo_check", "prompt", "changed_files", "commands",
|
|
119
131
|
"created_at", "updated_at", "started_at", "completed_at", "pid", "run_host_pid", "attention_reason", "run_evidence", "guard_policy", "input_context", "exit_code", "signal",
|
|
120
132
|
"stderr_tail", "last_event_at", "last_event_type", "last_message", "current_action",
|
|
121
133
|
"current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
|
|
122
134
|
"depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
|
|
123
135
|
"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"
|
|
136
|
+
"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
137
|
];
|
|
126
138
|
|
|
127
139
|
function tableColumns(dbInstance, tableName) {
|
|
@@ -143,8 +155,9 @@ function migrateTasksTable(dbInstance, columns) {
|
|
|
143
155
|
|
|
144
156
|
const selectExpression = (name) => {
|
|
145
157
|
if (legacyNames.has(name)) return name;
|
|
146
|
-
const definition = POST_V1_COLUMNS.find(([columnName]) => columnName === name);
|
|
158
|
+
const definition = [...POST_V1_COLUMNS, ...TASK_EXTRA_COLUMNS].find(([columnName]) => columnName === name);
|
|
147
159
|
if (definition && definition[1].includes("DEFAULT '[]'")) return "'[]'";
|
|
160
|
+
if (definition && definition[1].includes("DEFAULT 'legacy'")) return "'legacy'";
|
|
148
161
|
if (definition && definition[1].includes("DEFAULT 0")) return "0";
|
|
149
162
|
return "NULL";
|
|
150
163
|
};
|
|
@@ -241,14 +254,19 @@ const CONTROL_DDL = `
|
|
|
241
254
|
value_json TEXT NOT NULL,
|
|
242
255
|
state TEXT NOT NULL,
|
|
243
256
|
source_event_id INTEGER,
|
|
257
|
+
source_artifact_id TEXT,
|
|
244
258
|
valid_for_sha TEXT,
|
|
259
|
+
valid_for_content_hash TEXT,
|
|
260
|
+
valid_for_manifest_hash TEXT,
|
|
245
261
|
watched_paths TEXT NOT NULL DEFAULT '[]',
|
|
246
262
|
expires_at TEXT,
|
|
247
263
|
supersedes_id TEXT,
|
|
248
264
|
created_at TEXT NOT NULL,
|
|
249
|
-
verified_at TEXT
|
|
265
|
+
verified_at TEXT,
|
|
266
|
+
verified_by TEXT
|
|
250
267
|
);
|
|
251
268
|
CREATE INDEX IF NOT EXISTS idx_facts_scope ON facts(scope_type, scope_id, state);
|
|
269
|
+
CREATE INDEX IF NOT EXISTS idx_facts_supersedes ON facts(supersedes_id, state);
|
|
252
270
|
CREATE TABLE IF NOT EXISTS artifacts (
|
|
253
271
|
id TEXT PRIMARY KEY,
|
|
254
272
|
run_id TEXT NOT NULL,
|
|
@@ -260,6 +278,25 @@ const CONTROL_DDL = `
|
|
|
260
278
|
created_at TEXT NOT NULL
|
|
261
279
|
);
|
|
262
280
|
CREATE INDEX IF NOT EXISTS idx_artifacts_run ON artifacts(run_id, created_at);
|
|
281
|
+
CREATE TABLE IF NOT EXISTS review_findings (
|
|
282
|
+
id TEXT PRIMARY KEY,
|
|
283
|
+
subject_task_id TEXT NOT NULL,
|
|
284
|
+
verifier_task_id TEXT NOT NULL UNIQUE,
|
|
285
|
+
subject_run_id TEXT,
|
|
286
|
+
subject_base_sha TEXT,
|
|
287
|
+
subject_fingerprint TEXT,
|
|
288
|
+
status TEXT NOT NULL,
|
|
289
|
+
verdict TEXT,
|
|
290
|
+
reason TEXT,
|
|
291
|
+
evidence_artifact_id TEXT,
|
|
292
|
+
finding_event_id INTEGER,
|
|
293
|
+
resolved_at TEXT,
|
|
294
|
+
resolved_by TEXT,
|
|
295
|
+
resolution TEXT,
|
|
296
|
+
created_at TEXT NOT NULL,
|
|
297
|
+
updated_at TEXT NOT NULL
|
|
298
|
+
);
|
|
299
|
+
CREATE INDEX IF NOT EXISTS idx_review_findings_subject ON review_findings(subject_task_id, created_at);
|
|
263
300
|
CREATE TABLE IF NOT EXISTS context_snapshots (
|
|
264
301
|
id TEXT PRIMARY KEY,
|
|
265
302
|
run_id TEXT NOT NULL,
|
|
@@ -377,9 +414,18 @@ function initializeSchema(dbInstance) {
|
|
|
377
414
|
dbInstance.exec("UPDATE task_events SET actor = 'legacy' WHERE actor IS NULL");
|
|
378
415
|
dbInstance.exec(TASK_EVENTS_INDEX_DDL);
|
|
379
416
|
dbInstance.exec(TASKS_SESSION_INDEX_DDL);
|
|
417
|
+
for (const [name, definition] of TASK_EXTRA_COLUMNS) {
|
|
418
|
+
if (!tableColumns(dbInstance, "tasks").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE tasks ADD COLUMN ${name} ${definition}`);
|
|
419
|
+
}
|
|
380
420
|
dbInstance.exec(CONTROL_DDL);
|
|
381
|
-
|
|
382
|
-
|
|
421
|
+
for (const [name, definition] of [
|
|
422
|
+
["watched_paths", "TEXT NOT NULL DEFAULT '[]'"],
|
|
423
|
+
["source_artifact_id", "TEXT"],
|
|
424
|
+
["valid_for_content_hash", "TEXT"],
|
|
425
|
+
["valid_for_manifest_hash", "TEXT"],
|
|
426
|
+
["verified_by", "TEXT"]
|
|
427
|
+
]) {
|
|
428
|
+
if (!tableColumns(dbInstance, "facts").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE facts ADD COLUMN ${name} ${definition}`);
|
|
383
429
|
}
|
|
384
430
|
dbInstance.exec(SESSIONS_DDL);
|
|
385
431
|
for (const [name, definition] of [
|
|
@@ -421,6 +467,34 @@ function repoIdForRoot(root) {
|
|
|
421
467
|
return stableId("repo", resolve(root));
|
|
422
468
|
}
|
|
423
469
|
|
|
470
|
+
function canonicalizeRemote(value) {
|
|
471
|
+
let raw = String(value ?? "").trim();
|
|
472
|
+
if (!raw) return null;
|
|
473
|
+
const scp = raw.match(/^((?:[^@/:\s]+@)?)([^:/\s]+):(.+)$/);
|
|
474
|
+
if (scp && !raw.includes("://")) raw = `ssh://${scp[1]}${scp[2]}/${scp[3]}`;
|
|
475
|
+
try {
|
|
476
|
+
const parsed = new URL(raw);
|
|
477
|
+
if (parsed.protocol === "file:") {
|
|
478
|
+
const path = resolve(decodeURIComponent(parsed.pathname)).replace(/\.git$/i, "");
|
|
479
|
+
return `file://${path}`;
|
|
480
|
+
}
|
|
481
|
+
if (!parsed.hostname || !["ssh:", "https:", "http:"].includes(parsed.protocol)) return null;
|
|
482
|
+
const path = decodeURIComponent(parsed.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
483
|
+
if (!path) return null;
|
|
484
|
+
return `${parsed.protocol}//${parsed.hostname.toLowerCase()}${parsed.port ? `:${parsed.port}` : ""}/${path}`;
|
|
485
|
+
} catch {
|
|
486
|
+
return isAbsolute(raw) ? `file://${resolve(raw).replace(/\.git$/i, "")}` : null;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function canonicalRemoteForRoot(root) {
|
|
491
|
+
try {
|
|
492
|
+
return canonicalizeRemote(git(root, ["remote", "get-url", "origin"]));
|
|
493
|
+
} catch {
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
424
498
|
function workItemIdForTask(taskId) {
|
|
425
499
|
return `work-${taskId}`;
|
|
426
500
|
}
|
|
@@ -429,24 +503,26 @@ export function runIdFor(taskId, attempt) {
|
|
|
429
503
|
return `run-${taskId}-${attempt}`;
|
|
430
504
|
}
|
|
431
505
|
|
|
432
|
-
function ensureControlRecords(dbInstance, task) {
|
|
506
|
+
function ensureControlRecords(dbInstance, task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
|
|
433
507
|
if (!task?.id || !task.project_root) return;
|
|
434
508
|
const now = new Date().toISOString();
|
|
435
509
|
const root = resolve(task.project_root);
|
|
436
510
|
const repoId = repoIdForRoot(root);
|
|
437
511
|
const workItemId = workItemIdForTask(task.id);
|
|
438
|
-
dbInstance.prepare(
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
512
|
+
const repo = dbInstance.prepare("SELECT id FROM repos WHERE root = ?").get(root);
|
|
513
|
+
if (!repo || refreshRepo) {
|
|
514
|
+
const resolvedRemote = canonicalRemote === undefined ? canonicalRemoteForRoot(root) : canonicalRemote;
|
|
515
|
+
dbInstance.prepare(`
|
|
516
|
+
INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
|
|
517
|
+
VALUES (@id, @canonical_remote, @root, NULL, @now, @now)
|
|
518
|
+
ON CONFLICT(root) DO UPDATE SET canonical_remote = excluded.canonical_remote, updated_at = excluded.updated_at
|
|
519
|
+
`).run({ id: repoId, canonical_remote: resolvedRemote, root, now });
|
|
520
|
+
}
|
|
521
|
+
const workItem = dbInstance.prepare("SELECT id FROM work_items WHERE task_id = ?").get(task.id);
|
|
522
|
+
if (workItem) return;
|
|
443
523
|
dbInstance.prepare(`
|
|
444
524
|
INSERT INTO work_items (id, repo_id, task_id, parent_work_item_id, objective, owner, delivery_state, created_at, updated_at)
|
|
445
525
|
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
526
|
`).run({
|
|
451
527
|
id: workItemId,
|
|
452
528
|
repo_id: repoId,
|
|
@@ -458,7 +534,12 @@ function ensureControlRecords(dbInstance, task) {
|
|
|
458
534
|
}
|
|
459
535
|
|
|
460
536
|
function backfillControlRecords(dbInstance) {
|
|
461
|
-
const rows = dbInstance.prepare(
|
|
537
|
+
const rows = dbInstance.prepare(`
|
|
538
|
+
SELECT t.id,t.title,t.project_root,t.goal_objective,t.landed_at
|
|
539
|
+
FROM tasks AS t
|
|
540
|
+
LEFT JOIN work_items AS w ON w.task_id = t.id
|
|
541
|
+
WHERE w.task_id IS NULL
|
|
542
|
+
`).all();
|
|
462
543
|
for (const row of rows) ensureControlRecords(dbInstance, row);
|
|
463
544
|
}
|
|
464
545
|
|
|
@@ -478,6 +559,7 @@ function openDb() {
|
|
|
478
559
|
async function ensureFilesystem() {
|
|
479
560
|
await mkdir(dataDir, { recursive: true });
|
|
480
561
|
await mkdir(runsDir, { recursive: true });
|
|
562
|
+
await mkdir(artifactsDir, { recursive: true });
|
|
481
563
|
}
|
|
482
564
|
|
|
483
565
|
function encodeJson(value) {
|
|
@@ -498,6 +580,7 @@ function rowToTask(row) {
|
|
|
498
580
|
const nativeGoal = readNativeGoal(row.thread_id);
|
|
499
581
|
return {
|
|
500
582
|
...row,
|
|
583
|
+
workspace_kind: row.workspace_kind ?? "legacy",
|
|
501
584
|
skip_git_repo_check: Boolean(row.skip_git_repo_check),
|
|
502
585
|
changed_files: decodeJson(row.changed_files, []),
|
|
503
586
|
commands: decodeJson(row.commands, []),
|
|
@@ -509,6 +592,7 @@ function rowToTask(row) {
|
|
|
509
592
|
run_evidence: decodeJson(row.run_evidence, null),
|
|
510
593
|
guard_policy: decodeJson(row.guard_policy, null),
|
|
511
594
|
input_context: decodeJson(row.input_context, null),
|
|
595
|
+
workspace_metadata: decodeJson(row.workspace_metadata, null),
|
|
512
596
|
pid: row.pid ?? null,
|
|
513
597
|
exit_code: row.exit_code ?? null,
|
|
514
598
|
phase: row.phase ?? null,
|
|
@@ -616,10 +700,10 @@ export async function reconcileDetachedActiveTasks() {
|
|
|
616
700
|
|
|
617
701
|
export async function writeTask(task) {
|
|
618
702
|
await ensureFilesystem();
|
|
619
|
-
return writeTaskNow(task);
|
|
703
|
+
return runWithRetry(openDb(), () => writeTaskNow(task));
|
|
620
704
|
}
|
|
621
705
|
|
|
622
|
-
function writeTaskNow(task) {
|
|
706
|
+
function writeTaskNow(task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
|
|
623
707
|
const placeholders = TASK_COLUMNS.map((name) => `@${name}`).join(", ");
|
|
624
708
|
const updates = TASK_COLUMNS
|
|
625
709
|
.filter((name) => name !== "id" && name !== "created_at")
|
|
@@ -634,6 +718,7 @@ function writeTaskNow(task) {
|
|
|
634
718
|
const params = {};
|
|
635
719
|
for (const name of TASK_COLUMNS) params[name] = task[name] ?? null;
|
|
636
720
|
params.reasoning_effort = task.reasoning_effort ?? "high";
|
|
721
|
+
params.workspace_kind = task.workspace_kind ?? "legacy";
|
|
637
722
|
params.skip_git_repo_check = task.skip_git_repo_check ? 1 : 0;
|
|
638
723
|
params.changed_files = encodeJson(task.changed_files);
|
|
639
724
|
params.commands = encodeJson(task.commands);
|
|
@@ -647,11 +732,12 @@ function writeTaskNow(task) {
|
|
|
647
732
|
params.run_evidence = task.run_evidence ? JSON.stringify(task.run_evidence) : null;
|
|
648
733
|
params.guard_policy = task.guard_policy ? JSON.stringify(task.guard_policy) : null;
|
|
649
734
|
params.input_context = task.input_context ? JSON.stringify(task.input_context) : null;
|
|
735
|
+
params.workspace_metadata = task.workspace_metadata ? JSON.stringify(task.workspace_metadata) : null;
|
|
650
736
|
params.run_count = task.run_count ?? 0;
|
|
651
737
|
params.phase = task.phase ?? null;
|
|
652
738
|
|
|
653
739
|
stmt.run(params);
|
|
654
|
-
ensureControlRecords(openDb(), task);
|
|
740
|
+
ensureControlRecords(openDb(), task, { refreshRepo, canonicalRemote });
|
|
655
741
|
return task;
|
|
656
742
|
}
|
|
657
743
|
|
|
@@ -676,10 +762,11 @@ function checkOwnership(taskId, incoming) {
|
|
|
676
762
|
|
|
677
763
|
export async function reserveTaskOwnership(task) {
|
|
678
764
|
await ensureFilesystem();
|
|
765
|
+
const canonicalRemote = task?.project_root ? canonicalRemoteForRoot(resolve(task.project_root)) : null;
|
|
679
766
|
const connection=openDb();
|
|
680
767
|
return runWithRetry(connection,()=>{
|
|
681
768
|
connection.exec("BEGIN IMMEDIATE");
|
|
682
|
-
try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task);connection.exec("COMMIT");return task; }
|
|
769
|
+
try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task, { refreshRepo: true, canonicalRemote });connection.exec("COMMIT");return task; }
|
|
683
770
|
catch(error){connection.exec("ROLLBACK");throw error;}
|
|
684
771
|
});
|
|
685
772
|
}
|
|
@@ -931,35 +1018,38 @@ export async function ensureRunRecord(task, attempt) {
|
|
|
931
1018
|
await ensureFilesystem();
|
|
932
1019
|
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) throw new Error("run record requires a task and positive attempt");
|
|
933
1020
|
const dbInstance = openDb();
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
1021
|
+
return runWithRetry(dbInstance, () => {
|
|
1022
|
+
ensureControlRecords(dbInstance, task);
|
|
1023
|
+
const now = new Date().toISOString();
|
|
1024
|
+
const id = runIdFor(task.id, attempt);
|
|
1025
|
+
dbInstance.prepare(`
|
|
938
1026
|
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
1027
|
VALUES (@id, @task_id, @work_item_id, @attempt, @codex_thread_id, @worktree_path, @branch, @base_sha, 'running', @started_at, NULL)
|
|
940
1028
|
ON CONFLICT(task_id, attempt) DO UPDATE SET
|
|
941
1029
|
codex_thread_id = COALESCE(excluded.codex_thread_id, runs.codex_thread_id),
|
|
942
1030
|
worktree_path = COALESCE(excluded.worktree_path, runs.worktree_path),
|
|
943
1031
|
base_sha = COALESCE(excluded.base_sha, runs.base_sha)
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
1032
|
+
`).run({
|
|
1033
|
+
id,
|
|
1034
|
+
task_id: task.id,
|
|
1035
|
+
work_item_id: workItemIdForTask(task.id),
|
|
1036
|
+
attempt,
|
|
1037
|
+
codex_thread_id: task.thread_id ?? null,
|
|
1038
|
+
worktree_path: task.worktree_path ?? null,
|
|
1039
|
+
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
1040
|
+
base_sha: task.base_commit ?? null,
|
|
1041
|
+
started_at: now
|
|
1042
|
+
});
|
|
1043
|
+
return id;
|
|
954
1044
|
});
|
|
955
|
-
return id;
|
|
956
1045
|
}
|
|
957
1046
|
|
|
958
1047
|
export async function completeRunRecord(task, attempt) {
|
|
959
1048
|
await ensureFilesystem();
|
|
960
1049
|
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) return;
|
|
961
1050
|
const now = task.completed_at ?? new Date().toISOString();
|
|
962
|
-
openDb()
|
|
1051
|
+
const dbInstance = openDb();
|
|
1052
|
+
runWithRetry(dbInstance, () => dbInstance.prepare(`
|
|
963
1053
|
UPDATE runs SET codex_thread_id = @codex_thread_id,
|
|
964
1054
|
run_status = @run_status, finished_at = @finished_at
|
|
965
1055
|
WHERE task_id = @task_id AND attempt = @attempt
|
|
@@ -969,20 +1059,39 @@ export async function completeRunRecord(task, attempt) {
|
|
|
969
1059
|
codex_thread_id: task.thread_id ?? null,
|
|
970
1060
|
run_status: task.status ?? "unknown",
|
|
971
1061
|
finished_at: now
|
|
972
|
-
});
|
|
1062
|
+
}));
|
|
973
1063
|
}
|
|
974
1064
|
|
|
975
|
-
export async function
|
|
1065
|
+
export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor" } = {}) {
|
|
976
1066
|
await ensureFilesystem();
|
|
1067
|
+
if (!Array.isArray(events) || events.length === 0) return [];
|
|
977
1068
|
const dbInstance = openDb();
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
1069
|
+
return runWithRetry(dbInstance, () => {
|
|
1070
|
+
dbInstance.exec("BEGIN IMMEDIATE");
|
|
1071
|
+
try {
|
|
1072
|
+
const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
|
|
1073
|
+
const insert = dbInstance.prepare(`
|
|
981
1074
|
INSERT INTO task_events (task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256)
|
|
982
1075
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
1076
|
+
`);
|
|
1077
|
+
const createdAt = new Date().toISOString();
|
|
1078
|
+
const records = events.map((event, index) => {
|
|
1079
|
+
const payload = JSON.stringify(event);
|
|
1080
|
+
const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", payload,
|
|
1081
|
+
createHash("sha256").update(payload).digest("hex"));
|
|
1082
|
+
return { id: Number(result.lastInsertRowid), run_id: runId, actor };
|
|
1083
|
+
});
|
|
1084
|
+
dbInstance.exec("COMMIT");
|
|
1085
|
+
return records;
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
dbInstance.exec("ROLLBACK");
|
|
1088
|
+
throw error;
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
export async function appendTaskEvent(taskId, event, options = {}) {
|
|
1094
|
+
return (await appendTaskEvents(taskId, [event], options))[0];
|
|
986
1095
|
}
|
|
987
1096
|
|
|
988
1097
|
export async function readTaskEvents(taskId, limit = 100, kinds = null) {
|
|
@@ -1028,11 +1137,15 @@ export async function recordFact({
|
|
|
1028
1137
|
value,
|
|
1029
1138
|
state = "candidate",
|
|
1030
1139
|
sourceEventId = null,
|
|
1140
|
+
sourceArtifactId = null,
|
|
1031
1141
|
validForSha = null,
|
|
1142
|
+
validForContentHash = null,
|
|
1143
|
+
validForManifestHash = null,
|
|
1032
1144
|
watchedPaths = [],
|
|
1033
1145
|
expiresAt = null,
|
|
1034
1146
|
supersedesId = null,
|
|
1035
|
-
verifiedAt = null
|
|
1147
|
+
verifiedAt = null,
|
|
1148
|
+
verifiedBy = null
|
|
1036
1149
|
}) {
|
|
1037
1150
|
await ensureFilesystem();
|
|
1038
1151
|
if (!workItemId || !scopeType || !scopeId || !key) throw new Error("fact requires workItemId, scopeType, scopeId and key");
|
|
@@ -1041,8 +1154,8 @@ export async function recordFact({
|
|
|
1041
1154
|
const now = new Date().toISOString();
|
|
1042
1155
|
const id = randomUUID();
|
|
1043
1156
|
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)
|
|
1157
|
+
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)
|
|
1158
|
+
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
1159
|
`).run({
|
|
1047
1160
|
id,
|
|
1048
1161
|
work_item_id: workItemId,
|
|
@@ -1052,14 +1165,18 @@ export async function recordFact({
|
|
|
1052
1165
|
value_json: JSON.stringify(value),
|
|
1053
1166
|
state,
|
|
1054
1167
|
source_event_id: sourceEventId,
|
|
1168
|
+
source_artifact_id: sourceArtifactId,
|
|
1055
1169
|
valid_for_sha: validForSha,
|
|
1056
|
-
|
|
1170
|
+
valid_for_content_hash: validForContentHash,
|
|
1171
|
+
valid_for_manifest_hash: validForManifestHash,
|
|
1172
|
+
watched_paths: JSON.stringify(watchedPaths.map((path) => isAbsolute(path) ? resolve(path) : path)),
|
|
1057
1173
|
expires_at: expiresAt,
|
|
1058
1174
|
supersedes_id: supersedesId,
|
|
1059
1175
|
created_at: now,
|
|
1060
|
-
verified_at: verifiedAt ?? (state === "verified" ? now : null)
|
|
1176
|
+
verified_at: verifiedAt ?? (state === "verified" ? now : null),
|
|
1177
|
+
verified_by: verifiedBy ?? (state === "verified" ? "supervisor" : null)
|
|
1061
1178
|
});
|
|
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 };
|
|
1179
|
+
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
1180
|
}
|
|
1064
1181
|
|
|
1065
1182
|
function pathsOverlap(left, right) {
|
|
@@ -1069,27 +1186,139 @@ function pathsOverlap(left, right) {
|
|
|
1069
1186
|
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
1070
1187
|
}
|
|
1071
1188
|
|
|
1189
|
+
function repoRelativePaths(projectRoot, paths) {
|
|
1190
|
+
return (paths ?? []).flatMap((path) => {
|
|
1191
|
+
if (typeof path !== "string" || !path.trim()) return [];
|
|
1192
|
+
const candidate = isAbsolute(path) ? relative(projectRoot, path) : path;
|
|
1193
|
+
const normalized = candidate.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
|
|
1194
|
+
return !normalized || normalized === ".." || normalized.startsWith("../") ? [] : [normalized];
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
function git(cwd, args) {
|
|
1199
|
+
return execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", cwd, ...args], {
|
|
1200
|
+
encoding: "utf8",
|
|
1201
|
+
timeout: 15000,
|
|
1202
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
1203
|
+
}).trim();
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
function shaCoversBase(projectRoot, validForSha, baseSha) {
|
|
1207
|
+
if (!validForSha || !baseSha) return true;
|
|
1208
|
+
try {
|
|
1209
|
+
git(projectRoot, ["merge-base", "--is-ancestor", validForSha, baseSha]);
|
|
1210
|
+
return true;
|
|
1211
|
+
} catch {
|
|
1212
|
+
return false;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
function watchedPathsChanged(projectRoot, validForSha, baseSha, watchedPaths) {
|
|
1217
|
+
if (!validForSha || !baseSha || watchedPaths.length === 0) return false;
|
|
1218
|
+
try {
|
|
1219
|
+
const relativePaths = repoRelativePaths(projectRoot, watchedPaths);
|
|
1220
|
+
if (relativePaths.length === 0) return true;
|
|
1221
|
+
return Boolean(git(projectRoot, ["diff", "--name-only", validForSha, baseSha, "--", ...relativePaths]));
|
|
1222
|
+
} catch {
|
|
1223
|
+
return true;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
async function currentWorkspaceManifest(task) {
|
|
1228
|
+
const metadata = task.workspace_metadata;
|
|
1229
|
+
if (!metadata?.source_root || !Array.isArray(metadata.manifest_paths) || metadata.manifest_paths.length === 0) return null;
|
|
1230
|
+
try {
|
|
1231
|
+
return await captureWorkspaceManifest(metadata.source_root, metadata.manifest_paths);
|
|
1232
|
+
} catch {
|
|
1233
|
+
return null;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
async function currentContextContentHash(task) {
|
|
1238
|
+
const context = task.input_context?.context ?? [];
|
|
1239
|
+
if (!Array.isArray(context) || context.length === 0) return null;
|
|
1240
|
+
try {
|
|
1241
|
+
return (await buildHandoff({ context }, { maxLines: 1, maxChars: 1 })).content_hash;
|
|
1242
|
+
} catch {
|
|
1243
|
+
return null;
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function markFactExpired(id) {
|
|
1248
|
+
openDb().prepare(`
|
|
1249
|
+
INSERT INTO facts (id, work_item_id, scope_type, scope_id, key, value_json, state, source_event_id, source_artifact_id,
|
|
1250
|
+
valid_for_sha, valid_for_content_hash, valid_for_manifest_hash, watched_paths, expires_at, supersedes_id, created_at, verified_at, verified_by)
|
|
1251
|
+
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,
|
|
1252
|
+
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
|
|
1253
|
+
FROM facts AS source
|
|
1254
|
+
WHERE source.id = ? AND source.state = 'verified'
|
|
1255
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = source.id AND transition.state IN ('expired', 'revoked'))
|
|
1256
|
+
`).run(randomUUID(), new Date().toISOString(), id);
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1072
1259
|
export async function listContextFacts({ taskId, baseSha, ownedPaths = [], dependencyTaskIds = [] }) {
|
|
1073
1260
|
await ensureFilesystem();
|
|
1074
1261
|
const workItem = await getWorkItemForTask(taskId);
|
|
1075
1262
|
if (!workItem) return [];
|
|
1263
|
+
const task = await getTask(taskId);
|
|
1264
|
+
if (!task) return [];
|
|
1076
1265
|
const dependencyItems = dependencyTaskIds.length === 0
|
|
1077
1266
|
? []
|
|
1078
1267
|
: 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(
|
|
1268
|
+
const rows = openDb().prepare(`
|
|
1269
|
+
SELECT facts.* FROM facts
|
|
1270
|
+
WHERE state = 'verified'
|
|
1271
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
1272
|
+
ORDER BY created_at ASC
|
|
1273
|
+
`).all();
|
|
1080
1274
|
const now = Date.now();
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1275
|
+
const workspaceManifest = await currentWorkspaceManifest(task);
|
|
1276
|
+
const contextContentHash = await currentContextContentHash(task);
|
|
1277
|
+
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
1278
|
+
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
1279
|
+
const ownedRelative = repoRelativePaths(task.project_root, ownedPaths);
|
|
1280
|
+
const visible = [];
|
|
1281
|
+
for (const row of rows) {
|
|
1086
1282
|
const watched = decodeJson(row.watched_paths, []);
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1283
|
+
const watchedRelative = repoRelativePaths(task.project_root, watched);
|
|
1284
|
+
const included = row.scope_type === "work_item" ? row.scope_id === workItem.id
|
|
1285
|
+
: row.scope_type === "dependency" ? dependencyItems.includes(row.scope_id)
|
|
1286
|
+
: row.scope_type === "repo_verified" && canonicalRemote && row.scope_id === canonicalRemote
|
|
1287
|
+
&& watchedRelative.length > 0 && watchedRelative.some((path) => ownedRelative.some((owned) => pathsOverlap(path, owned)));
|
|
1288
|
+
if (!included) continue;
|
|
1289
|
+
if (row.expires_at && Date.parse(row.expires_at) <= now) {
|
|
1290
|
+
markFactExpired(row.id);
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
if (!shaCoversBase(task.project_root, row.valid_for_sha, baseSha)) continue;
|
|
1294
|
+
if (watchedPathsChanged(task.project_root, row.valid_for_sha, baseSha, watchedRelative)) {
|
|
1295
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
if (row.valid_for_manifest_hash && (!workspaceManifest || workspaceManifest.sha256 !== row.valid_for_manifest_hash)) {
|
|
1299
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id && workspaceManifest) markFactExpired(row.id);
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
if (row.valid_for_content_hash && contextContentHash !== row.valid_for_content_hash) {
|
|
1303
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
1304
|
+
continue;
|
|
1305
|
+
}
|
|
1306
|
+
visible.push({
|
|
1307
|
+
...row,
|
|
1308
|
+
value: decodeJson(row.value_json, null),
|
|
1309
|
+
watched_paths: watched
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
return visible;
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
export async function countVerifiedFacts() {
|
|
1316
|
+
await ensureFilesystem();
|
|
1317
|
+
return openDb().prepare(`
|
|
1318
|
+
SELECT COUNT(*) AS count FROM facts
|
|
1319
|
+
WHERE state = 'verified'
|
|
1320
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
1321
|
+
`).get().count;
|
|
1093
1322
|
}
|
|
1094
1323
|
|
|
1095
1324
|
export async function createContextSnapshot({ runId, recipient = "worker", factIds = [], baseSha = null, prompt, estimatedTokens, excluded = {} }) {
|
|
@@ -1124,6 +1353,201 @@ export async function getFact(factId) {
|
|
|
1124
1353
|
};
|
|
1125
1354
|
}
|
|
1126
1355
|
|
|
1356
|
+
export async function getTaskForWorkItem(workItemId) {
|
|
1357
|
+
await ensureFilesystem();
|
|
1358
|
+
return openDb().prepare("SELECT * FROM tasks WHERE id = (SELECT task_id FROM work_items WHERE id = ?)").get(workItemId) ?? null;
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
export async function isFactRevoked(factId) {
|
|
1362
|
+
await ensureFilesystem();
|
|
1363
|
+
return Boolean(openDb().prepare("SELECT 1 FROM facts WHERE supersedes_id = ? AND state = 'revoked'").get(factId));
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
export async function getFactEffectiveState(factId) {
|
|
1367
|
+
await ensureFilesystem();
|
|
1368
|
+
const transition = openDb().prepare(`
|
|
1369
|
+
SELECT state FROM facts WHERE supersedes_id = ? AND state IN ('revoked', 'expired')
|
|
1370
|
+
ORDER BY CASE state WHEN 'revoked' THEN 0 ELSE 1 END, created_at DESC LIMIT 1
|
|
1371
|
+
`).get(factId);
|
|
1372
|
+
return transition?.state ?? null;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
export async function promoteCandidateFact({ factId, scopeType = "work_item", watchedPaths = null, expiresAt = null, sourceEventId = null, verifiedBy = "main_thread" }) {
|
|
1376
|
+
await ensureFilesystem();
|
|
1377
|
+
const source = await getFact(factId);
|
|
1378
|
+
if (!source) throw new Error(`fact not found: ${factId}`);
|
|
1379
|
+
if (await isFactRevoked(factId)) {
|
|
1380
|
+
const error = new Error(`fact ${factId} is already revoked`);
|
|
1381
|
+
error.code = "fact_already_revoked";
|
|
1382
|
+
throw error;
|
|
1383
|
+
}
|
|
1384
|
+
if (source.state !== "candidate") {
|
|
1385
|
+
const error = new Error(`only candidate facts may be promoted; ${factId} is ${source.state}`);
|
|
1386
|
+
error.code = "fact_not_candidate";
|
|
1387
|
+
throw error;
|
|
1388
|
+
}
|
|
1389
|
+
if (!['work_item', 'repo_verified'].includes(scopeType)) throw new Error("promotion scope must be work_item or repo_verified");
|
|
1390
|
+
const workItem = openDb().prepare("SELECT * FROM work_items WHERE id = ?").get(source.work_item_id);
|
|
1391
|
+
if (!workItem) throw new Error(`work item not found for fact: ${factId}`);
|
|
1392
|
+
const sourceTask = await getTaskForWorkItem(workItem.id);
|
|
1393
|
+
const paths = watchedPaths ?? source.watched_paths ?? [];
|
|
1394
|
+
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
1395
|
+
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
1396
|
+
const normalizedRepoPaths = sourceTask ? repoRelativePaths(sourceTask.project_root, paths) : [];
|
|
1397
|
+
if (scopeType === "repo_verified" && paths.length === 0) {
|
|
1398
|
+
const error = new Error("repo_verified promotion requires watchedPaths so unrelated work cannot inherit it");
|
|
1399
|
+
error.code = "repo_fact_requires_paths";
|
|
1400
|
+
throw error;
|
|
1401
|
+
}
|
|
1402
|
+
if (scopeType === "repo_verified" && !canonicalRemote) {
|
|
1403
|
+
const error = new Error("repo_verified promotion requires a canonical origin remote; facts from an unrecognized or missing remote stay work-scoped");
|
|
1404
|
+
error.code = "repo_fact_requires_canonical_remote";
|
|
1405
|
+
throw error;
|
|
1406
|
+
}
|
|
1407
|
+
if (scopeType === "repo_verified" && normalizedRepoPaths.length === 0) {
|
|
1408
|
+
const error = new Error("repo_verified watchedPaths must stay inside the repository root");
|
|
1409
|
+
error.code = "repo_fact_paths_outside_root";
|
|
1410
|
+
throw error;
|
|
1411
|
+
}
|
|
1412
|
+
return recordFact({
|
|
1413
|
+
workItemId: source.work_item_id,
|
|
1414
|
+
scopeType,
|
|
1415
|
+
scopeId: scopeType === "repo_verified" ? canonicalRemote : workItem.id,
|
|
1416
|
+
key: source.key,
|
|
1417
|
+
value: source.value,
|
|
1418
|
+
state: "verified",
|
|
1419
|
+
sourceEventId,
|
|
1420
|
+
sourceArtifactId: source.source_artifact_id ?? null,
|
|
1421
|
+
validForSha: source.valid_for_sha ?? null,
|
|
1422
|
+
validForContentHash: source.valid_for_content_hash ?? null,
|
|
1423
|
+
validForManifestHash: source.valid_for_manifest_hash ?? null,
|
|
1424
|
+
watchedPaths: scopeType === "repo_verified" ? normalizedRepoPaths : paths,
|
|
1425
|
+
expiresAt: expiresAt ?? source.expires_at ?? null,
|
|
1426
|
+
supersedesId: source.id,
|
|
1427
|
+
verifiedBy
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
export async function revokeFact(factId) {
|
|
1432
|
+
await ensureFilesystem();
|
|
1433
|
+
const source = await getFact(factId);
|
|
1434
|
+
if (!source) return null;
|
|
1435
|
+
if (!["candidate", "verified"].includes(source.state)) {
|
|
1436
|
+
const error = new Error(`only candidate or verified facts may be revoked; ${factId} is ${source.state}`);
|
|
1437
|
+
error.code = "fact_not_revocable";
|
|
1438
|
+
throw error;
|
|
1439
|
+
}
|
|
1440
|
+
if (await isFactRevoked(factId)) {
|
|
1441
|
+
const error = new Error(`fact ${factId} is already revoked`);
|
|
1442
|
+
error.code = "fact_already_revoked";
|
|
1443
|
+
throw error;
|
|
1444
|
+
}
|
|
1445
|
+
return recordFact({
|
|
1446
|
+
workItemId: source.work_item_id,
|
|
1447
|
+
scopeType: source.scope_type,
|
|
1448
|
+
scopeId: source.scope_id,
|
|
1449
|
+
key: source.key,
|
|
1450
|
+
value: source.value,
|
|
1451
|
+
state: "revoked",
|
|
1452
|
+
sourceEventId: source.source_event_id,
|
|
1453
|
+
sourceArtifactId: source.source_artifact_id,
|
|
1454
|
+
validForSha: source.valid_for_sha,
|
|
1455
|
+
validForContentHash: source.valid_for_content_hash,
|
|
1456
|
+
validForManifestHash: source.valid_for_manifest_hash,
|
|
1457
|
+
watchedPaths: source.watched_paths,
|
|
1458
|
+
expiresAt: source.expires_at,
|
|
1459
|
+
supersedesId: source.id,
|
|
1460
|
+
verifiedBy: "main_thread"
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
export async function recordJsonArtifact({ runId, type, value, securityClass = "internal", retention = "permanent" }) {
|
|
1465
|
+
await ensureFilesystem();
|
|
1466
|
+
if (!runId || !type) throw new Error("artifact requires runId and type");
|
|
1467
|
+
const id = randomUUID();
|
|
1468
|
+
const content = JSON.stringify(value, null, 2);
|
|
1469
|
+
const sha256 = createHash("sha256").update(content).digest("hex");
|
|
1470
|
+
const path = join(artifactsDir, `${id}.json`);
|
|
1471
|
+
await writeFile(path, content, { encoding: "utf8", mode: 0o600 });
|
|
1472
|
+
const now = new Date().toISOString();
|
|
1473
|
+
openDb().prepare(`
|
|
1474
|
+
INSERT INTO artifacts (id, run_id, type, uri, sha256, security_class, retention, created_at)
|
|
1475
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1476
|
+
`).run(id, runId, type, path, sha256, securityClass, retention, now);
|
|
1477
|
+
return { id, run_id: runId, type, uri: path, sha256, security_class: securityClass, retention, created_at: now };
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
export async function getArtifact(artifactId) {
|
|
1481
|
+
await ensureFilesystem();
|
|
1482
|
+
return openDb().prepare("SELECT * FROM artifacts WHERE id = ?").get(artifactId) ?? null;
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
export async function readArtifact(artifactId, maxChars = 12000) {
|
|
1486
|
+
const artifact = await getArtifact(artifactId);
|
|
1487
|
+
if (!artifact) return null;
|
|
1488
|
+
const artifactPath = relative(artifactsDir, resolve(artifact.uri));
|
|
1489
|
+
if (!artifactPath || artifactPath === ".." || artifactPath.startsWith(`..${sep}`) || isAbsolute(artifactPath)) {
|
|
1490
|
+
return { ...artifact, content: null, reason: "artifact_uri_not_managed" };
|
|
1491
|
+
}
|
|
1492
|
+
let content;
|
|
1493
|
+
try {
|
|
1494
|
+
content = await readFile(artifact.uri, "utf8");
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
return { ...artifact, content: null, reason: `artifact_unreadable: ${error.code ?? error.message}` };
|
|
1497
|
+
}
|
|
1498
|
+
const truncated = content.length > maxChars;
|
|
1499
|
+
return { ...artifact, content: truncated ? `${content.slice(0, maxChars)}…` : content, truncated };
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
export async function listArtifactsForTask(taskId, limit = 50) {
|
|
1503
|
+
await ensureFilesystem();
|
|
1504
|
+
return openDb().prepare(`
|
|
1505
|
+
SELECT a.* FROM artifacts a JOIN runs r ON r.id = a.run_id
|
|
1506
|
+
WHERE r.task_id = ? ORDER BY a.created_at DESC LIMIT ?
|
|
1507
|
+
`).all(taskId, limit);
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
export async function createReviewAssignment({ subjectTaskId, verifierTaskId, subjectRunId = null, subjectBaseSha = null, subjectFingerprint = null }) {
|
|
1511
|
+
await ensureFilesystem();
|
|
1512
|
+
const now = new Date().toISOString();
|
|
1513
|
+
const id = randomUUID();
|
|
1514
|
+
openDb().prepare(`
|
|
1515
|
+
INSERT INTO review_findings (id, subject_task_id, verifier_task_id, subject_run_id, subject_base_sha, subject_fingerprint, status, created_at, updated_at)
|
|
1516
|
+
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)
|
|
1517
|
+
`).run(id, subjectTaskId, verifierTaskId, subjectRunId, subjectBaseSha, subjectFingerprint, now, now);
|
|
1518
|
+
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 };
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
export async function getReviewByVerifierTask(verifierTaskId) {
|
|
1522
|
+
await ensureFilesystem();
|
|
1523
|
+
return openDb().prepare("SELECT * FROM review_findings WHERE verifier_task_id = ?").get(verifierTaskId) ?? null;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
export async function recordReviewFinding({ verifierTaskId, verdict, reason, evidenceArtifactId = null, findingEventId = null }) {
|
|
1527
|
+
await ensureFilesystem();
|
|
1528
|
+
if (!['passes', 'fails', 'inconclusive'].includes(verdict)) throw new Error("review verdict must be passes, fails or inconclusive");
|
|
1529
|
+
const now = new Date().toISOString();
|
|
1530
|
+
const result = openDb().prepare(`
|
|
1531
|
+
UPDATE review_findings
|
|
1532
|
+
SET status = 'recorded', verdict = ?, reason = ?, evidence_artifact_id = ?, finding_event_id = ?, updated_at = ?
|
|
1533
|
+
WHERE verifier_task_id = ? AND status = 'pending'
|
|
1534
|
+
`).run(verdict, reason, evidenceArtifactId, findingEventId, now, verifierTaskId);
|
|
1535
|
+
if (result.changes === 0) return null;
|
|
1536
|
+
return getReviewByVerifierTask(verifierTaskId);
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
export async function resolveReviewFinding({ verifierTaskId, resolution, resolvedBy = 'main_thread' }) {
|
|
1540
|
+
await ensureFilesystem();
|
|
1541
|
+
const now = new Date().toISOString();
|
|
1542
|
+
const result = openDb().prepare(`
|
|
1543
|
+
UPDATE review_findings
|
|
1544
|
+
SET status = 'resolved', resolution = ?, resolved_at = ?, resolved_by = ?, updated_at = ?
|
|
1545
|
+
WHERE verifier_task_id = ? AND status = 'recorded'
|
|
1546
|
+
`).run(resolution, now, resolvedBy, now, verifierTaskId);
|
|
1547
|
+
if (result.changes === 0) return null;
|
|
1548
|
+
return getReviewByVerifierTask(verifierTaskId);
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1127
1551
|
export async function updateWorkItemDelivery(taskId, deliveryState) {
|
|
1128
1552
|
await ensureFilesystem();
|
|
1129
1553
|
if (!["draft", "verified", "landed", "push_verified", "cleanup_eligible", "cleanup_removed", "needs_attention"].includes(deliveryState)) {
|
|
@@ -1153,6 +1577,9 @@ export async function saveCleanupPlan(plan) {
|
|
|
1153
1577
|
if (item.verdict === "safe") {
|
|
1154
1578
|
dbInstance.prepare("UPDATE work_items SET delivery_state = 'cleanup_eligible', updated_at = ? WHERE task_id = ? AND delivery_state = 'push_verified'")
|
|
1155
1579
|
.run(new Date().toISOString(), item.task_id);
|
|
1580
|
+
} else {
|
|
1581
|
+
dbInstance.prepare("UPDATE work_items SET delivery_state = 'push_verified', updated_at = ? WHERE task_id = ? AND delivery_state = 'cleanup_eligible'")
|
|
1582
|
+
.run(new Date().toISOString(), item.task_id);
|
|
1156
1583
|
}
|
|
1157
1584
|
}
|
|
1158
1585
|
dbInstance.exec("COMMIT");
|