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
|
@@ -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,172 @@
|
|
|
1
|
+
import { 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
|
|
106
|
+
|| isPidAlive(task.pid) || isPidAlive(task.run_host_pid)) return false;
|
|
107
|
+
const runId = runIdFor(task.id, task.run_count);
|
|
108
|
+
const events = openDb().prepare(`
|
|
109
|
+
SELECT payload FROM task_events WHERE task_id = ? AND run_id = ? ORDER BY seq
|
|
110
|
+
`).all(task.id, runId).map((row) => decodeJson(row.payload, null)).filter(Boolean);
|
|
111
|
+
if (!events.some((event) => event.type === "turn.completed")) return false;
|
|
112
|
+
const structuredReport = parseWorkerReportForRun(lastReportText(events), { outputSchema: task.guard_policy?.output_schema !== false });
|
|
113
|
+
const recoveredEvidence = recoveredEvidenceFor(task, structuredReport);
|
|
114
|
+
const now = new Date().toISOString();
|
|
115
|
+
const recoveredTask = recoveredRow(task, recoveredEvidence, now);
|
|
116
|
+
await writeTask(recoveredTask);
|
|
117
|
+
await completeRunRecord(recoveredTask, task.run_count);
|
|
118
|
+
await appendTaskEvent(task.id, {
|
|
119
|
+
type: "supervisor.exit_recovered",
|
|
120
|
+
reason: "turn_completed_without_process_exit",
|
|
121
|
+
exit_code: 0,
|
|
122
|
+
recovered_at: now
|
|
123
|
+
}, { runId, actor: "supervisor" }).catch(() => null);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function reconcileDetachedActiveTasks() {
|
|
128
|
+
await reconcileInterruptedAcceptance();
|
|
129
|
+
const terminalCandidates = openDb().prepare(`
|
|
130
|
+
SELECT * FROM tasks
|
|
131
|
+
WHERE status IN ('completed','lost') AND exit_code IS NULL AND started_at IS NOT NULL
|
|
132
|
+
`).all().map(rowToTask);
|
|
133
|
+
for (const task of terminalCandidates) await recoverTerminalTurn(task);
|
|
134
|
+
const incomplete = (await readTasks()).filter((task) =>
|
|
135
|
+
["completed", "failed"].includes(task.status) && task.exit_code == null && task.started_at
|
|
136
|
+
&& !isPidAlive(task.pid) && !isPidAlive(task.run_host_pid)
|
|
137
|
+
&& (!task.acceptance_results || ["interrupted", "cancelled"].includes(task.acceptance_results.status))
|
|
138
|
+
&& Date.now() - Date.parse(task.updated_at) > 5000);
|
|
139
|
+
for (const task of incomplete) {
|
|
140
|
+
await writeTask({ ...task, status: "lost", phase: null,
|
|
141
|
+
error: task.acceptance_results?.status === "interrupted"
|
|
142
|
+
? "Worker ended but its supervisor did not record the process exit before acceptance; resume this run"
|
|
143
|
+
: "Worker ended but its supervisor did not record the process exit; recover this run before treating it as complete",
|
|
144
|
+
current_action: task.acceptance_results?.status === "interrupted"
|
|
145
|
+
? "Acceptance interrupted: worker process exit was not recorded; resume this run"
|
|
146
|
+
: "Resume required: process exit was not recorded",
|
|
147
|
+
updated_at: new Date().toISOString() });
|
|
148
|
+
}
|
|
149
|
+
const tasks = await readActiveTasks();
|
|
150
|
+
const staleTasks = tasks.filter((task) => !isPidAlive(task.run_host_pid)
|
|
151
|
+
&& ((task.pid && !isPidAlive(task.pid)) || neverStarted(task)));
|
|
152
|
+
for (const task of staleTasks) {
|
|
153
|
+
if (await recoverTerminalTurn(task)) continue;
|
|
154
|
+
const now = new Date().toISOString();
|
|
155
|
+
const vanished = Boolean(task.pid);
|
|
156
|
+
await writeTask({
|
|
157
|
+
...task,
|
|
158
|
+
status: "lost",
|
|
159
|
+
phase: null,
|
|
160
|
+
current_action: vanished
|
|
161
|
+
? "Worker process disappeared without a terminal event"
|
|
162
|
+
: "Worker was never started: no process was recorded for this row",
|
|
163
|
+
current_command: null,
|
|
164
|
+
error: task.error ?? (vanished
|
|
165
|
+
? "Codex worker process disappeared before a terminal event was recorded."
|
|
166
|
+
: "Codex worker row was written but no process was ever recorded for it."),
|
|
167
|
+
completed_at: task.completed_at || now,
|
|
168
|
+
updated_at: now
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return staleTasks;
|
|
172
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { artifactsDir } from "../paths.js";
|
|
2
|
+
import { decodeJson, ensureFilesystem, openDb } from "./db.js";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
5
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
|
|
7
|
+
export async function recordJsonArtifact({ runId, type, value, securityClass = "internal", retention = "permanent" }) {
|
|
8
|
+
await ensureFilesystem();
|
|
9
|
+
if (!runId || !type) throw new Error("artifact requires runId and type");
|
|
10
|
+
const id = randomUUID();
|
|
11
|
+
const content = JSON.stringify(value, null, 2);
|
|
12
|
+
const sha256 = createHash("sha256").update(content).digest("hex");
|
|
13
|
+
const path = join(artifactsDir, `${id}.json`);
|
|
14
|
+
await writeFile(path, content, { encoding: "utf8", mode: 0o600 });
|
|
15
|
+
const now = new Date().toISOString();
|
|
16
|
+
openDb().prepare(`
|
|
17
|
+
INSERT INTO artifacts (id, run_id, type, uri, sha256, security_class, retention, created_at)
|
|
18
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
19
|
+
`).run(id, runId, type, path, sha256, securityClass, retention, now);
|
|
20
|
+
return { id, run_id: runId, type, uri: path, sha256, security_class: securityClass, retention, created_at: now };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function getArtifact(artifactId) {
|
|
24
|
+
await ensureFilesystem();
|
|
25
|
+
return openDb().prepare("SELECT * FROM artifacts WHERE id = ?").get(artifactId) ?? null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function readArtifact(artifactId, maxChars = 12000) {
|
|
29
|
+
const artifact = await getArtifact(artifactId);
|
|
30
|
+
if (!artifact) return null;
|
|
31
|
+
const artifactPath = relative(artifactsDir, resolve(artifact.uri));
|
|
32
|
+
if (!artifactPath || artifactPath === ".." || artifactPath.startsWith(`..${sep}`) || isAbsolute(artifactPath)) {
|
|
33
|
+
return { ...artifact, content: null, reason: "artifact_uri_not_managed" };
|
|
34
|
+
}
|
|
35
|
+
let content;
|
|
36
|
+
try {
|
|
37
|
+
content = await readFile(artifact.uri, "utf8");
|
|
38
|
+
} catch (error) {
|
|
39
|
+
return { ...artifact, content: null, reason: `artifact_unreadable: ${error.code ?? error.message}` };
|
|
40
|
+
}
|
|
41
|
+
const truncated = content.length > maxChars;
|
|
42
|
+
return { ...artifact, content: truncated ? `${content.slice(0, maxChars)}…` : content, truncated };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function listArtifactsForTask(taskId, limit = 50) {
|
|
46
|
+
await ensureFilesystem();
|
|
47
|
+
return openDb().prepare(`
|
|
48
|
+
SELECT a.* FROM artifacts a JOIN runs r ON r.id = a.run_id
|
|
49
|
+
WHERE r.task_id = ? ORDER BY a.created_at DESC LIMIT ?
|
|
50
|
+
`).all(taskId, limit);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function createReviewAssignment({ subjectTaskId, verifierTaskId, subjectRunId = null, subjectBaseSha = null, subjectFingerprint = null }) {
|
|
54
|
+
await ensureFilesystem();
|
|
55
|
+
const now = new Date().toISOString();
|
|
56
|
+
const id = randomUUID();
|
|
57
|
+
openDb().prepare(`
|
|
58
|
+
INSERT INTO review_findings (id, subject_task_id, verifier_task_id, subject_run_id, subject_base_sha, subject_fingerprint, status, created_at, updated_at)
|
|
59
|
+
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)
|
|
60
|
+
`).run(id, subjectTaskId, verifierTaskId, subjectRunId, subjectBaseSha, subjectFingerprint, now, now);
|
|
61
|
+
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 };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function getReviewByVerifierTask(verifierTaskId) {
|
|
65
|
+
await ensureFilesystem();
|
|
66
|
+
return openDb().prepare("SELECT * FROM review_findings WHERE verifier_task_id = ?").get(verifierTaskId) ?? null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function recordReviewFinding({ verifierTaskId, verdict, reason, evidenceArtifactId = null, findingEventId = null }) {
|
|
70
|
+
await ensureFilesystem();
|
|
71
|
+
if (!['passes', 'fails', 'inconclusive'].includes(verdict)) throw new Error("review verdict must be passes, fails or inconclusive");
|
|
72
|
+
const now = new Date().toISOString();
|
|
73
|
+
const result = openDb().prepare(`
|
|
74
|
+
UPDATE review_findings
|
|
75
|
+
SET status = 'recorded', verdict = ?, reason = ?, evidence_artifact_id = ?, finding_event_id = ?, updated_at = ?
|
|
76
|
+
WHERE verifier_task_id = ? AND status = 'pending'
|
|
77
|
+
`).run(verdict, reason, evidenceArtifactId, findingEventId, now, verifierTaskId);
|
|
78
|
+
if (result.changes === 0) return null;
|
|
79
|
+
return getReviewByVerifierTask(verifierTaskId);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function resolveReviewFinding({ verifierTaskId, resolution, resolvedBy = 'main_thread' }) {
|
|
83
|
+
await ensureFilesystem();
|
|
84
|
+
const now = new Date().toISOString();
|
|
85
|
+
const result = openDb().prepare(`
|
|
86
|
+
UPDATE review_findings
|
|
87
|
+
SET status = 'resolved', resolution = ?, resolved_at = ?, resolved_by = ?, updated_at = ?
|
|
88
|
+
WHERE verifier_task_id = ? AND status = 'recorded'
|
|
89
|
+
`).run(resolution, now, resolvedBy, now, verifierTaskId);
|
|
90
|
+
if (result.changes === 0) return null;
|
|
91
|
+
return getReviewByVerifierTask(verifierTaskId);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function updateWorkItemDelivery(taskId, deliveryState) {
|
|
95
|
+
await ensureFilesystem();
|
|
96
|
+
if (!["draft", "verified", "landed", "push_verified", "cleanup_eligible", "cleanup_removed", "needs_attention"].includes(deliveryState)) {
|
|
97
|
+
throw new Error("invalid delivery state");
|
|
98
|
+
}
|
|
99
|
+
const result = openDb().prepare("UPDATE work_items SET delivery_state = ?, updated_at = ? WHERE task_id = ?")
|
|
100
|
+
.run(deliveryState, new Date().toISOString(), taskId);
|
|
101
|
+
return result.changes > 0;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function saveCleanupPlan(plan) {
|
|
105
|
+
await ensureFilesystem();
|
|
106
|
+
const dbInstance = openDb();
|
|
107
|
+
dbInstance.exec("BEGIN IMMEDIATE");
|
|
108
|
+
try {
|
|
109
|
+
dbInstance.prepare(`
|
|
110
|
+
INSERT INTO cleanup_plans (id, project_root, generated_at, expires_at, policy, summary_json)
|
|
111
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
112
|
+
`).run(plan.id, plan.project_root, plan.generated_at, plan.expires_at, plan.policy, JSON.stringify(plan.summary));
|
|
113
|
+
const insert = dbInstance.prepare(`
|
|
114
|
+
INSERT INTO cleanup_plan_items (id, plan_id, task_id, verdict, reasons_json, fingerprint, reclaimable_bytes, eligible_after, applied_at, applied_by)
|
|
115
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)
|
|
116
|
+
`);
|
|
117
|
+
for (const item of plan.items) {
|
|
118
|
+
item.id = item.id ?? randomUUID();
|
|
119
|
+
insert.run(item.id, plan.id, item.task_id, item.verdict, JSON.stringify(item.reasons), item.fingerprint, item.reclaimable_bytes, item.eligible_after);
|
|
120
|
+
if (item.verdict === "safe") {
|
|
121
|
+
dbInstance.prepare("UPDATE work_items SET delivery_state = 'cleanup_eligible', updated_at = ? WHERE task_id = ? AND delivery_state = 'push_verified'")
|
|
122
|
+
.run(new Date().toISOString(), item.task_id);
|
|
123
|
+
} else {
|
|
124
|
+
dbInstance.prepare("UPDATE work_items SET delivery_state = 'push_verified', updated_at = ? WHERE task_id = ? AND delivery_state = 'cleanup_eligible'")
|
|
125
|
+
.run(new Date().toISOString(), item.task_id);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
dbInstance.exec("COMMIT");
|
|
129
|
+
} catch (error) {
|
|
130
|
+
dbInstance.exec("ROLLBACK");
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export async function getCleanupPlan(planId) {
|
|
136
|
+
await ensureFilesystem();
|
|
137
|
+
const plan = openDb().prepare("SELECT * FROM cleanup_plans WHERE id = ?").get(planId);
|
|
138
|
+
if (!plan) return null;
|
|
139
|
+
const items = openDb().prepare("SELECT * FROM cleanup_plan_items WHERE plan_id = ? ORDER BY task_id").all(planId).map((item) => ({
|
|
140
|
+
...item,
|
|
141
|
+
reasons: decodeJson(item.reasons_json, [])
|
|
142
|
+
}));
|
|
143
|
+
return { ...plan, summary: decodeJson(plan.summary_json, {}), items };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function markCleanupPlanItemApplied(itemId, actor = "main_thread") {
|
|
147
|
+
await ensureFilesystem();
|
|
148
|
+
const now = new Date().toISOString();
|
|
149
|
+
openDb().prepare("UPDATE cleanup_plan_items SET applied_at = ?, applied_by = ? WHERE id = ? AND applied_at IS NULL")
|
|
150
|
+
.run(now, actor, itemId);
|
|
151
|
+
return now;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function readCleanupHistory(taskId = null, limit = 100) {
|
|
155
|
+
await ensureFilesystem();
|
|
156
|
+
const rows = taskId
|
|
157
|
+
? 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)
|
|
158
|
+
: 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);
|
|
159
|
+
return rows.map((row) => ({ ...row, reasons: decodeJson(row.reasons_json, []) }));
|
|
160
|
+
}
|