@deksden-com/dd-flow-cli 0.9.0-beta.14 → 0.9.0-beta.140

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.
Files changed (493) hide show
  1. package/CHANGELOG.md +733 -0
  2. package/README.md +143 -1
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/argument-values.js +38 -0
  5. package/dist/cli/command-inputs.js +376 -0
  6. package/dist/cli/command-metadata.js +197 -0
  7. package/dist/cli/command-option-descriptions.js +191 -0
  8. package/dist/cli/completion-cli.js +70 -0
  9. package/dist/cli/completion.js +57 -0
  10. package/dist/cli/error-output.js +52 -0
  11. package/dist/cli/executor-onboarding.js +76 -0
  12. package/dist/cli/flows.js +29 -0
  13. package/dist/cli/harnesses.js +84 -0
  14. package/dist/cli/help.js +328 -18
  15. package/dist/cli/hook-ingress.js +78 -0
  16. package/dist/cli/input-preparation.js +165 -0
  17. package/dist/cli/memory-flow-admission.js +44 -0
  18. package/dist/cli/memory-init-invocation.js +78 -0
  19. package/dist/cli/memory-init.js +240 -0
  20. package/dist/cli/memory-storage-admission.js +53 -0
  21. package/dist/cli/models.js +39 -0
  22. package/dist/cli/native-hook-ingress.js +80 -0
  23. package/dist/cli/operator-profiles.js +61 -0
  24. package/dist/cli/output-options.js +35 -0
  25. package/dist/cli/response-file.js +71 -0
  26. package/dist/cli/run-cli.js +1689 -545
  27. package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
  28. package/dist/cli/runtime-maintenance-ingress.js +52 -0
  29. package/dist/cli/runtime-process.js +153 -0
  30. package/dist/cli/setup.js +149 -0
  31. package/dist/cli.js +71 -2
  32. package/dist/domain/stage-catalog.js +1 -1
  33. package/dist/domain/stage-handler-identities.js +20 -0
  34. package/dist/harness-runtime/DD-ZCODE.md +112 -0
  35. package/dist/harness-runtime/OPENCODE-LICENSE.txt +24 -0
  36. package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
  37. package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
  38. package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
  39. package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
  40. package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
  41. package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
  42. package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
  43. package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
  44. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  45. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  46. package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
  47. package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
  48. package/dist/harness-runtime/lib/daemon-operations.d.mts +1 -0
  49. package/dist/harness-runtime/lib/daemon-operations.mjs +371 -0
  50. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  51. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +724 -0
  52. package/dist/harness-runtime/lib/dd-agy.mjs +70 -0
  53. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  54. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +196 -0
  55. package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
  56. package/dist/harness-runtime/lib/dd-codex.mjs +817 -0
  57. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +129 -0
  58. package/dist/harness-runtime/lib/dd-droid.mjs +584 -0
  59. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +498 -0
  60. package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
  61. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +507 -0
  62. package/dist/harness-runtime/lib/dd-opencode.mjs +354 -0
  63. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +750 -0
  64. package/dist/harness-runtime/lib/dd-zcode.mjs +1145 -0
  65. package/dist/harness-runtime/lib/delegation-instructions.d.mts +14 -0
  66. package/dist/harness-runtime/lib/delegation-instructions.mjs +157 -0
  67. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  68. package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
  69. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  70. package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
  71. package/dist/harness-runtime/lib/lease-renewal.mjs +37 -0
  72. package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
  73. package/dist/harness-runtime/lib/lifecycle-command.mjs +273 -0
  74. package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
  75. package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
  76. package/dist/harness-runtime/lib/managed-daemon.d.mts +13 -0
  77. package/dist/harness-runtime/lib/managed-daemon.mjs +654 -0
  78. package/dist/harness-runtime/lib/managed-flow-env.mjs +15 -0
  79. package/dist/harness-runtime/lib/model-observations.mjs +101 -0
  80. package/dist/harness-runtime/lib/native-children.d.mts +16 -0
  81. package/dist/harness-runtime/lib/native-children.mjs +113 -0
  82. package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
  83. package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
  84. package/dist/harness-runtime/lib/native-request-proof.d.mts +2 -0
  85. package/dist/harness-runtime/lib/native-request-proof.mjs +65 -0
  86. package/dist/harness-runtime/lib/native-streams.mjs +45 -0
  87. package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
  88. package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
  89. package/dist/harness-runtime/lib/opencode-plugin.mjs +85 -0
  90. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  91. package/dist/harness-runtime/lib/operation-errors.d.mts +14 -0
  92. package/dist/harness-runtime/lib/operation-errors.mjs +116 -0
  93. package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
  94. package/dist/harness-runtime/lib/operation-progress.mjs +114 -0
  95. package/dist/harness-runtime/lib/process-json.d.mts +5 -0
  96. package/dist/harness-runtime/lib/process-json.mjs +201 -0
  97. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  98. package/dist/harness-runtime/lib/provider-overload-policy.d.mts +13 -0
  99. package/dist/harness-runtime/lib/provider-overload-policy.mjs +138 -0
  100. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  101. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  102. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  103. package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
  104. package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
  105. package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
  106. package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
  107. package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
  108. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-1y4a697q.js +81 -0
  109. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-2ny4vxct.js +92 -0
  110. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-6mptkzbc.js +0 -0
  111. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-7x67cf1q.js +52 -0
  112. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-9rqn6x4v.js +16 -0
  113. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-9vdz0zwn.js +1661 -0
  114. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ecs5ftka.js +1466 -0
  115. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-frbwqjmf.js +145 -0
  116. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-gne7h7mq.js +50 -0
  117. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-gx9wnkzr.js +105 -0
  118. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-m2eywc8w.js +0 -0
  119. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-nwcpakzx.js +12 -0
  120. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-q4g3afnw.js +623 -0
  121. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-qav6mfdz.js +0 -0
  122. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-sxt88q69.js +12 -0
  123. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-t1xa31vm.js +39 -0
  124. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ve4aws36.js +103 -0
  125. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vmytr4q8.js +4 -0
  126. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vt9jbch8.js +36 -0
  127. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vyas3vgt.js +0 -0
  128. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-wjyeq25y.js +30 -0
  129. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-xgnj2w4v.js +20 -0
  130. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-y2etg5bs.js +9 -0
  131. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ydhz1zrh.js +238 -0
  132. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-z6qdwcsf.js +62 -0
  133. package/dist/harness-runtime/vendor/opencode-client/contract.d.ts +1 -0
  134. package/dist/harness-runtime/vendor/opencode-client/contract.js +12 -0
  135. package/dist/harness-runtime/vendor/opencode-client/effect/api/api.d.ts +2806 -0
  136. package/dist/harness-runtime/vendor/opencode-client/effect/api/api.js +0 -0
  137. package/dist/harness-runtime/vendor/opencode-client/effect/api.d.ts +4 -0
  138. package/dist/harness-runtime/vendor/opencode-client/effect/api.js +0 -0
  139. package/dist/harness-runtime/vendor/opencode-client/effect/client.d.ts +2530 -0
  140. package/dist/harness-runtime/vendor/opencode-client/effect/client.js +15 -0
  141. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client-error.d.ts +7 -0
  142. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client-error.js +6 -0
  143. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client.d.ts +2529 -0
  144. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client.js +8 -0
  145. package/dist/harness-runtime/vendor/opencode-client/effect/generated/index.d.ts +2 -0
  146. package/dist/harness-runtime/vendor/opencode-client/effect/generated/index.js +12 -0
  147. package/dist/harness-runtime/vendor/opencode-client/effect/index.d.ts +35 -0
  148. package/dist/harness-runtime/vendor/opencode-client/effect/index.js +75 -0
  149. package/dist/harness-runtime/vendor/opencode-client/effect/rpc.d.ts +20 -0
  150. package/dist/harness-runtime/vendor/opencode-client/effect/rpc.js +11 -0
  151. package/dist/harness-runtime/vendor/opencode-client/effect/service.d.ts +90 -0
  152. package/dist/harness-runtime/vendor/opencode-client/effect/service.js +187 -0
  153. package/dist/harness-runtime/vendor/opencode-client/package.json +84 -0
  154. package/dist/harness-runtime/vendor/opencode-client/promise/api.d.ts +21 -0
  155. package/dist/harness-runtime/vendor/opencode-client/promise/api.js +0 -0
  156. package/dist/harness-runtime/vendor/opencode-client/promise/client.d.ts +252 -0
  157. package/dist/harness-runtime/vendor/opencode-client/promise/client.js +14 -0
  158. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client-error.d.ts +8 -0
  159. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client-error.js +6 -0
  160. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client.d.ts +259 -0
  161. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client.js +7 -0
  162. package/dist/harness-runtime/vendor/opencode-client/promise/generated/index.d.ts +3 -0
  163. package/dist/harness-runtime/vendor/opencode-client/promise/generated/index.js +79 -0
  164. package/dist/harness-runtime/vendor/opencode-client/promise/generated/types.d.ts +8932 -0
  165. package/dist/harness-runtime/vendor/opencode-client/promise/generated/types.js +70 -0
  166. package/dist/harness-runtime/vendor/opencode-client/promise/index.d.ts +6 -0
  167. package/dist/harness-runtime/vendor/opencode-client/promise/index.js +83 -0
  168. package/dist/harness-runtime/vendor/opencode-client/promise/rpc.d.ts +32 -0
  169. package/dist/harness-runtime/vendor/opencode-client/promise/rpc.js +7 -0
  170. package/dist/harness-runtime/vendor/opencode-client/promise/service.d.ts +24 -0
  171. package/dist/harness-runtime/vendor/opencode-client/promise/service.js +187 -0
  172. package/dist/harness-runtime/vendor/opencode-client/pty-handoff.d.ts +12 -0
  173. package/dist/harness-runtime/vendor/opencode-client/pty-handoff.js +14 -0
  174. package/dist/harness-runtime/vendor/opencode-client/rpc-runtime.d.ts +20 -0
  175. package/dist/harness-runtime/vendor/opencode-client/rpc-runtime.js +14 -0
  176. package/dist/harness-runtime/vendor/opencode-client/service-contender.d.ts +37 -0
  177. package/dist/harness-runtime/vendor/opencode-client/service-contender.js +10 -0
  178. package/dist/harness-runtime/vendor/opencode-client/service-probe.d.ts +70 -0
  179. package/dist/harness-runtime/vendor/opencode-client/service-probe.js +16 -0
  180. package/dist/harness-runtime/vendor/opencode-client/service-timing.d.ts +12 -0
  181. package/dist/harness-runtime/vendor/opencode-client/service-timing.js +10 -0
  182. package/dist/harness-runtime/vendor/opencode-client/service-version.d.ts +2 -0
  183. package/dist/harness-runtime/vendor/opencode-client/service-version.js +6 -0
  184. package/dist/harness-runtime/vendor/opencode-client/service.d.ts +52 -0
  185. package/dist/harness-runtime/vendor/opencode-client/service.js +1 -0
  186. package/dist/harness-runtime/vendor/opencode-client/shared-events.d.ts +11 -0
  187. package/dist/harness-runtime/vendor/opencode-client/shared-events.js +8 -0
  188. package/dist/harness-runtime/vendor/opencode-client/solid/connection.d.ts +37 -0
  189. package/dist/harness-runtime/vendor/opencode-client/solid/connection.js +10 -0
  190. package/dist/harness-runtime/vendor/opencode-client/solid/data.d.ts +211 -0
  191. package/dist/harness-runtime/vendor/opencode-client/solid/data.js +18 -0
  192. package/dist/harness-runtime/vendor/opencode-client/solid/index.d.ts +3 -0
  193. package/dist/harness-runtime/vendor/opencode-client/solid/index.js +32 -0
  194. package/dist/harness-runtime/vendor/opencode-client/solid/pty.d.ts +22 -0
  195. package/dist/harness-runtime/vendor/opencode-client/solid/pty.js +8 -0
  196. package/dist/harness-runtime/vendor/opencode-plugin.mjs +3 -0
  197. package/dist/protocol/local-files.js +18 -9
  198. package/dist/runtime/context.js +8 -4
  199. package/dist/schemas/agent-profile.schema.json +1 -1
  200. package/dist/schemas/code-review-result.schema.json +1 -1
  201. package/dist/schemas/code-verification.schema.json +7 -5
  202. package/dist/schemas/code-work-batch.schema.json +2 -2
  203. package/dist/schemas/discovery-result.schema.json +184 -0
  204. package/dist/schemas/execution-bundle.schema.json +205 -0
  205. package/dist/schemas/execution-settings.schema.json +162 -0
  206. package/dist/schemas/flow-descriptor.schema.json +54 -0
  207. package/dist/schemas/flow-run.schema.json +28 -0
  208. package/dist/schemas/harness-catalog.schema.json +80 -0
  209. package/dist/schemas/mb-init-compose-result.schema.json +457 -0
  210. package/dist/schemas/mb-init-discover-result.schema.json +500 -0
  211. package/dist/schemas/mb-init-finish-result.schema.json +422 -0
  212. package/dist/schemas/mb-init-preflight-result.schema.json +367 -0
  213. package/dist/schemas/mb-init-review-result.schema.json +396 -0
  214. package/dist/schemas/mb-init-verify-result.schema.json +391 -0
  215. package/dist/schemas/memory-bootstrap-receipt-v2.schema.json +67 -0
  216. package/dist/schemas/memory-bootstrap-receipt.schema.json +354 -0
  217. package/dist/schemas/memory-composition-work-result.schema.json +38 -0
  218. package/dist/schemas/memory-repair-work-result.schema.json +49 -0
  219. package/dist/schemas/memory-review-correction-plan.schema.json +30 -0
  220. package/dist/schemas/memory-review-work-result.schema.json +43 -0
  221. package/dist/schemas/model-catalog.schema.json +153 -0
  222. package/dist/schemas/plan-review-decision.schema.json +3 -3
  223. package/dist/schemas/plan-review-result.schema.json +2 -2
  224. package/dist/schemas/profile-settings.schema.json +122 -0
  225. package/dist/schemas/release-manifest.schema.json +291 -0
  226. package/dist/schemas/run-control-receipt.schema.json +118 -0
  227. package/dist/schemas/run-control-request.schema.json +36 -0
  228. package/dist/schemas/run-engine-binding.schema.json +1 -1
  229. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  230. package/dist/services/branch-context.js +3 -3
  231. package/dist/services/canon.js +11 -8
  232. package/dist/services/check-runner-evidence.js +168 -0
  233. package/dist/services/cleanup.js +133 -40
  234. package/dist/services/cli-operation-classifier.js +25 -62
  235. package/dist/services/cli-upgrade-allowlist.js +27 -0
  236. package/dist/services/code-checks.js +1156 -107
  237. package/dist/services/codex-hook-delivery.js +32 -0
  238. package/dist/services/command-context.js +80 -0
  239. package/dist/services/compatibility-preflight.js +13 -3
  240. package/dist/services/config.js +11 -8
  241. package/dist/services/continuation-outcome.js +20 -0
  242. package/dist/services/controller-child-capacity.js +13 -0
  243. package/dist/services/controller-child-observer.js +115 -0
  244. package/dist/services/controller-execution.js +88 -0
  245. package/dist/services/controller-fanout.js +202 -0
  246. package/dist/services/dashboard.js +143 -58
  247. package/dist/services/descriptor-coordinator-session.js +35 -0
  248. package/dist/services/descriptor-root-work.js +53 -0
  249. package/dist/services/descriptor-run-settlement.js +105 -0
  250. package/dist/services/descriptor-run-start.js +449 -0
  251. package/dist/services/descriptor-stage-coordinator.js +197 -0
  252. package/dist/services/descriptor-stage-settlement.js +222 -0
  253. package/dist/services/descriptor-stage-start.js +139 -0
  254. package/dist/services/discovery/agy-discovery.js +2 -0
  255. package/dist/services/discovery/codex-discovery.js +2 -0
  256. package/dist/services/discovery/droid-discovery.js +2 -0
  257. package/dist/services/discovery/grok-discovery.js +2 -0
  258. package/dist/services/discovery/opencode-discovery.js +2 -0
  259. package/dist/services/discovery/static.js +31 -0
  260. package/dist/services/discovery/zcode-discovery.js +2 -0
  261. package/dist/services/engines.js +294 -153
  262. package/dist/services/eval-snapshots.js +1215 -116
  263. package/dist/services/execution-bundles.js +263 -0
  264. package/dist/services/execution-policy.js +185 -0
  265. package/dist/services/executor-onboarding.js +56 -0
  266. package/dist/services/external-work-launch.js +308 -0
  267. package/dist/services/flow-catalog.js +21 -0
  268. package/dist/services/flow-descriptors.js +82 -0
  269. package/dist/services/frozen-engine.js +250 -0
  270. package/dist/services/generic-execution.js +164 -0
  271. package/dist/services/harness-adapter.js +355 -36
  272. package/dist/services/harness-config.js +2 -0
  273. package/dist/services/harness-discovery.js +29 -0
  274. package/dist/services/harness-doctor.js +75 -0
  275. package/dist/services/harness-probe-effects.js +51 -0
  276. package/dist/services/harness-version-probe.js +100 -0
  277. package/dist/services/hooks.js +771 -325
  278. package/dist/services/hybrid-contracts.js +483 -0
  279. package/dist/services/ids.js +29 -1
  280. package/dist/services/installation-lock.js +95 -0
  281. package/dist/services/installed-flow-source.js +183 -0
  282. package/dist/services/lanes.js +78 -65
  283. package/dist/services/lifecycle-command.js +1 -288
  284. package/dist/services/lifecycle-contract.js +1 -0
  285. package/dist/services/lifecycle-invocations.js +2007 -0
  286. package/dist/services/managed-daemon-binding.js +38 -0
  287. package/dist/services/managed-lease-monitor.js +133 -0
  288. package/dist/services/managed-processes.js +475 -55
  289. package/dist/services/memory-accepted-composition.js +77 -0
  290. package/dist/services/memory-baseline-preservation.js +65 -0
  291. package/dist/services/memory-completed-correction-wave.js +320 -0
  292. package/dist/services/memory-compose-handler.js +258 -0
  293. package/dist/services/memory-composition-acceptance.js +199 -0
  294. package/dist/services/memory-composition-graph.js +134 -0
  295. package/dist/services/memory-composition-registration.js +146 -0
  296. package/dist/services/memory-composition-work-custody.js +151 -0
  297. package/dist/services/memory-composition-work-results.js +96 -0
  298. package/dist/services/memory-corrected-review-acceptance.js +129 -0
  299. package/dist/services/memory-corrected-review-batch.js +30 -0
  300. package/dist/services/memory-corrected-review-findings.js +106 -0
  301. package/dist/services/memory-corrected-review-inputs.js +210 -0
  302. package/dist/services/memory-corrected-review-projection.js +78 -0
  303. package/dist/services/memory-corrected-review-receipt.js +170 -0
  304. package/dist/services/memory-corrected-review-registration.js +191 -0
  305. package/dist/services/memory-correction-check-receipt.js +219 -0
  306. package/dist/services/memory-correction-input-owner.js +6 -0
  307. package/dist/services/memory-discover-handler.js +104 -0
  308. package/dist/services/memory-finish-evidence.js +435 -0
  309. package/dist/services/memory-finish-handler.js +215 -0
  310. package/dist/services/memory-finish-integration.js +280 -0
  311. package/dist/services/memory-finish-readiness.js +122 -0
  312. package/dist/services/memory-git-integration.js +151 -0
  313. package/dist/services/memory-historical-corrected-review.js +206 -0
  314. package/dist/services/memory-historical-original-review.js +130 -0
  315. package/dist/services/memory-historical-repair-registration.js +99 -0
  316. package/dist/services/memory-historical-second-review.js +128 -0
  317. package/dist/services/memory-init-bootstrap-readiness.js +210 -0
  318. package/dist/services/memory-init-contexts.js +89 -0
  319. package/dist/services/memory-init-controller-start.js +84 -0
  320. package/dist/services/memory-init-engine-release.js +223 -0
  321. package/dist/services/memory-init-git-policy.js +136 -0
  322. package/dist/services/memory-init-lint-capability.js +185 -0
  323. package/dist/services/memory-init-native-capacity.js +296 -0
  324. package/dist/services/memory-init-preflight.js +330 -0
  325. package/dist/services/memory-init-project-bootstrap.js +599 -0
  326. package/dist/services/memory-init-request-candidate.js +157 -0
  327. package/dist/services/memory-init-request-input.js +66 -0
  328. package/dist/services/memory-init-resource-storage.js +125 -0
  329. package/dist/services/memory-init-run-allocation.js +81 -0
  330. package/dist/services/memory-init-run-bundle.js +98 -0
  331. package/dist/services/memory-init-start.js +181 -0
  332. package/dist/services/memory-init-startup-custody.js +80 -0
  333. package/dist/services/memory-init-startup-input.js +240 -0
  334. package/dist/services/memory-init-storage.js +81 -0
  335. package/dist/services/memory-init-stores.js +359 -0
  336. package/dist/services/memory-init-worktrunk-capability.js +178 -0
  337. package/dist/services/memory-layer-publication.js +611 -0
  338. package/dist/services/memory-layer.js +156 -0
  339. package/dist/services/memory-lint-config.js +85 -0
  340. package/dist/services/memory-native-review-copy.js +165 -0
  341. package/dist/services/memory-normal-flow-entry.js +75 -0
  342. package/dist/services/memory-ordinary-defaults.js +112 -0
  343. package/dist/services/memory-preflight-bootstrap-custody.js +115 -0
  344. package/dist/services/memory-preflight-handler.js +259 -0
  345. package/dist/services/memory-repair-current-view.js +299 -0
  346. package/dist/services/memory-repair-document-delta.js +451 -0
  347. package/dist/services/memory-repair-history.js +491 -0
  348. package/dist/services/memory-repair-physical-binding.js +312 -0
  349. package/dist/services/memory-repair-publication-files.js +152 -0
  350. package/dist/services/memory-repair-publication-intent.js +27 -0
  351. package/dist/services/memory-repair-publication-plan.js +160 -0
  352. package/dist/services/memory-repair-publication-source.js +225 -0
  353. package/dist/services/memory-repair-publication.js +794 -0
  354. package/dist/services/memory-repair-registration.js +239 -0
  355. package/dist/services/memory-repair-work-baseline.js +413 -0
  356. package/dist/services/memory-repair-work-completion.js +97 -0
  357. package/dist/services/memory-repair-work-custody.js +73 -0
  358. package/dist/services/memory-repair-work-results.js +89 -0
  359. package/dist/services/memory-repair-workspace.js +252 -0
  360. package/dist/services/memory-repair-writer-copy.js +735 -0
  361. package/dist/services/memory-result-binding.js +173 -0
  362. package/dist/services/memory-retained-review-authority.js +129 -0
  363. package/dist/services/memory-retained-review-results.js +70 -0
  364. package/dist/services/memory-retained-second-baseline.js +102 -0
  365. package/dist/services/memory-retained-second-repairs.js +156 -0
  366. package/dist/services/memory-review-acceptance.js +214 -0
  367. package/dist/services/memory-review-correction-plan.js +171 -0
  368. package/dist/services/memory-review-handler.js +585 -0
  369. package/dist/services/memory-review-inputs.js +200 -0
  370. package/dist/services/memory-review-receipt.js +180 -0
  371. package/dist/services/memory-review-registration.js +108 -0
  372. package/dist/services/memory-review-work-custody.js +124 -0
  373. package/dist/services/memory-review-work-input.js +72 -0
  374. package/dist/services/memory-review-work-results.js +73 -0
  375. package/dist/services/memory-second-corrected-review-inputs.js +165 -0
  376. package/dist/services/memory-second-correction-plan.js +76 -0
  377. package/dist/services/memory-second-repair-baseline.js +91 -0
  378. package/dist/services/memory-second-repair-launch.js +614 -0
  379. package/dist/services/memory-second-repair-registration.js +88 -0
  380. package/dist/services/memory-second-repair-source.js +187 -0
  381. package/dist/services/memory-second-review-acceptance.js +115 -0
  382. package/dist/services/memory-source-observations.js +117 -0
  383. package/dist/services/memory-stage-dispatch.js +28 -0
  384. package/dist/services/memory-stage-results.js +199 -0
  385. package/dist/services/memory-verification-acceptance.js +135 -0
  386. package/dist/services/memory-verification-checks.js +252 -0
  387. package/dist/services/memory-verification-receipt.js +159 -0
  388. package/dist/services/memory-verify-handler.js +135 -0
  389. package/dist/services/memory-work-result-preparation.js +63 -0
  390. package/dist/services/merge-queue.js +228 -149
  391. package/dist/services/merge-server.js +161 -35
  392. package/dist/services/migrations.js +37 -16
  393. package/dist/services/model-catalog.js +109 -0
  394. package/dist/services/model-discovery.js +46 -0
  395. package/dist/services/native-daemon-history.js +49 -0
  396. package/dist/services/native-session-control.js +39 -0
  397. package/dist/services/operator-profiles.js +236 -0
  398. package/dist/services/plan-runtime.js +26 -11
  399. package/dist/services/plans.js +28 -25
  400. package/dist/services/projects.js +37 -17
  401. package/dist/services/prompts.js +28 -17
  402. package/dist/services/protocols.js +163 -87
  403. package/dist/services/provider-capacity.js +385 -0
  404. package/dist/services/recovery-observation-budget.js +121 -0
  405. package/dist/services/recovery-snapshot-database.js +560 -0
  406. package/dist/services/release-archive-producer.js +52 -0
  407. package/dist/services/release-archive.js +143 -0
  408. package/dist/services/release-cache.js +142 -0
  409. package/dist/services/release-compatibility.js +18 -0
  410. package/dist/services/release-download.js +67 -0
  411. package/dist/services/release-envelope.js +104 -0
  412. package/dist/services/release-manifest.js +45 -0
  413. package/dist/services/release-payload.js +114 -0
  414. package/dist/services/release-producer.js +63 -0
  415. package/dist/services/release-provenance.js +160 -0
  416. package/dist/services/release-registry.js +66 -0
  417. package/dist/services/release-source.js +194 -0
  418. package/dist/services/repair-intents.js +42 -0
  419. package/dist/services/review-copy.js +165 -0
  420. package/dist/services/review-deferral.js +23 -0
  421. package/dist/services/run-control-receipt.js +56 -0
  422. package/dist/services/run-control-worker.js +411 -0
  423. package/dist/services/run-control.js +1056 -0
  424. package/dist/services/run-controller-adapter.js +399 -0
  425. package/dist/services/run-controller-capture.js +186 -0
  426. package/dist/services/run-controller-process.js +208 -0
  427. package/dist/services/run-controller-recovery.js +289 -0
  428. package/dist/services/run-controller-state.js +97 -0
  429. package/dist/services/run-controller.js +1205 -0
  430. package/dist/services/run-engine-bindings.js +1 -1
  431. package/dist/services/run-fork.js +147 -0
  432. package/dist/services/run-health.js +149 -0
  433. package/dist/services/run-observations.js +152 -0
  434. package/dist/services/run-projection.js +22 -64
  435. package/dist/services/run-recovery-guard.js +77 -0
  436. package/dist/services/run-recovery-runtime.js +112 -0
  437. package/dist/services/run-recovery.js +489 -0
  438. package/dist/services/run-start-custody.js +177 -0
  439. package/dist/services/runs.js +1019 -247
  440. package/dist/services/runtime-budget.js +430 -0
  441. package/dist/services/runtime-command.js +43 -0
  442. package/dist/services/runtime-scope-capture.js +52 -0
  443. package/dist/services/runtime-scope-control.js +468 -0
  444. package/dist/services/runtime-scope-resume.js +599 -0
  445. package/dist/services/runtime-scope-stop.js +210 -0
  446. package/dist/services/runtime-scope-worker.js +287 -0
  447. package/dist/services/runtime-service.js +96 -0
  448. package/dist/services/schema-validation.js +10 -8
  449. package/dist/services/scope-writer-cleanup.js +27 -0
  450. package/dist/services/sessions.js +35 -69
  451. package/dist/services/setup.js +377 -0
  452. package/dist/services/stage-blocker.js +17 -7
  453. package/dist/services/stage-context.js +193 -19
  454. package/dist/services/stage-handlers.js +74 -0
  455. package/dist/services/stage-lifecycle.js +100 -108
  456. package/dist/services/stage-pause.js +89 -75
  457. package/dist/services/stage-report-renderer.js +234 -6
  458. package/dist/services/stage-work-graph.js +52 -0
  459. package/dist/services/tooling.js +32 -23
  460. package/dist/services/usage.js +49 -101
  461. package/dist/services/verification-matrix.js +374 -0
  462. package/dist/services/vnext-code-review.js +223 -88
  463. package/dist/services/vnext-code.js +327 -226
  464. package/dist/services/vnext-contracts.js +10 -1
  465. package/dist/services/vnext-execution-profile.js +80 -5
  466. package/dist/services/vnext-fanout.js +311 -19
  467. package/dist/services/vnext-merge.js +332 -111
  468. package/dist/services/vnext-plan-review.js +279 -127
  469. package/dist/services/vnext-plan.js +229 -104
  470. package/dist/services/vnext-protocolize.js +411 -86
  471. package/dist/services/vnext-specify.js +119 -81
  472. package/dist/services/vnext-workspace-policy.js +7 -2
  473. package/dist/services/work-registry.js +1627 -199
  474. package/dist/services/workspace-bootstrap.js +52 -15
  475. package/dist/services/workspace-files.js +85 -0
  476. package/dist/services/worktrees.js +98 -44
  477. package/dist/shared/entity-references.js +8 -0
  478. package/dist/shared/errors.js +17 -0
  479. package/dist/storage/agent-output.js +26 -0
  480. package/dist/storage/database.js +891 -39
  481. package/dist/storage/foreign-key-transaction.js +39 -0
  482. package/dist/storage/immutable-input.js +45 -0
  483. package/dist/storage/import-guard.js +102 -0
  484. package/dist/storage/native-cleanup.js +52 -0
  485. package/dist/storage/paths.js +17 -4
  486. package/dist/storage/projection-lock.js +73 -0
  487. package/dist/storage/work-references.js +23 -0
  488. package/dist/storage/writer-contract.js +89 -0
  489. package/dist/storage/writer-migration.js +85 -0
  490. package/package.json +43 -13
  491. package/tools/create-canon-release.mjs +33 -0
  492. package/tools/produce-hybrid-release.mjs +41 -0
  493. package/tools/repair-paused-run-status.mjs +84 -0
@@ -2,14 +2,40 @@ 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";
7
+ import { beginSnapshotImport, completeSnapshotImport } from "../storage/import-guard.js";
8
+ import { foreignKeyTransaction } from "../storage/foreign-key-transaction.js";
5
9
  import { createContext } from "../runtime/context.js";
6
10
  import { AppError } from "../shared/errors.js";
7
- import { resolveProjectRoot } from "../storage/paths.js";
11
+ import { canonicalPath, resolveProjectRoot, runtimeProtocolDir, runtimeRunDir } from "../storage/paths.js";
8
12
  import { registerProject, requireProjectByRoot } from "./projects.js";
9
- import { getFlowRunStatus, startFlowRun } from "./runs.js";
13
+ import { freezeRunExecutionRouting, getFlowRunStatus, importFlowRunExecutionProfile, startFlowRun } from "./runs.js";
14
+ import { loadExecutionRoutingInput, resolveExecutionPolicy } from "./execution-policy.js";
15
+ import { validateRunOperationalDecision } from "./vnext-execution-profile.js";
10
16
  import { readVnextFlowDefinition } from "./vnext-specify.js";
17
+ import { captureRecoveryDatabase, readRecoveryResourceEvidence } from "./recovery-snapshot-database.js";
18
+ import { resourceHome } from "./managed-processes.js";
19
+ import { getResourceDatabase } from "../storage/database.js";
20
+ import { codexHomeSharedEntries } from "./hooks.js";
21
+ import { prepareOutputFile } from "../cli/input-preparation.js";
22
+ import { localEnvironmentAllowed, projectServicePathFilter } from "./workspace-files.js";
23
+ import { cleanupScopeWriters } from "./scope-writer-cleanup.js";
24
+ import { PreparedInstalledFlowSource } from "./installed-flow-source.js";
25
+ import { readSetupStatus } from "./setup.js";
26
+ import { isObservationOperation, nativeInventoryVersion, retainedDaemonOperations } from "./run-control.js";
11
27
  /** Capture the only flow boundary which exists before `stage start --bootstrap` creates a RUN. */
12
- export function createEvalBootstrapSnapshot(context, input) {
28
+ export function prepareEvalBootstrapSnapshot(context, input) {
29
+ let source;
30
+ if (input.flow !== undefined && input.flow !== "sdlc") {
31
+ if (input.flow !== "mb-init")
32
+ throw new AppError("snapshot_flow_unsupported", "Bootstrap snapshot flow is not registered", 2, { phase: "prepare", effect: "no_effect" });
33
+ const home = context.env.DD_FLOW_CONFIG_HOME ?? context.ddFlowHome;
34
+ const selected = readSetupStatus(home);
35
+ if (!selected.installation)
36
+ throw new AppError("snapshot_flow_unavailable", "Bootstrap snapshot requires the selected installed flow", 2, { phase: "prepare", effect: "no_effect" });
37
+ source = PreparedInstalledFlowSource.fromInstalledRelease(home, selected.installation.manifest_sha256, input.flow);
38
+ }
13
39
  const projectRoot = resolveProjectRoot(input.projectRoot);
14
40
  const output = path.resolve(input.output);
15
41
  if (fs.existsSync(output))
@@ -18,44 +44,161 @@ export function createEvalBootstrapSnapshot(context, input) {
18
44
  throw new AppError("snapshot_output_inside_project", "Bootstrap snapshot output must be outside the project tree", 1, { output });
19
45
  if (isInside(physicalPath(context.ddFlowHome), physicalPath(output)))
20
46
  throw new AppError("snapshot_output_inside_runtime", "Bootstrap snapshot output must be outside DD_FLOW_HOME", 1, { output });
21
- fs.mkdirSync(output, { recursive: true });
22
- fs.cpSync(projectRoot, path.join(output, "project"), { recursive: true, verbatimSymlinks: true, filter: (source) => path.basename(source) !== ".git" });
23
- const manifest = {
24
- schema_id: "dd-eval/bootstrap-snapshot@1",
25
- stage: "specify",
26
- project_root: projectRoot,
27
- project_sha256: treeHash(path.join(output, "project")),
28
- project_git: snapshotProjectGit(projectRoot, output)
29
- };
30
- writeJson(path.join(output, "bootstrap.json"), manifest);
31
- return { ok: true, snapshot: output, ...manifest };
47
+ prepareOutputFile(output);
48
+ try {
49
+ prepareSnapshotProjectGit(projectRoot);
50
+ }
51
+ catch (error) {
52
+ if (!(error instanceof AppError) || error.code !== "snapshot_project_git_invalid")
53
+ throw error;
54
+ throw new AppError(error.code, error.message, 2, { ...error.details, phase: "prepare", effect: "no_effect", recoverable: true });
55
+ }
56
+ return { projectRoot, output, source };
57
+ }
58
+ export function createEvalBootstrapSnapshot(context, input) {
59
+ const { projectRoot, output, source } = prepareEvalBootstrapSnapshot(context, input);
60
+ const temporary = `${output}.partial-${crypto.randomUUID()}`;
61
+ const before = bootstrapSourceVersion(projectRoot);
62
+ try {
63
+ fs.mkdirSync(temporary, { recursive: true });
64
+ fs.cpSync(projectRoot, path.join(temporary, "project"), { recursive: true, verbatimSymlinks: true, filter: projectPayloadFilter(projectRoot) });
65
+ const after = bootstrapSourceVersion(projectRoot);
66
+ if (before !== after)
67
+ throw new AppError("snapshot_source_changed", "Bootstrap source changed during snapshot capture", 1, { phase: "bootstrap", recoverable: true });
68
+ const manifest = {
69
+ schema_id: source ? "dd-eval/bootstrap-snapshot@2" : "dd-eval/bootstrap-snapshot@1",
70
+ stage: source?.resolveRegisteredFlow().descriptor.stages[0]?.id ?? "specify",
71
+ ...(source ? { flow: { id: "mb-init", source_sha256: source.sha256, descriptor_sha256: source.descriptorReference().sha256 } } : {}),
72
+ project_root: projectRoot,
73
+ project_sha256: treeHash(path.join(temporary, "project")),
74
+ project_git: snapshotProjectGit(projectRoot, temporary)
75
+ };
76
+ writeJson(path.join(temporary, "bootstrap.json"), manifest);
77
+ if (after !== bootstrapSourceVersion(projectRoot))
78
+ throw new AppError("snapshot_source_changed", "Bootstrap source changed while preserving Git evidence", 1, { phase: "bootstrap", recoverable: true });
79
+ source?.revalidate();
80
+ syncSnapshotTree(temporary);
81
+ fs.renameSync(temporary, output);
82
+ syncPath(path.dirname(output));
83
+ return { ok: true, snapshot: output, ...manifest };
84
+ }
85
+ catch (error) {
86
+ fs.rmSync(temporary, { recursive: true, force: true });
87
+ throw error;
88
+ }
89
+ }
90
+ function bootstrapSourceVersion(projectRoot) {
91
+ return JSON.stringify([
92
+ treeHash(projectRoot, true),
93
+ treeModesHash(projectRoot, true),
94
+ git(projectRoot, ["symbolic-ref", "--quiet", "HEAD"]),
95
+ git(projectRoot, ["rev-parse", "HEAD"]),
96
+ indexEntries(projectRoot).toString("base64")
97
+ ]);
32
98
  }
33
99
  /** Restore a pre-RUN project state; `stage start --bootstrap` creates runtime state afterwards. */
34
- export function restoreEvalBootstrapSnapshot(_context, input) {
100
+ export function prepareEvalBootstrapRestore(input) {
35
101
  const snapshot = path.resolve(input.snapshot);
36
102
  const manifest = readBootstrapManifest(snapshot);
37
103
  const projectRoot = resolveProjectRoot(input.projectRoot);
104
+ assertRestoreTargetSeparation(snapshot, [projectRoot]);
38
105
  const sourceProject = path.join(snapshot, "project");
39
- if (treeHash(sourceProject) !== manifest.project_sha256)
40
- throw new AppError("snapshot_checksum_mismatch", "Bootstrap project checksum does not match manifest", 1, { snapshot });
106
+ verifyGitSnapshotPayload(snapshot, { name: "project", hash: manifest.project_sha256, git: manifest.project_git });
107
+ return { snapshot, manifest, projectRoot, sourceProject };
108
+ }
109
+ export function restoreEvalBootstrapSnapshot(_context, input, prepared = prepareEvalBootstrapRestore(input)) {
110
+ const { snapshot, manifest, projectRoot, sourceProject } = prepared;
111
+ assertRestoreTargetSeparation(snapshot, [projectRoot]);
41
112
  clearProjectTree(projectRoot, false);
42
113
  restoreProjectGit(snapshot, manifest.project_git, projectRoot);
43
114
  replaceProjectTree(projectRoot, sourceProject);
44
- return { ok: true, schema_id: "dd-eval/bootstrap-restore@1", snapshot, project_root: projectRoot, target_stage: "specify" };
115
+ return { ok: true, schema_id: "dd-eval/bootstrap-restore@1", snapshot, project_root: projectRoot, target_stage: manifest.stage, ...(manifest.flow ? { flow: manifest.flow } : {}) };
45
116
  }
46
117
  /**
47
- * Snapshot a deliberately dedicated DD_FLOW_HOME. Eval checkpoints are not a
48
- * general runtime export format: a shared home fails closed instead of trying
49
- * to infer a safe subset of SQLite rows.
118
+ * Eval fixtures require a dedicated home. Sealed recovery exports instead
119
+ * retain only the selected RUN's relational and filesystem evidence.
50
120
  */
51
121
  export function createEvalRunSnapshot(context, input) {
122
+ const { output } = prepareEvalRunSnapshotCreation(context, input);
123
+ const temporary = `${output}.partial-${crypto.randomUUID()}`;
124
+ let sourceVersion = null;
125
+ try {
126
+ input.boundary?.verify();
127
+ sourceVersion = input.boundary ? snapshotSourceVersion(context, input) : null;
128
+ const result = captureEvalRunSnapshot(context, { ...input, ...(sourceVersion ? { journalCuts: sourceVersion.journals, observationCuts: sourceVersion.observations } : {}), output: temporary });
129
+ if (input.boundary && sourceVersion) {
130
+ 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.sha256, observation: input.boundary.observation } });
131
+ writeJson(path.join(temporary, "snapshot.json"), Object.fromEntries(Object.entries(result).filter(([key]) => key !== "ok" && key !== "snapshot")));
132
+ }
133
+ if (input.recoveryId) {
134
+ const projectRoot = resolveProjectRoot(input.projectRoot);
135
+ const project = requireProjectByRoot(context, projectRoot);
136
+ const run = context.db.get("SELECT workspace_root FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
137
+ verifyRecoverySnapshot(temporary, { runId: input.runId, recoveryId: input.recoveryId, projectRoot, workspaceRoot: run?.workspace_root ?? projectRoot });
138
+ }
139
+ if (fs.existsSync(output))
140
+ throw new AppError("snapshot_exists", "Snapshot output already exists", 1, { output });
141
+ syncSnapshotTree(temporary);
142
+ if (input.boundary) {
143
+ if (sourceVersion) {
144
+ let after;
145
+ try {
146
+ after = snapshotSourceVersion(context, input, sourceVersion.databases, sourceVersion.journals);
147
+ }
148
+ catch (error) {
149
+ if (error.code !== "ENOENT")
150
+ throw error;
151
+ const missing = error.path;
152
+ throw new AppError("snapshot_source_changed", "Snapshot source disappeared during boundary capture", 1, { components: [missing && path.isAbsolute(missing) && isInside(context.ddFlowHome, missing) ? `runtime/${path.relative(context.ddFlowHome, missing)}` : "source_path_disappeared"] });
153
+ }
154
+ if (sourceVersion.sha256 !== after.sha256)
155
+ throw new AppError("snapshot_source_changed", "Snapshot source files or Git state changed during boundary capture", 1, { components: snapshotSourceChanges(sourceVersion.entries, after.entries), changes: snapshotSourceChangeProofs(sourceVersion.entries, after.entries) });
156
+ }
157
+ input.boundary.verify();
158
+ }
159
+ fs.renameSync(temporary, output);
160
+ syncPath(path.dirname(output));
161
+ return { ...result, snapshot: output };
162
+ }
163
+ catch (error) {
164
+ fs.rmSync(temporary, { recursive: true, force: true });
165
+ // Native journal publication creates its directory before requested.json.
166
+ // Retry a gap during any capture phase, without classifying an incomplete
167
+ // request as read-only. Persistent missing inputs still exhaust the budget.
168
+ if (input.boundary && error.code === "ENOENT") {
169
+ const missing = error.path;
170
+ throw new AppError("snapshot_source_changed", "Snapshot source was not fully published during boundary capture", 1, { components: [missing && path.isAbsolute(missing) && isInside(context.ddFlowHome, missing) ? `runtime/${path.relative(context.ddFlowHome, missing)}` : "source_path_disappeared"] });
171
+ }
172
+ throw error;
173
+ }
174
+ finally {
175
+ for (const db of sourceVersion?.databases.values() ?? [])
176
+ db.close();
177
+ }
178
+ }
179
+ export function prepareEvalRunSnapshotCreation(context, input) {
180
+ if (Number(Boolean(input.candidate)) + Number(Boolean(input.incomplete)) + Number(input.stageEntry !== undefined) + Number(input.recoveryId !== undefined) !== 1)
181
+ throw new AppError("usage", "Use exactly one of candidate, incomplete, recoveryId or stageEntry", 2, { phase: "prepare", effect: "no_effect", recoverable: true });
52
182
  const projectRoot = resolveProjectRoot(input.projectRoot);
53
183
  // Snapshot is read-only at the control-plane boundary. An invalid workspace
54
184
  // root must fail without registering a second project in a dedicated home.
55
185
  const project = requireProjectByRoot(context, projectRoot);
56
186
  const status = getFlowRunStatus(context, { projectRoot, runId: input.runId });
57
- assertDedicatedHome(context, project.id, input.runId);
58
- if (input.candidate)
187
+ const recovery = typeof input.recoveryId === "string";
188
+ if (!recovery && !input.incomplete && context.db.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'run_controllers'")) {
189
+ 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]);
190
+ 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))
191
+ 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 });
192
+ }
193
+ if (!recovery)
194
+ assertDedicatedHome(context, project.id, input.runId);
195
+ if (recovery) {
196
+ 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]);
197
+ if (!guard || guard.status !== "sealed")
198
+ 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 });
199
+ }
200
+ if (input.incomplete || recovery) { /* Recovery captures only after the runner seals all writers. */ }
201
+ else if (input.candidate)
59
202
  assertTerminalCandidate(status.index.stage_runs ?? []);
60
203
  else if (input.stageEntry)
61
204
  assertStageEntry(status.index.stage_runs ?? [], input.stageEntry);
@@ -65,7 +208,7 @@ export function createEvalRunSnapshot(context, input) {
65
208
  const activeChildren = input.candidate
66
209
  ? 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
210
  : 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)
211
+ if (!input.incomplete && !recovery && activeChildren > 0)
69
212
  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
213
  const output = path.resolve(input.output);
71
214
  if (fs.existsSync(output))
@@ -75,36 +218,97 @@ export function createEvalRunSnapshot(context, input) {
75
218
  const workspaceRoot = String(status.run.workspace_root ?? projectRoot);
76
219
  if (isInside(physicalPath(projectRoot), physicalPath(output)) || isInside(physicalPath(workspaceRoot), physicalPath(output)))
77
220
  throw new AppError("snapshot_output_inside_project", "Snapshot output must be outside the project and RUN workspace trees", 1, { output });
78
- context.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
79
- fs.mkdirSync(output, { recursive: true });
80
- fs.cpSync(context.ddFlowHome, path.join(output, "runtime"), {
81
- recursive: true,
82
- verbatimSymlinks: true,
83
- // Managed checkouts are restored from their Git bundle and workspace
84
- // payload. Copying their .git indirection into runtime makes the snapshot
85
- // dependent on the source machine's worktree metadata.
86
- filter: (source) => !["engines", "checkouts"].includes(path.basename(source))
87
- });
221
+ prepareOutputFile(output);
222
+ prepareSnapshotProjectGit(projectRoot, recovery && status.run.flow_kind === "mb-init");
223
+ prepareSnapshotWorkspace(workspaceRoot, projectRoot);
224
+ return { projectRoot, project, status, recovery, output, workspaceRoot, activeChildren };
225
+ }
226
+ function captureEvalRunSnapshot(context, input) {
227
+ const { projectRoot, project, status, recovery, output, workspaceRoot, activeChildren } = prepareEvalRunSnapshotCreation(context, input);
228
+ fs.mkdirSync(output, { recursive: true, mode: 0o700 });
229
+ const resourceDatabase = path.join(context.ddFlowHome, "runtime.sqlite");
230
+ const databaseFiles = [context.db.path, resourceDatabase].flatMap(file => [file, `${file}-wal`, `${file}-shm`]);
231
+ const codexExclusions = [...codexHomeSnapshotExclusions(context, project.id, input.runId), ...input.journalCuts?.keys() ?? [], ...input.observationCuts?.keys() ?? []];
232
+ if (recovery) {
233
+ 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)))
234
+ throw new AppError("snapshot_run_scope_invalid", "Recovery requires a RUN artifact root within its runtime", 1);
235
+ for (const source of new Set([status.run.run_root, runtimeRunDir(context.ddFlowHome, project.id, input.runId)])) {
236
+ if (fs.existsSync(source))
237
+ copyRuntimeTree(source, path.join(output, "runtime", path.relative(context.ddFlowHome, source)), true, codexExclusions, [], input.observationCuts);
238
+ }
239
+ }
240
+ else
241
+ copyRuntimeTree(context.ddFlowHome, path.join(output, "runtime"), false, [...databaseFiles, ...codexExclusions], grokProviderHomes(context.ddFlowHome), input.observationCuts);
242
+ for (const [file, cut] of input.journalCuts ?? []) {
243
+ const target = path.join(output, "runtime", path.relative(context.ddFlowHome, file));
244
+ fs.mkdirSync(path.dirname(target), { recursive: true });
245
+ fs.writeFileSync(target, cut.payload, { mode: cut.mode });
246
+ }
247
+ // VACUUM INTO is a consistent SQLite read snapshot, including committed WAL
248
+ // pages. Copying the live database and its WAL separately is not atomic.
249
+ const databaseCopy = path.join(output, "runtime", path.relative(context.ddFlowHome, context.db.path));
250
+ fs.mkdirSync(path.dirname(databaseCopy), { recursive: true });
251
+ if (recovery) {
252
+ 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;
253
+ if (report && !isInside(physicalPath(path.join(output, "runtime")), physicalPath(report)))
254
+ throw new AppError("snapshot_protocol_scope_invalid", "Recovery protocol evidence is outside the captured runtime", 1);
255
+ const protocols = report && fs.existsSync(report) ? JSON.parse(fs.readFileSync(report, "utf8")).semantic?.acceptance : [];
256
+ if (!Array.isArray(protocols) || !protocols.every(id => typeof id === "string" && id.startsWith("PRT-")))
257
+ throw new AppError("snapshot_protocol_scope_invalid", "Recovery export requires the accepted PROTOCOLIZE protocol IDs", 1);
258
+ captureRecoveryDatabase(context.db, databaseCopy, project.id, input.runId, protocols);
259
+ }
260
+ else
261
+ context.db.exec(`VACUUM INTO '${databaseCopy.replace(/'/g, "''")}'`);
262
+ // Resource heartbeats can continue after productive RUN writers are sealed.
263
+ // Keep their committed evidence consistent too; never copy a live WAL pair.
264
+ if (!recovery && fs.existsSync(resourceDatabase)) {
265
+ const resources = new DatabaseSync(resourceDatabase, { readOnly: true });
266
+ try {
267
+ const resourceCopy = path.join(output, "runtime", "runtime.sqlite");
268
+ resources.exec("PRAGMA busy_timeout = 4000");
269
+ resources.exec(`VACUUM INTO '${resourceCopy.replace(/'/g, "''")}'`);
270
+ }
271
+ finally {
272
+ resources.close();
273
+ }
274
+ }
88
275
  fs.cpSync(projectRoot, path.join(output, "project"), {
89
276
  recursive: true,
90
277
  verbatimSymlinks: true,
91
- filter: (source) => path.basename(source) !== ".git"
278
+ filter: projectPayloadFilter(projectRoot)
92
279
  });
93
- const projectGit = snapshotProjectGit(projectRoot, output);
280
+ const projectGit = snapshotProjectGit(projectRoot, output, recovery && status.run.flow_kind === "mb-init");
94
281
  const workspace = snapshotWorkspace(workspaceRoot, projectRoot, output);
282
+ // Accepted Work results are captured in SQLite. Their file representations
283
+ // are retained evidence, not a second authority or a checkpoint gate.
284
+ if (recovery) {
285
+ const copiedContext = createContext({ ...context.env, DD_FLOW_HOME: path.join(output, "runtime") }, "read_existing");
286
+ try {
287
+ captureRecoveryAuxiliary(context, copiedContext, { projectId: project.id, runId: input.runId, output });
288
+ }
289
+ finally {
290
+ copiedContext.db.close?.();
291
+ }
292
+ }
95
293
  const manifest = {
96
- schema_id: "dd-flow/eval-run-snapshot@5",
294
+ schema_id: projectGit.state === "unborn" ? "dd-flow/eval-run-snapshot@6" : "dd-flow/eval-run-snapshot@5",
97
295
  run_id: input.runId,
98
296
  project_id: project.id,
99
297
  project_root: projectRoot,
100
298
  dd_flow_home: context.ddFlowHome,
101
- purpose: input.candidate ? "candidate" : "stage_entry",
102
- stage_entry: input.candidate ? null : input.stageEntry,
299
+ purpose: input.incomplete ? "incomplete" : recovery ? "recovery" : input.candidate ? "candidate" : "stage_entry",
300
+ stage_entry: input.incomplete || recovery || input.candidate ? null : input.stageEntry,
301
+ ...(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
302
  created_at: context.now(),
104
303
  runtime_sha256: treeHash(path.join(output, "runtime")),
105
304
  project_sha256: treeHash(path.join(output, "project")),
305
+ project_payload_policy: "service-files@1",
306
+ ...(!recovery ? { runtime_payload_policy: "flow-evidence@1" } : {}),
307
+ ...(input.journalCuts ? { journal_cuts: [...input.journalCuts].map(([file, cut]) => ({ path: path.relative(context.ddFlowHome, file), bytes: cut.payload.length, sha256: cut.sha256 })) } : {}),
308
+ ...(input.observationCuts ? { observation_cuts: [...input.observationCuts].map(([file, receipt]) => ({ path: path.relative(context.ddFlowHome, file), receipt })) } : {}),
106
309
  project_git: projectGit,
107
310
  workspace,
311
+ 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
312
  source_status: status
109
313
  };
110
314
  writeJson(path.join(output, "snapshot.json"), manifest);
@@ -118,23 +322,144 @@ function createdWorkSchemaForStage(stage) {
118
322
  return "dd-flow/merge-result";
119
323
  return null;
120
324
  }
121
- export function restoreEvalRunSnapshot(context, input) {
122
- const snapshot = path.resolve(input.snapshot);
325
+ /** Validate sealed source data before any target cleanup or copy. */
326
+ export function prepareEvalRunSnapshot(snapshot) {
123
327
  const manifest = readManifest(snapshot);
328
+ if (manifest.purpose === "incomplete")
329
+ throw new AppError("snapshot_incomplete_not_restorable", "Incomplete snapshot is forensic evidence, not a stage-entry fixture", 1, { snapshot });
124
330
  if (manifest.purpose === "candidate")
125
331
  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)
332
+ verifySnapshotPayload(snapshot, manifest);
333
+ if (manifest.purpose === "stage_entry") {
334
+ const db = new DatabaseSync(path.join(snapshot, "runtime", "db.sqlite"), { readOnly: true });
335
+ try {
336
+ assertSnapshotRuntimeDetachAllowed(sql => db.prepare(sql).get());
337
+ const row = db.prepare("SELECT index_json FROM runs WHERE id = ?").get(manifest.run_id);
338
+ if (!row)
339
+ throw new AppError("snapshot_invalid", "Snapshot RUN is not registered", 1);
340
+ const index = JSON.parse(row.index_json);
341
+ if (!Array.isArray(index?.stage_runs))
342
+ throw new AppError("snapshot_invalid", "Snapshot RUN index is invalid", 1);
343
+ assertStageEntry(index.stage_runs, manifest.stage_entry);
344
+ }
345
+ finally {
346
+ db.close();
347
+ }
348
+ }
349
+ return manifest;
350
+ }
351
+ export function prepareEvalRunRestore(context, input, preparedManifest) {
352
+ const snapshot = path.resolve(input.snapshot);
353
+ const manifest = preparedManifest ?? prepareEvalRunSnapshot(snapshot);
354
+ if (manifest.purpose === "incomplete")
355
+ throw new AppError("snapshot_incomplete_not_restorable", "Incomplete snapshot is forensic evidence, not a stage-entry fixture", 1, { snapshot });
356
+ const recovery = manifest.purpose === "recovery";
357
+ if (recovery && input.executionRoutingFile !== undefined)
358
+ throw new AppError("snapshot_recovery_policy_frozen", "Recovery must retain its frozen execution policy", 2);
359
+ if (recovery && input.operationalDecisionFile !== undefined)
360
+ throw new AppError("snapshot_recovery_policy_frozen", "Recovery cannot replace its accepted operational decision", 2);
361
+ if (recovery && input.recoveryId !== manifest.recovery_id)
362
+ throw new AppError("snapshot_recovery_requires_explicit_restore", "Recovery snapshots require their explicit --recovery-id", 1, { snapshot });
363
+ if (!recovery && input.recoveryId)
364
+ throw new AppError("snapshot_invalid", "Recovery ID cannot restore a non-recovery snapshot", 1, { snapshot });
365
+ if (manifest.purpose === "candidate")
366
+ throw new AppError("snapshot_candidate_not_restorable", "A terminal candidate snapshot is evidence, not a stage-entry fixture", 1, { snapshot });
367
+ if (!recovery && !manifest.stage_entry)
127
368
  throw new AppError("snapshot_invalid", "Stage-entry snapshot has no target stage", 1, { snapshot });
128
369
  const projectRoot = resolveProjectRoot(input.projectRoot);
129
- const existing = fs.readdirSync(context.ddFlowHome).filter((name) => !["db.sqlite", "db.sqlite-wal", "db.sqlite-shm"].includes(name));
130
- if (existing.length > 0)
131
- throw new AppError("restore_home_not_empty", "Snapshot restore requires an empty DD_FLOW_HOME", 1, { dd_flow_home: context.ddFlowHome, existing });
370
+ assertRunRestoreTargets(context, input, snapshot, projectRoot, manifest);
371
+ if (recovery)
372
+ verifyRecoverySnapshot(snapshot, { runId: manifest.run_id, recoveryId: input.recoveryId, projectRoot, workspaceRoot: projectRoot }, false);
132
373
  const sourceRuntime = path.join(snapshot, "runtime");
133
374
  const sourceProject = path.join(snapshot, "project");
134
- if (treeHash(sourceRuntime) !== manifest.runtime_sha256)
135
- throw new AppError("snapshot_checksum_mismatch", "Snapshot runtime checksum does not match manifest", 1, { snapshot });
136
- if (treeHash(sourceProject) !== manifest.project_sha256)
137
- throw new AppError("snapshot_checksum_mismatch", "Snapshot project checksum does not match manifest", 1, { snapshot });
375
+ const routingInput = input.executionRoutingFile !== undefined ? loadExecutionRoutingInput(input.executionRoutingFile) : undefined;
376
+ const acceptedOperational = recovery ? undefined : prepareSnapshotOperationalDecision({ snapshot, runId: manifest.run_id, projectRoot, now: context.now(), ...(input.operationalDecisionFile ? { file: input.operationalDecisionFile } : {}) });
377
+ const operationalDecisionBytes = acceptedOperational?.bytes;
378
+ let selectedProfile = acceptedOperational?.profile;
379
+ if (routingInput) {
380
+ // Resolve selected profiles before replacing the caller's fresh runtime.
381
+ const sourceDb = new DatabaseSync(path.join(sourceRuntime, "db.sqlite"), { readOnly: true });
382
+ try {
383
+ const row = sourceDb.prepare("SELECT index_json FROM runs WHERE id = ?").get(manifest.run_id);
384
+ const index = row ? JSON.parse(row.index_json) : null;
385
+ if (!index?.execution_profile || !["vnext_specify", "vnext_protocolize"].includes(index.flow_kind))
386
+ throw new AppError("execution_profile_not_frozen", "Stage-entry routing requires a vNext execution snapshot", 1);
387
+ assertStageEntry(index.stage_runs, manifest.stage_entry);
388
+ selectedProfile = freezeRunExecutionRouting(context.ddFlowHome, selectedProfile ?? index.execution_profile, routingInput);
389
+ for (const row of sourceDb.prepare("SELECT payload_json FROM works WHERE run_id = ? AND status = 'created'").all(manifest.run_id)) {
390
+ const payload = row.payload_json ? JSON.parse(row.payload_json) : null;
391
+ if (payload?.execution_override !== undefined)
392
+ resolveExecutionPolicy({ ddFlowHome: context.ddFlowHome, policy: routingInput.execution, profiles: selectedProfile.agent_profiles, stage: manifest.stage_entry, work: payload.execution_override });
393
+ }
394
+ selectedProfile.routing_input.artifact = `execution-routing.${routingInput.source_checksum}.input.json`;
395
+ const sourceRun = sourceDb.prepare("SELECT run_root FROM runs WHERE id = ?").get(manifest.run_id);
396
+ if (typeof sourceRun?.run_root !== "string" || !path.isAbsolute(sourceRun.run_root) || !isInside(manifest.dd_flow_home, sourceRun.run_root))
397
+ throw new AppError("snapshot_invalid", "Snapshot RUN root must be inside its runtime home", 1);
398
+ const existingRouting = path.join(sourceRuntime, path.relative(manifest.dd_flow_home, sourceRun.run_root), selectedProfile.routing_input.artifact);
399
+ if (fs.existsSync(existingRouting) && !fs.readFileSync(existingRouting).equals(routingInput.bytes))
400
+ throw new AppError("snapshot_checksum_mismatch", "Existing routing input does not match its checksum", 1);
401
+ }
402
+ finally {
403
+ sourceDb.close();
404
+ }
405
+ }
406
+ return { snapshot, manifest, recovery, projectRoot, sourceRuntime, sourceProject, routingInput, selectedProfile, operationalDecisionBytes };
407
+ }
408
+ /** Shared no-effect scope preparation for direct restore and run fork. */
409
+ export function prepareSnapshotOperationalDecision(input) {
410
+ const sourceDb = new DatabaseSync(path.join(input.snapshot, "runtime", "db.sqlite"), { readOnly: true });
411
+ try {
412
+ const row = sourceDb.prepare("SELECT index_json FROM runs WHERE id = ?").get(input.runId);
413
+ const profile = row ? JSON.parse(row.index_json).execution_profile : undefined;
414
+ if (profile?.operational_decision && !input.file)
415
+ throw new AppError("snapshot_operational_acceptance_required", "A new stage-entry execution needs its own accepted operational decision", 2);
416
+ if (!input.file)
417
+ return undefined;
418
+ if (!profile)
419
+ throw new AppError("execution_profile_not_frozen", "Operational stage-entry decision needs a frozen vNext profile", 2);
420
+ const bytes = fs.readFileSync(input.file);
421
+ const decision = validateRunOperationalDecision(JSON.parse(bytes.toString("utf8")), profile.settings);
422
+ if (canonicalPath(decision.scope.project_root, false) !== canonicalPath(input.projectRoot, false))
423
+ throw new AppError("operational_decision_scope_mismatch", "Imported decision must name the new project root", 2);
424
+ const sourceProject = path.join(input.snapshot, "project"), policyFile = path.resolve(sourceProject, decision.policy.path);
425
+ if (!isInside(sourceProject, policyFile) || !fs.existsSync(policyFile) || !isInside(fs.realpathSync(sourceProject), fs.realpathSync(policyFile)) || fileHash(policyFile) !== decision.policy.sha256)
426
+ throw new AppError("operational_decision_policy_changed", "Imported decision policy must match the owned frozen project source", 2);
427
+ if (decision.exception?.expires_at && Date.parse(decision.exception.expires_at) <= Date.parse(input.now))
428
+ throw new AppError("operational_decision_expired", "Imported operational decision has explicitly expired", 2);
429
+ return { profile: { ...profile, operational_decision: decision }, bytes };
430
+ }
431
+ finally {
432
+ sourceDb.close();
433
+ }
434
+ }
435
+ function assertRunRestoreTargets(context, input, snapshot, projectRoot, manifest) {
436
+ assertRestoreTargetSeparation(snapshot, [projectRoot, context.ddFlowHome]);
437
+ if (manifest.workspace.kind === "git_worktree") {
438
+ const workspaceRoot = restoredWorkspaceRoot(manifest, projectRoot, context.ddFlowHome);
439
+ assertRestoreTargetSeparation(snapshot, [workspaceRoot]);
440
+ if (isInside(physicalPath(projectRoot), physicalPath(workspaceRoot)) || isInside(physicalPath(workspaceRoot), physicalPath(projectRoot)) || physicalPath(workspaceRoot) === physicalPath(context.ddFlowHome))
441
+ throw new AppError("snapshot_path_conflict", "Feature workspace overlaps a restore target", 2);
442
+ if (fs.existsSync(workspaceRoot))
443
+ throw new AppError("snapshot_workspace_target_exists", "Snapshot feature workspace target already exists", 1, { workspace_root: workspaceRoot });
444
+ }
445
+ if (manifest.purpose === "recovery") {
446
+ if (fs.readdirSync(projectRoot).length || (context.db.get("SELECT COUNT(*) AS count FROM projects")?.count ?? 0) > 0)
447
+ throw new AppError("recovery_restore_target_not_empty", "Recovery restore requires fresh project and runtime targets", 1);
448
+ }
449
+ 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));
450
+ if (existing.length > 0)
451
+ throw new AppError("restore_home_not_empty", "Snapshot restore requires an empty DD_FLOW_HOME", 1, { dd_flow_home: context.ddFlowHome, existing });
452
+ if (context.db.get("SELECT 1 FROM projects LIMIT 1") || context.db.get("SELECT 1 FROM runs LIMIT 1"))
453
+ throw new AppError("restore_home_not_empty", "Snapshot restore cannot replace an initialized runtime", 1);
454
+ }
455
+ export function restoreEvalRunSnapshot(context, input, prepared = prepareEvalRunRestore(context, input), prearmedImportId) {
456
+ const { snapshot, manifest, recovery, projectRoot, sourceRuntime, sourceProject, routingInput, selectedProfile } = prepared;
457
+ if (input.operationalDecisionFile && (!prepared.operationalDecisionBytes || !fs.readFileSync(input.operationalDecisionFile).equals(prepared.operationalDecisionBytes)))
458
+ throw new AppError("operational_decision_changed", "Accepted operational decision changed after import preparation", 2);
459
+ assertRunRestoreTargets(context, input, snapshot, projectRoot, manifest);
460
+ const sourceManifestSha256 = fileHash(path.join(snapshot, "snapshot.json"));
461
+ const importId = prearmedImportId ?? beginSnapshotImport({ home: context.ddFlowHome, projectRoot,
462
+ workspaceRoot: restoredWorkspaceRoot(manifest, projectRoot, context.ddFlowHome), sourceManifestSha256 });
138
463
  clearProjectTree(projectRoot, false);
139
464
  restoreProjectGit(snapshot, manifest.project_git, projectRoot);
140
465
  replaceProjectTree(projectRoot, sourceProject);
@@ -144,17 +469,69 @@ export function restoreEvalRunSnapshot(context, input) {
144
469
  const workspaceRoot = restoreWorkspace(snapshot, manifest, projectRoot, context.ddFlowHome);
145
470
  // The dispatch context was intentionally closed before replacing db.sqlite.
146
471
  // A fresh process owns all subsequent normal commands.
147
- const restored = createContext({ ...context.env, DD_FLOW_HOME: context.ddFlowHome });
472
+ const restored = createContext({ ...context.env, DD_FLOW_HOME: context.ddFlowHome }, "initialize", importId);
473
+ let result, primary, failed = false;
148
474
  try {
149
- rebaseRuntime(restored, manifest.project_root, projectRoot, sourceWorkspaceRoot(manifest), workspaceRoot, manifest.dd_flow_home, context.ddFlowHome);
475
+ const runtimeLineage = recovery ? null : detachSnapshotRuntimeOwners(restored, snapshot, manifest);
476
+ const originalRunRoot = restored.db.get("SELECT run_root FROM runs WHERE id = ?", [manifest.run_id])?.run_root;
477
+ rebaseRuntime(restored, manifest.project_root, projectRoot, sourceWorkspaceRoot(manifest), workspaceRoot, manifest.dd_flow_home, context.ddFlowHome, recovery);
478
+ const publicationRun = restored.db.get("SELECT project_id, run_root FROM runs WHERE id = ?", [manifest.run_id]);
479
+ if (!originalRunRoot || !publicationRun?.run_root || !isInside(manifest.dd_flow_home, originalRunRoot) || !isInside(context.ddFlowHome, publicationRun.run_root))
480
+ throw new AppError("snapshot_invalid", "Restored publication roots are not bound to their runtime", 1);
481
+ const pathMapping = [{ from: manifest.dd_flow_home, to: context.ddFlowHome }, { from: sourceWorkspaceRoot(manifest), to: workspaceRoot }, { from: manifest.project_root, to: projectRoot }];
482
+ restored.db.run("INSERT INTO audit_events (project_id, event_type, forced, payload_json, created_at) VALUES (?, 'flow_run.publication_relocation', 0, ?, ?)", [publicationRun.project_id, JSON.stringify({ run_id: manifest.run_id, from: originalRunRoot, to: publicationRun.run_root, source_manifest_sha256: sourceManifestSha256, import_id: importId, path_mapping: pathMapping }), restored.now()]);
150
483
  registerProject(restored, { root: projectRoot });
151
484
  requireProjectByRoot(restored, projectRoot);
485
+ if (selectedProfile && runtimeLineage) {
486
+ const run = restored.db.get("SELECT run_root FROM runs WHERE id = ?", [manifest.run_id]);
487
+ if (routingInput) {
488
+ const artifact = path.join(run.run_root, selectedProfile.routing_input.artifact);
489
+ if (fs.existsSync(artifact)) {
490
+ if (!fs.readFileSync(artifact).equals(routingInput.bytes))
491
+ throw new AppError("snapshot_checksum_mismatch", "Existing routing input does not match its checksum", 1);
492
+ }
493
+ else
494
+ fs.writeFileSync(artifact, routingInput.bytes, { flag: "wx", mode: 0o600 });
495
+ }
496
+ if (input.operationalDecisionFile) {
497
+ if (!prepared.operationalDecisionBytes || !fs.readFileSync(input.operationalDecisionFile).equals(prepared.operationalDecisionBytes))
498
+ throw new AppError("operational_decision_changed", "Accepted operational decision changed before import publication", 2);
499
+ const binding = { project_id: publicationRun.project_id, run_id: manifest.run_id, ...selectedProfile.operational_decision.scope };
500
+ const policyBytes = fs.readFileSync(path.resolve(projectRoot, selectedProfile.operational_decision.policy.path));
501
+ const policySource = { path: `operational-policy.${selectedProfile.operational_decision.policy.sha256}.source.md`, sha256: crypto.createHash("sha256").update(policyBytes).digest("hex") };
502
+ if (policySource.sha256 !== selectedProfile.operational_decision.policy.sha256)
503
+ throw new AppError("operational_decision_policy_changed", "Imported policy changed before binding", 2);
504
+ if (!fs.existsSync(path.join(run.run_root, policySource.path)))
505
+ fs.writeFileSync(path.join(run.run_root, policySource.path), policyBytes, { flag: "wx" });
506
+ const bytes = `${JSON.stringify({ schema_id: "dd-flow/run-operational-contract@1", binding, settings: { merge_delivery: selectedProfile.settings.merge_delivery, merge_cleanup: selectedProfile.settings.merge_cleanup }, decision: selectedProfile.operational_decision, policy_source: policySource }, null, 2)}\n`;
507
+ const artifact = `operational-contract.${crypto.createHash("sha256").update(bytes).digest("hex")}.json`;
508
+ fs.writeFileSync(path.join(run.run_root, artifact), bytes, { flag: "wx" });
509
+ selectedProfile.operational_contract = { path: artifact, sha256: crypto.createHash("sha256").update(bytes).digest("hex"), policy_source: policySource, binding };
510
+ }
511
+ importFlowRunExecutionProfile(restored, { projectRoot, runId: manifest.run_id, stage: manifest.stage_entry, lineageFile: runtimeLineage, profile: selectedProfile });
512
+ }
513
+ const relocation = recovery ? {
514
+ schema_id: "dd-flow/recovery-relocation@1", physical_runtime_id: crypto.randomUUID(), recovery_id: input.recoveryId, run_id: manifest.run_id,
515
+ path_mapping: [{ from: manifest.dd_flow_home, to: context.ddFlowHome }, { from: sourceWorkspaceRoot(manifest), to: workspaceRoot }, { from: manifest.project_root, to: projectRoot }]
516
+ } : null;
517
+ const relocationFile = relocation ? path.join(context.ddFlowHome, "recovery-imports", `${relocation.physical_runtime_id}.json`) : null;
518
+ if (relocationFile) {
519
+ fs.mkdirSync(path.dirname(relocationFile), { recursive: true });
520
+ writeJson(relocationFile, relocation);
521
+ }
152
522
  const status = getFlowRunStatus(restored, { projectRoot, runId: manifest.run_id });
153
- assertStageEntry(status.index.stage_runs ?? [], manifest.stage_entry);
523
+ if (!recovery)
524
+ assertStageEntry(status.index.stage_runs ?? [], manifest.stage_entry);
525
+ else
526
+ restored.db.run("UPDATE run_recovery_guards SET capture_path = ? WHERE recovery_id = ? AND status = 'sealed'", [snapshot, input.recoveryId]);
154
527
  if (!status.run.run_root)
155
528
  throw new AppError("runtime_missing", "Restored RUN has no artifact root", 1, { run_id: manifest.run_id });
156
529
  const runHome = status.run.run_root;
157
- return {
530
+ const expectedWorkspaceRoot = restoredWorkspaceRoot(manifest, projectRoot, context.ddFlowHome);
531
+ if (physicalPath(workspaceRoot) !== physicalPath(expectedWorkspaceRoot))
532
+ throw new AppError("snapshot_workspace_restore_failed", "Restored workspace differs from the import target", 1, { workspace_root: workspaceRoot, expected_workspace_root: expectedWorkspaceRoot });
533
+ completeSnapshotImport(context.ddFlowHome, importId, { projectRoot, workspaceRoot: expectedWorkspaceRoot, sourceManifestSha256 });
534
+ result = {
158
535
  ok: true,
159
536
  schema_id: "dd-flow/eval-run-restore@1",
160
537
  snapshot,
@@ -164,12 +541,24 @@ export function restoreEvalRunSnapshot(context, input) {
164
541
  dd_flow_home: context.ddFlowHome,
165
542
  run_home: runHome,
166
543
  target_stage: manifest.stage_entry,
167
- next_command: `dd-flow stage start ${status.run.id} --stage ${manifest.stage_entry} --project-root ${JSON.stringify(projectRoot)} --json`
544
+ ...(runtimeLineage ? { runtime_lineage_file: runtimeLineage } : {}),
545
+ ...(recovery ? { recovery_id: input.recoveryId, native_session_portability: "requires_adapter_verification", relocation_file: relocationFile, relocation } : {}),
546
+ 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
547
  };
169
548
  }
170
- finally {
171
- restored.db.close?.();
549
+ catch (error) {
550
+ primary = error;
551
+ failed = true;
172
552
  }
553
+ const cleanup = cleanupScopeWriters([{ name: restored.ddFlowHome, db: restored.db, rollback: false, close: "always" }]);
554
+ if (failed) {
555
+ if (primary instanceof AppError && cleanup.length)
556
+ primary.details.import_cleanup_errors = cleanup;
557
+ throw primary;
558
+ }
559
+ if (cleanup.length)
560
+ throw new AppError("snapshot_import_cleanup_failed", "Snapshot imported but its connection could not be closed", 1, { effect: "committed", import_complete: true, import_cleanup_errors: cleanup });
561
+ return result;
173
562
  }
174
563
  export function prepareVnextSpecifyRun(context, input) {
175
564
  const projectRoot = resolveProjectRoot(input.projectRoot);
@@ -182,6 +571,7 @@ export function prepareVnextSpecifyRun(context, input) {
182
571
  subjectType: "discussion",
183
572
  subjectId: "SPECIFY",
184
573
  slug: input.slug,
574
+ executionRoutingFile: input.executionRoutingFile,
185
575
  nextAction: "start_specify"
186
576
  });
187
577
  return { ok: true, run_id: started.run.id, run_root: started.run.run_root, target_stage: "specify" };
@@ -196,19 +586,91 @@ function assertDedicatedHome(context, projectId, runId) {
196
586
  function assertStageEntry(stages, target) {
197
587
  if (stages.some((entry) => entry.stage === target))
198
588
  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 !== "done");
589
+ const unfinished = stages.filter((entry) => !["done", "skipped"].includes(entry.status ?? ""));
200
590
  if (unfinished.length > 0)
201
591
  throw new AppError("snapshot_predecessor_incomplete", "Stage-entry snapshot requires completed predecessor stages", 1, { target, unfinished });
202
592
  }
203
593
  function assertTerminalCandidate(stages) {
204
- const unfinished = stages.filter((entry) => entry.status !== "done");
594
+ const unfinished = stages.filter((entry) => !["done", "skipped"].includes(entry.status ?? ""));
205
595
  if (unfinished.length > 0)
206
596
  throw new AppError("snapshot_candidate_incomplete", "Candidate snapshot requires every started stage to be done", 1, { unfinished });
207
597
  }
208
- function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) {
209
- context.db.exec("PRAGMA foreign_keys = OFF");
210
- context.db.exec("BEGIN IMMEDIATE");
598
+ /** A stage-entry import is a new experiment, not a lease takeover or recovery.
599
+ * Keep source authority as evidence, never as executable target inventory. */
600
+ function assertSnapshotRuntimeDetachAllowed(get) {
601
+ 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"))
602
+ throw new AppError("snapshot_control_requires_recovery", "A fenced RUN requires explicit recovery, not a stage-entry fork", 1);
603
+ if (get("SELECT 1 FROM merge_requests WHERE status IN ('dispatching','active','waiting_user','action_required','recovery_required') LIMIT 1"))
604
+ throw new AppError("snapshot_execution_active", "A stage-entry fork cannot discard an unresolved MERGE execution", 1);
605
+ }
606
+ function detachSnapshotRuntimeOwners(context, snapshot, manifest) {
607
+ const hasTable = (table) => Boolean(context.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?", [table]));
608
+ assertSnapshotRuntimeDetachAllowed(sql => context.db.get(sql));
609
+ const detachedTables = ["lifecycle_packet_assignments", "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);
610
+ const runTables = Object.fromEntries([...detachedTables, "runs", "merge_requests", "sessions", "work_sessions"].map(table => [table, context.db.all(`SELECT * FROM ${table}`)]));
611
+ const resourceFile = path.join(context.ddFlowHome, "runtime.sqlite");
612
+ const resources = fs.existsSync(resourceFile) ? new DatabaseSync(resourceFile) : null;
613
+ let resourceHeld = false, resourceCommitted = false, result, primary, failed = false;
211
614
  try {
615
+ if (resources)
616
+ registerStoreWriter(resources);
617
+ 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()]));
618
+ const directory = path.join(context.ddFlowHome, "snapshot-imports");
619
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
620
+ const file = path.join(directory, `${crypto.randomUUID()}.json`);
621
+ 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 });
622
+ syncPath(file);
623
+ syncPath(directory);
624
+ const lineage = JSON.stringify({ lineage_file: file, lineage_sha256: fileHash(file) });
625
+ context.db.writeTransaction(() => {
626
+ assertSnapshotRuntimeDetachAllowed(sql => context.db.get(sql));
627
+ for (const [table, rows] of Object.entries(runTables))
628
+ if (JSON.stringify(context.db.all(`SELECT * FROM ${table}`)) !== JSON.stringify(rows))
629
+ throw new AppError("snapshot_runtime_changed", "Imported runtime changed during lineage preparation", 1, { table });
630
+ context.db.run("UPDATE sessions SET metadata_json = json_set(metadata_json, '$.snapshot_import', json(?))", [lineage]);
631
+ for (const table of detachedTables) {
632
+ try {
633
+ context.db.exec(`DELETE FROM ${table}`);
634
+ }
635
+ catch (error) {
636
+ throw new AppError("snapshot_runtime_detach_failed", `Could not detach imported ${table} authority`, 1, { table, cause: String(error) });
637
+ }
638
+ }
639
+ 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");
640
+ // Only the copied dedicated registry is touched. Source/external homes
641
+ // are historical references in the archive and are never opened here.
642
+ if (resources) {
643
+ resources.exec("BEGIN IMMEDIATE");
644
+ resourceHeld = true;
645
+ for (const [table, rows] of Object.entries(resourceTables)) {
646
+ if (JSON.stringify(resources.prepare(`SELECT * FROM ${table}`).all()) !== JSON.stringify(rows))
647
+ throw new AppError("snapshot_runtime_changed", "Imported resource evidence changed during lineage preparation", 1, { table });
648
+ resources.exec(`DELETE FROM ${table}`);
649
+ }
650
+ resources.exec("COMMIT");
651
+ resourceHeld = false;
652
+ resourceCommitted = true;
653
+ }
654
+ });
655
+ result = file;
656
+ }
657
+ catch (error) {
658
+ primary = error;
659
+ failed = true;
660
+ }
661
+ const cleanup = resources ? cleanupScopeWriters([{ name: resourceFile, db: resources, rollback: resourceHeld, close: "always" }]) : [];
662
+ if (failed || cleanup.length) {
663
+ const details = { effect: resourceCommitted ? "partial" : "unknown", ...(cleanup.length ? { import_cleanup_errors: cleanup } : {}) };
664
+ if (primary instanceof AppError) {
665
+ Object.assign(primary.details, details);
666
+ throw primary;
667
+ }
668
+ throw new AppError("snapshot_runtime_detach_failed", primary instanceof Error ? primary.message : "Imported runtime authority could not be detached", 1, { ...details, ...(failed ? { cause: String(primary) } : {}) });
669
+ }
670
+ return result;
671
+ }
672
+ function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome, recovery = false) {
673
+ foreignKeyTransaction(context.db, () => {
212
674
  context.db.run("UPDATE projects SET root = ?", [newRoot]);
213
675
  context.db.run("UPDATE runs SET project_root = ?, workspace_root = ?", [newRoot, newWorkspace]);
214
676
  for (const column of ["runtime_path", "run_dir", "run_index_path", "run_home_path", "run_root", "index_json"])
@@ -216,7 +678,12 @@ function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, ol
216
678
  context.db.run("UPDATE protocols SET project_root = ?", [newRoot]);
217
679
  for (const column of ["state_path", "plan_path"])
218
680
  rewriteDatabaseColumn(context, "protocols", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
219
- 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]);
681
+ for (const column of ["source_workspace", "target_workspace"])
682
+ rewriteDatabaseColumn(context, "merge_requests", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
683
+ if (recovery)
684
+ 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]);
685
+ else
686
+ context.db.run("UPDATE sessions SET project_root = ?, status = 'stopped', stop_reason = 'snapshot_restored', stopped_at = ?", [newRoot, context.now()]);
220
687
  for (const column of ["workspace_path", "cwd", "transcript_path"])
221
688
  rewriteDatabaseColumn(context, "sessions", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
222
689
  for (const column of ["prompt_path", "result_path"])
@@ -226,47 +693,55 @@ function rebaseRuntime(context, oldRoot, newRoot, oldWorkspace, newWorkspace, ol
226
693
  rewriteDatabaseColumn(context, "usage", "source_locator", oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
227
694
  for (const column of ["worktree_path", "worktrunk_metadata_json", "last_command_result_json"])
228
695
  rewriteDatabaseColumn(context, "worktree_records", column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
229
- 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()]);
696
+ // Recovery imports remain sealed. Their old Work sessions are historical
697
+ // bindings, not completed work; explicit recovery closes them interrupted.
698
+ if (!recovery)
699
+ 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
700
  context.db.run("DELETE FROM codex_session_bindings");
231
- context.db.run("COMMIT");
232
- }
233
- catch (error) {
234
- context.db.exec("ROLLBACK");
235
- throw error;
236
- }
237
- finally {
238
- context.db.exec("PRAGMA foreign_keys = ON");
239
- }
240
- rewriteStructuredFiles(context.ddFlowHome, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
701
+ });
702
+ // Only operational database paths move. Imported packets, results and
703
+ // journals retain their historical bytes, including interrupted JSONL tails.
704
+ // The frozen workspace route is an operational receipt consumed by later
705
+ // stages, so its relocated path is the sole structured-file exception.
706
+ rewriteOperationalRouteReceipts(context.ddFlowHome, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
241
707
  }
242
- function rewriteStructuredFiles(root, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) {
243
- const visit = (dir) => {
244
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
245
- const file = path.join(dir, entry.name);
246
- // DD_FLOW_HOME also contains the restored checkout and installed tools.
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))
708
+ function rewriteOperationalRouteReceipts(root, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) {
709
+ const visit = (directory) => {
710
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
711
+ const file = path.join(directory, entry.name);
712
+ if (entry.isDirectory())
250
713
  visit(file);
251
- else if (entry.isFile() && entry.name.endsWith(".json")) {
714
+ else if (entry.isFile() && entry.name === "workspace-route.json") {
252
715
  const value = JSON.parse(fs.readFileSync(file, "utf8"));
253
- writeJson(file, rebaseStructuredValue(value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome));
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`);
716
+ fs.writeFileSync(file, `${JSON.stringify(rebaseStructuredValue(value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome), null, 2)}\n`);
258
717
  }
259
718
  }
260
719
  };
261
720
  visit(root);
262
721
  }
263
- function rewriteDatabaseColumn(context, table, column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) { for (const row of context.db.all(`SELECT rowid AS rid, ${column} AS value FROM ${table} WHERE ${column} IS NOT NULL`)) {
264
- if (!row.value)
265
- continue;
266
- const value = column.endsWith("_json") || column === "index_json" ? JSON.stringify(rebaseStructuredValue(JSON.parse(row.value), oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome)) : rebasePathString(row.value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
267
- if (value !== row.value)
268
- context.db.run(`UPDATE ${table} SET ${column} = ? WHERE rowid = ?`, [value, row.rid]);
269
- } }
722
+ function rewriteDatabaseColumn(context, table, column, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) {
723
+ for (const row of context.db.all(`SELECT rowid AS rid, ${column} AS value FROM ${table} WHERE ${column} IS NOT NULL`)) {
724
+ if (!row.value)
725
+ continue;
726
+ let value;
727
+ if (column.endsWith("_json") || column === "index_json") {
728
+ const original = JSON.parse(row.value);
729
+ const mapped = rebaseStructuredValue(original, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
730
+ if (table === "runs" && column === "index_json" && original.execution_profile) {
731
+ // Accepted source/binding are logical provenance, not mutable physical locators.
732
+ if (original.execution_profile.operational_decision)
733
+ mapped.execution_profile.operational_decision = original.execution_profile.operational_decision;
734
+ if (original.execution_profile.operational_contract)
735
+ mapped.execution_profile.operational_contract = original.execution_profile.operational_contract;
736
+ }
737
+ value = JSON.stringify(mapped);
738
+ }
739
+ else
740
+ value = rebasePathString(row.value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome);
741
+ if (value !== row.value)
742
+ context.db.run(`UPDATE ${table} SET ${column} = ? WHERE rowid = ?`, [value, row.rid]);
743
+ }
744
+ }
270
745
  function rebaseStructuredValue(value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) { if (typeof value === "string")
271
746
  return rebasePathString(value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome); if (Array.isArray(value))
272
747
  return value.map((item) => rebaseStructuredValue(item, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome)); if (value && typeof value === "object")
@@ -274,20 +749,27 @@ function rebaseStructuredValue(value, oldRoot, newRoot, oldWorkspace, newWorkspa
274
749
  function rebasePathString(value, oldRoot, newRoot, oldWorkspace, newWorkspace, oldHome, newHome) { for (const [oldPrefix, newPrefix] of [[oldHome, newHome], [oldWorkspace, newWorkspace], [oldRoot, newRoot]])
275
750
  if (value === oldPrefix || value.startsWith(`${oldPrefix}${path.sep}`))
276
751
  return `${newPrefix}${value.slice(oldPrefix.length)}`; return value; }
277
- function snapshotWorkspace(workspaceRoot, projectRoot, output) {
752
+ function prepareSnapshotWorkspace(workspaceRoot, projectRoot) {
278
753
  if (samePath(workspaceRoot, projectRoot))
279
- return { kind: "project" };
754
+ return null;
280
755
  const branch = git(workspaceRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
281
756
  if (!branch)
282
757
  throw new AppError("snapshot_workspace_invalid", "Feature workspace must be on a named Git branch", 1, { workspace_root: workspaceRoot });
283
758
  const baseRef = git(workspaceRoot, ["rev-parse", "HEAD"]);
284
759
  if (!baseRef)
285
760
  throw new AppError("snapshot_workspace_invalid", "Feature workspace has no readable HEAD", 1, { workspace_root: workspaceRoot });
761
+ return { branch, baseRef };
762
+ }
763
+ function snapshotWorkspace(workspaceRoot, projectRoot, output) {
764
+ const prepared = prepareSnapshotWorkspace(workspaceRoot, projectRoot);
765
+ if (!prepared)
766
+ return { kind: "project" };
767
+ const { branch, baseRef } = prepared;
286
768
  const workspace = path.join(output, "workspace");
287
769
  const bundle = path.join(output, "workspace.bundle");
288
- fs.cpSync(workspaceRoot, workspace, { recursive: true, verbatimSymlinks: true, filter: (source) => path.basename(source) !== ".git" });
770
+ fs.cpSync(workspaceRoot, workspace, { recursive: true, verbatimSymlinks: true, filter: projectPayloadFilter(workspaceRoot) });
289
771
  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) };
772
+ return { kind: "git_worktree", source_root: workspaceRoot, branch, base_ref: baseRef, sha256: treeHash(workspace), bundle_sha256: fileHash(bundle), ...snapshotIndex(workspaceRoot, output, "workspace") };
291
773
  }
292
774
  function restoreWorkspace(snapshot, manifest, projectRoot, ddFlowHome) {
293
775
  if (manifest.workspace.kind === "project")
@@ -298,11 +780,7 @@ function restoreWorkspace(snapshot, manifest, projectRoot, ddFlowHome) {
298
780
  throw new AppError("snapshot_checksum_mismatch", "Snapshot workspace checksum does not match manifest", 1, { snapshot });
299
781
  if (!fs.existsSync(bundle) || fileHash(bundle) !== manifest.workspace.bundle_sha256)
300
782
  throw new AppError("snapshot_checksum_mismatch", "Snapshot workspace Git bundle does not match manifest", 1, { snapshot });
301
- const managedRoot = physicalPath(manifest.dd_flow_home);
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");
783
+ const workspaceRoot = restoredWorkspaceRoot(manifest, projectRoot, ddFlowHome);
306
784
  if (fs.existsSync(workspaceRoot))
307
785
  throw new AppError("snapshot_workspace_target_exists", "Snapshot feature workspace target already exists", 1, { workspace_root: workspaceRoot });
308
786
  runGit(projectRoot, ["fetch", bundle, `+refs/heads/${manifest.workspace.branch}:refs/heads/${manifest.workspace.branch}`]);
@@ -310,28 +788,192 @@ function restoreWorkspace(snapshot, manifest, projectRoot, ddFlowHome) {
310
788
  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
789
  runGit(projectRoot, ["worktree", "add", workspaceRoot, manifest.workspace.branch]);
312
790
  replaceProjectTree(workspaceRoot, source);
791
+ restoreIndex(snapshot, "workspace", manifest.workspace, workspaceRoot);
313
792
  return fs.realpathSync(workspaceRoot);
314
793
  }
794
+ export function restoredWorkspaceRoot(manifest, projectRoot, ddFlowHome) {
795
+ if (manifest.workspace.kind === "project")
796
+ return projectRoot;
797
+ const managedRoot = physicalPath(manifest.dd_flow_home), sourceRoot = physicalPath(manifest.workspace.source_root);
798
+ return isInside(managedRoot, sourceRoot) ? path.join(ddFlowHome, path.relative(managedRoot, sourceRoot)) : path.join(path.dirname(projectRoot), "workspace");
799
+ }
800
+ function assertRestoreTargetSeparation(snapshot, targets) {
801
+ const roots = [snapshot, ...targets].map(physicalPath);
802
+ for (let i = 0; i < roots.length; i++)
803
+ for (let j = i + 1; j < roots.length; j++) {
804
+ if (isInside(roots[i], roots[j]) || isInside(roots[j], roots[i]))
805
+ throw new AppError("snapshot_path_conflict", "Snapshot source and restore targets must not overlap", 2, { source: roots[i], target: roots[j] });
806
+ }
807
+ }
315
808
  function sourceWorkspaceRoot(manifest) {
316
809
  return manifest.workspace.kind === "project" ? manifest.project_root : manifest.workspace.source_root;
317
810
  }
318
- function snapshotProjectGit(projectRoot, output) {
811
+ function prepareSnapshotProjectGit(projectRoot, allowUnborn = false) {
319
812
  const branch = git(projectRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
320
- const head = git(projectRoot, ["rev-parse", "HEAD"]);
321
- if (!branch || !head)
322
- throw new AppError("snapshot_project_git_invalid", "Snapshot requires a project on a named Git branch with a readable HEAD", 1, { project_root: projectRoot });
813
+ const head = git(projectRoot, ["rev-parse", "--verify", "HEAD"]);
814
+ if (!branch || !head && !(allowUnborn && git(projectRoot, ["for-each-ref", "--format=%(refname)"]) === ""))
815
+ throw new AppError("snapshot_project_git_invalid", "Snapshot requires a named Git branch and readable HEAD, or an admitted empty-ref Memory recovery", 1, { project_root: projectRoot });
816
+ return { branch, head };
817
+ }
818
+ function snapshotProjectGit(projectRoot, output, allowUnborn = false) {
819
+ const { branch, head } = prepareSnapshotProjectGit(projectRoot, allowUnborn);
820
+ if (head === null)
821
+ return { branch, head: null, bundle_sha256: null, state: "unborn", ...snapshotIndex(projectRoot, output, "project") };
323
822
  const bundle = path.join(output, "project.bundle");
324
- runGit(projectRoot, ["bundle", "create", bundle, "--all"]);
325
- return { branch, head, bundle_sha256: fileHash(bundle) };
823
+ runGit(projectRoot, ["bundle", "create", bundle, `refs/heads/${branch}`]);
824
+ return { branch, head, bundle_sha256: fileHash(bundle), ...snapshotIndex(projectRoot, output, "project") };
326
825
  }
327
826
  function restoreProjectGit(snapshot, source, projectRoot) {
328
827
  const bundle = path.join(snapshot, "project.bundle");
329
- if (!fs.existsSync(bundle) || fileHash(bundle) !== source.bundle_sha256)
828
+ if (source.state === "unborn" ? fs.existsSync(bundle) : !fs.existsSync(bundle) || fileHash(bundle) !== source.bundle_sha256)
330
829
  throw new AppError("snapshot_checksum_mismatch", "Snapshot project Git bundle checksum does not match manifest", 1, { snapshot });
331
830
  fs.rmSync(path.join(projectRoot, ".git"), { recursive: true, force: true });
332
831
  runGit(projectRoot, ["init", "-b", source.branch]);
333
- runGit(projectRoot, ["fetch", bundle, `+refs/heads/${source.branch}:refs/remotes/snapshot/${source.branch}`]);
334
- runGit(projectRoot, ["checkout", "-B", source.branch, source.head]);
832
+ if (source.state !== "unborn") {
833
+ runGit(projectRoot, ["fetch", bundle, `+refs/heads/${source.branch}:refs/remotes/snapshot/${source.branch}`]);
834
+ runGit(projectRoot, ["checkout", "-B", source.branch, source.head]);
835
+ }
836
+ restoreIndex(snapshot, "project", source, projectRoot);
837
+ }
838
+ const mergeStateFiles = ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE", "ORIG_HEAD", "AUTO_MERGE"];
839
+ function indexEntries(root) {
840
+ const entries = Buffer.from(gitBytes(root, ["ls-files", "--stage", "-z"])
841
+ .toString("utf8").split("\0").filter(entry => entry && localEnvironmentAllowed(entry.slice(entry.indexOf("\t") + 1)))
842
+ .map(entry => `${entry}\0`).join(""));
843
+ const merge = {};
844
+ for (const name of mergeStateFiles) {
845
+ const file = git(root, ["rev-parse", "--git-path", name]);
846
+ if (!file)
847
+ throw new AppError("snapshot_index_invalid", "Could not locate Git merge state", 1);
848
+ const resolved = path.resolve(root, file);
849
+ if (fs.existsSync(resolved))
850
+ merge[name] = fs.readFileSync(resolved).toString("base64");
851
+ }
852
+ return Buffer.from(JSON.stringify({ entries: entries.toString("base64"), merge }));
853
+ }
854
+ function snapshotIndex(root, output, name) {
855
+ const bytes = indexEntries(root);
856
+ const value = JSON.parse(bytes.toString());
857
+ const objects = new Set();
858
+ for (const entry of Buffer.from(value.entries, "base64").toString("utf8").split("\0").filter(Boolean)) {
859
+ const match = /^\d{6} ([a-f0-9]{40,64}) [0-3]\t/.exec(entry);
860
+ if (!match)
861
+ throw new AppError("snapshot_index_invalid", "Malformed Git index entry", 1);
862
+ // Gitlinks belong to another repository and are preserved as index IDs.
863
+ if (!entry.startsWith("160000 "))
864
+ objects.add(match[1]);
865
+ }
866
+ for (const name of ["MERGE_HEAD", "ORIG_HEAD", "AUTO_MERGE"]) {
867
+ if (value.merge[name])
868
+ for (const oid of Buffer.from(value.merge[name], "base64").toString().trim().split("\n")) {
869
+ if (!/^[a-f0-9]{40,64}$/.test(oid))
870
+ throw new AppError("snapshot_index_invalid", "Malformed Git merge reference", 1);
871
+ objects.add(oid);
872
+ }
873
+ }
874
+ const payload = path.join(output, `${name}.index.patch`);
875
+ const pack = path.join(output, `${name}.index.pack`);
876
+ fs.writeFileSync(payload, bytes);
877
+ fs.writeFileSync(pack, gitBytes(root, ["pack-objects", "--stdout", "--revs"], Buffer.from([...objects].sort().join("\n") + "\n")));
878
+ return { index_format: "entries@1", index_sha256: fileHash(payload), index_objects_sha256: fileHash(pack) };
879
+ }
880
+ function gitBytes(root, args, input) {
881
+ const result = spawnSync("git", ["-C", root, ...args], { input, maxBuffer: 64 * 1024 * 1024 });
882
+ if (result.status !== 0)
883
+ throw new AppError("snapshot_index_invalid", "Could not preserve Git index objects", 1, { args, stderr: result.stderr?.toString().trim() });
884
+ return result.stdout;
885
+ }
886
+ function indexPatch(root) {
887
+ const result = spawnSync("git", ["-C", root, "diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "HEAD", "--", ".", ":(exclude)**/.env", ":(exclude)**/.env.*"], { maxBuffer: 64 * 1024 * 1024 });
888
+ if (result.status !== 0)
889
+ throw new AppError("snapshot_index_invalid", "Could not capture Git index", 1);
890
+ return result.stdout;
891
+ }
892
+ function restoreIndex(snapshot, name, metadata, root) {
893
+ if (!metadata.index_sha256)
894
+ return;
895
+ const file = path.join(snapshot, `${name}.index.patch`);
896
+ if (fileHash(file) !== metadata.index_sha256)
897
+ throw new AppError("snapshot_checksum_mismatch", "Snapshot Git index checksum does not match", 1);
898
+ if (metadata.index_format === "entries@1") {
899
+ const pack = path.join(snapshot, `${name}.index.pack`);
900
+ if (!metadata.index_objects_sha256 || fileHash(pack) !== metadata.index_objects_sha256)
901
+ throw new AppError("snapshot_checksum_mismatch", "Snapshot Git index object checksum does not match", 1);
902
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
903
+ gitBytes(root, ["unpack-objects"], fs.readFileSync(pack));
904
+ runGit(root, ["read-tree", "--empty"]);
905
+ gitBytes(root, ["update-index", "-z", "--index-info"], Buffer.from(value.entries, "base64"));
906
+ for (const name of mergeStateFiles) {
907
+ const target = git(root, ["rev-parse", "--git-path", name]);
908
+ if (!target)
909
+ throw new AppError("snapshot_index_invalid", "Could not locate restored Git merge state", 1);
910
+ if (value.merge[name] !== undefined)
911
+ fs.writeFileSync(path.resolve(root, target), Buffer.from(value.merge[name], "base64"));
912
+ else
913
+ fs.rmSync(path.resolve(root, target), { force: true });
914
+ }
915
+ return;
916
+ }
917
+ if (fs.statSync(file).size)
918
+ runGit(root, ["apply", "--cached", "--binary", file]);
919
+ }
920
+ export function verifyRecoverySnapshot(snapshot, input, checkWorkingState = true) {
921
+ const manifest = readManifest(snapshot);
922
+ if (manifest.purpose !== "recovery" || manifest.recovery_id !== input.recoveryId || manifest.run_id !== input.runId)
923
+ throw new AppError("recovery_capture_invalid", "Snapshot does not identify this recovery", 1);
924
+ const entries = [
925
+ { name: "project", root: input.projectRoot, hash: manifest.project_sha256, git: manifest.project_git, head: manifest.project_git.head },
926
+ ...(manifest.workspace.kind === "git_worktree" ? [{ name: "workspace", root: input.workspaceRoot, hash: manifest.workspace.sha256, git: manifest.workspace, head: manifest.workspace.base_ref }] : [])
927
+ ];
928
+ verifySnapshotPayload(snapshot, manifest);
929
+ for (const entry of entries) {
930
+ const allowed = manifest.project_payload_policy === "service-files@1" ? projectPayloadFilter(entry.root) : snapshotPayloadAllowed;
931
+ const expectedModes = manifest.payload_modes?.[entry.name];
932
+ if (checkWorkingState && expectedModes && treeModesHash(entry.root, allowed) !== expectedModes)
933
+ throw new AppError("recovery_workspace_drift", "Executable file modes changed after recovery capture", 1, { payload: entry.name });
934
+ if (checkWorkingState && (treeHash(entry.root, allowed) !== entry.hash || git(entry.root, ["rev-parse", "--verify", "HEAD"]) !== entry.head
935
+ || entry.head === null && git(entry.root, ["for-each-ref", "--format=%(refname)"]) !== ""
936
+ || 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)))
937
+ throw new AppError("recovery_workspace_drift", "Working files or Git state changed after recovery capture", 1, { payload: entry.name });
938
+ }
939
+ }
940
+ /** Reuse an already published boundary only after checking its identity and
941
+ * every payload, including its Git index objects. Never overwrite evidence. */
942
+ export function verifyControllerBoundarySnapshot(snapshot, input) {
943
+ const manifest = readManifest(snapshot), boundary = manifest.boundary_capture;
944
+ 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)
945
+ throw new AppError("controller_boundary_snapshot_invalid", "Published snapshot does not prove this controller boundary", 1, { snapshot });
946
+ verifySnapshotPayload(snapshot, manifest);
947
+ const file = path.join(snapshot, "snapshot.json");
948
+ if (input.manifestSha256 !== undefined && fileHash(file) !== input.manifestSha256)
949
+ throw new AppError("snapshot_checksum_mismatch", "Boundary manifest no longer matches its retained publication receipt", 1, { snapshot });
950
+ return { snapshot, manifest: file, manifest_sha256: fileHash(file), purpose: manifest.purpose, stage_entry: manifest.stage_entry };
951
+ }
952
+ function verifySnapshotPayload(snapshot, manifest) {
953
+ if (treeHash(path.join(snapshot, "runtime")) !== manifest.runtime_sha256)
954
+ throw new AppError("snapshot_checksum_mismatch", "Snapshot runtime checksum does not match", 1);
955
+ verifySnapshotModes(snapshot, manifest);
956
+ 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 }] : [])];
957
+ for (const payload of payloads)
958
+ verifyGitSnapshotPayload(snapshot, payload);
959
+ if (manifest.schema_id === "dd-flow/eval-run-snapshot@6") {
960
+ const db = new DatabaseSync(path.join(snapshot, "runtime", "db.sqlite"), { readOnly: true });
961
+ try {
962
+ const row = db.prepare("SELECT flow_kind, project_root, workspace_root FROM runs WHERE id=?").get(manifest.run_id);
963
+ if (!row || row.flow_kind !== "mb-init" || row.project_root !== manifest.project_root || row.workspace_root !== manifest.project_root)
964
+ throw new AppError("snapshot_invalid", "Unborn recovery must belong to its captured Memory RUN", 1, { snapshot });
965
+ }
966
+ finally {
967
+ db.close();
968
+ }
969
+ }
970
+ }
971
+ function verifyGitSnapshotPayload(snapshot, payload) {
972
+ const bundle = path.join(snapshot, `${payload.name}.bundle`);
973
+ const invalidBundle = payload.git.state === "unborn" ? payload.git.bundle_sha256 !== null || fs.existsSync(bundle)
974
+ : !fs.existsSync(bundle) || fileHash(bundle) !== payload.git.bundle_sha256;
975
+ if (treeHash(path.join(snapshot, payload.name)) !== payload.hash || invalidBundle || 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))
976
+ throw new AppError("snapshot_checksum_mismatch", "Snapshot payload or Git index checksum does not match", 1, { payload: payload.name });
335
977
  }
336
978
  function git(root, args) {
337
979
  const result = spawnSync("git", ["-C", root, ...args], { encoding: "utf8" });
@@ -343,12 +985,408 @@ function runGit(root, args) {
343
985
  throw new AppError("snapshot_workspace_restore_failed", "Could not restore feature worktree", 1, { stderr: result.stderr.trim(), args });
344
986
  }
345
987
  function samePath(left, right) { return path.resolve(left) === path.resolve(right); }
346
- function treeHash(root) {
988
+ function snapshotPayloadAllowed(source) {
989
+ const name = path.basename(source);
990
+ return ![".git", "node_modules", ".cache", ".npm", ".pnpm-store"].includes(name)
991
+ && localEnvironmentAllowed(source);
992
+ }
993
+ function projectPayloadFilter(root) {
994
+ const serviceAllowed = projectServicePathFilter(root);
995
+ return file => snapshotPayloadAllowed(file) && serviceAllowed(file);
996
+ }
997
+ function runtimePayloadAllowed(source) {
998
+ return snapshotPayloadAllowed(source) && !["auth.json", "auth.bk", "auth.encrypted", "auth.v2.key", "auth.v2.file", "credentials.json", ".credentials.json", "credentials", ".credentials", "id_rsa", "id_ed25519", "engines", "checkouts"].includes(path.basename(source));
999
+ }
1000
+ /** Only a Grok daemon's verified provider root is excluded from flow evidence.
1001
+ * An unrelated directory named grok-home remains ordinary project data. */
1002
+ function grokProviderHomes(runtimeRoot) {
1003
+ const homes = [];
1004
+ const visit = (directory) => {
1005
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1006
+ const file = path.join(directory, entry.name);
1007
+ if (entry.isDirectory()) {
1008
+ if (![".git", "node_modules", "grok-home"].includes(entry.name))
1009
+ visit(file);
1010
+ }
1011
+ else if (entry.isFile() && entry.name === "daemon.json") {
1012
+ let state;
1013
+ try {
1014
+ state = JSON.parse(fs.readFileSync(file, "utf8"));
1015
+ }
1016
+ catch {
1017
+ continue;
1018
+ }
1019
+ if (state.schema_id !== "dd-grok/daemon-state@1")
1020
+ continue;
1021
+ const expected = path.join(directory, "grok-home");
1022
+ if (state.config?.grokHome !== expected || state.config?.ddFlowHome !== runtimeRoot)
1023
+ throw new AppError("snapshot_native_scope_invalid", "Grok provider home differs from its retained daemon binding", 1, { state_dir: directory });
1024
+ homes.push(expected);
1025
+ }
1026
+ }
1027
+ };
1028
+ visit(runtimeRoot);
1029
+ return homes;
1030
+ }
1031
+ function nativeDaemonFile(file) {
1032
+ if (!fs.lstatSync(file, { throwIfNoEntry: false })?.isFile())
1033
+ return false;
1034
+ try {
1035
+ const state = JSON.parse(fs.readFileSync(file, "utf8"));
1036
+ return typeof state.daemon_id === "string" && (/^dd-(codex|zcode|grok|agy|opencode|droid)\/daemon-state@1$/.test(String(state.schema_id)) || state.schema_id === "dd-opencode/daemon-state@2");
1037
+ }
1038
+ catch {
1039
+ return false;
1040
+ } // Unrecognized files retain full-byte protection.
1041
+ }
1042
+ function sqliteFile(file) {
1043
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile())
1044
+ return false;
1045
+ const descriptor = fs.openSync(file, "r");
1046
+ try {
1047
+ const header = Buffer.alloc(16);
1048
+ return fs.readSync(descriptor, header, 0, 16, 0) === 16 && header.toString() === "SQLite format 3\0";
1049
+ }
1050
+ finally {
1051
+ fs.closeSync(descriptor);
1052
+ }
1053
+ }
1054
+ function sqliteIdentifier(value) { return `"${value.replaceAll('"', '""')}"`; }
1055
+ function sqliteValue(value) {
1056
+ if (value === null || typeof value === "string" || typeof value === "boolean")
1057
+ return value;
1058
+ if (typeof value === "number")
1059
+ return Number.isFinite(value) ? value : String(value);
1060
+ if (typeof value === "bigint")
1061
+ return `${value}n`;
1062
+ if (Buffer.isBuffer(value))
1063
+ return `blob:${value.toString("base64")}`;
1064
+ if (value instanceof Uint8Array)
1065
+ return `blob:${Buffer.from(value).toString("base64")}`;
1066
+ return String(value);
1067
+ }
1068
+ /**
1069
+ * SQLite page layout is not semantic identity: VACUUM, checkpoint and a
1070
+ * delete/insert rewrite can change serialized bytes without changing the
1071
+ * logical database. Snapshot only the schema and ordered logical row values.
1072
+ * This intentionally applies to the small set of managed SQLite files, not
1073
+ * to arbitrary provider databases.
1074
+ */
1075
+ function sqliteSemanticFingerprint(db) {
1076
+ db.exec("PRAGMA busy_timeout = 4000");
1077
+ db.exec("BEGIN");
1078
+ try {
1079
+ const schema = db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name, tbl_name, sql").all();
1080
+ const tables = schema.filter(row => row.type === "table").map(row => {
1081
+ const columns = db.prepare(`PRAGMA table_info(${sqliteIdentifier(row.name)})`).all()
1082
+ .sort((left, right) => Number(left.cid ?? 0) - Number(right.cid ?? 0))
1083
+ .map(column => ({ name: String(column.name ?? ""), type: String(column.type ?? ""), notnull: Number(column.notnull ?? 0), default: sqliteValue(column.dflt_value ?? null), pk: Number(column.pk ?? 0) }));
1084
+ const names = columns.map(column => column.name);
1085
+ const rows = db.prepare(`SELECT * FROM ${sqliteIdentifier(row.name)}`).all()
1086
+ .map(record => names.map(name => [name, sqliteValue(record[name])]))
1087
+ .sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
1088
+ return { name: row.name, columns, rows };
1089
+ });
1090
+ return crypto.createHash("sha256").update(JSON.stringify({ schema, tables })).digest("hex");
1091
+ }
1092
+ finally {
1093
+ try {
1094
+ db.exec("ROLLBACK");
1095
+ }
1096
+ catch { /* The read transaction may already have closed on provider error. */ }
1097
+ }
1098
+ }
1099
+ /** A WAL is copied through its SQLite read snapshot, not as raw bytes. */
1100
+ function runtimeSnapshotKind(file, excluded, providerHomes = []) {
1101
+ if (!runtimePayloadAllowed(file) || providerHomes.some(home => file === home || isInside(home, file)) || excluded.includes(file))
1102
+ return "excluded";
1103
+ if (fs.lstatSync(file).isFile()) {
1104
+ if (/-(?:wal|shm|journal)$/.test(file) && sqliteFile(file.replace(/-(?:wal|shm|journal)$/, "")))
1105
+ return "sidecar";
1106
+ if (sqliteFile(file))
1107
+ return "sqlite";
1108
+ }
1109
+ return "ordinary";
1110
+ }
1111
+ /** Productive writers are fenced separately. Compare the copied source set
1112
+ * without idle diagnostic appends; SQLite includes committed WAL pages without
1113
+ * mistaking a physical checkpoint for new logical content. */
1114
+ function snapshotSourceVersion(context, input, retainedDatabases, retainedJournals) {
1115
+ const databases = retainedDatabases ?? new Map();
1116
+ const journals = retainedJournals ?? new Map();
1117
+ const projectRoot = resolveProjectRoot(input.projectRoot);
1118
+ const project = requireProjectByRoot(context, projectRoot);
1119
+ const run = context.db.get("SELECT workspace_root FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
1120
+ if (!run)
1121
+ throw new AppError("not_found", "Snapshot RUN is not registered", 1);
1122
+ const entries = new Map();
1123
+ const diagnosticLogs = new Set(getResourceDatabase(resourceHome(context), "read_existing").all("SELECT stdout_path,stderr_path,metadata_json FROM managed_processes WHERE project_id=? AND run_id=? AND kind IN ('codex-daemon','zcode-daemon','grok-daemon','agy-daemon','opencode-daemon','droid-daemon')", [project.id, input.runId]).flatMap(row => {
1124
+ const directory = JSON.parse(row.metadata_json).state_dir;
1125
+ const log = typeof directory === "string" && path.isAbsolute(directory) ? path.join(directory, "daemon.log") : null;
1126
+ return log && isInside(context.ddFlowHome, log) && row.stdout_path === log && row.stderr_path === log ? [log] : [];
1127
+ }));
1128
+ const excluded = codexHomeSnapshotExclusions(context, project.id, input.runId);
1129
+ const providerHomes = input.recoveryId === undefined ? grokProviderHomes(context.ddFlowHome) : [];
1130
+ const observations = new Map();
1131
+ const operationRoots = new Set();
1132
+ const visit = (directory) => {
1133
+ const daemon = path.join(directory, "daemon.json");
1134
+ const native = nativeDaemonFile(daemon);
1135
+ if (native) {
1136
+ operationRoots.add(path.join(directory, "operations"));
1137
+ for (const operation of retainedDaemonOperations(directory))
1138
+ if (isObservationOperation(operation.operation))
1139
+ observations.set(path.join(directory, "operations", crypto.createHash("sha256").update(String(operation.operation_id)).digest("hex")), operation);
1140
+ }
1141
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1142
+ const file = path.join(directory, entry.name);
1143
+ // These diagnostic cuts are retained, but their creation cannot
1144
+ // invalidate a productive boundary. Unknown operations remain protected.
1145
+ if (observations.has(file))
1146
+ continue;
1147
+ const kind = runtimeSnapshotKind(file, excluded, providerHomes);
1148
+ if (kind === "excluded" || kind === "sidecar")
1149
+ continue;
1150
+ const key = `runtime/${path.relative(context.ddFlowHome, file)}`;
1151
+ const stat = fs.lstatSync(file);
1152
+ if (stat.isDirectory()) {
1153
+ if (!operationRoots.has(file))
1154
+ entries.set(key, "directory");
1155
+ visit(file);
1156
+ }
1157
+ else if (stat.isSymbolicLink())
1158
+ entries.set(key, `link:${fs.readlinkSync(file)}`);
1159
+ else if (native && file === daemon)
1160
+ entries.set(key, `daemon:${nativeInventoryVersion(directory)}:${stat.mode & 0o111}`);
1161
+ else if (kind === "sqlite") {
1162
+ // Their productive identities are checked by boundary.verify(). A
1163
+ // consistent backup is evidence, not a demand for global DB silence.
1164
+ if (file === context.db.path || file === path.join(resourceHome(context), "runtime.sqlite")) {
1165
+ entries.set(key, `managed-sqlite:${stat.mode & 0o111}`);
1166
+ continue;
1167
+ }
1168
+ let db = databases.get(file);
1169
+ if (!db) {
1170
+ db = new DatabaseSync(file, { readOnly: true });
1171
+ databases.set(file, db);
1172
+ }
1173
+ entries.set(key, `sqlite:${sqliteSemanticFingerprint(db)}:${stat.mode & 0o111}`);
1174
+ }
1175
+ else if (stat.isFile() && diagnosticLogs.has(file)) {
1176
+ // Daemon stdout/stderr can append while an otherwise settled Session is idle.
1177
+ // Keep its identity/mode fenced; the copied bytes remain sealed in the snapshot.
1178
+ entries.set(key, `diagnostic-log:${stat.dev}:${stat.ino}:${stat.mode & 0o111}`);
1179
+ }
1180
+ else if (stat.isFile() && (["adapter.events.jsonl", "events.jsonl", "model-observations.jsonl", "timeline.jsonl", "controller.log"].includes(path.basename(file)) || native && file === path.join(directory, "daemon.log"))) {
1181
+ const bytes = fs.readFileSync(file);
1182
+ let cut = journals.get(file);
1183
+ if (!cut && !retainedJournals) {
1184
+ const payload = bytes.subarray(0, bytes.lastIndexOf(10) + 1);
1185
+ cut = { payload, dev: stat.dev, ino: stat.ino, mode: stat.mode, sha256: crypto.createHash("sha256").update(payload).digest("hex") };
1186
+ journals.set(file, cut);
1187
+ }
1188
+ const valid = cut && cut.dev === stat.dev && cut.ino === stat.ino && bytes.length >= cut.payload.length && bytes.subarray(0, cut.payload.length).equals(cut.payload);
1189
+ entries.set(key, valid && cut ? `journal:${cut.sha256}:${cut.payload.length}:${stat.mode & 0o111}` : "journal:changed");
1190
+ }
1191
+ else if (stat.isFile())
1192
+ entries.set(key, `file:${crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex")}:${stat.mode & 0o111}`);
1193
+ }
1194
+ };
1195
+ try {
1196
+ visit(context.ddFlowHome);
1197
+ for (const root of new Set([projectRoot, run.workspace_root]))
1198
+ entries.set(`source/${root}`, JSON.stringify([
1199
+ treeHash(root, true), treeModesHash(root, true), git(root, ["symbolic-ref", "--quiet", "HEAD"]), git(root, ["rev-parse", "HEAD"]), indexEntries(root).toString("base64")
1200
+ ]));
1201
+ return { entries, databases, journals, observations, sha256: crypto.createHash("sha256").update(JSON.stringify([...entries].sort(([a], [b]) => a.localeCompare(b)))).digest("hex") };
1202
+ }
1203
+ catch (error) {
1204
+ if (!retainedDatabases)
1205
+ for (const db of databases.values())
1206
+ try {
1207
+ db.close();
1208
+ }
1209
+ catch { /* Preserve the original source error. */ }
1210
+ throw error;
1211
+ }
1212
+ }
1213
+ function snapshotSourceChanges(before, after) {
1214
+ return [...new Set([...before.keys(), ...after.keys()])].filter(key => before.get(key) !== after.get(key)).sort().slice(0, 8);
1215
+ }
1216
+ function snapshotSourceChangeProofs(before, after) {
1217
+ return snapshotSourceChanges(before, after).map(component => ({
1218
+ component,
1219
+ before: before.has(component) ? crypto.createHash("sha256").update(before.get(component)).digest("hex") : null,
1220
+ after: after.has(component) ? crypto.createHash("sha256").update(after.get(component)).digest("hex") : null
1221
+ }));
1222
+ }
1223
+ /** Managed Codex homes share host configuration, not owned snapshot payload. */
1224
+ function codexHomeSnapshotExclusions(context, projectId, runId) {
1225
+ const homes = new Set(context.db.all("SELECT target_home FROM codex_home_profiles WHERE project_id = ?", [projectId]).map(row => row.target_home));
1226
+ if (context.db.get("SELECT 1 FROM sqlite_schema WHERE name = 'run_controllers'")) {
1227
+ 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]))
1228
+ if (home)
1229
+ homes.add(home);
1230
+ }
1231
+ const excluded = [];
1232
+ for (const home of homes) {
1233
+ if (!path.isAbsolute(home) || !fs.existsSync(home) || fs.lstatSync(home).isSymbolicLink())
1234
+ continue;
1235
+ const marker = path.join(home, ".dd-flow-home.json");
1236
+ if (!fs.existsSync(marker) || fs.lstatSync(marker).isSymbolicLink())
1237
+ continue;
1238
+ const identity = JSON.parse(fs.readFileSync(marker, "utf8"));
1239
+ if (identity.managed_by !== "dd-flow-cli" || identity.project_id !== projectId || identity.target_home !== home || !identity.source_home || !path.isAbsolute(identity.source_home))
1240
+ continue;
1241
+ for (const entry of codexHomeSharedEntries) {
1242
+ const file = path.join(home, entry);
1243
+ // Skip only the exact links installed by initCodexHome, never arbitrary
1244
+ // external links or owned local files with the same convenient name.
1245
+ if (fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink() && fs.readlinkSync(file) === path.join(identity.source_home, entry))
1246
+ excluded.push(file);
1247
+ }
1248
+ excluded.push(path.join(home, "tmp"), path.join(home, ".tmp"));
1249
+ }
1250
+ return excluded;
1251
+ }
1252
+ /** Copy a dedicated home or scoped recovery tree, preserving SQLite WAL commits. */
1253
+ function copyRuntimeTree(source, destination, scoped = true, excluded = [], providerHomes = [], observationCuts) {
1254
+ if (fs.lstatSync(source).isSymbolicLink())
1255
+ throw new AppError("snapshot_runtime_symlink_outside_scope", "Recovery artifact roots must not be symbolic links", 1, { path: source });
1256
+ const root = physicalPath(source);
1257
+ if (isInside(root, physicalPath(destination)))
1258
+ throw new AppError("snapshot_output_inside_runtime", "Recovery output must be outside its source artifact tree", 1);
1259
+ const databases = [];
1260
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
1261
+ fs.cpSync(source, destination, {
1262
+ recursive: true, verbatimSymlinks: true,
1263
+ filter: file => {
1264
+ if (observationCuts && path.basename(path.dirname(file)) === "operations" && fs.lstatSync(file).isDirectory() && nativeDaemonFile(path.join(path.dirname(path.dirname(file)), "daemon.json"))) {
1265
+ let operations;
1266
+ try {
1267
+ operations = retainedDaemonOperations(path.dirname(path.dirname(file)));
1268
+ }
1269
+ catch (error) {
1270
+ if (error.code !== "ENOENT")
1271
+ throw error;
1272
+ throw new AppError("snapshot_source_changed", "Native operation was not fully published during capture", 1, { components: ["native_operation_publication"] });
1273
+ }
1274
+ const operation = operations.find(row => crypto.createHash("sha256").update(String(row.operation_id)).digest("hex") === path.basename(file));
1275
+ if (operation && isObservationOperation(operation.operation)) {
1276
+ if (!observationCuts.has(file))
1277
+ observationCuts.set(file, operation);
1278
+ return false;
1279
+ }
1280
+ }
1281
+ const kind = runtimeSnapshotKind(file, excluded, providerHomes);
1282
+ if (kind === "excluded" || kind === "sidecar")
1283
+ return false;
1284
+ const stat = fs.lstatSync(file);
1285
+ if (stat.isSymbolicLink()) {
1286
+ if (scoped && !isInside(root, physicalPath(file)))
1287
+ throw new AppError("snapshot_runtime_symlink_outside_scope", "Recovery artifact link leaves its owned tree", 1, { path: file });
1288
+ return true;
1289
+ }
1290
+ if (!stat.isDirectory() && !stat.isFile())
1291
+ return false;
1292
+ if (stat.isFile()) {
1293
+ if (kind === "sqlite") {
1294
+ databases.push(file);
1295
+ return false;
1296
+ }
1297
+ }
1298
+ return true;
1299
+ }
1300
+ });
1301
+ for (const file of databases) {
1302
+ const db = new DatabaseSync(file, { readOnly: true });
1303
+ try {
1304
+ const target = source === file ? destination : path.join(destination, path.relative(source, file));
1305
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1306
+ db.exec("PRAGMA busy_timeout = 4000");
1307
+ db.exec(`VACUUM INTO '${target.replace(/'/g, "''")}'`);
1308
+ }
1309
+ finally {
1310
+ db.close();
1311
+ }
1312
+ }
1313
+ }
1314
+ function captureRecoveryAuxiliary(context, captured, input) {
1315
+ const runtime = path.join(input.output, "runtime");
1316
+ const codexExclusions = codexHomeSnapshotExclusions(context, input.projectId, input.runId);
1317
+ const run = captured.db.get("SELECT run_root, project_root, workspace_root FROM runs WHERE project_id = ? AND id = ?", [input.projectId, input.runId]);
1318
+ const roots = [run.run_root, runtimeRunDir(context.ddFlowHome, input.projectId, input.runId)];
1319
+ for (const protocol of captured.db.all("SELECT id, state_path, plan_path FROM protocols")) {
1320
+ const directory = runtimeProtocolDir(context.ddFlowHome, input.projectId, protocol.id);
1321
+ if (!isInside(physicalPath(context.ddFlowHome), physicalPath(directory)))
1322
+ throw new AppError("snapshot_protocol_scope_invalid", "Protocol runtime leaves DD_FLOW_HOME", 1);
1323
+ if (fs.existsSync(directory)) {
1324
+ copyRuntimeTree(directory, path.join(runtime, path.relative(context.ddFlowHome, directory)), true, codexExclusions);
1325
+ roots.push(directory);
1326
+ }
1327
+ for (const file of [protocol.state_path, protocol.plan_path]) {
1328
+ if (!fs.existsSync(file) || roots.some(root => isInside(physicalPath(root), physicalPath(file))))
1329
+ continue;
1330
+ if (isInside(physicalPath(context.ddFlowHome), physicalPath(file)) && fs.statSync(file).isFile())
1331
+ copyRuntimeTree(file, path.join(runtime, path.relative(context.ddFlowHome, file)));
1332
+ else if (![run.project_root, run.workspace_root].some(root => isInside(physicalPath(root), physicalPath(file))))
1333
+ throw new AppError("snapshot_protocol_scope_invalid", "Protocol evidence is outside captured payloads", 1, { path: file });
1334
+ }
1335
+ }
1336
+ const homes = new Set([context.ddFlowHome, resourceHome(context)]);
1337
+ const queries = {
1338
+ 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')",
1339
+ run_control_workers: "SELECT resource_home AS home FROM run_control_workers",
1340
+ work_launches: "SELECT json_extract(profile_json, '$.runtime_adapter.owner.resource_home') AS home FROM work_launches",
1341
+ merge_requests: "SELECT json_extract(adapter_receipt_json, '$.owner.resource_home') AS home FROM merge_requests",
1342
+ run_recovery_guards: "SELECT value AS home FROM run_recovery_guards, json_each(settlement_json, '$.resource_homes')"
1343
+ };
1344
+ 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) : []);
1345
+ for (const { home } of references) {
1346
+ if (home === null)
1347
+ continue;
1348
+ if (typeof home !== "string" || !path.isAbsolute(home))
1349
+ throw new AppError("snapshot_resource_scope_invalid", "Retained resource home must be an absolute path", 1);
1350
+ homes.add(home);
1351
+ }
1352
+ const nativeCaptures = new Map();
1353
+ const registries = [];
1354
+ for (const home of [...homes].sort()) {
1355
+ if (!path.isAbsolute(home))
1356
+ throw new AppError("snapshot_resource_scope_invalid", "Resource home must be an absolute path", 1);
1357
+ const evidence = readRecoveryResourceEvidence(home, input.projectId, input.runId, { db: captured.db, ddFlowHome: context.ddFlowHome });
1358
+ for (const process of evidence.processes) {
1359
+ const directory = JSON.parse(process.metadata_json).state_dir;
1360
+ if (directory === undefined)
1361
+ continue;
1362
+ if (typeof directory !== "string" || !path.isAbsolute(directory))
1363
+ throw new AppError("snapshot_native_scope_invalid", "Native artifact root must be absolute", 1);
1364
+ if (roots.some(root => isInside(physicalPath(root), physicalPath(directory))) || nativeCaptures.has(directory))
1365
+ continue;
1366
+ const state = JSON.parse(fs.readFileSync(path.join(directory, "daemon.json"), "utf8"));
1367
+ const owner = state.config?.runtime_owner;
1368
+ 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)
1369
+ throw new AppError("snapshot_native_scope_invalid", "External native artifact root has no matching RUN owner", 1, { state_dir: directory });
1370
+ const relative = path.join("native-evidence", crypto.createHash("sha256").update(directory).digest("hex"));
1371
+ copyRuntimeTree(directory, path.join(runtime, relative), true, codexExclusions);
1372
+ nativeCaptures.set(directory, relative);
1373
+ }
1374
+ const relative = path.join("resource-evidence", `${crypto.createHash("sha256").update(home).digest("hex")}.json`);
1375
+ fs.mkdirSync(path.dirname(path.join(runtime, relative)), { recursive: true });
1376
+ writeJson(path.join(runtime, relative), evidence);
1377
+ registries.push(relative);
1378
+ }
1379
+ 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 })) });
1380
+ }
1381
+ function treeHash(root, filtered = false) {
347
1382
  const hash = crypto.createHash("sha256");
1383
+ const allowed = typeof filtered === "function" ? filtered : filtered ? projectPayloadFilter(root) : () => true;
348
1384
  const visit = (dir, relative) => {
349
1385
  for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
350
1386
  const file = path.join(dir, entry.name);
351
1387
  const rel = path.join(relative, entry.name);
1388
+ if (!allowed(file))
1389
+ continue;
352
1390
  if (entry.isDirectory())
353
1391
  visit(file, rel);
354
1392
  else if (entry.isFile()) {
@@ -364,15 +1402,72 @@ function treeHash(root) {
364
1402
  visit(root, "");
365
1403
  return hash.digest("hex");
366
1404
  }
1405
+ function treeModesHash(root, filtered = false) {
1406
+ const entries = [];
1407
+ const allowed = typeof filtered === "function" ? filtered : filtered ? projectPayloadFilter(root) : () => true;
1408
+ const visit = (directory) => {
1409
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1410
+ const file = path.join(directory, entry.name);
1411
+ if (!allowed(file))
1412
+ continue;
1413
+ if (entry.isDirectory())
1414
+ visit(file);
1415
+ else if (entry.isFile())
1416
+ entries.push([path.relative(root, file), fs.statSync(file).mode & 0o111]);
1417
+ }
1418
+ };
1419
+ visit(root);
1420
+ return crypto.createHash("sha256").update(JSON.stringify(entries)).digest("hex");
1421
+ }
1422
+ function verifySnapshotModes(snapshot, manifest) {
1423
+ if (!manifest.payload_modes)
1424
+ return; // Legacy snapshots did not attest modes.
1425
+ for (const name of ["project", "runtime", ...(manifest.workspace.kind === "git_worktree" ? ["workspace"] : [])]) {
1426
+ if (treeModesHash(path.join(snapshot, name)) !== manifest.payload_modes[name])
1427
+ throw new AppError("snapshot_checksum_mismatch", "Snapshot executable modes do not match manifest", 1, { payload: name });
1428
+ }
1429
+ }
367
1430
  function fileHash(file) { return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
1431
+ // Flush children before their directory entries, then publish and flush the
1432
+ // parent. Never follow snapshot symlinks into the original project tree.
1433
+ function syncSnapshotTree(root) {
1434
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
1435
+ const file = path.join(root, entry.name);
1436
+ if (entry.isDirectory())
1437
+ syncSnapshotTree(file);
1438
+ else if (entry.isFile())
1439
+ syncPath(file);
1440
+ }
1441
+ syncPath(root);
1442
+ }
1443
+ function syncPath(file) {
1444
+ const descriptor = fs.openSync(file, "r");
1445
+ try {
1446
+ fs.fsyncSync(descriptor);
1447
+ }
1448
+ finally {
1449
+ fs.closeSync(descriptor);
1450
+ }
1451
+ }
368
1452
  function readManifest(snapshot) {
369
1453
  const file = path.join(snapshot, "snapshot.json");
370
1454
  if (!fs.existsSync(file))
371
1455
  throw new AppError("snapshot_missing", "Snapshot manifest is missing", 1, { snapshot });
372
1456
  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 === "candidate" && value.stage_entry !== null) || !value.runtime_sha256 || !value.project_sha256 || !value.project_git || !value.workspace)
1457
+ if (!["dd-flow/eval-run-snapshot@5", "dd-flow/eval-run-snapshot@6"].includes(String(value.schema_id)) || !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
1458
  throw new AppError("snapshot_invalid", "Snapshot manifest is invalid", 1, { snapshot });
375
- if (!value.project_git.branch || !value.project_git.head || !value.project_git.bundle_sha256)
1459
+ if (value.runtime_payload_policy !== undefined && (value.runtime_payload_policy !== "flow-evidence@1" || value.purpose === "recovery"))
1460
+ throw new AppError("snapshot_invalid", "Snapshot runtime payload policy is invalid for its purpose", 1, { snapshot });
1461
+ const unborn = value.schema_id === "dd-flow/eval-run-snapshot@6";
1462
+ if (!value.project_git.branch || (unborn
1463
+ ? value.purpose !== "recovery" || value.workspace.kind !== "project" || value.project_git.state !== "unborn"
1464
+ || value.project_git.head !== null || value.project_git.bundle_sha256 !== null
1465
+ || value.project_git.index_format !== "entries@1" || !/^[a-f0-9]{64}$/.test(value.project_git.index_sha256 ?? "")
1466
+ || !/^[a-f0-9]{64}$/.test(value.project_git.index_objects_sha256 ?? "")
1467
+ || Object.keys(value.project_git).sort().join() !== "branch,bundle_sha256,head,index_format,index_objects_sha256,index_sha256,state"
1468
+ || typeof value.project_git.branch !== "string"
1469
+ || spawnSync("git", ["check-ref-format", "--branch", value.project_git.branch], { encoding: "utf8" }).status !== 0
1470
+ : value.project_git.state !== undefined || !value.project_git.head || !value.project_git.bundle_sha256))
376
1471
  throw new AppError("snapshot_invalid", "Snapshot project Git metadata is incomplete", 1, { snapshot });
377
1472
  if (value.workspace.kind === "git_worktree" && (!value.workspace.branch || !value.workspace.base_ref || !value.workspace.bundle_sha256))
378
1473
  throw new AppError("snapshot_invalid", "Snapshot worktree manifest is incomplete", 1, { snapshot });
@@ -383,7 +1478,11 @@ function readBootstrapManifest(snapshot) {
383
1478
  if (!fs.existsSync(file))
384
1479
  throw new AppError("snapshot_missing", "Bootstrap snapshot manifest is missing", 1, { snapshot });
385
1480
  const value = JSON.parse(fs.readFileSync(file, "utf8"));
386
- if (value.schema_id !== "dd-eval/bootstrap-snapshot@1" || value.stage !== "specify" || !value.project_root || !value.project_sha256 || !value.project_git?.branch || !value.project_git.head || !value.project_git.bundle_sha256)
1481
+ const validBoundary = value.schema_id === "dd-eval/bootstrap-snapshot@1" ? value.stage === "specify" && value.flow === undefined
1482
+ : value.schema_id === "dd-eval/bootstrap-snapshot@2" && value.flow?.id === "mb-init" && value.stage === "preflight"
1483
+ && Object.keys(value.flow).sort().join() === "descriptor_sha256,id,source_sha256"
1484
+ && /^[a-f0-9]{64}$/.test(value.flow.source_sha256) && /^[a-f0-9]{64}$/.test(value.flow.descriptor_sha256);
1485
+ if (!validBoundary || !value.project_root || !value.project_sha256 || !value.project_git?.branch || !value.project_git.head || !value.project_git.bundle_sha256)
387
1486
  throw new AppError("snapshot_invalid", "Bootstrap snapshot manifest is invalid", 1, { snapshot });
388
1487
  return value;
389
1488
  }