agent-supervisor-mcp 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +208 -0
- package/README.md +206 -2
- package/package.json +76 -4
- package/skills/agent-supervisor/SKILL.md +139 -0
- package/src/app/acceptance.js +263 -0
- package/src/app/auto-cleanup.js +91 -0
- package/src/app/cancel.js +57 -0
- package/src/app/cleanup-facts.js +101 -0
- package/src/app/cleanup-plan.js +166 -0
- package/src/app/compose.js +17 -0
- package/src/app/context-compiler.js +83 -0
- package/src/app/dispatch.js +398 -0
- package/src/app/followup.js +104 -0
- package/src/app/land-chain.js +134 -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/restore-worktree.js +51 -0
- package/src/app/resume.js +179 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/app/side-chat.js +370 -0
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +114 -0
- package/src/app/worktree-setup.js +218 -0
- package/src/domain/acceptance-baseline.js +65 -0
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/cleanup-policy.js +44 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/domain/failure-class.js +63 -0
- package/src/domain/owned-changes.js +27 -0
- package/src/domain/prompt.js +161 -0
- package/src/domain/side-turn-view.js +73 -0
- package/src/domain/status.js +50 -0
- package/src/domain/thread-health.js +33 -0
- package/src/domain/truncate.js +148 -0
- package/src/domain/worker-branch.js +6 -0
- package/src/domain/worker-changes.js +58 -0
- package/src/domain/worker-env.js +14 -0
- package/src/domain/worker-preflight.js +167 -0
- package/src/domain/worker-report.js +85 -0
- package/src/domain/worker-report.schema.json +10 -0
- package/src/infra/bin-resolver.js +287 -0
- package/src/infra/cleanup-hint.js +29 -0
- package/src/infra/crash-guard.js +44 -0
- package/src/infra/external-output.js +29 -0
- package/src/infra/git.js +61 -0
- package/src/infra/handoff.js +38 -0
- package/src/infra/paths.js +34 -0
- package/src/infra/process.js +59 -0
- package/src/infra/sandbox-roots.js +106 -0
- package/src/infra/skill-sync.js +109 -0
- package/src/infra/stage-store.js +39 -0
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/event-body.js +82 -0
- package/src/infra/store/events.js +149 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +173 -0
- package/src/infra/store/records.js +171 -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 +351 -0
- package/src/infra/update/auto-update-worker.js +186 -0
- package/src/infra/update/auto-update.js +143 -0
- package/src/infra/update/update-check.js +246 -0
- package/src/infra/workspace-kind.js +165 -0
- package/src/infra/worktree.js +361 -0
- package/src/interface/bin/acceptance-cli.js +62 -0
- package/src/interface/bin/cleanup.js +81 -0
- package/src/interface/bin/monitor.jsx +301 -0
- package/src/interface/bin/setup.js +342 -0
- package/src/interface/bin/stage.js +17 -0
- package/src/interface/bin/web-server.js +53 -0
- package/src/interface/mcp/handlers/delivery.js +165 -0
- package/src/interface/mcp/handlers/dispatch.js +236 -0
- package/src/interface/mcp/handlers/facts.js +204 -0
- package/src/interface/mcp/handlers/overview.js +106 -0
- package/src/interface/mcp/handlers/results.js +262 -0
- package/src/interface/mcp/handlers/review.js +115 -0
- package/src/interface/mcp/handlers/wait.js +141 -0
- 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 +64 -0
- package/src/interface/mcp/tools/deliver.js +48 -0
- package/src/interface/mcp/tools/dispatch.js +90 -0
- package/src/interface/mcp/tools/optional.js +57 -0
- package/src/interface/mcp/tools/read.js +115 -0
- package/src/interface/mcp/tools/run.js +57 -0
- package/src/interface/mcp/tools/shapes.js +67 -0
- package/src/interface/mcp/tools/track.js +84 -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 +224 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +227 -0
- package/src/mcp-server.js +4 -0
- package/src/run-host/entry.js +26 -0
- package/src/run-host/finalize.js +243 -0
- package/src/run-host/launch.js +49 -0
- package/src/run-host/live-run.js +76 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +102 -0
- package/src/run-host/track.js +132 -0
- package/src/runners/claude/adapter.js +118 -0
- package/src/runners/claude/events.js +100 -0
- package/src/runners/claude/tool-guard.js +48 -0
- package/src/runners/codex/adapter.js +157 -0
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/runners/codex/event-parser.js +266 -0
- package/src/runners/codex/goal-store.js +54 -0
- package/src/runners/codex/mcp-config.js +39 -0
- package/src/runners/codex/tool-guard.js +184 -0
- package/src/runners/contract-check.js +82 -0
- package/src/runners/contract.js +53 -0
- package/src/runners/registry.js +45 -0
- package/web/dist/assets/index-D-A2xlpx.js +154 -0
- package/web/dist/assets/index-f8esISCp.css +2 -0
- package/web/dist/index.html +15 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { branchOf } from "../../domain/worker-branch.js";
|
|
2
|
+
import { ensureControlRecords, ensureFilesystem, openDb, runIdFor, runWithRetry, workItemIdForTask } from "./db.js";
|
|
3
|
+
import { storedForm } from "./event-body.js";
|
|
4
|
+
import { extractAgentMessage } from "./runner-readers.js";
|
|
5
|
+
|
|
6
|
+
export async function ensureRunRecord(task, attempt) {
|
|
7
|
+
await ensureFilesystem();
|
|
8
|
+
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) throw new Error("run record requires a task and positive attempt");
|
|
9
|
+
const dbInstance = openDb();
|
|
10
|
+
return runWithRetry(dbInstance, () => {
|
|
11
|
+
ensureControlRecords(dbInstance, task);
|
|
12
|
+
const now = new Date().toISOString();
|
|
13
|
+
const id = runIdFor(task.id, attempt);
|
|
14
|
+
dbInstance.prepare(`
|
|
15
|
+
INSERT INTO runs (id, task_id, work_item_id, attempt, codex_thread_id, worktree_path, branch, base_sha, run_status, started_at, finished_at)
|
|
16
|
+
VALUES (@id, @task_id, @work_item_id, @attempt, @codex_thread_id, @worktree_path, @branch, @base_sha, 'running', @started_at, NULL)
|
|
17
|
+
ON CONFLICT(task_id, attempt) DO UPDATE SET
|
|
18
|
+
codex_thread_id = COALESCE(excluded.codex_thread_id, runs.codex_thread_id),
|
|
19
|
+
worktree_path = COALESCE(excluded.worktree_path, runs.worktree_path),
|
|
20
|
+
base_sha = COALESCE(excluded.base_sha, runs.base_sha)
|
|
21
|
+
`).run({
|
|
22
|
+
id,
|
|
23
|
+
task_id: task.id,
|
|
24
|
+
work_item_id: workItemIdForTask(task.id),
|
|
25
|
+
attempt,
|
|
26
|
+
codex_thread_id: task.thread_id ?? null,
|
|
27
|
+
worktree_path: task.worktree_path ?? null,
|
|
28
|
+
branch: task.worktree_path ? branchOf(task) : null,
|
|
29
|
+
base_sha: task.base_commit ?? null,
|
|
30
|
+
started_at: now
|
|
31
|
+
});
|
|
32
|
+
return id;
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function completeRunRecord(task, attempt) {
|
|
37
|
+
await ensureFilesystem();
|
|
38
|
+
if (!task?.id || !Number.isInteger(attempt) || attempt < 1) return;
|
|
39
|
+
const now = task.completed_at ?? new Date().toISOString();
|
|
40
|
+
const dbInstance = openDb();
|
|
41
|
+
runWithRetry(dbInstance, () => dbInstance.prepare(`
|
|
42
|
+
UPDATE runs SET codex_thread_id = @codex_thread_id,
|
|
43
|
+
run_status = @run_status, finished_at = @finished_at
|
|
44
|
+
WHERE task_id = @task_id AND attempt = @attempt
|
|
45
|
+
`).run({
|
|
46
|
+
task_id: task.id,
|
|
47
|
+
attempt,
|
|
48
|
+
codex_thread_id: task.thread_id ?? null,
|
|
49
|
+
run_status: task.status ?? "unknown",
|
|
50
|
+
finished_at: now
|
|
51
|
+
}));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// bodyInLog: each event is already in the run log (the caller waited for the
|
|
55
|
+
// write), so a large one need not be kept whole here as well. logOffsets says
|
|
56
|
+
// where each line starts.
|
|
57
|
+
export async function appendTaskEvents(taskId, events, { runId = null, actor = "supervisor", bodyInLog = false, logOffsets = [] } = {}) {
|
|
58
|
+
await ensureFilesystem();
|
|
59
|
+
if (!Array.isArray(events) || events.length === 0) return [];
|
|
60
|
+
const dbInstance = openDb();
|
|
61
|
+
return runWithRetry(dbInstance, () => {
|
|
62
|
+
dbInstance.exec("BEGIN IMMEDIATE");
|
|
63
|
+
try {
|
|
64
|
+
const nextSeqRow = dbInstance.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM task_events WHERE task_id = ?").get(taskId);
|
|
65
|
+
const insert = dbInstance.prepare(`
|
|
66
|
+
INSERT INTO task_events (task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256)
|
|
67
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
68
|
+
`);
|
|
69
|
+
const createdAt = new Date().toISOString();
|
|
70
|
+
const records = events.map((event, index) => {
|
|
71
|
+
const stored = storedForm(event, { bodyInLog, offset: logOffsets[index] ?? null });
|
|
72
|
+
const result = insert.run(taskId, runId, nextSeqRow.seq + index, createdAt, actor, event.type ?? "unknown", stored.payload, stored.sha256);
|
|
73
|
+
return { id: Number(result.lastInsertRowid), run_id: runId, actor };
|
|
74
|
+
});
|
|
75
|
+
dbInstance.exec("COMMIT");
|
|
76
|
+
return records;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
dbInstance.exec("ROLLBACK");
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function appendTaskEvent(taskId, event, options = {}) {
|
|
85
|
+
return (await appendTaskEvents(taskId, [event], options))[0];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function readTaskEvents(taskId, limit = 100, kinds = null) {
|
|
89
|
+
await ensureFilesystem();
|
|
90
|
+
const kindList = Array.isArray(kinds) && kinds.length > 0 ? kinds : null;
|
|
91
|
+
// Filtering happens before the limit so "give me the last 10 file changes"
|
|
92
|
+
// actually returns 10 file changes, not the tail of an unfiltered stream.
|
|
93
|
+
const rows = kindList
|
|
94
|
+
? openDb().prepare(`
|
|
95
|
+
SELECT payload FROM task_events
|
|
96
|
+
WHERE task_id = ? AND event_type IN (${kindList.map(() => "?").join(", ")})
|
|
97
|
+
ORDER BY seq DESC LIMIT ?
|
|
98
|
+
`).all(taskId, ...kindList, limit)
|
|
99
|
+
: openDb().prepare(`
|
|
100
|
+
SELECT payload FROM task_events
|
|
101
|
+
WHERE task_id = ? ORDER BY seq DESC LIMIT ?
|
|
102
|
+
`).all(taskId, limit);
|
|
103
|
+
return rows.reverse().map((row) => JSON.parse(row.payload));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function readTaskEventRecords(taskId, limit = 100) {
|
|
107
|
+
await ensureFilesystem();
|
|
108
|
+
const rows = openDb().prepare(`
|
|
109
|
+
SELECT id, task_id, run_id, seq, created_at, actor, event_type, payload, payload_sha256
|
|
110
|
+
FROM task_events WHERE task_id = ? ORDER BY seq DESC LIMIT ?
|
|
111
|
+
`).all(taskId, limit);
|
|
112
|
+
return rows.reverse().map((row) => ({
|
|
113
|
+
...row,
|
|
114
|
+
event: JSON.parse(row.payload)
|
|
115
|
+
}));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function listTaskEventKinds(taskId) {
|
|
119
|
+
await ensureFilesystem();
|
|
120
|
+
return openDb().prepare(`
|
|
121
|
+
SELECT event_type AS kind, COUNT(*) AS count
|
|
122
|
+
FROM task_events WHERE task_id = ? GROUP BY event_type ORDER BY count DESC
|
|
123
|
+
`).all(taskId);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// A worker's report is the only thing a supervisor usually wants back, and the
|
|
127
|
+
// task row keeps just the most recent one. This reads them out of the raw
|
|
128
|
+
// stream newest-first: `payload LIKE` is a cheap prefilter, and every row that
|
|
129
|
+
// survives it is verified through the same extraction the state machine uses.
|
|
130
|
+
export async function readAgentMessages(taskId, limit = 1) {
|
|
131
|
+
await ensureFilesystem();
|
|
132
|
+
const rows = openDb().prepare(`
|
|
133
|
+
SELECT payload FROM task_events
|
|
134
|
+
WHERE task_id = ? AND event_type = 'item.completed' AND payload LIKE '%"agent_message"%'
|
|
135
|
+
ORDER BY seq DESC LIMIT ?
|
|
136
|
+
`).all(taskId, limit * 5 + 10);
|
|
137
|
+
const messages = [];
|
|
138
|
+
for (const row of rows) {
|
|
139
|
+
let text;
|
|
140
|
+
try {
|
|
141
|
+
text = extractAgentMessage(JSON.parse(row.payload));
|
|
142
|
+
} catch {
|
|
143
|
+
text = null;
|
|
144
|
+
}
|
|
145
|
+
if (text) messages.push(text);
|
|
146
|
+
if (messages.length >= limit) break;
|
|
147
|
+
}
|
|
148
|
+
return messages.reverse();
|
|
149
|
+
}
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { runGit } from "../git.js";
|
|
2
|
+
import { buildHandoff } from "../handoff.js";
|
|
3
|
+
import { captureWorkspaceManifest } from "../workspace-kind.js";
|
|
4
|
+
import { decodeJson, ensureFilesystem, openDb } from "./db.js";
|
|
5
|
+
import { getTask } from "./tasks.js";
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
8
|
+
|
|
9
|
+
export async function getWorkItemForTask(taskId) {
|
|
10
|
+
await ensureFilesystem();
|
|
11
|
+
return openDb().prepare("SELECT * FROM work_items WHERE task_id = ?").get(taskId) ?? null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function recordFact({
|
|
15
|
+
workItemId,
|
|
16
|
+
scopeType,
|
|
17
|
+
scopeId,
|
|
18
|
+
key,
|
|
19
|
+
value,
|
|
20
|
+
state = "candidate",
|
|
21
|
+
sourceEventId = null,
|
|
22
|
+
sourceArtifactId = null,
|
|
23
|
+
validForSha = null,
|
|
24
|
+
validForContentHash = null,
|
|
25
|
+
validForManifestHash = null,
|
|
26
|
+
watchedPaths = [],
|
|
27
|
+
expiresAt = null,
|
|
28
|
+
supersedesId = null,
|
|
29
|
+
verifiedAt = null,
|
|
30
|
+
verifiedBy = null
|
|
31
|
+
}) {
|
|
32
|
+
await ensureFilesystem();
|
|
33
|
+
if (!workItemId || !scopeType || !scopeId || !key) throw new Error("fact requires workItemId, scopeType, scopeId and key");
|
|
34
|
+
if (!["candidate", "verified", "expired", "revoked"].includes(state)) throw new Error("invalid fact state");
|
|
35
|
+
if (!Array.isArray(watchedPaths) || watchedPaths.some((path) => typeof path !== "string")) throw new Error("watchedPaths must be a string list");
|
|
36
|
+
const now = new Date().toISOString();
|
|
37
|
+
const id = randomUUID();
|
|
38
|
+
openDb().prepare(`
|
|
39
|
+
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)
|
|
40
|
+
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)
|
|
41
|
+
`).run({
|
|
42
|
+
id,
|
|
43
|
+
work_item_id: workItemId,
|
|
44
|
+
scope_type: scopeType,
|
|
45
|
+
scope_id: scopeId,
|
|
46
|
+
key,
|
|
47
|
+
value_json: JSON.stringify(value),
|
|
48
|
+
state,
|
|
49
|
+
source_event_id: sourceEventId,
|
|
50
|
+
source_artifact_id: sourceArtifactId,
|
|
51
|
+
valid_for_sha: validForSha,
|
|
52
|
+
valid_for_content_hash: validForContentHash,
|
|
53
|
+
valid_for_manifest_hash: validForManifestHash,
|
|
54
|
+
watched_paths: JSON.stringify(watchedPaths.map((path) => isAbsolute(path) ? resolve(path) : path)),
|
|
55
|
+
expires_at: expiresAt,
|
|
56
|
+
supersedes_id: supersedesId,
|
|
57
|
+
created_at: now,
|
|
58
|
+
verified_at: verifiedAt ?? (state === "verified" ? now : null),
|
|
59
|
+
verified_by: verifiedBy ?? (state === "verified" ? "supervisor" : null)
|
|
60
|
+
});
|
|
61
|
+
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 };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function pathsOverlap(left, right) {
|
|
65
|
+
const normalize = (path) => process.platform === "win32" ? path.replace(/\\/g, "/").toLowerCase() : path;
|
|
66
|
+
const a = normalize(left).replace(/\/$/, "");
|
|
67
|
+
const b = normalize(right).replace(/\/$/, "");
|
|
68
|
+
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function repoRelativePaths(projectRoot, paths) {
|
|
72
|
+
return (paths ?? []).flatMap((path) => {
|
|
73
|
+
if (typeof path !== "string" || !path.trim()) return [];
|
|
74
|
+
const candidate = isAbsolute(path) ? relative(projectRoot, path) : path;
|
|
75
|
+
const normalized = candidate.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
|
|
76
|
+
return !normalized || normalized === ".." || normalized.startsWith("../") ? [] : [normalized];
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const git = (cwd, args) => runGit(cwd, args, { timeout: 15000, stderr: "ignore" });
|
|
81
|
+
|
|
82
|
+
function shaCoversBase(projectRoot, validForSha, baseSha) {
|
|
83
|
+
if (!validForSha || !baseSha) return true;
|
|
84
|
+
try {
|
|
85
|
+
git(projectRoot, ["merge-base", "--is-ancestor", validForSha, baseSha]);
|
|
86
|
+
return true;
|
|
87
|
+
} catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function watchedPathsChanged(projectRoot, validForSha, baseSha, watchedPaths) {
|
|
93
|
+
if (!validForSha || !baseSha || watchedPaths.length === 0) return false;
|
|
94
|
+
try {
|
|
95
|
+
const relativePaths = repoRelativePaths(projectRoot, watchedPaths);
|
|
96
|
+
if (relativePaths.length === 0) return true;
|
|
97
|
+
return Boolean(git(projectRoot, ["diff", "--name-only", validForSha, baseSha, "--", ...relativePaths]));
|
|
98
|
+
} catch {
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function currentWorkspaceManifest(task) {
|
|
104
|
+
const metadata = task.workspace_metadata;
|
|
105
|
+
if (!metadata?.source_root || !Array.isArray(metadata.manifest_paths) || metadata.manifest_paths.length === 0) return null;
|
|
106
|
+
try {
|
|
107
|
+
return await captureWorkspaceManifest(metadata.source_root, metadata.manifest_paths);
|
|
108
|
+
} catch {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function currentContextContentHash(task) {
|
|
114
|
+
const context = task.input_context?.context ?? [];
|
|
115
|
+
if (!Array.isArray(context) || context.length === 0) return null;
|
|
116
|
+
try {
|
|
117
|
+
return (await buildHandoff({ context }, { maxLines: 1, maxChars: 1 })).content_hash;
|
|
118
|
+
} catch {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function markFactExpired(id) {
|
|
124
|
+
openDb().prepare(`
|
|
125
|
+
INSERT INTO facts (id, work_item_id, scope_type, scope_id, key, value_json, state, source_event_id, source_artifact_id,
|
|
126
|
+
valid_for_sha, valid_for_content_hash, valid_for_manifest_hash, watched_paths, expires_at, supersedes_id, created_at, verified_at, verified_by)
|
|
127
|
+
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,
|
|
128
|
+
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
|
|
129
|
+
FROM facts AS source
|
|
130
|
+
WHERE source.id = ? AND source.state = 'verified'
|
|
131
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = source.id AND transition.state IN ('expired', 'revoked'))
|
|
132
|
+
`).run(randomUUID(), new Date().toISOString(), id);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export async function listContextFacts({ taskId, baseSha, ownedPaths = [], dependencyTaskIds = [] }) {
|
|
136
|
+
await ensureFilesystem();
|
|
137
|
+
const workItem = await getWorkItemForTask(taskId);
|
|
138
|
+
if (!workItem) return [];
|
|
139
|
+
const task = await getTask(taskId);
|
|
140
|
+
if (!task) return [];
|
|
141
|
+
const dependencyItems = dependencyTaskIds.length === 0
|
|
142
|
+
? []
|
|
143
|
+
: openDb().prepare(`SELECT id FROM work_items WHERE task_id IN (${dependencyTaskIds.map(() => "?").join(",")})`).all(...dependencyTaskIds).map((row) => row.id);
|
|
144
|
+
const rows = openDb().prepare(`
|
|
145
|
+
SELECT facts.* FROM facts
|
|
146
|
+
WHERE state = 'verified'
|
|
147
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
148
|
+
ORDER BY created_at ASC
|
|
149
|
+
`).all();
|
|
150
|
+
const now = Date.now();
|
|
151
|
+
const workspaceManifest = await currentWorkspaceManifest(task);
|
|
152
|
+
const contextContentHash = await currentContextContentHash(task);
|
|
153
|
+
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
154
|
+
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
155
|
+
const ownedRelative = repoRelativePaths(task.project_root, ownedPaths);
|
|
156
|
+
const visible = [];
|
|
157
|
+
for (const row of rows) {
|
|
158
|
+
const watched = decodeJson(row.watched_paths, []);
|
|
159
|
+
const watchedRelative = repoRelativePaths(task.project_root, watched);
|
|
160
|
+
const included = row.scope_type === "work_item" ? row.scope_id === workItem.id
|
|
161
|
+
: row.scope_type === "dependency" ? dependencyItems.includes(row.scope_id)
|
|
162
|
+
: row.scope_type === "repo_verified" && canonicalRemote && row.scope_id === canonicalRemote
|
|
163
|
+
&& watchedRelative.length > 0 && watchedRelative.some((path) => ownedRelative.some((owned) => pathsOverlap(path, owned)));
|
|
164
|
+
if (!included) continue;
|
|
165
|
+
if (row.expires_at && Date.parse(row.expires_at) <= now) {
|
|
166
|
+
markFactExpired(row.id);
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (!shaCoversBase(task.project_root, row.valid_for_sha, baseSha)) continue;
|
|
170
|
+
if (watchedPathsChanged(task.project_root, row.valid_for_sha, baseSha, watchedRelative)) {
|
|
171
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (row.valid_for_manifest_hash && (!workspaceManifest || workspaceManifest.sha256 !== row.valid_for_manifest_hash)) {
|
|
175
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id && workspaceManifest) markFactExpired(row.id);
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (row.valid_for_content_hash && contextContentHash !== row.valid_for_content_hash) {
|
|
179
|
+
if (row.scope_type === "work_item" && row.scope_id === workItem.id) markFactExpired(row.id);
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
visible.push({
|
|
183
|
+
...row,
|
|
184
|
+
value: decodeJson(row.value_json, null),
|
|
185
|
+
watched_paths: watched
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return visible;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function countVerifiedFacts() {
|
|
192
|
+
await ensureFilesystem();
|
|
193
|
+
return openDb().prepare(`
|
|
194
|
+
SELECT COUNT(*) AS count FROM facts
|
|
195
|
+
WHERE state = 'verified'
|
|
196
|
+
AND NOT EXISTS (SELECT 1 FROM facts AS transition WHERE transition.supersedes_id = facts.id AND transition.state IN ('expired', 'revoked'))
|
|
197
|
+
`).get().count;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export async function createContextSnapshot({ runId, recipient = "worker", factIds = [], baseSha = null, prompt, estimatedTokens, excluded = {} }) {
|
|
201
|
+
await ensureFilesystem();
|
|
202
|
+
if (!runId || typeof prompt !== "string") throw new Error("context snapshot requires runId and prompt");
|
|
203
|
+
const now = new Date().toISOString();
|
|
204
|
+
const id = randomUUID();
|
|
205
|
+
openDb().prepare(`
|
|
206
|
+
INSERT INTO context_snapshots (id, run_id, recipient, fact_versions, base_sha, prompt_sha256, estimated_tokens, excluded_json, created_at)
|
|
207
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
208
|
+
`).run(id, runId, recipient, JSON.stringify(factIds), baseSha,
|
|
209
|
+
createHash("sha256").update(prompt).digest("hex"), estimatedTokens, JSON.stringify(excluded), now);
|
|
210
|
+
return { id, run_id: runId, recipient, fact_versions: factIds, base_sha: baseSha, estimated_tokens: estimatedTokens, created_at: now };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export async function latestContextSnapshotForTask(taskId) {
|
|
214
|
+
await ensureFilesystem();
|
|
215
|
+
return openDb().prepare(`
|
|
216
|
+
SELECT s.* FROM context_snapshots s JOIN runs r ON r.id = s.run_id
|
|
217
|
+
WHERE r.task_id = ? ORDER BY s.created_at DESC LIMIT 1
|
|
218
|
+
`).get(taskId) ?? null;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export async function getFact(factId) {
|
|
222
|
+
await ensureFilesystem();
|
|
223
|
+
const row = openDb().prepare("SELECT * FROM facts WHERE id = ?").get(factId);
|
|
224
|
+
if (!row) return null;
|
|
225
|
+
return {
|
|
226
|
+
...row,
|
|
227
|
+
value: decodeJson(row.value_json, null),
|
|
228
|
+
watched_paths: decodeJson(row.watched_paths, [])
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export async function getTaskForWorkItem(workItemId) {
|
|
233
|
+
await ensureFilesystem();
|
|
234
|
+
return openDb().prepare("SELECT * FROM tasks WHERE id = (SELECT task_id FROM work_items WHERE id = ?)").get(workItemId) ?? null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export async function isFactRevoked(factId) {
|
|
238
|
+
await ensureFilesystem();
|
|
239
|
+
return Boolean(openDb().prepare("SELECT 1 FROM facts WHERE supersedes_id = ? AND state = 'revoked'").get(factId));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export async function getFactEffectiveState(factId) {
|
|
243
|
+
await ensureFilesystem();
|
|
244
|
+
const transition = openDb().prepare(`
|
|
245
|
+
SELECT state FROM facts WHERE supersedes_id = ? AND state IN ('revoked', 'expired')
|
|
246
|
+
ORDER BY CASE state WHEN 'revoked' THEN 0 ELSE 1 END, created_at DESC LIMIT 1
|
|
247
|
+
`).get(factId);
|
|
248
|
+
return transition?.state ?? null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export async function promoteCandidateFact({ factId, scopeType = "work_item", watchedPaths = null, expiresAt = null, sourceEventId = null, verifiedBy = "main_thread" }) {
|
|
252
|
+
await ensureFilesystem();
|
|
253
|
+
const source = await getFact(factId);
|
|
254
|
+
if (!source) throw new Error(`fact not found: ${factId}`);
|
|
255
|
+
if (await isFactRevoked(factId)) {
|
|
256
|
+
const error = new Error(`fact ${factId} is already revoked`);
|
|
257
|
+
error.code = "fact_already_revoked";
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
if (source.state !== "candidate") {
|
|
261
|
+
const error = new Error(`only candidate facts may be promoted; ${factId} is ${source.state}`);
|
|
262
|
+
error.code = "fact_not_candidate";
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
if (!['work_item', 'repo_verified'].includes(scopeType)) throw new Error("promotion scope must be work_item or repo_verified");
|
|
266
|
+
const workItem = openDb().prepare("SELECT * FROM work_items WHERE id = ?").get(source.work_item_id);
|
|
267
|
+
if (!workItem) throw new Error(`work item not found for fact: ${factId}`);
|
|
268
|
+
const sourceTask = await getTaskForWorkItem(workItem.id);
|
|
269
|
+
const paths = watchedPaths ?? source.watched_paths ?? [];
|
|
270
|
+
const repo = openDb().prepare("SELECT canonical_remote FROM repos WHERE id = ?").get(workItem.repo_id);
|
|
271
|
+
const canonicalRemote = repo?.canonical_remote ?? null;
|
|
272
|
+
const normalizedRepoPaths = sourceTask ? repoRelativePaths(sourceTask.project_root, paths) : [];
|
|
273
|
+
if (scopeType === "repo_verified" && paths.length === 0) {
|
|
274
|
+
const error = new Error("repo_verified promotion requires watchedPaths so unrelated work cannot inherit it");
|
|
275
|
+
error.code = "repo_fact_requires_paths";
|
|
276
|
+
throw error;
|
|
277
|
+
}
|
|
278
|
+
if (scopeType === "repo_verified" && !canonicalRemote) {
|
|
279
|
+
const error = new Error("repo_verified promotion requires a canonical origin remote; facts from an unrecognized or missing remote stay work-scoped");
|
|
280
|
+
error.code = "repo_fact_requires_canonical_remote";
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
if (scopeType === "repo_verified" && normalizedRepoPaths.length === 0) {
|
|
284
|
+
const error = new Error("repo_verified watchedPaths must stay inside the repository root");
|
|
285
|
+
error.code = "repo_fact_paths_outside_root";
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
return recordFact({
|
|
289
|
+
workItemId: source.work_item_id,
|
|
290
|
+
scopeType,
|
|
291
|
+
scopeId: scopeType === "repo_verified" ? canonicalRemote : workItem.id,
|
|
292
|
+
key: source.key,
|
|
293
|
+
value: source.value,
|
|
294
|
+
state: "verified",
|
|
295
|
+
sourceEventId,
|
|
296
|
+
sourceArtifactId: source.source_artifact_id ?? null,
|
|
297
|
+
validForSha: source.valid_for_sha ?? null,
|
|
298
|
+
validForContentHash: source.valid_for_content_hash ?? null,
|
|
299
|
+
validForManifestHash: source.valid_for_manifest_hash ?? null,
|
|
300
|
+
watchedPaths: scopeType === "repo_verified" ? normalizedRepoPaths : paths,
|
|
301
|
+
expiresAt: expiresAt ?? source.expires_at ?? null,
|
|
302
|
+
supersedesId: source.id,
|
|
303
|
+
verifiedBy
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export async function revokeFact(factId) {
|
|
308
|
+
await ensureFilesystem();
|
|
309
|
+
const source = await getFact(factId);
|
|
310
|
+
if (!source) return null;
|
|
311
|
+
if (!["candidate", "verified"].includes(source.state)) {
|
|
312
|
+
const error = new Error(`only candidate or verified facts may be revoked; ${factId} is ${source.state}`);
|
|
313
|
+
error.code = "fact_not_revocable";
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
if (await isFactRevoked(factId)) {
|
|
317
|
+
const error = new Error(`fact ${factId} is already revoked`);
|
|
318
|
+
error.code = "fact_already_revoked";
|
|
319
|
+
throw error;
|
|
320
|
+
}
|
|
321
|
+
return recordFact({
|
|
322
|
+
workItemId: source.work_item_id,
|
|
323
|
+
scopeType: source.scope_type,
|
|
324
|
+
scopeId: source.scope_id,
|
|
325
|
+
key: source.key,
|
|
326
|
+
value: source.value,
|
|
327
|
+
state: "revoked",
|
|
328
|
+
sourceEventId: source.source_event_id,
|
|
329
|
+
sourceArtifactId: source.source_artifact_id,
|
|
330
|
+
validForSha: source.valid_for_sha,
|
|
331
|
+
validForContentHash: source.valid_for_content_hash,
|
|
332
|
+
validForManifestHash: source.valid_for_manifest_hash,
|
|
333
|
+
watchedPaths: source.watched_paths,
|
|
334
|
+
expiresAt: source.expires_at,
|
|
335
|
+
supersedesId: source.id,
|
|
336
|
+
verifiedBy: "main_thread"
|
|
337
|
+
});
|
|
338
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { runIsOver, TERMINAL_STATUSES } from "../../domain/status.js";
|
|
2
|
+
import { parseWorkerReportForRun } from "../../domain/worker-report.js";
|
|
3
|
+
import { decodeJson, openDb, runIdFor } from "./db.js";
|
|
4
|
+
import { appendTaskEvent, completeRunRecord, readTaskEvents } from "./events.js";
|
|
5
|
+
import { isPidAlive, neverStarted, readActiveTasks, readTasks, rowToTask, writeTask } from "./tasks.js";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
|
|
8
|
+
// A terminal row whose acceptance run was cut short: the MCP process that
|
|
9
|
+
// was running the checks is gone. Left alone it would read as "running"
|
|
10
|
+
// forever and land would treat it as never run.
|
|
11
|
+
async function reconcileInterruptedAcceptance() {
|
|
12
|
+
const tasks = await readTasks();
|
|
13
|
+
const interrupted = tasks.filter((task) =>
|
|
14
|
+
TERMINAL_STATUSES.has(task.status)
|
|
15
|
+
&& task.acceptance_results?.status === "running"
|
|
16
|
+
&& !isPidAlive(task.acceptance_results.supervisor_pid));
|
|
17
|
+
for (const task of interrupted) {
|
|
18
|
+
const now = new Date().toISOString();
|
|
19
|
+
const durable = (await readTaskEvents(task.id, 1, ["supervisor.acceptance"]))[0] ?? null;
|
|
20
|
+
if (durable && durable.run === task.run_count) {
|
|
21
|
+
const reportInvalid = task.attention_reason === "invalid_report";
|
|
22
|
+
await writeTask({
|
|
23
|
+
...task,
|
|
24
|
+
status: reportInvalid ? "completed" : task.status,
|
|
25
|
+
exit_code: task.exit_code ?? (reportInvalid ? 0 : null),
|
|
26
|
+
acceptance_results: durable,
|
|
27
|
+
current_action: durable.passed === true
|
|
28
|
+
? "Acceptance passed (recovered from the durable event)"
|
|
29
|
+
: `Acceptance ${durable.status} (recovered from the durable event)`,
|
|
30
|
+
updated_at: now
|
|
31
|
+
});
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
await writeTask({
|
|
35
|
+
...task,
|
|
36
|
+
acceptance_results: { ...task.acceptance_results, status: "interrupted", passed: null, finished_at: now },
|
|
37
|
+
current_action: "Acceptance interrupted: the supervisor process exited while running the checks",
|
|
38
|
+
updated_at: now
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
return interrupted;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function lastReportText(events) {
|
|
45
|
+
let reportText = null;
|
|
46
|
+
for (const event of events) {
|
|
47
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message") reportText = event.item.text ?? null;
|
|
48
|
+
}
|
|
49
|
+
return reportText;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function recoveredEvidenceFor(task, structuredReport) {
|
|
53
|
+
const evidence = task.run_evidence
|
|
54
|
+
? { ...task.run_evidence, structured_report: structuredReport }
|
|
55
|
+
: {
|
|
56
|
+
run: task.run_count,
|
|
57
|
+
commands_run: (task.commands ?? []).length,
|
|
58
|
+
structured_report: structuredReport,
|
|
59
|
+
recovered: "turn_completed_without_process_exit"
|
|
60
|
+
};
|
|
61
|
+
if (!evidence.attempt_fingerprint) {
|
|
62
|
+
evidence.attempt_fingerprint = createHash("sha256").update(JSON.stringify({
|
|
63
|
+
output_changed: evidence.output_changed ?? null,
|
|
64
|
+
commands_run: evidence.commands_run ?? (task.commands ?? []).length,
|
|
65
|
+
changed_files: task.changed_files ?? [],
|
|
66
|
+
acceptance_configured: Array.isArray(task.acceptance) && task.acceptance.length > 0,
|
|
67
|
+
workspace_manifest_changed: evidence.workspace?.manifest_changed ?? null
|
|
68
|
+
})).digest("hex");
|
|
69
|
+
}
|
|
70
|
+
return evidence;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function recoveredRow(task, recoveredEvidence, now) {
|
|
74
|
+
const reportInvalid = recoveredEvidence.structured_report?.valid === false && !task.guard_policy?.preflight;
|
|
75
|
+
const attentionReason = task.attention_reason ?? (reportInvalid ? "invalid_report" : null);
|
|
76
|
+
const staleExitError = /did not record the process exit|process disappeared/i.test(task.error ?? "");
|
|
77
|
+
const acceptanceResults = task.acceptance_results ?? (task.acceptance?.length ? {
|
|
78
|
+
status: "interrupted", passed: null, run: task.run_count, finished_at: now,
|
|
79
|
+
error: "worker completed before its acceptance result was recorded; rerun acceptance"
|
|
80
|
+
} : null);
|
|
81
|
+
return {
|
|
82
|
+
...task,
|
|
83
|
+
status: "completed",
|
|
84
|
+
phase: null,
|
|
85
|
+
exit_code: 0,
|
|
86
|
+
attention_reason: attentionReason,
|
|
87
|
+
error: reportInvalid
|
|
88
|
+
? (staleExitError ? null : task.error) ?? `Invalid final worker report: ${recoveredEvidence.structured_report.error}`
|
|
89
|
+
: staleExitError ? null : task.error ?? null,
|
|
90
|
+
current_action: attentionReason ? task.current_action : "Completed (exit recovered from the durable turn event)",
|
|
91
|
+
current_command: null,
|
|
92
|
+
acceptance_results: acceptanceResults,
|
|
93
|
+
run_evidence: recoveredEvidence,
|
|
94
|
+
completed_at: task.completed_at ?? now,
|
|
95
|
+
updated_at: now
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// A run host can disappear after Codex has finished its turn but before it
|
|
100
|
+
// writes the process exit. The terminal event is already durable, and the
|
|
101
|
+
// work did complete; the missing scalar is a supervisor bookkeeping fault,
|
|
102
|
+
// not evidence that the worker vanished. Acceptance keeps its own verdict;
|
|
103
|
+
// recovering the worker completion must never imply that checks passed.
|
|
104
|
+
async function recoverTerminalTurn(task) {
|
|
105
|
+
if (task.exit_code != null || task.signal || !task.started_at) return false;
|
|
106
|
+
// Once the run is over its pids may belong to anyone.
|
|
107
|
+
if (!runIsOver(task) && (isPidAlive(task.pid) || isPidAlive(task.run_host_pid))) return false;
|
|
108
|
+
const runId = runIdFor(task.id, task.run_count);
|
|
109
|
+
const events = openDb().prepare(`
|
|
110
|
+
SELECT payload FROM task_events WHERE task_id = ? AND run_id = ? ORDER BY seq
|
|
111
|
+
`).all(task.id, runId).map((row) => decodeJson(row.payload, null)).filter(Boolean);
|
|
112
|
+
if (!events.some((event) => event.type === "turn.completed")) return false;
|
|
113
|
+
const structuredReport = parseWorkerReportForRun(lastReportText(events), { outputSchema: task.guard_policy?.output_schema !== false });
|
|
114
|
+
const recoveredEvidence = recoveredEvidenceFor(task, structuredReport);
|
|
115
|
+
const now = new Date().toISOString();
|
|
116
|
+
const recoveredTask = recoveredRow(task, recoveredEvidence, now);
|
|
117
|
+
await writeTask(recoveredTask);
|
|
118
|
+
await completeRunRecord(recoveredTask, task.run_count);
|
|
119
|
+
await appendTaskEvent(task.id, {
|
|
120
|
+
type: "supervisor.exit_recovered",
|
|
121
|
+
reason: "turn_completed_without_process_exit",
|
|
122
|
+
exit_code: 0,
|
|
123
|
+
recovered_at: now
|
|
124
|
+
}, { runId, actor: "supervisor" }).catch(() => null);
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function reconcileDetachedActiveTasks() {
|
|
129
|
+
await reconcileInterruptedAcceptance();
|
|
130
|
+
const terminalCandidates = openDb().prepare(`
|
|
131
|
+
SELECT * FROM tasks
|
|
132
|
+
WHERE status IN ('completed','lost') AND exit_code IS NULL AND started_at IS NOT NULL
|
|
133
|
+
`).all().map(rowToTask);
|
|
134
|
+
for (const task of terminalCandidates) await recoverTerminalTurn(task);
|
|
135
|
+
const incomplete = (await readTasks()).filter((task) =>
|
|
136
|
+
["completed", "failed"].includes(task.status) && task.exit_code == null && task.started_at
|
|
137
|
+
&& !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid)
|
|
138
|
+
&& (!task.acceptance_results || ["interrupted", "cancelled"].includes(task.acceptance_results.status))
|
|
139
|
+
&& Date.now() - Date.parse(task.updated_at) > 5000);
|
|
140
|
+
for (const task of incomplete) {
|
|
141
|
+
await writeTask({ ...task, status: "lost", phase: null,
|
|
142
|
+
error: task.acceptance_results?.status === "interrupted"
|
|
143
|
+
? "Worker ended but its supervisor did not record the process exit before acceptance; resume this run"
|
|
144
|
+
: "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
|
|
145
|
+
current_action: task.acceptance_results?.status === "interrupted"
|
|
146
|
+
? "Acceptance interrupted: worker process exit was not recorded; resume this run"
|
|
147
|
+
: "Resume required: process exit was not recorded",
|
|
148
|
+
updated_at: new Date().toISOString() });
|
|
149
|
+
}
|
|
150
|
+
const tasks = await readActiveTasks();
|
|
151
|
+
const staleTasks = tasks.filter((task) => !isPidAlive(task.run_host_pid)
|
|
152
|
+
&& ((task.pid && !isPidAlive(task.pid)) || neverStarted(task)));
|
|
153
|
+
for (const task of staleTasks) {
|
|
154
|
+
if (await recoverTerminalTurn(task)) continue;
|
|
155
|
+
const now = new Date().toISOString();
|
|
156
|
+
const vanished = Boolean(task.pid);
|
|
157
|
+
await writeTask({
|
|
158
|
+
...task,
|
|
159
|
+
status: "lost",
|
|
160
|
+
phase: null,
|
|
161
|
+
current_action: vanished
|
|
162
|
+
? "Worker process disappeared without a terminal event"
|
|
163
|
+
: "Worker was never started: no process was recorded for this row",
|
|
164
|
+
current_command: null,
|
|
165
|
+
error: task.error ?? (vanished
|
|
166
|
+
? "Codex worker process disappeared before a terminal event was recorded."
|
|
167
|
+
: "Codex worker row was written but no process was ever recorded for it."),
|
|
168
|
+
completed_at: task.completed_at || now,
|
|
169
|
+
updated_at: now
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return staleTasks;
|
|
173
|
+
}
|