@deksden-com/dd-flow-cli 0.9.0-beta.16 → 0.9.0-beta.161

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