@deksden-com/dd-flow-cli 0.9.0-beta.37 → 0.9.0-beta.39
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/CHANGELOG.md +16 -0
- package/dist/build-info.json +5 -5
- package/dist/cli/help.js +42 -1
- package/dist/cli/run-cli.js +145 -17
- package/dist/harness-runtime/bin/dd-agy.mjs +3 -2
- package/dist/harness-runtime/bin/dd-codex.mjs +4 -3
- package/dist/harness-runtime/bin/dd-droid.mjs +3 -2
- package/dist/harness-runtime/bin/dd-grok.mjs +4 -3
- package/dist/harness-runtime/bin/dd-opencode.mjs +4 -3
- package/dist/harness-runtime/bin/dd-zcode.mjs +4 -3
- package/dist/harness-runtime/lib/daemon-operations.mjs +48 -9
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +73 -20
- package/dist/harness-runtime/lib/dd-codex-daemon.mjs +57 -16
- package/dist/harness-runtime/lib/dd-codex.mjs +10 -2
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +3 -2
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +12 -6
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +4 -3
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +8 -5
- package/dist/harness-runtime/lib/managed-daemon.mjs +125 -6
- package/dist/harness-runtime/lib/process-json.mjs +1 -1
- package/dist/harness-runtime/lib/session-settlement.mjs +4 -2
- package/dist/schemas/run-control-receipt.schema.json +99 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/services/cleanup.js +7 -4
- package/dist/services/cli-operation-classifier.js +3 -1
- package/dist/services/code-checks.js +33 -7
- package/dist/services/controller-fanout.js +105 -0
- package/dist/services/engines.js +2 -0
- package/dist/services/eval-snapshots.js +347 -36
- package/dist/services/execution-policy.js +122 -6
- package/dist/services/external-work-launch.js +33 -12
- package/dist/services/harness-adapter.js +49 -2
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-processes.js +54 -7
- package/dist/services/merge-server.js +53 -30
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +31 -0
- package/dist/services/protocols.js +9 -0
- package/dist/services/recovery-snapshot-database.js +103 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +297 -0
- package/dist/services/run-control.js +752 -0
- package/dist/services/run-controller-adapter.js +44 -0
- package/dist/services/run-controller-capture.js +117 -0
- package/dist/services/run-controller-process.js +178 -0
- package/dist/services/run-controller-recovery.js +219 -0
- package/dist/services/run-controller-state.js +31 -0
- package/dist/services/run-controller.js +538 -0
- package/dist/services/run-recovery-runtime.js +69 -0
- package/dist/services/run-recovery.js +33 -9
- package/dist/services/runs.js +65 -13
- package/dist/services/runtime-budget.js +362 -0
- package/dist/services/runtime-scope-capture.js +50 -0
- package/dist/services/runtime-scope-control.js +431 -0
- package/dist/services/runtime-scope-resume.js +543 -0
- package/dist/services/runtime-scope-stop.js +95 -0
- package/dist/services/runtime-scope-worker.js +165 -0
- package/dist/services/runtime-service.js +4 -0
- package/dist/services/vnext-code-review.js +1 -1
- package/dist/services/vnext-code.js +1 -1
- package/dist/services/vnext-execution-profile.js +2 -35
- package/dist/services/vnext-fanout.js +23 -7
- package/dist/services/vnext-plan-review.js +12 -9
- package/dist/services/vnext-plan.js +1 -1
- package/dist/services/vnext-protocolize.js +10 -4
- package/dist/services/vnext-specify.js +12 -5
- package/dist/services/work-registry.js +26 -8
- package/dist/services/workspace-bootstrap.js +10 -1
- package/dist/storage/database.js +160 -13
- package/dist/storage/writer-contract.js +76 -0
- package/dist/storage/writer-migration.js +102 -0
- package/package.json +1 -1
|
@@ -2,13 +2,18 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { DatabaseSync } from "node:sqlite";
|
|
6
|
+
import { registerStoreWriter } from "../storage/writer-contract.js";
|
|
5
7
|
import { createContext } from "../runtime/context.js";
|
|
6
8
|
import { AppError } from "../shared/errors.js";
|
|
7
|
-
import { resolveProjectRoot } from "../storage/paths.js";
|
|
9
|
+
import { resolveProjectRoot, runtimeProtocolDir, runtimeRunDir } from "../storage/paths.js";
|
|
8
10
|
import { registerProject, requireProjectByRoot } from "./projects.js";
|
|
9
|
-
import { getFlowRunStatus, startFlowRun } from "./runs.js";
|
|
11
|
+
import { freezeRunExecutionRouting, getFlowRunStatus, importFlowRunExecutionProfile, startFlowRun } from "./runs.js";
|
|
12
|
+
import { loadExecutionRoutingInput, resolveExecutionPolicy } from "./execution-policy.js";
|
|
10
13
|
import { readVnextFlowDefinition } from "./vnext-specify.js";
|
|
11
14
|
import { assertRunWorkResultArtifacts, runWorkResultArtifactIssues } from "./work-registry.js";
|
|
15
|
+
import { captureRecoveryDatabase, readRecoveryResourceEvidence } from "./recovery-snapshot-database.js";
|
|
16
|
+
import { resourceHome } from "./managed-processes.js";
|
|
12
17
|
/** Capture the only flow boundary which exists before `stage start --bootstrap` creates a RUN. */
|
|
13
18
|
export function createEvalBootstrapSnapshot(context, input) {
|
|
14
19
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
@@ -45,9 +50,8 @@ export function restoreEvalBootstrapSnapshot(_context, input) {
|
|
|
45
50
|
return { ok: true, schema_id: "dd-eval/bootstrap-restore@1", snapshot, project_root: projectRoot, target_stage: "specify" };
|
|
46
51
|
}
|
|
47
52
|
/**
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* to infer a safe subset of SQLite rows.
|
|
53
|
+
* Eval fixtures require a dedicated home. Sealed recovery exports instead
|
|
54
|
+
* retain only the selected RUN's relational and filesystem evidence.
|
|
51
55
|
*/
|
|
52
56
|
export function createEvalRunSnapshot(context, input) {
|
|
53
57
|
const output = path.resolve(input.output);
|
|
@@ -55,7 +59,13 @@ export function createEvalRunSnapshot(context, input) {
|
|
|
55
59
|
throw new AppError("snapshot_exists", "Snapshot output already exists", 1, { output });
|
|
56
60
|
const temporary = `${output}.partial-${crypto.randomUUID()}`;
|
|
57
61
|
try {
|
|
62
|
+
input.boundary?.verify();
|
|
63
|
+
const sourceVersion = input.boundary ? snapshotSourceVersion(context, input) : null;
|
|
58
64
|
const result = captureEvalRunSnapshot(context, { ...input, output: temporary });
|
|
65
|
+
if (input.boundary && sourceVersion) {
|
|
66
|
+
Object.assign(result, { consistency: "controller_boundary_writer_barrier@1", boundary_capture: { controller_id: input.boundary.controllerId, operation_id: input.boundary.operationId, boundary_key: input.boundary.boundaryKey, source_sha256: sourceVersion, observation: input.boundary.observation } });
|
|
67
|
+
writeJson(path.join(temporary, "snapshot.json"), Object.fromEntries(Object.entries(result).filter(([key]) => key !== "ok" && key !== "snapshot")));
|
|
68
|
+
}
|
|
59
69
|
if (input.recoveryId) {
|
|
60
70
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
61
71
|
const project = requireProjectByRoot(context, projectRoot);
|
|
@@ -65,6 +75,11 @@ export function createEvalRunSnapshot(context, input) {
|
|
|
65
75
|
if (fs.existsSync(output))
|
|
66
76
|
throw new AppError("snapshot_exists", "Snapshot output already exists", 1, { output });
|
|
67
77
|
syncSnapshotTree(temporary);
|
|
78
|
+
if (input.boundary) {
|
|
79
|
+
if (sourceVersion !== snapshotSourceVersion(context, input))
|
|
80
|
+
throw new AppError("snapshot_source_changed", "Snapshot source files or Git state changed during boundary capture", 1);
|
|
81
|
+
input.boundary.verify();
|
|
82
|
+
}
|
|
68
83
|
fs.renameSync(temporary, output);
|
|
69
84
|
syncPath(path.dirname(output));
|
|
70
85
|
return { ...result, snapshot: output };
|
|
@@ -80,10 +95,16 @@ function captureEvalRunSnapshot(context, input) {
|
|
|
80
95
|
// root must fail without registering a second project in a dedicated home.
|
|
81
96
|
const project = requireProjectByRoot(context, projectRoot);
|
|
82
97
|
const status = getFlowRunStatus(context, { projectRoot, runId: input.runId });
|
|
83
|
-
|
|
98
|
+
const recovery = typeof input.recoveryId === "string";
|
|
99
|
+
if (!recovery && !input.incomplete && context.db.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'run_controllers'")) {
|
|
100
|
+
const controller = context.db.get("SELECT controller_id,status,owner_pid,owner_token FROM run_controllers WHERE project_id = ? AND run_id = ? AND status NOT IN ('completed','cancelled','superseded','stop_target_reached')", [project.id, input.runId]);
|
|
101
|
+
if (controller && (controller.status !== "capturing" || controller.controller_id !== input.boundary?.controllerId || controller.owner_pid !== process.pid || controller.owner_token !== context.env.DD_FLOW_CONTROLLER_TOKEN))
|
|
102
|
+
throw new AppError("snapshot_controller_capture_required", "A live managed RUN must be captured by its fenced controller, not an external observer", 1, { controller_id: controller.controller_id });
|
|
103
|
+
}
|
|
104
|
+
if (!recovery)
|
|
105
|
+
assertDedicatedHome(context, project.id, input.runId);
|
|
84
106
|
if (!input.incomplete)
|
|
85
107
|
assertRunWorkResultArtifacts(context, project.id, input.runId);
|
|
86
|
-
const recovery = typeof input.recoveryId === "string";
|
|
87
108
|
if (recovery) {
|
|
88
109
|
const guard = context.db.get("SELECT status, recovery_id FROM run_recovery_guards WHERE project_id = ? AND run_id = ? AND recovery_id = ?", [project.id, input.runId, input.recoveryId]);
|
|
89
110
|
if (!guard || guard.status !== "sealed")
|
|
@@ -110,20 +131,47 @@ function captureEvalRunSnapshot(context, input) {
|
|
|
110
131
|
const workspaceRoot = String(status.run.workspace_root ?? projectRoot);
|
|
111
132
|
if (isInside(physicalPath(projectRoot), physicalPath(output)) || isInside(physicalPath(workspaceRoot), physicalPath(output)))
|
|
112
133
|
throw new AppError("snapshot_output_inside_project", "Snapshot output must be outside the project and RUN workspace trees", 1, { output });
|
|
113
|
-
fs.mkdirSync(output, { recursive: true });
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
134
|
+
fs.mkdirSync(output, { recursive: true, mode: 0o700 });
|
|
135
|
+
const resourceDatabase = path.join(context.ddFlowHome, "runtime.sqlite");
|
|
136
|
+
const databaseFiles = [context.db.path, resourceDatabase].flatMap(file => [file, `${file}-wal`, `${file}-shm`]);
|
|
137
|
+
if (recovery) {
|
|
138
|
+
if (typeof status.run.run_root !== "string" || !isInside(physicalPath(context.ddFlowHome), physicalPath(status.run.run_root)) || samePath(physicalPath(context.ddFlowHome), physicalPath(status.run.run_root)))
|
|
139
|
+
throw new AppError("snapshot_run_scope_invalid", "Recovery requires a RUN artifact root within its runtime", 1);
|
|
140
|
+
for (const source of new Set([status.run.run_root, runtimeRunDir(context.ddFlowHome, project.id, input.runId)])) {
|
|
141
|
+
if (fs.existsSync(source))
|
|
142
|
+
copyRuntimeTree(source, path.join(output, "runtime", path.relative(context.ddFlowHome, source)));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
else
|
|
146
|
+
copyRuntimeTree(context.ddFlowHome, path.join(output, "runtime"), false, databaseFiles);
|
|
122
147
|
// VACUUM INTO is a consistent SQLite read snapshot, including committed WAL
|
|
123
148
|
// pages. Copying the live database and its WAL separately is not atomic.
|
|
124
149
|
const databaseCopy = path.join(output, "runtime", path.relative(context.ddFlowHome, context.db.path));
|
|
125
150
|
fs.mkdirSync(path.dirname(databaseCopy), { recursive: true });
|
|
126
|
-
|
|
151
|
+
if (recovery) {
|
|
152
|
+
const report = typeof status.run.run_root === "string" ? path.join(output, "runtime", path.relative(context.ddFlowHome, status.run.run_root), "02-protocolize", "stage-report.json") : null;
|
|
153
|
+
if (report && !isInside(physicalPath(path.join(output, "runtime")), physicalPath(report)))
|
|
154
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Recovery protocol evidence is outside the captured runtime", 1);
|
|
155
|
+
const protocols = report && fs.existsSync(report) ? JSON.parse(fs.readFileSync(report, "utf8")).semantic?.acceptance : [];
|
|
156
|
+
if (!Array.isArray(protocols) || !protocols.every(id => typeof id === "string" && id.startsWith("PRT-")))
|
|
157
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Recovery export requires the accepted PROTOCOLIZE protocol IDs", 1);
|
|
158
|
+
captureRecoveryDatabase(context.db, databaseCopy, project.id, input.runId, protocols);
|
|
159
|
+
}
|
|
160
|
+
else
|
|
161
|
+
context.db.exec(`VACUUM INTO '${databaseCopy.replace(/'/g, "''")}'`);
|
|
162
|
+
// Resource heartbeats can continue after productive RUN writers are sealed.
|
|
163
|
+
// Keep their committed evidence consistent too; never copy a live WAL pair.
|
|
164
|
+
if (!recovery && fs.existsSync(resourceDatabase)) {
|
|
165
|
+
const resources = new DatabaseSync(resourceDatabase, { readOnly: true });
|
|
166
|
+
try {
|
|
167
|
+
const resourceCopy = path.join(output, "runtime", "runtime.sqlite");
|
|
168
|
+
resources.exec("PRAGMA busy_timeout = 4000");
|
|
169
|
+
resources.exec(`VACUUM INTO '${resourceCopy.replace(/'/g, "''")}'`);
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
resources.close();
|
|
173
|
+
}
|
|
174
|
+
}
|
|
127
175
|
fs.cpSync(projectRoot, path.join(output, "project"), {
|
|
128
176
|
recursive: true,
|
|
129
177
|
verbatimSymlinks: true,
|
|
@@ -136,6 +184,8 @@ function captureEvalRunSnapshot(context, input) {
|
|
|
136
184
|
const copiedContext = createContext({ ...context.env, DD_FLOW_HOME: path.join(output, "runtime") }, "read_existing");
|
|
137
185
|
let receiptIssues;
|
|
138
186
|
try {
|
|
187
|
+
if (recovery)
|
|
188
|
+
captureRecoveryAuxiliary(context, copiedContext, { projectId: project.id, runId: input.runId, output });
|
|
139
189
|
receiptIssues = runWorkResultArtifactIssues(copiedContext, project.id, input.runId, file => {
|
|
140
190
|
const roots = [[context.ddFlowHome, "runtime"], [workspaceRoot, workspace.kind === "git_worktree" ? "workspace" : "project"], [projectRoot, "project"]];
|
|
141
191
|
for (const [source, payload] of roots) {
|
|
@@ -186,6 +236,8 @@ export function restoreEvalRunSnapshot(context, input) {
|
|
|
186
236
|
if (manifest.purpose === "incomplete")
|
|
187
237
|
throw new AppError("snapshot_incomplete_not_restorable", "Incomplete snapshot is forensic evidence, not a stage-entry fixture", 1, { snapshot });
|
|
188
238
|
const recovery = manifest.purpose === "recovery";
|
|
239
|
+
if (recovery && input.executionRoutingFile !== undefined)
|
|
240
|
+
throw new AppError("snapshot_recovery_policy_frozen", "Recovery must retain its frozen execution policy", 2);
|
|
189
241
|
if (recovery && input.recoveryId !== manifest.recovery_id)
|
|
190
242
|
throw new AppError("snapshot_recovery_requires_explicit_restore", "Recovery snapshots require their explicit --recovery-id", 1, { snapshot });
|
|
191
243
|
if (!recovery && input.recoveryId)
|
|
@@ -200,16 +252,38 @@ export function restoreEvalRunSnapshot(context, input) {
|
|
|
200
252
|
throw new AppError("recovery_restore_target_not_empty", "Recovery restore requires fresh project and runtime targets", 1);
|
|
201
253
|
verifyRecoverySnapshot(snapshot, { runId: manifest.run_id, recoveryId: input.recoveryId, projectRoot, workspaceRoot: projectRoot }, false);
|
|
202
254
|
}
|
|
203
|
-
const existing = fs.readdirSync(context.ddFlowHome).filter((name) => !["db.sqlite", "db.sqlite-wal", "db.sqlite-shm"].includes(name));
|
|
255
|
+
const existing = fs.readdirSync(context.ddFlowHome).filter((name) => !["db.sqlite", "db.sqlite-wal", "db.sqlite-shm", ...(input.executionRoutingFile !== undefined ? ["agent-profiles"] : [])].includes(name));
|
|
204
256
|
if (existing.length > 0)
|
|
205
257
|
throw new AppError("restore_home_not_empty", "Snapshot restore requires an empty DD_FLOW_HOME", 1, { dd_flow_home: context.ddFlowHome, existing });
|
|
258
|
+
if (context.db.get("SELECT 1 FROM projects LIMIT 1") || context.db.get("SELECT 1 FROM runs LIMIT 1"))
|
|
259
|
+
throw new AppError("restore_home_not_empty", "Snapshot restore cannot replace an initialized runtime", 1);
|
|
206
260
|
const sourceRuntime = path.join(snapshot, "runtime");
|
|
207
261
|
const sourceProject = path.join(snapshot, "project");
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
262
|
+
verifySnapshotPayload(snapshot, manifest);
|
|
263
|
+
const routingInput = input.executionRoutingFile !== undefined ? loadExecutionRoutingInput(input.executionRoutingFile) : undefined;
|
|
264
|
+
let selectedProfile;
|
|
265
|
+
if (routingInput) {
|
|
266
|
+
// Resolve selected profiles from the fresh caller home before replacing it.
|
|
267
|
+
// Source DB is read-only; no context or migrations may touch the snapshot.
|
|
268
|
+
const sourceDb = new DatabaseSync(path.join(sourceRuntime, "db.sqlite"), { readOnly: true });
|
|
269
|
+
try {
|
|
270
|
+
const row = sourceDb.prepare("SELECT index_json FROM runs WHERE id = ?").get(manifest.run_id);
|
|
271
|
+
const index = row ? JSON.parse(row.index_json) : null;
|
|
272
|
+
if (!index?.execution_profile || !["vnext_specify", "vnext_protocolize"].includes(index.flow_kind))
|
|
273
|
+
throw new AppError("execution_profile_not_frozen", "Stage-entry routing requires a vNext execution snapshot", 1);
|
|
274
|
+
assertStageEntry(index.stage_runs, manifest.stage_entry);
|
|
275
|
+
selectedProfile = freezeRunExecutionRouting(context.ddFlowHome, index.execution_profile, routingInput);
|
|
276
|
+
for (const row of sourceDb.prepare("SELECT payload_json FROM works WHERE run_id = ? AND status = 'created'").all(manifest.run_id)) {
|
|
277
|
+
const payload = row.payload_json ? JSON.parse(row.payload_json) : null;
|
|
278
|
+
if (payload?.execution_override !== undefined)
|
|
279
|
+
resolveExecutionPolicy({ ddFlowHome: context.ddFlowHome, policy: routingInput.execution, profiles: selectedProfile.agent_profiles, stage: manifest.stage_entry, work: payload.execution_override });
|
|
280
|
+
}
|
|
281
|
+
selectedProfile.routing_input.artifact = `execution-routing.${routingInput.source_checksum}.input.json`;
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
sourceDb.close();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
213
287
|
clearProjectTree(projectRoot, false);
|
|
214
288
|
restoreProjectGit(snapshot, manifest.project_git, projectRoot);
|
|
215
289
|
replaceProjectTree(projectRoot, sourceProject);
|
|
@@ -221,9 +295,21 @@ export function restoreEvalRunSnapshot(context, input) {
|
|
|
221
295
|
// A fresh process owns all subsequent normal commands.
|
|
222
296
|
const restored = createContext({ ...context.env, DD_FLOW_HOME: context.ddFlowHome });
|
|
223
297
|
try {
|
|
298
|
+
const runtimeLineage = recovery ? null : detachSnapshotRuntimeOwners(restored, snapshot, manifest);
|
|
224
299
|
rebaseRuntime(restored, manifest.project_root, projectRoot, sourceWorkspaceRoot(manifest), workspaceRoot, manifest.dd_flow_home, context.ddFlowHome, recovery);
|
|
225
300
|
registerProject(restored, { root: projectRoot });
|
|
226
301
|
requireProjectByRoot(restored, projectRoot);
|
|
302
|
+
if (selectedProfile && routingInput && runtimeLineage) {
|
|
303
|
+
const run = restored.db.get("SELECT run_root FROM runs WHERE id = ?", [manifest.run_id]);
|
|
304
|
+
const artifact = path.join(run.run_root, selectedProfile.routing_input.artifact);
|
|
305
|
+
if (fs.existsSync(artifact)) {
|
|
306
|
+
if (!fs.readFileSync(artifact).equals(routingInput.bytes))
|
|
307
|
+
throw new AppError("snapshot_checksum_mismatch", "Existing routing input does not match its checksum", 1);
|
|
308
|
+
}
|
|
309
|
+
else
|
|
310
|
+
fs.writeFileSync(artifact, routingInput.bytes, { flag: "wx", mode: 0o600 });
|
|
311
|
+
importFlowRunExecutionProfile(restored, { projectRoot, runId: manifest.run_id, stage: manifest.stage_entry, lineageFile: runtimeLineage, profile: selectedProfile });
|
|
312
|
+
}
|
|
227
313
|
const status = getFlowRunStatus(restored, { projectRoot, runId: manifest.run_id });
|
|
228
314
|
if (!recovery)
|
|
229
315
|
assertStageEntry(status.index.stage_runs ?? [], manifest.stage_entry);
|
|
@@ -251,6 +337,7 @@ export function restoreEvalRunSnapshot(context, input) {
|
|
|
251
337
|
dd_flow_home: context.ddFlowHome,
|
|
252
338
|
run_home: runHome,
|
|
253
339
|
target_stage: manifest.stage_entry,
|
|
340
|
+
...(runtimeLineage ? { runtime_lineage_file: runtimeLineage } : {}),
|
|
254
341
|
...(recovery ? { recovery_id: input.recoveryId, native_session_portability: "requires_adapter_verification", relocation_file: relocationFile, relocation } : {}),
|
|
255
342
|
next_command: recovery ? `dd-flow run recovery inspect ${status.run.id} --project-root ${JSON.stringify(projectRoot)} --json` : `dd-flow stage start ${status.run.id} --stage ${manifest.stage_entry} --project-root ${JSON.stringify(projectRoot)} --json`
|
|
256
343
|
};
|
|
@@ -270,6 +357,7 @@ export function prepareVnextSpecifyRun(context, input) {
|
|
|
270
357
|
subjectType: "discussion",
|
|
271
358
|
subjectId: "SPECIFY",
|
|
272
359
|
slug: input.slug,
|
|
360
|
+
executionRoutingFile: input.executionRoutingFile,
|
|
273
361
|
nextAction: "start_specify"
|
|
274
362
|
});
|
|
275
363
|
return { ok: true, run_id: started.run.id, run_root: started.run.run_root, target_stage: "specify" };
|
|
@@ -284,15 +372,69 @@ function assertDedicatedHome(context, projectId, runId) {
|
|
|
284
372
|
function assertStageEntry(stages, target) {
|
|
285
373
|
if (stages.some((entry) => entry.stage === target))
|
|
286
374
|
throw new AppError("snapshot_target_started", "Stage-entry snapshot requires its target stage to be unstarted", 1, { target });
|
|
287
|
-
const unfinished = stages.filter((entry) => entry.status
|
|
375
|
+
const unfinished = stages.filter((entry) => !["done", "skipped"].includes(entry.status ?? ""));
|
|
288
376
|
if (unfinished.length > 0)
|
|
289
377
|
throw new AppError("snapshot_predecessor_incomplete", "Stage-entry snapshot requires completed predecessor stages", 1, { target, unfinished });
|
|
290
378
|
}
|
|
291
379
|
function assertTerminalCandidate(stages) {
|
|
292
|
-
const unfinished = stages.filter((entry) => entry.status
|
|
380
|
+
const unfinished = stages.filter((entry) => !["done", "skipped"].includes(entry.status ?? ""));
|
|
293
381
|
if (unfinished.length > 0)
|
|
294
382
|
throw new AppError("snapshot_candidate_incomplete", "Candidate snapshot requires every started stage to be done", 1, { unfinished });
|
|
295
383
|
}
|
|
384
|
+
/** A stage-entry import is a new experiment, not a lease takeover or recovery.
|
|
385
|
+
* Keep source authority as evidence, never as executable target inventory. */
|
|
386
|
+
function detachSnapshotRuntimeOwners(context, snapshot, manifest) {
|
|
387
|
+
const hasTable = (table) => Boolean(context.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?", [table]));
|
|
388
|
+
if (hasTable("run_recovery_guards") && context.db.get("SELECT 1 FROM run_recovery_guards WHERE status IN ('draining','sealed','resuming') LIMIT 1"))
|
|
389
|
+
throw new AppError("snapshot_control_requires_recovery", "A fenced RUN requires explicit recovery, not a stage-entry fork", 1);
|
|
390
|
+
if (context.db.get("SELECT 1 FROM merge_requests WHERE status IN ('dispatching','active','waiting_user','action_required','recovery_required') LIMIT 1"))
|
|
391
|
+
throw new AppError("snapshot_execution_active", "A stage-entry fork cannot discard an unresolved MERGE execution", 1);
|
|
392
|
+
const detachedTables = ["run_control_admissions", "run_control_stage_admissions", "run_control_operations", "run_control_workers", "run_controls", "run_controller_events", "run_controller_operations", "run_controllers", "run_recovery_bindings", "work_recovery_segments", "run_recovery_guards", "work_launches", "merge_servers", "merge_sessions", "lane_locks", "lane_waiters"].filter(hasTable);
|
|
393
|
+
const runTables = Object.fromEntries([...detachedTables, "runs", "merge_requests", "sessions", "work_sessions"].map(table => [table, context.db.all(`SELECT * FROM ${table}`)]));
|
|
394
|
+
const resourceFile = path.join(context.ddFlowHome, "runtime.sqlite");
|
|
395
|
+
const resources = fs.existsSync(resourceFile) ? new DatabaseSync(resourceFile) : null;
|
|
396
|
+
try {
|
|
397
|
+
if (resources)
|
|
398
|
+
registerStoreWriter(resources);
|
|
399
|
+
const resourceTables = Object.fromEntries(["managed_resources", "managed_processes"].filter(table => resources?.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(table)).map(table => [table, resources.prepare(`SELECT * FROM ${table}`).all()]));
|
|
400
|
+
const directory = path.join(context.ddFlowHome, "snapshot-imports");
|
|
401
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
402
|
+
const file = path.join(directory, `${crypto.randomUUID()}.json`);
|
|
403
|
+
fs.writeFileSync(file, `${JSON.stringify({ schema_id: "dd-flow/snapshot-runtime-lineage@1", source_snapshot: snapshot, source_manifest_sha256: fileHash(path.join(snapshot, "snapshot.json")), source_runtime: manifest.dd_flow_home, restored_runtime: context.ddFlowHome, run_id: manifest.run_id, run_tables: runTables, resource_tables: resourceTables }, null, 2)}\n`, { flag: "wx", mode: 0o600 });
|
|
404
|
+
syncPath(file);
|
|
405
|
+
syncPath(directory);
|
|
406
|
+
context.db.exec("BEGIN IMMEDIATE");
|
|
407
|
+
try {
|
|
408
|
+
context.db.run("UPDATE sessions SET metadata_json = json_set(metadata_json, '$.snapshot_import', json(?))", [JSON.stringify({ lineage_file: file, lineage_sha256: fileHash(file) })]);
|
|
409
|
+
for (const table of detachedTables)
|
|
410
|
+
context.db.exec(`DELETE FROM ${table}`);
|
|
411
|
+
context.db.run("UPDATE merge_requests SET dispatch_owner = NULL, dispatch_lease_token = NULL, dispatch_lease_expires_at = NULL, lock_acquired_at = NULL, adapter_receipt_json = NULL");
|
|
412
|
+
// Only the copied dedicated registry is touched. Source/external homes
|
|
413
|
+
// are historical references in the archive and are never opened here.
|
|
414
|
+
if (resources) {
|
|
415
|
+
resources.exec("BEGIN IMMEDIATE");
|
|
416
|
+
try {
|
|
417
|
+
for (const table of Object.keys(resourceTables))
|
|
418
|
+
resources.exec(`DELETE FROM ${table}`);
|
|
419
|
+
resources.exec("COMMIT");
|
|
420
|
+
}
|
|
421
|
+
catch (error) {
|
|
422
|
+
resources.exec("ROLLBACK");
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
context.db.exec("COMMIT");
|
|
427
|
+
}
|
|
428
|
+
catch (error) {
|
|
429
|
+
context.db.exec("ROLLBACK");
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
return file;
|
|
433
|
+
}
|
|
434
|
+
finally {
|
|
435
|
+
resources?.close();
|
|
436
|
+
}
|
|
437
|
+
}
|
|
296
438
|
function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome, recovery = false) {
|
|
297
439
|
context.db.exec("PRAGMA foreign_keys = OFF");
|
|
298
440
|
context.db.exec("BEGIN IMMEDIATE");
|
|
@@ -304,7 +446,12 @@ function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, ol
|
|
|
304
446
|
context.db.run("UPDATE protocols SET project_root = ?", [newRoot]);
|
|
305
447
|
for (const column of ["state_path", "plan_path"])
|
|
306
448
|
rewriteDatabaseColumn(context, "protocols", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
307
|
-
|
|
449
|
+
for (const column of ["source_workspace", "target_workspace"])
|
|
450
|
+
rewriteDatabaseColumn(context, "merge_requests", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
451
|
+
if (recovery)
|
|
452
|
+
context.db.run("UPDATE sessions SET project_root = ?, status = CASE WHEN status = 'active' THEN 'stopped' ELSE status END, stop_reason = CASE WHEN status = 'active' THEN 'snapshot_restored' ELSE stop_reason END", [newRoot]);
|
|
453
|
+
else
|
|
454
|
+
context.db.run("UPDATE sessions SET project_root = ?, status = 'stopped', stop_reason = 'snapshot_restored', stopped_at = ?", [newRoot, context.now()]);
|
|
308
455
|
for (const column of ["workspace_path", "cwd", "transcript_path"])
|
|
309
456
|
rewriteDatabaseColumn(context, "sessions", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
310
457
|
for (const column of ["prompt_path", "result_path"])
|
|
@@ -337,10 +484,13 @@ function rewriteStructuredFiles(root, oldRoot, newRoot, oldWorkspace, newWorkspa
|
|
|
337
484
|
const visit = (dir) => {
|
|
338
485
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
339
486
|
const file = path.join(dir, entry.name);
|
|
487
|
+
// This is hashed input evidence, not a mutable runtime projection.
|
|
488
|
+
if (/^execution-routing(?:\.[a-f0-9]{64})?\.input\.json$/.test(entry.name))
|
|
489
|
+
continue;
|
|
340
490
|
// DD_FLOW_HOME also contains the restored checkout and installed tools.
|
|
341
491
|
// They are project/tool bytes, not flow records; parsing every *.json
|
|
342
492
|
// there breaks on valid JSON-with-comments such as tsconfig files.
|
|
343
|
-
if (entry.isDirectory() && ![".git", "checkouts", "engines", "node_modules", "tools"].includes(entry.name))
|
|
493
|
+
if (entry.isDirectory() && ![".git", "checkouts", "engines", "node_modules", "tools", "snapshot-imports"].includes(entry.name))
|
|
344
494
|
visit(file);
|
|
345
495
|
else if (entry.isFile() && entry.name.endsWith(".json")) {
|
|
346
496
|
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
@@ -517,21 +667,37 @@ export function verifyRecoverySnapshot(snapshot, input, checkWorkingState = true
|
|
|
517
667
|
{ name: "project", root: input.projectRoot, hash: manifest.project_sha256, git: manifest.project_git, head: manifest.project_git.head },
|
|
518
668
|
...(manifest.workspace.kind === "git_worktree" ? [{ name: "workspace", root: input.workspaceRoot, hash: manifest.workspace.sha256, git: manifest.workspace, head: manifest.workspace.base_ref }] : [])
|
|
519
669
|
];
|
|
520
|
-
|
|
521
|
-
throw new AppError("snapshot_checksum_mismatch", "Recovery runtime checksum does not match", 1);
|
|
522
|
-
verifySnapshotModes(snapshot, manifest);
|
|
670
|
+
verifySnapshotPayload(snapshot, manifest);
|
|
523
671
|
for (const entry of entries) {
|
|
524
672
|
const expectedModes = manifest.payload_modes?.[entry.name];
|
|
525
673
|
if (checkWorkingState && expectedModes && treeModesHash(entry.root, true) !== expectedModes)
|
|
526
674
|
throw new AppError("recovery_workspace_drift", "Executable file modes changed after recovery capture", 1, { payload: entry.name });
|
|
527
|
-
if (treeHash(path.join(snapshot, entry.name)) !== entry.hash || fileHash(path.join(snapshot, `${entry.name}.bundle`)) !== entry.git.bundle_sha256 || (entry.git.index_sha256 && fileHash(path.join(snapshot, `${entry.name}.index.patch`)) !== entry.git.index_sha256))
|
|
528
|
-
throw new AppError("snapshot_checksum_mismatch", "Recovery payload checksum does not match", 1, { payload: entry.name });
|
|
529
|
-
if (entry.git.index_format === "entries@1" && (!entry.git.index_objects_sha256 || fileHash(path.join(snapshot, `${entry.name}.index.pack`)) !== entry.git.index_objects_sha256))
|
|
530
|
-
throw new AppError("snapshot_checksum_mismatch", "Recovery Git object checksum does not match", 1, { payload: entry.name });
|
|
531
675
|
if (checkWorkingState && (treeHash(entry.root, true) !== entry.hash || git(entry.root, ["rev-parse", "HEAD"]) !== entry.head || git(entry.root, ["symbolic-ref", "--quiet", "--short", "HEAD"]) !== entry.git.branch || (entry.git.index_sha256 && crypto.createHash("sha256").update(entry.git.index_format === "entries@1" ? indexEntries(entry.root) : indexPatch(entry.root)).digest("hex") !== entry.git.index_sha256)))
|
|
532
676
|
throw new AppError("recovery_workspace_drift", "Working files or Git state changed after recovery capture", 1, { payload: entry.name });
|
|
533
677
|
}
|
|
534
678
|
}
|
|
679
|
+
/** Reuse an already published boundary only after checking its identity and
|
|
680
|
+
* every payload, including its Git index objects. Never overwrite evidence. */
|
|
681
|
+
export function verifyControllerBoundarySnapshot(snapshot, input) {
|
|
682
|
+
const manifest = readManifest(snapshot), boundary = manifest.boundary_capture;
|
|
683
|
+
if (!boundary || manifest.consistency !== "controller_boundary_writer_barrier@1" || manifest.run_id !== input.runId || boundary.controller_id !== input.controllerId || boundary.operation_id !== input.operationId || boundary.boundary_key !== input.boundaryKey || manifest.stage_entry !== input.stageEntry || manifest.purpose !== (input.stageEntry ? "stage_entry" : "candidate") || !/^[a-f0-9]{64}$/.test(boundary.source_sha256) || boundary.observation?.settled !== true || boundary.observation.operation_id !== input.operationId)
|
|
684
|
+
throw new AppError("controller_boundary_snapshot_invalid", "Published snapshot does not prove this controller boundary", 1, { snapshot });
|
|
685
|
+
verifySnapshotPayload(snapshot, manifest);
|
|
686
|
+
const file = path.join(snapshot, "snapshot.json");
|
|
687
|
+
if (input.manifestSha256 !== undefined && fileHash(file) !== input.manifestSha256)
|
|
688
|
+
throw new AppError("snapshot_checksum_mismatch", "Boundary manifest no longer matches its retained publication receipt", 1, { snapshot });
|
|
689
|
+
return { snapshot, manifest: file, manifest_sha256: fileHash(file), purpose: manifest.purpose, stage_entry: manifest.stage_entry };
|
|
690
|
+
}
|
|
691
|
+
function verifySnapshotPayload(snapshot, manifest) {
|
|
692
|
+
if (treeHash(path.join(snapshot, "runtime")) !== manifest.runtime_sha256)
|
|
693
|
+
throw new AppError("snapshot_checksum_mismatch", "Snapshot runtime checksum does not match", 1);
|
|
694
|
+
verifySnapshotModes(snapshot, manifest);
|
|
695
|
+
const payloads = [{ name: "project", hash: manifest.project_sha256, git: manifest.project_git }, ...(manifest.workspace.kind === "git_worktree" ? [{ name: "workspace", hash: manifest.workspace.sha256, git: manifest.workspace }] : [])];
|
|
696
|
+
for (const payload of payloads) {
|
|
697
|
+
if (treeHash(path.join(snapshot, payload.name)) !== payload.hash || fileHash(path.join(snapshot, `${payload.name}.bundle`)) !== payload.git.bundle_sha256 || payload.git.index_sha256 && fileHash(path.join(snapshot, `${payload.name}.index.patch`)) !== payload.git.index_sha256 || payload.git.index_format === "entries@1" && (!payload.git.index_objects_sha256 || fileHash(path.join(snapshot, `${payload.name}.index.pack`)) !== payload.git.index_objects_sha256))
|
|
698
|
+
throw new AppError("snapshot_checksum_mismatch", "Snapshot payload or Git index checksum does not match", 1, { payload: payload.name });
|
|
699
|
+
}
|
|
700
|
+
}
|
|
535
701
|
function git(root, args) {
|
|
536
702
|
const result = spawnSync("git", ["-C", root, ...args], { encoding: "utf8" });
|
|
537
703
|
return result.status === 0 ? result.stdout.trim() : null;
|
|
@@ -547,13 +713,158 @@ function snapshotPayloadAllowed(source) {
|
|
|
547
713
|
return ![".git", "node_modules", ".cache", ".npm", ".pnpm-store"].includes(name)
|
|
548
714
|
&& name !== ".env" && !name.startsWith(".env.");
|
|
549
715
|
}
|
|
716
|
+
function runtimePayloadAllowed(source) {
|
|
717
|
+
return snapshotPayloadAllowed(source) && !["auth.json", "auth.bk", "credentials.json", ".credentials.json", "credentials", ".credentials", "id_rsa", "id_ed25519", "engines", "checkouts"].includes(path.basename(source));
|
|
718
|
+
}
|
|
719
|
+
/** Productive writers are fenced separately. Recheck copied bytes and Git
|
|
720
|
+
* state so an uncoordinated file writer cannot publish a mixed boundary. */
|
|
721
|
+
function snapshotSourceVersion(context, input) {
|
|
722
|
+
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
723
|
+
const project = requireProjectByRoot(context, projectRoot);
|
|
724
|
+
const run = context.db.get("SELECT workspace_root FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
|
|
725
|
+
if (!run)
|
|
726
|
+
throw new AppError("not_found", "Snapshot RUN is not registered", 1);
|
|
727
|
+
const resources = path.join(context.ddFlowHome, "runtime.sqlite");
|
|
728
|
+
// Resource heartbeats are not productive writers. Their semantic identities
|
|
729
|
+
// are rechecked by the owner; each resource DB is copied consistently.
|
|
730
|
+
const runtimeFilter = (file) => runtimePayloadAllowed(file) && !file.endsWith("-shm") && ![resources, `${resources}-wal`, `${resources}-journal`].includes(file);
|
|
731
|
+
const roots = [...new Set([projectRoot, run.workspace_root])];
|
|
732
|
+
return crypto.createHash("sha256").update(JSON.stringify([
|
|
733
|
+
treeHash(context.ddFlowHome, runtimeFilter), treeModesHash(context.ddFlowHome, runtimeFilter),
|
|
734
|
+
...roots.map(root => [treeHash(root, true), treeModesHash(root, true), git(root, ["symbolic-ref", "--quiet", "HEAD"]), gitBytes(root, ["show-ref", "--head"]).toString("base64"), indexEntries(root).toString("base64")])
|
|
735
|
+
])).digest("hex");
|
|
736
|
+
}
|
|
737
|
+
/** Copy a dedicated home or scoped recovery tree, preserving SQLite WAL commits. */
|
|
738
|
+
function copyRuntimeTree(source, destination, scoped = true, excluded = []) {
|
|
739
|
+
if (fs.lstatSync(source).isSymbolicLink())
|
|
740
|
+
throw new AppError("snapshot_runtime_symlink_outside_scope", "Recovery artifact roots must not be symbolic links", 1, { path: source });
|
|
741
|
+
const root = physicalPath(source);
|
|
742
|
+
if (isInside(root, physicalPath(destination)))
|
|
743
|
+
throw new AppError("snapshot_output_inside_runtime", "Recovery output must be outside its source artifact tree", 1);
|
|
744
|
+
const databases = [];
|
|
745
|
+
const sqlite = (file) => {
|
|
746
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile())
|
|
747
|
+
return false;
|
|
748
|
+
const descriptor = fs.openSync(file, "r");
|
|
749
|
+
try {
|
|
750
|
+
const header = Buffer.alloc(16);
|
|
751
|
+
return fs.readSync(descriptor, header, 0, 16, 0) === 16 && header.toString() === "SQLite format 3\0";
|
|
752
|
+
}
|
|
753
|
+
finally {
|
|
754
|
+
fs.closeSync(descriptor);
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
758
|
+
fs.cpSync(source, destination, {
|
|
759
|
+
recursive: true, verbatimSymlinks: true,
|
|
760
|
+
filter: file => {
|
|
761
|
+
if (!runtimePayloadAllowed(file) || excluded.includes(file))
|
|
762
|
+
return false;
|
|
763
|
+
const stat = fs.lstatSync(file);
|
|
764
|
+
if (stat.isSymbolicLink()) {
|
|
765
|
+
if (scoped && !isInside(root, physicalPath(file)))
|
|
766
|
+
throw new AppError("snapshot_runtime_symlink_outside_scope", "Recovery artifact link leaves its owned tree", 1, { path: file });
|
|
767
|
+
return true;
|
|
768
|
+
}
|
|
769
|
+
if (!stat.isDirectory() && !stat.isFile())
|
|
770
|
+
return false;
|
|
771
|
+
if (stat.isFile()) {
|
|
772
|
+
if (/-(?:wal|shm|journal)$/.test(file) && sqlite(file.replace(/-(?:wal|shm|journal)$/, "")))
|
|
773
|
+
return false;
|
|
774
|
+
if (sqlite(file)) {
|
|
775
|
+
databases.push(file);
|
|
776
|
+
return false;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
});
|
|
782
|
+
for (const file of databases) {
|
|
783
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
784
|
+
try {
|
|
785
|
+
const target = source === file ? destination : path.join(destination, path.relative(source, file));
|
|
786
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
787
|
+
db.exec("PRAGMA busy_timeout = 4000");
|
|
788
|
+
db.exec(`VACUUM INTO '${target.replace(/'/g, "''")}'`);
|
|
789
|
+
}
|
|
790
|
+
finally {
|
|
791
|
+
db.close();
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
function captureRecoveryAuxiliary(context, captured, input) {
|
|
796
|
+
const runtime = path.join(input.output, "runtime");
|
|
797
|
+
const run = captured.db.get("SELECT run_root, project_root, workspace_root FROM runs WHERE project_id = ? AND id = ?", [input.projectId, input.runId]);
|
|
798
|
+
const roots = [run.run_root, runtimeRunDir(context.ddFlowHome, input.projectId, input.runId)];
|
|
799
|
+
for (const protocol of captured.db.all("SELECT id, state_path, plan_path FROM protocols")) {
|
|
800
|
+
const directory = runtimeProtocolDir(context.ddFlowHome, input.projectId, protocol.id);
|
|
801
|
+
if (!isInside(physicalPath(context.ddFlowHome), physicalPath(directory)))
|
|
802
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Protocol runtime leaves DD_FLOW_HOME", 1);
|
|
803
|
+
if (fs.existsSync(directory)) {
|
|
804
|
+
copyRuntimeTree(directory, path.join(runtime, path.relative(context.ddFlowHome, directory)));
|
|
805
|
+
roots.push(directory);
|
|
806
|
+
}
|
|
807
|
+
for (const file of [protocol.state_path, protocol.plan_path]) {
|
|
808
|
+
if (!fs.existsSync(file) || roots.some(root => isInside(physicalPath(root), physicalPath(file))))
|
|
809
|
+
continue;
|
|
810
|
+
if (isInside(physicalPath(context.ddFlowHome), physicalPath(file)) && fs.statSync(file).isFile())
|
|
811
|
+
copyRuntimeTree(file, path.join(runtime, path.relative(context.ddFlowHome, file)));
|
|
812
|
+
else if (![run.project_root, run.workspace_root].some(root => isInside(physicalPath(root), physicalPath(file))))
|
|
813
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Protocol evidence is outside captured payloads", 1, { path: file });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
const homes = new Set([context.ddFlowHome, resourceHome(context)]);
|
|
817
|
+
const queries = {
|
|
818
|
+
run_controllers: "SELECT json_extract(manifest_json, '$.resource_home') AS home FROM run_controllers UNION SELECT json_extract(value, '$.owner.resource_home') FROM run_controllers, json_each(state_json, '$.sessions')",
|
|
819
|
+
run_control_workers: "SELECT resource_home AS home FROM run_control_workers",
|
|
820
|
+
work_launches: "SELECT json_extract(profile_json, '$.runtime_adapter.owner.resource_home') AS home FROM work_launches",
|
|
821
|
+
merge_requests: "SELECT json_extract(adapter_receipt_json, '$.owner.resource_home') AS home FROM merge_requests",
|
|
822
|
+
run_recovery_guards: "SELECT value AS home FROM run_recovery_guards, json_each(settlement_json, '$.resource_homes')"
|
|
823
|
+
};
|
|
824
|
+
const references = Object.entries(queries).flatMap(([table, query]) => captured.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?", [table]) ? captured.db.all(query) : []);
|
|
825
|
+
for (const { home } of references) {
|
|
826
|
+
if (home === null)
|
|
827
|
+
continue;
|
|
828
|
+
if (typeof home !== "string" || !path.isAbsolute(home))
|
|
829
|
+
throw new AppError("snapshot_resource_scope_invalid", "Retained resource home must be an absolute path", 1);
|
|
830
|
+
homes.add(home);
|
|
831
|
+
}
|
|
832
|
+
const nativeCaptures = new Map();
|
|
833
|
+
const registries = [];
|
|
834
|
+
for (const home of [...homes].sort()) {
|
|
835
|
+
if (!path.isAbsolute(home))
|
|
836
|
+
throw new AppError("snapshot_resource_scope_invalid", "Resource home must be an absolute path", 1);
|
|
837
|
+
const evidence = readRecoveryResourceEvidence(home, input.projectId, input.runId, { db: captured.db, ddFlowHome: context.ddFlowHome });
|
|
838
|
+
for (const process of evidence.processes) {
|
|
839
|
+
const directory = JSON.parse(process.metadata_json).state_dir;
|
|
840
|
+
if (directory === undefined)
|
|
841
|
+
continue;
|
|
842
|
+
if (typeof directory !== "string" || !path.isAbsolute(directory))
|
|
843
|
+
throw new AppError("snapshot_native_scope_invalid", "Native artifact root must be absolute", 1);
|
|
844
|
+
if (roots.some(root => isInside(physicalPath(root), physicalPath(directory))) || nativeCaptures.has(directory))
|
|
845
|
+
continue;
|
|
846
|
+
const state = JSON.parse(fs.readFileSync(path.join(directory, "daemon.json"), "utf8"));
|
|
847
|
+
const owner = state.config?.runtime_owner;
|
|
848
|
+
if (!owner || owner.project_id !== input.projectId || owner.run_id !== input.runId || owner.owner_id !== process.owner_id || owner.dd_flow_home !== context.ddFlowHome || owner.resource_home !== home || owner.state_dir !== directory)
|
|
849
|
+
throw new AppError("snapshot_native_scope_invalid", "External native artifact root has no matching RUN owner", 1, { state_dir: directory });
|
|
850
|
+
const relative = path.join("native-evidence", crypto.createHash("sha256").update(directory).digest("hex"));
|
|
851
|
+
copyRuntimeTree(directory, path.join(runtime, relative));
|
|
852
|
+
nativeCaptures.set(directory, relative);
|
|
853
|
+
}
|
|
854
|
+
const relative = path.join("resource-evidence", `${crypto.createHash("sha256").update(home).digest("hex")}.json`);
|
|
855
|
+
fs.mkdirSync(path.dirname(path.join(runtime, relative)), { recursive: true });
|
|
856
|
+
writeJson(path.join(runtime, relative), evidence);
|
|
857
|
+
registries.push(relative);
|
|
858
|
+
}
|
|
859
|
+
writeJson(path.join(runtime, "recovery-evidence.json"), { schema_id: "dd-flow/recovery-runtime-evidence@1", project_id: input.projectId, run_id: input.runId, registries, native_captures: [...nativeCaptures].map(([source_root, payload]) => ({ source_root, payload })) });
|
|
860
|
+
}
|
|
550
861
|
function treeHash(root, filtered = false) {
|
|
551
862
|
const hash = crypto.createHash("sha256");
|
|
552
863
|
const visit = (dir, relative) => {
|
|
553
864
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
554
865
|
const file = path.join(dir, entry.name);
|
|
555
866
|
const rel = path.join(relative, entry.name);
|
|
556
|
-
if (filtered && !snapshotPayloadAllowed(file))
|
|
867
|
+
if (typeof filtered === "function" ? !filtered(file) : filtered && !snapshotPayloadAllowed(file))
|
|
557
868
|
continue;
|
|
558
869
|
if (entry.isDirectory())
|
|
559
870
|
visit(file, rel);
|
|
@@ -575,7 +886,7 @@ function treeModesHash(root, filtered = false) {
|
|
|
575
886
|
const visit = (directory) => {
|
|
576
887
|
for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
577
888
|
const file = path.join(directory, entry.name);
|
|
578
|
-
if (filtered && !snapshotPayloadAllowed(file))
|
|
889
|
+
if (typeof filtered === "function" ? !filtered(file) : filtered && !snapshotPayloadAllowed(file))
|
|
579
890
|
continue;
|
|
580
891
|
if (entry.isDirectory())
|
|
581
892
|
visit(file);
|