@deksden-com/dd-flow-cli 0.9.0-beta.8 → 0.9.0-beta.80
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 +396 -0
- package/README.md +65 -0
- package/dist/build-info.json +8 -8
- package/dist/cli/command-inputs.js +300 -0
- package/dist/cli/help.js +81 -9
- package/dist/cli/hook-ingress.js +82 -0
- package/dist/cli/input-preparation.js +115 -0
- package/dist/cli/run-cli.js +1342 -375
- package/dist/cli.js +6 -2
- package/dist/harness-runtime/bin/dd-agy.mjs +37 -0
- package/dist/harness-runtime/bin/dd-codex.mjs +25 -0
- package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
- package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
- package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
- package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
- package/dist/harness-runtime/lib/daemon-operations.mjs +215 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +423 -0
- package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.mjs +146 -0
- package/dist/harness-runtime/lib/dd-codex.mjs +562 -0
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
- package/dist/harness-runtime/lib/dd-droid.mjs +471 -0
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +274 -0
- package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +198 -0
- package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +644 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +910 -0
- package/dist/harness-runtime/lib/delegation-instructions.d.mts +10 -0
- package/dist/harness-runtime/lib/delegation-instructions.mjs +130 -0
- package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
- package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
- package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
- package/dist/harness-runtime/lib/managed-daemon.mjs +260 -0
- package/dist/harness-runtime/lib/model-observations.mjs +77 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +1 -0
- package/dist/harness-runtime/lib/native-hook-command.mjs +34 -0
- package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
- package/dist/harness-runtime/lib/operation-context.mjs +5 -0
- package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
- package/dist/harness-runtime/lib/process-json.mjs +70 -0
- package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
- package/dist/harness-runtime/lib/runner-events.mjs +200 -0
- package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
- package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
- package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
- package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
- package/dist/schemas/agent-profile.schema.json +1 -1
- package/dist/schemas/code-review-result.schema.json +2 -2
- package/dist/schemas/code-work-batch.schema.json +4 -3
- package/dist/schemas/code-work-result.schema.json +4 -4
- package/dist/schemas/plan-review-result.schema.json +2 -2
- package/dist/schemas/run-control-receipt.schema.json +99 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
- package/dist/services/canon.js +11 -8
- package/dist/services/cleanup.js +57 -13
- package/dist/services/cli-operation-classifier.js +22 -24
- package/dist/services/code-checks.js +543 -96
- package/dist/services/codex-hook-delivery.js +28 -0
- package/dist/services/config.js +11 -8
- package/dist/services/controller-fanout.js +116 -0
- package/dist/services/dashboard.js +103 -31
- package/dist/services/engines.js +121 -76
- package/dist/services/eval-snapshots.js +750 -73
- package/dist/services/execution-policy.js +170 -0
- package/dist/services/external-work-launch.js +110 -0
- package/dist/services/harness-adapter.js +147 -24
- package/dist/services/harness-config.js +2 -0
- package/dist/services/hooks.js +553 -285
- package/dist/services/lanes.js +61 -53
- package/dist/services/lifecycle-command.js +87 -7
- package/dist/services/lifecycle-invocations.js +828 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-processes.js +283 -27
- package/dist/services/merge-queue.js +179 -104
- package/dist/services/merge-server.js +73 -28
- package/dist/services/migrations.js +14 -9
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +39 -0
- package/dist/services/plan-runtime.js +19 -8
- package/dist/services/plans.js +28 -25
- package/dist/services/projects.js +18 -5
- package/dist/services/prompts.js +23 -16
- package/dist/services/protocols.js +64 -20
- package/dist/services/recovery-observation-budget.js +61 -0
- package/dist/services/recovery-snapshot-database.js +107 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +363 -0
- package/dist/services/run-control.js +876 -0
- package/dist/services/run-controller-adapter.js +222 -0
- package/dist/services/run-controller-capture.js +134 -0
- package/dist/services/run-controller-process.js +189 -0
- package/dist/services/run-controller-recovery.js +222 -0
- package/dist/services/run-controller-state.js +36 -0
- package/dist/services/run-controller.js +779 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +138 -0
- package/dist/services/run-observations.js +112 -0
- package/dist/services/run-recovery-runtime.js +69 -0
- package/dist/services/run-recovery.js +342 -0
- package/dist/services/runs.js +368 -74
- package/dist/services/runtime-budget.js +434 -0
- package/dist/services/runtime-scope-capture.js +50 -0
- package/dist/services/runtime-scope-control.js +450 -0
- package/dist/services/runtime-scope-resume.js +565 -0
- package/dist/services/runtime-scope-stop.js +99 -0
- package/dist/services/runtime-scope-worker.js +243 -0
- package/dist/services/runtime-service.js +97 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/sessions.js +35 -69
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +44 -18
- package/dist/services/stage-lifecycle.js +99 -102
- package/dist/services/stage-pause.js +65 -23
- package/dist/services/usage.js +37 -93
- package/dist/services/vnext-code-review.js +189 -85
- package/dist/services/vnext-code.js +257 -243
- package/dist/services/vnext-execution-profile.js +5 -3
- package/dist/services/vnext-fanout.js +134 -19
- package/dist/services/vnext-merge.js +285 -102
- package/dist/services/vnext-plan-review.js +148 -94
- package/dist/services/vnext-plan.js +141 -72
- package/dist/services/vnext-protocolize.js +129 -56
- package/dist/services/vnext-specify.js +87 -64
- package/dist/services/work-registry.js +707 -156
- package/dist/services/workspace-bootstrap.js +76 -0
- package/dist/services/worktrees.js +85 -35
- package/dist/shared/errors.js +12 -0
- package/dist/storage/database.js +444 -32
- package/dist/storage/paths.js +17 -4
- package/dist/storage/writer-contract.js +77 -0
- package/dist/storage/writer-migration.js +102 -0
- package/package.json +11 -4
- package/tools/repair-paused-run-status.mjs +59 -0
|
@@ -2,14 +2,21 @@ 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";
|
|
14
|
+
import { captureRecoveryDatabase, readRecoveryResourceEvidence } from "./recovery-snapshot-database.js";
|
|
15
|
+
import { resourceHome } from "./managed-processes.js";
|
|
16
|
+
import { codexHomeSharedEntries } from "./hooks.js";
|
|
17
|
+
import { prepareOutputFile } from "../cli/input-preparation.js";
|
|
11
18
|
/** Capture the only flow boundary which exists before `stage start --bootstrap` creates a RUN. */
|
|
12
|
-
export function
|
|
19
|
+
export function prepareEvalBootstrapSnapshot(context, input) {
|
|
13
20
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
14
21
|
const output = path.resolve(input.output);
|
|
15
22
|
if (fs.existsSync(output))
|
|
@@ -18,8 +25,21 @@ export function createEvalBootstrapSnapshot(context, input) {
|
|
|
18
25
|
throw new AppError("snapshot_output_inside_project", "Bootstrap snapshot output must be outside the project tree", 1, { output });
|
|
19
26
|
if (isInside(physicalPath(context.ddFlowHome), physicalPath(output)))
|
|
20
27
|
throw new AppError("snapshot_output_inside_runtime", "Bootstrap snapshot output must be outside DD_FLOW_HOME", 1, { output });
|
|
28
|
+
prepareOutputFile(output);
|
|
29
|
+
try {
|
|
30
|
+
prepareSnapshotProjectGit(projectRoot);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
if (!(error instanceof AppError) || error.code !== "snapshot_project_git_invalid")
|
|
34
|
+
throw error;
|
|
35
|
+
throw new AppError(error.code, error.message, 2, { ...error.details, phase: "prepare", effect: "no_effect", recoverable: true });
|
|
36
|
+
}
|
|
37
|
+
return { projectRoot, output };
|
|
38
|
+
}
|
|
39
|
+
export function createEvalBootstrapSnapshot(context, input) {
|
|
40
|
+
const { projectRoot, output } = prepareEvalBootstrapSnapshot(context, input);
|
|
21
41
|
fs.mkdirSync(output, { recursive: true });
|
|
22
|
-
fs.cpSync(projectRoot, path.join(output, "project"), { recursive: true, verbatimSymlinks: true, filter:
|
|
42
|
+
fs.cpSync(projectRoot, path.join(output, "project"), { recursive: true, verbatimSymlinks: true, filter: snapshotPayloadAllowed });
|
|
23
43
|
const manifest = {
|
|
24
44
|
schema_id: "dd-eval/bootstrap-snapshot@1",
|
|
25
45
|
stage: "specify",
|
|
@@ -31,31 +51,84 @@ export function createEvalBootstrapSnapshot(context, input) {
|
|
|
31
51
|
return { ok: true, snapshot: output, ...manifest };
|
|
32
52
|
}
|
|
33
53
|
/** Restore a pre-RUN project state; `stage start --bootstrap` creates runtime state afterwards. */
|
|
34
|
-
export function
|
|
54
|
+
export function prepareEvalBootstrapRestore(input) {
|
|
35
55
|
const snapshot = path.resolve(input.snapshot);
|
|
36
56
|
const manifest = readBootstrapManifest(snapshot);
|
|
37
57
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
58
|
+
assertRestoreTargetSeparation(snapshot, [projectRoot]);
|
|
38
59
|
const sourceProject = path.join(snapshot, "project");
|
|
39
|
-
|
|
40
|
-
|
|
60
|
+
verifyGitSnapshotPayload(snapshot, { name: "project", hash: manifest.project_sha256, git: manifest.project_git });
|
|
61
|
+
return { snapshot, manifest, projectRoot, sourceProject };
|
|
62
|
+
}
|
|
63
|
+
export function restoreEvalBootstrapSnapshot(_context, input, prepared = prepareEvalBootstrapRestore(input)) {
|
|
64
|
+
const { snapshot, manifest, projectRoot, sourceProject } = prepared;
|
|
65
|
+
assertRestoreTargetSeparation(snapshot, [projectRoot]);
|
|
41
66
|
clearProjectTree(projectRoot, false);
|
|
42
67
|
restoreProjectGit(snapshot, manifest.project_git, projectRoot);
|
|
43
68
|
replaceProjectTree(projectRoot, sourceProject);
|
|
44
69
|
return { ok: true, schema_id: "dd-eval/bootstrap-restore@1", snapshot, project_root: projectRoot, target_stage: "specify" };
|
|
45
70
|
}
|
|
46
71
|
/**
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* to infer a safe subset of SQLite rows.
|
|
72
|
+
* Eval fixtures require a dedicated home. Sealed recovery exports instead
|
|
73
|
+
* retain only the selected RUN's relational and filesystem evidence.
|
|
50
74
|
*/
|
|
51
75
|
export function createEvalRunSnapshot(context, input) {
|
|
76
|
+
const { output } = prepareEvalRunSnapshotCreation(context, input);
|
|
77
|
+
const temporary = `${output}.partial-${crypto.randomUUID()}`;
|
|
78
|
+
try {
|
|
79
|
+
input.boundary?.verify();
|
|
80
|
+
const sourceVersion = input.boundary ? snapshotSourceVersion(context, input) : null;
|
|
81
|
+
const result = captureEvalRunSnapshot(context, { ...input, output: temporary });
|
|
82
|
+
if (input.boundary && sourceVersion) {
|
|
83
|
+
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 } });
|
|
84
|
+
writeJson(path.join(temporary, "snapshot.json"), Object.fromEntries(Object.entries(result).filter(([key]) => key !== "ok" && key !== "snapshot")));
|
|
85
|
+
}
|
|
86
|
+
if (input.recoveryId) {
|
|
87
|
+
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
88
|
+
const project = requireProjectByRoot(context, projectRoot);
|
|
89
|
+
const run = context.db.get("SELECT workspace_root FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
|
|
90
|
+
verifyRecoverySnapshot(temporary, { runId: input.runId, recoveryId: input.recoveryId, projectRoot, workspaceRoot: run?.workspace_root ?? projectRoot });
|
|
91
|
+
}
|
|
92
|
+
if (fs.existsSync(output))
|
|
93
|
+
throw new AppError("snapshot_exists", "Snapshot output already exists", 1, { output });
|
|
94
|
+
syncSnapshotTree(temporary);
|
|
95
|
+
if (input.boundary) {
|
|
96
|
+
if (sourceVersion !== snapshotSourceVersion(context, input))
|
|
97
|
+
throw new AppError("snapshot_source_changed", "Snapshot source files or Git state changed during boundary capture", 1);
|
|
98
|
+
input.boundary.verify();
|
|
99
|
+
}
|
|
100
|
+
fs.renameSync(temporary, output);
|
|
101
|
+
syncPath(path.dirname(output));
|
|
102
|
+
return { ...result, snapshot: output };
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
fs.rmSync(temporary, { recursive: true, force: true });
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export function prepareEvalRunSnapshotCreation(context, input) {
|
|
110
|
+
if (Number(Boolean(input.candidate)) + Number(Boolean(input.incomplete)) + Number(input.stageEntry !== undefined) + Number(input.recoveryId !== undefined) !== 1)
|
|
111
|
+
throw new AppError("usage", "Use exactly one of candidate, incomplete, recoveryId or stageEntry", 2, { phase: "prepare", effect: "no_effect", recoverable: true });
|
|
52
112
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
53
113
|
// Snapshot is read-only at the control-plane boundary. An invalid workspace
|
|
54
114
|
// root must fail without registering a second project in a dedicated home.
|
|
55
115
|
const project = requireProjectByRoot(context, projectRoot);
|
|
56
116
|
const status = getFlowRunStatus(context, { projectRoot, runId: input.runId });
|
|
57
|
-
|
|
58
|
-
if (input.
|
|
117
|
+
const recovery = typeof input.recoveryId === "string";
|
|
118
|
+
if (!recovery && !input.incomplete && context.db.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'run_controllers'")) {
|
|
119
|
+
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]);
|
|
120
|
+
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))
|
|
121
|
+
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 });
|
|
122
|
+
}
|
|
123
|
+
if (!recovery)
|
|
124
|
+
assertDedicatedHome(context, project.id, input.runId);
|
|
125
|
+
if (recovery) {
|
|
126
|
+
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]);
|
|
127
|
+
if (!guard || guard.status !== "sealed")
|
|
128
|
+
throw new AppError("recovery_invalid_state", "Recovery snapshots require the matching sealed recovery guard", 1, { run_id: input.runId, recovery_id: input.recoveryId ?? null, status: guard?.status ?? null });
|
|
129
|
+
}
|
|
130
|
+
if (input.incomplete || recovery) { /* Recovery captures only after the runner seals all writers. */ }
|
|
131
|
+
else if (input.candidate)
|
|
59
132
|
assertTerminalCandidate(status.index.stage_runs ?? []);
|
|
60
133
|
else if (input.stageEntry)
|
|
61
134
|
assertStageEntry(status.index.stage_runs ?? [], input.stageEntry);
|
|
@@ -65,7 +138,7 @@ export function createEvalRunSnapshot(context, input) {
|
|
|
65
138
|
const activeChildren = input.candidate
|
|
66
139
|
? context.db.get("SELECT COUNT(*) AS count FROM works WHERE project_id = ? AND run_id = ? AND parent_work_id IS NOT NULL AND status IN ('created', 'running', 'paused')", [project.id, input.runId])?.count ?? 0
|
|
67
140
|
: context.db.get("SELECT COUNT(*) AS count FROM works WHERE project_id = ? AND run_id = ? AND parent_work_id IS NOT NULL AND (status IN ('running', 'paused') OR (status = 'created' AND (? IS NULL OR COALESCE(result_schema, '') NOT LIKE ?)))", [project.id, input.runId, allowedCreatedResultSchema, allowedCreatedResultSchema ? `${allowedCreatedResultSchema}@%` : ""])?.count ?? 0;
|
|
68
|
-
if (activeChildren > 0)
|
|
141
|
+
if (!input.incomplete && !recovery && activeChildren > 0)
|
|
69
142
|
throw new AppError("snapshot_not_quiescent", `${input.candidate ? "Candidate" : "Stage-entry"} snapshot requires no active child Work`, 1, { run_id: input.runId, active_children: activeChildren });
|
|
70
143
|
const output = path.resolve(input.output);
|
|
71
144
|
if (fs.existsSync(output))
|
|
@@ -75,36 +148,88 @@ export function createEvalRunSnapshot(context, input) {
|
|
|
75
148
|
const workspaceRoot = String(status.run.workspace_root ?? projectRoot);
|
|
76
149
|
if (isInside(physicalPath(projectRoot), physicalPath(output)) || isInside(physicalPath(workspaceRoot), physicalPath(output)))
|
|
77
150
|
throw new AppError("snapshot_output_inside_project", "Snapshot output must be outside the project and RUN workspace trees", 1, { output });
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
});
|
|
151
|
+
prepareOutputFile(output);
|
|
152
|
+
prepareSnapshotProjectGit(projectRoot);
|
|
153
|
+
prepareSnapshotWorkspace(workspaceRoot, projectRoot);
|
|
154
|
+
return { projectRoot, project, status, recovery, output, workspaceRoot, activeChildren };
|
|
155
|
+
}
|
|
156
|
+
function captureEvalRunSnapshot(context, input) {
|
|
157
|
+
const { projectRoot, project, status, recovery, output, workspaceRoot, activeChildren } = prepareEvalRunSnapshotCreation(context, input);
|
|
158
|
+
fs.mkdirSync(output, { recursive: true, mode: 0o700 });
|
|
159
|
+
const resourceDatabase = path.join(context.ddFlowHome, "runtime.sqlite");
|
|
160
|
+
const databaseFiles = [context.db.path, resourceDatabase].flatMap(file => [file, `${file}-wal`, `${file}-shm`]);
|
|
161
|
+
const codexExclusions = codexHomeSnapshotExclusions(context, project.id, input.runId);
|
|
162
|
+
if (recovery) {
|
|
163
|
+
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)))
|
|
164
|
+
throw new AppError("snapshot_run_scope_invalid", "Recovery requires a RUN artifact root within its runtime", 1);
|
|
165
|
+
for (const source of new Set([status.run.run_root, runtimeRunDir(context.ddFlowHome, project.id, input.runId)])) {
|
|
166
|
+
if (fs.existsSync(source))
|
|
167
|
+
copyRuntimeTree(source, path.join(output, "runtime", path.relative(context.ddFlowHome, source)), true, codexExclusions);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else
|
|
171
|
+
copyRuntimeTree(context.ddFlowHome, path.join(output, "runtime"), false, [...databaseFiles, ...codexExclusions]);
|
|
172
|
+
// VACUUM INTO is a consistent SQLite read snapshot, including committed WAL
|
|
173
|
+
// pages. Copying the live database and its WAL separately is not atomic.
|
|
174
|
+
const databaseCopy = path.join(output, "runtime", path.relative(context.ddFlowHome, context.db.path));
|
|
175
|
+
fs.mkdirSync(path.dirname(databaseCopy), { recursive: true });
|
|
176
|
+
if (recovery) {
|
|
177
|
+
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;
|
|
178
|
+
if (report && !isInside(physicalPath(path.join(output, "runtime")), physicalPath(report)))
|
|
179
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Recovery protocol evidence is outside the captured runtime", 1);
|
|
180
|
+
const protocols = report && fs.existsSync(report) ? JSON.parse(fs.readFileSync(report, "utf8")).semantic?.acceptance : [];
|
|
181
|
+
if (!Array.isArray(protocols) || !protocols.every(id => typeof id === "string" && id.startsWith("PRT-")))
|
|
182
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Recovery export requires the accepted PROTOCOLIZE protocol IDs", 1);
|
|
183
|
+
captureRecoveryDatabase(context.db, databaseCopy, project.id, input.runId, protocols);
|
|
184
|
+
}
|
|
185
|
+
else
|
|
186
|
+
context.db.exec(`VACUUM INTO '${databaseCopy.replace(/'/g, "''")}'`);
|
|
187
|
+
// Resource heartbeats can continue after productive RUN writers are sealed.
|
|
188
|
+
// Keep their committed evidence consistent too; never copy a live WAL pair.
|
|
189
|
+
if (!recovery && fs.existsSync(resourceDatabase)) {
|
|
190
|
+
const resources = new DatabaseSync(resourceDatabase, { readOnly: true });
|
|
191
|
+
try {
|
|
192
|
+
const resourceCopy = path.join(output, "runtime", "runtime.sqlite");
|
|
193
|
+
resources.exec("PRAGMA busy_timeout = 4000");
|
|
194
|
+
resources.exec(`VACUUM INTO '${resourceCopy.replace(/'/g, "''")}'`);
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
resources.close();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
88
200
|
fs.cpSync(projectRoot, path.join(output, "project"), {
|
|
89
201
|
recursive: true,
|
|
90
202
|
verbatimSymlinks: true,
|
|
91
|
-
filter:
|
|
203
|
+
filter: snapshotPayloadAllowed
|
|
92
204
|
});
|
|
93
205
|
const projectGit = snapshotProjectGit(projectRoot, output);
|
|
94
206
|
const workspace = snapshotWorkspace(workspaceRoot, projectRoot, output);
|
|
207
|
+
// Accepted Work results are captured in SQLite. Their file representations
|
|
208
|
+
// are retained evidence, not a second authority or a checkpoint gate.
|
|
209
|
+
if (recovery) {
|
|
210
|
+
const copiedContext = createContext({ ...context.env, DD_FLOW_HOME: path.join(output, "runtime") }, "read_existing");
|
|
211
|
+
try {
|
|
212
|
+
captureRecoveryAuxiliary(context, copiedContext, { projectId: project.id, runId: input.runId, output });
|
|
213
|
+
}
|
|
214
|
+
finally {
|
|
215
|
+
copiedContext.db.close?.();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
95
218
|
const manifest = {
|
|
96
219
|
schema_id: "dd-flow/eval-run-snapshot@5",
|
|
97
220
|
run_id: input.runId,
|
|
98
221
|
project_id: project.id,
|
|
99
222
|
project_root: projectRoot,
|
|
100
223
|
dd_flow_home: context.ddFlowHome,
|
|
101
|
-
purpose: input.candidate ? "candidate" : "stage_entry",
|
|
102
|
-
stage_entry: input.candidate ? null : input.stageEntry,
|
|
224
|
+
purpose: input.incomplete ? "incomplete" : recovery ? "recovery" : input.candidate ? "candidate" : "stage_entry",
|
|
225
|
+
stage_entry: input.incomplete || recovery || input.candidate ? null : input.stageEntry,
|
|
226
|
+
...(input.incomplete ? { consistency: "sqlite_read_snapshot_files_copied_nonatomically", active_child_work_count: activeChildren, restorable: false } : recovery ? { recovery_id: input.recoveryId, consistency: "sealed_writer_barrier_required", active_child_work_count: activeChildren, restorable: "same-runtime-or-explicit-restore" } : {}),
|
|
103
227
|
created_at: context.now(),
|
|
104
228
|
runtime_sha256: treeHash(path.join(output, "runtime")),
|
|
105
229
|
project_sha256: treeHash(path.join(output, "project")),
|
|
106
230
|
project_git: projectGit,
|
|
107
231
|
workspace,
|
|
232
|
+
payload_modes: { project: treeModesHash(path.join(output, "project")), runtime: treeModesHash(path.join(output, "runtime")), ...(workspace.kind === "git_worktree" ? { workspace: treeModesHash(path.join(output, "workspace")) } : {}) },
|
|
108
233
|
source_status: status
|
|
109
234
|
};
|
|
110
235
|
writeJson(path.join(output, "snapshot.json"), manifest);
|
|
@@ -118,23 +243,108 @@ function createdWorkSchemaForStage(stage) {
|
|
|
118
243
|
return "dd-flow/merge-result";
|
|
119
244
|
return null;
|
|
120
245
|
}
|
|
121
|
-
|
|
122
|
-
|
|
246
|
+
/** Validate sealed source data before any target cleanup or copy. */
|
|
247
|
+
export function prepareEvalRunSnapshot(snapshot) {
|
|
123
248
|
const manifest = readManifest(snapshot);
|
|
249
|
+
if (manifest.purpose === "incomplete")
|
|
250
|
+
throw new AppError("snapshot_incomplete_not_restorable", "Incomplete snapshot is forensic evidence, not a stage-entry fixture", 1, { snapshot });
|
|
251
|
+
if (manifest.purpose === "candidate")
|
|
252
|
+
throw new AppError("snapshot_candidate_not_restorable", "A terminal candidate snapshot is evidence, not a stage-entry fixture", 1, { snapshot });
|
|
253
|
+
verifySnapshotPayload(snapshot, manifest);
|
|
254
|
+
if (manifest.purpose === "stage_entry") {
|
|
255
|
+
const db = new DatabaseSync(path.join(snapshot, "runtime", "db.sqlite"), { readOnly: true });
|
|
256
|
+
try {
|
|
257
|
+
assertSnapshotRuntimeDetachAllowed(sql => db.prepare(sql).get());
|
|
258
|
+
const row = db.prepare("SELECT index_json FROM runs WHERE id = ?").get(manifest.run_id);
|
|
259
|
+
if (!row)
|
|
260
|
+
throw new AppError("snapshot_invalid", "Snapshot RUN is not registered", 1);
|
|
261
|
+
const index = JSON.parse(row.index_json);
|
|
262
|
+
if (!Array.isArray(index?.stage_runs))
|
|
263
|
+
throw new AppError("snapshot_invalid", "Snapshot RUN index is invalid", 1);
|
|
264
|
+
assertStageEntry(index.stage_runs, manifest.stage_entry);
|
|
265
|
+
}
|
|
266
|
+
finally {
|
|
267
|
+
db.close();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return manifest;
|
|
271
|
+
}
|
|
272
|
+
export function prepareEvalRunRestore(context, input, preparedManifest) {
|
|
273
|
+
const snapshot = path.resolve(input.snapshot);
|
|
274
|
+
const manifest = preparedManifest ?? prepareEvalRunSnapshot(snapshot);
|
|
275
|
+
if (manifest.purpose === "incomplete")
|
|
276
|
+
throw new AppError("snapshot_incomplete_not_restorable", "Incomplete snapshot is forensic evidence, not a stage-entry fixture", 1, { snapshot });
|
|
277
|
+
const recovery = manifest.purpose === "recovery";
|
|
278
|
+
if (recovery && input.executionRoutingFile !== undefined)
|
|
279
|
+
throw new AppError("snapshot_recovery_policy_frozen", "Recovery must retain its frozen execution policy", 2);
|
|
280
|
+
if (recovery && input.recoveryId !== manifest.recovery_id)
|
|
281
|
+
throw new AppError("snapshot_recovery_requires_explicit_restore", "Recovery snapshots require their explicit --recovery-id", 1, { snapshot });
|
|
282
|
+
if (!recovery && input.recoveryId)
|
|
283
|
+
throw new AppError("snapshot_invalid", "Recovery ID cannot restore a non-recovery snapshot", 1, { snapshot });
|
|
124
284
|
if (manifest.purpose === "candidate")
|
|
125
285
|
throw new AppError("snapshot_candidate_not_restorable", "A terminal candidate snapshot is evidence, not a stage-entry fixture", 1, { snapshot });
|
|
126
|
-
if (!manifest.stage_entry)
|
|
286
|
+
if (!recovery && !manifest.stage_entry)
|
|
127
287
|
throw new AppError("snapshot_invalid", "Stage-entry snapshot has no target stage", 1, { snapshot });
|
|
128
288
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
129
|
-
|
|
130
|
-
if (
|
|
131
|
-
|
|
289
|
+
assertRunRestoreTargets(context, input, snapshot, projectRoot, manifest);
|
|
290
|
+
if (recovery)
|
|
291
|
+
verifyRecoverySnapshot(snapshot, { runId: manifest.run_id, recoveryId: input.recoveryId, projectRoot, workspaceRoot: projectRoot }, false);
|
|
132
292
|
const sourceRuntime = path.join(snapshot, "runtime");
|
|
133
293
|
const sourceProject = path.join(snapshot, "project");
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
if (
|
|
137
|
-
|
|
294
|
+
const routingInput = input.executionRoutingFile !== undefined ? loadExecutionRoutingInput(input.executionRoutingFile) : undefined;
|
|
295
|
+
let selectedProfile;
|
|
296
|
+
if (routingInput) {
|
|
297
|
+
// Resolve selected profiles before replacing the caller's fresh runtime.
|
|
298
|
+
const sourceDb = new DatabaseSync(path.join(sourceRuntime, "db.sqlite"), { readOnly: true });
|
|
299
|
+
try {
|
|
300
|
+
const row = sourceDb.prepare("SELECT index_json FROM runs WHERE id = ?").get(manifest.run_id);
|
|
301
|
+
const index = row ? JSON.parse(row.index_json) : null;
|
|
302
|
+
if (!index?.execution_profile || !["vnext_specify", "vnext_protocolize"].includes(index.flow_kind))
|
|
303
|
+
throw new AppError("execution_profile_not_frozen", "Stage-entry routing requires a vNext execution snapshot", 1);
|
|
304
|
+
assertStageEntry(index.stage_runs, manifest.stage_entry);
|
|
305
|
+
selectedProfile = freezeRunExecutionRouting(context.ddFlowHome, index.execution_profile, routingInput);
|
|
306
|
+
for (const row of sourceDb.prepare("SELECT payload_json FROM works WHERE run_id = ? AND status = 'created'").all(manifest.run_id)) {
|
|
307
|
+
const payload = row.payload_json ? JSON.parse(row.payload_json) : null;
|
|
308
|
+
if (payload?.execution_override !== undefined)
|
|
309
|
+
resolveExecutionPolicy({ ddFlowHome: context.ddFlowHome, policy: routingInput.execution, profiles: selectedProfile.agent_profiles, stage: manifest.stage_entry, work: payload.execution_override });
|
|
310
|
+
}
|
|
311
|
+
selectedProfile.routing_input.artifact = `execution-routing.${routingInput.source_checksum}.input.json`;
|
|
312
|
+
const sourceRun = sourceDb.prepare("SELECT run_root FROM runs WHERE id = ?").get(manifest.run_id);
|
|
313
|
+
if (typeof sourceRun?.run_root !== "string" || !path.isAbsolute(sourceRun.run_root) || !isInside(manifest.dd_flow_home, sourceRun.run_root))
|
|
314
|
+
throw new AppError("snapshot_invalid", "Snapshot RUN root must be inside its runtime home", 1);
|
|
315
|
+
const existingRouting = path.join(sourceRuntime, path.relative(manifest.dd_flow_home, sourceRun.run_root), selectedProfile.routing_input.artifact);
|
|
316
|
+
if (fs.existsSync(existingRouting) && !fs.readFileSync(existingRouting).equals(routingInput.bytes))
|
|
317
|
+
throw new AppError("snapshot_checksum_mismatch", "Existing routing input does not match its checksum", 1);
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
sourceDb.close();
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return { snapshot, manifest, recovery, projectRoot, sourceRuntime, sourceProject, routingInput, selectedProfile };
|
|
324
|
+
}
|
|
325
|
+
function assertRunRestoreTargets(context, input, snapshot, projectRoot, manifest) {
|
|
326
|
+
assertRestoreTargetSeparation(snapshot, [projectRoot, context.ddFlowHome]);
|
|
327
|
+
if (manifest.workspace.kind === "git_worktree") {
|
|
328
|
+
const workspaceRoot = restoredWorkspaceRoot(manifest, projectRoot, context.ddFlowHome);
|
|
329
|
+
assertRestoreTargetSeparation(snapshot, [workspaceRoot]);
|
|
330
|
+
if (isInside(physicalPath(projectRoot), physicalPath(workspaceRoot)) || isInside(physicalPath(workspaceRoot), physicalPath(projectRoot)) || physicalPath(workspaceRoot) === physicalPath(context.ddFlowHome))
|
|
331
|
+
throw new AppError("snapshot_path_conflict", "Feature workspace overlaps a restore target", 2);
|
|
332
|
+
if (fs.existsSync(workspaceRoot))
|
|
333
|
+
throw new AppError("snapshot_workspace_target_exists", "Snapshot feature workspace target already exists", 1, { workspace_root: workspaceRoot });
|
|
334
|
+
}
|
|
335
|
+
if (manifest.purpose === "recovery") {
|
|
336
|
+
if (fs.readdirSync(projectRoot).length || (context.db.get("SELECT COUNT(*) AS count FROM projects")?.count ?? 0) > 0)
|
|
337
|
+
throw new AppError("recovery_restore_target_not_empty", "Recovery restore requires fresh project and runtime targets", 1);
|
|
338
|
+
}
|
|
339
|
+
const existing = (fs.existsSync(context.ddFlowHome) ? fs.readdirSync(context.ddFlowHome) : []).filter((name) => !["db.sqlite", "db.sqlite-wal", "db.sqlite-shm", ...(input.executionRoutingFile !== undefined ? ["agent-profiles"] : [])].includes(name));
|
|
340
|
+
if (existing.length > 0)
|
|
341
|
+
throw new AppError("restore_home_not_empty", "Snapshot restore requires an empty DD_FLOW_HOME", 1, { dd_flow_home: context.ddFlowHome, existing });
|
|
342
|
+
if (context.db.get("SELECT 1 FROM projects LIMIT 1") || context.db.get("SELECT 1 FROM runs LIMIT 1"))
|
|
343
|
+
throw new AppError("restore_home_not_empty", "Snapshot restore cannot replace an initialized runtime", 1);
|
|
344
|
+
}
|
|
345
|
+
export function restoreEvalRunSnapshot(context, input, prepared = prepareEvalRunRestore(context, input)) {
|
|
346
|
+
const { snapshot, manifest, recovery, projectRoot, sourceRuntime, sourceProject, routingInput, selectedProfile } = prepared;
|
|
347
|
+
assertRunRestoreTargets(context, input, snapshot, projectRoot, manifest);
|
|
138
348
|
clearProjectTree(projectRoot, false);
|
|
139
349
|
restoreProjectGit(snapshot, manifest.project_git, projectRoot);
|
|
140
350
|
replaceProjectTree(projectRoot, sourceProject);
|
|
@@ -146,14 +356,38 @@ export function restoreEvalRunSnapshot(context, input) {
|
|
|
146
356
|
// A fresh process owns all subsequent normal commands.
|
|
147
357
|
const restored = createContext({ ...context.env, DD_FLOW_HOME: context.ddFlowHome });
|
|
148
358
|
try {
|
|
149
|
-
|
|
359
|
+
const runtimeLineage = recovery ? null : detachSnapshotRuntimeOwners(restored, snapshot, manifest);
|
|
360
|
+
rebaseRuntime(restored, manifest.project_root, projectRoot, sourceWorkspaceRoot(manifest), workspaceRoot, manifest.dd_flow_home, context.ddFlowHome, recovery);
|
|
150
361
|
registerProject(restored, { root: projectRoot });
|
|
151
362
|
requireProjectByRoot(restored, projectRoot);
|
|
363
|
+
if (selectedProfile && routingInput && runtimeLineage) {
|
|
364
|
+
const run = restored.db.get("SELECT run_root FROM runs WHERE id = ?", [manifest.run_id]);
|
|
365
|
+
const artifact = path.join(run.run_root, selectedProfile.routing_input.artifact);
|
|
366
|
+
if (fs.existsSync(artifact)) {
|
|
367
|
+
if (!fs.readFileSync(artifact).equals(routingInput.bytes))
|
|
368
|
+
throw new AppError("snapshot_checksum_mismatch", "Existing routing input does not match its checksum", 1);
|
|
369
|
+
}
|
|
370
|
+
else
|
|
371
|
+
fs.writeFileSync(artifact, routingInput.bytes, { flag: "wx", mode: 0o600 });
|
|
372
|
+
importFlowRunExecutionProfile(restored, { projectRoot, runId: manifest.run_id, stage: manifest.stage_entry, lineageFile: runtimeLineage, profile: selectedProfile });
|
|
373
|
+
}
|
|
152
374
|
const status = getFlowRunStatus(restored, { projectRoot, runId: manifest.run_id });
|
|
153
|
-
|
|
375
|
+
if (!recovery)
|
|
376
|
+
assertStageEntry(status.index.stage_runs ?? [], manifest.stage_entry);
|
|
377
|
+
else
|
|
378
|
+
restored.db.run("UPDATE run_recovery_guards SET capture_path = ? WHERE recovery_id = ? AND status = 'sealed'", [snapshot, input.recoveryId]);
|
|
154
379
|
if (!status.run.run_root)
|
|
155
380
|
throw new AppError("runtime_missing", "Restored RUN has no artifact root", 1, { run_id: manifest.run_id });
|
|
156
381
|
const runHome = status.run.run_root;
|
|
382
|
+
const relocation = recovery ? {
|
|
383
|
+
schema_id: "dd-flow/recovery-relocation@1", physical_runtime_id: crypto.randomUUID(), recovery_id: input.recoveryId, run_id: manifest.run_id,
|
|
384
|
+
path_mapping: [{ from: manifest.dd_flow_home, to: context.ddFlowHome }, { from: sourceWorkspaceRoot(manifest), to: workspaceRoot }, { from: manifest.project_root, to: projectRoot }]
|
|
385
|
+
} : null;
|
|
386
|
+
const relocationFile = relocation ? path.join(context.ddFlowHome, "recovery-imports", `${relocation.physical_runtime_id}.json`) : null;
|
|
387
|
+
if (relocationFile) {
|
|
388
|
+
fs.mkdirSync(path.dirname(relocationFile), { recursive: true });
|
|
389
|
+
writeJson(relocationFile, relocation);
|
|
390
|
+
}
|
|
157
391
|
return {
|
|
158
392
|
ok: true,
|
|
159
393
|
schema_id: "dd-flow/eval-run-restore@1",
|
|
@@ -164,7 +398,9 @@ export function restoreEvalRunSnapshot(context, input) {
|
|
|
164
398
|
dd_flow_home: context.ddFlowHome,
|
|
165
399
|
run_home: runHome,
|
|
166
400
|
target_stage: manifest.stage_entry,
|
|
167
|
-
|
|
401
|
+
...(runtimeLineage ? { runtime_lineage_file: runtimeLineage } : {}),
|
|
402
|
+
...(recovery ? { recovery_id: input.recoveryId, native_session_portability: "requires_adapter_verification", relocation_file: relocationFile, relocation } : {}),
|
|
403
|
+
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`
|
|
168
404
|
};
|
|
169
405
|
}
|
|
170
406
|
finally {
|
|
@@ -182,6 +418,7 @@ export function prepareVnextSpecifyRun(context, input) {
|
|
|
182
418
|
subjectType: "discussion",
|
|
183
419
|
subjectId: "SPECIFY",
|
|
184
420
|
slug: input.slug,
|
|
421
|
+
executionRoutingFile: input.executionRoutingFile,
|
|
185
422
|
nextAction: "start_specify"
|
|
186
423
|
});
|
|
187
424
|
return { ok: true, run_id: started.run.id, run_root: started.run.run_root, target_stage: "specify" };
|
|
@@ -196,18 +433,75 @@ function assertDedicatedHome(context, projectId, runId) {
|
|
|
196
433
|
function assertStageEntry(stages, target) {
|
|
197
434
|
if (stages.some((entry) => entry.stage === target))
|
|
198
435
|
throw new AppError("snapshot_target_started", "Stage-entry snapshot requires its target stage to be unstarted", 1, { target });
|
|
199
|
-
const unfinished = stages.filter((entry) => entry.status
|
|
436
|
+
const unfinished = stages.filter((entry) => !["done", "skipped"].includes(entry.status ?? ""));
|
|
200
437
|
if (unfinished.length > 0)
|
|
201
438
|
throw new AppError("snapshot_predecessor_incomplete", "Stage-entry snapshot requires completed predecessor stages", 1, { target, unfinished });
|
|
202
439
|
}
|
|
203
440
|
function assertTerminalCandidate(stages) {
|
|
204
|
-
const unfinished = stages.filter((entry) => entry.status
|
|
441
|
+
const unfinished = stages.filter((entry) => !["done", "skipped"].includes(entry.status ?? ""));
|
|
205
442
|
if (unfinished.length > 0)
|
|
206
443
|
throw new AppError("snapshot_candidate_incomplete", "Candidate snapshot requires every started stage to be done", 1, { unfinished });
|
|
207
444
|
}
|
|
208
|
-
|
|
445
|
+
/** A stage-entry import is a new experiment, not a lease takeover or recovery.
|
|
446
|
+
* Keep source authority as evidence, never as executable target inventory. */
|
|
447
|
+
function assertSnapshotRuntimeDetachAllowed(get) {
|
|
448
|
+
if (get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'run_recovery_guards'") && get("SELECT 1 FROM run_recovery_guards WHERE status IN ('draining','sealed','resuming') LIMIT 1"))
|
|
449
|
+
throw new AppError("snapshot_control_requires_recovery", "A fenced RUN requires explicit recovery, not a stage-entry fork", 1);
|
|
450
|
+
if (get("SELECT 1 FROM merge_requests WHERE status IN ('dispatching','active','waiting_user','action_required','recovery_required') LIMIT 1"))
|
|
451
|
+
throw new AppError("snapshot_execution_active", "A stage-entry fork cannot discard an unresolved MERGE execution", 1);
|
|
452
|
+
}
|
|
453
|
+
function detachSnapshotRuntimeOwners(context, snapshot, manifest) {
|
|
454
|
+
const hasTable = (table) => Boolean(context.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?", [table]));
|
|
455
|
+
assertSnapshotRuntimeDetachAllowed(sql => context.db.get(sql));
|
|
456
|
+
const detachedTables = ["lifecycle_invocations", "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);
|
|
457
|
+
const runTables = Object.fromEntries([...detachedTables, "runs", "merge_requests", "sessions", "work_sessions"].map(table => [table, context.db.all(`SELECT * FROM ${table}`)]));
|
|
458
|
+
const resourceFile = path.join(context.ddFlowHome, "runtime.sqlite");
|
|
459
|
+
const resources = fs.existsSync(resourceFile) ? new DatabaseSync(resourceFile) : null;
|
|
460
|
+
try {
|
|
461
|
+
if (resources)
|
|
462
|
+
registerStoreWriter(resources);
|
|
463
|
+
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()]));
|
|
464
|
+
const directory = path.join(context.ddFlowHome, "snapshot-imports");
|
|
465
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
466
|
+
const file = path.join(directory, `${crypto.randomUUID()}.json`);
|
|
467
|
+
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 });
|
|
468
|
+
syncPath(file);
|
|
469
|
+
syncPath(directory);
|
|
470
|
+
context.db.beginWriteTransaction();
|
|
471
|
+
try {
|
|
472
|
+
context.db.run("UPDATE sessions SET metadata_json = json_set(metadata_json, '$.snapshot_import', json(?))", [JSON.stringify({ lineage_file: file, lineage_sha256: fileHash(file) })]);
|
|
473
|
+
for (const table of detachedTables)
|
|
474
|
+
context.db.exec(`DELETE FROM ${table}`);
|
|
475
|
+
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");
|
|
476
|
+
// Only the copied dedicated registry is touched. Source/external homes
|
|
477
|
+
// are historical references in the archive and are never opened here.
|
|
478
|
+
if (resources) {
|
|
479
|
+
resources.exec("BEGIN IMMEDIATE");
|
|
480
|
+
try {
|
|
481
|
+
for (const table of Object.keys(resourceTables))
|
|
482
|
+
resources.exec(`DELETE FROM ${table}`);
|
|
483
|
+
resources.exec("COMMIT");
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
resources.exec("ROLLBACK");
|
|
487
|
+
throw error;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
context.db.exec("COMMIT");
|
|
491
|
+
}
|
|
492
|
+
catch (error) {
|
|
493
|
+
context.db.exec("ROLLBACK");
|
|
494
|
+
throw error;
|
|
495
|
+
}
|
|
496
|
+
return file;
|
|
497
|
+
}
|
|
498
|
+
finally {
|
|
499
|
+
resources?.close();
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome, recovery = false) {
|
|
209
503
|
context.db.exec("PRAGMA foreign_keys = OFF");
|
|
210
|
-
context.db.
|
|
504
|
+
context.db.beginWriteTransaction();
|
|
211
505
|
try {
|
|
212
506
|
context.db.run("UPDATE projects SET root = ?", [newRoot]);
|
|
213
507
|
context.db.run("UPDATE runs SET project_root = ?, workspace_root = ?", [newRoot, newWorkspace]);
|
|
@@ -216,7 +510,12 @@ function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, ol
|
|
|
216
510
|
context.db.run("UPDATE protocols SET project_root = ?", [newRoot]);
|
|
217
511
|
for (const column of ["state_path", "plan_path"])
|
|
218
512
|
rewriteDatabaseColumn(context, "protocols", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
219
|
-
|
|
513
|
+
for (const column of ["source_workspace", "target_workspace"])
|
|
514
|
+
rewriteDatabaseColumn(context, "merge_requests", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
515
|
+
if (recovery)
|
|
516
|
+
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]);
|
|
517
|
+
else
|
|
518
|
+
context.db.run("UPDATE sessions SET project_root = ?, status = 'stopped', stop_reason = 'snapshot_restored', stopped_at = ?", [newRoot, context.now()]);
|
|
220
519
|
for (const column of ["workspace_path", "cwd", "transcript_path"])
|
|
221
520
|
rewriteDatabaseColumn(context, "sessions", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
222
521
|
for (const column of ["prompt_path", "result_path"])
|
|
@@ -226,7 +525,10 @@ function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, ol
|
|
|
226
525
|
rewriteDatabaseColumn(context, "usage", "source_locator", oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
227
526
|
for (const column of ["worktree_path", "worktrunk_metadata_json", "last_command_result_json"])
|
|
228
527
|
rewriteDatabaseColumn(context, "worktree_records", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
229
|
-
|
|
528
|
+
// Recovery imports remain sealed. Their old Work sessions are historical
|
|
529
|
+
// bindings, not completed work; explicit recovery closes them interrupted.
|
|
530
|
+
if (!recovery)
|
|
531
|
+
context.db.run("UPDATE work_sessions SET status = CASE WHEN status = 'running' THEN 'completed' ELSE status END, completed_at = COALESCE(completed_at, ?), updated_at = ?", [context.now(), context.now()]);
|
|
230
532
|
context.db.run("DELETE FROM codex_session_bindings");
|
|
231
533
|
context.db.run("COMMIT");
|
|
232
534
|
}
|
|
@@ -237,24 +539,21 @@ function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, ol
|
|
|
237
539
|
finally {
|
|
238
540
|
context.db.exec("PRAGMA foreign_keys = ON");
|
|
239
541
|
}
|
|
240
|
-
|
|
542
|
+
// Only operational database paths move. Imported packets, results and
|
|
543
|
+
// journals retain their historical bytes, including interrupted JSONL tails.
|
|
544
|
+
// The frozen workspace route is an operational receipt consumed by later
|
|
545
|
+
// stages, so its relocated path is the sole structured-file exception.
|
|
546
|
+
rewriteOperationalRouteReceipts(context.ddFlowHome, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
|
|
241
547
|
}
|
|
242
|
-
function
|
|
243
|
-
const visit = (
|
|
244
|
-
for (const entry of fs.readdirSync(
|
|
245
|
-
const file = path.join(
|
|
246
|
-
|
|
247
|
-
// They are project/tool bytes, not flow records; parsing every *.json
|
|
248
|
-
// there breaks on valid JSON-with-comments such as tsconfig files.
|
|
249
|
-
if (entry.isDirectory() && ![".git", "checkouts", "engines", "node_modules", "tools"].includes(entry.name))
|
|
548
|
+
function rewriteOperationalRouteReceipts(root, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) {
|
|
549
|
+
const visit = (directory) => {
|
|
550
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
551
|
+
const file = path.join(directory, entry.name);
|
|
552
|
+
if (entry.isDirectory())
|
|
250
553
|
visit(file);
|
|
251
|
-
else if (entry.isFile() && entry.name
|
|
554
|
+
else if (entry.isFile() && entry.name === "workspace-route.json") {
|
|
252
555
|
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
253
|
-
|
|
254
|
-
}
|
|
255
|
-
else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
256
|
-
const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((line) => JSON.stringify(rebaseStructuredValue(JSON.parse(line), oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome)));
|
|
257
|
-
fs.writeFileSync(file, `${lines.join("\n")}\n`);
|
|
556
|
+
fs.writeFileSync(file, `${JSON.stringify(rebaseStructuredValue(value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome), null, 2)}\n`);
|
|
258
557
|
}
|
|
259
558
|
}
|
|
260
559
|
};
|
|
@@ -274,20 +573,27 @@ function rebaseStructuredValue(value, oldRoot, newRoot, oldWorkspace, newWorkspa
|
|
|
274
573
|
function rebasePathString(value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) { for (const [oldPrefix, newPrefix] of [[oldHome, newHome], [oldWorkspace, newWorkspace], [oldRoot, newRoot]])
|
|
275
574
|
if (value === oldPrefix || value.startsWith(`${oldPrefix}${path.sep}`))
|
|
276
575
|
return `${newPrefix}${value.slice(oldPrefix.length)}`; return value; }
|
|
277
|
-
function
|
|
576
|
+
function prepareSnapshotWorkspace(workspaceRoot, projectRoot) {
|
|
278
577
|
if (samePath(workspaceRoot, projectRoot))
|
|
279
|
-
return
|
|
578
|
+
return null;
|
|
280
579
|
const branch = git(workspaceRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
281
580
|
if (!branch)
|
|
282
581
|
throw new AppError("snapshot_workspace_invalid", "Feature workspace must be on a named Git branch", 1, { workspace_root: workspaceRoot });
|
|
283
582
|
const baseRef = git(workspaceRoot, ["rev-parse", "HEAD"]);
|
|
284
583
|
if (!baseRef)
|
|
285
584
|
throw new AppError("snapshot_workspace_invalid", "Feature workspace has no readable HEAD", 1, { workspace_root: workspaceRoot });
|
|
585
|
+
return { branch, baseRef };
|
|
586
|
+
}
|
|
587
|
+
function snapshotWorkspace(workspaceRoot, projectRoot, output) {
|
|
588
|
+
const prepared = prepareSnapshotWorkspace(workspaceRoot, projectRoot);
|
|
589
|
+
if (!prepared)
|
|
590
|
+
return { kind: "project" };
|
|
591
|
+
const { branch, baseRef } = prepared;
|
|
286
592
|
const workspace = path.join(output, "workspace");
|
|
287
593
|
const bundle = path.join(output, "workspace.bundle");
|
|
288
|
-
fs.cpSync(workspaceRoot, workspace, { recursive: true, verbatimSymlinks: true, filter:
|
|
594
|
+
fs.cpSync(workspaceRoot, workspace, { recursive: true, verbatimSymlinks: true, filter: snapshotPayloadAllowed });
|
|
289
595
|
runGit(projectRoot, ["bundle", "create", bundle, branch]);
|
|
290
|
-
return { kind: "git_worktree", source_root: workspaceRoot, branch, base_ref: baseRef, sha256: treeHash(workspace), bundle_sha256: fileHash(bundle) };
|
|
596
|
+
return { kind: "git_worktree", source_root: workspaceRoot, branch, base_ref: baseRef, sha256: treeHash(workspace), bundle_sha256: fileHash(bundle), ...snapshotIndex(workspaceRoot, output, "workspace") };
|
|
291
597
|
}
|
|
292
598
|
function restoreWorkspace(snapshot, manifest, projectRoot, ddFlowHome) {
|
|
293
599
|
if (manifest.workspace.kind === "project")
|
|
@@ -298,11 +604,7 @@ function restoreWorkspace(snapshot, manifest, projectRoot, ddFlowHome) {
|
|
|
298
604
|
throw new AppError("snapshot_checksum_mismatch", "Snapshot workspace checksum does not match manifest", 1, { snapshot });
|
|
299
605
|
if (!fs.existsSync(bundle) || fileHash(bundle) !== manifest.workspace.bundle_sha256)
|
|
300
606
|
throw new AppError("snapshot_checksum_mismatch", "Snapshot workspace Git bundle does not match manifest", 1, { snapshot });
|
|
301
|
-
const
|
|
302
|
-
const sourceRoot = physicalPath(manifest.workspace.source_root);
|
|
303
|
-
const workspaceRoot = isInside(managedRoot, sourceRoot)
|
|
304
|
-
? path.join(ddFlowHome, path.relative(managedRoot, sourceRoot))
|
|
305
|
-
: path.join(path.dirname(projectRoot), "workspace");
|
|
607
|
+
const workspaceRoot = restoredWorkspaceRoot(manifest, projectRoot, ddFlowHome);
|
|
306
608
|
if (fs.existsSync(workspaceRoot))
|
|
307
609
|
throw new AppError("snapshot_workspace_target_exists", "Snapshot feature workspace target already exists", 1, { workspace_root: workspaceRoot });
|
|
308
610
|
runGit(projectRoot, ["fetch", bundle, `+refs/heads/${manifest.workspace.branch}:refs/heads/${manifest.workspace.branch}`]);
|
|
@@ -310,19 +612,38 @@ function restoreWorkspace(snapshot, manifest, projectRoot, ddFlowHome) {
|
|
|
310
612
|
throw new AppError("snapshot_workspace_restore_failed", "Snapshot Git bundle did not restore the frozen feature base", 1, { branch: manifest.workspace.branch, expected_base: manifest.workspace.base_ref });
|
|
311
613
|
runGit(projectRoot, ["worktree", "add", workspaceRoot, manifest.workspace.branch]);
|
|
312
614
|
replaceProjectTree(workspaceRoot, source);
|
|
615
|
+
restoreIndex(snapshot, "workspace", manifest.workspace, workspaceRoot);
|
|
313
616
|
return fs.realpathSync(workspaceRoot);
|
|
314
617
|
}
|
|
618
|
+
function restoredWorkspaceRoot(manifest, projectRoot, ddFlowHome) {
|
|
619
|
+
if (manifest.workspace.kind === "project")
|
|
620
|
+
return projectRoot;
|
|
621
|
+
const managedRoot = physicalPath(manifest.dd_flow_home), sourceRoot = physicalPath(manifest.workspace.source_root);
|
|
622
|
+
return isInside(managedRoot, sourceRoot) ? path.join(ddFlowHome, path.relative(managedRoot, sourceRoot)) : path.join(path.dirname(projectRoot), "workspace");
|
|
623
|
+
}
|
|
624
|
+
function assertRestoreTargetSeparation(snapshot, targets) {
|
|
625
|
+
const roots = [snapshot, ...targets].map(physicalPath);
|
|
626
|
+
for (let i = 0; i < roots.length; i++)
|
|
627
|
+
for (let j = i + 1; j < roots.length; j++) {
|
|
628
|
+
if (isInside(roots[i], roots[j]) || isInside(roots[j], roots[i]))
|
|
629
|
+
throw new AppError("snapshot_path_conflict", "Snapshot source and restore targets must not overlap", 2, { source: roots[i], target: roots[j] });
|
|
630
|
+
}
|
|
631
|
+
}
|
|
315
632
|
function sourceWorkspaceRoot(manifest) {
|
|
316
633
|
return manifest.workspace.kind === "project" ? manifest.project_root : manifest.workspace.source_root;
|
|
317
634
|
}
|
|
318
|
-
function
|
|
635
|
+
function prepareSnapshotProjectGit(projectRoot) {
|
|
319
636
|
const branch = git(projectRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
320
637
|
const head = git(projectRoot, ["rev-parse", "HEAD"]);
|
|
321
638
|
if (!branch || !head)
|
|
322
639
|
throw new AppError("snapshot_project_git_invalid", "Snapshot requires a project on a named Git branch with a readable HEAD", 1, { project_root: projectRoot });
|
|
640
|
+
return { branch, head };
|
|
641
|
+
}
|
|
642
|
+
function snapshotProjectGit(projectRoot, output) {
|
|
643
|
+
const { branch, head } = prepareSnapshotProjectGit(projectRoot);
|
|
323
644
|
const bundle = path.join(output, "project.bundle");
|
|
324
645
|
runGit(projectRoot, ["bundle", "create", bundle, "--all"]);
|
|
325
|
-
return { branch, head, bundle_sha256: fileHash(bundle) };
|
|
646
|
+
return { branch, head, bundle_sha256: fileHash(bundle), ...snapshotIndex(projectRoot, output, "project") };
|
|
326
647
|
}
|
|
327
648
|
function restoreProjectGit(snapshot, source, projectRoot) {
|
|
328
649
|
const bundle = path.join(snapshot, "project.bundle");
|
|
@@ -332,6 +653,130 @@ function restoreProjectGit(snapshot, source, projectRoot) {
|
|
|
332
653
|
runGit(projectRoot, ["init", "-b", source.branch]);
|
|
333
654
|
runGit(projectRoot, ["fetch", bundle, `+refs/heads/${source.branch}:refs/remotes/snapshot/${source.branch}`]);
|
|
334
655
|
runGit(projectRoot, ["checkout", "-B", source.branch, source.head]);
|
|
656
|
+
restoreIndex(snapshot, "project", source, projectRoot);
|
|
657
|
+
}
|
|
658
|
+
const mergeStateFiles = ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "ORIG_HEAD", "AUTO_MERGE"];
|
|
659
|
+
function indexEntries(root) {
|
|
660
|
+
const entries = Buffer.from(gitBytes(root, ["ls-files", "--stage", "-z"])
|
|
661
|
+
.toString("utf8").split("\0").filter(entry => entry && snapshotEnvironmentAllowed(entry.slice(entry.indexOf("\t") + 1)))
|
|
662
|
+
.map(entry => `${entry}\0`).join(""));
|
|
663
|
+
const merge = {};
|
|
664
|
+
for (const name of mergeStateFiles) {
|
|
665
|
+
const file = git(root, ["rev-parse", "--git-path", name]);
|
|
666
|
+
if (!file)
|
|
667
|
+
throw new AppError("snapshot_index_invalid", "Could not locate Git merge state", 1);
|
|
668
|
+
const resolved = path.resolve(root, file);
|
|
669
|
+
if (fs.existsSync(resolved))
|
|
670
|
+
merge[name] = fs.readFileSync(resolved).toString("base64");
|
|
671
|
+
}
|
|
672
|
+
return Buffer.from(JSON.stringify({ entries: entries.toString("base64"), merge }));
|
|
673
|
+
}
|
|
674
|
+
function snapshotIndex(root, output, name) {
|
|
675
|
+
const bytes = indexEntries(root);
|
|
676
|
+
const value = JSON.parse(bytes.toString());
|
|
677
|
+
const objects = new Set();
|
|
678
|
+
for (const entry of Buffer.from(value.entries, "base64").toString("utf8").split("\0").filter(Boolean)) {
|
|
679
|
+
const match = /^\d{6} ([a-f0-9]{40,64}) [0-3]\t/.exec(entry);
|
|
680
|
+
if (!match)
|
|
681
|
+
throw new AppError("snapshot_index_invalid", "Malformed Git index entry", 1);
|
|
682
|
+
// Gitlinks belong to another repository and are preserved as index IDs.
|
|
683
|
+
if (!entry.startsWith("160000 "))
|
|
684
|
+
objects.add(match[1]);
|
|
685
|
+
}
|
|
686
|
+
for (const name of ["MERGE_HEAD", "ORIG_HEAD", "AUTO_MERGE"]) {
|
|
687
|
+
if (value.merge[name])
|
|
688
|
+
for (const oid of Buffer.from(value.merge[name], "base64").toString().trim().split("\n")) {
|
|
689
|
+
if (!/^[a-f0-9]{40,64}$/.test(oid))
|
|
690
|
+
throw new AppError("snapshot_index_invalid", "Malformed Git merge reference", 1);
|
|
691
|
+
objects.add(oid);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const payload = path.join(output, `${name}.index.patch`);
|
|
695
|
+
const pack = path.join(output, `${name}.index.pack`);
|
|
696
|
+
fs.writeFileSync(payload, bytes);
|
|
697
|
+
fs.writeFileSync(pack, gitBytes(root, ["pack-objects", "--stdout", "--revs"], Buffer.from([...objects].sort().join("\n") + "\n")));
|
|
698
|
+
return { index_format: "entries@1", index_sha256: fileHash(payload), index_objects_sha256: fileHash(pack) };
|
|
699
|
+
}
|
|
700
|
+
function gitBytes(root, args, input) {
|
|
701
|
+
const result = spawnSync("git", ["-C", root, ...args], { input, maxBuffer: 64 * 1024 * 1024 });
|
|
702
|
+
if (result.status !== 0)
|
|
703
|
+
throw new AppError("snapshot_index_invalid", "Could not preserve Git index objects", 1, { args, stderr: result.stderr?.toString().trim() });
|
|
704
|
+
return result.stdout;
|
|
705
|
+
}
|
|
706
|
+
function indexPatch(root) {
|
|
707
|
+
const result = spawnSync("git", ["-C", root, "diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "HEAD", "--", ".", ":(exclude)**/.env", ":(exclude)**/.env.*"], { maxBuffer: 64 * 1024 * 1024 });
|
|
708
|
+
if (result.status !== 0)
|
|
709
|
+
throw new AppError("snapshot_index_invalid", "Could not capture Git index", 1);
|
|
710
|
+
return result.stdout;
|
|
711
|
+
}
|
|
712
|
+
function restoreIndex(snapshot, name, metadata, root) {
|
|
713
|
+
if (!metadata.index_sha256)
|
|
714
|
+
return;
|
|
715
|
+
const file = path.join(snapshot, `${name}.index.patch`);
|
|
716
|
+
if (fileHash(file) !== metadata.index_sha256)
|
|
717
|
+
throw new AppError("snapshot_checksum_mismatch", "Snapshot Git index checksum does not match", 1);
|
|
718
|
+
if (metadata.index_format === "entries@1") {
|
|
719
|
+
const pack = path.join(snapshot, `${name}.index.pack`);
|
|
720
|
+
if (!metadata.index_objects_sha256 || fileHash(pack) !== metadata.index_objects_sha256)
|
|
721
|
+
throw new AppError("snapshot_checksum_mismatch", "Snapshot Git index object checksum does not match", 1);
|
|
722
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
723
|
+
gitBytes(root, ["unpack-objects"], fs.readFileSync(pack));
|
|
724
|
+
runGit(root, ["read-tree", "--empty"]);
|
|
725
|
+
gitBytes(root, ["update-index", "-z", "--index-info"], Buffer.from(value.entries, "base64"));
|
|
726
|
+
for (const name of mergeStateFiles) {
|
|
727
|
+
const target = git(root, ["rev-parse", "--git-path", name]);
|
|
728
|
+
if (!target)
|
|
729
|
+
throw new AppError("snapshot_index_invalid", "Could not locate restored Git merge state", 1);
|
|
730
|
+
if (value.merge[name] !== undefined)
|
|
731
|
+
fs.writeFileSync(path.resolve(root, target), Buffer.from(value.merge[name], "base64"));
|
|
732
|
+
else
|
|
733
|
+
fs.rmSync(path.resolve(root, target), { force: true });
|
|
734
|
+
}
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
if (fs.statSync(file).size)
|
|
738
|
+
runGit(root, ["apply", "--cached", "--binary", file]);
|
|
739
|
+
}
|
|
740
|
+
export function verifyRecoverySnapshot(snapshot, input, checkWorkingState = true) {
|
|
741
|
+
const manifest = readManifest(snapshot);
|
|
742
|
+
if (manifest.purpose !== "recovery" || manifest.recovery_id !== input.recoveryId || manifest.run_id !== input.runId)
|
|
743
|
+
throw new AppError("recovery_capture_invalid", "Snapshot does not identify this recovery", 1);
|
|
744
|
+
const entries = [
|
|
745
|
+
{ name: "project", root: input.projectRoot, hash: manifest.project_sha256, git: manifest.project_git, head: manifest.project_git.head },
|
|
746
|
+
...(manifest.workspace.kind === "git_worktree" ? [{ name: "workspace", root: input.workspaceRoot, hash: manifest.workspace.sha256, git: manifest.workspace, head: manifest.workspace.base_ref }] : [])
|
|
747
|
+
];
|
|
748
|
+
verifySnapshotPayload(snapshot, manifest);
|
|
749
|
+
for (const entry of entries) {
|
|
750
|
+
const expectedModes = manifest.payload_modes?.[entry.name];
|
|
751
|
+
if (checkWorkingState && expectedModes && treeModesHash(entry.root, true) !== expectedModes)
|
|
752
|
+
throw new AppError("recovery_workspace_drift", "Executable file modes changed after recovery capture", 1, { payload: entry.name });
|
|
753
|
+
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)))
|
|
754
|
+
throw new AppError("recovery_workspace_drift", "Working files or Git state changed after recovery capture", 1, { payload: entry.name });
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
/** Reuse an already published boundary only after checking its identity and
|
|
758
|
+
* every payload, including its Git index objects. Never overwrite evidence. */
|
|
759
|
+
export function verifyControllerBoundarySnapshot(snapshot, input) {
|
|
760
|
+
const manifest = readManifest(snapshot), boundary = manifest.boundary_capture;
|
|
761
|
+
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)
|
|
762
|
+
throw new AppError("controller_boundary_snapshot_invalid", "Published snapshot does not prove this controller boundary", 1, { snapshot });
|
|
763
|
+
verifySnapshotPayload(snapshot, manifest);
|
|
764
|
+
const file = path.join(snapshot, "snapshot.json");
|
|
765
|
+
if (input.manifestSha256 !== undefined && fileHash(file) !== input.manifestSha256)
|
|
766
|
+
throw new AppError("snapshot_checksum_mismatch", "Boundary manifest no longer matches its retained publication receipt", 1, { snapshot });
|
|
767
|
+
return { snapshot, manifest: file, manifest_sha256: fileHash(file), purpose: manifest.purpose, stage_entry: manifest.stage_entry };
|
|
768
|
+
}
|
|
769
|
+
function verifySnapshotPayload(snapshot, manifest) {
|
|
770
|
+
if (treeHash(path.join(snapshot, "runtime")) !== manifest.runtime_sha256)
|
|
771
|
+
throw new AppError("snapshot_checksum_mismatch", "Snapshot runtime checksum does not match", 1);
|
|
772
|
+
verifySnapshotModes(snapshot, manifest);
|
|
773
|
+
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 }] : [])];
|
|
774
|
+
for (const payload of payloads)
|
|
775
|
+
verifyGitSnapshotPayload(snapshot, payload);
|
|
776
|
+
}
|
|
777
|
+
function verifyGitSnapshotPayload(snapshot, payload) {
|
|
778
|
+
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))
|
|
779
|
+
throw new AppError("snapshot_checksum_mismatch", "Snapshot payload or Git index checksum does not match", 1, { payload: payload.name });
|
|
335
780
|
}
|
|
336
781
|
function git(root, args) {
|
|
337
782
|
const result = spawnSync("git", ["-C", root, ...args], { encoding: "utf8" });
|
|
@@ -343,12 +788,199 @@ function runGit(root, args) {
|
|
|
343
788
|
throw new AppError("snapshot_workspace_restore_failed", "Could not restore feature worktree", 1, { stderr: result.stderr.trim(), args });
|
|
344
789
|
}
|
|
345
790
|
function samePath(left, right) { return path.resolve(left) === path.resolve(right); }
|
|
346
|
-
function
|
|
791
|
+
function snapshotEnvironmentAllowed(source) {
|
|
792
|
+
const name = path.basename(source);
|
|
793
|
+
// Public configuration template, not a local environment/credential file.
|
|
794
|
+
return name === ".env.example" || (name !== ".env" && !name.startsWith(".env."));
|
|
795
|
+
}
|
|
796
|
+
function snapshotPayloadAllowed(source) {
|
|
797
|
+
const name = path.basename(source);
|
|
798
|
+
return ![".git", "node_modules", ".cache", ".npm", ".pnpm-store"].includes(name)
|
|
799
|
+
&& snapshotEnvironmentAllowed(source);
|
|
800
|
+
}
|
|
801
|
+
function runtimePayloadAllowed(source) {
|
|
802
|
+
return snapshotPayloadAllowed(source) && !["auth.json", "auth.bk", "credentials.json", ".credentials.json", "credentials", ".credentials", "id_rsa", "id_ed25519", "engines", "checkouts"].includes(path.basename(source));
|
|
803
|
+
}
|
|
804
|
+
/** Productive writers are fenced separately. Recheck copied bytes and Git
|
|
805
|
+
* state so an uncoordinated file writer cannot publish a mixed boundary. */
|
|
806
|
+
function snapshotSourceVersion(context, input) {
|
|
807
|
+
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
808
|
+
const project = requireProjectByRoot(context, projectRoot);
|
|
809
|
+
const run = context.db.get("SELECT workspace_root FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
|
|
810
|
+
if (!run)
|
|
811
|
+
throw new AppError("not_found", "Snapshot RUN is not registered", 1);
|
|
812
|
+
const resources = path.join(context.ddFlowHome, "runtime.sqlite");
|
|
813
|
+
// Resource heartbeats are not productive writers. Their semantic identities
|
|
814
|
+
// are rechecked by the owner; each resource DB is copied consistently.
|
|
815
|
+
const runtimeFilter = (file) => runtimePayloadAllowed(file) && !file.endsWith("-shm") && ![resources, `${resources}-wal`, `${resources}-journal`].includes(file);
|
|
816
|
+
const roots = [...new Set([projectRoot, run.workspace_root])];
|
|
817
|
+
return crypto.createHash("sha256").update(JSON.stringify([
|
|
818
|
+
treeHash(context.ddFlowHome, runtimeFilter), treeModesHash(context.ddFlowHome, runtimeFilter),
|
|
819
|
+
...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")])
|
|
820
|
+
])).digest("hex");
|
|
821
|
+
}
|
|
822
|
+
/** Managed Codex homes share host configuration, not owned snapshot payload. */
|
|
823
|
+
function codexHomeSnapshotExclusions(context, projectId, runId) {
|
|
824
|
+
const homes = new Set(context.db.all("SELECT target_home FROM codex_home_profiles WHERE project_id = ?", [projectId]).map(row => row.target_home));
|
|
825
|
+
if (context.db.get("SELECT 1 FROM sqlite_schema WHERE name = 'run_controllers'")) {
|
|
826
|
+
for (const { home } of context.db.all("SELECT json_extract(value, '$.codex_home') AS home FROM run_controllers, json_each(state_json, '$.sessions') WHERE project_id = ? AND run_id = ?", [projectId, runId]))
|
|
827
|
+
if (home)
|
|
828
|
+
homes.add(home);
|
|
829
|
+
}
|
|
830
|
+
const excluded = [];
|
|
831
|
+
for (const home of homes) {
|
|
832
|
+
if (!path.isAbsolute(home) || !fs.existsSync(home) || fs.lstatSync(home).isSymbolicLink())
|
|
833
|
+
continue;
|
|
834
|
+
const marker = path.join(home, ".dd-flow-home.json");
|
|
835
|
+
if (!fs.existsSync(marker) || fs.lstatSync(marker).isSymbolicLink())
|
|
836
|
+
continue;
|
|
837
|
+
const identity = JSON.parse(fs.readFileSync(marker, "utf8"));
|
|
838
|
+
if (identity.managed_by !== "dd-flow-cli" || identity.project_id !== projectId || identity.target_home !== home || !identity.source_home || !path.isAbsolute(identity.source_home))
|
|
839
|
+
continue;
|
|
840
|
+
for (const entry of codexHomeSharedEntries) {
|
|
841
|
+
const file = path.join(home, entry);
|
|
842
|
+
// Skip only the exact links installed by initCodexHome, never arbitrary
|
|
843
|
+
// external links or owned local files with the same convenient name.
|
|
844
|
+
if (fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink() && fs.readlinkSync(file) === path.join(identity.source_home, entry))
|
|
845
|
+
excluded.push(file);
|
|
846
|
+
}
|
|
847
|
+
excluded.push(path.join(home, "tmp"), path.join(home, ".tmp"));
|
|
848
|
+
}
|
|
849
|
+
return excluded;
|
|
850
|
+
}
|
|
851
|
+
/** Copy a dedicated home or scoped recovery tree, preserving SQLite WAL commits. */
|
|
852
|
+
function copyRuntimeTree(source, destination, scoped = true, excluded = []) {
|
|
853
|
+
if (fs.lstatSync(source).isSymbolicLink())
|
|
854
|
+
throw new AppError("snapshot_runtime_symlink_outside_scope", "Recovery artifact roots must not be symbolic links", 1, { path: source });
|
|
855
|
+
const root = physicalPath(source);
|
|
856
|
+
if (isInside(root, physicalPath(destination)))
|
|
857
|
+
throw new AppError("snapshot_output_inside_runtime", "Recovery output must be outside its source artifact tree", 1);
|
|
858
|
+
const databases = [];
|
|
859
|
+
const sqlite = (file) => {
|
|
860
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile())
|
|
861
|
+
return false;
|
|
862
|
+
const descriptor = fs.openSync(file, "r");
|
|
863
|
+
try {
|
|
864
|
+
const header = Buffer.alloc(16);
|
|
865
|
+
return fs.readSync(descriptor, header, 0, 16, 0) === 16 && header.toString() === "SQLite format 3\0";
|
|
866
|
+
}
|
|
867
|
+
finally {
|
|
868
|
+
fs.closeSync(descriptor);
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
872
|
+
fs.cpSync(source, destination, {
|
|
873
|
+
recursive: true, verbatimSymlinks: true,
|
|
874
|
+
filter: file => {
|
|
875
|
+
if (!runtimePayloadAllowed(file) || excluded.includes(file))
|
|
876
|
+
return false;
|
|
877
|
+
const stat = fs.lstatSync(file);
|
|
878
|
+
if (stat.isSymbolicLink()) {
|
|
879
|
+
if (scoped && !isInside(root, physicalPath(file)))
|
|
880
|
+
throw new AppError("snapshot_runtime_symlink_outside_scope", "Recovery artifact link leaves its owned tree", 1, { path: file });
|
|
881
|
+
return true;
|
|
882
|
+
}
|
|
883
|
+
if (!stat.isDirectory() && !stat.isFile())
|
|
884
|
+
return false;
|
|
885
|
+
if (stat.isFile()) {
|
|
886
|
+
if (/-(?:wal|shm|journal)$/.test(file) && sqlite(file.replace(/-(?:wal|shm|journal)$/, "")))
|
|
887
|
+
return false;
|
|
888
|
+
if (sqlite(file)) {
|
|
889
|
+
databases.push(file);
|
|
890
|
+
return false;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
return true;
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
for (const file of databases) {
|
|
897
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
898
|
+
try {
|
|
899
|
+
const target = source === file ? destination : path.join(destination, path.relative(source, file));
|
|
900
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
901
|
+
db.exec("PRAGMA busy_timeout = 4000");
|
|
902
|
+
db.exec(`VACUUM INTO '${target.replace(/'/g, "''")}'`);
|
|
903
|
+
}
|
|
904
|
+
finally {
|
|
905
|
+
db.close();
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
function captureRecoveryAuxiliary(context, captured, input) {
|
|
910
|
+
const runtime = path.join(input.output, "runtime");
|
|
911
|
+
const codexExclusions = codexHomeSnapshotExclusions(context, input.projectId, input.runId);
|
|
912
|
+
const run = captured.db.get("SELECT run_root, project_root, workspace_root FROM runs WHERE project_id = ? AND id = ?", [input.projectId, input.runId]);
|
|
913
|
+
const roots = [run.run_root, runtimeRunDir(context.ddFlowHome, input.projectId, input.runId)];
|
|
914
|
+
for (const protocol of captured.db.all("SELECT id, state_path, plan_path FROM protocols")) {
|
|
915
|
+
const directory = runtimeProtocolDir(context.ddFlowHome, input.projectId, protocol.id);
|
|
916
|
+
if (!isInside(physicalPath(context.ddFlowHome), physicalPath(directory)))
|
|
917
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Protocol runtime leaves DD_FLOW_HOME", 1);
|
|
918
|
+
if (fs.existsSync(directory)) {
|
|
919
|
+
copyRuntimeTree(directory, path.join(runtime, path.relative(context.ddFlowHome, directory)), true, codexExclusions);
|
|
920
|
+
roots.push(directory);
|
|
921
|
+
}
|
|
922
|
+
for (const file of [protocol.state_path, protocol.plan_path]) {
|
|
923
|
+
if (!fs.existsSync(file) || roots.some(root => isInside(physicalPath(root), physicalPath(file))))
|
|
924
|
+
continue;
|
|
925
|
+
if (isInside(physicalPath(context.ddFlowHome), physicalPath(file)) && fs.statSync(file).isFile())
|
|
926
|
+
copyRuntimeTree(file, path.join(runtime, path.relative(context.ddFlowHome, file)));
|
|
927
|
+
else if (![run.project_root, run.workspace_root].some(root => isInside(physicalPath(root), physicalPath(file))))
|
|
928
|
+
throw new AppError("snapshot_protocol_scope_invalid", "Protocol evidence is outside captured payloads", 1, { path: file });
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
const homes = new Set([context.ddFlowHome, resourceHome(context)]);
|
|
932
|
+
const queries = {
|
|
933
|
+
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')",
|
|
934
|
+
run_control_workers: "SELECT resource_home AS home FROM run_control_workers",
|
|
935
|
+
work_launches: "SELECT json_extract(profile_json, '$.runtime_adapter.owner.resource_home') AS home FROM work_launches",
|
|
936
|
+
merge_requests: "SELECT json_extract(adapter_receipt_json, '$.owner.resource_home') AS home FROM merge_requests",
|
|
937
|
+
run_recovery_guards: "SELECT value AS home FROM run_recovery_guards, json_each(settlement_json, '$.resource_homes')"
|
|
938
|
+
};
|
|
939
|
+
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) : []);
|
|
940
|
+
for (const { home } of references) {
|
|
941
|
+
if (home === null)
|
|
942
|
+
continue;
|
|
943
|
+
if (typeof home !== "string" || !path.isAbsolute(home))
|
|
944
|
+
throw new AppError("snapshot_resource_scope_invalid", "Retained resource home must be an absolute path", 1);
|
|
945
|
+
homes.add(home);
|
|
946
|
+
}
|
|
947
|
+
const nativeCaptures = new Map();
|
|
948
|
+
const registries = [];
|
|
949
|
+
for (const home of [...homes].sort()) {
|
|
950
|
+
if (!path.isAbsolute(home))
|
|
951
|
+
throw new AppError("snapshot_resource_scope_invalid", "Resource home must be an absolute path", 1);
|
|
952
|
+
const evidence = readRecoveryResourceEvidence(home, input.projectId, input.runId, { db: captured.db, ddFlowHome: context.ddFlowHome });
|
|
953
|
+
for (const process of evidence.processes) {
|
|
954
|
+
const directory = JSON.parse(process.metadata_json).state_dir;
|
|
955
|
+
if (directory === undefined)
|
|
956
|
+
continue;
|
|
957
|
+
if (typeof directory !== "string" || !path.isAbsolute(directory))
|
|
958
|
+
throw new AppError("snapshot_native_scope_invalid", "Native artifact root must be absolute", 1);
|
|
959
|
+
if (roots.some(root => isInside(physicalPath(root), physicalPath(directory))) || nativeCaptures.has(directory))
|
|
960
|
+
continue;
|
|
961
|
+
const state = JSON.parse(fs.readFileSync(path.join(directory, "daemon.json"), "utf8"));
|
|
962
|
+
const owner = state.config?.runtime_owner;
|
|
963
|
+
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)
|
|
964
|
+
throw new AppError("snapshot_native_scope_invalid", "External native artifact root has no matching RUN owner", 1, { state_dir: directory });
|
|
965
|
+
const relative = path.join("native-evidence", crypto.createHash("sha256").update(directory).digest("hex"));
|
|
966
|
+
copyRuntimeTree(directory, path.join(runtime, relative), true, codexExclusions);
|
|
967
|
+
nativeCaptures.set(directory, relative);
|
|
968
|
+
}
|
|
969
|
+
const relative = path.join("resource-evidence", `${crypto.createHash("sha256").update(home).digest("hex")}.json`);
|
|
970
|
+
fs.mkdirSync(path.dirname(path.join(runtime, relative)), { recursive: true });
|
|
971
|
+
writeJson(path.join(runtime, relative), evidence);
|
|
972
|
+
registries.push(relative);
|
|
973
|
+
}
|
|
974
|
+
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 })) });
|
|
975
|
+
}
|
|
976
|
+
function treeHash(root, filtered = false) {
|
|
347
977
|
const hash = crypto.createHash("sha256");
|
|
348
978
|
const visit = (dir, relative) => {
|
|
349
979
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
350
980
|
const file = path.join(dir, entry.name);
|
|
351
981
|
const rel = path.join(relative, entry.name);
|
|
982
|
+
if (typeof filtered === "function" ? !filtered(file) : filtered && !snapshotPayloadAllowed(file))
|
|
983
|
+
continue;
|
|
352
984
|
if (entry.isDirectory())
|
|
353
985
|
visit(file, rel);
|
|
354
986
|
else if (entry.isFile()) {
|
|
@@ -364,13 +996,58 @@ function treeHash(root) {
|
|
|
364
996
|
visit(root, "");
|
|
365
997
|
return hash.digest("hex");
|
|
366
998
|
}
|
|
999
|
+
function treeModesHash(root, filtered = false) {
|
|
1000
|
+
const entries = [];
|
|
1001
|
+
const visit = (directory) => {
|
|
1002
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1003
|
+
const file = path.join(directory, entry.name);
|
|
1004
|
+
if (typeof filtered === "function" ? !filtered(file) : filtered && !snapshotPayloadAllowed(file))
|
|
1005
|
+
continue;
|
|
1006
|
+
if (entry.isDirectory())
|
|
1007
|
+
visit(file);
|
|
1008
|
+
else if (entry.isFile())
|
|
1009
|
+
entries.push([path.relative(root, file), fs.statSync(file).mode & 0o111]);
|
|
1010
|
+
}
|
|
1011
|
+
};
|
|
1012
|
+
visit(root);
|
|
1013
|
+
return crypto.createHash("sha256").update(JSON.stringify(entries)).digest("hex");
|
|
1014
|
+
}
|
|
1015
|
+
function verifySnapshotModes(snapshot, manifest) {
|
|
1016
|
+
if (!manifest.payload_modes)
|
|
1017
|
+
return; // Legacy snapshots did not attest modes.
|
|
1018
|
+
for (const name of ["project", "runtime", ...(manifest.workspace.kind === "git_worktree" ? ["workspace"] : [])]) {
|
|
1019
|
+
if (treeModesHash(path.join(snapshot, name)) !== manifest.payload_modes[name])
|
|
1020
|
+
throw new AppError("snapshot_checksum_mismatch", "Snapshot executable modes do not match manifest", 1, { payload: name });
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
367
1023
|
function fileHash(file) { return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
|
|
1024
|
+
// Flush children before their directory entries, then publish and flush the
|
|
1025
|
+
// parent. Never follow snapshot symlinks into the original project tree.
|
|
1026
|
+
function syncSnapshotTree(root) {
|
|
1027
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
1028
|
+
const file = path.join(root, entry.name);
|
|
1029
|
+
if (entry.isDirectory())
|
|
1030
|
+
syncSnapshotTree(file);
|
|
1031
|
+
else if (entry.isFile())
|
|
1032
|
+
syncPath(file);
|
|
1033
|
+
}
|
|
1034
|
+
syncPath(root);
|
|
1035
|
+
}
|
|
1036
|
+
function syncPath(file) {
|
|
1037
|
+
const descriptor = fs.openSync(file, "r");
|
|
1038
|
+
try {
|
|
1039
|
+
fs.fsyncSync(descriptor);
|
|
1040
|
+
}
|
|
1041
|
+
finally {
|
|
1042
|
+
fs.closeSync(descriptor);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
368
1045
|
function readManifest(snapshot) {
|
|
369
1046
|
const file = path.join(snapshot, "snapshot.json");
|
|
370
1047
|
if (!fs.existsSync(file))
|
|
371
1048
|
throw new AppError("snapshot_missing", "Snapshot manifest is missing", 1, { snapshot });
|
|
372
1049
|
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
373
|
-
if (value.schema_id !== "dd-flow/eval-run-snapshot@5" || !value.run_id || !value.project_root || !value.dd_flow_home || typeof value.purpose !== "string" || !["stage_entry", "candidate"].includes(value.purpose) || (value.purpose === "stage_entry" && !value.stage_entry) || (value.purpose
|
|
1050
|
+
if (value.schema_id !== "dd-flow/eval-run-snapshot@5" || !value.run_id || !value.project_root || !value.dd_flow_home || typeof value.purpose !== "string" || !["stage_entry", "candidate", "incomplete", "recovery"].includes(value.purpose) || (value.purpose === "stage_entry" && !value.stage_entry) || (value.purpose !== "stage_entry" && value.stage_entry !== null) || !value.runtime_sha256 || !value.project_sha256 || !value.project_git || !value.workspace)
|
|
374
1051
|
throw new AppError("snapshot_invalid", "Snapshot manifest is invalid", 1, { snapshot });
|
|
375
1052
|
if (!value.project_git.branch || !value.project_git.head || !value.project_git.bundle_sha256)
|
|
376
1053
|
throw new AppError("snapshot_invalid", "Snapshot project Git metadata is incomplete", 1, { snapshot });
|