codex-supervisor-mcp 0.13.5 → 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/package.json +18 -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} +11 -12
- 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 -265
- 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 -3
- 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} +56 -41
- 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} +7 -6
- 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
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { PHASES } from "../../domain/status.js";
|
|
2
|
+
import { artifactsDir, dataDir, dbPath, runsDir } from "../paths.js";
|
|
3
|
+
import { git } from "./facts.js";
|
|
4
|
+
import { CONTROL_DDL, POST_V1_COLUMNS, SESSIONS_DDL, SIDE_DDL, TASK_COLUMNS, TASK_EVENTS_DDL, TASK_EVENTS_INDEX_DDL, TASK_EXTRA_COLUMNS, TASKS_DDL, TASKS_SESSION_INDEX_DDL } from "./schema.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { mkdir } from "node:fs/promises";
|
|
7
|
+
import { isAbsolute, resolve } from "node:path";
|
|
8
|
+
import { DatabaseSync } from "node:sqlite";
|
|
9
|
+
|
|
10
|
+
let db;
|
|
11
|
+
|
|
12
|
+
function tableColumns(dbInstance, tableName) {
|
|
13
|
+
return dbInstance.prepare(`PRAGMA table_info(${tableName})`).all();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// v1 stored progress phases ("editing", "command", "reporting") in the status
|
|
17
|
+
// column and required phase to be non-null. Both have to change, and SQLite
|
|
18
|
+
// cannot relax NOT NULL in place, so the table is rebuilt once.
|
|
19
|
+
function migrateTasksTable(dbInstance, columns) {
|
|
20
|
+
const phaseColumn = columns.find((column) => column.name === "phase");
|
|
21
|
+
const isCurrentSchema = POST_V1_COLUMNS.every(([name]) => columns.some((column) => column.name === name))
|
|
22
|
+
&& phaseColumn
|
|
23
|
+
&& !phaseColumn.notnull;
|
|
24
|
+
if (isCurrentSchema) return { migrated: false, rows: 0 };
|
|
25
|
+
|
|
26
|
+
const legacyNames = new Set(columns.map((column) => column.name));
|
|
27
|
+
const rows = dbInstance.prepare("SELECT COUNT(*) AS count FROM tasks").get().count;
|
|
28
|
+
|
|
29
|
+
const selectExpression = (name) => {
|
|
30
|
+
if (legacyNames.has(name)) return name;
|
|
31
|
+
const definition = [...POST_V1_COLUMNS, ...TASK_EXTRA_COLUMNS].find(([columnName]) => columnName === name);
|
|
32
|
+
if (definition && definition[1].includes("DEFAULT '[]'")) return "'[]'";
|
|
33
|
+
if (definition && definition[1].includes("DEFAULT 'legacy'")) return "'legacy'";
|
|
34
|
+
if (definition && definition[1].includes("DEFAULT 0")) return "0";
|
|
35
|
+
return "NULL";
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const statusExpression = legacyNames.has("status")
|
|
39
|
+
? `CASE WHEN status IN ('editing','command','command_completed','reporting') THEN 'running' ELSE status END`
|
|
40
|
+
: "'failed'";
|
|
41
|
+
|
|
42
|
+
const phaseExpression = legacyNames.has("phase")
|
|
43
|
+
? `CASE
|
|
44
|
+
WHEN status IN ('editing','command','reporting') THEN status
|
|
45
|
+
WHEN status = 'command_completed' THEN 'command'
|
|
46
|
+
WHEN status = 'running' THEN CASE WHEN phase IN (${PHASES.map((p) => `'${p}'`).join(",")}) THEN phase ELSE 'starting' END
|
|
47
|
+
ELSE NULL
|
|
48
|
+
END`
|
|
49
|
+
: "NULL";
|
|
50
|
+
|
|
51
|
+
{
|
|
52
|
+
dbInstance.exec("ALTER TABLE tasks RENAME TO tasks_legacy_v1;");
|
|
53
|
+
dbInstance.exec(TASKS_DDL);
|
|
54
|
+
const selectList = TASK_COLUMNS.map((name) => {
|
|
55
|
+
if (name === "status") return `${statusExpression} AS status`;
|
|
56
|
+
if (name === "phase") return `${phaseExpression} AS phase`;
|
|
57
|
+
return `${selectExpression(name)} AS ${name}`;
|
|
58
|
+
}).join(", ");
|
|
59
|
+
dbInstance.exec(`INSERT INTO tasks (${TASK_COLUMNS.join(", ")}) SELECT ${selectList} FROM tasks_legacy_v1;`);
|
|
60
|
+
dbInstance.exec("DROP TABLE tasks_legacy_v1;");
|
|
61
|
+
}
|
|
62
|
+
return { migrated: true, rows };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function sleepSync(ms) {
|
|
66
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isBusyError(error) {
|
|
70
|
+
return /SQLITE_BUSY|database is locked|database table is locked/i.test(String(error?.message ?? ""));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Several MCP processes may open a brand-new database at the same moment, so
|
|
74
|
+
// schema setup runs inside one immediate transaction (which the busy timeout
|
|
75
|
+
// makes wait instead of failing) and is retried if the file is still locked.
|
|
76
|
+
export function runWithRetry(dbInstance, work, attempts = 10) {
|
|
77
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
78
|
+
try {
|
|
79
|
+
return work();
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (attempt === attempts - 1 || !isBusyError(error)) throw error;
|
|
82
|
+
sleepSync(50 * (attempt + 1));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function initializeSchema(dbInstance) {
|
|
89
|
+
runWithRetry(dbInstance, () => {
|
|
90
|
+
dbInstance.exec("BEGIN IMMEDIATE;");
|
|
91
|
+
try {
|
|
92
|
+
const columns = tableColumns(dbInstance, "tasks");
|
|
93
|
+
if (columns.length === 0) dbInstance.exec(TASKS_DDL);
|
|
94
|
+
else migrateTasksTable(dbInstance, columns);
|
|
95
|
+
dbInstance.exec(TASK_EVENTS_DDL);
|
|
96
|
+
for (const [name, definition] of [
|
|
97
|
+
["run_id", "TEXT"],
|
|
98
|
+
["actor", "TEXT NOT NULL DEFAULT 'legacy'"],
|
|
99
|
+
["payload_sha256", "TEXT"]
|
|
100
|
+
]) {
|
|
101
|
+
if (!tableColumns(dbInstance, "task_events").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE task_events ADD COLUMN ${name} ${definition}`);
|
|
102
|
+
}
|
|
103
|
+
dbInstance.exec("UPDATE task_events SET actor = 'legacy' WHERE actor IS NULL");
|
|
104
|
+
dbInstance.exec(TASK_EVENTS_INDEX_DDL);
|
|
105
|
+
dbInstance.exec(TASKS_SESSION_INDEX_DDL);
|
|
106
|
+
for (const [name, definition] of TASK_EXTRA_COLUMNS) {
|
|
107
|
+
if (!tableColumns(dbInstance, "tasks").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE tasks ADD COLUMN ${name} ${definition}`);
|
|
108
|
+
}
|
|
109
|
+
dbInstance.exec(CONTROL_DDL);
|
|
110
|
+
for (const [name, definition] of [
|
|
111
|
+
["watched_paths", "TEXT NOT NULL DEFAULT '[]'"],
|
|
112
|
+
["source_artifact_id", "TEXT"],
|
|
113
|
+
["valid_for_content_hash", "TEXT"],
|
|
114
|
+
["valid_for_manifest_hash", "TEXT"],
|
|
115
|
+
["verified_by", "TEXT"]
|
|
116
|
+
]) {
|
|
117
|
+
if (!tableColumns(dbInstance, "facts").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE facts ADD COLUMN ${name} ${definition}`);
|
|
118
|
+
}
|
|
119
|
+
dbInstance.exec(SESSIONS_DDL);
|
|
120
|
+
for (const [name, definition] of [
|
|
121
|
+
["objective", "TEXT"], ["default_acceptance", "TEXT"],
|
|
122
|
+
["approval_state", "TEXT NOT NULL DEFAULT 'approved'"], ["policy_revision", "INTEGER NOT NULL DEFAULT 0"]
|
|
123
|
+
]) {
|
|
124
|
+
if (!tableColumns(dbInstance, "sessions").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE sessions ADD COLUMN ${name} ${definition}`);
|
|
125
|
+
}
|
|
126
|
+
dbInstance.exec("CREATE TABLE IF NOT EXISTS observer_cursors (id TEXT PRIMARY KEY, cursor TEXT NOT NULL, updated_at TEXT NOT NULL)");
|
|
127
|
+
dbInstance.exec("CREATE TABLE IF NOT EXISTS run_claims (task_id TEXT PRIMARY KEY, token TEXT NOT NULL, owner_pid INTEGER NOT NULL)");
|
|
128
|
+
dbInstance.exec(SIDE_DDL);
|
|
129
|
+
// Rows written before 0.7.1 have no worker_run_count: the fork is then
|
|
130
|
+
|
|
131
|
+
// never judged stale, which is what those rows did before.
|
|
132
|
+
|
|
133
|
+
if (!dbInstance.prepare("PRAGMA table_info(side_sessions)").all().some((column) => column.name === "worker_run_count")) {
|
|
134
|
+
|
|
135
|
+
dbInstance.exec("ALTER TABLE side_sessions ADD COLUMN worker_run_count INTEGER;");
|
|
136
|
+
|
|
137
|
+
}
|
|
138
|
+
backfillControlRecords(dbInstance);
|
|
139
|
+
dbInstance.exec("COMMIT;");
|
|
140
|
+
} catch (error) {
|
|
141
|
+
try {
|
|
142
|
+
dbInstance.exec("ROLLBACK;");
|
|
143
|
+
} catch {
|
|
144
|
+
/* transaction already unwound */
|
|
145
|
+
}
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function stableId(prefix, value) {
|
|
152
|
+
return `${prefix}-${createHash("sha256").update(String(value)).digest("hex").slice(0, 24)}`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function repoIdForRoot(root) {
|
|
156
|
+
return stableId("repo", resolve(root));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function canonicalizeRemote(value) {
|
|
160
|
+
let raw = String(value ?? "").trim();
|
|
161
|
+
if (!raw) return null;
|
|
162
|
+
const scp = raw.match(/^((?:[^@/:\s]+@)?)([^:/\s]+):(.+)$/);
|
|
163
|
+
if (scp && !raw.includes("://")) raw = `ssh://${scp[1]}${scp[2]}/${scp[3]}`;
|
|
164
|
+
try {
|
|
165
|
+
const parsed = new URL(raw);
|
|
166
|
+
if (parsed.protocol === "file:") {
|
|
167
|
+
const path = resolve(decodeURIComponent(parsed.pathname)).replace(/\.git$/i, "");
|
|
168
|
+
return `file://${path}`;
|
|
169
|
+
}
|
|
170
|
+
if (!parsed.hostname || !["ssh:", "https:", "http:"].includes(parsed.protocol)) return null;
|
|
171
|
+
const path = decodeURIComponent(parsed.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
172
|
+
if (!path) return null;
|
|
173
|
+
return `${parsed.protocol}//${parsed.hostname.toLowerCase()}${parsed.port ? `:${parsed.port}` : ""}/${path}`;
|
|
174
|
+
} catch {
|
|
175
|
+
return isAbsolute(raw) ? `file://${resolve(raw).replace(/\.git$/i, "")}` : null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function canonicalRemoteForRoot(root) {
|
|
180
|
+
try {
|
|
181
|
+
return canonicalizeRemote(git(root, ["remote", "get-url", "origin"]));
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function workItemIdForTask(taskId) {
|
|
188
|
+
return `work-${taskId}`;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function runIdFor(taskId, attempt) {
|
|
192
|
+
return `run-${taskId}-${attempt}`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function ensureControlRecords(dbInstance, task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
|
|
196
|
+
if (!task?.id || !task.project_root) return;
|
|
197
|
+
const now = new Date().toISOString();
|
|
198
|
+
const root = resolve(task.project_root);
|
|
199
|
+
const repoId = repoIdForRoot(root);
|
|
200
|
+
const workItemId = workItemIdForTask(task.id);
|
|
201
|
+
const repo = dbInstance.prepare("SELECT id FROM repos WHERE root = ?").get(root);
|
|
202
|
+
if (!repo || refreshRepo) {
|
|
203
|
+
const resolvedRemote = canonicalRemote === undefined ? canonicalRemoteForRoot(root) : canonicalRemote;
|
|
204
|
+
dbInstance.prepare(`
|
|
205
|
+
INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
|
|
206
|
+
VALUES (@id, @canonical_remote, @root, NULL, @now, @now)
|
|
207
|
+
ON CONFLICT(root) DO UPDATE SET canonical_remote = excluded.canonical_remote, updated_at = excluded.updated_at
|
|
208
|
+
`).run({ id: repoId, canonical_remote: resolvedRemote, root, now });
|
|
209
|
+
}
|
|
210
|
+
const workItem = dbInstance.prepare("SELECT id FROM work_items WHERE task_id = ?").get(task.id);
|
|
211
|
+
if (workItem) return;
|
|
212
|
+
dbInstance.prepare(`
|
|
213
|
+
INSERT INTO work_items (id, repo_id, task_id, parent_work_item_id, objective, owner, delivery_state, created_at, updated_at)
|
|
214
|
+
VALUES (@id, @repo_id, @task_id, NULL, @objective, NULL, @delivery_state, @now, @now)
|
|
215
|
+
`).run({
|
|
216
|
+
id: workItemId,
|
|
217
|
+
repo_id: repoId,
|
|
218
|
+
task_id: task.id,
|
|
219
|
+
objective: task.goal_objective ?? task.title ?? null,
|
|
220
|
+
delivery_state: task.landed_at ? "landed" : "draft",
|
|
221
|
+
now
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function backfillControlRecords(dbInstance) {
|
|
226
|
+
const rows = dbInstance.prepare(`
|
|
227
|
+
SELECT t.id,t.title,t.project_root,t.goal_objective,t.landed_at
|
|
228
|
+
FROM tasks AS t
|
|
229
|
+
LEFT JOIN work_items AS w ON w.task_id = t.id
|
|
230
|
+
WHERE w.task_id IS NULL
|
|
231
|
+
`).all();
|
|
232
|
+
for (const row of rows) ensureControlRecords(dbInstance, row);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function openDb() {
|
|
236
|
+
if (db) return db;
|
|
237
|
+
db = new DatabaseSync(dbPath);
|
|
238
|
+
// Several MCP processes share one database file. The busy timeout has to be
|
|
239
|
+
// set before anything that can touch the write lock, otherwise a concurrent
|
|
240
|
+
// writer turns into an immediate SQLITE_BUSY.
|
|
241
|
+
db.exec("PRAGMA busy_timeout=15000;");
|
|
242
|
+
runWithRetry(db, () => db.exec("PRAGMA journal_mode=WAL;"));
|
|
243
|
+
db.exec("PRAGMA synchronous=NORMAL;");
|
|
244
|
+
initializeSchema(db);
|
|
245
|
+
return db;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export async function ensureFilesystem() {
|
|
249
|
+
await mkdir(dataDir, { recursive: true });
|
|
250
|
+
await mkdir(runsDir, { recursive: true });
|
|
251
|
+
await mkdir(artifactsDir, { recursive: true });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function encodeJson(value) {
|
|
255
|
+
return JSON.stringify(value ?? []);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function decodeJson(value, fallback) {
|
|
259
|
+
if (!value) return fallback;
|
|
260
|
+
try {
|
|
261
|
+
return JSON.parse(value);
|
|
262
|
+
} catch {
|
|
263
|
+
return fallback;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { ensureControlRecords, ensureFilesystem, openDb, runIdFor, runWithRetry, workItemIdForTask } from "./db.js";
|
|
2
|
+
import { extractAgentMessage } from "./runner-readers.js";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
export async function ensureRunRecord(task, attempt) {
|
|
6
|
+
await ensureFilesystem();
|
|
7
|
+
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) throw new Error("run record requires a task and positive attempt");
|
|
8
|
+
const dbInstance = openDb();
|
|
9
|
+
return runWithRetry(dbInstance, () => {
|
|
10
|
+
ensureControlRecords(dbInstance, task);
|
|
11
|
+
const now = new Date().toISOString();
|
|
12
|
+
const id = runIdFor(task.id, attempt);
|
|
13
|
+
dbInstance.prepare(`
|
|
14
|
+
INSERT INTO runs (id, task_id, work_item_id, attempt, codex_thread_id, worktree_path, branch, base_sha, run_status, started_at, finished_at)
|
|
15
|
+
VALUES (@id, @task_id, @work_item_id, @attempt, @codex_thread_id, @worktree_path, @branch, @base_sha, 'running', @started_at, NULL)
|
|
16
|
+
ON CONFLICT(task_id, attempt) DO UPDATE SET
|
|
17
|
+
codex_thread_id = COALESCE(excluded.codex_thread_id, runs.codex_thread_id),
|
|
18
|
+
worktree_path = COALESCE(excluded.worktree_path, runs.worktree_path),
|
|
19
|
+
base_sha = COALESCE(excluded.base_sha, runs.base_sha)
|
|
20
|
+
`).run({
|
|
21
|
+
id,
|
|
22
|
+
task_id: task.id,
|
|
23
|
+
work_item_id: workItemIdForTask(task.id),
|
|
24
|
+
attempt,
|
|
25
|
+
codex_thread_id: task.thread_id ?? null,
|
|
26
|
+
worktree_path: task.worktree_path ?? null,
|
|
27
|
+
branch: task.worktree_path ? `codex/${task.id}` : null,
|
|
28
|
+
base_sha: task.base_commit ?? null,
|
|
29
|
+
started_at: now
|
|
30
|
+
});
|
|
31
|
+
return id;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function completeRunRecord(task, attempt) {
|
|
36
|
+
await ensureFilesystem();
|
|
37
|
+
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) return;
|
|
38
|
+
const now = task.completed_at ?? new Date().toISOString();
|
|
39
|
+
const dbInstance = openDb();
|
|
40
|
+
runWithRetry(dbInstance, () => dbInstance.prepare(`
|
|
41
|
+
UPDATE runs SET codex_thread_id = @codex_thread_id,
|
|
42
|
+
run_status = @run_status, finished_at = @finished_at
|
|
43
|
+
WHERE task_id = @task_id AND attempt = @attempt
|
|
44
|
+
`).run({
|
|
45
|
+
task_id: task.id,
|
|
46
|
+
attempt,
|
|
47
|
+
codex_thread_id: task.thread_id ?? null,
|
|
48
|
+
run_status: task.status ?? "unknown",
|
|
49
|
+
finished_at: now
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor" } = {}) {
|
|
54
|
+
await ensureFilesystem();
|
|
55
|
+
if (!Array.isArray(events) || events.length === 0) return [];
|
|
56
|
+
const dbInstance = openDb();
|
|
57
|
+
return runWithRetry(dbInstance, () => {
|
|
58
|
+
dbInstance.exec("BEGIN IMMEDIATE");
|
|
59
|
+
try {
|
|
60
|
+
const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
|
|
61
|
+
const insert = dbInstance.prepare(`
|
|
62
|
+
INSERT INTO task_events (task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256)
|
|
63
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
64
|
+
`);
|
|
65
|
+
const createdAt = new Date().toISOString();
|
|
66
|
+
const records = events.map((event, index) => {
|
|
67
|
+
const payload = JSON.stringify(event);
|
|
68
|
+
const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", payload,
|
|
69
|
+
createHash("sha256").update(payload).digest("hex"));
|
|
70
|
+
return { id: Number(result.lastInsertRowid), run_id: runId, actor };
|
|
71
|
+
});
|
|
72
|
+
dbInstance.exec("COMMIT");
|
|
73
|
+
return records;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
dbInstance.exec("ROLLBACK");
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function appendTaskEvent(taskId, event, options = {}) {
|
|
82
|
+
return (await appendTaskEvents(taskId, [event], options))[0];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function readTaskEvents(taskId, limit = 100, kinds = null) {
|
|
86
|
+
await ensureFilesystem();
|
|
87
|
+
const kindList = Array.isArray(kinds) && kinds.length > 0 ? kinds : null;
|
|
88
|
+
// Filtering happens before the limit so "give me the last 10 file changes"
|
|
89
|
+
// actually returns 10 file changes, not the tail of an unfiltered stream.
|
|
90
|
+
const rows = kindList
|
|
91
|
+
? openDb().prepare(`
|
|
92
|
+
SELECT payload FROM task_events
|
|
93
|
+
WHERE task_id = ? AND event_type IN (${kindList.map(() => "?").join(", ")})
|
|
94
|
+
ORDER BY seq DESC LIMIT ?
|
|
95
|
+
`).all(taskId, ...kindList, limit)
|
|
96
|
+
: openDb().prepare(`
|
|
97
|
+
SELECT payload FROM task_events
|
|
98
|
+
WHERE task_id = ? ORDER BY seq DESC LIMIT ?
|
|
99
|
+
`).all(taskId, limit);
|
|
100
|
+
return rows.reverse().map((row) => JSON.parse(row.payload));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function readTaskEventRecords(taskId, limit = 100) {
|
|
104
|
+
await ensureFilesystem();
|
|
105
|
+
const rows = openDb().prepare(`
|
|
106
|
+
SELECT id, task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256
|
|
107
|
+
FROM task_events WHERE task_id = ? ORDER BY seq DESC LIMIT ?
|
|
108
|
+
`).all(taskId, limit);
|
|
109
|
+
return rows.reverse().map((row) => ({
|
|
110
|
+
...row,
|
|
111
|
+
event: JSON.parse(row.payload)
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function listTaskEventKinds(taskId) {
|
|
116
|
+
await ensureFilesystem();
|
|
117
|
+
return openDb().prepare(`
|
|
118
|
+
SELECT event_type AS kind, COUNT(*) AS count
|
|
119
|
+
FROM task_events WHERE task_id = ? GROUP BY event_type ORDER BY count DESC
|
|
120
|
+
`).all(taskId);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// A worker's report is the only thing a supervisor usually wants back, and the
|
|
124
|
+
// task row keeps just the most recent one. This reads them out of the raw
|
|
125
|
+
// stream newest-first: `payload LIKE` is a cheap prefilter, and every row that
|
|
126
|
+
// survives it is verified through the same extraction the state machine uses.
|
|
127
|
+
export async function readAgentMessages(taskId, limit = 1) {
|
|
128
|
+
await ensureFilesystem();
|
|
129
|
+
const rows = openDb().prepare(`
|
|
130
|
+
SELECT payload FROM task_events
|
|
131
|
+
WHERE task_id = ? AND event_type = 'item.completed' AND payload LIKE '%"agent_message"%'
|
|
132
|
+
ORDER BY seq DESC LIMIT ?
|
|
133
|
+
`).all(taskId, limit * 5 + 10);
|
|
134
|
+
const messages = [];
|
|
135
|
+
for (const row of rows) {
|
|
136
|
+
let text;
|
|
137
|
+
try {
|
|
138
|
+
text = extractAgentMessage(JSON.parse(row.payload));
|
|
139
|
+
} catch {
|
|
140
|
+
text = null;
|
|
141
|
+
}
|
|
142
|
+
if (text) messages.push(text);
|
|
143
|
+
if (messages.length >= limit) break;
|
|
144
|
+
}
|
|
145
|
+
return messages.reverse();
|
|
146
|
+
}
|