@deksden-com/dd-flow-cli 0.9.0-beta.15 → 0.9.0-beta.150

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 (557) hide show
  1. package/CHANGELOG.md +895 -0
  2. package/README.md +140 -6
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/argument-values.js +38 -0
  5. package/dist/cli/command-inputs.js +386 -0
  6. package/dist/cli/command-metadata.js +232 -0
  7. package/dist/cli/command-option-descriptions.js +192 -0
  8. package/dist/cli/completion-cli.js +70 -0
  9. package/dist/cli/completion.js +57 -0
  10. package/dist/cli/diagnostic-invocation.js +46 -0
  11. package/dist/cli/diagnostic.js +120 -0
  12. package/dist/cli/error-output.js +52 -0
  13. package/dist/cli/executor-onboarding.js +76 -0
  14. package/dist/cli/flows.js +29 -0
  15. package/dist/cli/harnesses.js +84 -0
  16. package/dist/cli/help.js +396 -19
  17. package/dist/cli/hook-ingress.js +102 -0
  18. package/dist/cli/input-preparation.js +165 -0
  19. package/dist/cli/memory-flow-admission.js +50 -0
  20. package/dist/cli/memory-init-invocation.js +85 -0
  21. package/dist/cli/memory-init.js +249 -0
  22. package/dist/cli/memory-storage-admission.js +54 -0
  23. package/dist/cli/memory-storage-qualification.js +105 -0
  24. package/dist/cli/memory-storage-transition.js +123 -0
  25. package/dist/cli/memory-upgrade.js +189 -0
  26. package/dist/cli/models.js +39 -0
  27. package/dist/cli/native-hook-ingress.js +90 -0
  28. package/dist/cli/native-hook-preparation.js +55 -0
  29. package/dist/cli/operator-profiles.js +61 -0
  30. package/dist/cli/output-options.js +35 -0
  31. package/dist/cli/response-file.js +72 -0
  32. package/dist/cli/run-cli.js +1734 -550
  33. package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
  34. package/dist/cli/runtime-maintenance-ingress.js +52 -0
  35. package/dist/cli/runtime-process.js +153 -0
  36. package/dist/cli/setup.js +150 -0
  37. package/dist/cli.js +89 -2
  38. package/dist/domain/diagnostic-aspects.js +103 -0
  39. package/dist/domain/diagnostic-flows.js +8 -0
  40. package/dist/domain/stage-catalog.js +1 -1
  41. package/dist/domain/stage-handler-identities.js +28 -0
  42. package/dist/harness-runtime/DD-ZCODE.md +112 -0
  43. package/dist/harness-runtime/OPENCODE-LICENSE.txt +24 -0
  44. package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
  45. package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
  46. package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
  47. package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
  48. package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
  49. package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
  50. package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
  51. package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
  52. package/dist/harness-runtime/lib/agy-error-boundary.mjs +58 -0
  53. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  54. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  55. package/dist/harness-runtime/lib/agy-native-inspection.mjs +216 -0
  56. package/dist/harness-runtime/lib/agy-native_pb.js +117 -0
  57. package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
  58. package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
  59. package/dist/harness-runtime/lib/daemon-operations.d.mts +2 -0
  60. package/dist/harness-runtime/lib/daemon-operations.mjs +462 -0
  61. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  62. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +1096 -0
  63. package/dist/harness-runtime/lib/dd-agy.mjs +86 -0
  64. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  65. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +231 -0
  66. package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
  67. package/dist/harness-runtime/lib/dd-codex.mjs +954 -0
  68. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +141 -0
  69. package/dist/harness-runtime/lib/dd-droid.mjs +626 -0
  70. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +555 -0
  71. package/dist/harness-runtime/lib/dd-grok.mjs +180 -0
  72. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +622 -0
  73. package/dist/harness-runtime/lib/dd-opencode.mjs +390 -0
  74. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +752 -0
  75. package/dist/harness-runtime/lib/dd-zcode.mjs +1175 -0
  76. package/dist/harness-runtime/lib/delegation-instructions.d.mts +14 -0
  77. package/dist/harness-runtime/lib/delegation-instructions.mjs +157 -0
  78. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  79. package/dist/harness-runtime/lib/driver-recovery.mjs +140 -0
  80. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  81. package/dist/harness-runtime/lib/entity-references.d.mts +2 -0
  82. package/dist/harness-runtime/lib/entity-references.mjs +9 -0
  83. package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
  84. package/dist/harness-runtime/lib/lease-renewal.mjs +37 -0
  85. package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
  86. package/dist/harness-runtime/lib/lifecycle-command.mjs +273 -0
  87. package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
  88. package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
  89. package/dist/harness-runtime/lib/managed-daemon.d.mts +16 -0
  90. package/dist/harness-runtime/lib/managed-daemon.mjs +698 -0
  91. package/dist/harness-runtime/lib/managed-flow-env.mjs +15 -0
  92. package/dist/harness-runtime/lib/model-observations.mjs +101 -0
  93. package/dist/harness-runtime/lib/native-children.d.mts +23 -0
  94. package/dist/harness-runtime/lib/native-children.mjs +219 -0
  95. package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
  96. package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
  97. package/dist/harness-runtime/lib/native-request-proof.d.mts +2 -0
  98. package/dist/harness-runtime/lib/native-request-proof.mjs +65 -0
  99. package/dist/harness-runtime/lib/native-streams.mjs +45 -0
  100. package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
  101. package/dist/harness-runtime/lib/observation-clock.mjs +95 -0
  102. package/dist/harness-runtime/lib/opencode-plugin.mjs +85 -0
  103. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  104. package/dist/harness-runtime/lib/operation-errors.d.mts +16 -0
  105. package/dist/harness-runtime/lib/operation-errors.mjs +127 -0
  106. package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
  107. package/dist/harness-runtime/lib/operation-progress.mjs +114 -0
  108. package/dist/harness-runtime/lib/process-json.d.mts +5 -0
  109. package/dist/harness-runtime/lib/process-json.mjs +201 -0
  110. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  111. package/dist/harness-runtime/lib/provider-overload-policy.d.mts +15 -0
  112. package/dist/harness-runtime/lib/provider-overload-policy.mjs +151 -0
  113. package/dist/harness-runtime/lib/runner-events.mjs +202 -0
  114. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  115. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  116. package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
  117. package/dist/harness-runtime/lib/setup-progress.mjs +53 -0
  118. package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
  119. package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
  120. package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
  121. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-1y4a697q.js +81 -0
  122. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-2ny4vxct.js +92 -0
  123. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-6mptkzbc.js +0 -0
  124. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-7x67cf1q.js +52 -0
  125. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-9rqn6x4v.js +16 -0
  126. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-9vdz0zwn.js +1661 -0
  127. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ecs5ftka.js +1466 -0
  128. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-frbwqjmf.js +145 -0
  129. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-gne7h7mq.js +50 -0
  130. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-gx9wnkzr.js +105 -0
  131. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-m2eywc8w.js +0 -0
  132. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-nwcpakzx.js +12 -0
  133. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-q4g3afnw.js +623 -0
  134. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-qav6mfdz.js +0 -0
  135. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-sxt88q69.js +12 -0
  136. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-t1xa31vm.js +39 -0
  137. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ve4aws36.js +103 -0
  138. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vmytr4q8.js +4 -0
  139. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vt9jbch8.js +36 -0
  140. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vyas3vgt.js +0 -0
  141. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-wjyeq25y.js +30 -0
  142. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-xgnj2w4v.js +20 -0
  143. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-y2etg5bs.js +9 -0
  144. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ydhz1zrh.js +238 -0
  145. package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-z6qdwcsf.js +62 -0
  146. package/dist/harness-runtime/vendor/opencode-client/contract.d.ts +1 -0
  147. package/dist/harness-runtime/vendor/opencode-client/contract.js +12 -0
  148. package/dist/harness-runtime/vendor/opencode-client/effect/api/api.d.ts +2806 -0
  149. package/dist/harness-runtime/vendor/opencode-client/effect/api/api.js +0 -0
  150. package/dist/harness-runtime/vendor/opencode-client/effect/api.d.ts +4 -0
  151. package/dist/harness-runtime/vendor/opencode-client/effect/api.js +0 -0
  152. package/dist/harness-runtime/vendor/opencode-client/effect/client.d.ts +2530 -0
  153. package/dist/harness-runtime/vendor/opencode-client/effect/client.js +15 -0
  154. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client-error.d.ts +7 -0
  155. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client-error.js +6 -0
  156. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client.d.ts +2529 -0
  157. package/dist/harness-runtime/vendor/opencode-client/effect/generated/client.js +8 -0
  158. package/dist/harness-runtime/vendor/opencode-client/effect/generated/index.d.ts +2 -0
  159. package/dist/harness-runtime/vendor/opencode-client/effect/generated/index.js +12 -0
  160. package/dist/harness-runtime/vendor/opencode-client/effect/index.d.ts +35 -0
  161. package/dist/harness-runtime/vendor/opencode-client/effect/index.js +75 -0
  162. package/dist/harness-runtime/vendor/opencode-client/effect/rpc.d.ts +20 -0
  163. package/dist/harness-runtime/vendor/opencode-client/effect/rpc.js +11 -0
  164. package/dist/harness-runtime/vendor/opencode-client/effect/service.d.ts +90 -0
  165. package/dist/harness-runtime/vendor/opencode-client/effect/service.js +187 -0
  166. package/dist/harness-runtime/vendor/opencode-client/package.json +84 -0
  167. package/dist/harness-runtime/vendor/opencode-client/promise/api.d.ts +21 -0
  168. package/dist/harness-runtime/vendor/opencode-client/promise/api.js +0 -0
  169. package/dist/harness-runtime/vendor/opencode-client/promise/client.d.ts +252 -0
  170. package/dist/harness-runtime/vendor/opencode-client/promise/client.js +14 -0
  171. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client-error.d.ts +8 -0
  172. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client-error.js +6 -0
  173. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client.d.ts +259 -0
  174. package/dist/harness-runtime/vendor/opencode-client/promise/generated/client.js +7 -0
  175. package/dist/harness-runtime/vendor/opencode-client/promise/generated/index.d.ts +3 -0
  176. package/dist/harness-runtime/vendor/opencode-client/promise/generated/index.js +79 -0
  177. package/dist/harness-runtime/vendor/opencode-client/promise/generated/types.d.ts +8932 -0
  178. package/dist/harness-runtime/vendor/opencode-client/promise/generated/types.js +70 -0
  179. package/dist/harness-runtime/vendor/opencode-client/promise/index.d.ts +6 -0
  180. package/dist/harness-runtime/vendor/opencode-client/promise/index.js +83 -0
  181. package/dist/harness-runtime/vendor/opencode-client/promise/rpc.d.ts +32 -0
  182. package/dist/harness-runtime/vendor/opencode-client/promise/rpc.js +7 -0
  183. package/dist/harness-runtime/vendor/opencode-client/promise/service.d.ts +24 -0
  184. package/dist/harness-runtime/vendor/opencode-client/promise/service.js +187 -0
  185. package/dist/harness-runtime/vendor/opencode-client/pty-handoff.d.ts +12 -0
  186. package/dist/harness-runtime/vendor/opencode-client/pty-handoff.js +14 -0
  187. package/dist/harness-runtime/vendor/opencode-client/rpc-runtime.d.ts +20 -0
  188. package/dist/harness-runtime/vendor/opencode-client/rpc-runtime.js +14 -0
  189. package/dist/harness-runtime/vendor/opencode-client/service-contender.d.ts +37 -0
  190. package/dist/harness-runtime/vendor/opencode-client/service-contender.js +10 -0
  191. package/dist/harness-runtime/vendor/opencode-client/service-probe.d.ts +70 -0
  192. package/dist/harness-runtime/vendor/opencode-client/service-probe.js +16 -0
  193. package/dist/harness-runtime/vendor/opencode-client/service-timing.d.ts +12 -0
  194. package/dist/harness-runtime/vendor/opencode-client/service-timing.js +10 -0
  195. package/dist/harness-runtime/vendor/opencode-client/service-version.d.ts +2 -0
  196. package/dist/harness-runtime/vendor/opencode-client/service-version.js +6 -0
  197. package/dist/harness-runtime/vendor/opencode-client/service.d.ts +52 -0
  198. package/dist/harness-runtime/vendor/opencode-client/service.js +1 -0
  199. package/dist/harness-runtime/vendor/opencode-client/shared-events.d.ts +11 -0
  200. package/dist/harness-runtime/vendor/opencode-client/shared-events.js +8 -0
  201. package/dist/harness-runtime/vendor/opencode-client/solid/connection.d.ts +37 -0
  202. package/dist/harness-runtime/vendor/opencode-client/solid/connection.js +10 -0
  203. package/dist/harness-runtime/vendor/opencode-client/solid/data.d.ts +211 -0
  204. package/dist/harness-runtime/vendor/opencode-client/solid/data.js +18 -0
  205. package/dist/harness-runtime/vendor/opencode-client/solid/index.d.ts +3 -0
  206. package/dist/harness-runtime/vendor/opencode-client/solid/index.js +32 -0
  207. package/dist/harness-runtime/vendor/opencode-client/solid/pty.d.ts +22 -0
  208. package/dist/harness-runtime/vendor/opencode-client/solid/pty.js +8 -0
  209. package/dist/harness-runtime/vendor/opencode-plugin.mjs +3 -0
  210. package/dist/protocol/local-files.js +18 -9
  211. package/dist/runtime/context.js +8 -4
  212. package/dist/schemas/agent-profile.schema.json +1 -1
  213. package/dist/schemas/code-review-decision.schema.json +9 -0
  214. package/dist/schemas/code-review-result.schema.json +1 -1
  215. package/dist/schemas/code-verification.schema.json +7 -5
  216. package/dist/schemas/code-work-batch.schema.json +2 -2
  217. package/dist/schemas/diagnostic-stage-result.schema.json +354 -0
  218. package/dist/schemas/diagnostic-work-result.schema.json +296 -0
  219. package/dist/schemas/discovery-result.schema.json +184 -0
  220. package/dist/schemas/execution-bundle.schema.json +211 -0
  221. package/dist/schemas/execution-settings.schema.json +162 -0
  222. package/dist/schemas/flow-descriptor.schema.json +54 -0
  223. package/dist/schemas/flow-run.schema.json +29 -0
  224. package/dist/schemas/harness-catalog.schema.json +80 -0
  225. package/dist/schemas/mb-init-compose-result.schema.json +457 -0
  226. package/dist/schemas/mb-init-discover-result.schema.json +500 -0
  227. package/dist/schemas/mb-init-finish-result.schema.json +422 -0
  228. package/dist/schemas/mb-init-preflight-result.schema.json +367 -0
  229. package/dist/schemas/mb-init-review-result.schema.json +396 -0
  230. package/dist/schemas/mb-init-verify-result.schema.json +391 -0
  231. package/dist/schemas/mb-upgrade-stage-result.schema.json +863 -0
  232. package/dist/schemas/memory-bootstrap-receipt-v2.schema.json +67 -0
  233. package/dist/schemas/memory-bootstrap-receipt.schema.json +354 -0
  234. package/dist/schemas/memory-composition-work-result.schema.json +38 -0
  235. package/dist/schemas/memory-repair-work-result.schema.json +56 -0
  236. package/dist/schemas/memory-review-correction-plan.schema.json +30 -0
  237. package/dist/schemas/memory-review-work-result.schema.json +43 -0
  238. package/dist/schemas/model-catalog.schema.json +153 -0
  239. package/dist/schemas/plan-review-decision.schema.json +12 -3
  240. package/dist/schemas/plan-review-result.schema.json +2 -2
  241. package/dist/schemas/profile-settings.schema.json +122 -0
  242. package/dist/schemas/project-flow-pack-manifest.schema.json +1 -1
  243. package/dist/schemas/release-impact.schema.json +3 -3
  244. package/dist/schemas/release-manifest.schema.json +291 -0
  245. package/dist/schemas/run-control-receipt.schema.json +118 -0
  246. package/dist/schemas/run-control-request.schema.json +36 -0
  247. package/dist/schemas/run-engine-binding.schema.json +1 -1
  248. package/dist/schemas/stage-start-response.schema.json +4 -0
  249. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  250. package/dist/services/accepted-intent.js +139 -0
  251. package/dist/services/branch-context.js +3 -3
  252. package/dist/services/canon.js +54 -15
  253. package/dist/services/check-environment.js +21 -0
  254. package/dist/services/check-runner-evidence.js +562 -0
  255. package/dist/services/cleanup.js +133 -40
  256. package/dist/services/cli-operation-classifier.js +26 -63
  257. package/dist/services/cli-upgrade-allowlist.js +27 -0
  258. package/dist/services/code-checks.js +1398 -119
  259. package/dist/services/codex-hook-delivery.js +32 -0
  260. package/dist/services/command-context.js +80 -0
  261. package/dist/services/compatibility-preflight.js +16 -3
  262. package/dist/services/config.js +11 -8
  263. package/dist/services/continuation-outcome.js +20 -0
  264. package/dist/services/controller-child-capacity.js +13 -0
  265. package/dist/services/controller-child-observer.js +115 -0
  266. package/dist/services/controller-execution.js +94 -0
  267. package/dist/services/controller-fanout.js +226 -0
  268. package/dist/services/controller-memory-task.js +45 -0
  269. package/dist/services/controller-memory-worker.js +49 -0
  270. package/dist/services/dashboard.js +143 -58
  271. package/dist/services/descriptor-coordinator-session.js +35 -0
  272. package/dist/services/descriptor-root-work.js +53 -0
  273. package/dist/services/descriptor-run-settlement.js +107 -0
  274. package/dist/services/descriptor-run-start.js +475 -0
  275. package/dist/services/descriptor-stage-coordinator.js +250 -0
  276. package/dist/services/descriptor-stage-settlement.js +223 -0
  277. package/dist/services/descriptor-stage-start.js +175 -0
  278. package/dist/services/diagnostic-evidence.js +73 -0
  279. package/dist/services/diagnostic-report-publication.js +72 -0
  280. package/dist/services/diagnostic-report.js +67 -0
  281. package/dist/services/diagnostic-run-bundle.js +74 -0
  282. package/dist/services/diagnostic-snapshot.js +159 -0
  283. package/dist/services/diagnostic-stage-handlers.js +108 -0
  284. package/dist/services/diagnostic-stage-results.js +132 -0
  285. package/dist/services/diagnostic-start.js +84 -0
  286. package/dist/services/diagnostic-work-batch.js +34 -0
  287. package/dist/services/diagnostic-work-collection.js +97 -0
  288. package/dist/services/diagnostic-work-registration.js +101 -0
  289. package/dist/services/diagnostic-work-results.js +93 -0
  290. package/dist/services/discovery/agy-discovery.js +2 -0
  291. package/dist/services/discovery/codex-discovery.js +2 -0
  292. package/dist/services/discovery/droid-discovery.js +2 -0
  293. package/dist/services/discovery/grok-discovery.js +2 -0
  294. package/dist/services/discovery/opencode-discovery.js +2 -0
  295. package/dist/services/discovery/static.js +31 -0
  296. package/dist/services/discovery/zcode-discovery.js +2 -0
  297. package/dist/services/engines.js +354 -163
  298. package/dist/services/eval-snapshots.js +1316 -150
  299. package/dist/services/execution-bundles.js +275 -0
  300. package/dist/services/execution-policy.js +185 -0
  301. package/dist/services/executor-onboarding.js +56 -0
  302. package/dist/services/external-work-launch.js +310 -0
  303. package/dist/services/flow-catalog.js +30 -0
  304. package/dist/services/flow-descriptors.js +82 -0
  305. package/dist/services/frozen-engine.js +387 -0
  306. package/dist/services/generic-execution.js +164 -0
  307. package/dist/services/harness-adapter.js +355 -36
  308. package/dist/services/harness-config.js +2 -0
  309. package/dist/services/harness-discovery.js +29 -0
  310. package/dist/services/harness-doctor.js +75 -0
  311. package/dist/services/harness-probe-effects.js +51 -0
  312. package/dist/services/harness-version-probe.js +100 -0
  313. package/dist/services/hook-memory-routing.js +188 -0
  314. package/dist/services/hook-recovery-guard.js +14 -0
  315. package/dist/services/hook-session-observation.js +24 -0
  316. package/dist/services/hooks.js +791 -326
  317. package/dist/services/hybrid-contracts.js +474 -0
  318. package/dist/services/hybrid-digest.js +14 -0
  319. package/dist/services/ids.js +29 -1
  320. package/dist/services/installation-lock.js +95 -0
  321. package/dist/services/installed-flow-source.js +226 -0
  322. package/dist/services/lanes.js +78 -65
  323. package/dist/services/lifecycle-command.js +1 -288
  324. package/dist/services/lifecycle-contract.js +1 -0
  325. package/dist/services/lifecycle-invocations.js +2148 -0
  326. package/dist/services/managed-daemon-binding.js +38 -0
  327. package/dist/services/managed-lease-monitor.js +133 -0
  328. package/dist/services/managed-processes.js +449 -69
  329. package/dist/services/memory-accepted-composition.js +78 -0
  330. package/dist/services/memory-baseline-preservation.js +65 -0
  331. package/dist/services/memory-completed-correction-wave.js +328 -0
  332. package/dist/services/memory-compose-handler.js +400 -0
  333. package/dist/services/memory-composition-acceptance.js +375 -0
  334. package/dist/services/memory-composition-graph.js +165 -0
  335. package/dist/services/memory-composition-registration.js +161 -0
  336. package/dist/services/memory-composition-work-custody.js +156 -0
  337. package/dist/services/memory-composition-work-results.js +108 -0
  338. package/dist/services/memory-corrected-review-acceptance.js +129 -0
  339. package/dist/services/memory-corrected-review-batch.js +37 -0
  340. package/dist/services/memory-corrected-review-findings.js +108 -0
  341. package/dist/services/memory-corrected-review-inputs.js +215 -0
  342. package/dist/services/memory-corrected-review-projection.js +78 -0
  343. package/dist/services/memory-corrected-review-receipt.js +178 -0
  344. package/dist/services/memory-corrected-review-registration.js +192 -0
  345. package/dist/services/memory-correction-check-receipt.js +235 -0
  346. package/dist/services/memory-correction-input-owner.js +6 -0
  347. package/dist/services/memory-custody-snapshot.js +36 -0
  348. package/dist/services/memory-discover-handler.js +104 -0
  349. package/dist/services/memory-finish-evidence.js +457 -0
  350. package/dist/services/memory-finish-handler.js +229 -0
  351. package/dist/services/memory-finish-integration.js +450 -0
  352. package/dist/services/memory-finish-readiness.js +169 -0
  353. package/dist/services/memory-git-integration.js +220 -0
  354. package/dist/services/memory-historical-corrected-review.js +212 -0
  355. package/dist/services/memory-historical-original-review.js +143 -0
  356. package/dist/services/memory-historical-repair-registration.js +105 -0
  357. package/dist/services/memory-historical-second-review.js +147 -0
  358. package/dist/services/memory-init-bootstrap-readiness.js +210 -0
  359. package/dist/services/memory-init-contexts.js +131 -0
  360. package/dist/services/memory-init-controller-start.js +103 -0
  361. package/dist/services/memory-init-engine-release.js +223 -0
  362. package/dist/services/memory-init-git-policy.js +165 -0
  363. package/dist/services/memory-init-lint-capability.js +203 -0
  364. package/dist/services/memory-init-native-capacity.js +309 -0
  365. package/dist/services/memory-init-preflight.js +334 -0
  366. package/dist/services/memory-init-project-bootstrap.js +599 -0
  367. package/dist/services/memory-init-request-candidate.js +213 -0
  368. package/dist/services/memory-init-request-input.js +82 -0
  369. package/dist/services/memory-init-resource-storage.js +125 -0
  370. package/dist/services/memory-init-run-allocation.js +81 -0
  371. package/dist/services/memory-init-run-bundle.js +135 -0
  372. package/dist/services/memory-init-start.js +181 -0
  373. package/dist/services/memory-init-startup-custody.js +80 -0
  374. package/dist/services/memory-init-startup-input.js +240 -0
  375. package/dist/services/memory-init-storage.js +91 -0
  376. package/dist/services/memory-init-stores.js +359 -0
  377. package/dist/services/memory-init-worktrunk-capability.js +174 -0
  378. package/dist/services/memory-layer-publication.js +611 -0
  379. package/dist/services/memory-layer.js +221 -0
  380. package/dist/services/memory-lint-config.js +194 -0
  381. package/dist/services/memory-native-review-copy.js +103 -0
  382. package/dist/services/memory-normal-flow-entry.js +87 -0
  383. package/dist/services/memory-ordinary-defaults.js +129 -0
  384. package/dist/services/memory-preflight-bootstrap-custody.js +115 -0
  385. package/dist/services/memory-preflight-handler.js +274 -0
  386. package/dist/services/memory-repair-current-view.js +299 -0
  387. package/dist/services/memory-repair-document-delta.js +488 -0
  388. package/dist/services/memory-repair-history.js +496 -0
  389. package/dist/services/memory-repair-physical-binding.js +194 -0
  390. package/dist/services/memory-repair-publication-files.js +152 -0
  391. package/dist/services/memory-repair-publication-intent.js +27 -0
  392. package/dist/services/memory-repair-publication-plan.js +162 -0
  393. package/dist/services/memory-repair-publication-source.js +225 -0
  394. package/dist/services/memory-repair-publication.js +795 -0
  395. package/dist/services/memory-repair-registration.js +240 -0
  396. package/dist/services/memory-repair-work-baseline.js +415 -0
  397. package/dist/services/memory-repair-work-completion.js +117 -0
  398. package/dist/services/memory-repair-work-custody.js +73 -0
  399. package/dist/services/memory-repair-work-results.js +108 -0
  400. package/dist/services/memory-repair-workspace.js +261 -0
  401. package/dist/services/memory-repair-writer-copy.js +736 -0
  402. package/dist/services/memory-result-binding.js +239 -0
  403. package/dist/services/memory-retained-review-authority.js +138 -0
  404. package/dist/services/memory-retained-review-results.js +70 -0
  405. package/dist/services/memory-retained-second-baseline.js +102 -0
  406. package/dist/services/memory-retained-second-repairs.js +162 -0
  407. package/dist/services/memory-review-acceptance.js +214 -0
  408. package/dist/services/memory-review-correction-plan.js +206 -0
  409. package/dist/services/memory-review-handler.js +585 -0
  410. package/dist/services/memory-review-inputs.js +246 -0
  411. package/dist/services/memory-review-limits.js +10 -0
  412. package/dist/services/memory-review-receipt.js +180 -0
  413. package/dist/services/memory-review-registration.js +117 -0
  414. package/dist/services/memory-review-work-custody.js +126 -0
  415. package/dist/services/memory-review-work-input.js +91 -0
  416. package/dist/services/memory-review-work-results.js +95 -0
  417. package/dist/services/memory-second-corrected-review-inputs.js +167 -0
  418. package/dist/services/memory-second-correction-plan.js +77 -0
  419. package/dist/services/memory-second-repair-baseline.js +91 -0
  420. package/dist/services/memory-second-repair-launch.js +614 -0
  421. package/dist/services/memory-second-repair-registration.js +88 -0
  422. package/dist/services/memory-second-repair-source.js +187 -0
  423. package/dist/services/memory-second-review-acceptance.js +115 -0
  424. package/dist/services/memory-source-observations.js +117 -0
  425. package/dist/services/memory-stage-dispatch.js +65 -0
  426. package/dist/services/memory-stage-results.js +290 -0
  427. package/dist/services/memory-tool-probe.js +25 -0
  428. package/dist/services/memory-upgrade-analysis-handler.js +243 -0
  429. package/dist/services/memory-upgrade-bootstrap-readiness.js +251 -0
  430. package/dist/services/memory-upgrade-evidence.js +100 -0
  431. package/dist/services/memory-upgrade-inventory.js +442 -0
  432. package/dist/services/memory-upgrade-publication-custody.js +73 -0
  433. package/dist/services/memory-upgrade-publication.js +413 -0
  434. package/dist/services/memory-upgrade-selection.js +430 -0
  435. package/dist/services/memory-upgrade-start.js +60 -0
  436. package/dist/services/memory-upgrade-storage-readiness.js +340 -0
  437. package/dist/services/memory-verification-acceptance.js +156 -0
  438. package/dist/services/memory-verification-checks.js +317 -0
  439. package/dist/services/memory-verification-receipt.js +160 -0
  440. package/dist/services/memory-verify-handler.js +137 -0
  441. package/dist/services/memory-work-result-json.js +12 -0
  442. package/dist/services/memory-work-result-preparation.js +64 -0
  443. package/dist/services/merge-queue.js +228 -149
  444. package/dist/services/merge-server.js +163 -35
  445. package/dist/services/migrations.js +164 -114
  446. package/dist/services/model-catalog.js +109 -0
  447. package/dist/services/model-discovery.js +46 -0
  448. package/dist/services/native-daemon-history.js +50 -0
  449. package/dist/services/native-session-control.js +39 -0
  450. package/dist/services/operator-profiles.js +236 -0
  451. package/dist/services/physical-startup.js +45 -0
  452. package/dist/services/plan-runtime.js +26 -11
  453. package/dist/services/plans.js +28 -25
  454. package/dist/services/project-registry.js +97 -0
  455. package/dist/services/project-summary.js +1 -1
  456. package/dist/services/projects.js +17 -87
  457. package/dist/services/prompt-delivery.js +71 -0
  458. package/dist/services/prompts.js +28 -17
  459. package/dist/services/protocols.js +163 -87
  460. package/dist/services/provider-capacity.js +455 -0
  461. package/dist/services/recovery-observation-budget.js +121 -0
  462. package/dist/services/recovery-snapshot-database.js +588 -0
  463. package/dist/services/release-archive-producer.js +52 -0
  464. package/dist/services/release-archive.js +143 -0
  465. package/dist/services/release-cache.js +150 -0
  466. package/dist/services/release-compatibility.js +18 -0
  467. package/dist/services/release-download.js +67 -0
  468. package/dist/services/release-envelope.js +104 -0
  469. package/dist/services/release-manifest.js +45 -0
  470. package/dist/services/release-payload.js +114 -0
  471. package/dist/services/release-producer.js +63 -0
  472. package/dist/services/release-provenance.js +160 -0
  473. package/dist/services/release-registry.js +66 -0
  474. package/dist/services/release-source.js +194 -0
  475. package/dist/services/repair-intents.js +31 -0
  476. package/dist/services/repair-receipt.js +13 -0
  477. package/dist/services/review-copy.js +165 -0
  478. package/dist/services/review-deferral.js +23 -0
  479. package/dist/services/run-control-receipt.js +56 -0
  480. package/dist/services/run-control-worker.js +428 -0
  481. package/dist/services/run-control.js +1092 -0
  482. package/dist/services/run-controller-adapter.js +400 -0
  483. package/dist/services/run-controller-capture.js +186 -0
  484. package/dist/services/run-controller-process.js +205 -0
  485. package/dist/services/run-controller-recovery.js +295 -0
  486. package/dist/services/run-controller-state.js +97 -0
  487. package/dist/services/run-controller.js +1326 -0
  488. package/dist/services/run-engine-bindings.js +1 -1
  489. package/dist/services/run-fork.js +147 -0
  490. package/dist/services/run-health.js +149 -0
  491. package/dist/services/run-observations.js +152 -0
  492. package/dist/services/run-projection.js +22 -64
  493. package/dist/services/run-recovery-guard.js +107 -0
  494. package/dist/services/run-recovery-runtime.js +112 -0
  495. package/dist/services/run-recovery.js +456 -0
  496. package/dist/services/run-start-custody.js +189 -0
  497. package/dist/services/runs.js +1023 -246
  498. package/dist/services/runtime-budget.js +446 -0
  499. package/dist/services/runtime-command.js +43 -0
  500. package/dist/services/runtime-scope-capture.js +52 -0
  501. package/dist/services/runtime-scope-control.js +468 -0
  502. package/dist/services/runtime-scope-resume.js +605 -0
  503. package/dist/services/runtime-scope-stop.js +211 -0
  504. package/dist/services/runtime-scope-worker.js +314 -0
  505. package/dist/services/runtime-service.js +19 -14
  506. package/dist/services/schema-validation.js +10 -8
  507. package/dist/services/scope-writer-cleanup.js +27 -0
  508. package/dist/services/sessions.js +36 -91
  509. package/dist/services/setup.js +427 -0
  510. package/dist/services/stage-blocker.js +17 -7
  511. package/dist/services/stage-context.js +193 -19
  512. package/dist/services/stage-handlers.js +89 -0
  513. package/dist/services/stage-lifecycle.js +152 -116
  514. package/dist/services/stage-pause.js +202 -91
  515. package/dist/services/stage-report-renderer.js +234 -6
  516. package/dist/services/stage-work-graph.js +52 -0
  517. package/dist/services/tooling.js +41 -30
  518. package/dist/services/usage.js +49 -101
  519. package/dist/services/verification-matrix.js +393 -0
  520. package/dist/services/version-status.js +1 -1
  521. package/dist/services/vnext-code-review.js +235 -88
  522. package/dist/services/vnext-code.js +327 -226
  523. package/dist/services/vnext-contracts.js +10 -1
  524. package/dist/services/vnext-execution-profile.js +80 -5
  525. package/dist/services/vnext-fanout.js +355 -21
  526. package/dist/services/vnext-merge.js +332 -111
  527. package/dist/services/vnext-plan-review.js +287 -132
  528. package/dist/services/vnext-plan.js +228 -104
  529. package/dist/services/vnext-protocolize.js +533 -95
  530. package/dist/services/vnext-specify.js +123 -81
  531. package/dist/services/vnext-workspace-policy.js +7 -2
  532. package/dist/services/work-registry.js +1706 -200
  533. package/dist/services/workspace-bootstrap.js +53 -15
  534. package/dist/services/workspace-files.js +85 -0
  535. package/dist/services/worktrees.js +105 -48
  536. package/dist/shared/entity-references.js +1 -0
  537. package/dist/shared/errors.js +27 -0
  538. package/dist/storage/agent-output.js +26 -0
  539. package/dist/storage/data-preservation.js +65 -0
  540. package/dist/storage/database.js +930 -40
  541. package/dist/storage/foreign-key-transaction.js +39 -0
  542. package/dist/storage/immutable-input.js +45 -0
  543. package/dist/storage/import-guard.js +159 -0
  544. package/dist/storage/memory-upgrade-schema-bootstrap.js +38 -0
  545. package/dist/storage/native-cleanup.js +52 -0
  546. package/dist/storage/paired-writer-migration.js +424 -0
  547. package/dist/storage/paths.js +17 -4
  548. package/dist/storage/projection-lock.js +73 -0
  549. package/dist/storage/work-references.js +23 -0
  550. package/dist/storage/writer-contract.js +96 -0
  551. package/dist/storage/writer-migration.js +346 -0
  552. package/dist/storage/writer-restore.js +217 -0
  553. package/package.json +50 -13
  554. package/tools/create-canon-release.mjs +33 -0
  555. package/tools/probe-codex-history.mjs +37 -0
  556. package/tools/produce-hybrid-release.mjs +41 -0
  557. package/tools/repair-paused-run-status.mjs +84 -0
@@ -1,25 +1,94 @@
1
1
  import crypto from "node:crypto";
2
+ import { candidateAbsencesValid, candidateFailureAbsences, candidateFailureFiles, checkRepairDisposition, readRunnerEvidence, readRunnerEvidenceDetailed, readRunnerProgress, runnerContractsValid, runnerEvidencePass, runnerObservationDurations, runnerProofArtifacts } from "./check-runner-evidence.js";
3
+ export { assertSourceRepairEligible, checkRepairDisposition } from "./check-runner-evidence.js";
4
+ import { isGitlessWorkspace, ownedWorkspaceHookPath, projectServicePathFilter, workspaceGitFiles } from "./workspace-files.js";
2
5
  import { spawn, spawnSync } from "node:child_process";
6
+ import { ObservationClock, validateObservationDuration } from "../harness-runtime/lib/observation-clock.mjs";
3
7
  import fs from "node:fs";
4
8
  import path from "node:path";
5
- import { AppError } from "../shared/errors.js";
6
- import { confirmManagedProcess, finishManagedProcess, heartbeatManagedProcess, managedProcessStatus, managedOwnerIsAlive, processTreeIsAlive, registerManagedProcess, reservePorts } from "./managed-processes.js";
9
+ import { isDeepStrictEqual } from "node:util";
10
+ import { parse } from "shell-quote";
11
+ import { assertRunMutationAllowed } from "./run-recovery.js";
12
+ import { AppError, errorRecord } from "../shared/errors.js";
13
+ import { stopProcessGroup } from "../harness-runtime/lib/managed-daemon.mjs";
14
+ import { createRenewalState, maintenanceRetryable, renewalConfirmed, renewalDelay, renewalFailure, renewalRemaining, RENEWAL_POLICY } from "../harness-runtime/lib/lease-renewal.mjs";
15
+ import { confirmManagedProcess, finishManagedProcess, renewManagedProcess, managedProcessStatus, managedProcessRuntimeHome, managedOwnerIsAlive, processTreeIsAlive, registerManagedProcess, reservePorts } from "./managed-processes.js";
16
+ import { admitRuntimeCheck, runtimeBudgetForRun } from "./runtime-budget.js";
17
+ import { getResourceDatabase } from "../storage/database.js";
18
+ import { readBoundedReleaseFile } from "./release-source.js";
19
+ import { ownedCheckEnvironment, validateCheckEnvironment } from "./check-environment.js";
7
20
  const profileRelativePath = path.join(".memory-bank", "spec", "engineering", "code-check-profile.json");
8
21
  // Receipt reservation precedes child spawn so an interrupted CLI leaves an
9
22
  // auditable attempt. A second caller must not mistake that small handoff window
10
23
  // for a dead check and overwrite its outcome.
11
24
  const receiptStartingGraceMs = 30_000;
12
- export function codeExecutionEnvironment(workspaceRoot) { const suffix = crypto.createHash("sha256").update(path.resolve(workspaceRoot)).digest("hex").slice(0, 12); return { ...process.env, DD_FLOW_LOCAL_DATABASE_SUFFIX: suffix }; }
25
+ /** The check writer proves an empty tree before marking its registration terminal. */
26
+ export function terminalCheckSettled(context, record) {
27
+ if (record.kind !== "check" || !record.check_id || record.owner_id !== `check:${record.check_id}` || !record.project_id || !record.run_id
28
+ || !record.pid || !record.pid_started_at || !["stopped", "failed"].includes(record.state) || !record.finished_at)
29
+ return null;
30
+ let metadata;
31
+ try {
32
+ metadata = JSON.parse(record.metadata_json);
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ if (metadata.role !== "check" || managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
38
+ return null;
39
+ let resource;
40
+ try {
41
+ resource = getResourceDatabase(context.env.DD_FLOW_RESOURCE_HOME ?? context.ddFlowHome, "read_existing");
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ try {
47
+ const current = resource.get("SELECT * FROM managed_processes WHERE id = ?", [record.id]);
48
+ if (!current || current.lease_token !== record.lease_token || current.owner_id !== record.owner_id || current.pid !== record.pid
49
+ || current.pid_started_at !== record.pid_started_at || current.metadata_json !== record.metadata_json || current.state !== record.state
50
+ || current.project_id !== record.project_id || current.run_id !== record.run_id || current.work_id !== record.work_id
51
+ || current.check_id !== record.check_id || current.finished_at !== record.finished_at)
52
+ return null;
53
+ const receipt = context.db.get("SELECT status, finished_at, work_id FROM check_receipts WHERE id = ? AND project_id = ? AND run_id = ?", [record.check_id, record.project_id, record.run_id]);
54
+ return receipt && receipt.work_id === record.work_id && ["passed", "failed", "aborted"].includes(receipt.status) && receipt.finished_at
55
+ ? { status: receipt.status, finished_at: receipt.finished_at } : null;
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ finally {
61
+ resource.close?.();
62
+ }
63
+ }
64
+ export function codeExecutionEnvironment(workspaceRoot, checkEnvironment) {
65
+ const selected = validateCheckEnvironment(checkEnvironment);
66
+ const suffix = crypto.createHash("sha256").update(path.resolve(workspaceRoot)).digest("hex").slice(0, 12);
67
+ // The managed CLI's Node must win over a provider app's PATH: a Rosetta
68
+ // provider can otherwise run x64 checks against arm64-installed modules.
69
+ const environment = { ...process.env, PATH: `${path.dirname(process.execPath)}${path.delimiter}${process.env.PATH ?? ""}`, DD_FLOW_LOCAL_DATABASE_SUFFIX: suffix };
70
+ delete environment.NODE_PATH;
71
+ for (const key of ["DD_FLOW_CHECK_RUNNER_EVIDENCE_PATH", "DD_FLOW_CHECK_RUNNER_PROGRESS_PATH", "DD_FLOW_CHECK_INVOCATION_ID", "DD_FLOW_CHECK_ID", "DD_FLOW_CHECK_INPUT_HASH", "DD_FLOW_CHECK_VERIFICATION_EPOCH", "DD_FLOW_CHECK_COMMAND"])
72
+ delete environment[key];
73
+ Object.assign(environment, selected);
74
+ return environment;
75
+ }
76
+ export function workspaceOperationId(workspaceRoot) { return `workspace:${crypto.createHash("sha256").update(path.resolve(workspaceRoot)).digest("hex")}`; }
13
77
  export function readCodeCheckProfile(workspaceRoot) {
14
78
  const file = path.join(workspaceRoot, profileRelativePath);
15
79
  if (!fs.existsSync(file))
16
80
  return { profile: null, hash: null, file };
17
81
  const bytes = fs.readFileSync(file);
18
82
  const value = JSON.parse(bytes.toString("utf8"));
19
- if (value.schema_id !== "dd-flow/code-check-profile@6")
20
- throw new AppError("invalid_code_check_profile", "CODE check profile has an unsupported schema", 2, { file, schema_id: value.schema_id ?? null, required: "dd-flow/code-check-profile@6" });
21
- if (!isStringRecord(value.aliases) || !isStringRecord(value.require_alias_for) || !isGateRecord(value.mandatory_by_gate) || !isPortAliasRecord(value.ports_by_alias))
22
- throw new AppError("invalid_code_check_profile", "CODE check profile aliases, require_alias_for, mandatory_by_gate or ports_by_alias are invalid", 2, { file });
83
+ if (!["dd-flow/code-check-profile@6", "dd-flow/code-check-profile@7"].includes(value.schema_id ?? ""))
84
+ throw new AppError("invalid_code_check_profile", "CODE check profile has an unsupported schema", 2, { file, schema_id: value.schema_id ?? null, supported: ["dd-flow/code-check-profile@6", "dd-flow/code-check-profile@7"] });
85
+ if (!runnerContractsValid(value.runner_evidence_by_alias) || value.schema_id === "dd-flow/code-check-profile@6" && value.runner_evidence_by_alias !== undefined)
86
+ throw new AppError("invalid_code_check_profile", "Runner evidence requires valid profile@7 relative artifact contracts", 2, { file });
87
+ for (const alias of Object.keys(value.runner_evidence_by_alias ?? {}))
88
+ if (!value.aliases?.[alias])
89
+ throw new AppError("invalid_code_check_profile", "Runner evidence references an unknown alias", 2, { file, alias });
90
+ if (!isStringRecord(value.aliases) || !isStringRecord(value.require_alias_for) || !isGateRecord(value.mandatory_by_gate) || !isPortAliasRecord(value.ports_by_alias) || !isInputAliasRecord(workspaceRoot, value.inputs_by_alias))
91
+ throw new AppError("invalid_code_check_profile", "CODE check profile aliases, require_alias_for, mandatory_by_gate, ports_by_alias or inputs_by_alias are invalid", 2, { file });
23
92
  for (const [gate, aliases] of Object.entries(value.mandatory_by_gate))
24
93
  for (const alias of aliases ?? [])
25
94
  if (!value.aliases[alias])
@@ -27,19 +96,76 @@ export function readCodeCheckProfile(workspaceRoot) {
27
96
  for (const alias of Object.keys(value.ports_by_alias ?? {}))
28
97
  if (!value.aliases[alias])
29
98
  throw new AppError("invalid_code_check_profile", "A port declaration references an unknown alias", 2, { file, alias });
99
+ for (const alias of Object.keys(value.inputs_by_alias ?? {}))
100
+ if (!value.aliases[alias])
101
+ throw new AppError("invalid_code_check_profile", "An input declaration references an unknown alias", 2, { file, alias });
30
102
  return { profile: value, hash: crypto.createHash("sha256").update(bytes).digest("hex"), file };
31
103
  }
104
+ /**
105
+ * Planned aliases are qualification-owned extensions: their provider Work is
106
+ * expected to materialize them after PLAN. Freeze the project policy and
107
+ * existing aliases, while still validating every planned alias definition at
108
+ * execution time. Unknown edits and changes to existing policy remain part
109
+ * of the hash and therefore fail closed.
110
+ */
111
+ export function codeCheckProfileHash(workspaceRoot, checks = []) {
112
+ const { profile } = readCodeCheckProfile(workspaceRoot);
113
+ if (!profile)
114
+ return null;
115
+ const planned = new Set(checks.filter(check => check.availability === "planned" && check.command.startsWith("@check/")).map(check => check.command));
116
+ const serialize = (value) => profile.schema_id === "dd-flow/code-check-profile@7"
117
+ ? JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([left], [right]) => left.localeCompare(right))) : item)
118
+ : JSON.stringify(value);
119
+ if (!planned.size)
120
+ return crypto.createHash("sha256").update(serialize(profile)).digest("hex");
121
+ const canonical = {
122
+ ...profile,
123
+ aliases: Object.fromEntries(Object.entries(profile.aliases).filter(([alias]) => !planned.has(alias))),
124
+ ports_by_alias: Object.fromEntries(Object.entries(profile.ports_by_alias ?? {}).filter(([alias]) => !planned.has(alias))),
125
+ inputs_by_alias: Object.fromEntries(Object.entries(profile.inputs_by_alias ?? {}).filter(([alias]) => !planned.has(alias))),
126
+ ...(profile.schema_id === "dd-flow/code-check-profile@7" ? { runner_evidence_by_alias: Object.fromEntries(Object.entries(profile.runner_evidence_by_alias ?? {}).filter(([alias]) => !planned.has(alias))) } : {})
127
+ };
128
+ return crypto.createHash("sha256").update(serialize(canonical)).digest("hex");
129
+ }
130
+ /** The integration target starts at its baseline profile; the reviewed source
131
+ * may add aliases, but must not change existing check policy or bindings. */
132
+ export function mergeCheckProfileHash(sourceWorkspace, targetWorkspace, checks) {
133
+ const source = readCodeCheckProfile(sourceWorkspace).profile;
134
+ const target = readCodeCheckProfile(targetWorkspace).profile;
135
+ if (!source && !target)
136
+ return null;
137
+ if (!source || !target)
138
+ throw new AppError("check_profile_drift", "Source and integration check profiles differ", 1);
139
+ const retained = structuredClone(source);
140
+ for (const field of ["aliases", "ports_by_alias", "inputs_by_alias", "runner_evidence_by_alias"]) {
141
+ const old = target[field];
142
+ if (!old) {
143
+ delete retained[field];
144
+ continue;
145
+ }
146
+ const current = source[field] ?? {};
147
+ retained[field] = Object.fromEntries(Object.keys(old).filter(key => key in current).map(key => [key, current[key]]));
148
+ }
149
+ const existingAliases = new Set(Object.keys(target.aliases));
150
+ const changedExistingMetadata = ["ports_by_alias", "inputs_by_alias", "runner_evidence_by_alias"].some(field => Object.keys(source[field] ?? {}).some(alias => existingAliases.has(alias) && !(alias in (target[field] ?? {}))));
151
+ if (changedExistingMetadata || !isDeepStrictEqual(retained, target)) {
152
+ throw new AppError("check_profile_drift", "Source check profile changes existing integration policy", 1, { source_profile_hash: codeCheckProfileHash(sourceWorkspace, checks), target_profile_hash: codeCheckProfileHash(targetWorkspace, checks) });
153
+ }
154
+ return codeCheckProfileHash(sourceWorkspace, checks);
155
+ }
32
156
  export function validateCodeCheckCommands(workspaceRoot, commands) {
33
157
  const { profile, file } = readCodeCheckProfile(workspaceRoot);
34
- if (!profile)
35
- return [...commands];
36
- return commands.map((command) => { if (command.startsWith("@check/")) {
37
- if (!profile.aliases[command]?.trim())
38
- throw new AppError("unknown_code_check_alias", "CODE check alias is not defined by the project profile", 2, { alias: command, file });
158
+ return commands.map((command) => {
159
+ if (command.startsWith("@check/")) {
160
+ if (!profile?.aliases[command]?.trim())
161
+ throw new AppError("unknown_code_check_alias", "CODE check alias is not defined by the project profile", 2, { alias: command, file });
162
+ return command;
163
+ }
164
+ for (const [prefix, alias] of Object.entries(profile?.require_alias_for ?? {}))
165
+ if (command === prefix || command.startsWith(`${prefix} `))
166
+ throw new AppError("raw_code_check_forbidden", "CODE check must use the project alias instead of a raw guarded command", 2, { command, required_alias: alias, file });
39
167
  return command;
40
- } for (const [prefix, alias] of Object.entries(profile.require_alias_for))
41
- if (command === prefix || command.startsWith(`${prefix} `))
42
- throw new AppError("raw_code_check_forbidden", "CODE check must use the project alias instead of a raw guarded command", 2, { command, required_alias: alias, file }); return command; });
168
+ });
43
169
  }
44
170
  export function resolveCodeCheckCommands(workspaceRoot, runId, commands) {
45
171
  const validated = validateCodeCheckCommands(workspaceRoot, commands);
@@ -50,7 +176,11 @@ export function resolveCodeCheckCommands(workspaceRoot, runId, commands) {
50
176
  }
51
177
  export function projectPolicyCheckDeclarations(workspaceRoot, gate) {
52
178
  const { profile } = readCodeCheckProfile(workspaceRoot);
53
- return (profile?.mandatory_by_gate[gate] ?? []).map((alias) => { const ref = `POLICY/${gate}/${alias.slice(7).replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "").toLowerCase()}`; return { id: ref, canonical_ref: ref, source: "project_policy", command: alias, purpose: `Mandatory project ${gate} gate.`, run_at: gate, availability: "available", ...(profile?.ports_by_alias?.[alias] ? { ports: profile.ports_by_alias[alias] } : {}) }; });
179
+ return projectPolicyCheckDeclarationsFromProfile(profile, gate);
180
+ }
181
+ /** The caller may already have independently admitted exact profile bytes. */
182
+ export function projectPolicyCheckDeclarationsFromProfile(profile, gate) {
183
+ return (profile?.mandatory_by_gate[gate] ?? []).map((alias) => { const ref = `POLICY/${gate}/${alias.slice(7).replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "").toLowerCase()}`; return { id: ref, canonical_ref: ref, source: "project_policy", command: alias, purpose: `Mandatory project ${gate} gate.`, run_at: gate, availability: "available", ...(profile?.ports_by_alias?.[alias] ? { ports: profile.ports_by_alias[alias] } : {}), ...(profile?.inputs_by_alias?.[alias] ? { inputs: profile.inputs_by_alias[alias] } : {}) }; });
54
184
  }
55
185
  export function effectiveCheckDeclarations(workspaceRoot, declared, gates) { return gates.flatMap((gate) => [...declared.filter((check) => check.run_at === gate), ...projectPolicyCheckDeclarations(workspaceRoot, gate)]); }
56
186
  export function aggregateCheckDeclarations(workspaceRoot) { return projectPolicyCheckDeclarations(workspaceRoot, "code"); }
@@ -60,12 +190,21 @@ export function validateCheckPlacement(workspaceRoot, checks) { const { profile
60
190
  if (check.run_at === "work" && aggregateCommands.has(check.command))
61
191
  throw new AppError("aggregate_check_requires_code_gate", "A project aggregate check must run at CODE or readiness, not inside one scoped Work", 2, { check_id: check.id, command: check.command, run_at: check.run_at }); }
62
192
  export function validateCheckDeclaration(workspaceRoot, check) {
63
- if (check.run_at === "external")
64
- return;
193
+ if ((check.required_artifacts ?? []).some(file => path.posix.normalize(file.replaceAll("\\", "/")).split("/")[0] === "engine-outcome.json"))
194
+ throw new AppError("invalid_code_check_profile", "engine-outcome.json is reserved for engine execution evidence, not a candidate artifact", 2, { check_id: check.id });
195
+ if (!["work", "code", "readiness", "merge", "release"].includes(check.run_at))
196
+ throw new AppError("unsupported_check_gate", "Check requires an autonomous executable gate; replan the incompatible declaration", 2, { check_id: check.id, run_at: check.run_at });
197
+ if (check.runner_evidence !== undefined && !runnerContractsValid({ "@check/declaration": check.runner_evidence }))
198
+ throw new AppError("invalid_code_check_profile", "Check runner evidence contract is invalid", 2, { check_id: check.id });
65
199
  const { profile } = readCodeCheckProfile(workspaceRoot);
200
+ const resolvedCommand = profile?.aliases[check.command] ?? check.command;
201
+ validateTerminatingCheckCommand(resolvedCommand, check.id);
66
202
  if (check.availability === "planned" && check.command.startsWith("@check/") && !profile?.aliases[check.command])
67
203
  throw new AppError("planned_check_not_materialized", "A planned check alias was not materialized by its provider Work", 2, { check_id: check.id, command: check.command, provider: check.provided_by ?? null });
68
204
  validateCodeCheckCommands(workspaceRoot, [check.command]);
205
+ if (check.availability === "available" && !check.command.startsWith("@check/"))
206
+ assertDirectCheckExecutable(workspaceRoot, check.command, check.id);
207
+ validateCheckInputs(workspaceRoot, check.inputs ?? []);
69
208
  if (check.command.startsWith("@check/") && check.definition && profile?.aliases[check.command] !== check.definition)
70
209
  throw new AppError("check_definition_drift", "The accepted check alias definition differs from the current project profile", 2, { check_id: check.id, alias: check.command, expected: check.definition, actual: profile?.aliases[check.command] ?? null });
71
210
  if (check.availability !== "planned")
@@ -77,36 +216,417 @@ export function validateCheckDeclaration(workspaceRoot, check) {
77
216
  if (!profile?.aliases[check.command])
78
217
  throw new AppError("planned_check_not_materialized", "A planned check alias was not materialized by its provider Work", 2, { check_id: check.id, command: check.command, provider: check.provided_by ?? null });
79
218
  }
219
+ export function validateTerminatingCheckCommand(command, checkId) {
220
+ if (isBareServiceScript(command))
221
+ throw new AppError("non_terminating_check", "A check must terminate; run a finite test instead of a bare dev/start/serve/watch service script", 2, { check_id: checkId, command });
222
+ }
223
+ function isBareServiceScript(command) {
224
+ const words = parse(command.trim());
225
+ if (words.some((word) => typeof word !== "string"))
226
+ return false;
227
+ let args = words;
228
+ while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(args[0] ?? ""))
229
+ args = args.slice(1);
230
+ const manager = path.basename(args.shift() ?? "");
231
+ if (!["pnpm", "npm", "yarn", "bun"].includes(manager))
232
+ return false;
233
+ while (args.length && ["--filter", "-F", "--dir", "-C", "--cwd"].includes(args[0]))
234
+ args.splice(0, 2);
235
+ if (args[0] === "run")
236
+ args.shift();
237
+ return ["dev", "start", "serve", "watch"].includes(args[0] ?? "");
238
+ }
239
+ /** Reject a plan-time typo or a fictitious "manual" command before it becomes
240
+ * a late shell exit. Compound shell programs remain valid: only a simple,
241
+ * directly named executable is preflighted here. */
242
+ function assertDirectCheckExecutable(workspaceRoot, command, checkId) {
243
+ const trimmed = command.trim();
244
+ // A shell operator or expansion makes the launch path dynamic. Do not
245
+ // guess there; this preflight is deliberately limited to a direct program
246
+ // with ordinary arguments and optional literal environment assignments.
247
+ if (/[|&;<>()`$\n\r~]/.test(trimmed))
248
+ return;
249
+ const parsed = parse(trimmed);
250
+ if (parsed.some(word => typeof word !== "string"))
251
+ return;
252
+ const words = parsed;
253
+ let index = 0;
254
+ const env = codeExecutionEnvironment(workspaceRoot);
255
+ while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[index] ?? "")) {
256
+ const assignment = words[index++];
257
+ const equals = assignment.indexOf("=");
258
+ env[assignment.slice(0, equals)] = assignment.slice(equals + 1);
259
+ }
260
+ const program = words[index];
261
+ if (!program)
262
+ return;
263
+ const probe = spawnSync("/bin/sh", ["-c", "command -v -- \"$1\" >/dev/null", "dd-flow-check", program], { cwd: workspaceRoot, env, encoding: "utf8", timeout: 5000 });
264
+ if (probe.error || probe.signal)
265
+ throw new AppError("check_command_probe_unavailable", "Executable probe could not be observed; availability is unknown", 2, { check_id: checkId, executable: program, cause: probe.error?.message, signal: probe.signal });
266
+ if (probe.status !== 0)
267
+ throw new AppError("check_command_unavailable", "Available CODE check names an executable that is unavailable in this environment", 2, { check_id: checkId, command, executable: program });
268
+ }
269
+ // An owning handler supplies this identity; it is a reuse boundary, not an
270
+ // authority proof. Omitting it preserves the historical SDLC input hash.
271
+ function validateCheckEvidenceContext(value) {
272
+ if (value !== undefined && (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9:._-]{0,255}$/.test(value)))
273
+ throw new AppError("check_evidence_context_invalid", "Check evidence context must be a bounded opaque identifier", 2, { effect: "no_effect" });
274
+ }
275
+ // Additive NULL columns must not invalidate accepted legacy SQL digests.
276
+ const scopedReceiptColumns = new Set(["fingerprint_scope", "input_manifest_json", "execution_failures_json", "execution_contract_hash"]);
277
+ const evidenceDigest = (value) => crypto.createHash("sha256").update(JSON.stringify(value, (key, item) => scopedReceiptColumns.has(key) && item === null ? undefined : item)).digest("hex");
278
+ /** Prepares current physical evidence outside a writer and retains an exact
279
+ * SQL-only fence. Declarations must come from the owning handler/policy, never
280
+ * from the result whose acceptance is being decided. This does not supply
281
+ * semantic acceptance or choose a memory verification policy.
282
+ */
283
+ export class PreparedCheckEvidence {
284
+ #input;
285
+ #snapshot;
286
+ #generation;
287
+ #references;
288
+ #artifacts;
289
+ #completions = [];
290
+ #passed;
291
+ constructor(input, snapshot, generation, references, artifacts, passed) {
292
+ this.#input = structuredClone({ projectId: input.projectId, runId: input.runId, runHome: input.runHome, workspaceRoot: input.workspaceRoot, scope: input.scope, checks: input.checks,
293
+ ...(input.mode === undefined ? {} : { mode: input.mode }), ...(input.workId === undefined ? {} : { workId: input.workId }), ...(input.expectedProfileHash === undefined ? {} : { expectedProfileHash: input.expectedProfileHash }), ...(input.evidenceContext === undefined ? {} : { evidenceContext: input.evidenceContext }), ...(input.checkEnvironment === undefined ? {} : { checkEnvironment: input.checkEnvironment }) });
294
+ this.#snapshot = snapshot;
295
+ this.#generation = generation;
296
+ this.#references = references;
297
+ this.#artifacts = artifacts;
298
+ this.#passed = passed;
299
+ Object.freeze(this);
300
+ }
301
+ static prepare(context, input) {
302
+ const checkEnvironment = ownedCheckEnvironment(context.env, input.checkEnvironment);
303
+ if (checkEnvironment)
304
+ input = { ...input, checkEnvironment };
305
+ validateCheckEvidenceContext(input.evidenceContext);
306
+ const fail = () => { throw new AppError("check_evidence_stale", "Current declared checks lack owned passed evidence", 2, { effect: "no_effect" }); };
307
+ if (!input.checks.length || (input.scope === "work") !== Boolean(input.workId) || input.mode !== undefined && input.mode !== "diagnostic")
308
+ fail();
309
+ const generation = assertRunMutationAllowed(context, input.projectId, input.runId);
310
+ const snapshot = checkEvidenceSqlSnapshot(context, input);
311
+ const selected = JSON.parse(snapshot);
312
+ if (!selected.run || fs.realpathSync.native(selected.run.workspace_root) !== fs.realpathSync.native(input.workspaceRoot)
313
+ || fs.realpathSync.native(selected.run.run_root ?? selected.run.run_dir) !== fs.realpathSync.native(input.runHome))
314
+ fail();
315
+ const rows = selected.receipts;
316
+ const root = fs.realpathSync.native(input.runHome);
317
+ for (const row of rows) {
318
+ const relative = path.relative(path.resolve(input.runHome), row.receipt_path);
319
+ if (!path.isAbsolute(row.receipt_path) || relative.startsWith(`..${path.sep}`) || relative === ".." || path.isAbsolute(relative))
320
+ fail();
321
+ if (fs.existsSync(row.receipt_path)) {
322
+ const physical = path.relative(root, fs.realpathSync.native(row.receipt_path));
323
+ if (physical.startsWith(`..${path.sep}`) || physical === ".." || path.isAbsolute(physical))
324
+ fail();
325
+ }
326
+ }
327
+ for (const check of input.checks)
328
+ validateCheckDeclaration(input.workspaceRoot, check);
329
+ const { profile } = readCodeCheckProfile(input.workspaceRoot), profileHash = codeCheckProfileHash(input.workspaceRoot, input.checks);
330
+ if (input.expectedProfileHash !== undefined && profileHash !== input.expectedProfileHash)
331
+ fail();
332
+ const checks = input.checks.map(check => {
333
+ const runner = profile?.runner_evidence_by_alias?.[check.command] ?? check.runner_evidence;
334
+ return { ...check, ports: check.ports ?? profile?.ports_by_alias?.[check.command] ?? [], inputs: check.inputs ?? profile?.inputs_by_alias?.[check.command] ?? [],
335
+ ...(runner ? { runner_evidence: runner, required_artifacts: [...new Set([...(check.required_artifacts ?? []), runner.path])] } : {}) };
336
+ });
337
+ const commands = resolveCodeCheckCommands(input.workspaceRoot, input.runId, checks.map(check => check.command));
338
+ assertConsistentDeclarations(checks, commands);
339
+ const state = workspaceState(input.workspaceRoot, [input.runHome]);
340
+ const receipts = rows.map(projectCheckReceiptRow);
341
+ const artifacts = [], completions = [];
342
+ let passed = true;
343
+ const references = deduplicate(checks, commands).map(group => {
344
+ const inputHash = checkInputHash(input.workspaceRoot, group, profileHash, workspaceInputFingerprint(input.workspaceRoot, state.files, group.inputs, [input.runHome]), input.evidenceContext, input.checkEnvironment);
345
+ const receipt = receipts.filter(item => item.input_hash === inputHash && item.profile_hash === profileHash && item.scope === input.scope && item.work_id === (input.workId ?? null)).at(-1);
346
+ if (!receipt)
347
+ throw new AppError("check_evidence_stale", "Current declared checks lack owned passed evidence", 2, {
348
+ effect: "no_effect", reason: "input_identity_mismatch", expected_input_hash: inputHash,
349
+ candidates: receipts.filter(item => item.scope === input.scope && item.work_id === (input.workId ?? null))
350
+ .slice(-16).map(item => ({ id: item.id, input_hash: item.input_hash, profile_hash: item.profile_hash }))
351
+ });
352
+ if (!checkReceiptEvidenceValidForMode(bindReceipt(receipt, group), input.mode))
353
+ fail();
354
+ passed = passed && receipt.status === "passed";
355
+ for (const artifact of receipt.artifacts)
356
+ artifacts.push({ root: "run", path: path.relative(input.runHome, path.join(path.dirname(receipt.receipt_path), "artifacts", artifact.path)).split(path.sep).join("/"), sha256: artifact.sha256 });
357
+ const bytes = fs.readFileSync(receipt.receipt_path);
358
+ completions.push({ root: "run", path: path.relative(input.runHome, receipt.completion_path).split(path.sep).join("/"), sha256: crypto.createHash("sha256").update(fs.readFileSync(receipt.completion_path)).digest("hex") });
359
+ if (receipt.input_manifest)
360
+ completions.push({ root: "run", path: path.relative(input.runHome, path.join(path.dirname(receipt.receipt_path), receipt.input_manifest.path)).split(path.sep).join("/"), sha256: receipt.input_manifest.sha256 });
361
+ return { id: receipt.id, path: receipt.receipt_path, sha256: crypto.createHash("sha256").update(bytes).digest("hex") };
362
+ });
363
+ const prepared = new PreparedCheckEvidence(input, snapshot, generation, references, artifacts, passed);
364
+ prepared.#completions = completions;
365
+ prepared.assertCustody(context);
366
+ return prepared;
367
+ }
368
+ references() { return structuredClone(this.#references); }
369
+ artifactReferences() { return structuredClone(this.#artifacts); }
370
+ sourceReferences() { return [...this.artifactReferences(), ...structuredClone(this.#completions), ...this.resultReferences().map(reference => ({ root: "run", ...reference }))]; }
371
+ qualityPassed() { return this.#passed; }
372
+ resultReferences() {
373
+ return this.#references.map(reference => ({ path: path.relative(this.#input.runHome, reference.path).split(path.sep).join("/"), sha256: reference.sha256 }));
374
+ }
375
+ /** For an owning acceptance writer to retain independently of agent bytes.
376
+ * The row digest pins historical execution, not later workspace policy.
377
+ */
378
+ retainedReferences(context) {
379
+ return context.db.readSnapshot(() => {
380
+ this.assertCustody(context);
381
+ return this.#references.map(reference => ({ id: reference.id, path: path.relative(this.#input.runHome, reference.path).split(path.sep).join("/"), sha256: reference.sha256,
382
+ sql_sha256: evidenceDigest(context.db.get("SELECT * FROM check_receipts WHERE project_id=? AND run_id=? AND id=?", [this.#input.projectId, this.#input.runId, reference.id])) }));
383
+ });
384
+ }
385
+ assertOwner(scope) {
386
+ if (scope.projectId !== this.#input.projectId || scope.runId !== this.#input.runId || scope.scope !== undefined && scope.scope !== this.#input.scope)
387
+ throw new AppError("check_receipt_changed", "Prepared checks belong to another RUN or scope", 2, { effect: "no_effect" });
388
+ }
389
+ assertCustody(context) {
390
+ assertRunMutationAllowed(context, this.#input.projectId, this.#input.runId, this.#generation);
391
+ if (checkEvidenceSqlSnapshot(context, this.#input) !== this.#snapshot)
392
+ throw new AppError("check_receipt_changed", "Prepared check SQL custody changed", 2, { effect: "no_effect" });
393
+ }
394
+ revalidate(context) {
395
+ const current = PreparedCheckEvidence.prepare(context, this.#input);
396
+ if (!isDeepStrictEqual(current.sourceReferences(), this.sourceReferences()) || !isDeepStrictEqual(current.#references, this.#references) || current.#snapshot !== this.#snapshot)
397
+ throw new AppError("check_evidence_stale", "Prepared check evidence changed", 2, { effect: "no_effect" });
398
+ this.assertCustody(context);
399
+ }
400
+ }
401
+ /** Historical aggregate execution proof. Selectors must come from an owning
402
+ * committed acceptance receipt, not a proposed result. This reader does not
403
+ * select current declarations, inspect the current workspace or execute checks.
404
+ * Relocation of SQL path fields still requires explicit receipt projection.
405
+ */
406
+ export class PreparedRetainedCheckEvidence {
407
+ #input;
408
+ #snapshot;
409
+ #generation;
410
+ constructor(input, snapshot, generation) {
411
+ this.#input = structuredClone(input);
412
+ this.#snapshot = snapshot;
413
+ this.#generation = generation;
414
+ Object.freeze(this);
415
+ }
416
+ static prepare(context, input) {
417
+ const fail = () => { throw new AppError("retained_check_evidence_invalid", "Accepted checks lack exact historical execution proof", 2, { effect: "no_effect" }); };
418
+ if (!Array.isArray(input.references) || !input.references.length || input.references.length > 4096
419
+ || new Set(input.references.map(reference => reference?.id)).size !== input.references.length
420
+ || input.references.some(reference => !reference || typeof reference.id !== "string" || !reference.id
421
+ || typeof reference.path !== "string" || !/^[a-f0-9]{64}$/.test(reference.sha256) || !/^[a-f0-9]{64}$/.test(reference.sql_sha256)))
422
+ fail();
423
+ const generation = assertRunMutationAllowed(context, input.projectId, input.runId), snapshot = retainedCheckSqlSnapshot(context, input);
424
+ const selected = JSON.parse(snapshot);
425
+ if (!selected.run || selected.receipts.some(row => !row))
426
+ fail();
427
+ const runRoot = selected.run.run_root ?? selected.run.run_dir;
428
+ if (!path.isAbsolute(runRoot) || fs.realpathSync.native(runRoot) !== path.resolve(runRoot))
429
+ fail();
430
+ for (let index = 0; index < input.references.length; index++) {
431
+ const reference = input.references[index], row = selected.receipts[index];
432
+ if (row.scope !== "aggregate" || row.work_id !== null || evidenceDigest(row) !== reference.sql_sha256
433
+ || row.receipt_path !== path.join(runRoot, reference.path))
434
+ fail();
435
+ // Admit contained regular receipt/completion files before any helper
436
+ // reads them; escaping paths and symlink parents are rejected.
437
+ const bytes = readRetainedCheckFile(runRoot, reference.path);
438
+ readRetainedCheckFile(runRoot, path.posix.join(path.posix.dirname(reference.path), "completion.json"));
439
+ if (crypto.createHash("sha256").update(bytes).digest("hex") !== reference.sha256 || !checkReceiptEvidenceValidForMode(projectCheckReceiptRow(row), input.mode))
440
+ fail();
441
+ }
442
+ const prepared = new PreparedRetainedCheckEvidence(input, snapshot, generation);
443
+ prepared.assertCustody(context);
444
+ return prepared;
445
+ }
446
+ assertCustody(context) {
447
+ assertRunMutationAllowed(context, this.#input.projectId, this.#input.runId, this.#generation);
448
+ if (retainedCheckSqlSnapshot(context, this.#input) !== this.#snapshot)
449
+ throw new AppError("retained_check_evidence_invalid", "Accepted check SQL custody changed", 2, { effect: "no_effect" });
450
+ }
451
+ revalidate(context) {
452
+ const current = PreparedRetainedCheckEvidence.prepare(context, this.#input);
453
+ if (current.#snapshot !== this.#snapshot)
454
+ throw new AppError("retained_check_evidence_invalid", "Accepted check proof changed", 2, { effect: "no_effect" });
455
+ this.assertCustody(context);
456
+ }
457
+ }
458
+ function readRetainedCheckFile(root, relative) {
459
+ const fail = () => { throw new AppError("retained_check_evidence_invalid", "Accepted check file is not a contained regular file", 2, { effect: "no_effect" }); };
460
+ if (!relative || path.posix.isAbsolute(relative) || path.win32.isAbsolute(relative) || relative.includes("\\") || relative.includes("\0")
461
+ || relative.split("/").some(segment => !segment || segment === "." || segment === ".."))
462
+ fail();
463
+ try {
464
+ let parent = root;
465
+ if (!fs.lstatSync(parent).isDirectory())
466
+ fail();
467
+ for (const segment of relative.split("/").slice(0, -1)) {
468
+ parent = path.join(parent, segment);
469
+ if (!fs.lstatSync(parent).isDirectory())
470
+ fail();
471
+ }
472
+ return readBoundedReleaseFile(path.join(root, relative), 16 * 1024 * 1024);
473
+ }
474
+ catch {
475
+ return fail();
476
+ }
477
+ }
478
+ function retainedCheckSqlSnapshot(context, input) {
479
+ return context.db.readSnapshot(() => JSON.stringify({
480
+ run: context.db.get("SELECT project_id,id,workspace_root,run_root,run_dir FROM runs WHERE project_id=? AND id=?", [input.projectId, input.runId]) ?? null,
481
+ receipts: input.references.map(reference => context.db.get("SELECT * FROM check_receipts WHERE project_id=? AND run_id=? AND id=?", [input.projectId, input.runId, reference.id]) ?? null)
482
+ }));
483
+ }
484
+ function checkEvidenceSqlSnapshot(context, input) {
485
+ return context.db.readSnapshot(() => JSON.stringify({
486
+ run: context.db.get("SELECT project_id,id,workspace_root,run_root,run_dir FROM runs WHERE project_id=? AND id=?", [input.projectId, input.runId]),
487
+ receipts: context.db.all("SELECT * FROM check_receipts WHERE project_id=? AND run_id=? ORDER BY reservation_sequence,rowid", [input.projectId, input.runId])
488
+ }));
489
+ }
80
490
  export async function runCodeChecks(context, input) {
81
- reconcileUnfinishedChecks(context, input);
491
+ const checkEnvironment = ownedCheckEnvironment(context.env, input.checkEnvironment);
492
+ if (checkEnvironment)
493
+ input = { ...input, checkEnvironment };
494
+ validateCheckEvidenceContext(input.evidenceContext);
495
+ const generation = assertRunMutationAllowed(context, input.projectId, input.runId);
496
+ let gate;
497
+ for (;;) {
498
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
499
+ reconcileUnfinishedChecks(context, input);
500
+ reconcileWorkspaceOwnership(context, input.workspaceRoot);
501
+ try {
502
+ gate = acquireWorkspaceGate(context, input);
503
+ break;
504
+ }
505
+ catch (error) {
506
+ const sameRunGate = managedProcessStatus(context).find(item => item.kind === "workspace-gate" && item.operation_id === workspaceOperationId(input.workspaceRoot) && ["starting", "running", "stopping"].includes(item.state) && item.project_id === input.projectId && item.run_id === input.runId);
507
+ if (input.scope !== "work" || !input.workId || !(error instanceof AppError) || !["check_in_progress", "managed_operation_in_progress"].includes(error.code) || !sameRunGate)
508
+ throw error;
509
+ await new Promise(resolve => setTimeout(resolve, 500));
510
+ }
511
+ }
512
+ try {
513
+ let receipts = await runCodeChecksOwned(context, input, gate.id, generation);
514
+ // One bounded episode, not a product-repair turn. The second execution
515
+ // remains guarded by its own before/after snapshot and SQL reservation.
516
+ const stale = receipts.filter(staleCheckRetryEligible);
517
+ if (!input.retryReceiptId && !input.retryReceiptIds?.length && stale.length) {
518
+ const otherSession = context.db.get("SELECT 1 FROM work_sessions s JOIN works w ON w.work_id = s.work_id WHERE w.project_id = ? AND w.run_id = ? AND w.work_id != ? AND s.status = 'running' AND s.completed_at IS NULL LIMIT 1", [input.projectId, input.runId, input.workId ?? ""]);
519
+ if (!otherSession) {
520
+ for (const predecessor of stale) {
521
+ const selected = input.checks.filter(check => predecessor.check_refs.includes(checkRef(check)));
522
+ if (!selected.length || selected.some(check => check.reuse !== "deterministic"))
523
+ continue;
524
+ const retried = await runCodeChecksOwned(context, { ...input, retryReceiptId: predecessor.id, retryReason: "check_inputs_changed" }, gate.id, generation, new Set(predecessor.check_refs));
525
+ receipts = receipts.filter(receipt => receipt.id !== predecessor.id).concat(retried);
526
+ }
527
+ }
528
+ }
529
+ return receipts;
530
+ }
531
+ finally {
532
+ finishManagedProcess(context, { id: gate.id, leaseToken: gate.lease_token, state: "stopped", reason: "workspace_gate_settled" });
533
+ }
534
+ }
535
+ async function runCodeChecksOwned(context, input, workspaceGateId, generation, selectedRefs) {
536
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
82
537
  for (const check of input.checks)
83
538
  validateCheckDeclaration(input.workspaceRoot, check);
84
- const { hash: profileHash, profile } = readCodeCheckProfile(input.workspaceRoot);
85
- const checks = input.checks.map((check) => { const ports = profile?.ports_by_alias?.[check.command]; return check.ports || !ports ? check : { ...check, ports }; });
539
+ const { profile } = readCodeCheckProfile(input.workspaceRoot);
540
+ const profileHash = codeCheckProfileHash(input.workspaceRoot, input.checks);
541
+ if (input.expectedProfileHash !== undefined && input.expectedProfileHash !== profileHash)
542
+ throw new AppError("check_profile_drift", "The frozen check profile differs from the workspace profile", 1, { expected_profile_hash: input.expectedProfileHash, actual_profile_hash: profileHash });
543
+ const checks = input.checks.map(check => {
544
+ const ports = profile?.ports_by_alias?.[check.command], inputs = profile?.inputs_by_alias?.[check.command];
545
+ const runner = profile?.runner_evidence_by_alias?.[check.command] ?? check.runner_evidence;
546
+ if (runner && !runnerContractsValid({ "@check/declaration": runner }))
547
+ throw new AppError("invalid_code_check_profile", "Check runner evidence contract is invalid", 2, { check_id: check.id });
548
+ return { ...check, ...(check.ports || !ports ? {} : { ports }), ...(check.inputs || !inputs ? {} : { inputs }), ...(runner ? { runner_evidence: runner, required_artifacts: [...new Set([...(check.required_artifacts ?? []), runner.path])] } : {}) };
549
+ });
86
550
  const resolved = resolveCodeCheckCommands(input.workspaceRoot, input.runId, checks.map((check) => check.command));
87
- const groups = deduplicate(checks, resolved);
88
- const receipts = [];
551
+ assertConsistentDeclarations(checks, resolved);
552
+ // Retain all declarations for the planned-alias profile hash; filter only
553
+ // execution, otherwise a targeted retry changes its own frozen contract.
554
+ const groups = deduplicate(checks, resolved).filter(group => !selectedRefs || group.declarations.some(check => selectedRefs.has(checkRef(check)))), receipts = [];
555
+ const retryIds = [...new Set([...(input.retryReceiptId ? [input.retryReceiptId] : []), ...(input.retryReceiptIds ?? [])])];
556
+ const retries = new Map();
557
+ for (const receiptId of retryIds) {
558
+ const predecessor = validateFailedCheckRetry(context, { projectId: input.projectId, runId: input.runId, receiptId, declarations: checks, reason: input.retryReason });
559
+ const snapshot = workspaceState(input.workspaceRoot, [input.runHome]);
560
+ const group = groups.find(candidate => candidate.declarations.some(check => check.run_at === predecessor.gate)
561
+ && (checkInputHash(input.workspaceRoot, { ...candidate, gate: predecessor.gate }, profileHash, workspaceInputFingerprint(input.workspaceRoot, snapshot.files, candidate.inputs, [input.runHome]), input.evidenceContext, input.checkEnvironment) === predecessor.input_hash
562
+ || sourceRepairContractMatches(predecessor, candidate, profileHash)
563
+ || input.retryReason === "check_inputs_changed" && staleRetryContractMatches(predecessor, candidate, profileHash, input)));
564
+ if (!group || retries.has(group))
565
+ throw new AppError("retry_check_invalid", "Retry must match exactly one current execution contract", 2, { check_receipt_id: receiptId });
566
+ // Preserve the identity of a pre-deduplication failed execution when an
567
+ // upgraded RUN retries it; the new receipt still proves every grouped ref.
568
+ group.gate = predecessor.gate;
569
+ retries.set(group, receiptId);
570
+ }
89
571
  for (let index = 0; index < groups.length; index += 1) {
90
572
  const group = groups[index];
91
573
  const before = workspaceState(input.workspaceRoot, [input.runHome]);
92
574
  const startedAt = context.now();
93
- const inputHash = crypto.createHash("sha256").update(JSON.stringify({ gate: group.gate, command: group.command, environment: String(codeExecutionEnvironment(input.workspaceRoot).DD_FLOW_LOCAL_DATABASE_SUFFIX), required_artifacts: group.requiredArtifacts, ports: [...group.ports].sort() })).digest("hex");
94
- const epoch = crypto.createHash("sha256").update(`${group.gate}\0${before.fingerprint}`).digest("hex");
95
- const reserved = reserveReceipt(context, { ...input, group, before, profileHash, inputHash, epoch, startedAt });
575
+ const inputFiles = selectedInputFiles(input.workspaceRoot, before.files, group.inputs, [input.runHome]);
576
+ const inputFingerprint = inputFilesFingerprint(inputFiles);
577
+ const inputHash = checkInputHash(input.workspaceRoot, group, profileHash, inputFingerprint, input.evidenceContext, input.checkEnvironment);
578
+ const epoch = crypto.createHash("sha256").update(`${group.gate}\0${inputFingerprint}`).digest("hex");
579
+ const executionContractHash = checkInputHash(input.workspaceRoot, group, profileHash, "", input.evidenceContext, input.checkEnvironment);
580
+ const reservationInput = { ...input, retryReceiptIds: retries.has(group) ? [retries.get(group)] : [], generation, group, before, inputFiles, inputFingerprint, executionContractHash, profileHash, inputHash, epoch, startedAt };
581
+ delete reservationInput.retryReceiptId;
582
+ const decision = reserveOrReuseReceipt(context, reservationInput);
583
+ if (decision.receipt) {
584
+ receipts.push(bindReceipt(decision.receipt, group));
585
+ input.progress?.(`check ${index + 1}/${groups.length} ${decision.receipt.status === "passed" ? "reused" : "requires repair"}: ${group.command}`);
586
+ continue;
587
+ }
588
+ const reserved = decision.reserved;
96
589
  const { id, evidenceDir, stdoutPath, stderrPath, receiptPath, completionPath } = reserved;
97
590
  let resources = {};
98
591
  let result = { exitCode: null, error: "check did not start", aborted: true };
99
592
  try {
100
593
  fs.mkdirSync(evidenceDir, { recursive: true });
101
- writeReceipt(receiptPath, receiptFor({ ...reserved, resources, result, status: "running", after: before, mutationPaths: [], artifacts: [] }));
102
- const managed = registerManagedProcess(context, { kind: "check", ownerPid: process.pid, ownerId: `check:${id}`, projectId: input.projectId, runId: input.runId, workId: input.workId ?? null, checkId: id, stdoutPath, stderrPath, metadata: { command: group.command } });
594
+ retainInputManifest(context, reserved);
595
+ const startingReceipt = receiptFor({ ...reserved, resources, result, status: "running", after: before, mutationPaths: [], artifacts: [] });
596
+ if (group.runnerEvidence)
597
+ startingReceipt.runner_evidence_required = group.runnerEvidence;
598
+ writeReceipt(receiptPath, startingReceipt);
599
+ const budget = runtimeBudgetForRun(context, input.projectId, input.runId);
600
+ if (group.runnerEvidence) {
601
+ // Reject configuration before acquiring a check lease/ports, so there
602
+ // is no unconfirmed managed child to strand on a validation error.
603
+ runnerObservationDurations(process.env);
604
+ }
605
+ const managed = registerManagedProcess(context, { kind: "check", ownerPid: process.pid, ownerId: `check:${id}`, operationId: workspaceOperationId(input.workspaceRoot), projectId: input.projectId, runId: input.runId, workId: input.workId ?? null, checkId: id, stdoutPath, stderrPath, metadata: { command: group.command, role: "check", workspace_root: input.workspaceRoot, workspace_gate_id: workspaceGateId, budget } });
103
606
  const allocation = await reservePorts(context, { ownerId: managed.owner_id, processId: managed.id, names: group.ports });
104
607
  resources = allocation.ports;
105
- input.progress?.(`check ${index + 1}/${groups.length} started: ${group.command}`);
608
+ try {
609
+ input.progress?.(`check ${index + 1}/${groups.length} preparing: ${group.command}`);
610
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
611
+ }
612
+ catch (error) {
613
+ allocation.release();
614
+ finishManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, state: "failed", reason: "dispatch_fenced_before_spawn" });
615
+ throw error;
616
+ }
106
617
  const stdout = fs.openSync(stdoutPath, "a");
107
618
  const stderr = fs.openSync(stderrPath, "a");
619
+ let confirmedExpiry = null;
108
620
  try {
109
- result = await runCheck(group.command, input.workspaceRoot, { ...codeExecutionEnvironment(input.workspaceRoot), DD_FLOW_EVIDENCE_DIR: evidenceDir, DD_FLOW_CHECK_COMPLETION_FILE: completionPath, ...portEnvironment(resources) }, stdout, stderr, (elapsed) => input.progress?.(`check ${index + 1}/${groups.length} still running (${elapsed}s): ${group.command}`), (pid) => confirmManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, pid, processGroupId: process.platform === "win32" ? null : pid }), () => heartbeatManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token }));
621
+ const runnerEnvironment = group.runnerEvidence ? { DD_FLOW_CHECK_RUNNER_EVIDENCE_PATH: path.join(evidenceDir, group.runnerEvidence.path), DD_FLOW_CHECK_RUNNER_PROGRESS_PATH: path.join(evidenceDir, "runner-progress.jsonl"), DD_FLOW_CHECK_INVOCATION_ID: id, DD_FLOW_CHECK_ID: id, DD_FLOW_CHECK_INPUT_HASH: inputHash, DD_FLOW_CHECK_VERIFICATION_EPOCH: epoch } : {};
622
+ if (group.runnerEvidence)
623
+ fs.mkdirSync(path.dirname(path.join(evidenceDir, group.runnerEvidence.path)), { recursive: true });
624
+ result = await runCheck(group.command, input.workspaceRoot, { ...codeExecutionEnvironment(input.workspaceRoot, input.checkEnvironment), DD_FLOW_EVIDENCE_DIR: evidenceDir, DD_FLOW_CHECK_COMPLETION_FILE: completionPath, ...runnerEnvironment, ...portEnvironment(resources) }, stdout, stderr, (elapsed) => input.progress?.(`check ${index + 1}/${groups.length} still running (${elapsed}s): ${group.command}`), (pid) => {
625
+ confirmedExpiry = confirmManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, pid, processGroupId: process.platform === "win32" ? null : pid }).lease_expires_at;
626
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
627
+ if (budget)
628
+ admitRuntimeCheck(context, managed.id, managed.lease_token);
629
+ }, attemptMs => renewManagedProcess({ ...context, resourceDatabaseMode: "prepared_existing", databaseDeadlineAt: Date.now() + attemptMs }, { id: managed.id, leaseToken: managed.lease_token }), { leaseExpiresAt: () => confirmedExpiry });
110
630
  }
111
631
  finally {
112
632
  fs.closeSync(stdout);
@@ -116,7 +636,8 @@ export async function runCodeChecks(context, input) {
116
636
  if (processTreeIsAlive(current))
117
637
  throw new AppError("check_in_progress", "The check shell exited but its process tree is still live; retain this receipt and its resources until settlement", 2, { process_id: managed.id, check_receipt_id: id });
118
638
  allocation.release();
119
- finishManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, state: result.aborted || result.exitCode !== 0 || Boolean(result.error) ? "failed" : "stopped", reason: result.error });
639
+ if (!result.cleanupUnconfirmed)
640
+ finishManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, state: result.aborted || result.exitCode !== 0 || Boolean(result.error) ? "failed" : "stopped", reason: result.error });
120
641
  }
121
642
  catch (error) {
122
643
  if (error instanceof AppError && error.code === "check_in_progress")
@@ -124,23 +645,63 @@ export async function runCodeChecks(context, input) {
124
645
  result = { exitCode: null, error: error instanceof Error ? error.message : String(error), aborted: true };
125
646
  }
126
647
  const after = workspaceState(input.workspaceRoot, [input.runHome]);
127
- const mutationPaths = changedPaths(before.files, after.files);
128
- const artifacts = collectRequiredArtifacts(evidenceDir, group.requiredArtifacts);
648
+ const afterFiles = selectedInputFiles(input.workspaceRoot, after.files, group.inputs, [input.runHome]);
649
+ const mutationPaths = changedPaths(reserved.inputFiles, afterFiles);
650
+ let artifacts = collectCheckArtifacts(evidenceDir, group.requiredArtifacts);
129
651
  if (fs.existsSync(stderrPath)) {
130
652
  if (!artifacts.complete)
131
653
  fs.appendFileSync(stderrPath, `\nmissing required evidence artifacts: ${artifacts.missing.join(", ")}\n`);
132
654
  if (result.error)
133
655
  fs.appendFileSync(stderrPath, `\n${result.error}\n`);
134
656
  if (mutationPaths.length)
135
- fs.appendFileSync(stderrPath, `\ncheck mutated project workspace: ${mutationPaths.join(", ")}\n`);
657
+ fs.appendFileSync(stderrPath, `\ncheck inputs changed while running: ${mutationPaths.join(", ")}\n`);
658
+ }
659
+ const runnerRead = group.runnerEvidence ? readRunnerEvidenceDetailed(evidenceDir, group.runnerEvidence, { invocation_id: id, check_id: id, command: group.command, input_hash: inputHash, verification_epoch: epoch }) : undefined;
660
+ const runnerEvidence = runnerRead?.evidence;
661
+ const physicalFailures = executionFailures({ fingerprintScope: "check_inputs", exitCode: result.exitCode, launcherError: result.error ?? undefined, cleanupUnconfirmed: result.cleanupUnconfirmed, missing: artifacts.missing, mutations: mutationPaths, invalidRunner: Boolean(group.runnerEvidence && !runnerEvidence) });
662
+ if (result.failure)
663
+ physicalFailures.push(result.failure);
664
+ const candidateFiles = candidateFailureFiles(runnerEvidence, input.workspaceRoot);
665
+ const candidateAbsences = candidateFailureAbsences(runnerEvidence, input.workspaceRoot);
666
+ if (group.runnerEvidence)
667
+ retainExecutionOutcome(evidenceDir, { id, command: group.command, input_hash: inputHash, verification_epoch: epoch, fingerprint_scope: "check_inputs", input_manifest: reserved.inputManifest ?? null, execution_contract_hash: executionContractHash }, input.workspaceRoot, physicalFailures, candidateFiles, candidateAbsences);
668
+ const requiredArtifacts = [...new Set([...group.requiredArtifacts, ...runnerProofArtifacts(runnerEvidence), ...(group.runnerEvidence ? ["engine-outcome.json"] : [])])];
669
+ artifacts = collectCheckArtifacts(evidenceDir, requiredArtifacts);
670
+ const status = result.aborted ? "aborted" : result.exitCode === 0 && !result.error && artifacts.complete && mutationPaths.length === 0 && (!group.runnerEvidence || runnerEvidencePass(runnerEvidence)) ? "passed" : "failed";
671
+ const receipt = receiptFor({ ...reserved, resources, result, status, after: { ...after, fingerprint: inputFilesFingerprint(afterFiles) }, mutationPaths, artifacts: artifacts.items });
672
+ receipt.required_artifacts = requiredArtifacts;
673
+ receipt.candidate_root = input.workspaceRoot;
674
+ receipt.candidate_files = candidateFiles;
675
+ receipt.candidate_absences = candidateAbsences;
676
+ receipt.execution_failures = physicalFailures;
677
+ context.db.run("UPDATE check_receipts SET execution_failures_json = ? WHERE project_id = ? AND id = ? AND status = 'running'", [JSON.stringify(physicalFailures), input.projectId, id]);
678
+ const completion = readCompletion(completionPath);
679
+ if (completion)
680
+ writeCompletionSnapshot(completionPath, completion, receipt);
681
+ if (group.runnerEvidence) {
682
+ receipt.runner_evidence_required = group.runnerEvidence;
683
+ receipt.runner_evidence = runnerEvidence ?? null;
684
+ receipt.runner_evidence_diagnostics = runnerRead.diagnostics;
685
+ if (runnerRead?.diagnostics_truncated)
686
+ receipt.runner_evidence_diagnostics_truncated = true;
136
687
  }
137
- const status = result.aborted ? "aborted" : result.exitCode === 0 && !result.error && artifacts.complete && mutationPaths.length === 0 ? "passed" : "failed";
138
- const receipt = receiptFor({ ...reserved, resources, result, status, after, mutationPaths, artifacts: artifacts.items });
139
688
  context.db.run("UPDATE check_receipts SET status = ?, exit_code = ?, after_fingerprint = ?, mutation_paths_json = ?, artifacts_json = ?, finished_at = ? WHERE id = ? AND project_id = ? AND status = 'running'", [receipt.status, receipt.exit_code, receipt.after_fingerprint, JSON.stringify(receipt.mutation_paths), JSON.stringify(receipt.artifacts), receipt.finished_at, id, input.projectId]);
140
689
  writeReceipt(receiptPath, receipt);
690
+ if (status === "failed")
691
+ receipt.diagnostic_evidence_valid = checkReceiptEvidenceValidForMode(receipt, "diagnostic");
141
692
  receipts.push(receipt);
142
693
  input.progress?.(`check ${index + 1}/${groups.length} ${status}: ${group.command}`);
143
694
  }
695
+ if (receipts.every(receipt => receipt.status === "passed")) {
696
+ const current = workspaceState(input.workspaceRoot, [input.runHome]), currentProfileHash = codeCheckProfileHash(input.workspaceRoot, input.checks);
697
+ for (const receipt of receipts) {
698
+ const group = groups.find(candidate => candidate.declarations.some(check => receipt.check_refs.includes(checkRef(check))));
699
+ const currentHash = group ? checkInputHash(input.workspaceRoot, group, currentProfileHash, workspaceInputFingerprint(input.workspaceRoot, current.files, group.inputs, [input.runHome]), input.evidenceContext, input.checkEnvironment) : null;
700
+ if (!group || !checkReceiptEvidenceValid(receipt) || receipt.input_hash !== currentHash)
701
+ throw new AppError("check_evidence_stale", "Check evidence changed before the gate could be accepted", 1, { check_receipt_id: receipt.id });
702
+ }
703
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
704
+ }
144
705
  return receipts;
145
706
  }
146
707
  /**
@@ -149,62 +710,218 @@ export async function runCodeChecks(context, input) {
149
710
  * a dead/terminal process becomes an explicit aborted receipt that can retry.
150
711
  */
151
712
  export function reconcileUnfinishedChecks(context, input) {
152
- const where = input.workId ? "project_id = ? AND run_id = ? AND work_id = ? AND status = 'running'" : "project_id = ? AND run_id = ? AND status = 'running'";
713
+ let where = input.workId ? "project_id = ? AND run_id = ? AND work_id = ? AND status = 'running'" : "project_id = ? AND run_id = ? AND status = 'running'";
153
714
  const params = input.workId ? [input.projectId, input.runId, input.workId] : [input.projectId, input.runId];
715
+ if (input.receiptId) {
716
+ where += " AND id = ?";
717
+ params.push(input.receiptId);
718
+ }
154
719
  const pending = context.db.all(`SELECT id, receipt_path, started_at FROM check_receipts WHERE ${where}`, params);
155
720
  if (pending.length === 0)
156
721
  return [];
157
722
  const processes = managedProcessStatus(context);
158
723
  const reconciled = [];
159
724
  for (const pendingReceipt of pending) {
160
- const process = processes.filter((item) => item.check_id === pendingReceipt.id).at(-1);
725
+ const process = processes.filter((item) => item.check_id === pendingReceipt.id && item.project_id === input.projectId && item.run_id === input.runId).at(-1);
161
726
  const receipt = readReceipt(pendingReceipt.receipt_path);
727
+ const authority = context.db.get("SELECT * FROM check_receipts WHERE project_id = ? AND id = ?", [input.projectId, pendingReceipt.id]);
728
+ if ((receipt?.fingerprint_scope ?? null) !== (authority?.fingerprint_scope ?? null)
729
+ || authority?.fingerprint_scope === "check_inputs" && JSON.stringify(receipt?.input_manifest ?? null) !== authority.input_manifest_json)
730
+ throw new AppError("check_receipt_changed", "Detached receipt scope or input manifest differs from SQL custody", 2, { check_receipt_id: pendingReceipt.id });
162
731
  const completion = receipt ? readCompletion(receipt.completion_path || path.join(path.dirname(pendingReceipt.receipt_path), "completion.json")) : null;
163
732
  // A stale lease after host sleep is not permission to duplicate a living
164
733
  // check. Its durable completion marker or explicit reconciliation decides
165
734
  // the outcome before another invocation may start.
166
- if (process && ["starting", "running", "stopping"].includes(process.state) && (processTreeIsAlive(process) || (process.state === "starting" && (managedOwnerIsAlive(process) !== false || Date.parse(process.lease_expires_at) > Date.parse(context.now()))))) {
735
+ // A confirmed PID plus its birth time is sufficient to prove that this
736
+ // exact check writer is gone. Do not retain a dead receipt merely because
737
+ // older registrations lack the optional parent-owner identity.
738
+ const processProvenDead = Boolean(process?.pid && process.pid_started_at && !processTreeIsAlive(process));
739
+ if (process && !processProvenDead && (processTreeIsAlive(process) || (["starting", "running", "stopping", "orphaned"].includes(process.state) && managedOwnerIsAlive(process) !== false))) {
167
740
  throw new AppError("check_in_progress", "A previous check invocation is still running", 1, { check_receipt_id: pendingReceipt.id, process_id: process.id, pid: process.pid });
168
741
  }
169
742
  if (!process && !completion && Date.now() - Date.parse(pendingReceipt.started_at) < receiptStartingGraceMs) {
170
743
  throw new AppError("check_in_progress", "A previous check invocation is still initializing", 1, { check_receipt_id: pendingReceipt.id, initializing: true });
171
744
  }
172
745
  const after = workspaceState(input.workspaceRoot, input.runHome ? [input.runHome] : []);
173
- const artifacts = receipt ? collectRequiredArtifacts(path.join(path.dirname(receipt.completion_path || pendingReceipt.receipt_path), "artifacts"), receipt.required_artifacts ?? []) : { complete: false, missing: [], items: [] };
174
- const workspaceUnchanged = receipt?.before_fingerprint === after.fingerprint;
175
- const status = completion === null ? "aborted" : completion.exit_code === 0 && workspaceUnchanged && artifacts.complete ? "passed" : "failed";
746
+ let artifacts = receipt ? collectCheckArtifacts(path.join(path.dirname(receipt.completion_path || pendingReceipt.receipt_path), "artifacts"), receipt.required_artifacts ?? []) : { complete: false, missing: [], items: [] };
747
+ const scoped = receipt?.fingerprint_scope === "check_inputs";
748
+ const completionSnapshot = scoped && completion?.fingerprint_scope === "check_inputs" && completion.id === receipt.id && completion.input_hash === receipt.input_hash
749
+ && completion.verification_epoch === receipt.verification_epoch && completion.before_fingerprint === receipt.before_fingerprint
750
+ && JSON.stringify(completion.input_manifest ?? null) === JSON.stringify(receipt.input_manifest ?? null) && typeof completion.after_fingerprint === "string";
751
+ const afterFingerprint = scoped ? completionSnapshot ? completion.after_fingerprint : workspaceInputFingerprint(input.workspaceRoot, after.files, receipt.inputs ?? [], input.runHome ? [input.runHome] : []) : after.fingerprint;
752
+ const workspaceUnchanged = receipt?.before_fingerprint === afterFingerprint;
753
+ const beforeFiles = scoped ? retainedInputFiles(receipt) : null;
754
+ // A completion digest describes that instant, not the later recovery tree.
755
+ // Without an after manifest, never attach today's delta to that old proof.
756
+ const mutationPaths = workspaceUnchanged ? [] : scoped && completionSnapshot ? ["<declared check inputs differed at completion; exact delta unavailable>"]
757
+ : scoped && beforeFiles ? changedPaths(beforeFiles, selectedInputFiles(input.workspaceRoot, after.files, receipt.inputs ?? [], input.runHome ? [input.runHome] : []))
758
+ : [scoped ? "<declared check inputs changed; exact manifest unavailable>" : "<workspace changed while detached check ran>"];
759
+ const runnerRead = receipt?.runner_evidence_required ? readRunnerEvidenceDetailed(path.join(path.dirname(pendingReceipt.receipt_path), "artifacts"), receipt.runner_evidence_required, { invocation_id: receipt.id, check_id: receipt.id, command: receipt.command, input_hash: receipt.input_hash, verification_epoch: receipt.verification_epoch }) : undefined;
760
+ const runnerEvidence = runnerRead?.evidence;
176
761
  const exitCode = completion?.exit_code ?? null;
177
762
  const finishedAt = completion?.finished_at ?? context.now();
178
- context.db.run("UPDATE check_receipts SET status = ?, exit_code = ?, after_fingerprint = ?, mutation_paths_json = ?, artifacts_json = ?, finished_at = ? WHERE id = ? AND project_id = ? AND status = 'running'", [status, exitCode, after.fingerprint, JSON.stringify(workspaceUnchanged ? [] : ["<workspace changed while detached check ran>"]), JSON.stringify(artifacts.items), finishedAt, pendingReceipt.id, input.projectId]);
763
+ const physicalFailures = executionFailures({ fingerprintScope: scoped ? "check_inputs" : undefined, exitCode, missing: artifacts.missing.filter(file => file !== "engine-outcome.json"), mutations: mutationPaths, invalidRunner: Boolean(receipt?.runner_evidence_required && !runnerEvidence) });
764
+ if (scoped && !completionSnapshot)
765
+ physicalFailures.push({ code: "completion_snapshot_unknown", message: "Detached check has no bound scoped completion snapshot; current inputs cannot prove inputs at command completion" });
766
+ let candidateFiles = candidateFailureFiles(runnerEvidence, input.workspaceRoot);
767
+ let candidateAbsences = candidateFailureAbsences(runnerEvidence, input.workspaceRoot);
768
+ if (receipt?.runner_evidence_required) {
769
+ const evidenceDir = path.join(path.dirname(pendingReceipt.receipt_path), "artifacts");
770
+ if (fs.existsSync(path.join(evidenceDir, "engine-outcome.json"))) {
771
+ // A completed live writer's bound proof is already authoritative. Never erase its blockers during reconciliation.
772
+ const retained = context.db.get("SELECT artifacts_json FROM check_receipts WHERE id = ?", [pendingReceipt.id]);
773
+ const proven = resolvedReceiptArtifacts(pendingReceipt.receipt_path, retained ? JSON.parse(retained.artifacts_json) : [], receipt);
774
+ if (proven.candidate_root) {
775
+ physicalFailures.push(...(proven.execution_failures ?? []));
776
+ candidateFiles = proven.candidate_files ?? candidateFiles;
777
+ candidateAbsences = proven.candidate_absences ?? [];
778
+ }
779
+ else {
780
+ physicalFailures.push({ code: "engine_outcome_unbound", message: "Existing execution outcome is not bound to retained inventory; prior launcher/cleanup outcome is unknown" });
781
+ fs.renameSync(path.join(evidenceDir, "engine-outcome.json"), path.join(evidenceDir, `engine-outcome-unconfirmed-${crypto.randomUUID()}.json`));
782
+ }
783
+ }
784
+ retainExecutionOutcome(evidenceDir, receipt, input.workspaceRoot, physicalFailures, candidateFiles, candidateAbsences);
785
+ receipt.required_artifacts = [...new Set([...(receipt.required_artifacts ?? []), ...runnerProofArtifacts(runnerEvidence), "engine-outcome.json"])];
786
+ artifacts = collectCheckArtifacts(evidenceDir, receipt.required_artifacts);
787
+ }
788
+ const status = completion === null ? "aborted" : completion.exit_code === 0 && workspaceUnchanged && artifacts.complete && physicalFailures.length === 0 && (!receipt?.runner_evidence_required || runnerEvidencePass(runnerEvidence)) ? "passed" : "failed";
789
+ context.db.run("UPDATE check_receipts SET status = ?, exit_code = ?, after_fingerprint = ?, mutation_paths_json = ?, artifacts_json = ?, finished_at = ? WHERE id = ? AND project_id = ? AND status = 'running'", [status, exitCode, afterFingerprint, JSON.stringify(mutationPaths), JSON.stringify(artifacts.items), finishedAt, pendingReceipt.id, input.projectId]);
790
+ context.db.run("UPDATE check_receipts SET execution_failures_json = ? WHERE project_id = ? AND id = ?", [JSON.stringify(physicalFailures), input.projectId, pendingReceipt.id]);
179
791
  if (process)
180
792
  finishManagedProcess(context, { id: process.id, leaseToken: process.lease_token, state: status === "passed" ? "stopped" : "failed", reason: status === "passed" ? "reconciled_completion" : completion === null ? "completion_marker_missing" : "reconciled_check_failed" });
181
793
  if (receipt) {
182
- const repaired = { ...receipt, completion_path: receipt.completion_path || path.join(path.dirname(pendingReceipt.receipt_path), "completion.json"), required_artifacts: receipt.required_artifacts ?? [], status, exit_code: exitCode, after_fingerprint: after.fingerprint, mutation_paths: workspaceUnchanged ? [] : ["<workspace changed while detached check ran>"], artifacts: artifacts.items, finished_at: finishedAt };
794
+ const repaired = { ...receipt, ...(receipt.runner_evidence_required ? { runner_evidence: runnerEvidence ?? null, runner_evidence_diagnostics: runnerRead.diagnostics, ...(runnerRead?.diagnostics_truncated ? { runner_evidence_diagnostics_truncated: true } : {}) } : {}), completion_path: receipt.completion_path || path.join(path.dirname(pendingReceipt.receipt_path), "completion.json"), required_artifacts: receipt.required_artifacts ?? [], ...(status === "aborted" ? { abort_reason: "completion_marker_missing" } : {}), status, exit_code: exitCode, after_fingerprint: afterFingerprint, mutation_paths: mutationPaths, artifacts: artifacts.items, finished_at: finishedAt };
795
+ repaired.candidate_root = input.workspaceRoot;
796
+ repaired.candidate_files = candidateFiles;
797
+ repaired.candidate_absences = candidateAbsences;
798
+ repaired.execution_failures = physicalFailures;
183
799
  writeReceipt(pendingReceipt.receipt_path, repaired);
800
+ if (status === "failed")
801
+ repaired.diagnostic_evidence_valid = checkReceiptEvidenceValidForMode(repaired, "diagnostic");
184
802
  reconciled.push(repaired);
185
803
  }
186
804
  }
187
805
  return reconciled;
188
806
  }
189
- function reserveReceipt(context, input) {
190
- context.db.exec("BEGIN IMMEDIATE");
191
- try {
192
- const rows = context.db.all("SELECT id FROM check_receipts WHERE work_id IS ? AND run_id = ?", [input.workId ?? null, input.runId]);
193
- const ordinal = rows.reduce((max, row) => Math.max(max, Number(/\/RCP-(\d+)$/.exec(row.id)?.[1] ?? 0)), 0) + 1;
194
- const localId = `RCP-${String(ordinal).padStart(3, "0")}`;
195
- const id = `${input.workId ?? input.runId}/${localId}`;
807
+ function reserveOrReuseReceipt(context, input) {
808
+ // Receipt files and artifact hashes are prepared before reserving SQLite.
809
+ // The compact SQL snapshot below fences races with another check settlement.
810
+ const snapshotSql = "SELECT * FROM check_receipts WHERE project_id = ? AND run_id = ? ORDER BY reservation_sequence, rowid";
811
+ const snapshot = JSON.stringify(context.db.all(snapshotSql, [input.projectId, input.runId]));
812
+ const receipts = checkReceipts(context, { projectId: input.projectId, runId: input.runId });
813
+ if (JSON.stringify(context.db.all(snapshotSql, [input.projectId, input.runId])) !== snapshot)
814
+ throw new AppError("check_receipt_changed", "Check receipts changed during evidence preparation", 1);
815
+ const prior = receipts.filter((receipt) => receipt.fingerprint_scope === "check_inputs" && receipt.input_hash === input.inputHash && receipt.profile_hash === input.profileHash).at(-1) ?? null;
816
+ const reusablePrior = prior?.status === "passed" && checkReceiptEvidenceValid(prior);
817
+ const retryIds = new Set([...(input.retryReceiptId ? [input.retryReceiptId] : []), ...(input.retryReceiptIds ?? [])]);
818
+ const successor = retryIds.size === 1 ? receipts.find((receipt) => receipt.retry_of_receipt_id === [...retryIds][0] && receipt.input_hash === input.inputHash && receipt.profile_hash === input.profileHash) : null;
819
+ const reusableSuccessor = successor?.status === "passed" && checkReceiptEvidenceValid(successor);
820
+ const retryPredecessor = receipts.find(receipt => retryIds.has(receipt.id));
821
+ const sourceCorrection = Boolean(retryPredecessor && (sourceRepairContractMatches(retryPredecessor, input.group, input.profileHash)
822
+ || input.retryReason === "check_inputs_changed" && staleRetryContractMatches(retryPredecessor, input.group, input.profileHash, input)));
823
+ const latestContract = receipts.filter(receipt => receipt.command === input.group.command && receipt.profile_hash === input.profileHash && receipt.gate === input.group.gate && receipt.scope === input.scope && receipt.work_id === (input.workId ?? null)).at(-1);
824
+ return context.db.writeTransaction(() => {
825
+ assertRunMutationAllowed(context, input.projectId, input.runId, input.generation);
826
+ if (JSON.stringify(context.db.all(snapshotSql, [input.projectId, input.runId])) !== snapshot)
827
+ throw new AppError("check_receipt_changed", "Check receipts changed before reservation", 1);
828
+ if (prior?.status === "running")
829
+ throw new AppError("check_in_progress", "A matching check invocation is still running", 1, { check_receipt_id: prior.id });
830
+ if (retryIds.size > 1)
831
+ throw new AppError("retry_check_invalid", "A check execution accepts exactly one retry predecessor", 2);
832
+ const retryId = [...retryIds][0];
833
+ if (retryId) {
834
+ if (input.retryReason === "check_inputs_changed" && retryPredecessor) {
835
+ const allSuccessors = receipts.filter(receipt => receipt.retry_of_receipt_id === retryId);
836
+ if (allSuccessors.length === 1 && reusableSuccessor)
837
+ return { receipt: successor };
838
+ if (retryPredecessor.retry_reason === "check_inputs_changed" || allSuccessors.length)
839
+ throw new AppError("retry_check_invalid", "Scoped input retry episode already consumed its one successor", 2, { check_receipt_id: retryId });
840
+ }
841
+ if (!input.retryReason?.trim())
842
+ throw new AppError("retry_check_invalid", "A check retry requires the restored-condition reason", 2, { check_receipt_id: retryId });
843
+ const predecessor = receipts.find(receipt => receipt.id === retryId);
844
+ if (!predecessor || !["failed", "aborted"].includes(predecessor.status) || predecessor.input_hash !== input.inputHash && !sourceCorrection || predecessor.profile_hash !== input.profileHash || predecessor.command !== input.group.command || predecessor.gate !== input.group.gate)
845
+ throw new AppError("retry_check_invalid", "Retry predecessor does not match this exact check contract", 2, { check_receipt_id: retryId });
846
+ if ((sourceCorrection ? latestContract?.id : prior?.id) !== (successor?.id ?? predecessor.id))
847
+ throw new AppError("retry_check_invalid", "This retry was superseded by a newer check outcome; inspect the latest receipt", 2, { check_receipt_id: retryId, latest_check_receipt_id: prior?.id ?? null, latest_status: prior?.status ?? null });
848
+ if (successor?.status === "running")
849
+ throw new AppError("check_in_progress", "The requested retry is already running", 1, { check_receipt_id: successor.id, retry_of_receipt_id: retryId });
850
+ if (successor) {
851
+ if (reusableSuccessor)
852
+ return { receipt: successor };
853
+ throw new AppError("retry_check_invalid", "The requested retry already has a terminal outcome; choose its failed receipt for another retry", 2, { check_receipt_id: successor.id, retry_of_receipt_id: retryId, status: successor.status });
854
+ }
855
+ }
856
+ // An unchanged failed contract needs a concrete restored-condition retry,
857
+ // not repeated coordinator finish until it happens to become green.
858
+ if (!retryId && latestContract?.fingerprint_scope === "check_inputs" && latestContract.status === "failed"
859
+ && latestContract.execution_failures?.some(failure => failure.code === "check_inputs_changed") && latestContract.execution_contract_hash === input.executionContractHash)
860
+ return { receipt: latestContract };
861
+ if (prior && ["failed", "aborted"].includes(prior.status) && !retryId)
862
+ return { receipt: prior };
863
+ if (prior?.status === "passed" && !retryIds.has(prior.id) && input.group.reusable && reusablePrior)
864
+ return { receipt: prior };
865
+ let ordinal = (context.db.get("SELECT COALESCE(MAX(reservation_sequence), 0) + 1 AS sequence FROM check_receipts WHERE project_id = ? AND run_id = ?", [input.projectId, input.runId])?.sequence ?? 1);
866
+ let localId = `RCP-${String(ordinal).padStart(3, "0")}`, id = `${input.workId ?? input.runId}/${localId}`;
867
+ while (context.db.get("SELECT 1 FROM check_receipts WHERE id = ?", [id])) {
868
+ ordinal += 1;
869
+ localId = `RCP-${String(ordinal).padStart(3, "0")}`;
870
+ id = `${input.workId ?? input.runId}/${localId}`;
871
+ }
196
872
  const directory = path.join(input.runHome, input.artifactDir ?? "05-code", "checks", localId);
197
- const reserved = { id, localId, directory, evidenceDir: path.join(directory, "artifacts"), stdoutPath: path.join(directory, "stdout.log"), stderrPath: path.join(directory, "stderr.log"), receiptPath: path.join(directory, "receipt.json"), completionPath: path.join(directory, "completion.json"), group: input.group, before: input.before, profileHash: input.profileHash, inputHash: input.inputHash, epoch: input.epoch, startedAt: input.startedAt, scope: input.scope, ...(input.workId ? { workId: input.workId } : {}), projectId: input.projectId, runId: input.runId };
198
- context.db.run("INSERT INTO check_receipts (id, project_id, run_id, work_id, scope, declaration_id, check_refs_json, gate, command, input_hash, verification_epoch, status, exit_code, stdout_path, stderr_path, receipt_path, workspace_fingerprint, before_fingerprint, after_fingerprint, profile_hash, mutation_paths_json, artifacts_json, started_at, finished_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', NULL, ?, ?, ?, ?, ?, ?, ?, '[]', '[]', ?, ?)", [id, input.projectId, input.runId, input.workId ?? null, input.scope, input.group.declarations[0].id, JSON.stringify(input.group.declarations.map(checkRef)), input.group.gate, input.group.command, input.inputHash, input.epoch, reserved.stdoutPath, reserved.stderrPath, reserved.receiptPath, input.before.fingerprint, input.before.fingerprint, input.before.fingerprint, input.profileHash, input.startedAt, input.startedAt]);
199
- context.db.exec("COMMIT");
200
- return reserved;
873
+ const reserved = { id, localId, directory, evidenceDir: path.join(directory, "artifacts"), stdoutPath: path.join(directory, "stdout.log"), stderrPath: path.join(directory, "stderr.log"), receiptPath: path.join(directory, "receipt.json"), completionPath: path.join(directory, "completion.json"), group: input.group, before: input.before, inputFiles: input.inputFiles, inputFingerprint: input.inputFingerprint, executionContractHash: input.executionContractHash, profileHash: input.profileHash, inputHash: input.inputHash, epoch: input.epoch, startedAt: input.startedAt, scope: input.scope, ...(retryId ? { retryOf: retryId, retryReason: input.retryReason } : {}), ...(input.workId ? { workId: input.workId } : {}), projectId: input.projectId, runId: input.runId, workspaceRoot: input.workspaceRoot, runHome: input.runHome };
874
+ context.db.run("INSERT INTO check_receipts (id, project_id, run_id, work_id, scope, declaration_id, check_refs_json, gate, command, input_hash, verification_epoch, reservation_sequence, retry_of_receipt_id, retry_reason, status, exit_code, stdout_path, stderr_path, receipt_path, workspace_fingerprint, before_fingerprint, after_fingerprint, profile_hash, mutation_paths_json, artifacts_json, started_at, finished_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', NULL, ?, ?, ?, ?, ?, ?, ?, '[]', '[]', ?, ?)", [id, input.projectId, input.runId, input.workId ?? null, input.scope, input.group.declarations[0].id, JSON.stringify(input.group.declarations.map(checkRef).sort()), input.group.gate, input.group.command, input.inputHash, input.epoch, ordinal, reserved.retryOf ?? null, reserved.retryReason ?? null, reserved.stdoutPath, reserved.stderrPath, reserved.receiptPath, input.before.fingerprint, input.before.fingerprint, input.before.fingerprint, input.profileHash, input.startedAt, input.startedAt]);
875
+ context.db.run("UPDATE check_receipts SET fingerprint_scope = ?, before_fingerprint = ?, after_fingerprint = ?, execution_contract_hash = ? WHERE id = ? AND project_id = ?", ["check_inputs", input.inputFingerprint, input.inputFingerprint, input.executionContractHash, id, input.projectId]);
876
+ return { reserved };
877
+ }, "checks.reserveOrReuseReceipt");
878
+ }
879
+ function sourceRepairContractMatches(receipt, group, profileHash) {
880
+ return checkRepairDisposition(receipt) === "source_repair" && group.command === receipt.command && profileHash === receipt.profile_hash && isDeepStrictEqual(group.inputs, receipt.inputs)
881
+ && isDeepStrictEqual(derivedReceiptArtifacts(group, receipt).sort(), [...receipt.required_artifacts].sort()) && isDeepStrictEqual([...group.ports].sort(), Object.keys(receipt.resources.ports).sort());
882
+ }
883
+ function staleCheckRetryEligible(receipt) {
884
+ if (receipt.fingerprint_scope !== "check_inputs" || receipt.status !== "failed" || receipt.exit_code !== 0 || receipt.retry_reason === "check_inputs_changed"
885
+ || !receipt.execution_failures?.length || receipt.execution_failures.some(failure => failure.code !== "check_inputs_changed")
886
+ || receipt.runner_evidence_required && !runnerEvidencePass(receipt.runner_evidence))
887
+ return false;
888
+ return checkReceiptEvidenceValidForMode(receipt, "diagnostic");
889
+ }
890
+ function staleRetryContractMatches(receipt, group, profileHash, input) {
891
+ return group.reusable && staleCheckRetryEligible(receipt) && isDeepStrictEqual(group.runnerEvidence ?? null, receipt.runner_evidence_required ?? null)
892
+ && receipt.execution_contract_hash === checkInputHash(input.workspaceRoot, group, profileHash, "", input.evidenceContext, input.checkEnvironment);
893
+ }
894
+ function receiptFor(input) { return { id: input.id, local_id: input.localId, declaration_id: input.group.declarations[0].id, check_refs: input.group.declarations.map(checkRef), gate: input.group.gate, scope: input.scope, work_id: input.workId ?? null, command: input.group.command, input_hash: input.inputHash, verification_epoch: input.epoch, retry_of_receipt_id: input.retryOf ?? null, retry_reason: input.retryReason ?? null, status: input.status, ...(input.status === "aborted" ? { abort_reason: input.result.error } : {}), exit_code: input.status === "running" ? null : input.result.exitCode, stdout_path: input.stdoutPath, stderr_path: input.stderrPath, receipt_path: input.receiptPath, completion_path: input.completionPath, required_artifacts: input.group.requiredArtifacts, inputs: input.group.inputs, fingerprint_scope: "check_inputs", input_manifest: input.inputManifest ?? null, execution_contract_hash: input.executionContractHash, workspace_fingerprint: input.before.fingerprint, before_fingerprint: input.inputFingerprint, after_fingerprint: input.status === "running" ? input.inputFingerprint : input.after.fingerprint, profile_hash: input.profileHash, mutation_paths: input.mutationPaths, artifacts: input.artifacts, resources: { ports: input.resources }, started_at: input.startedAt, finished_at: input.status === "running" ? input.startedAt : new Date().toISOString() }; }
895
+ function retainInputManifest(context, reserved) {
896
+ const full = JSON.stringify({ fingerprint_scope: "check_inputs", before_fingerprint: reserved.inputFingerprint, files: [...reserved.inputFiles].sort(([left], [right]) => left.localeCompare(right)) });
897
+ const truncated = Buffer.byteLength(full) > 1024 * 1024;
898
+ const bytes = truncated ? JSON.stringify({ fingerprint_scope: "check_inputs", before_fingerprint: reserved.inputFingerprint, truncated: true }) : full;
899
+ const relative = "inputs-before.json", file = path.join(reserved.directory, relative);
900
+ fs.writeFileSync(file, bytes, { flag: "wx", mode: 0o600 });
901
+ reserved.inputManifest = { path: relative, sha256: crypto.createHash("sha256").update(bytes).digest("hex"), truncated };
902
+ context.db.run("UPDATE check_receipts SET input_manifest_json = ? WHERE project_id = ? AND id = ? AND status = 'running'", [JSON.stringify(reserved.inputManifest), reserved.projectId, reserved.id]);
903
+ }
904
+ function retainedInputFiles(receipt) {
905
+ if (!receipt.input_manifest || receipt.input_manifest.truncated || receipt.input_manifest.path !== "inputs-before.json")
906
+ return null;
907
+ try {
908
+ const bytes = readBoundedReleaseFile(path.join(path.dirname(receipt.receipt_path), receipt.input_manifest.path), 1024 * 1024);
909
+ if (crypto.createHash("sha256").update(bytes).digest("hex") !== receipt.input_manifest.sha256)
910
+ return null;
911
+ const value = JSON.parse(bytes.toString("utf8"));
912
+ if (value.before_fingerprint !== receipt.before_fingerprint || !Array.isArray(value.files) || value.files.some((entry) => !Array.isArray(entry) || entry.length !== 2 || entry.some(item => typeof item !== "string")))
913
+ return null;
914
+ return new Map(value.files);
201
915
  }
202
- catch (error) {
203
- context.db.exec("ROLLBACK");
204
- throw error;
916
+ catch {
917
+ return null;
205
918
  }
206
919
  }
207
- function receiptFor(input) { return { id: input.id, local_id: input.localId, declaration_id: input.group.declarations[0].id, check_refs: input.group.declarations.map(checkRef), gate: input.group.gate, scope: input.scope, work_id: input.workId ?? null, command: input.group.command, input_hash: input.inputHash, verification_epoch: input.epoch, status: input.status, exit_code: input.status === "running" ? null : input.result.exitCode, stdout_path: input.stdoutPath, stderr_path: input.stderrPath, receipt_path: input.receiptPath, completion_path: input.completionPath, required_artifacts: input.group.requiredArtifacts, workspace_fingerprint: input.before.fingerprint, before_fingerprint: input.before.fingerprint, after_fingerprint: input.after.fingerprint, profile_hash: input.profileHash, mutation_paths: input.mutationPaths, artifacts: input.artifacts, resources: { ports: input.resources }, started_at: input.startedAt, finished_at: input.status === "running" ? input.startedAt : new Date().toISOString() }; }
920
+ function writeCompletionSnapshot(file, completion, receipt) {
921
+ const temporary = file + ".tmp-" + crypto.randomUUID();
922
+ fs.writeFileSync(temporary, JSON.stringify({ ...completion, fingerprint_scope: receipt.fingerprint_scope, id: receipt.id, input_hash: receipt.input_hash, verification_epoch: receipt.verification_epoch, before_fingerprint: receipt.before_fingerprint, after_fingerprint: receipt.after_fingerprint, input_manifest: receipt.input_manifest ?? null }));
923
+ fs.renameSync(temporary, file);
924
+ }
208
925
  function writeReceipt(file, receipt) { const temporary = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`; fs.writeFileSync(temporary, `${JSON.stringify(receipt, null, 2)}\n`); fs.renameSync(temporary, file); }
209
926
  function readReceipt(file) { try {
210
927
  return JSON.parse(fs.readFileSync(file, "utf8"));
@@ -215,35 +932,444 @@ catch {
215
932
  function readCompletion(file) { try {
216
933
  const value = JSON.parse(fs.readFileSync(file, "utf8"));
217
934
  const done = value;
218
- return value && typeof value === "object" && Number.isInteger(done.exit_code) ? { exit_code: Number(done.exit_code), finished_at: typeof done.finished_at === "string" && Number.isFinite(Date.parse(done.finished_at)) ? done.finished_at : null } : null;
935
+ return value && typeof value === "object" && Number.isInteger(done.exit_code) ? { ...done, exit_code: Number(done.exit_code), finished_at: typeof done.finished_at === "string" && Number.isFinite(Date.parse(done.finished_at)) ? done.finished_at : null } : null;
219
936
  }
220
937
  catch {
221
938
  return null;
222
939
  } }
223
- export function unchangedFinalGateFailures(context, input) { const wanted = new Set(input.declarations.flatMap((check) => [check.id, checkRef(check)])); const current = workspaceFingerprint(input.workspaceRoot); const latest = new Map(); for (const receipt of checkReceipts(context, { projectId: input.projectId, runId: input.runId }).filter((item) => item.scope === "aggregate" && item.check_refs.some((ref) => wanted.has(ref))))
224
- for (const ref of receipt.check_refs)
225
- latest.set(ref, receipt); return [...new Set(latest.values())].filter((receipt) => receipt.status === "failed" && receipt.before_fingerprint === current); }
940
+ /** Validate an explicit retry; the caller still executes a fresh real gate and retains a new receipt. */
941
+ export function validateFailedCheckRetry(context, input) {
942
+ if (!input.reason?.trim())
943
+ throw new AppError("retry_check_invalid", "--retry-check requires --reason describing the restored environment", 2);
944
+ const receipt = checkReceipts(context, { projectId: input.projectId, runId: input.runId }).find((item) => item.id === input.receiptId);
945
+ if (!receipt || !["failed", "aborted"].includes(receipt.status))
946
+ throw new AppError("retry_check_invalid", "--retry-check must name a failed or aborted receipt in this RUN", 2, { check_receipt_id: input.receiptId });
947
+ const declared = new Set(input.declarations.flatMap((check) => [check.id, checkRef(check)]));
948
+ if (!receipt.check_refs.some((ref) => declared.has(ref)))
949
+ throw new AppError("retry_check_invalid", "--retry-check does not belong to this stage gate", 2, { check_receipt_id: input.receiptId, check_refs: receipt.check_refs });
950
+ if (receipt.fingerprint_scope === "check_inputs" && receipt.execution_failures?.some(failure => failure.code === "check_inputs_changed") && input.reason !== "check_inputs_changed")
951
+ throw new AppError("retry_check_invalid", "Scoped drift uses its bounded stale transition, not an environment/source retry", 2, { check_receipt_id: receipt.id });
952
+ if (input.reason === "check_inputs_changed" && (!staleCheckRetryEligible(receipt) || receipt.retry_reason === "check_inputs_changed"))
953
+ throw new AppError("retry_check_invalid", "Scoped input retry requires a bound, safely completed stale predecessor and one unconsumed episode", 2, { check_receipt_id: receipt.id });
954
+ return receipt;
955
+ }
226
956
  export function checkReceipts(context, input) {
227
957
  const where = input.workId ? "project_id = ? AND run_id = ? AND work_id = ?" : "project_id = ? AND run_id = ?";
228
958
  const params = input.workId ? [input.projectId, input.runId, input.workId] : [input.projectId, input.runId];
229
- return context.db.all(`SELECT id, declaration_id, check_refs_json, gate, scope, work_id, command, input_hash, verification_epoch, status, exit_code, stdout_path, stderr_path, receipt_path, workspace_fingerprint, before_fingerprint, after_fingerprint, profile_hash, mutation_paths_json, artifacts_json, started_at, finished_at FROM check_receipts WHERE ${where} ORDER BY started_at, id`, params).map((row) => ({ ...row, local_id: row.id.slice(row.id.lastIndexOf("/") + 1), check_refs: parseArray(row.check_refs_json, [row.declaration_id]), mutation_paths: parseArray(row.mutation_paths_json, []), artifacts: JSON.parse(row.artifacts_json), resources: readReceiptResources(row.receipt_path) }));
959
+ return context.db.all(`SELECT * FROM check_receipts WHERE ${where} ORDER BY reservation_sequence, rowid`, params).map(projectCheckReceiptRow);
960
+ }
961
+ function projectCheckReceiptRow(row) {
962
+ const inputManifest = row.input_manifest_json ? JSON.parse(row.input_manifest_json) : null;
963
+ const receipt = { ...row, input_manifest: inputManifest, local_id: row.id.slice(row.id.lastIndexOf("/") + 1), check_refs: parseArray(row.check_refs_json, [row.declaration_id]), mutation_paths: parseArray(row.mutation_paths_json, []), resources: readReceiptResources(row.receipt_path), ...resolvedReceiptArtifacts(row.receipt_path, JSON.parse(row.artifacts_json), { ...row, input_manifest: inputManifest }), ...(row.execution_failures_json ? { execution_failures: JSON.parse(row.execution_failures_json) } : {}) };
964
+ if (receipt.status === "failed")
965
+ receipt.diagnostic_evidence_valid = checkReceiptEvidenceValidForMode(receipt, "diagnostic");
966
+ return receipt;
967
+ }
968
+ /** File bytes remain immutable; only the reader projects their current location. */
969
+ function resolvedReceiptArtifacts(receiptPath, artifacts, binding) {
970
+ let original = {};
971
+ try {
972
+ const value = JSON.parse(fs.readFileSync(receiptPath, "utf8"));
973
+ if (value && typeof value === "object" && !Array.isArray(value))
974
+ original = value;
975
+ }
976
+ catch { /* Historical missing receipts remain visibly incomplete. */ }
977
+ const currentRoot = path.dirname(receiptPath);
978
+ const oldRoot = typeof original.receipt_path === "string" ? path.dirname(original.receipt_path) : currentRoot;
979
+ const relocate = (file) => {
980
+ const relative = path.relative(oldRoot, file);
981
+ return !path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`) ? path.join(currentRoot, relative) : file;
982
+ };
983
+ let evidence = null;
984
+ let diagnostics = [];
985
+ let diagnosticsTruncated = false;
986
+ if (original.runner_evidence_required && original.id && original.command && original.input_hash && original.verification_epoch) {
987
+ const root = path.join(currentRoot, "artifacts");
988
+ const retained = collectCheckArtifacts(root, [original.runner_evidence_required.path]);
989
+ if (retained.complete && retained.items.every(item => artifacts.some(artifact => relocate(artifact.path) === item.path && artifact.sha256 === item.sha256))) {
990
+ const read = readRunnerEvidenceDetailed(root, original.runner_evidence_required, { invocation_id: binding.id, check_id: binding.id, command: binding.command, input_hash: binding.input_hash, verification_epoch: binding.verification_epoch });
991
+ evidence = read.evidence;
992
+ diagnostics = read.diagnostics;
993
+ diagnosticsTruncated = Boolean(read.diagnostics_truncated);
994
+ }
995
+ else
996
+ diagnostics = [{ reason: retained.complete ? "artifact_mismatch" : "missing", report: original.runner_evidence_required.path }];
997
+ }
998
+ let outcome = {};
999
+ const outcomePath = path.join(currentRoot, "artifacts", "engine-outcome.json");
1000
+ const retainedOutcome = collectCheckArtifacts(path.join(currentRoot, "artifacts"), ["engine-outcome.json"]);
1001
+ if (retainedOutcome.complete && retainedOutcome.items.every(item => artifacts.some(artifact => relocate(artifact.path) === item.path && artifact.sha256 === item.sha256))) {
1002
+ try {
1003
+ const value = JSON.parse(fs.readFileSync(outcomePath, "utf8"));
1004
+ if (value.schema_id === "dd-flow/check-execution-outcome@1" && value.id === binding.id && value.command === binding.command && value.input_hash === binding.input_hash && value.verification_epoch === binding.verification_epoch && (value.fingerprint_scope ?? null) === (binding.fingerprint_scope ?? null) && (value.execution_contract_hash ?? null) === (binding.execution_contract_hash ?? null) && JSON.stringify(value.input_manifest ?? null) === JSON.stringify(binding.input_manifest ?? null) && typeof value.candidate_root === "string" && path.isAbsolute(value.candidate_root) && (value.candidate_files === undefined || Array.isArray(value.candidate_files) && value.candidate_files.length <= 64 && value.candidate_files.every((file) => typeof file === "string" && path.isAbsolute(file) && Buffer.byteLength(file) <= 4096)) && (value.candidate_absences === undefined || candidateAbsencesValid(value.candidate_absences)) && Array.isArray(value.execution_failures) && value.execution_failures.every((failure) => failure && typeof failure === "object" && typeof failure.code === "string" && typeof failure.message === "string"))
1005
+ outcome = value;
1006
+ }
1007
+ catch { /* Missing physical proof cannot grant attribution. */ }
1008
+ }
1009
+ return { completion_path: path.join(currentRoot, "completion.json"), required_artifacts: original.required_artifacts ?? [], inputs: original.inputs ?? [], artifacts: artifacts.map((artifact) => ({ ...artifact, path: relocate(artifact.path) })), ...(original.runner_evidence_required ? { runner_evidence_required: original.runner_evidence_required, runner_evidence: evidence, runner_evidence_diagnostics: diagnostics, ...(diagnosticsTruncated ? { runner_evidence_diagnostics_truncated: true } : {}) } : {}), execution_failures: outcome.execution_failures ?? [], ...(outcome.candidate_root ? { candidate_root: outcome.candidate_root } : {}), ...(outcome.candidate_files ? { candidate_files: outcome.candidate_files } : {}), ...(outcome.candidate_absences ? { candidate_absences: outcome.candidate_absences } : {}) };
1010
+ }
1011
+ function executionFailures(input) {
1012
+ const failures = [];
1013
+ if (input.exitCode === null)
1014
+ failures.push({ code: "completion_unknown", message: "Check completion is unknown" });
1015
+ if (input.launcherError)
1016
+ failures.push({ code: "launcher_error", message: input.launcherError });
1017
+ if (input.cleanupUnconfirmed)
1018
+ failures.push({ code: "cleanup_unconfirmed", message: "Check process cleanup is not confirmed" });
1019
+ if (input.missing.length)
1020
+ failures.push({ code: "missing_required_artifact", message: input.missing.join(", ") });
1021
+ if (input.mutations.length)
1022
+ failures.push({ code: input.fingerprintScope === "check_inputs" ? "check_inputs_changed" : "check_input_mutated", message: input.mutations.join(", ") });
1023
+ if (input.invalidRunner)
1024
+ failures.push({ code: "invalid_runner_evidence", message: "Required runner evidence is unavailable or invalid" });
1025
+ return failures;
1026
+ }
1027
+ function retainExecutionOutcome(evidenceDir, binding, candidateRoot, failures, candidateFiles, candidateAbsences = []) {
1028
+ const temporary = path.join(evidenceDir, `.engine-outcome-${crypto.randomUUID()}.tmp`);
1029
+ if (!fs.lstatSync(evidenceDir).isDirectory() || fs.lstatSync(evidenceDir).isSymbolicLink())
1030
+ throw new AppError("check_evidence_stale", "Check evidence directory was replaced", 1);
1031
+ fs.writeFileSync(temporary, JSON.stringify({ schema_id: "dd-flow/check-execution-outcome@1", id: binding.id, command: binding.command, input_hash: binding.input_hash, verification_epoch: binding.verification_epoch, fingerprint_scope: binding.fingerprint_scope ?? null, input_manifest: binding.input_manifest ?? null, execution_contract_hash: binding.execution_contract_hash ?? null, candidate_root: candidateRoot, candidate_files: candidateFiles, candidate_absences: candidateAbsences, execution_failures: failures }), { flag: "wx", mode: 0o600 });
1032
+ fs.renameSync(temporary, path.join(evidenceDir, "engine-outcome.json"));
230
1033
  }
231
1034
  export function workspaceFingerprint(root) { return workspaceState(root).fingerprint; }
232
- export function workspaceChangedPaths(root) { const status = spawnSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); if (status.status !== 0)
233
- return null; return status.stdout.split("\0").filter(Boolean).map((entry) => entry.slice(3)).filter(Boolean).sort(); }
234
- function deduplicate(checks, commands) { const groups = new Map(); checks.forEach((check, index) => { const artifacts = [...(check.required_artifacts ?? [])].sort(); const ports = [...(check.ports ?? [])].sort(); const key = JSON.stringify([check.run_at, commands[index], artifacts, ports]); const current = groups.get(key); if (current)
235
- current.declarations.push(check);
236
- else
237
- groups.set(key, { gate: check.run_at, command: commands[index], declarations: [check], requiredArtifacts: artifacts, ports }); }); return [...groups.values()]; }
238
- function workspaceState(root, ignoredRoots = []) { const git = spawnSync("git", ["ls-files", "-co", "--exclude-standard", "-z"], { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); const ignored = ignoredRoots.map((entry) => path.resolve(entry)); const listing = (git.status === 0 ? git.stdout.split("\0").filter(Boolean).sort() : listFiles(root)).filter((relative) => { const file = path.resolve(root, relative); return !ignored.some((ignoredRoot) => file === ignoredRoot || file.startsWith(`${ignoredRoot}${path.sep}`)); }); const files = new Map(); const hash = crypto.createHash("sha256"); for (const relative of listing) {
239
- const file = path.join(root, relative);
240
- const content = fs.existsSync(file) && fs.statSync(file).isFile() ? fs.readFileSync(file) : Buffer.from("<missing>");
241
- const digest = crypto.createHash("sha256").update(content).digest("hex");
242
- files.set(relative, digest);
243
- hash.update(relative).update("\0").update(digest).update("\0");
244
- } return { fingerprint: hash.digest("hex"), files }; }
1035
+ /** One NUL-aware source of truth for paths differing from HEAD. Rename/copy
1036
+ * records carry a second path; retain both because the old side is a deletion. */
1037
+ export function workspaceChangedPaths(root) {
1038
+ const status = spawnSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { cwd: root, env: { ...process.env, LC_ALL: "C" }, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
1039
+ // A workspace can be intentionally gitless. Keep the same conservative
1040
+ // file inventory used for fingerprints instead of making result validation
1041
+ // fail before the work contract can report its actual error.
1042
+ if (isGitlessWorkspace(root, status))
1043
+ return listFiles(root);
1044
+ if (status.status !== 0 || status.error)
1045
+ throw new AppError("workspace_status_failed", "Could not determine changed workspace paths", 1, { workspace_root: root, stderr: status.stderr || null, cause: status.error?.message ?? null });
1046
+ const records = status.stdout.split("\0");
1047
+ const paths = [];
1048
+ for (let index = 0; index < records.length; index += 1) {
1049
+ const record = records[index];
1050
+ if (!record)
1051
+ continue;
1052
+ if (record.length < 4 || record[2] !== " ")
1053
+ throw new AppError("workspace_status_invalid", "Git returned an invalid porcelain-v1 record", 1, { workspace_root: root, record });
1054
+ paths.push(normalizeWorkspacePath(root, record.slice(3)));
1055
+ if (record[0] === "R" || record[0] === "C" || record[1] === "R" || record[1] === "C") {
1056
+ const prior = records[++index];
1057
+ if (!prior)
1058
+ throw new AppError("workspace_status_invalid", "Git rename/copy record is missing its second path", 1, { workspace_root: root, record });
1059
+ paths.push(normalizeWorkspacePath(root, prior));
1060
+ }
1061
+ }
1062
+ const ownedHook = paths.includes(".agents/hooks.json") ? ownedWorkspaceHookPath(root) : null;
1063
+ return [...new Set(paths)].filter(file => file !== ownedHook).sort();
1064
+ }
1065
+ /** Ignored machine state cannot be reported as a product change. Tracked paths
1066
+ * remain eligible regardless of their directory name. */
1067
+ export function ignoredWorkspacePaths(root, paths) {
1068
+ const normalized = [...new Set(paths.map((item) => normalizeWorkspacePath(root, item)))];
1069
+ if (!normalized.length)
1070
+ return [];
1071
+ const status = spawnSync("git", ["check-ignore", "-z", "--stdin"], { cwd: root, env: { ...process.env, LC_ALL: "C" }, encoding: "utf8", input: `${normalized.join("\0")}\0`, maxBuffer: 64 * 1024 * 1024 });
1072
+ // The canonical owned hook has one meaning across Git status, check cache
1073
+ // and MERGE, without changing a sibling worktree's shared Git excludes.
1074
+ const gitless = isGitlessWorkspace(root, status);
1075
+ if (!gitless && (![0, 1].includes(status.status ?? -1) || status.error))
1076
+ throw new AppError("workspace_ignore_check_failed", "Could not classify reported workspace paths", 1, { workspace_root: root, stderr: status.stderr || null, cause: status.error?.message ?? null });
1077
+ const ownedHook = normalized.includes(".agents/hooks.json") ? ownedWorkspaceHookPath(root, gitless ? [] : undefined) : null;
1078
+ if (gitless)
1079
+ return ownedHook ? [ownedHook] : [];
1080
+ return [...new Set([...status.stdout.split("\0").filter(Boolean).map((item) => normalizeWorkspacePath(root, item)), ...(ownedHook ? [ownedHook] : [])])].sort();
1081
+ }
1082
+ export function normalizeWorkspacePath(root, value) {
1083
+ if (typeof value !== "string" || !value || value.includes("\0") || path.isAbsolute(value))
1084
+ throw new AppError("workspace_path_invalid", "Workspace path must be a non-empty relative path", 2, { path: value });
1085
+ const resolvedRoot = path.resolve(root);
1086
+ const resolved = path.resolve(resolvedRoot, value);
1087
+ const relative = path.relative(resolvedRoot, resolved);
1088
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
1089
+ throw new AppError("workspace_path_invalid", "Workspace path escapes its root", 2, { path: value, workspace_root: root });
1090
+ return relative.split(path.sep).join("/");
1091
+ }
1092
+ function deduplicate(checks, commands) {
1093
+ const groups = new Map();
1094
+ checks.forEach((check, index) => {
1095
+ const artifacts = [...(check.required_artifacts ?? [])].sort(), ports = [...(check.ports ?? [])].sort(), inputs = normalizedInputs(check.inputs ?? []);
1096
+ const reusable = check.reuse === "deterministic";
1097
+ // Stage labels identify obligations, not different processes in this gate.
1098
+ // Cross-invocation reuse still requires the explicit deterministic contract.
1099
+ const environmentInputs = normalizedEnvironmentInputs(check.environment_inputs);
1100
+ const key = JSON.stringify([commands[index], artifacts, ports, inputs, reusable, environmentInputs, check.runner_evidence ?? null]);
1101
+ const current = groups.get(key);
1102
+ if (current)
1103
+ current.declarations.push(check);
1104
+ else
1105
+ groups.set(key, { gate: check.run_at, command: commands[index], declarations: [check], requiredArtifacts: artifacts, ports, inputs, reusable, ...(environmentInputs === undefined ? {} : { environmentInputs }), ...(check.runner_evidence ? { runnerEvidence: check.runner_evidence } : {}) });
1106
+ });
1107
+ return [...groups.values()].map(group => ({ ...group, gate: [...group.declarations].map(check => check.run_at).sort()[0], declarations: [...group.declarations].sort((left, right) => checkRef(left).localeCompare(checkRef(right))) }));
1108
+ }
1109
+ function workspaceState(root, ignoredRoots = []) {
1110
+ const git = workspaceGitFiles(root, ["-co", "--exclude-standard"]);
1111
+ const ignored = ignoredRoots.map(entry => path.resolve(entry));
1112
+ const listing = [...new Set(git ?? listFiles(root))].sort();
1113
+ const ownedHook = listing.includes(".agents/hooks.json") ? ownedWorkspaceHookPath(root, git ? undefined : []) : null;
1114
+ const files = new Map(), hash = crypto.createHash("sha256");
1115
+ for (const relative of listing) {
1116
+ if (relative === ownedHook)
1117
+ continue;
1118
+ const file = path.resolve(root, relative);
1119
+ if (ignored.some(ignoredRoot => file === ignoredRoot || file.startsWith(`${ignoredRoot}${path.sep}`)))
1120
+ continue;
1121
+ // Deleted tracked paths are absent content, both before and after commit.
1122
+ // Do not mask other IO errors as an unchanged workspace.
1123
+ let stat;
1124
+ try {
1125
+ stat = fs.lstatSync(file);
1126
+ }
1127
+ catch (error) {
1128
+ if (error.code === "ENOENT")
1129
+ continue;
1130
+ throw error;
1131
+ }
1132
+ const content = stat.isSymbolicLink() ? Buffer.from(`symlink\0${fs.readlinkSync(file)}`) : stat.isFile() ? fs.readFileSync(file) : Buffer.from("<directory>");
1133
+ const digest = crypto.createHash("sha256").update(content).digest("hex");
1134
+ files.set(relative, digest);
1135
+ hash.update(relative).update("\0").update(digest).update("\0");
1136
+ }
1137
+ return { fingerprint: hash.digest("hex"), files };
1138
+ }
1139
+ function selectedInputFiles(root, files, inputs, ignoredRoots) {
1140
+ const selected = new Map(inputs.length === 0 || inputs.includes(".") ? files : []);
1141
+ for (const [file, digest] of explicitInputFiles(root, inputs.filter(input => input !== "."), ignoredRoots, files.keys()))
1142
+ selected.set(file, digest);
1143
+ return selected;
1144
+ }
1145
+ function workspaceInputFingerprint(root, files, inputs, ignoredRoots) {
1146
+ return inputFilesFingerprint(selectedInputFiles(root, files, inputs, ignoredRoots));
1147
+ }
1148
+ function inputFilesFingerprint(selected) {
1149
+ const hash = crypto.createHash("sha256");
1150
+ for (const [file, digest] of [...selected].sort(([left], [right]) => left.localeCompare(right)))
1151
+ hash.update(file).update("\0").update(digest).update("\0");
1152
+ return hash.digest("hex");
1153
+ }
245
1154
  function changedPaths(before, after) { return [...new Set([...before.keys(), ...after.keys()])].filter((key) => before.get(key) !== after.get(key)).sort(); }
246
1155
  function checkRef(check) { return check.canonical_ref ?? check.id; }
1156
+ function assertConsistentDeclarations(checks, commands) {
1157
+ const seen = new Map();
1158
+ for (const [index, check] of checks.entries()) {
1159
+ const contract = JSON.stringify([check.run_at, commands[index], [...(check.required_artifacts ?? [])].sort(), [...(check.ports ?? [])].sort(), normalizedInputs(check.inputs ?? []), check.reuse ?? null, normalizedEnvironmentInputs(check.environment_inputs), check.runner_evidence ?? null]);
1160
+ const ref = checkRef(check), prior = seen.get(ref);
1161
+ if (prior && prior !== contract)
1162
+ throw new AppError("check_declaration_conflict", "The same check reference has conflicting execution definitions", 2, { check_ref: ref });
1163
+ seen.set(ref, contract);
1164
+ }
1165
+ }
1166
+ function normalizedEnvironmentInputs(value) {
1167
+ if (value === undefined)
1168
+ return undefined;
1169
+ if (!Array.isArray(value) || !value.length || value.length > 64 || value.some(name => typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*\*?$/.test(name)))
1170
+ throw new AppError("invalid_check_environment_inputs", "Internal check environment inputs must be bounded names or prefixes", 2, { effect: "no_effect" });
1171
+ return [...new Set(value)].sort();
1172
+ }
1173
+ function environmentFingerprint(workspaceRoot, inputs, checkEnvironment) {
1174
+ const environment = codeExecutionEnvironment(workspaceRoot, checkEnvironment);
1175
+ // Invocation authority is checked by its own owners, not an application check
1176
+ // input. Preserve arbitrary application variables (including DD_FLOW_PORT_*)
1177
+ // and tool selection; omit only known process/control bookkeeping.
1178
+ const bookkeeping = new Set(["PWD", "OLDPWD", "SHLVL", "_", "DD_FLOW_DAEMON_ID",
1179
+ "DD_FLOW_CURRENT_INVOCATION", "DD_FLOW_INVOCATION_READONLY", "DD_FLOW_INVOCATION_SCOPE", "DD_FLOW_CODEX_STATE_DIR",
1180
+ "DD_FLOW_HOOK_DEADLINE_AT", // Per-call transport budget, not a project check input.
1181
+ "DD_FLOW_RUNTIME_OWNER", "DD_FLOW_CONTROLLER_TOKEN", "DD_FLOW_CONTROL_TOKEN", "DD_FLOW_SCOPE_CONTROL_TOKEN",
1182
+ "DD_FLOW_BIN", "DD_FLOW_ENGINE_HOME", "DD_FLOW_RUNTIME_BUDGET", "DD_FLOW_WORK_ID", "DD_FLOW_SESSION_ID", "CODEX_THREAD_ID", "DD_EVAL_OPERATION_ID",
1183
+ "CODEX_PERMISSION_PROFILE", "CODEX_SESSION_ID", "CODEX_VERSION", "CODEX_TOOL_CALL_ID"]);
1184
+ return crypto.createHash("sha256").update(JSON.stringify(Object.entries(environment)
1185
+ .filter(([name, value]) => value !== undefined && !bookkeeping.has(name)
1186
+ && (name === "PLAYWRIGHT_BROWSERS_PATH" || inputs === undefined || inputs.some(input => input.endsWith("*") ? name.startsWith(input.slice(0, -1)) : name === input)))
1187
+ .sort(([left], [right]) => left.localeCompare(right)))).digest("hex");
1188
+ }
1189
+ function acquireWorkspaceGate(context, input) {
1190
+ const operationId = workspaceOperationId(input.workspaceRoot);
1191
+ const active = managedProcessStatus(context).find(item => item.operation_id === operationId && ["starting", "running", "stopping"].includes(item.state));
1192
+ if (active)
1193
+ throw new AppError("check_in_progress", "The workspace is owned by another bootstrap or check; observe it before starting a new check", 1, { process_id: active.id, operation_id: operationId });
1194
+ return registerManagedProcess(context, { kind: "workspace-gate", ownerPid: process.pid, ownerId: `workspace-gate:${crypto.randomUUID()}`, operationId, uniqueActiveOperation: true, projectId: input.projectId, runId: input.runId, metadata: { workspace_root: input.workspaceRoot, role: "check_gate" } });
1195
+ }
1196
+ export function reconcileWorkspaceOwnership(context, workspaceRoot) {
1197
+ const operationId = workspaceOperationId(workspaceRoot);
1198
+ const active = managedProcessStatus(context).filter(item => item.operation_id === operationId && ["starting", "running", "stopping", "orphaned"].includes(item.state));
1199
+ if (active.some(item => processTreeIsAlive(item) || managedOwnerIsAlive(item) !== false))
1200
+ return;
1201
+ // Registry IDs are host-wide, whereas receipts belong to one runtime DB.
1202
+ // An unknown/foreign home must not be settled against this client's rows.
1203
+ if (active.some(item => managedProcessRuntimeHome(item, context) !== context.ddFlowHome))
1204
+ return;
1205
+ for (const child of active.filter(item => item.kind !== "workspace-gate")) {
1206
+ if (child.kind !== "check" || !child.project_id || !child.run_id || !child.check_id)
1207
+ return;
1208
+ const run = context.db.get("SELECT run_root FROM runs WHERE project_id = ? AND id = ?", [child.project_id, child.run_id]);
1209
+ if (!run?.run_root || !context.db.get("SELECT 1 FROM check_receipts WHERE id = ? AND project_id = ? AND run_id = ?", [child.check_id, child.project_id, child.run_id]))
1210
+ return;
1211
+ reconcileUnfinishedChecks(context, { projectId: child.project_id, runId: child.run_id, workspaceRoot, runHome: run.run_root, receiptId: child.check_id });
1212
+ // A crash may occur after receipt settlement but before registry settlement.
1213
+ const current = managedProcessStatus(context).find(item => item.id === child.id);
1214
+ if (!current || current.lease_token !== child.lease_token)
1215
+ return;
1216
+ if (!["stopped", "failed"].includes(current.state) && !finishManagedProcess(context, { id: child.id, leaseToken: child.lease_token, state: "stopped", reason: "workspace_check_owner_reconciled" }))
1217
+ return;
1218
+ }
1219
+ for (const gate of active.filter(item => item.kind === "workspace-gate"))
1220
+ finishManagedProcess(context, { id: gate.id, leaseToken: gate.lease_token, state: "stopped", reason: "workspace_gate_owner_reconciled" });
1221
+ }
1222
+ function normalizedInputs(inputs) { for (const input of inputs)
1223
+ validateCheckInputSyntax(input); return [...new Set(inputs.map((input) => { const normalized = path.posix.normalize(input.replaceAll("\\", "/")).replace(/^\.\/$/, ""); return normalized === "" || normalized === "." ? "." : normalized.replace(/\/$/, ""); }))].sort(); }
1224
+ function validateCheckInputs(workspaceRoot, inputs) { const root = fs.realpathSync.native(workspaceRoot); const allowed = sourceInputPathFilter(workspaceRoot, inputs); for (const input of normalizedInputs(inputs)) {
1225
+ if (input.split("/").some(part => [".git", "node_modules"].includes(part)))
1226
+ throw new AppError("invalid_check_input", "Check inputs cannot include Git internals or installed dependencies; declare lock/config inputs", 2, { input });
1227
+ const candidate = path.resolve(workspaceRoot, input);
1228
+ if (candidate !== workspaceRoot && !candidate.startsWith(`${workspaceRoot}${path.sep}`))
1229
+ throw new AppError("invalid_check_input", "Check inputs must stay within the workspace", 2, { input });
1230
+ if (fs.existsSync(candidate))
1231
+ validateInputTree(root, candidate, input, new Set(), allowed);
1232
+ else
1233
+ validateMissingInputParent(root, candidate, input);
1234
+ } }
1235
+ /** Directory scopes select source inventory, not generated Git-ignored output.
1236
+ * Direct ignored inputs (e.g. a real config) remain explicit obligations. */
1237
+ function sourceInputPathFilter(root, inputs, sourceFiles) {
1238
+ const listing = sourceFiles ? [...sourceFiles] : workspaceGitFiles(root, ["-co", "--exclude-standard"]);
1239
+ const retained = new Set([...(listing ?? []), ...inputs]), branches = new Set();
1240
+ for (const file of retained)
1241
+ for (let parent = path.posix.dirname(file); parent !== "." && parent !== "/"; parent = path.posix.dirname(parent))
1242
+ branches.add(parent);
1243
+ const explicitTrees = inputs.filter(input => !listing?.some(file => file === input || file.startsWith(`${input}/`)));
1244
+ const serviceAllowed = projectServicePathFilter(root, inputs, listing ?? []);
1245
+ return file => {
1246
+ const relative = path.relative(root, file).split(path.sep).join("/");
1247
+ if (relative.split("/").some(part => [".git", "node_modules"].includes(part)) || !serviceAllowed(file))
1248
+ return false;
1249
+ return listing === null || retained.has(relative) || branches.has(relative) || explicitTrees.some(input => relative.startsWith(`${input}/`));
1250
+ };
1251
+ }
1252
+ function validateCheckInputSyntax(input) { if (typeof input !== "string" || !input.trim() || path.isAbsolute(input) || input.split(/[\\/]/).includes(".."))
1253
+ throw new AppError("invalid_check_input", "Check inputs must be non-empty relative workspace paths", 2, { input }); }
1254
+ function validateMissingInputParent(root, candidate, input) { let parent = candidate; while (!fs.existsSync(parent))
1255
+ parent = path.dirname(parent); const resolved = fs.realpathSync.native(parent); if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`))
1256
+ throw new AppError("invalid_check_input", "Check input parent symlink escapes the workspace", 2, { input }); }
1257
+ function validateInputTree(root, candidate, input, seen, allowed) {
1258
+ const resolved = fs.realpathSync.native(candidate);
1259
+ if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`))
1260
+ throw new AppError("invalid_check_input", "Check input symlink escapes the workspace", 2, { input });
1261
+ if (seen.has(resolved))
1262
+ throw new AppError("invalid_check_input", "Check input contains a symbolic-link cycle", 2, { input });
1263
+ seen.add(resolved);
1264
+ const stat = fs.statSync(candidate);
1265
+ if (stat.isDirectory() && fs.lstatSync(candidate).isSymbolicLink())
1266
+ throw new AppError("invalid_check_input", "Directory symlinks cannot prove scoped source inputs; declare their contained real source path instead", 2, { input });
1267
+ if (stat.isDirectory())
1268
+ for (const entry of fs.readdirSync(candidate)) {
1269
+ const file = path.join(candidate, entry);
1270
+ if (allowed(file))
1271
+ validateInputTree(root, file, input, seen, allowed);
1272
+ }
1273
+ seen.delete(resolved);
1274
+ }
1275
+ function explicitInputFiles(root, inputs, ignoredRoots, sourceFiles) {
1276
+ const rootReal = fs.realpathSync.native(root), ignored = ignoredRoots.map(entry => path.resolve(entry)), result = new Map();
1277
+ const allowed = sourceInputPathFilter(root, inputs, sourceFiles);
1278
+ const visit = (file, relative, seen) => {
1279
+ if (ignored.some(entry => file === entry || file.startsWith(`${entry}${path.sep}`)))
1280
+ return;
1281
+ if (!fs.existsSync(file)) {
1282
+ result.set(relative, "<missing>");
1283
+ return;
1284
+ }
1285
+ const resolved = fs.realpathSync.native(file);
1286
+ if (resolved !== rootReal && !resolved.startsWith(`${rootReal}${path.sep}`))
1287
+ throw new AppError("invalid_check_input", "Check input symlink escapes the workspace", 2, { input: relative });
1288
+ if (seen.has(resolved))
1289
+ throw new AppError("invalid_check_input", "Check input contains a symbolic-link cycle", 2, { input: relative });
1290
+ const symbolic = fs.lstatSync(file).isSymbolicLink();
1291
+ const stat = fs.statSync(file);
1292
+ if (symbolic && stat.isDirectory())
1293
+ throw new AppError("invalid_check_input", "Directory symlinks cannot prove scoped source inputs; declare their contained real source path instead", 2, { input: relative });
1294
+ if (stat.isDirectory()) {
1295
+ seen.add(resolved);
1296
+ for (const entry of fs.readdirSync(file).sort()) {
1297
+ const child = path.join(file, entry);
1298
+ if (allowed(child))
1299
+ visit(child, path.posix.join(relative, entry), seen);
1300
+ }
1301
+ seen.delete(resolved);
1302
+ }
1303
+ else if (stat.isFile())
1304
+ result.set(relative, crypto.createHash("sha256").update(symbolic ? `symlink\0${fs.readlinkSync(file)}\0` : "").update(fs.readFileSync(file)).digest("hex"));
1305
+ };
1306
+ for (const input of inputs)
1307
+ visit(path.resolve(root, input), input, new Set());
1308
+ return [...result.entries()];
1309
+ }
1310
+ function checkInputHash(workspaceRoot, group, profileHash, inputFingerprint, evidenceContext, checkEnvironment) { return crypto.createHash("sha256").update(JSON.stringify({ workspace_root: path.resolve(workspaceRoot), gate: group.reusable ? null : group.gate, command: group.command, required_artifacts: group.requiredArtifacts, ports: group.ports, inputs: group.inputs, ...(group.runnerEvidence ? { runner_evidence: group.runnerEvidence } : {}), profile_hash: profileHash, environment: environmentFingerprint(workspaceRoot, group.environmentInputs, checkEnvironment), input_fingerprint: inputFingerprint, ...(group.environmentInputs === undefined ? {} : { environment_inputs: group.environmentInputs }), ...(evidenceContext === undefined ? {} : { evidence_context: evidenceContext }) })).digest("hex"); }
1311
+ function derivedReceiptArtifacts(group, receipt) { return [...new Set([...group.requiredArtifacts, ...runnerProofArtifacts(receipt.runner_evidence), ...(receipt.required_artifacts.includes("engine-outcome.json") ? ["engine-outcome.json"] : [])])]; }
1312
+ function bindReceipt(receipt, group) { return { ...receipt, gate: group.gate, declaration_id: group.declarations[0].id, check_refs: group.declarations.map(checkRef), required_artifacts: derivedReceiptArtifacts(group, receipt), inputs: group.inputs }; }
1313
+ export function checkReceiptEvidenceValid(receipt) { return checkReceiptEvidenceValidForMode(receipt); }
1314
+ function checkReceiptEvidenceValidForMode(receipt, mode) {
1315
+ try {
1316
+ const staleDiagnostic = mode === "diagnostic" && receipt.fingerprint_scope === "check_inputs" && receipt.status === "failed" && Number.isInteger(receipt.exit_code)
1317
+ && receipt.before_fingerprint !== receipt.after_fingerprint && receipt.mutation_paths.length > 0 && receipt.execution_failures?.some(failure => failure.code === "check_inputs_changed");
1318
+ if (receipt.fingerprint_scope != null && receipt.fingerprint_scope !== "check_inputs")
1319
+ return false;
1320
+ if (receipt.fingerprint_scope === "check_inputs") {
1321
+ const completion = readCompletion(receipt.completion_path);
1322
+ if (!completion || completion.fingerprint_scope !== "check_inputs" || completion.id !== receipt.id || completion.input_hash !== receipt.input_hash
1323
+ || completion.verification_epoch !== receipt.verification_epoch || completion.before_fingerprint !== receipt.before_fingerprint || completion.after_fingerprint !== receipt.after_fingerprint
1324
+ || JSON.stringify(completion.input_manifest ?? null) !== JSON.stringify(receipt.input_manifest ?? null))
1325
+ return false;
1326
+ if (!receipt.input_manifest || receipt.input_manifest.path !== "inputs-before.json")
1327
+ return false;
1328
+ const manifestBytes = readBoundedReleaseFile(path.join(path.dirname(receipt.receipt_path), receipt.input_manifest.path), 1024 * 1024);
1329
+ if (crypto.createHash("sha256").update(manifestBytes).digest("hex") !== receipt.input_manifest.sha256)
1330
+ return false;
1331
+ }
1332
+ if (!(receipt.status === "passed" && receipt.exit_code === 0 || mode === "diagnostic" && receipt.status === "failed" && typeof receipt.exit_code === "number" && receipt.exit_code !== 0 || staleDiagnostic) || !staleDiagnostic && receipt.before_fingerprint !== receipt.after_fingerprint
1333
+ || !staleDiagnostic && receipt.mutation_paths.length !== 0 || receipt.completion_path !== path.join(path.dirname(receipt.receipt_path), "completion.json")
1334
+ || readCompletion(receipt.completion_path)?.exit_code !== receipt.exit_code)
1335
+ return false;
1336
+ const stored = readReceipt(receipt.receipt_path);
1337
+ if (!stored || typeof stored !== "object" || Array.isArray(stored)
1338
+ || typeof stored.receipt_path !== "string" || !path.isAbsolute(stored.receipt_path)
1339
+ || path.basename(stored.receipt_path) !== "receipt.json"
1340
+ || stored.completion_path !== path.join(path.dirname(stored.receipt_path), "completion.json"))
1341
+ return false;
1342
+ // Gate/ref labels may be rebound for explicit deterministic reuse. Physical
1343
+ // execution identity and settled SQL evidence must never be rebound from a
1344
+ // mutable receipt file, including after recovery relocates the RUN home.
1345
+ const fields = ["fingerprint_scope", "execution_contract_hash", "id", "scope", "work_id", "command", "input_hash", "verification_epoch", "status", "exit_code",
1346
+ "workspace_fingerprint", "before_fingerprint", "after_fingerprint", "profile_hash", "started_at", "finished_at"];
1347
+ if (JSON.stringify(stored.input_manifest ?? null) !== JSON.stringify(receipt.input_manifest ?? null))
1348
+ return false;
1349
+ if (fields.some(field => (stored[field] ?? null) !== (receipt[field] ?? null)) || !Array.isArray(stored.artifacts)
1350
+ || !Array.isArray(stored.mutation_paths) || !isDeepStrictEqual(stored.mutation_paths, receipt.mutation_paths)
1351
+ || JSON.stringify(stored.required_artifacts) !== JSON.stringify(receipt.required_artifacts)
1352
+ || JSON.stringify(stored.inputs) !== JSON.stringify(receipt.inputs))
1353
+ return false;
1354
+ const retainedProof = resolvedReceiptArtifacts(receipt.receipt_path, stored.artifacts, receipt);
1355
+ const retained = retainedProof.artifacts;
1356
+ if (JSON.stringify(retained) !== JSON.stringify(receipt.artifacts))
1357
+ return false;
1358
+ // Receipt annotations are not execution authority. Compare the SQL-owned
1359
+ // failures with the independently hash/binding-checked engine sidecar.
1360
+ const hasEngineOutcome = receipt.required_artifacts.includes("engine-outcome.json") || receipt.artifacts.some(artifact => artifact.path === "engine-outcome.json" || artifact.path === path.join(path.dirname(receipt.receipt_path), "artifacts", "engine-outcome.json"));
1361
+ if (hasEngineOutcome && (!isDeepStrictEqual(retainedProof.execution_failures ?? [], receipt.execution_failures ?? []) || !isDeepStrictEqual(retainedProof.candidate_absences ?? [], receipt.candidate_absences ?? [])))
1362
+ return false;
1363
+ const root = path.join(path.dirname(receipt.receipt_path), "artifacts");
1364
+ if (stored.runner_evidence_required && mode !== "diagnostic" && !runnerEvidencePass(readRunnerEvidence(root, stored.runner_evidence_required, { invocation_id: receipt.id, check_id: receipt.id, command: receipt.command, input_hash: receipt.input_hash, verification_epoch: receipt.verification_epoch })))
1365
+ return false;
1366
+ const artifacts = collectCheckArtifacts(root, receipt.required_artifacts);
1367
+ return artifacts.complete && JSON.stringify(artifacts.items) === JSON.stringify(retained);
1368
+ }
1369
+ catch {
1370
+ return false;
1371
+ }
1372
+ }
247
1373
  function parseArray(value, fallback) { try {
248
1374
  const parsed = JSON.parse(value);
249
1375
  return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : fallback;
@@ -252,8 +1378,14 @@ catch {
252
1378
  return fallback;
253
1379
  } }
254
1380
  function isStringRecord(value) { return Boolean(value) && typeof value === "object" && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string" && item.trim().length > 0); }
255
- function isGateRecord(value) { return Boolean(value) && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([gate, aliases]) => ["work", "code", "readiness", "merge", "release", "external"].includes(gate) && Array.isArray(aliases) && aliases.every((item) => typeof item === "string" && item.startsWith("@check/"))); }
1381
+ function isGateRecord(value) { return Boolean(value) && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([gate, aliases]) => ["work", "code", "readiness", "merge", "release"].includes(gate) && Array.isArray(aliases) && aliases.every((item) => typeof item === "string" && item.startsWith("@check/"))); }
256
1382
  function isPortAliasRecord(value) { return value === undefined || (Boolean(value) && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([alias, ports]) => alias.startsWith("@check/") && Array.isArray(ports) && ports.length > 0 && new Set(ports).size === ports.length && ports.every((port) => typeof port === "string" && /^[A-Za-z][A-Za-z0-9_]*$/.test(port)))); }
1383
+ function isInputAliasRecord(workspaceRoot, value) { try {
1384
+ return value === undefined || (Boolean(value) && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([alias, inputs]) => alias.startsWith("@check/") && Array.isArray(inputs) && (validateCheckInputs(workspaceRoot, inputs), true)));
1385
+ }
1386
+ catch {
1387
+ return false;
1388
+ } }
257
1389
  function portEnvironment(ports) { return Object.fromEntries(Object.entries(ports).map(([name, value]) => [`DD_FLOW_PORT_${name.toUpperCase()}`, String(value)])); }
258
1390
  function readReceiptResources(file) { try {
259
1391
  const value = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -262,88 +1394,235 @@ function readReceiptResources(file) { try {
262
1394
  catch {
263
1395
  return { ports: {} };
264
1396
  } }
265
- function collectRequiredArtifacts(root, required) { const missing = []; const items = []; for (const relative of required) {
266
- if (path.isAbsolute(relative) || relative.split(/[\\/]/).includes(".."))
267
- throw new AppError("invalid_evidence_path", "Required evidence paths must be relative to DD_FLOW_EVIDENCE_DIR", 2, { path: relative });
268
- const file = path.join(root, relative);
269
- if (!fs.existsSync(file) || !fs.statSync(file).isFile()) {
270
- missing.push(relative);
271
- continue;
272
- }
273
- items.push({ path: relative, sha256: crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex") });
274
- } return { complete: missing.length === 0, missing, items }; }
275
- function listFiles(root, current = root) { return fs.readdirSync(current, { withFileTypes: true }).flatMap((entry) => { if ([".git", "node_modules"].includes(entry.name))
276
- return []; const absolute = path.join(current, entry.name); return entry.isDirectory() ? listFiles(root, absolute) : [path.relative(root, absolute)]; }).sort(); }
277
- export function runCheck(command, cwd, environment, stdout, stderr, heartbeat, onSpawn, renewLease) {
1397
+ function collectCheckArtifacts(root, required) {
1398
+ for (const relative of required) {
1399
+ if (path.isAbsolute(relative) || relative.split(/[\\/]/).includes(".."))
1400
+ throw new AppError("invalid_evidence_path", "Required evidence paths must be relative to DD_FLOW_EVIDENCE_DIR", 2, { path: relative });
1401
+ }
1402
+ // Required paths are minimum obligations; retain all explicit check evidence.
1403
+ // Never follow symlinks, including a replaced evidence root.
1404
+ const items = [];
1405
+ const visit = (directory) => {
1406
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1407
+ const file = path.join(directory, entry.name);
1408
+ if (entry.isDirectory())
1409
+ visit(file);
1410
+ else if (entry.isFile())
1411
+ items.push({ path: path.relative(root, file), sha256: crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex") });
1412
+ }
1413
+ };
1414
+ if (fs.existsSync(root) && fs.lstatSync(root).isDirectory())
1415
+ visit(root);
1416
+ items.sort((a, b) => a.path.localeCompare(b.path));
1417
+ const retained = new Set(items.map((item) => item.path));
1418
+ const missing = required.filter((relative) => !retained.has(path.normalize(relative)));
1419
+ return { complete: missing.length === 0, missing, items };
1420
+ }
1421
+ function listFiles(root) {
1422
+ const allowed = projectServicePathFilter(root, [], []);
1423
+ const ownedHook = ownedWorkspaceHookPath(root, []);
1424
+ const visit = (current) => fs.readdirSync(current, { withFileTypes: true }).flatMap(entry => {
1425
+ const absolute = path.join(current, entry.name);
1426
+ if ([".git", "node_modules"].includes(entry.name) || !allowed(absolute))
1427
+ return [];
1428
+ return entry.isDirectory() ? visit(absolute) : [path.relative(root, absolute)];
1429
+ });
1430
+ return visit(root).filter(file => file.split(path.sep).join("/") !== ownedHook).sort();
1431
+ }
1432
+ export function runCheck(command, cwd, environment, stdout, stderr, heartbeat, onSpawn, renewLease, observation = {}) {
1433
+ const inactivityTimeoutMs = validateObservationDuration(observation.inactivityTimeoutMs ?? 30 * 60_000);
1434
+ const { startupMs: runnerStartupMs, executionMs: runnerExecutionMs } = runnerObservationDurations(environment.DD_FLOW_CHECK_RUNNER_PROGRESS_PATH ? environment : {});
278
1435
  return new Promise((resolve) => {
279
1436
  const started = Date.now();
280
- const child = spawn("/bin/sh", ["-lc", checkShellScript()], { cwd, env: { ...environment, DD_FLOW_CHECK_COMMAND: command }, stdio: ["ignore", stdout, stderr], detached: process.platform !== "win32" });
1437
+ const child = spawn("/bin/sh", ["-c", checkShellScript()], { cwd, env: { ...environment, DD_FLOW_CHECK_COMMAND: command }, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
281
1438
  let error = null;
1439
+ let failure;
282
1440
  let stopping = false;
1441
+ let closed = false;
1442
+ let admitted = false;
283
1443
  let progress;
284
- let escalation;
1444
+ let cleanup;
1445
+ let cleanupUnconfirmed = false;
1446
+ const renewal = createRenewalState();
1447
+ let renewalTimer;
1448
+ const clock = new ObservationClock({ timeoutMs: inactivityTimeoutMs });
1449
+ let outputCursor = 0;
1450
+ let runnerSequence = 0;
1451
+ let runnerPhase = "startup";
1452
+ const runnerProgress = environment.DD_FLOW_CHECK_RUNNER_PROGRESS_PATH;
1453
+ const runnerClock = runnerProgress ? new ObservationClock({ timeoutMs: runnerStartupMs }) : null;
1454
+ const outputs = [fs.createWriteStream("", { fd: stdout, autoClose: false }), fs.createWriteStream("", { fd: stderr, autoClose: false })];
1455
+ const flushed = outputs.map(output => new Promise(resolve => { output.once("finish", resolve); output.once("error", () => resolve()); }));
285
1456
  const stop = (cause) => {
286
1457
  if (stopping)
287
1458
  return;
288
1459
  stopping = true;
289
1460
  error = cause instanceof Error ? cause.message : String(cause);
1461
+ if (cause instanceof AppError)
1462
+ failure = { code: cause.code, message: cause.message };
290
1463
  if (progress) {
291
1464
  clearInterval(progress);
292
1465
  progress = undefined;
293
1466
  }
294
- if (child.pid) {
295
- terminateProcessGroup(child.pid, "SIGTERM");
296
- escalation = setTimeout(() => terminateProcessGroup(child.pid, "SIGKILL"), 5_000);
297
- }
1467
+ if (renewalTimer)
1468
+ clearTimeout(renewalTimer);
1469
+ if (observationTimer)
1470
+ clearInterval(observationTimer);
1471
+ cleanup = stopProcessGroup(child, 5_000).catch(cause => {
1472
+ cleanupUnconfirmed = true;
1473
+ error = `${error}; cleanup: ${JSON.stringify(errorRecord(cause))}`;
1474
+ resolve({ exitCode: null, error, aborted: true, cleanupUnconfirmed, ...(failure ? { failure } : {}) });
1475
+ });
298
1476
  };
1477
+ const observationTimer = setInterval(() => {
1478
+ if (stopping || closed || !admitted || observation.phase?.() === "serving")
1479
+ return;
1480
+ if (runnerClock && runnerProgress) {
1481
+ try {
1482
+ for (const event of readRunnerProgress(runnerProgress, environment.DD_FLOW_CHECK_INVOCATION_ID ?? "", runnerSequence)) {
1483
+ runnerSequence = event.sequence;
1484
+ if (runnerPhase !== "execution")
1485
+ runnerPhase = event.phase;
1486
+ runnerClock.sample(runnerSequence, Date.parse(event.at));
1487
+ }
1488
+ // The outer guard includes the runner's bounded cleanup tail.
1489
+ runnerClock.timeoutMs = runnerPhase === "execution" ? runnerExecutionMs : runnerStartupMs;
1490
+ if (runnerClock.sample(runnerSequence))
1491
+ stop(new AppError("operation_observation_lost", "Structured test runner stopped making progress", 1, { phase: runnerPhase, sequence: runnerSequence }));
1492
+ }
1493
+ catch (cause) {
1494
+ stop(cause);
1495
+ }
1496
+ return;
1497
+ }
1498
+ if (clock.sample(outputCursor))
1499
+ stop(new AppError("operation_observation_lost", "Owned command has no confirmed progress within its inactivity window", 1, { phase: observation.phase?.() ?? "finite", inactivity_timeout_ms: inactivityTimeoutMs }));
1500
+ }, Math.min(1000, inactivityTimeoutMs));
299
1501
  // Register handlers before checking pid or calling persistence callbacks.
300
1502
  // Failure is not completion until the spawned process has actually closed.
301
1503
  child.once("error", (value) => { error = value.message; });
302
- child.once("close", (exitCode, signal) => {
1504
+ for (const [index, stream] of [child.stdout, child.stderr].entries()) {
1505
+ outputs[index].once("error", stop);
1506
+ stream.on("data", () => { if (!runnerClock) {
1507
+ outputCursor++;
1508
+ clock.sample(outputCursor);
1509
+ } });
1510
+ stream.pipe(outputs[index]);
1511
+ }
1512
+ child.stdin.on("error", stop);
1513
+ child.once("close", async (exitCode, signal) => {
1514
+ closed = true;
303
1515
  if (progress)
304
1516
  clearInterval(progress);
305
- if (escalation)
306
- clearTimeout(escalation);
307
- if (stopping)
308
- terminateProcessGroup(child.pid, "SIGKILL");
309
- resolve({ exitCode, error: error ?? (signal ? `terminated by ${signal}` : null), aborted: stopping || Boolean(signal) || Boolean(error) });
1517
+ if (renewalTimer)
1518
+ clearTimeout(renewalTimer);
1519
+ if (observationTimer)
1520
+ clearInterval(observationTimer);
1521
+ await cleanup;
1522
+ await Promise.all(flushed);
1523
+ resolve({ exitCode, error: error ?? (signal ? `terminated by ${signal}` : null), aborted: stopping || Boolean(signal) || Boolean(error), ...(cleanupUnconfirmed ? { cleanupUnconfirmed } : {}), ...(failure ? { failure } : {}) });
310
1524
  });
311
1525
  if (!child.pid) {
312
1526
  error = "check process did not provide a PID";
313
1527
  return;
314
1528
  }
315
- try {
316
- onSpawn(child.pid);
317
- }
318
- catch (cause) {
319
- stop(cause);
320
- return;
321
- }
322
- progress = setInterval(() => {
1529
+ const renew = () => {
1530
+ if (stopping || closed)
1531
+ return;
1532
+ if (renewalTimer) {
1533
+ clearTimeout(renewalTimer);
1534
+ renewalTimer = undefined;
1535
+ }
323
1536
  try {
324
- if (!renewLease()) {
1537
+ renewal.uncertainSince ??= performance.now();
1538
+ const remaining = renewalRemaining(renewal);
1539
+ if (!remaining) {
1540
+ stop("managed process renewal budget exhausted");
1541
+ return;
1542
+ }
1543
+ const receipt = renewLease(Math.min(RENEWAL_POLICY.attemptMs, remaining));
1544
+ if (receipt === false || typeof receipt === "object" && !receipt.owned) {
325
1545
  stop("managed process lease lost");
326
1546
  return;
327
1547
  }
1548
+ if (typeof receipt === "object" && receipt.owned) {
1549
+ const expiry = Date.parse(receipt.lease_expires_at);
1550
+ if (!Number.isFinite(expiry))
1551
+ throw new AppError("managed_lease_receipt_invalid", "Check renewal returned invalid expiry", 1);
1552
+ if (expiry <= Date.now())
1553
+ throw Object.assign(new Error("Check renewal receipt expired before acknowledgement"), { code: "process_maintenance_timeout" });
1554
+ }
1555
+ if (!renewalConfirmed(renewal, performance.now(), typeof receipt === "object" && receipt.owned ? receipt.lease_expires_at : null)) {
1556
+ stop("managed process renewal budget exhausted");
1557
+ return;
1558
+ }
1559
+ }
1560
+ catch (cause) {
1561
+ if (!maintenanceRetryable(cause) || !renewalFailure(renewal)) {
1562
+ stop(cause);
1563
+ return;
1564
+ }
1565
+ renewalTimer = setTimeout(renew, Math.min(renewalDelay(renewal), renewalRemaining(renewal)));
1566
+ return;
1567
+ }
1568
+ // A progress callback error is not a retryable renewal failure.
1569
+ try {
328
1570
  heartbeat(Math.floor((Date.now() - started) / 1000));
329
1571
  }
330
1572
  catch (cause) {
331
1573
  stop(cause);
332
1574
  }
333
- }, 15_000);
1575
+ };
1576
+ // The shell is held on stdin: a no-effect identity read may be retried,
1577
+ // but never the command or an admission callback with unknown effects.
1578
+ const confirmation = createRenewalState();
1579
+ confirmation.uncertainSince = performance.now();
1580
+ let confirmationError;
1581
+ const admit = () => {
1582
+ renewalTimer = undefined;
1583
+ if (stopping || closed)
1584
+ return;
1585
+ if (confirmationError && !renewalRemaining(confirmation)) {
1586
+ stop(confirmationError);
1587
+ return;
1588
+ }
1589
+ try {
1590
+ onSpawn(child.pid);
1591
+ }
1592
+ catch (cause) {
1593
+ if (cause instanceof AppError && cause.code === "process_ownership_unknown"
1594
+ && cause.details.reason === "physical_identity_unavailable" && maintenanceRetryable(cause)
1595
+ && renewalFailure(confirmation)) {
1596
+ confirmationError = cause;
1597
+ renewalTimer = setTimeout(admit, Math.min(renewalDelay(confirmation), renewalRemaining(confirmation)));
1598
+ return;
1599
+ }
1600
+ stop(cause);
1601
+ return;
1602
+ }
1603
+ if (observation.leaseExpiresAt) {
1604
+ const expiry = observation.leaseExpiresAt();
1605
+ if (!expiry || !renewalConfirmed(renewal, performance.now(), expiry)) {
1606
+ stop("check confirmation has no current authority");
1607
+ return;
1608
+ }
1609
+ }
1610
+ admitted = true;
1611
+ child.stdin.end("admitted\n");
1612
+ clock.sample(++outputCursor);
1613
+ progress = setInterval(renew, 15_000);
1614
+ };
1615
+ admit();
334
1616
  });
335
1617
  }
336
1618
  function checkShellScript() {
337
1619
  return [
1620
+ // The actual command cannot run before PID ownership and admission persist.
1621
+ 'IFS= read -r admission && [ "$admission" = admitted ] || exit 125',
338
1622
  'completion="${DD_FLOW_CHECK_COMPLETION_FILE:-}"',
339
- '/bin/sh -lc "$DD_FLOW_CHECK_COMMAND"',
1623
+ '/bin/sh -c "$DD_FLOW_CHECK_COMMAND"',
340
1624
  "code=$?",
341
1625
  'if [ -n "$completion" ]; then temporary="$completion.tmp.$$"; printf \'{"exit_code":%s,"finished_at":"%s"}\\n\' "$code" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$temporary" && mv "$temporary" "$completion"; fi',
342
1626
  'exit "$code"'
343
1627
  ].join("\n");
344
1628
  }
345
- function terminateProcessGroup(pid, signal) { if (!pid)
346
- return; try {
347
- process.kill(process.platform === "win32" ? pid : -pid, signal);
348
- }
349
- catch { /* already exited */ } }