codex-supervisor-mcp 0.13.4 → 0.13.6
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 +101 -297
- package/README.md +99 -310
- package/package.json +24 -63
- package/src/{acceptance.js → app/acceptance.js} +54 -68
- package/src/app/cancel.js +60 -0
- package/src/{cleanup-plan.js → app/cleanup-plan.js} +13 -14
- package/src/app/compose.js +7 -0
- package/src/{context-compiler.js → app/context-compiler.js} +7 -13
- package/src/app/dispatch.js +396 -0
- package/src/app/followup.js +98 -0
- package/src/app/land-chain.js +124 -0
- package/src/app/landing.js +357 -0
- package/src/app/ownership.js +57 -0
- package/src/app/rebase.js +216 -0
- package/src/app/resume.js +164 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/{side-chat.js → app/side-chat.js} +79 -266
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +119 -0
- package/src/app/worktree-setup.js +176 -0
- package/src/{acceptance-baseline.js → domain/acceptance-baseline.js} +2 -1
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/{overview-delta.js → domain/overview-delta.js} +5 -1
- package/src/domain/side-turn-view.js +73 -0
- package/src/{worker-preflight.js → domain/worker-preflight.js} +1 -1
- package/src/infra/git.js +30 -0
- package/src/infra/process.js +59 -0
- package/src/{sandbox-roots.js → infra/sandbox-roots.js} +2 -1
- package/src/{skill-sync.js → infra/skill-sync.js} +1 -1
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/events.js +146 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +172 -0
- package/src/infra/store/records.js +160 -0
- package/src/infra/store/runner-readers.js +16 -0
- package/src/infra/store/schema.js +306 -0
- package/src/infra/store/sessions.js +138 -0
- package/src/infra/store/tasks.js +307 -0
- package/src/{auto-update-worker.js → infra/update/auto-update-worker.js} +4 -4
- package/src/{auto-update.js → infra/update/auto-update.js} +3 -4
- package/src/{update-check.js → infra/update/update-check.js} +4 -4
- package/src/{workspace-kind.js → infra/workspace-kind.js} +5 -7
- package/src/{worktree.js → infra/worktree.js} +57 -42
- package/src/{acceptance-cli.js → interface/bin/acceptance-cli.js} +7 -3
- package/src/{cleanup.js → interface/bin/cleanup.js} +3 -2
- package/src/{monitor.jsx → interface/bin/monitor.jsx} +4 -1
- package/src/{setup.js → interface/bin/setup.js} +9 -8
- package/src/{stage.js → interface/bin/stage.js} +1 -1
- package/src/{web-server.js → interface/bin/web-server.js} +2 -2
- package/src/interface/mcp/meta.js +7 -0
- package/src/interface/mcp/result.js +34 -0
- package/src/interface/mcp/schemas.js +24 -0
- package/src/interface/mcp/server.js +94 -0
- package/src/interface/mcp/tools/delivery.js +197 -0
- package/src/interface/mcp/tools/dispatch.js +267 -0
- package/src/interface/mcp/tools/facts.js +239 -0
- package/src/interface/mcp/tools/overview.js +202 -0
- package/src/interface/mcp/tools/poll.js +62 -0
- package/src/interface/mcp/tools/results.js +270 -0
- package/src/interface/mcp/tools/review.js +135 -0
- package/src/interface/mcp/tools/wait.js +145 -0
- package/src/interface/mcp/update-state.js +34 -0
- package/src/interface/mcp/views/overview.js +183 -0
- package/src/interface/mcp/views/task.js +223 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +224 -0
- package/src/mcp-server.js +3 -2223
- package/src/run-host/entry.js +23 -0
- package/src/run-host/finalize.js +236 -0
- package/src/run-host/launch.js +63 -0
- package/src/run-host/live-run.js +73 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +76 -0
- package/src/run-host/track.js +128 -0
- package/src/{runner-adapter.js → runners/codex/adapter.js} +6 -6
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/{event-parser.js → runners/codex/event-parser.js} +57 -55
- package/src/{goal-store.js → runners/codex/goal-store.js} +2 -2
- package/src/{mcp-config.js → runners/codex/mcp-config.js} +1 -1
- package/src/codex-runner.js +0 -1586
- package/src/landing.js +0 -507
- package/src/task-store.js +0 -1800
- package/src/web-app.js +0 -425
- /package/src/{failure-class.js → domain/failure-class.js} +0 -0
- /package/src/{owned-changes.js → domain/owned-changes.js} +0 -0
- /package/src/{prompt.js → domain/prompt.js} +0 -0
- /package/src/{status.js → domain/status.js} +0 -0
- /package/src/{thread-health.js → domain/thread-health.js} +0 -0
- /package/src/{truncate.js → domain/truncate.js} +0 -0
- /package/src/{worker-changes.js → domain/worker-changes.js} +0 -0
- /package/src/{worker-env.js → domain/worker-env.js} +0 -0
- /package/src/{worker-report.js → domain/worker-report.js} +0 -0
- /package/src/{worker-report.schema.json → domain/worker-report.schema.json} +0 -0
- /package/src/{bin-resolver.js → infra/bin-resolver.js} +0 -0
- /package/src/{cleanup-hint.js → infra/cleanup-hint.js} +0 -0
- /package/src/{external-output.js → infra/external-output.js} +0 -0
- /package/src/{handoff.js → infra/handoff.js} +0 -0
- /package/src/{paths.js → infra/paths.js} +0 -0
- /package/src/{stage-store.js → infra/stage-store.js} +0 -0
- /package/src/{tool-guard.js → runners/codex/tool-guard.js} +0 -0
package/src/task-store.js
DELETED
|
@@ -1,1800 +0,0 @@
|
|
|
1
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
-
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
-
import { DatabaseSync } from "node:sqlite";
|
|
4
|
-
import { execFileSync } from "node:child_process";
|
|
5
|
-
import { artifactsDir, dataDir, dbPath, runsDir } from "./paths.js";
|
|
6
|
-
import { extractAgentMessage } from "./event-parser.js";
|
|
7
|
-
import { ACTIVE_STATUSES, PHASES, TERMINAL_STATUSES } from "./status.js";
|
|
8
|
-
import { readNativeGoal } from "./goal-store.js";
|
|
9
|
-
import { normalizeAcceptance } from "./acceptance.js";
|
|
10
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
11
|
-
import { captureWorkspaceManifest } from "./workspace-kind.js";
|
|
12
|
-
import { buildHandoff } from "./handoff.js";
|
|
13
|
-
import { readPreflightResult } from "./worker-preflight.js";
|
|
14
|
-
import { parseWorkerReportForRun } from "./worker-report.js";
|
|
15
|
-
|
|
16
|
-
let db;
|
|
17
|
-
|
|
18
|
-
// Columns added after v1. Kept in one place so the legacy rebuild and the
|
|
19
|
-
// fresh CREATE TABLE cannot drift apart.
|
|
20
|
-
const POST_V1_COLUMNS = [
|
|
21
|
-
["run_host_pid", "INTEGER"],
|
|
22
|
-
["attention_reason", "TEXT"],
|
|
23
|
-
["run_evidence", "TEXT"],
|
|
24
|
-
["guard_policy", "TEXT"],
|
|
25
|
-
["input_context", "TEXT"],
|
|
26
|
-
["resumed_from", "TEXT"],
|
|
27
|
-
["thread_id", "TEXT"],
|
|
28
|
-
["owned_paths", "TEXT NOT NULL DEFAULT '[]'"],
|
|
29
|
-
["depends_on", "TEXT NOT NULL DEFAULT '[]'"],
|
|
30
|
-
["goal_objective", "TEXT"],
|
|
31
|
-
["goal_token_budget", "INTEGER"],
|
|
32
|
-
["goal_status", "TEXT"],
|
|
33
|
-
["goal_tokens_used", "INTEGER"],
|
|
34
|
-
["goal_time_used_seconds", "INTEGER"],
|
|
35
|
-
["goal_updated_at", "TEXT"],
|
|
36
|
-
["run_count", "INTEGER NOT NULL DEFAULT 0"],
|
|
37
|
-
["cancel_requested_at", "TEXT"],
|
|
38
|
-
["notices", "TEXT"],
|
|
39
|
-
["session_id", "TEXT"],
|
|
40
|
-
["base_commit", "TEXT"],
|
|
41
|
-
["acceptance", "TEXT"],
|
|
42
|
-
["acceptance_local", "TEXT"],
|
|
43
|
-
["session_policy_revision", "INTEGER"],
|
|
44
|
-
["acceptance_timeout_ms", "INTEGER"],
|
|
45
|
-
["acceptance_results", "TEXT"],
|
|
46
|
-
["landed_at", "TEXT"],
|
|
47
|
-
["landed_head", "TEXT"],
|
|
48
|
-
["landed_branch", "TEXT"],
|
|
49
|
-
["push_verified_at", "TEXT"],
|
|
50
|
-
["push_remote", "TEXT"],
|
|
51
|
-
["push_branch", "TEXT"],
|
|
52
|
-
["push_remote_head", "TEXT"]
|
|
53
|
-
];
|
|
54
|
-
|
|
55
|
-
const TASK_EXTRA_COLUMNS = [
|
|
56
|
-
["workspace_kind", "TEXT NOT NULL DEFAULT 'legacy'"],
|
|
57
|
-
["workspace_metadata", "TEXT"]
|
|
58
|
-
];
|
|
59
|
-
|
|
60
|
-
const TASKS_DDL = `
|
|
61
|
-
CREATE TABLE IF NOT EXISTS tasks (
|
|
62
|
-
id TEXT PRIMARY KEY,
|
|
63
|
-
title TEXT,
|
|
64
|
-
worker TEXT NOT NULL,
|
|
65
|
-
status TEXT NOT NULL,
|
|
66
|
-
phase TEXT,
|
|
67
|
-
cwd TEXT NOT NULL,
|
|
68
|
-
project_root TEXT NOT NULL,
|
|
69
|
-
workspace_kind TEXT NOT NULL DEFAULT 'legacy',
|
|
70
|
-
workspace_metadata TEXT,
|
|
71
|
-
sandbox TEXT NOT NULL,
|
|
72
|
-
model TEXT,
|
|
73
|
-
reasoning_effort TEXT NOT NULL DEFAULT 'high',
|
|
74
|
-
skip_git_repo_check INTEGER NOT NULL DEFAULT 1,
|
|
75
|
-
prompt TEXT NOT NULL,
|
|
76
|
-
changed_files TEXT NOT NULL DEFAULT '[]',
|
|
77
|
-
commands TEXT NOT NULL DEFAULT '[]',
|
|
78
|
-
created_at TEXT NOT NULL,
|
|
79
|
-
updated_at TEXT NOT NULL,
|
|
80
|
-
started_at TEXT,
|
|
81
|
-
completed_at TEXT,
|
|
82
|
-
pid INTEGER,
|
|
83
|
-
run_host_pid INTEGER,
|
|
84
|
-
attention_reason TEXT,
|
|
85
|
-
run_evidence TEXT,
|
|
86
|
-
guard_policy TEXT,
|
|
87
|
-
input_context TEXT,
|
|
88
|
-
exit_code INTEGER,
|
|
89
|
-
signal TEXT,
|
|
90
|
-
stderr_tail TEXT,
|
|
91
|
-
last_event_at TEXT,
|
|
92
|
-
last_event_type TEXT,
|
|
93
|
-
last_message TEXT,
|
|
94
|
-
current_action TEXT,
|
|
95
|
-
current_command TEXT,
|
|
96
|
-
error TEXT,
|
|
97
|
-
followup_of TEXT,
|
|
98
|
-
resumed_from TEXT,
|
|
99
|
-
session_id TEXT,
|
|
100
|
-
thread_id TEXT,
|
|
101
|
-
owned_paths TEXT NOT NULL DEFAULT '[]',
|
|
102
|
-
depends_on TEXT NOT NULL DEFAULT '[]',
|
|
103
|
-
goal_objective TEXT,
|
|
104
|
-
goal_token_budget INTEGER,
|
|
105
|
-
goal_status TEXT,
|
|
106
|
-
goal_tokens_used INTEGER,
|
|
107
|
-
goal_time_used_seconds INTEGER,
|
|
108
|
-
goal_updated_at TEXT,
|
|
109
|
-
run_count INTEGER NOT NULL DEFAULT 0,
|
|
110
|
-
cancel_requested_at TEXT,
|
|
111
|
-
notices TEXT,
|
|
112
|
-
worktree_path TEXT,
|
|
113
|
-
base_commit TEXT,
|
|
114
|
-
acceptance TEXT,
|
|
115
|
-
acceptance_local TEXT,
|
|
116
|
-
session_policy_revision INTEGER,
|
|
117
|
-
acceptance_timeout_ms INTEGER,
|
|
118
|
-
acceptance_results TEXT,
|
|
119
|
-
landed_at TEXT,
|
|
120
|
-
landed_head TEXT,
|
|
121
|
-
landed_branch TEXT,
|
|
122
|
-
push_verified_at TEXT,
|
|
123
|
-
push_remote TEXT,
|
|
124
|
-
push_branch TEXT,
|
|
125
|
-
push_remote_head TEXT,
|
|
126
|
-
run_log TEXT NOT NULL
|
|
127
|
-
);
|
|
128
|
-
`;
|
|
129
|
-
|
|
130
|
-
const TASK_COLUMNS = [
|
|
131
|
-
"id", "title", "worker", "status", "phase", "cwd", "project_root", "workspace_kind", "workspace_metadata", "sandbox", "model",
|
|
132
|
-
"reasoning_effort", "skip_git_repo_check", "prompt", "changed_files", "commands",
|
|
133
|
-
"created_at", "updated_at", "started_at", "completed_at", "pid", "run_host_pid", "attention_reason", "run_evidence", "guard_policy", "input_context", "exit_code", "signal",
|
|
134
|
-
"stderr_tail", "last_event_at", "last_event_type", "last_message", "current_action",
|
|
135
|
-
"current_command", "error", "followup_of", "resumed_from", "session_id", "thread_id", "owned_paths",
|
|
136
|
-
"depends_on", "goal_objective", "goal_token_budget", "goal_status", "goal_tokens_used",
|
|
137
|
-
"goal_time_used_seconds", "goal_updated_at", "run_count", "cancel_requested_at",
|
|
138
|
-
"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"
|
|
139
|
-
];
|
|
140
|
-
|
|
141
|
-
function tableColumns(dbInstance, tableName) {
|
|
142
|
-
return dbInstance.prepare(`PRAGMA table_info(${tableName})`).all();
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// v1 stored progress phases ("editing", "command", "reporting") in the status
|
|
146
|
-
// column and required phase to be non-null. Both have to change, and SQLite
|
|
147
|
-
// cannot relax NOT NULL in place, so the table is rebuilt once.
|
|
148
|
-
function migrateTasksTable(dbInstance, columns) {
|
|
149
|
-
const phaseColumn = columns.find((column) => column.name === "phase");
|
|
150
|
-
const isCurrentSchema = POST_V1_COLUMNS.every(([name]) => columns.some((column) => column.name === name))
|
|
151
|
-
&& phaseColumn
|
|
152
|
-
&& !phaseColumn.notnull;
|
|
153
|
-
if (isCurrentSchema) return { migrated: false, rows: 0 };
|
|
154
|
-
|
|
155
|
-
const legacyNames = new Set(columns.map((column) => column.name));
|
|
156
|
-
const rows = dbInstance.prepare("SELECT COUNT(*) AS count FROM tasks").get().count;
|
|
157
|
-
|
|
158
|
-
const selectExpression = (name) => {
|
|
159
|
-
if (legacyNames.has(name)) return name;
|
|
160
|
-
const definition = [...POST_V1_COLUMNS, ...TASK_EXTRA_COLUMNS].find(([columnName]) => columnName === name);
|
|
161
|
-
if (definition && definition[1].includes("DEFAULT '[]'")) return "'[]'";
|
|
162
|
-
if (definition && definition[1].includes("DEFAULT 'legacy'")) return "'legacy'";
|
|
163
|
-
if (definition && definition[1].includes("DEFAULT 0")) return "0";
|
|
164
|
-
return "NULL";
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
const statusExpression = legacyNames.has("status")
|
|
168
|
-
? `CASE WHEN status IN ('editing','command','command_completed','reporting') THEN 'running' ELSE status END`
|
|
169
|
-
: "'failed'";
|
|
170
|
-
|
|
171
|
-
const phaseExpression = legacyNames.has("phase")
|
|
172
|
-
? `CASE
|
|
173
|
-
WHEN status IN ('editing','command','reporting') THEN status
|
|
174
|
-
WHEN status = 'command_completed' THEN 'command'
|
|
175
|
-
WHEN status = 'running' THEN CASE WHEN phase IN (${PHASES.map((p) => `'${p}'`).join(",")}) THEN phase ELSE 'starting' END
|
|
176
|
-
ELSE NULL
|
|
177
|
-
END`
|
|
178
|
-
: "NULL";
|
|
179
|
-
|
|
180
|
-
{
|
|
181
|
-
dbInstance.exec("ALTER TABLE tasks RENAME TO tasks_legacy_v1;");
|
|
182
|
-
dbInstance.exec(TASKS_DDL);
|
|
183
|
-
const selectList = TASK_COLUMNS.map((name) => {
|
|
184
|
-
if (name === "status") return `${statusExpression} AS status`;
|
|
185
|
-
if (name === "phase") return `${phaseExpression} AS phase`;
|
|
186
|
-
return `${selectExpression(name)} AS ${name}`;
|
|
187
|
-
}).join(", ");
|
|
188
|
-
dbInstance.exec(`INSERT INTO tasks (${TASK_COLUMNS.join(", ")}) SELECT ${selectList} FROM tasks_legacy_v1;`);
|
|
189
|
-
dbInstance.exec("DROP TABLE tasks_legacy_v1;");
|
|
190
|
-
}
|
|
191
|
-
return { migrated: true, rows };
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
const TASK_EVENTS_DDL = `
|
|
195
|
-
CREATE TABLE IF NOT EXISTS task_events (
|
|
196
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
197
|
-
task_id TEXT NOT NULL,
|
|
198
|
-
run_id TEXT,
|
|
199
|
-
seq INTEGER NOT NULL,
|
|
200
|
-
created_at TEXT NOT NULL,
|
|
201
|
-
actor TEXT NOT NULL DEFAULT 'legacy',
|
|
202
|
-
event_type TEXT NOT NULL,
|
|
203
|
-
payload TEXT NOT NULL,
|
|
204
|
-
payload_sha256 TEXT
|
|
205
|
-
);
|
|
206
|
-
`;
|
|
207
|
-
|
|
208
|
-
const TASK_EVENTS_INDEX_DDL =
|
|
209
|
-
"CREATE INDEX IF NOT EXISTS idx_task_events_task_seq ON task_events(task_id, seq);";
|
|
210
|
-
|
|
211
|
-
const TASKS_SESSION_INDEX_DDL =
|
|
212
|
-
"CREATE INDEX IF NOT EXISTS idx_tasks_session ON tasks(session_id);";
|
|
213
|
-
|
|
214
|
-
const CONTROL_DDL = `
|
|
215
|
-
CREATE TABLE IF NOT EXISTS repos (
|
|
216
|
-
id TEXT PRIMARY KEY,
|
|
217
|
-
canonical_remote TEXT,
|
|
218
|
-
root TEXT NOT NULL UNIQUE,
|
|
219
|
-
default_branch TEXT,
|
|
220
|
-
created_at TEXT NOT NULL,
|
|
221
|
-
updated_at TEXT NOT NULL
|
|
222
|
-
);
|
|
223
|
-
CREATE TABLE IF NOT EXISTS work_items (
|
|
224
|
-
id TEXT PRIMARY KEY,
|
|
225
|
-
repo_id TEXT NOT NULL,
|
|
226
|
-
task_id TEXT NOT NULL UNIQUE,
|
|
227
|
-
parent_work_item_id TEXT,
|
|
228
|
-
objective TEXT,
|
|
229
|
-
owner TEXT,
|
|
230
|
-
delivery_state TEXT NOT NULL DEFAULT 'draft',
|
|
231
|
-
created_at TEXT NOT NULL,
|
|
232
|
-
updated_at TEXT NOT NULL
|
|
233
|
-
);
|
|
234
|
-
CREATE INDEX IF NOT EXISTS idx_work_items_repo ON work_items(repo_id, created_at);
|
|
235
|
-
CREATE TABLE IF NOT EXISTS runs (
|
|
236
|
-
id TEXT PRIMARY KEY,
|
|
237
|
-
task_id TEXT NOT NULL,
|
|
238
|
-
work_item_id TEXT NOT NULL,
|
|
239
|
-
attempt INTEGER NOT NULL,
|
|
240
|
-
codex_thread_id TEXT,
|
|
241
|
-
worktree_path TEXT,
|
|
242
|
-
branch TEXT,
|
|
243
|
-
base_sha TEXT,
|
|
244
|
-
run_status TEXT NOT NULL,
|
|
245
|
-
started_at TEXT NOT NULL,
|
|
246
|
-
finished_at TEXT,
|
|
247
|
-
UNIQUE(task_id, attempt)
|
|
248
|
-
);
|
|
249
|
-
CREATE INDEX IF NOT EXISTS idx_runs_work_item ON runs(work_item_id, attempt);
|
|
250
|
-
CREATE TABLE IF NOT EXISTS facts (
|
|
251
|
-
id TEXT PRIMARY KEY,
|
|
252
|
-
work_item_id TEXT NOT NULL,
|
|
253
|
-
scope_type TEXT NOT NULL,
|
|
254
|
-
scope_id TEXT NOT NULL,
|
|
255
|
-
key TEXT NOT NULL,
|
|
256
|
-
value_json TEXT NOT NULL,
|
|
257
|
-
state TEXT NOT NULL,
|
|
258
|
-
source_event_id INTEGER,
|
|
259
|
-
source_artifact_id TEXT,
|
|
260
|
-
valid_for_sha TEXT,
|
|
261
|
-
valid_for_content_hash TEXT,
|
|
262
|
-
valid_for_manifest_hash TEXT,
|
|
263
|
-
watched_paths TEXT NOT NULL DEFAULT '[]',
|
|
264
|
-
expires_at TEXT,
|
|
265
|
-
supersedes_id TEXT,
|
|
266
|
-
created_at TEXT NOT NULL,
|
|
267
|
-
verified_at TEXT,
|
|
268
|
-
verified_by TEXT
|
|
269
|
-
);
|
|
270
|
-
CREATE INDEX IF NOT EXISTS idx_facts_scope ON facts(scope_type, scope_id, state);
|
|
271
|
-
CREATE INDEX IF NOT EXISTS idx_facts_supersedes ON facts(supersedes_id, state);
|
|
272
|
-
CREATE TABLE IF NOT EXISTS artifacts (
|
|
273
|
-
id TEXT PRIMARY KEY,
|
|
274
|
-
run_id TEXT NOT NULL,
|
|
275
|
-
type TEXT NOT NULL,
|
|
276
|
-
uri TEXT NOT NULL,
|
|
277
|
-
sha256 TEXT,
|
|
278
|
-
security_class TEXT NOT NULL DEFAULT 'internal',
|
|
279
|
-
retention TEXT NOT NULL DEFAULT 'permanent',
|
|
280
|
-
created_at TEXT NOT NULL
|
|
281
|
-
);
|
|
282
|
-
CREATE INDEX IF NOT EXISTS idx_artifacts_run ON artifacts(run_id, created_at);
|
|
283
|
-
CREATE TABLE IF NOT EXISTS review_findings (
|
|
284
|
-
id TEXT PRIMARY KEY,
|
|
285
|
-
subject_task_id TEXT NOT NULL,
|
|
286
|
-
verifier_task_id TEXT NOT NULL UNIQUE,
|
|
287
|
-
subject_run_id TEXT,
|
|
288
|
-
subject_base_sha TEXT,
|
|
289
|
-
subject_fingerprint TEXT,
|
|
290
|
-
status TEXT NOT NULL,
|
|
291
|
-
verdict TEXT,
|
|
292
|
-
reason TEXT,
|
|
293
|
-
evidence_artifact_id TEXT,
|
|
294
|
-
finding_event_id INTEGER,
|
|
295
|
-
resolved_at TEXT,
|
|
296
|
-
resolved_by TEXT,
|
|
297
|
-
resolution TEXT,
|
|
298
|
-
created_at TEXT NOT NULL,
|
|
299
|
-
updated_at TEXT NOT NULL
|
|
300
|
-
);
|
|
301
|
-
CREATE INDEX IF NOT EXISTS idx_review_findings_subject ON review_findings(subject_task_id, created_at);
|
|
302
|
-
CREATE TABLE IF NOT EXISTS context_snapshots (
|
|
303
|
-
id TEXT PRIMARY KEY,
|
|
304
|
-
run_id TEXT NOT NULL,
|
|
305
|
-
recipient TEXT NOT NULL,
|
|
306
|
-
fact_versions TEXT NOT NULL DEFAULT '[]',
|
|
307
|
-
base_sha TEXT,
|
|
308
|
-
prompt_sha256 TEXT NOT NULL,
|
|
309
|
-
estimated_tokens INTEGER NOT NULL,
|
|
310
|
-
excluded_json TEXT NOT NULL DEFAULT '{}',
|
|
311
|
-
created_at TEXT NOT NULL
|
|
312
|
-
);
|
|
313
|
-
CREATE INDEX IF NOT EXISTS idx_context_snapshots_run ON context_snapshots(run_id, created_at);
|
|
314
|
-
CREATE TABLE IF NOT EXISTS cleanup_plans (
|
|
315
|
-
id TEXT PRIMARY KEY,
|
|
316
|
-
project_root TEXT,
|
|
317
|
-
generated_at TEXT NOT NULL,
|
|
318
|
-
expires_at TEXT NOT NULL,
|
|
319
|
-
policy TEXT NOT NULL,
|
|
320
|
-
summary_json TEXT NOT NULL
|
|
321
|
-
);
|
|
322
|
-
CREATE TABLE IF NOT EXISTS cleanup_plan_items (
|
|
323
|
-
id TEXT PRIMARY KEY,
|
|
324
|
-
plan_id TEXT NOT NULL,
|
|
325
|
-
task_id TEXT NOT NULL,
|
|
326
|
-
verdict TEXT NOT NULL,
|
|
327
|
-
reasons_json TEXT NOT NULL,
|
|
328
|
-
fingerprint TEXT,
|
|
329
|
-
reclaimable_bytes INTEGER NOT NULL DEFAULT 0,
|
|
330
|
-
eligible_after TEXT,
|
|
331
|
-
applied_at TEXT,
|
|
332
|
-
applied_by TEXT,
|
|
333
|
-
UNIQUE(plan_id, task_id)
|
|
334
|
-
);
|
|
335
|
-
CREATE INDEX IF NOT EXISTS idx_cleanup_plan_items_plan ON cleanup_plan_items(plan_id, verdict);
|
|
336
|
-
CREATE INDEX IF NOT EXISTS idx_cleanup_plan_items_task ON cleanup_plan_items(task_id, applied_at);
|
|
337
|
-
`;
|
|
338
|
-
|
|
339
|
-
// A session is a string on each task row; this table is what a session is
|
|
340
|
-
// *about*. A main thread sets it once per batch, so a reader sees "给 12
|
|
341
|
-
// 个接口补单测" instead of a bare id.
|
|
342
|
-
const SESSIONS_DDL = `
|
|
343
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
344
|
-
id TEXT PRIMARY KEY,
|
|
345
|
-
title TEXT,
|
|
346
|
-
note TEXT,
|
|
347
|
-
created_at TEXT NOT NULL,
|
|
348
|
-
updated_at TEXT NOT NULL
|
|
349
|
-
);
|
|
350
|
-
`;
|
|
351
|
-
|
|
352
|
-
// Side questions asked from the board. One side session per worker (the
|
|
353
|
-
// forked Codex thread), many turns under it. A turn keeps the stream chunks
|
|
354
|
-
// it produced, so a page that comes back can replay what it missed and the
|
|
355
|
-
// conversation survives a board restart.
|
|
356
|
-
const SIDE_DDL = `
|
|
357
|
-
CREATE TABLE IF NOT EXISTS side_sessions (
|
|
358
|
-
task_id TEXT PRIMARY KEY,
|
|
359
|
-
fork_thread_id TEXT,
|
|
360
|
-
created_at TEXT NOT NULL,
|
|
361
|
-
ended_at TEXT,
|
|
362
|
-
worker_run_count INTEGER
|
|
363
|
-
);
|
|
364
|
-
CREATE TABLE IF NOT EXISTS side_turns (
|
|
365
|
-
id TEXT PRIMARY KEY,
|
|
366
|
-
task_id TEXT NOT NULL,
|
|
367
|
-
question TEXT NOT NULL,
|
|
368
|
-
status TEXT NOT NULL,
|
|
369
|
-
chunks TEXT NOT NULL DEFAULT '[]',
|
|
370
|
-
usage TEXT,
|
|
371
|
-
error TEXT,
|
|
372
|
-
started_at TEXT NOT NULL,
|
|
373
|
-
ended_at TEXT
|
|
374
|
-
);
|
|
375
|
-
CREATE INDEX IF NOT EXISTS idx_side_turns_task ON side_turns(task_id, started_at);
|
|
376
|
-
`;
|
|
377
|
-
|
|
378
|
-
function sleepSync(ms) {
|
|
379
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
function isBusyError(error) {
|
|
383
|
-
return /SQLITE_BUSY|database is locked|database table is locked/i.test(String(error?.message ?? ""));
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// Several MCP processes may open a brand-new database at the same moment, so
|
|
387
|
-
// schema setup runs inside one immediate transaction (which the busy timeout
|
|
388
|
-
// makes wait instead of failing) and is retried if the file is still locked.
|
|
389
|
-
function runWithRetry(dbInstance, work, attempts = 10) {
|
|
390
|
-
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
391
|
-
try {
|
|
392
|
-
return work();
|
|
393
|
-
} catch (error) {
|
|
394
|
-
if (attempt === attempts - 1 || !isBusyError(error)) throw error;
|
|
395
|
-
sleepSync(50 * (attempt + 1));
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
return undefined;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
function initializeSchema(dbInstance) {
|
|
402
|
-
runWithRetry(dbInstance, () => {
|
|
403
|
-
dbInstance.exec("BEGIN IMMEDIATE;");
|
|
404
|
-
try {
|
|
405
|
-
const columns = tableColumns(dbInstance, "tasks");
|
|
406
|
-
if (columns.length === 0) dbInstance.exec(TASKS_DDL);
|
|
407
|
-
else migrateTasksTable(dbInstance, columns);
|
|
408
|
-
dbInstance.exec(TASK_EVENTS_DDL);
|
|
409
|
-
for (const [name, definition] of [
|
|
410
|
-
["run_id", "TEXT"],
|
|
411
|
-
["actor", "TEXT NOT NULL DEFAULT 'legacy'"],
|
|
412
|
-
["payload_sha256", "TEXT"]
|
|
413
|
-
]) {
|
|
414
|
-
if (!tableColumns(dbInstance, "task_events").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE task_events ADD COLUMN ${name} ${definition}`);
|
|
415
|
-
}
|
|
416
|
-
dbInstance.exec("UPDATE task_events SET actor = 'legacy' WHERE actor IS NULL");
|
|
417
|
-
dbInstance.exec(TASK_EVENTS_INDEX_DDL);
|
|
418
|
-
dbInstance.exec(TASKS_SESSION_INDEX_DDL);
|
|
419
|
-
for (const [name, definition] of TASK_EXTRA_COLUMNS) {
|
|
420
|
-
if (!tableColumns(dbInstance, "tasks").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE tasks ADD COLUMN ${name} ${definition}`);
|
|
421
|
-
}
|
|
422
|
-
dbInstance.exec(CONTROL_DDL);
|
|
423
|
-
for (const [name, definition] of [
|
|
424
|
-
["watched_paths", "TEXT NOT NULL DEFAULT '[]'"],
|
|
425
|
-
["source_artifact_id", "TEXT"],
|
|
426
|
-
["valid_for_content_hash", "TEXT"],
|
|
427
|
-
["valid_for_manifest_hash", "TEXT"],
|
|
428
|
-
["verified_by", "TEXT"]
|
|
429
|
-
]) {
|
|
430
|
-
if (!tableColumns(dbInstance, "facts").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE facts ADD COLUMN ${name} ${definition}`);
|
|
431
|
-
}
|
|
432
|
-
dbInstance.exec(SESSIONS_DDL);
|
|
433
|
-
for (const [name, definition] of [
|
|
434
|
-
["objective", "TEXT"], ["default_acceptance", "TEXT"],
|
|
435
|
-
["approval_state", "TEXT NOT NULL DEFAULT 'approved'"], ["policy_revision", "INTEGER NOT NULL DEFAULT 0"]
|
|
436
|
-
]) {
|
|
437
|
-
if (!tableColumns(dbInstance, "sessions").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE sessions ADD COLUMN ${name} ${definition}`);
|
|
438
|
-
}
|
|
439
|
-
dbInstance.exec("CREATE TABLE IF NOT EXISTS observer_cursors (id TEXT PRIMARY KEY, cursor TEXT NOT NULL, updated_at TEXT NOT NULL)");
|
|
440
|
-
dbInstance.exec("CREATE TABLE IF NOT EXISTS run_claims (task_id TEXT PRIMARY KEY, token TEXT NOT NULL, owner_pid INTEGER NOT NULL)");
|
|
441
|
-
dbInstance.exec(SIDE_DDL);
|
|
442
|
-
// Rows written before 0.7.1 have no worker_run_count: the fork is then
|
|
443
|
-
|
|
444
|
-
// never judged stale, which is what those rows did before.
|
|
445
|
-
|
|
446
|
-
if (!dbInstance.prepare("PRAGMA table_info(side_sessions)").all().some((column) => column.name === "worker_run_count")) {
|
|
447
|
-
|
|
448
|
-
dbInstance.exec("ALTER TABLE side_sessions ADD COLUMN worker_run_count INTEGER;");
|
|
449
|
-
|
|
450
|
-
}
|
|
451
|
-
backfillControlRecords(dbInstance);
|
|
452
|
-
dbInstance.exec("COMMIT;");
|
|
453
|
-
} catch (error) {
|
|
454
|
-
try {
|
|
455
|
-
dbInstance.exec("ROLLBACK;");
|
|
456
|
-
} catch {
|
|
457
|
-
/* transaction already unwound */
|
|
458
|
-
}
|
|
459
|
-
throw error;
|
|
460
|
-
}
|
|
461
|
-
});
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
function stableId(prefix, value) {
|
|
465
|
-
return `${prefix}-${createHash("sha256").update(String(value)).digest("hex").slice(0, 24)}`;
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
function repoIdForRoot(root) {
|
|
469
|
-
return stableId("repo", resolve(root));
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
function canonicalizeRemote(value) {
|
|
473
|
-
let raw = String(value ?? "").trim();
|
|
474
|
-
if (!raw) return null;
|
|
475
|
-
const scp = raw.match(/^((?:[^@/:\s]+@)?)([^:/\s]+):(.+)$/);
|
|
476
|
-
if (scp && !raw.includes("://")) raw = `ssh://${scp[1]}${scp[2]}/${scp[3]}`;
|
|
477
|
-
try {
|
|
478
|
-
const parsed = new URL(raw);
|
|
479
|
-
if (parsed.protocol === "file:") {
|
|
480
|
-
const path = resolve(decodeURIComponent(parsed.pathname)).replace(/\.git$/i, "");
|
|
481
|
-
return `file://${path}`;
|
|
482
|
-
}
|
|
483
|
-
if (!parsed.hostname || !["ssh:", "https:", "http:"].includes(parsed.protocol)) return null;
|
|
484
|
-
const path = decodeURIComponent(parsed.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
485
|
-
if (!path) return null;
|
|
486
|
-
return `${parsed.protocol}//${parsed.hostname.toLowerCase()}${parsed.port ? `:${parsed.port}` : ""}/${path}`;
|
|
487
|
-
} catch {
|
|
488
|
-
return isAbsolute(raw) ? `file://${resolve(raw).replace(/\.git$/i, "")}` : null;
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
function canonicalRemoteForRoot(root) {
|
|
493
|
-
try {
|
|
494
|
-
return canonicalizeRemote(git(root, ["remote", "get-url", "origin"]));
|
|
495
|
-
} catch {
|
|
496
|
-
return null;
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
function workItemIdForTask(taskId) {
|
|
501
|
-
return `work-${taskId}`;
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
export function runIdFor(taskId, attempt) {
|
|
505
|
-
return `run-${taskId}-${attempt}`;
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
function ensureControlRecords(dbInstance, task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
|
|
509
|
-
if (!task?.id || !task.project_root) return;
|
|
510
|
-
const now = new Date().toISOString();
|
|
511
|
-
const root = resolve(task.project_root);
|
|
512
|
-
const repoId = repoIdForRoot(root);
|
|
513
|
-
const workItemId = workItemIdForTask(task.id);
|
|
514
|
-
const repo = dbInstance.prepare("SELECT id FROM repos WHERE root = ?").get(root);
|
|
515
|
-
if (!repo || refreshRepo) {
|
|
516
|
-
const resolvedRemote = canonicalRemote === undefined ? canonicalRemoteForRoot(root) : canonicalRemote;
|
|
517
|
-
dbInstance.prepare(`
|
|
518
|
-
INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
|
|
519
|
-
VALUES (@id, @canonical_remote, @root, NULL, @now, @now)
|
|
520
|
-
ON CONFLICT(root) DO UPDATE SET canonical_remote = excluded.canonical_remote, updated_at = excluded.updated_at
|
|
521
|
-
`).run({ id: repoId, canonical_remote: resolvedRemote, root, now });
|
|
522
|
-
}
|
|
523
|
-
const workItem = dbInstance.prepare("SELECT id FROM work_items WHERE task_id = ?").get(task.id);
|
|
524
|
-
if (workItem) return;
|
|
525
|
-
dbInstance.prepare(`
|
|
526
|
-
INSERT INTO work_items (id, repo_id, task_id, parent_work_item_id, objective, owner, delivery_state, created_at, updated_at)
|
|
527
|
-
VALUES (@id, @repo_id, @task_id, NULL, @objective, NULL, @delivery_state, @now, @now)
|
|
528
|
-
`).run({
|
|
529
|
-
id: workItemId,
|
|
530
|
-
repo_id: repoId,
|
|
531
|
-
task_id: task.id,
|
|
532
|
-
objective: task.goal_objective ?? task.title ?? null,
|
|
533
|
-
delivery_state: task.landed_at ? "landed" : "draft",
|
|
534
|
-
now
|
|
535
|
-
});
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
function backfillControlRecords(dbInstance) {
|
|
539
|
-
const rows = dbInstance.prepare(`
|
|
540
|
-
SELECT t.id,t.title,t.project_root,t.goal_objective,t.landed_at
|
|
541
|
-
FROM tasks AS t
|
|
542
|
-
LEFT JOIN work_items AS w ON w.task_id = t.id
|
|
543
|
-
WHERE w.task_id IS NULL
|
|
544
|
-
`).all();
|
|
545
|
-
for (const row of rows) ensureControlRecords(dbInstance, row);
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
function openDb() {
|
|
549
|
-
if (db) return db;
|
|
550
|
-
db = new DatabaseSync(dbPath);
|
|
551
|
-
// Several MCP processes share one database file. The busy timeout has to be
|
|
552
|
-
// set before anything that can touch the write lock, otherwise a concurrent
|
|
553
|
-
// writer turns into an immediate SQLITE_BUSY.
|
|
554
|
-
db.exec("PRAGMA busy_timeout=15000;");
|
|
555
|
-
runWithRetry(db, () => db.exec("PRAGMA journal_mode=WAL;"));
|
|
556
|
-
db.exec("PRAGMA synchronous=NORMAL;");
|
|
557
|
-
initializeSchema(db);
|
|
558
|
-
return db;
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
async function ensureFilesystem() {
|
|
562
|
-
await mkdir(dataDir, { recursive: true });
|
|
563
|
-
await mkdir(runsDir, { recursive: true });
|
|
564
|
-
await mkdir(artifactsDir, { recursive: true });
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
function encodeJson(value) {
|
|
568
|
-
return JSON.stringify(value ?? []);
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
function decodeJson(value, fallback) {
|
|
572
|
-
if (!value) return fallback;
|
|
573
|
-
try {
|
|
574
|
-
return JSON.parse(value);
|
|
575
|
-
} catch {
|
|
576
|
-
return fallback;
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
function rowToTask(row) {
|
|
581
|
-
if (!row) return null;
|
|
582
|
-
const nativeGoal = readNativeGoal(row.thread_id);
|
|
583
|
-
return {
|
|
584
|
-
...row,
|
|
585
|
-
workspace_kind: row.workspace_kind ?? "legacy",
|
|
586
|
-
skip_git_repo_check: Boolean(row.skip_git_repo_check),
|
|
587
|
-
changed_files: decodeJson(row.changed_files, []),
|
|
588
|
-
commands: decodeJson(row.commands, []),
|
|
589
|
-
owned_paths: decodeJson(row.owned_paths, []),
|
|
590
|
-
depends_on: decodeJson(row.depends_on, []),
|
|
591
|
-
acceptance: decodeJson(row.acceptance, null),
|
|
592
|
-
acceptance_local: decodeJson(row.acceptance_local, null),
|
|
593
|
-
acceptance_results: decodeJson(row.acceptance_results, null),
|
|
594
|
-
run_evidence: decodeJson(row.run_evidence, null),
|
|
595
|
-
guard_policy: decodeJson(row.guard_policy, null),
|
|
596
|
-
input_context: decodeJson(row.input_context, null),
|
|
597
|
-
workspace_metadata: decodeJson(row.workspace_metadata, null),
|
|
598
|
-
pid: row.pid ?? null,
|
|
599
|
-
exit_code: row.exit_code ?? null,
|
|
600
|
-
phase: row.phase ?? null,
|
|
601
|
-
goal_token_budget: row.goal_token_budget ?? null,
|
|
602
|
-
goal_status: nativeGoal?.storage_status ?? row.goal_status ?? null,
|
|
603
|
-
goal_tokens_used: nativeGoal?.tokens_used ?? row.goal_tokens_used ?? null,
|
|
604
|
-
goal_time_used_seconds: nativeGoal?.time_used_seconds ?? row.goal_time_used_seconds ?? null,
|
|
605
|
-
goal_updated_at: nativeGoal?.updated_at ?? row.goal_updated_at ?? null
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
export function isPidAlive(pid) {
|
|
610
|
-
if (!pid) return false;
|
|
611
|
-
try {
|
|
612
|
-
process.kill(pid, 0);
|
|
613
|
-
return true;
|
|
614
|
-
} catch {
|
|
615
|
-
return false;
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
export async function readTasks() {
|
|
620
|
-
await ensureFilesystem();
|
|
621
|
-
const rows = openDb().prepare("SELECT * FROM tasks ORDER BY created_at ASC").all();
|
|
622
|
-
return rows.map(rowToTask);
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
export async function readActiveTasks() {
|
|
626
|
-
const tasks = await readTasks();
|
|
627
|
-
return tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
// A worker whose process is gone and that never wrote a terminal event is not
|
|
631
|
-
// "failed": nothing told us it failed. It is lost, and the fix is to re-run it.
|
|
632
|
-
// A row can also be active without ever having had a process: the dispatch
|
|
633
|
-
// wrote the row and then died before the spawn was recorded (one real store
|
|
634
|
-
// carried such a row for days, pid 0 and no created_at, forever "running").
|
|
635
|
-
// Only a row old enough that the dispatch cannot still be in flight is judged
|
|
636
|
-
// this way; a row with an unreadable created_at is treated as old.
|
|
637
|
-
const NEVER_STARTED_GRACE_MS = 5 * 60 * 1000;
|
|
638
|
-
|
|
639
|
-
function neverStarted(task, now = Date.now()) {
|
|
640
|
-
if (task.pid) return false;
|
|
641
|
-
if (task.started_at) return false;
|
|
642
|
-
const created = Date.parse(task.created_at ?? "");
|
|
643
|
-
if (Number.isNaN(created)) return true;
|
|
644
|
-
return now - created > NEVER_STARTED_GRACE_MS;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
// A terminal row whose acceptance run was cut short: the MCP process that
|
|
648
|
-
// was running the checks is gone. Left alone it would read as "running"
|
|
649
|
-
// forever and land would treat it as never run.
|
|
650
|
-
async function reconcileInterruptedAcceptance() {
|
|
651
|
-
const tasks = await readTasks();
|
|
652
|
-
const interrupted = tasks.filter((task) =>
|
|
653
|
-
TERMINAL_STATUSES.has(task.status)
|
|
654
|
-
&& task.acceptance_results?.status === "running"
|
|
655
|
-
&& !isPidAlive(task.acceptance_results.supervisor_pid));
|
|
656
|
-
for (const task of interrupted) {
|
|
657
|
-
const now = new Date().toISOString();
|
|
658
|
-
const durable = (await readTaskEvents(task.id, 1, ["supervisor.acceptance"]))[0] ?? null;
|
|
659
|
-
if (durable && durable.run === task.run_count) {
|
|
660
|
-
const reportInvalid = task.attention_reason === "invalid_report";
|
|
661
|
-
await writeTask({
|
|
662
|
-
...task,
|
|
663
|
-
status: reportInvalid ? "completed" : task.status,
|
|
664
|
-
exit_code: task.exit_code ?? (reportInvalid ? 0 : null),
|
|
665
|
-
acceptance_results: durable,
|
|
666
|
-
current_action: durable.passed === true
|
|
667
|
-
? "Acceptance passed (recovered from the durable event)"
|
|
668
|
-
: `Acceptance ${durable.status} (recovered from the durable event)`,
|
|
669
|
-
updated_at: now
|
|
670
|
-
});
|
|
671
|
-
continue;
|
|
672
|
-
}
|
|
673
|
-
await writeTask({
|
|
674
|
-
...task,
|
|
675
|
-
acceptance_results: { ...task.acceptance_results, status: "interrupted", passed: null, finished_at: now },
|
|
676
|
-
current_action: "Acceptance interrupted: the supervisor process exited while running the checks",
|
|
677
|
-
updated_at: now
|
|
678
|
-
});
|
|
679
|
-
}
|
|
680
|
-
return interrupted;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
export async function reconcileDetachedActiveTasks() {
|
|
684
|
-
await reconcileInterruptedAcceptance();
|
|
685
|
-
// A run host can disappear after Codex has finished its turn but before it
|
|
686
|
-
// writes the process exit. The terminal event is already durable, and the
|
|
687
|
-
// work did complete; the missing scalar is a supervisor bookkeeping fault,
|
|
688
|
-
// not evidence that the worker vanished. Acceptance keeps its own verdict;
|
|
689
|
-
// recovering the worker completion must never imply that checks passed.
|
|
690
|
-
const recoverTerminalTurn = async (task) => {
|
|
691
|
-
if (task.exit_code != null || task.signal || !task.started_at
|
|
692
|
-
|| isPidAlive(task.pid) || isPidAlive(task.run_host_pid)) return false;
|
|
693
|
-
const runId = runIdFor(task.id, task.run_count);
|
|
694
|
-
const events = openDb().prepare(`
|
|
695
|
-
SELECT payload FROM task_events WHERE task_id = ? AND run_id = ? ORDER BY seq
|
|
696
|
-
`).all(task.id, runId).map((row) => decodeJson(row.payload, null)).filter(Boolean);
|
|
697
|
-
if (!events.some((event) => event.type === "turn.completed")) return false;
|
|
698
|
-
let reportText = null;
|
|
699
|
-
for (const event of events) {
|
|
700
|
-
if (event.type === "item.completed" && event.item?.type === "agent_message") reportText = event.item.text ?? null;
|
|
701
|
-
}
|
|
702
|
-
const structuredReport = parseWorkerReportForRun(reportText, { outputSchema: task.guard_policy?.output_schema !== false });
|
|
703
|
-
const recoveredEvidence = task.run_evidence
|
|
704
|
-
? { ...task.run_evidence, structured_report: structuredReport }
|
|
705
|
-
: {
|
|
706
|
-
run: task.run_count,
|
|
707
|
-
commands_run: (task.commands ?? []).length,
|
|
708
|
-
structured_report: structuredReport,
|
|
709
|
-
recovered: "turn_completed_without_process_exit"
|
|
710
|
-
};
|
|
711
|
-
if (!recoveredEvidence.attempt_fingerprint) {
|
|
712
|
-
recoveredEvidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
|
|
713
|
-
output_changed: recoveredEvidence.output_changed ?? null,
|
|
714
|
-
commands_run: recoveredEvidence.commands_run ?? (task.commands ?? []).length,
|
|
715
|
-
changed_files: task.changed_files ?? [],
|
|
716
|
-
acceptance_configured: Array.isArray(task.acceptance) && task.acceptance.length > 0,
|
|
717
|
-
workspace_manifest_changed: recoveredEvidence.workspace?.manifest_changed ?? null
|
|
718
|
-
})).digest("hex");
|
|
719
|
-
}
|
|
720
|
-
const reportInvalid = recoveredEvidence.structured_report?.valid === false && !task.guard_policy?.preflight;
|
|
721
|
-
const attentionReason = task.attention_reason ?? (reportInvalid ? "invalid_report" : null);
|
|
722
|
-
const staleExitError = /did not record the process exit|process disappeared/i.test(task.error ?? "");
|
|
723
|
-
const now = new Date().toISOString();
|
|
724
|
-
const acceptanceResults = task.acceptance_results ?? (task.acceptance?.length ? {
|
|
725
|
-
status: "interrupted", passed: null, run: task.run_count, finished_at: now,
|
|
726
|
-
error: "worker completed before its acceptance result was recorded; rerun acceptance"
|
|
727
|
-
} : null);
|
|
728
|
-
const recoveredTask = {
|
|
729
|
-
...task,
|
|
730
|
-
status: "completed",
|
|
731
|
-
phase: null,
|
|
732
|
-
exit_code: 0,
|
|
733
|
-
attention_reason: attentionReason,
|
|
734
|
-
error: reportInvalid
|
|
735
|
-
? (staleExitError ? null : task.error) ?? `Invalid final worker report: ${recoveredEvidence.structured_report.error}`
|
|
736
|
-
: staleExitError ? null : task.error ?? null,
|
|
737
|
-
current_action: attentionReason ? task.current_action : "Completed (exit recovered from the durable turn event)",
|
|
738
|
-
current_command: null,
|
|
739
|
-
acceptance_results: acceptanceResults,
|
|
740
|
-
run_evidence: recoveredEvidence,
|
|
741
|
-
completed_at: task.completed_at ?? now,
|
|
742
|
-
updated_at: now
|
|
743
|
-
};
|
|
744
|
-
await writeTask(recoveredTask);
|
|
745
|
-
await completeRunRecord(recoveredTask, task.run_count);
|
|
746
|
-
await appendTaskEvent(task.id, {
|
|
747
|
-
type: "supervisor.exit_recovered",
|
|
748
|
-
reason: "turn_completed_without_process_exit",
|
|
749
|
-
exit_code: 0,
|
|
750
|
-
recovered_at: now
|
|
751
|
-
}, { runId, actor: "supervisor" }).catch(() => null);
|
|
752
|
-
return true;
|
|
753
|
-
};
|
|
754
|
-
const terminalCandidates = openDb().prepare(`
|
|
755
|
-
SELECT * FROM tasks
|
|
756
|
-
WHERE status IN ('completed','lost') AND exit_code IS NULL AND started_at IS NOT NULL
|
|
757
|
-
`).all().map(rowToTask);
|
|
758
|
-
for (const task of terminalCandidates) await recoverTerminalTurn(task);
|
|
759
|
-
const incomplete = (await readTasks()).filter((task) =>
|
|
760
|
-
["completed", "failed"].includes(task.status) && task.exit_code == null && task.started_at
|
|
761
|
-
&& !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid)
|
|
762
|
-
&& (!task.acceptance_results || ["interrupted", "cancelled"].includes(task.acceptance_results.status))
|
|
763
|
-
&& Date.now() - Date.parse(task.updated_at) > 5000);
|
|
764
|
-
for (const task of incomplete) {
|
|
765
|
-
await writeTask({ ...task, status: "lost", phase: null,
|
|
766
|
-
error: task.acceptance_results?.status === "interrupted"
|
|
767
|
-
? "Worker ended but its supervisor did not record the process exit before acceptance; resume this run"
|
|
768
|
-
: "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
|
|
769
|
-
current_action: task.acceptance_results?.status === "interrupted"
|
|
770
|
-
? "Acceptance interrupted: worker process exit was not recorded; resume this run"
|
|
771
|
-
: "Resume required: process exit was not recorded",
|
|
772
|
-
updated_at: new Date().toISOString() });
|
|
773
|
-
}
|
|
774
|
-
const tasks = await readActiveTasks();
|
|
775
|
-
const staleTasks = tasks.filter((task) => !isPidAlive(task.run_host_pid)
|
|
776
|
-
&& ((task.pid && !isPidAlive(task.pid)) || neverStarted(task)));
|
|
777
|
-
for (const task of staleTasks) {
|
|
778
|
-
if (await recoverTerminalTurn(task)) continue;
|
|
779
|
-
const now = new Date().toISOString();
|
|
780
|
-
const vanished = Boolean(task.pid);
|
|
781
|
-
await writeTask({
|
|
782
|
-
...task,
|
|
783
|
-
status: "lost",
|
|
784
|
-
phase: null,
|
|
785
|
-
current_action: vanished
|
|
786
|
-
? "Worker process disappeared without a terminal event"
|
|
787
|
-
: "Worker was never started: no process was recorded for this row",
|
|
788
|
-
current_command: null,
|
|
789
|
-
error: task.error ?? (vanished
|
|
790
|
-
? "Codex worker process disappeared before a terminal event was recorded."
|
|
791
|
-
: "Codex worker row was written but no process was ever recorded for it."),
|
|
792
|
-
completed_at: task.completed_at || now,
|
|
793
|
-
updated_at: now
|
|
794
|
-
});
|
|
795
|
-
}
|
|
796
|
-
return staleTasks;
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
export async function writeTask(task) {
|
|
800
|
-
await ensureFilesystem();
|
|
801
|
-
return runWithRetry(openDb(), () => writeTaskNow(task));
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
function writeTaskNow(task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
|
|
805
|
-
const placeholders = TASK_COLUMNS.map((name) => `@${name}`).join(", ");
|
|
806
|
-
const updates = TASK_COLUMNS
|
|
807
|
-
.filter((name) => name !== "id" && name !== "created_at")
|
|
808
|
-
.map((name) => `${name} = excluded.${name}`)
|
|
809
|
-
.join(",\n ");
|
|
810
|
-
const stmt = openDb().prepare(`
|
|
811
|
-
INSERT INTO tasks (${TASK_COLUMNS.join(", ")}) VALUES (${placeholders})
|
|
812
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
813
|
-
${updates}
|
|
814
|
-
`);
|
|
815
|
-
|
|
816
|
-
const params = {};
|
|
817
|
-
for (const name of TASK_COLUMNS) params[name] = task[name] ?? null;
|
|
818
|
-
params.reasoning_effort = task.reasoning_effort ?? "high";
|
|
819
|
-
params.workspace_kind = task.workspace_kind ?? "legacy";
|
|
820
|
-
params.skip_git_repo_check = task.skip_git_repo_check ? 1 : 0;
|
|
821
|
-
params.changed_files = encodeJson(task.changed_files);
|
|
822
|
-
params.commands = encodeJson(task.commands);
|
|
823
|
-
params.owned_paths = encodeJson(task.owned_paths);
|
|
824
|
-
params.depends_on = encodeJson(task.depends_on);
|
|
825
|
-
// JSON columns: node:sqlite refuses to bind an array or object, and a
|
|
826
|
-
// refused bind drops the whole row update.
|
|
827
|
-
params.acceptance = task.acceptance ? JSON.stringify(task.acceptance) : null;
|
|
828
|
-
params.acceptance_local = task.acceptance_local ? JSON.stringify(task.acceptance_local) : null;
|
|
829
|
-
params.acceptance_results = task.acceptance_results ? JSON.stringify(task.acceptance_results) : null;
|
|
830
|
-
params.run_evidence = task.run_evidence ? JSON.stringify(task.run_evidence) : null;
|
|
831
|
-
params.guard_policy = task.guard_policy ? JSON.stringify(task.guard_policy) : null;
|
|
832
|
-
params.input_context = task.input_context ? JSON.stringify(task.input_context) : null;
|
|
833
|
-
params.workspace_metadata = task.workspace_metadata ? JSON.stringify(task.workspace_metadata) : null;
|
|
834
|
-
params.run_count = task.run_count ?? 0;
|
|
835
|
-
params.phase = task.phase ?? null;
|
|
836
|
-
|
|
837
|
-
stmt.run(params);
|
|
838
|
-
ensureControlRecords(openDb(), task, { refreshRepo, canonicalRemote });
|
|
839
|
-
return task;
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
function checkOwnership(taskId, incoming) {
|
|
843
|
-
const normalized = (value) => process.platform === "win32" ? value.replace(/\\/g, "/").toLowerCase() : value;
|
|
844
|
-
const overlaps = (left, right) => {
|
|
845
|
-
const a=normalized(left).replace(/\/$/,""),b=normalized(right).replace(/\/$/,"");
|
|
846
|
-
return a===b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
847
|
-
};
|
|
848
|
-
const conflicts = [];
|
|
849
|
-
const pending = openDb().prepare("SELECT t.id,t.title,t.status,t.owned_paths,t.acceptance_results,t.started_at,t.exit_code,t.guard_policy,t.commands,t.attention_reason,c.owner_pid FROM tasks t LEFT JOIN run_claims c ON c.task_id=t.id WHERE t.id<>? AND (c.owner_pid IS NOT NULL OR status IN ('queued','running') OR json_extract(acceptance_results,'$.status')='running' OR (status IN ('completed','failed') AND started_at IS NOT NULL AND exit_code IS NULL AND acceptance_results IS NULL))").all(taskId);
|
|
850
|
-
for (const row of pending) {
|
|
851
|
-
const settling = decodeJson(row.acceptance_results,null)?.status === "running"
|
|
852
|
-
|| (["completed","failed"].includes(row.status) && row.started_at && row.exit_code == null && !row.acceptance_results);
|
|
853
|
-
if (row.owner_pid && !ACTIVE_STATUSES.has(row.status) && !settling && !isPidAlive(row.owner_pid)) continue;
|
|
854
|
-
const preflightTask = {
|
|
855
|
-
...row,
|
|
856
|
-
guard_policy: decodeJson(row.guard_policy, null),
|
|
857
|
-
commands: decodeJson(row.commands, [])
|
|
858
|
-
};
|
|
859
|
-
if (preflightTask.guard_policy?.preflight && readPreflightResult(preflightTask).status === "passed") continue;
|
|
860
|
-
const paths=decodeJson(row.owned_paths,[]);
|
|
861
|
-
const matching=incoming.flatMap(path=>paths.filter(other=>overlaps(path,other)).map(other=>({incoming:path,existing:other})));
|
|
862
|
-
if(matching.length)conflicts.push({task_id:row.id,title:row.title,status:row.status,overlapping_paths:matching});
|
|
863
|
-
}
|
|
864
|
-
if(conflicts.length){const error=new Error("ownedPaths overlap with an active worker claimed by another dispatcher");error.code="ownership_conflict";error.conflicts=conflicts;throw error;}
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
export async function reserveTaskOwnership(task) {
|
|
868
|
-
await ensureFilesystem();
|
|
869
|
-
const canonicalRemote = task?.project_root ? canonicalRemoteForRoot(resolve(task.project_root)) : null;
|
|
870
|
-
const connection=openDb();
|
|
871
|
-
return runWithRetry(connection,()=>{
|
|
872
|
-
connection.exec("BEGIN IMMEDIATE");
|
|
873
|
-
try { checkOwnership(task.id,task.owned_paths??[]);writeTaskNow(task, { refreshRepo: true, canonicalRemote });connection.exec("COMMIT");return task; }
|
|
874
|
-
catch(error){connection.exec("ROLLBACK");throw error;}
|
|
875
|
-
});
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
export async function upsertTask(task) {
|
|
879
|
-
await writeTask(task);
|
|
880
|
-
return task;
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
export async function getTask(taskId) {
|
|
884
|
-
await ensureFilesystem();
|
|
885
|
-
const row = openDb().prepare("SELECT * FROM tasks WHERE id = ?").get(taskId);
|
|
886
|
-
return rowToTask(row);
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
// Compare and claim under one write lock before rebase or spawning. A claim
|
|
890
|
-
// whose dispatcher died can be replaced; a different run cannot be resumed
|
|
891
|
-
// using an earlier snapshot, even when both dispatchers read it together.
|
|
892
|
-
export async function claimTaskRun(taskId, expectedRun) {
|
|
893
|
-
await ensureFilesystem();
|
|
894
|
-
const connection = openDb();
|
|
895
|
-
return runWithRetry(connection, () => {
|
|
896
|
-
connection.exec("BEGIN IMMEDIATE");
|
|
897
|
-
try {
|
|
898
|
-
const row = connection.prepare("SELECT * FROM tasks WHERE id=?").get(taskId);
|
|
899
|
-
const claim = connection.prepare("SELECT * FROM run_claims WHERE task_id=?").get(taskId);
|
|
900
|
-
const busy = !row || row.run_count !== expectedRun || ACTIVE_STATUSES.has(row.status)
|
|
901
|
-
|| (["completed", "failed"].includes(row.status) && row.exit_code == null)
|
|
902
|
-
|| decodeJson(row.acceptance_results, null)?.status === "running"
|
|
903
|
-
|| (claim && isPidAlive(claim.owner_pid));
|
|
904
|
-
let token = null;
|
|
905
|
-
if (!busy) {
|
|
906
|
-
checkOwnership(taskId,decodeJson(row.owned_paths,[]));
|
|
907
|
-
token = randomUUID();
|
|
908
|
-
connection.prepare("INSERT INTO run_claims VALUES (?,?,?) ON CONFLICT(task_id) DO UPDATE SET token=excluded.token,owner_pid=excluded.owner_pid")
|
|
909
|
-
.run(taskId, token, process.pid);
|
|
910
|
-
}
|
|
911
|
-
connection.exec("COMMIT");
|
|
912
|
-
return token;
|
|
913
|
-
} catch (error) { connection.exec("ROLLBACK"); throw error; }
|
|
914
|
-
});
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
export async function releaseTaskRun(taskId, token) {
|
|
918
|
-
openDb().prepare("DELETE FROM run_claims WHERE task_id=? AND token=?").run(taskId, token);
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
export async function readObserverCursor(observerId) {
|
|
922
|
-
await ensureFilesystem();
|
|
923
|
-
return decodeJson(openDb().prepare("SELECT cursor FROM observer_cursors WHERE id=?").get(observerId)?.cursor, {});
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
export async function writeObserverCursor(observerId, cursor) {
|
|
927
|
-
await ensureFilesystem();
|
|
928
|
-
runWithRetry(openDb(), () => openDb().prepare("INSERT INTO observer_cursors VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET cursor=excluded.cursor,updated_at=excluded.updated_at")
|
|
929
|
-
.run(observerId, JSON.stringify(cursor), new Date().toISOString()));
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
// Keyword search over the fields that describe what a work was for and how it
|
|
933
|
-
// ended. Substring match, newest first. Deliberately not full-text and not
|
|
934
|
-
// vector search: at this scale a LIKE scan over a few hundred rows is faster
|
|
935
|
-
// than any index would be to maintain.
|
|
936
|
-
export async function searchTasks(query, limit = 20) {
|
|
937
|
-
await ensureFilesystem();
|
|
938
|
-
const pattern = `%${String(query).trim()}%`;
|
|
939
|
-
const rows = openDb().prepare(`
|
|
940
|
-
SELECT * FROM tasks
|
|
941
|
-
WHERE title LIKE @pattern
|
|
942
|
-
OR goal_objective LIKE @pattern
|
|
943
|
-
OR prompt LIKE @pattern
|
|
944
|
-
OR last_message LIKE @pattern
|
|
945
|
-
ORDER BY created_at DESC
|
|
946
|
-
LIMIT @limit
|
|
947
|
-
`).all({ pattern, limit });
|
|
948
|
-
return rows.map(rowToTask);
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
export async function readTasksBySession(sessionId) {
|
|
952
|
-
await ensureFilesystem();
|
|
953
|
-
const rows = openDb()
|
|
954
|
-
.prepare("SELECT * FROM tasks WHERE session_id = ? ORDER BY created_at ASC")
|
|
955
|
-
.all(sessionId);
|
|
956
|
-
return rows.map(rowToTask);
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
// Record the files a terminal worker changed, and nothing else. The summary
|
|
960
|
-
// read used to upsert the whole row, which on a running worker put stale
|
|
961
|
-
// copies of every live field (phase, current_action, exit_code) back over
|
|
962
|
-
// what the runner had just written. A terminal row has no writer left, and
|
|
963
|
-
// even then only this one column is touched.
|
|
964
|
-
export async function recordTerminalChangedFiles(taskId, changedFiles) {
|
|
965
|
-
await ensureFilesystem();
|
|
966
|
-
const terminal = Array.from(TERMINAL_STATUSES).map((s) => `'${s}'`).join(", ");
|
|
967
|
-
const result = openDb()
|
|
968
|
-
.prepare(`UPDATE tasks SET changed_files = @files WHERE id = @id AND status IN (${terminal})`)
|
|
969
|
-
.run({ id: taskId, files: encodeJson(changedFiles) });
|
|
970
|
-
return result.changes > 0;
|
|
971
|
-
}
|
|
972
|
-
|
|
973
|
-
export async function upsertSession({ id, title = null, note = null, objective, defaultAcceptance, approvalState, expectedRevision }) {
|
|
974
|
-
if (!id) throw new Error("session id is required");
|
|
975
|
-
await ensureFilesystem();
|
|
976
|
-
const now = new Date().toISOString();
|
|
977
|
-
// Only overwrite what the caller sent: a later dispatch that names the
|
|
978
|
-
// session without a title must not blank the title set earlier.
|
|
979
|
-
openDb()
|
|
980
|
-
.prepare(`
|
|
981
|
-
INSERT INTO sessions (id, title, note, created_at, updated_at) VALUES (@id, @title, @note, @now, @now)
|
|
982
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
983
|
-
title = COALESCE(excluded.title, sessions.title),
|
|
984
|
-
note = COALESCE(excluded.note, sessions.note),
|
|
985
|
-
updated_at = excluded.updated_at
|
|
986
|
-
`)
|
|
987
|
-
.run({ id, title: title ?? null, note: note ?? null, now });
|
|
988
|
-
if (objective !== undefined || defaultAcceptance !== undefined || approvalState !== undefined || expectedRevision !== undefined) {
|
|
989
|
-
const acceptance = defaultAcceptance === undefined ? undefined : normalizeAcceptance(defaultAcceptance) ?? [];
|
|
990
|
-
if (objective !== undefined && (typeof objective !== "string" || !objective.trim())) throw new Error("session objective must be nonempty");
|
|
991
|
-
if (approvalState !== undefined && !["approved", "waiting_user"].includes(approvalState)) throw new Error("invalid session approval state");
|
|
992
|
-
runWithRetry(openDb(), () => {
|
|
993
|
-
const store = openDb();
|
|
994
|
-
store.exec("BEGIN IMMEDIATE");
|
|
995
|
-
try {
|
|
996
|
-
const before = store.prepare("SELECT * FROM sessions WHERE id=?").get(id);
|
|
997
|
-
if (expectedRevision !== undefined && expectedRevision !== before.policy_revision) {
|
|
998
|
-
const error = new Error(`session policy changed; current revision is ${before.policy_revision}`);
|
|
999
|
-
error.code = "session_policy_conflict";
|
|
1000
|
-
throw error;
|
|
1001
|
-
}
|
|
1002
|
-
const policy = {
|
|
1003
|
-
objective: objective ?? before.objective,
|
|
1004
|
-
acceptance: acceptance === undefined ? before.default_acceptance : JSON.stringify(acceptance),
|
|
1005
|
-
approval: approvalState ?? before.approval_state
|
|
1006
|
-
};
|
|
1007
|
-
const changed = policy.objective !== before.objective || policy.acceptance !== before.default_acceptance || policy.approval !== before.approval_state;
|
|
1008
|
-
store.prepare("UPDATE sessions SET objective=?,default_acceptance=?,approval_state=?,policy_revision=?,updated_at=? WHERE id=?")
|
|
1009
|
-
.run(policy.objective, policy.acceptance, policy.approval, before.policy_revision + (changed ? 1 : 0), now, id);
|
|
1010
|
-
store.exec("COMMIT");
|
|
1011
|
-
} catch (error) { store.exec("ROLLBACK"); throw error; }
|
|
1012
|
-
});
|
|
1013
|
-
}
|
|
1014
|
-
return getSession(id);
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
export async function getSession(sessionId) {
|
|
1018
|
-
await ensureFilesystem();
|
|
1019
|
-
const row = openDb().prepare("SELECT * FROM sessions WHERE id = ?").get(sessionId);
|
|
1020
|
-
return row ? { ...row, default_acceptance: decodeJson(row.default_acceptance, []) } : null;
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
export async function readSessions() {
|
|
1024
|
-
await ensureFilesystem();
|
|
1025
|
-
return openDb().prepare("SELECT * FROM sessions").all();
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
// ---- side sessions and turns
|
|
1029
|
-
|
|
1030
|
-
export async function getSideSession(taskId) {
|
|
1031
|
-
await ensureFilesystem();
|
|
1032
|
-
return openDb().prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
// `workerRunCount` is the worker's run_count when the fork is taken; a
|
|
1036
|
-
// worker resumed after that has a thread the fork no longer reflects.
|
|
1037
|
-
export async function openSideSession(taskId, workerRunCount = null) {
|
|
1038
|
-
await ensureFilesystem();
|
|
1039
|
-
const now = new Date().toISOString();
|
|
1040
|
-
openDb()
|
|
1041
|
-
.prepare(`INSERT INTO side_sessions (task_id, fork_thread_id, created_at, ended_at, worker_run_count) VALUES (?, NULL, ?, NULL, ?)
|
|
1042
|
-
ON CONFLICT(task_id) DO UPDATE SET fork_thread_id = NULL, created_at = excluded.created_at, ended_at = NULL, worker_run_count = excluded.worker_run_count`)
|
|
1043
|
-
.run(taskId, now, workerRunCount);
|
|
1044
|
-
return getSideSession(taskId);
|
|
1045
|
-
}
|
|
1046
|
-
|
|
1047
|
-
export async function setSideSessionFork(taskId, forkThreadId) {
|
|
1048
|
-
await ensureFilesystem();
|
|
1049
|
-
openDb().prepare("UPDATE side_sessions SET fork_thread_id = ? WHERE task_id = ? AND ended_at IS NULL").run(forkThreadId, taskId);
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
export async function closeSideSession(taskId) {
|
|
1053
|
-
await ensureFilesystem();
|
|
1054
|
-
const db = openDb();
|
|
1055
|
-
const row = db.prepare("SELECT * FROM side_sessions WHERE task_id = ? AND ended_at IS NULL").get(taskId) ?? null;
|
|
1056
|
-
const now = new Date().toISOString();
|
|
1057
|
-
db.prepare("UPDATE side_sessions SET ended_at = ? WHERE task_id = ? AND ended_at IS NULL").run(now, taskId);
|
|
1058
|
-
db.prepare("DELETE FROM side_turns WHERE task_id = ?").run(taskId);
|
|
1059
|
-
return row;
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
export async function insertSideTurn(turn) {
|
|
1063
|
-
await ensureFilesystem();
|
|
1064
|
-
openDb()
|
|
1065
|
-
.prepare(`INSERT INTO side_turns (id, task_id, question, status, chunks, usage, error, started_at, ended_at)
|
|
1066
|
-
VALUES (@id, @task_id, @question, @status, @chunks, @usage, @error, @started_at, @ended_at)`)
|
|
1067
|
-
.run({
|
|
1068
|
-
id: turn.id,
|
|
1069
|
-
task_id: turn.task_id,
|
|
1070
|
-
question: turn.question,
|
|
1071
|
-
status: turn.status,
|
|
1072
|
-
chunks: JSON.stringify(turn.chunks ?? []),
|
|
1073
|
-
usage: turn.usage ? JSON.stringify(turn.usage) : null,
|
|
1074
|
-
error: turn.error ?? null,
|
|
1075
|
-
started_at: turn.started_at,
|
|
1076
|
-
ended_at: turn.ended_at ?? null
|
|
1077
|
-
});
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
export async function updateSideTurn(id, fields) {
|
|
1081
|
-
await ensureFilesystem();
|
|
1082
|
-
const sets = [];
|
|
1083
|
-
const params = { id };
|
|
1084
|
-
for (const [key, value] of Object.entries(fields)) {
|
|
1085
|
-
sets.push(`${key} = @${key}`);
|
|
1086
|
-
params[key] = key === "chunks" || key === "usage" ? (value === null ? null : JSON.stringify(value)) : value;
|
|
1087
|
-
}
|
|
1088
|
-
if (sets.length === 0) return;
|
|
1089
|
-
openDb().prepare(`UPDATE side_turns SET ${sets.join(", ")} WHERE id = @id`).run(params);
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
export async function readSideTurns(taskId) {
|
|
1093
|
-
await ensureFilesystem();
|
|
1094
|
-
return openDb()
|
|
1095
|
-
.prepare("SELECT * FROM side_turns WHERE task_id = ? ORDER BY started_at ASC")
|
|
1096
|
-
.all(taskId)
|
|
1097
|
-
.map((row) => ({ ...row, chunks: decodeJson(row.chunks, []), usage: row.usage ? decodeJson(row.usage, null) : null }));
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
// A board that restarts cannot own a turn that was running when it died.
|
|
1101
|
-
export async function interruptRunningSideTurns() {
|
|
1102
|
-
await ensureFilesystem();
|
|
1103
|
-
const now = new Date().toISOString();
|
|
1104
|
-
return openDb()
|
|
1105
|
-
.prepare("UPDATE side_turns SET status = 'interrupted', error = COALESCE(error, 'the board restarted while this turn was running'), ended_at = ? WHERE status = 'running'")
|
|
1106
|
-
.run(now).changes;
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
export async function getTasks(taskIds) {
|
|
1110
|
-
await ensureFilesystem();
|
|
1111
|
-
return taskIds.map((taskId) => {
|
|
1112
|
-
const row = openDb().prepare("SELECT * FROM tasks WHERE id = ?").get(taskId);
|
|
1113
|
-
return rowToTask(row);
|
|
1114
|
-
});
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
export function taskRunPath(taskId) {
|
|
1118
|
-
return join(runsDir, `${taskId}.jsonl`);
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
export async function ensureRunRecord(task, attempt) {
|
|
1122
|
-
await ensureFilesystem();
|
|
1123
|
-
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) throw new Error("run record requires a task and positive attempt");
|
|
1124
|
-
const dbInstance = openDb();
|
|
1125
|
-
return runWithRetry(dbInstance, () => {
|
|
1126
|
-
ensureControlRecords(dbInstance, task);
|
|
1127
|
-
const now = new Date().toISOString();
|
|
1128
|
-
const id = runIdFor(task.id, attempt);
|
|
1129
|
-
dbInstance.prepare(`
|
|
1130
|
-
INSERT INTO runs (id, task_id, work_item_id, attempt, codex_thread_id, worktree_path, branch, base_sha, run_status, started_at, finished_at)
|
|
1131
|
-
VALUES (@id, @task_id, @work_item_id, @attempt, @codex_thread_id, @worktree_path, @branch, @base_sha, 'running', @started_at, NULL)
|
|
1132
|
-
ON CONFLICT(task_id, attempt) DO UPDATE SET
|
|
1133
|
-
codex_thread_id = COALESCE(excluded.codex_thread_id, runs.codex_thread_id),
|
|
1134
|
-
worktree_path = COALESCE(excluded.worktree_path, runs.worktree_path),
|
|
1135
|
-
base_sha = COALESCE(excluded.base_sha, runs.base_sha)
|
|
1136
|
-
`).run({
|
|
1137
|
-
id,
|
|
1138
|
-
task_id: task.id,
|
|
1139
|
-
work_item_id: workItemIdForTask(task.id),
|
|
1140
|
-
attempt,
|
|
1141
|
-
codex_thread_id: task.thread_id ?? null,
|
|
1142
|
-
worktree_path: task.worktree_path ?? null,
|
|
1143
|
-
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
1144
|
-
base_sha: task.base_commit ?? null,
|
|
1145
|
-
started_at: now
|
|
1146
|
-
});
|
|
1147
|
-
return id;
|
|
1148
|
-
});
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
export async function completeRunRecord(task, attempt) {
|
|
1152
|
-
await ensureFilesystem();
|
|
1153
|
-
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) return;
|
|
1154
|
-
const now = task.completed_at ?? new Date().toISOString();
|
|
1155
|
-
const dbInstance = openDb();
|
|
1156
|
-
runWithRetry(dbInstance, () => dbInstance.prepare(`
|
|
1157
|
-
UPDATE runs SET codex_thread_id = @codex_thread_id,
|
|
1158
|
-
run_status = @run_status, finished_at = @finished_at
|
|
1159
|
-
WHERE task_id = @task_id AND attempt = @attempt
|
|
1160
|
-
`).run({
|
|
1161
|
-
task_id: task.id,
|
|
1162
|
-
attempt,
|
|
1163
|
-
codex_thread_id: task.thread_id ?? null,
|
|
1164
|
-
run_status: task.status ?? "unknown",
|
|
1165
|
-
finished_at: now
|
|
1166
|
-
}));
|
|
1167
|
-
}
|
|
1168
|
-
|
|
1169
|
-
export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor" } = {}) {
|
|
1170
|
-
await ensureFilesystem();
|
|
1171
|
-
if (!Array.isArray(events) || events.length === 0) return [];
|
|
1172
|
-
const dbInstance = openDb();
|
|
1173
|
-
return runWithRetry(dbInstance, () => {
|
|
1174
|
-
dbInstance.exec("BEGIN IMMEDIATE");
|
|
1175
|
-
try {
|
|
1176
|
-
const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
|
|
1177
|
-
const insert = dbInstance.prepare(`
|
|
1178
|
-
INSERT INTO task_events (task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256)
|
|
1179
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1180
|
-
`);
|
|
1181
|
-
const createdAt = new Date().toISOString();
|
|
1182
|
-
const records = events.map((event, index) => {
|
|
1183
|
-
const payload = JSON.stringify(event);
|
|
1184
|
-
const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", payload,
|
|
1185
|
-
createHash("sha256").update(payload).digest("hex"));
|
|
1186
|
-
return { id: Number(result.lastInsertRowid), run_id: runId, actor };
|
|
1187
|
-
});
|
|
1188
|
-
dbInstance.exec("COMMIT");
|
|
1189
|
-
return records;
|
|
1190
|
-
} catch (error) {
|
|
1191
|
-
dbInstance.exec("ROLLBACK");
|
|
1192
|
-
throw error;
|
|
1193
|
-
}
|
|
1194
|
-
});
|
|
1195
|
-
}
|
|
1196
|
-
|
|
1197
|
-
export async function appendTaskEvent(taskId, event, options = {}) {
|
|
1198
|
-
return (await appendTaskEvents(taskId, [event], options))[0];
|
|
1199
|
-
}
|
|
1200
|
-
|
|
1201
|
-
export async function readTaskEvents(taskId, limit = 100, kinds = null) {
|
|
1202
|
-
await ensureFilesystem();
|
|
1203
|
-
const kindList = Array.isArray(kinds) && kinds.length > 0 ? kinds : null;
|
|
1204
|
-
// Filtering happens before the limit so "give me the last 10 file changes"
|
|
1205
|
-
// actually returns 10 file changes, not the tail of an unfiltered stream.
|
|
1206
|
-
const rows = kindList
|
|
1207
|
-
? openDb().prepare(`
|
|
1208
|
-
SELECT payload FROM task_events
|
|
1209
|
-
WHERE task_id = ? AND event_type IN (${kindList.map(() => "?").join(", ")})
|
|
1210
|
-
ORDER BY seq DESC LIMIT ?
|
|
1211
|
-
`).all(taskId, ...kindList, limit)
|
|
1212
|
-
: openDb().prepare(`
|
|
1213
|
-
SELECT payload FROM task_events
|
|
1214
|
-
WHERE task_id = ? ORDER BY seq DESC LIMIT ?
|
|
1215
|
-
`).all(taskId, limit);
|
|
1216
|
-
return rows.reverse().map((row) => JSON.parse(row.payload));
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
export async function readTaskEventRecords(taskId, limit = 100) {
|
|
1220
|
-
await ensureFilesystem();
|
|
1221
|
-
const rows = openDb().prepare(`
|
|
1222
|
-
SELECT id, task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256
|
|
1223
|
-
FROM task_events WHERE task_id = ? ORDER BY seq DESC LIMIT ?
|
|
1224
|
-
`).all(taskId, limit);
|
|
1225
|
-
return rows.reverse().map((row) => ({
|
|
1226
|
-
...row,
|
|
1227
|
-
event: JSON.parse(row.payload)
|
|
1228
|
-
}));
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
export async function getWorkItemForTask(taskId) {
|
|
1232
|
-
await ensureFilesystem();
|
|
1233
|
-
return openDb().prepare("SELECT * FROM work_items WHERE task_id = ?").get(taskId) ?? null;
|
|
1234
|
-
}
|
|
1235
|
-
|
|
1236
|
-
export async function recordFact({
|
|
1237
|
-
workItemId,
|
|
1238
|
-
scopeType,
|
|
1239
|
-
scopeId,
|
|
1240
|
-
key,
|
|
1241
|
-
value,
|
|
1242
|
-
state = "candidate",
|
|
1243
|
-
sourceEventId = null,
|
|
1244
|
-
sourceArtifactId = null,
|
|
1245
|
-
validForSha = null,
|
|
1246
|
-
validForContentHash = null,
|
|
1247
|
-
validForManifestHash = null,
|
|
1248
|
-
watchedPaths = [],
|
|
1249
|
-
expiresAt = null,
|
|
1250
|
-
supersedesId = null,
|
|
1251
|
-
verifiedAt = null,
|
|
1252
|
-
verifiedBy = null
|
|
1253
|
-
}) {
|
|
1254
|
-
await ensureFilesystem();
|
|
1255
|
-
if (!workItemId || !scopeType || !scopeId || !key) throw new Error("fact requires workItemId, scopeType, scopeId and key");
|
|
1256
|
-
if (!["candidate", "verified", "expired", "revoked"].includes(state)) throw new Error("invalid fact state");
|
|
1257
|
-
if (!Array.isArray(watchedPaths) || watchedPaths.some((path) => typeof path !== "string")) throw new Error("watchedPaths must be a string list");
|
|
1258
|
-
const now = new Date().toISOString();
|
|
1259
|
-
const id = randomUUID();
|
|
1260
|
-
openDb().prepare(`
|
|
1261
|
-
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)
|
|
1262
|
-
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)
|
|
1263
|
-
`).run({
|
|
1264
|
-
id,
|
|
1265
|
-
work_item_id: workItemId,
|
|
1266
|
-
scope_type: scopeType,
|
|
1267
|
-
scope_id: scopeId,
|
|
1268
|
-
key,
|
|
1269
|
-
value_json: JSON.stringify(value),
|
|
1270
|
-
state,
|
|
1271
|
-
source_event_id: sourceEventId,
|
|
1272
|
-
source_artifact_id: sourceArtifactId,
|
|
1273
|
-
valid_for_sha: validForSha,
|
|
1274
|
-
valid_for_content_hash: validForContentHash,
|
|
1275
|
-
valid_for_manifest_hash: validForManifestHash,
|
|
1276
|
-
watched_paths: JSON.stringify(watchedPaths.map((path) => isAbsolute(path) ? resolve(path) : path)),
|
|
1277
|
-
expires_at: expiresAt,
|
|
1278
|
-
supersedes_id: supersedesId,
|
|
1279
|
-
created_at: now,
|
|
1280
|
-
verified_at: verifiedAt ?? (state === "verified" ? now : null),
|
|
1281
|
-
verified_by: verifiedBy ?? (state === "verified" ? "supervisor" : null)
|
|
1282
|
-
});
|
|
1283
|
-
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 };
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
function pathsOverlap(left, right) {
|
|
1287
|
-
const normalize = (path) => process.platform === "win32" ? path.replace(/\\/g, "/").toLowerCase() : path;
|
|
1288
|
-
const a = normalize(left).replace(/\/$/, "");
|
|
1289
|
-
const b = normalize(right).replace(/\/$/, "");
|
|
1290
|
-
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
function repoRelativePaths(projectRoot, paths) {
|
|
1294
|
-
return (paths ?? []).flatMap((path) => {
|
|
1295
|
-
if (typeof path !== "string" || !path.trim()) return [];
|
|
1296
|
-
const candidate = isAbsolute(path) ? relative(projectRoot, path) : path;
|
|
1297
|
-
const normalized = candidate.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
|
|
1298
|
-
return !normalized || normalized === ".." || normalized.startsWith("../") ? [] : [normalized];
|
|
1299
|
-
});
|
|
1300
|
-
}
|
|
1301
|
-
|
|
1302
|
-
function git(cwd, args) {
|
|
1303
|
-
return execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", cwd, ...args], {
|
|
1304
|
-
encoding: "utf8",
|
|
1305
|
-
timeout: 15000,
|
|
1306
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
1307
|
-
}).trim();
|
|
1308
|
-
}
|
|
1309
|
-
|
|
1310
|
-
function shaCoversBase(projectRoot, validForSha, baseSha) {
|
|
1311
|
-
if (!validForSha || !baseSha) return true;
|
|
1312
|
-
try {
|
|
1313
|
-
git(projectRoot, ["merge-base", "--is-ancestor", validForSha, baseSha]);
|
|
1314
|
-
return true;
|
|
1315
|
-
} catch {
|
|
1316
|
-
return false;
|
|
1317
|
-
}
|
|
1318
|
-
}
|
|
1319
|
-
|
|
1320
|
-
function watchedPathsChanged(projectRoot, validForSha, baseSha, watchedPaths) {
|
|
1321
|
-
if (!validForSha || !baseSha || watchedPaths.length === 0) return false;
|
|
1322
|
-
try {
|
|
1323
|
-
const relativePaths = repoRelativePaths(projectRoot, watchedPaths);
|
|
1324
|
-
if (relativePaths.length === 0) return true;
|
|
1325
|
-
return Boolean(git(projectRoot, ["diff", "--name-only", validForSha, baseSha, "--", ...relativePaths]));
|
|
1326
|
-
} catch {
|
|
1327
|
-
return true;
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
|
|
1331
|
-
async function currentWorkspaceManifest(task) {
|
|
1332
|
-
const metadata = task.workspace_metadata;
|
|
1333
|
-
if (!metadata?.source_root || !Array.isArray(metadata.manifest_paths) || metadata.manifest_paths.length === 0) return null;
|
|
1334
|
-
try {
|
|
1335
|
-
return await captureWorkspaceManifest(metadata.source_root, metadata.manifest_paths);
|
|
1336
|
-
} catch {
|
|
1337
|
-
return null;
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
|
|
1341
|
-
async function currentContextContentHash(task) {
|
|
1342
|
-
const context = task.input_context?.context ?? [];
|
|
1343
|
-
if (!Array.isArray(context) || context.length === 0) return null;
|
|
1344
|
-
try {
|
|
1345
|
-
return (await buildHandoff({ context }, { maxLines: 1, maxChars: 1 })).content_hash;
|
|
1346
|
-
} catch {
|
|
1347
|
-
return null;
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
|
-
|
|
1351
|
-
function markFactExpired(id) {
|
|
1352
|
-
openDb().prepare(`
|
|
1353
|
-
INSERT INTO facts (id, work_item_id, scope_type, scope_id, key, value_json, state, source_event_id, source_artifact_id,
|
|
1354
|
-
valid_for_sha, valid_for_content_hash, valid_for_manifest_hash, watched_paths, expires_at, supersedes_id, created_at, verified_at, verified_by)
|
|
1355
|
-
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,
|
|
1356
|
-
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
|
|
1357
|
-
FROM facts AS source
|
|
1358
|
-
WHERE source.id = ? AND source.state = 'verified'
|
|
1359
|
-
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = source.id AND transition.state IN ('expired', 'revoked'))
|
|
1360
|
-
`).run(randomUUID(), new Date().toISOString(), id);
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
export async function listContextFacts({ taskId, baseSha, ownedPaths = [], dependencyTaskIds = [] }) {
|
|
1364
|
-
await ensureFilesystem();
|
|
1365
|
-
const workItem = await getWorkItemForTask(taskId);
|
|
1366
|
-
if (!workItem) return [];
|
|
1367
|
-
const task = await getTask(taskId);
|
|
1368
|
-
if (!task) return [];
|
|
1369
|
-
const dependencyItems = dependencyTaskIds.length === 0
|
|
1370
|
-
? []
|
|
1371
|
-
: openDb().prepare(`SELECT id FROM work_items WHERE task_id IN (${dependencyTaskIds.map(() => "?").join(",")})`).all(...dependencyTaskIds).map((row) => row.id);
|
|
1372
|
-
const rows = openDb().prepare(`
|
|
1373
|
-
SELECT facts.* FROM facts
|
|
1374
|
-
WHERE state = 'verified'
|
|
1375
|
-
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
1376
|
-
ORDER BY created_at ASC
|
|
1377
|
-
`).all();
|
|
1378
|
-
const now = Date.now();
|
|
1379
|
-
const workspaceManifest = await currentWorkspaceManifest(task);
|
|
1380
|
-
const contextContentHash = await currentContextContentHash(task);
|
|
1381
|
-
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
1382
|
-
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
1383
|
-
const ownedRelative = repoRelativePaths(task.project_root, ownedPaths);
|
|
1384
|
-
const visible = [];
|
|
1385
|
-
for (const row of rows) {
|
|
1386
|
-
const watched = decodeJson(row.watched_paths, []);
|
|
1387
|
-
const watchedRelative = repoRelativePaths(task.project_root, watched);
|
|
1388
|
-
const included = row.scope_type === "work_item" ? row.scope_id === workItem.id
|
|
1389
|
-
: row.scope_type === "dependency" ? dependencyItems.includes(row.scope_id)
|
|
1390
|
-
: row.scope_type === "repo_verified" && canonicalRemote && row.scope_id === canonicalRemote
|
|
1391
|
-
&& watchedRelative.length > 0 && watchedRelative.some((path) => ownedRelative.some((owned) => pathsOverlap(path, owned)));
|
|
1392
|
-
if (!included) continue;
|
|
1393
|
-
if (row.expires_at && Date.parse(row.expires_at) <= now) {
|
|
1394
|
-
markFactExpired(row.id);
|
|
1395
|
-
continue;
|
|
1396
|
-
}
|
|
1397
|
-
if (!shaCoversBase(task.project_root, row.valid_for_sha, baseSha)) continue;
|
|
1398
|
-
if (watchedPathsChanged(task.project_root, row.valid_for_sha, baseSha, watchedRelative)) {
|
|
1399
|
-
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
1400
|
-
continue;
|
|
1401
|
-
}
|
|
1402
|
-
if (row.valid_for_manifest_hash && (!workspaceManifest || workspaceManifest.sha256 !== row.valid_for_manifest_hash)) {
|
|
1403
|
-
if (row.scope_type === "work_item" && row.scope_id === workItem.id && workspaceManifest) markFactExpired(row.id);
|
|
1404
|
-
continue;
|
|
1405
|
-
}
|
|
1406
|
-
if (row.valid_for_content_hash && contextContentHash !== row.valid_for_content_hash) {
|
|
1407
|
-
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
1408
|
-
continue;
|
|
1409
|
-
}
|
|
1410
|
-
visible.push({
|
|
1411
|
-
...row,
|
|
1412
|
-
value: decodeJson(row.value_json, null),
|
|
1413
|
-
watched_paths: watched
|
|
1414
|
-
});
|
|
1415
|
-
}
|
|
1416
|
-
return visible;
|
|
1417
|
-
}
|
|
1418
|
-
|
|
1419
|
-
export async function countVerifiedFacts() {
|
|
1420
|
-
await ensureFilesystem();
|
|
1421
|
-
return openDb().prepare(`
|
|
1422
|
-
SELECT COUNT(*) AS count FROM facts
|
|
1423
|
-
WHERE state = 'verified'
|
|
1424
|
-
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
1425
|
-
`).get().count;
|
|
1426
|
-
}
|
|
1427
|
-
|
|
1428
|
-
export async function createContextSnapshot({ runId, recipient = "worker", factIds = [], baseSha = null, prompt, estimatedTokens, excluded = {} }) {
|
|
1429
|
-
await ensureFilesystem();
|
|
1430
|
-
if (!runId || typeof prompt !== "string") throw new Error("context snapshot requires runId and prompt");
|
|
1431
|
-
const now = new Date().toISOString();
|
|
1432
|
-
const id = randomUUID();
|
|
1433
|
-
openDb().prepare(`
|
|
1434
|
-
INSERT INTO context_snapshots (id, run_id, recipient, fact_versions, base_sha, prompt_sha256, estimated_tokens, excluded_json, created_at)
|
|
1435
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1436
|
-
`).run(id, runId, recipient, JSON.stringify(factIds), baseSha,
|
|
1437
|
-
createHash("sha256").update(prompt).digest("hex"), estimatedTokens, JSON.stringify(excluded), now);
|
|
1438
|
-
return { id, run_id: runId, recipient, fact_versions: factIds, base_sha: baseSha, estimated_tokens: estimatedTokens, created_at: now };
|
|
1439
|
-
}
|
|
1440
|
-
|
|
1441
|
-
export async function latestContextSnapshotForTask(taskId) {
|
|
1442
|
-
await ensureFilesystem();
|
|
1443
|
-
return openDb().prepare(`
|
|
1444
|
-
SELECT s.* FROM context_snapshots s JOIN runs r ON r.id = s.run_id
|
|
1445
|
-
WHERE r.task_id = ? ORDER BY s.created_at DESC LIMIT 1
|
|
1446
|
-
`).get(taskId) ?? null;
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
|
-
export async function getFact(factId) {
|
|
1450
|
-
await ensureFilesystem();
|
|
1451
|
-
const row = openDb().prepare("SELECT * FROM facts WHERE id = ?").get(factId);
|
|
1452
|
-
if (!row) return null;
|
|
1453
|
-
return {
|
|
1454
|
-
...row,
|
|
1455
|
-
value: decodeJson(row.value_json, null),
|
|
1456
|
-
watched_paths: decodeJson(row.watched_paths, [])
|
|
1457
|
-
};
|
|
1458
|
-
}
|
|
1459
|
-
|
|
1460
|
-
export async function getTaskForWorkItem(workItemId) {
|
|
1461
|
-
await ensureFilesystem();
|
|
1462
|
-
return openDb().prepare("SELECT * FROM tasks WHERE id = (SELECT task_id FROM work_items WHERE id = ?)").get(workItemId) ?? null;
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
export async function isFactRevoked(factId) {
|
|
1466
|
-
await ensureFilesystem();
|
|
1467
|
-
return Boolean(openDb().prepare("SELECT 1 FROM facts WHERE supersedes_id = ? AND state = 'revoked'").get(factId));
|
|
1468
|
-
}
|
|
1469
|
-
|
|
1470
|
-
export async function getFactEffectiveState(factId) {
|
|
1471
|
-
await ensureFilesystem();
|
|
1472
|
-
const transition = openDb().prepare(`
|
|
1473
|
-
SELECT state FROM facts WHERE supersedes_id = ? AND state IN ('revoked', 'expired')
|
|
1474
|
-
ORDER BY CASE state WHEN 'revoked' THEN 0 ELSE 1 END, created_at DESC LIMIT 1
|
|
1475
|
-
`).get(factId);
|
|
1476
|
-
return transition?.state ?? null;
|
|
1477
|
-
}
|
|
1478
|
-
|
|
1479
|
-
export async function promoteCandidateFact({ factId, scopeType = "work_item", watchedPaths = null, expiresAt = null, sourceEventId = null, verifiedBy = "main_thread" }) {
|
|
1480
|
-
await ensureFilesystem();
|
|
1481
|
-
const source = await getFact(factId);
|
|
1482
|
-
if (!source) throw new Error(`fact not found: ${factId}`);
|
|
1483
|
-
if (await isFactRevoked(factId)) {
|
|
1484
|
-
const error = new Error(`fact ${factId} is already revoked`);
|
|
1485
|
-
error.code = "fact_already_revoked";
|
|
1486
|
-
throw error;
|
|
1487
|
-
}
|
|
1488
|
-
if (source.state !== "candidate") {
|
|
1489
|
-
const error = new Error(`only candidate facts may be promoted; ${factId} is ${source.state}`);
|
|
1490
|
-
error.code = "fact_not_candidate";
|
|
1491
|
-
throw error;
|
|
1492
|
-
}
|
|
1493
|
-
if (!['work_item', 'repo_verified'].includes(scopeType)) throw new Error("promotion scope must be work_item or repo_verified");
|
|
1494
|
-
const workItem = openDb().prepare("SELECT * FROM work_items WHERE id = ?").get(source.work_item_id);
|
|
1495
|
-
if (!workItem) throw new Error(`work item not found for fact: ${factId}`);
|
|
1496
|
-
const sourceTask = await getTaskForWorkItem(workItem.id);
|
|
1497
|
-
const paths = watchedPaths ?? source.watched_paths ?? [];
|
|
1498
|
-
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
1499
|
-
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
1500
|
-
const normalizedRepoPaths = sourceTask ? repoRelativePaths(sourceTask.project_root, paths) : [];
|
|
1501
|
-
if (scopeType === "repo_verified" && paths.length === 0) {
|
|
1502
|
-
const error = new Error("repo_verified promotion requires watchedPaths so unrelated work cannot inherit it");
|
|
1503
|
-
error.code = "repo_fact_requires_paths";
|
|
1504
|
-
throw error;
|
|
1505
|
-
}
|
|
1506
|
-
if (scopeType === "repo_verified" && !canonicalRemote) {
|
|
1507
|
-
const error = new Error("repo_verified promotion requires a canonical origin remote; facts from an unrecognized or missing remote stay work-scoped");
|
|
1508
|
-
error.code = "repo_fact_requires_canonical_remote";
|
|
1509
|
-
throw error;
|
|
1510
|
-
}
|
|
1511
|
-
if (scopeType === "repo_verified" && normalizedRepoPaths.length === 0) {
|
|
1512
|
-
const error = new Error("repo_verified watchedPaths must stay inside the repository root");
|
|
1513
|
-
error.code = "repo_fact_paths_outside_root";
|
|
1514
|
-
throw error;
|
|
1515
|
-
}
|
|
1516
|
-
return recordFact({
|
|
1517
|
-
workItemId: source.work_item_id,
|
|
1518
|
-
scopeType,
|
|
1519
|
-
scopeId: scopeType === "repo_verified" ? canonicalRemote : workItem.id,
|
|
1520
|
-
key: source.key,
|
|
1521
|
-
value: source.value,
|
|
1522
|
-
state: "verified",
|
|
1523
|
-
sourceEventId,
|
|
1524
|
-
sourceArtifactId: source.source_artifact_id ?? null,
|
|
1525
|
-
validForSha: source.valid_for_sha ?? null,
|
|
1526
|
-
validForContentHash: source.valid_for_content_hash ?? null,
|
|
1527
|
-
validForManifestHash: source.valid_for_manifest_hash ?? null,
|
|
1528
|
-
watchedPaths: scopeType === "repo_verified" ? normalizedRepoPaths : paths,
|
|
1529
|
-
expiresAt: expiresAt ?? source.expires_at ?? null,
|
|
1530
|
-
supersedesId: source.id,
|
|
1531
|
-
verifiedBy
|
|
1532
|
-
});
|
|
1533
|
-
}
|
|
1534
|
-
|
|
1535
|
-
export async function revokeFact(factId) {
|
|
1536
|
-
await ensureFilesystem();
|
|
1537
|
-
const source = await getFact(factId);
|
|
1538
|
-
if (!source) return null;
|
|
1539
|
-
if (!["candidate", "verified"].includes(source.state)) {
|
|
1540
|
-
const error = new Error(`only candidate or verified facts may be revoked; ${factId} is ${source.state}`);
|
|
1541
|
-
error.code = "fact_not_revocable";
|
|
1542
|
-
throw error;
|
|
1543
|
-
}
|
|
1544
|
-
if (await isFactRevoked(factId)) {
|
|
1545
|
-
const error = new Error(`fact ${factId} is already revoked`);
|
|
1546
|
-
error.code = "fact_already_revoked";
|
|
1547
|
-
throw error;
|
|
1548
|
-
}
|
|
1549
|
-
return recordFact({
|
|
1550
|
-
workItemId: source.work_item_id,
|
|
1551
|
-
scopeType: source.scope_type,
|
|
1552
|
-
scopeId: source.scope_id,
|
|
1553
|
-
key: source.key,
|
|
1554
|
-
value: source.value,
|
|
1555
|
-
state: "revoked",
|
|
1556
|
-
sourceEventId: source.source_event_id,
|
|
1557
|
-
sourceArtifactId: source.source_artifact_id,
|
|
1558
|
-
validForSha: source.valid_for_sha,
|
|
1559
|
-
validForContentHash: source.valid_for_content_hash,
|
|
1560
|
-
validForManifestHash: source.valid_for_manifest_hash,
|
|
1561
|
-
watchedPaths: source.watched_paths,
|
|
1562
|
-
expiresAt: source.expires_at,
|
|
1563
|
-
supersedesId: source.id,
|
|
1564
|
-
verifiedBy: "main_thread"
|
|
1565
|
-
});
|
|
1566
|
-
}
|
|
1567
|
-
|
|
1568
|
-
export async function recordJsonArtifact({ runId, type, value, securityClass = "internal", retention = "permanent" }) {
|
|
1569
|
-
await ensureFilesystem();
|
|
1570
|
-
if (!runId || !type) throw new Error("artifact requires runId and type");
|
|
1571
|
-
const id = randomUUID();
|
|
1572
|
-
const content = JSON.stringify(value, null, 2);
|
|
1573
|
-
const sha256 = createHash("sha256").update(content).digest("hex");
|
|
1574
|
-
const path = join(artifactsDir, `${id}.json`);
|
|
1575
|
-
await writeFile(path, content, { encoding: "utf8", mode: 0o600 });
|
|
1576
|
-
const now = new Date().toISOString();
|
|
1577
|
-
openDb().prepare(`
|
|
1578
|
-
INSERT INTO artifacts (id, run_id, type, uri, sha256, security_class, retention, created_at)
|
|
1579
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1580
|
-
`).run(id, runId, type, path, sha256, securityClass, retention, now);
|
|
1581
|
-
return { id, run_id: runId, type, uri: path, sha256, security_class: securityClass, retention, created_at: now };
|
|
1582
|
-
}
|
|
1583
|
-
|
|
1584
|
-
export async function getArtifact(artifactId) {
|
|
1585
|
-
await ensureFilesystem();
|
|
1586
|
-
return openDb().prepare("SELECT * FROM artifacts WHERE id = ?").get(artifactId) ?? null;
|
|
1587
|
-
}
|
|
1588
|
-
|
|
1589
|
-
export async function readArtifact(artifactId, maxChars = 12000) {
|
|
1590
|
-
const artifact = await getArtifact(artifactId);
|
|
1591
|
-
if (!artifact) return null;
|
|
1592
|
-
const artifactPath = relative(artifactsDir, resolve(artifact.uri));
|
|
1593
|
-
if (!artifactPath || artifactPath === ".." || artifactPath.startsWith(`..${sep}`) || isAbsolute(artifactPath)) {
|
|
1594
|
-
return { ...artifact, content: null, reason: "artifact_uri_not_managed" };
|
|
1595
|
-
}
|
|
1596
|
-
let content;
|
|
1597
|
-
try {
|
|
1598
|
-
content = await readFile(artifact.uri, "utf8");
|
|
1599
|
-
} catch (error) {
|
|
1600
|
-
return { ...artifact, content: null, reason: `artifact_unreadable: ${error.code ?? error.message}` };
|
|
1601
|
-
}
|
|
1602
|
-
const truncated = content.length > maxChars;
|
|
1603
|
-
return { ...artifact, content: truncated ? `${content.slice(0, maxChars)}…` : content, truncated };
|
|
1604
|
-
}
|
|
1605
|
-
|
|
1606
|
-
export async function listArtifactsForTask(taskId, limit = 50) {
|
|
1607
|
-
await ensureFilesystem();
|
|
1608
|
-
return openDb().prepare(`
|
|
1609
|
-
SELECT a.* FROM artifacts a JOIN runs r ON r.id = a.run_id
|
|
1610
|
-
WHERE r.task_id = ? ORDER BY a.created_at DESC LIMIT ?
|
|
1611
|
-
`).all(taskId, limit);
|
|
1612
|
-
}
|
|
1613
|
-
|
|
1614
|
-
export async function createReviewAssignment({ subjectTaskId, verifierTaskId, subjectRunId = null, subjectBaseSha = null, subjectFingerprint = null }) {
|
|
1615
|
-
await ensureFilesystem();
|
|
1616
|
-
const now = new Date().toISOString();
|
|
1617
|
-
const id = randomUUID();
|
|
1618
|
-
openDb().prepare(`
|
|
1619
|
-
INSERT INTO review_findings (id, subject_task_id, verifier_task_id, subject_run_id, subject_base_sha, subject_fingerprint, status, created_at, updated_at)
|
|
1620
|
-
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)
|
|
1621
|
-
`).run(id, subjectTaskId, verifierTaskId, subjectRunId, subjectBaseSha, subjectFingerprint, now, now);
|
|
1622
|
-
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 };
|
|
1623
|
-
}
|
|
1624
|
-
|
|
1625
|
-
export async function getReviewByVerifierTask(verifierTaskId) {
|
|
1626
|
-
await ensureFilesystem();
|
|
1627
|
-
return openDb().prepare("SELECT * FROM review_findings WHERE verifier_task_id = ?").get(verifierTaskId) ?? null;
|
|
1628
|
-
}
|
|
1629
|
-
|
|
1630
|
-
export async function recordReviewFinding({ verifierTaskId, verdict, reason, evidenceArtifactId = null, findingEventId = null }) {
|
|
1631
|
-
await ensureFilesystem();
|
|
1632
|
-
if (!['passes', 'fails', 'inconclusive'].includes(verdict)) throw new Error("review verdict must be passes, fails or inconclusive");
|
|
1633
|
-
const now = new Date().toISOString();
|
|
1634
|
-
const result = openDb().prepare(`
|
|
1635
|
-
UPDATE review_findings
|
|
1636
|
-
SET status = 'recorded', verdict = ?, reason = ?, evidence_artifact_id = ?, finding_event_id = ?, updated_at = ?
|
|
1637
|
-
WHERE verifier_task_id = ? AND status = 'pending'
|
|
1638
|
-
`).run(verdict, reason, evidenceArtifactId, findingEventId, now, verifierTaskId);
|
|
1639
|
-
if (result.changes === 0) return null;
|
|
1640
|
-
return getReviewByVerifierTask(verifierTaskId);
|
|
1641
|
-
}
|
|
1642
|
-
|
|
1643
|
-
export async function resolveReviewFinding({ verifierTaskId, resolution, resolvedBy = 'main_thread' }) {
|
|
1644
|
-
await ensureFilesystem();
|
|
1645
|
-
const now = new Date().toISOString();
|
|
1646
|
-
const result = openDb().prepare(`
|
|
1647
|
-
UPDATE review_findings
|
|
1648
|
-
SET status = 'resolved', resolution = ?, resolved_at = ?, resolved_by = ?, updated_at = ?
|
|
1649
|
-
WHERE verifier_task_id = ? AND status = 'recorded'
|
|
1650
|
-
`).run(resolution, now, resolvedBy, now, verifierTaskId);
|
|
1651
|
-
if (result.changes === 0) return null;
|
|
1652
|
-
return getReviewByVerifierTask(verifierTaskId);
|
|
1653
|
-
}
|
|
1654
|
-
|
|
1655
|
-
export async function updateWorkItemDelivery(taskId, deliveryState) {
|
|
1656
|
-
await ensureFilesystem();
|
|
1657
|
-
if (!["draft", "verified", "landed", "push_verified", "cleanup_eligible", "cleanup_removed", "needs_attention"].includes(deliveryState)) {
|
|
1658
|
-
throw new Error("invalid delivery state");
|
|
1659
|
-
}
|
|
1660
|
-
const result = openDb().prepare("UPDATE work_items SET delivery_state = ?, updated_at = ? WHERE task_id = ?")
|
|
1661
|
-
.run(deliveryState, new Date().toISOString(), taskId);
|
|
1662
|
-
return result.changes > 0;
|
|
1663
|
-
}
|
|
1664
|
-
|
|
1665
|
-
export async function saveCleanupPlan(plan) {
|
|
1666
|
-
await ensureFilesystem();
|
|
1667
|
-
const dbInstance = openDb();
|
|
1668
|
-
dbInstance.exec("BEGIN IMMEDIATE");
|
|
1669
|
-
try {
|
|
1670
|
-
dbInstance.prepare(`
|
|
1671
|
-
INSERT INTO cleanup_plans (id, project_root, generated_at, expires_at, policy, summary_json)
|
|
1672
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
1673
|
-
`).run(plan.id, plan.project_root, plan.generated_at, plan.expires_at, plan.policy, JSON.stringify(plan.summary));
|
|
1674
|
-
const insert = dbInstance.prepare(`
|
|
1675
|
-
INSERT INTO cleanup_plan_items (id, plan_id, task_id, verdict, reasons_json, fingerprint, reclaimable_bytes, eligible_after, applied_at, applied_by)
|
|
1676
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)
|
|
1677
|
-
`);
|
|
1678
|
-
for (const item of plan.items) {
|
|
1679
|
-
item.id = item.id ?? randomUUID();
|
|
1680
|
-
insert.run(item.id, plan.id, item.task_id, item.verdict, JSON.stringify(item.reasons), item.fingerprint, item.reclaimable_bytes, item.eligible_after);
|
|
1681
|
-
if (item.verdict === "safe") {
|
|
1682
|
-
dbInstance.prepare("UPDATE work_items SET delivery_state = 'cleanup_eligible', updated_at = ? WHERE task_id = ? AND delivery_state = 'push_verified'")
|
|
1683
|
-
.run(new Date().toISOString(), item.task_id);
|
|
1684
|
-
} else {
|
|
1685
|
-
dbInstance.prepare("UPDATE work_items SET delivery_state = 'push_verified', updated_at = ? WHERE task_id = ? AND delivery_state = 'cleanup_eligible'")
|
|
1686
|
-
.run(new Date().toISOString(), item.task_id);
|
|
1687
|
-
}
|
|
1688
|
-
}
|
|
1689
|
-
dbInstance.exec("COMMIT");
|
|
1690
|
-
} catch (error) {
|
|
1691
|
-
dbInstance.exec("ROLLBACK");
|
|
1692
|
-
throw error;
|
|
1693
|
-
}
|
|
1694
|
-
}
|
|
1695
|
-
|
|
1696
|
-
export async function getCleanupPlan(planId) {
|
|
1697
|
-
await ensureFilesystem();
|
|
1698
|
-
const plan = openDb().prepare("SELECT * FROM cleanup_plans WHERE id = ?").get(planId);
|
|
1699
|
-
if (!plan) return null;
|
|
1700
|
-
const items = openDb().prepare("SELECT * FROM cleanup_plan_items WHERE plan_id = ? ORDER BY task_id").all(planId).map((item) => ({
|
|
1701
|
-
...item,
|
|
1702
|
-
reasons: decodeJson(item.reasons_json, [])
|
|
1703
|
-
}));
|
|
1704
|
-
return { ...plan, summary: decodeJson(plan.summary_json, {}), items };
|
|
1705
|
-
}
|
|
1706
|
-
|
|
1707
|
-
export async function markCleanupPlanItemApplied(itemId, actor = "main_thread") {
|
|
1708
|
-
await ensureFilesystem();
|
|
1709
|
-
const now = new Date().toISOString();
|
|
1710
|
-
openDb().prepare("UPDATE cleanup_plan_items SET applied_at = ?, applied_by = ? WHERE id = ? AND applied_at IS NULL")
|
|
1711
|
-
.run(now, actor, itemId);
|
|
1712
|
-
return now;
|
|
1713
|
-
}
|
|
1714
|
-
|
|
1715
|
-
export async function readCleanupHistory(taskId = null, limit = 100) {
|
|
1716
|
-
await ensureFilesystem();
|
|
1717
|
-
const rows = taskId
|
|
1718
|
-
? 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)
|
|
1719
|
-
: 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);
|
|
1720
|
-
return rows.map((row) => ({ ...row, reasons: decodeJson(row.reasons_json, []) }));
|
|
1721
|
-
}
|
|
1722
|
-
|
|
1723
|
-
export async function listTaskEventKinds(taskId) {
|
|
1724
|
-
await ensureFilesystem();
|
|
1725
|
-
return openDb().prepare(`
|
|
1726
|
-
SELECT event_type AS kind, COUNT(*) AS count
|
|
1727
|
-
FROM task_events WHERE task_id = ? GROUP BY event_type ORDER BY count DESC
|
|
1728
|
-
`).all(taskId);
|
|
1729
|
-
}
|
|
1730
|
-
|
|
1731
|
-
// A worker's report is the only thing a supervisor usually wants back, and the
|
|
1732
|
-
// task row keeps just the most recent one. This reads them out of the raw
|
|
1733
|
-
// stream newest-first: `payload LIKE` is a cheap prefilter, and every row that
|
|
1734
|
-
// survives it is verified through the same extraction the state machine uses.
|
|
1735
|
-
export async function readAgentMessages(taskId, limit = 1) {
|
|
1736
|
-
await ensureFilesystem();
|
|
1737
|
-
const rows = openDb().prepare(`
|
|
1738
|
-
SELECT payload FROM task_events
|
|
1739
|
-
WHERE task_id = ? AND event_type = 'item.completed' AND payload LIKE '%"agent_message"%'
|
|
1740
|
-
ORDER BY seq DESC LIMIT ?
|
|
1741
|
-
`).all(taskId, limit * 5 + 10);
|
|
1742
|
-
const messages = [];
|
|
1743
|
-
for (const row of rows) {
|
|
1744
|
-
let text = null;
|
|
1745
|
-
try {
|
|
1746
|
-
text = extractAgentMessage(JSON.parse(row.payload));
|
|
1747
|
-
} catch {
|
|
1748
|
-
text = null;
|
|
1749
|
-
}
|
|
1750
|
-
if (text) messages.push(text);
|
|
1751
|
-
if (messages.length >= limit) break;
|
|
1752
|
-
}
|
|
1753
|
-
return messages.reverse();
|
|
1754
|
-
}
|
|
1755
|
-
|
|
1756
|
-
export async function taskCount() {
|
|
1757
|
-
await ensureFilesystem();
|
|
1758
|
-
const row = openDb().prepare("SELECT COUNT(*) AS count FROM tasks").get();
|
|
1759
|
-
return row.count;
|
|
1760
|
-
}
|
|
1761
|
-
|
|
1762
|
-
export async function taskExists(taskId) {
|
|
1763
|
-
return Boolean(await getTask(taskId));
|
|
1764
|
-
}
|
|
1765
|
-
|
|
1766
|
-
export async function taskHasEvents(taskId) {
|
|
1767
|
-
await ensureFilesystem();
|
|
1768
|
-
const row = openDb().prepare("SELECT 1 FROM task_events WHERE task_id = ? LIMIT 1").get(taskId);
|
|
1769
|
-
return Boolean(row);
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
export async function taskEventCount(taskId) {
|
|
1773
|
-
await ensureFilesystem();
|
|
1774
|
-
const row = openDb().prepare("SELECT COUNT(*) AS count FROM task_events WHERE task_id = ?").get(taskId);
|
|
1775
|
-
return row.count;
|
|
1776
|
-
}
|
|
1777
|
-
|
|
1778
|
-
export async function deleteTasks(taskIds) {
|
|
1779
|
-
await ensureFilesystem();
|
|
1780
|
-
if (taskIds.length === 0) return;
|
|
1781
|
-
const dbInstance = openDb();
|
|
1782
|
-
const deleteEvents = dbInstance.prepare("DELETE FROM task_events WHERE task_id = ?");
|
|
1783
|
-
const deleteTask = dbInstance.prepare("DELETE FROM tasks WHERE id = ?");
|
|
1784
|
-
dbInstance.exec("BEGIN IMMEDIATE;");
|
|
1785
|
-
try {
|
|
1786
|
-
for (const taskId of taskIds) {
|
|
1787
|
-
deleteEvents.run(taskId);
|
|
1788
|
-
deleteTask.run(taskId);
|
|
1789
|
-
}
|
|
1790
|
-
dbInstance.exec("COMMIT;");
|
|
1791
|
-
} catch (error) {
|
|
1792
|
-
dbInstance.exec("ROLLBACK;");
|
|
1793
|
-
throw error;
|
|
1794
|
-
}
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
export async function vacuumStore() {
|
|
1798
|
-
await ensureFilesystem();
|
|
1799
|
-
openDb().exec("VACUUM;");
|
|
1800
|
-
}
|