@gpustack/loopwright 0.0.0-stage → 0.0.2

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 (477) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +356 -2
  3. package/bin/loopwright.js +3 -0
  4. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
  5. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
  6. package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
  7. package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
  8. package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
  9. package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
  10. package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
  11. package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
  12. package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
  13. package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
  14. package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
  15. package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
  16. package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
  17. package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
  18. package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
  19. package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
  20. package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
  21. package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
  22. package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
  23. package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
  24. package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
  25. package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
  26. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
  27. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
  28. package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
  29. package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
  30. package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
  31. package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
  32. package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
  33. package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
  34. package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
  35. package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
  36. package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
  37. package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
  38. package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
  39. package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
  40. package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
  41. package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
  42. package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
  43. package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
  44. package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
  45. package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
  46. package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
  47. package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
  48. package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
  49. package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
  50. package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
  51. package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
  52. package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
  53. package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
  54. package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
  55. package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
  56. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
  57. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
  58. package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
  59. package/node_modules/@loopwright/agent-pi/dist/host-session.js +2083 -0
  60. package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
  61. package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
  62. package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
  63. package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
  64. package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
  65. package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
  66. package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
  67. package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
  68. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
  69. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
  70. package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
  71. package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
  72. package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
  73. package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
  74. package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
  75. package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
  76. package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
  77. package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
  78. package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
  79. package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
  80. package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
  81. package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
  82. package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
  83. package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
  84. package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
  85. package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
  86. package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
  87. package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
  88. package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
  89. package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
  90. package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
  91. package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
  92. package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
  93. package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
  94. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
  95. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
  96. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
  97. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
  98. package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
  99. package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
  100. package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
  101. package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
  102. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
  103. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
  104. package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
  105. package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
  106. package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
  107. package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
  108. package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
  109. package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
  110. package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
  111. package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
  112. package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
  113. package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
  114. package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
  115. package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
  116. package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
  117. package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
  118. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
  119. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
  120. package/node_modules/@loopwright/agent-pi/package.json +24 -0
  121. package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
  122. package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
  123. package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
  124. package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
  125. package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
  126. package/node_modules/@loopwright/cli/dist/closure.js +230 -0
  127. package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
  128. package/node_modules/@loopwright/cli/dist/draft.js +106 -0
  129. package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
  130. package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
  131. package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
  132. package/node_modules/@loopwright/cli/dist/index.js +5 -0
  133. package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
  134. package/node_modules/@loopwright/cli/dist/main.js +1855 -0
  135. package/node_modules/@loopwright/cli/package.json +16 -0
  136. package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
  137. package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
  138. package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
  139. package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
  140. package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
  141. package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
  142. package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
  143. package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
  144. package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
  145. package/node_modules/@loopwright/controller/dist/capture.js +587 -0
  146. package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
  147. package/node_modules/@loopwright/controller/dist/compile.js +402 -0
  148. package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
  149. package/node_modules/@loopwright/controller/dist/config.js +255 -0
  150. package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
  151. package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
  152. package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
  153. package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
  154. package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
  155. package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
  156. package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
  157. package/node_modules/@loopwright/controller/dist/errors.js +41 -0
  158. package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
  159. package/node_modules/@loopwright/controller/dist/events.js +228 -0
  160. package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
  161. package/node_modules/@loopwright/controller/dist/files.js +386 -0
  162. package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
  163. package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
  164. package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
  165. package/node_modules/@loopwright/controller/dist/gate.js +640 -0
  166. package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
  167. package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
  168. package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
  169. package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
  170. package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
  171. package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
  172. package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
  173. package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
  174. package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
  175. package/node_modules/@loopwright/controller/dist/index.js +21 -0
  176. package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
  177. package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
  178. package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
  179. package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
  180. package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
  181. package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
  182. package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
  183. package/node_modules/@loopwright/controller/dist/parser.js +200 -0
  184. package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
  185. package/node_modules/@loopwright/controller/dist/progress.js +904 -0
  186. package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
  187. package/node_modules/@loopwright/controller/dist/publication.js +329 -0
  188. package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
  189. package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
  190. package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
  191. package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
  192. package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
  193. package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
  194. package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
  195. package/node_modules/@loopwright/controller/dist/registry.js +374 -0
  196. package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
  197. package/node_modules/@loopwright/controller/dist/repair.js +102 -0
  198. package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
  199. package/node_modules/@loopwright/controller/dist/report.js +596 -0
  200. package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
  201. package/node_modules/@loopwright/controller/dist/retained.js +193 -0
  202. package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
  203. package/node_modules/@loopwright/controller/dist/rules.js +110 -0
  204. package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
  205. package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
  206. package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
  207. package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
  208. package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
  209. package/node_modules/@loopwright/controller/dist/schema.js +78 -0
  210. package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
  211. package/node_modules/@loopwright/controller/dist/source.js +872 -0
  212. package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
  213. package/node_modules/@loopwright/controller/dist/step.js +1776 -0
  214. package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
  215. package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
  216. package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
  217. package/node_modules/@loopwright/controller/dist/submission.js +292 -0
  218. package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
  219. package/node_modules/@loopwright/controller/dist/types.js +9 -0
  220. package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
  221. package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
  222. package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
  223. package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
  224. package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
  225. package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
  226. package/node_modules/@loopwright/controller/package.json +12 -0
  227. package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
  228. package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
  229. package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
  230. package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
  231. package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
  232. package/node_modules/@loopwright/core/dist/boundary.js +484 -0
  233. package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
  234. package/node_modules/@loopwright/core/dist/contracts.js +694 -0
  235. package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
  236. package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
  237. package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
  238. package/node_modules/@loopwright/core/dist/evidence.js +85 -0
  239. package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
  240. package/node_modules/@loopwright/core/dist/graph.js +44 -0
  241. package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
  242. package/node_modules/@loopwright/core/dist/identity.js +80 -0
  243. package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
  244. package/node_modules/@loopwright/core/dist/index.js +39 -0
  245. package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
  246. package/node_modules/@loopwright/core/dist/limits.js +59 -0
  247. package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
  248. package/node_modules/@loopwright/core/dist/results.js +98 -0
  249. package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
  250. package/node_modules/@loopwright/core/dist/scope.js +154 -0
  251. package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
  252. package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
  253. package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
  254. package/node_modules/@loopwright/core/dist/usage.js +56 -0
  255. package/node_modules/@loopwright/core/package.json +12 -0
  256. package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
  257. package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
  258. package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
  259. package/node_modules/@loopwright/decisions/dist/client.js +292 -0
  260. package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
  261. package/node_modules/@loopwright/decisions/dist/index.js +8 -0
  262. package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
  263. package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
  264. package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
  265. package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
  266. package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
  267. package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
  268. package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
  269. package/node_modules/@loopwright/decisions/dist/router.js +248 -0
  270. package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
  271. package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
  272. package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
  273. package/node_modules/@loopwright/decisions/dist/types.js +80 -0
  274. package/node_modules/@loopwright/decisions/package.json +12 -0
  275. package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
  276. package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
  277. package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
  278. package/node_modules/@loopwright/github-app/dist/config.js +297 -0
  279. package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
  280. package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
  281. package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
  282. package/node_modules/@loopwright/github-app/dist/index.js +13 -0
  283. package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
  284. package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
  285. package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
  286. package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
  287. package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
  288. package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
  289. package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
  290. package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
  291. package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
  292. package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
  293. package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
  294. package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
  295. package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
  296. package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
  297. package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
  298. package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
  299. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
  300. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
  301. package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
  302. package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
  303. package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
  304. package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
  305. package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
  306. package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
  307. package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
  308. package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
  309. package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
  310. package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
  311. package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
  312. package/node_modules/@loopwright/github-app/dist/types.js +14 -0
  313. package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
  314. package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
  315. package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
  316. package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
  317. package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
  318. package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
  319. package/node_modules/@loopwright/github-app/package.json +12 -0
  320. package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
  321. package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
  322. package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
  323. package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
  324. package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
  325. package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
  326. package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
  327. package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
  328. package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
  329. package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
  330. package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
  331. package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
  332. package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
  333. package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
  334. package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
  335. package/node_modules/@loopwright/hardware-runner/dist/worker.js +1646 -0
  336. package/node_modules/@loopwright/hardware-runner/package.json +12 -0
  337. package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
  338. package/node_modules/@loopwright/memory/dist/cas.js +510 -0
  339. package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
  340. package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
  341. package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
  342. package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
  343. package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
  344. package/node_modules/@loopwright/memory/dist/index.js +8 -0
  345. package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
  346. package/node_modules/@loopwright/memory/dist/schema.js +510 -0
  347. package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
  348. package/node_modules/@loopwright/memory/dist/selector.js +157 -0
  349. package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
  350. package/node_modules/@loopwright/memory/dist/store.js +554 -0
  351. package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
  352. package/node_modules/@loopwright/memory/dist/types.js +8 -0
  353. package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
  354. package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
  355. package/node_modules/@loopwright/memory/package.json +12 -0
  356. package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
  357. package/node_modules/@loopwright/state/dist/admission.js +199 -0
  358. package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
  359. package/node_modules/@loopwright/state/dist/boundary.js +194 -0
  360. package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
  361. package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
  362. package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
  363. package/node_modules/@loopwright/state/dist/clock.js +27 -0
  364. package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
  365. package/node_modules/@loopwright/state/dist/connection.js +391 -0
  366. package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
  367. package/node_modules/@loopwright/state/dist/errors.js +34 -0
  368. package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
  369. package/node_modules/@loopwright/state/dist/index.js +1 -0
  370. package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
  371. package/node_modules/@loopwright/state/dist/journal.js +72 -0
  372. package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
  373. package/node_modules/@loopwright/state/dist/model.js +58 -0
  374. package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
  375. package/node_modules/@loopwright/state/dist/ownership.js +45 -0
  376. package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
  377. package/node_modules/@loopwright/state/dist/pages.js +41 -0
  378. package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
  379. package/node_modules/@loopwright/state/dist/receipts.js +97 -0
  380. package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
  381. package/node_modules/@loopwright/state/dist/schema.js +41 -0
  382. package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
  383. package/node_modules/@loopwright/state/dist/settlement.js +129 -0
  384. package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
  385. package/node_modules/@loopwright/state/dist/store.js +100 -0
  386. package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
  387. package/node_modules/@loopwright/state/dist/types.js +1 -0
  388. package/node_modules/@loopwright/state/package.json +12 -0
  389. package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
  390. package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
  391. package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
  392. package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
  393. package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
  394. package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
  395. package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
  396. package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
  397. package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
  398. package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
  399. package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
  400. package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
  401. package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
  402. package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
  403. package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
  404. package/node_modules/@loopwright/taskpack/dist/sandbox.js +2605 -0
  405. package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
  406. package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
  407. package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
  408. package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
  409. package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
  410. package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
  411. package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
  412. package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
  413. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
  414. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
  415. package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
  416. package/node_modules/@loopwright/taskpack/dist/turnkey.js +7313 -0
  417. package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
  418. package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
  419. package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
  420. package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
  421. package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
  422. package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
  423. package/node_modules/@loopwright/taskpack/package.json +12 -0
  424. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
  425. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
  426. package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
  427. package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
  428. package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
  429. package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
  430. package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
  431. package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
  432. package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
  433. package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
  434. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
  435. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
  436. package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
  437. package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
  438. package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
  439. package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
  440. package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
  441. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
  442. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
  443. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
  444. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
  445. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
  446. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
  447. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
  448. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
  449. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
  450. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
  451. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
  452. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
  453. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
  454. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
  455. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
  456. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
  457. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
  458. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
  459. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
  460. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
  461. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
  462. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
  463. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
  464. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
  465. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
  466. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
  467. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
  468. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
  469. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
  470. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
  471. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
  472. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
  473. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
  474. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
  475. package/node_modules/package-lock.json +3021 -0
  476. package/package-lock.json +3021 -0
  477. package/package.json +52 -4
@@ -0,0 +1,3147 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { link, lstat, open } from 'node:fs/promises';
4
+ import { isAbsolute, join } from 'node:path';
5
+ import { types } from 'node:util';
6
+ import { LIMITS, VERIFIER_ARTIFACT_LIMITS, bindSubject, digestArtifactFromMetadata, isVerifierNamespacePath, matchesHardwareTarget, validateDocument, validateRelativePath, } from '@loopwright/core';
7
+ import { checkedRef, cleanMarkerTempFilesInDirectory, overwriteAtomicMarker, privateDirectory, publishAtomicMarker, resolveCanonicalCasBlobPath, stateValue, streamVerifiedCasBlob, syncDirectory, unlinkIfOwnedInode, } from './storage.js';
8
+ import { STREAM_CHUNK_BYTES, readBoundedFile, writeAllToHandle } from './files.js';
9
+ import { compareUtf16 } from './git-objects.js';
10
+ import { canonical, digestValue, freeze, hash, id, integer, isRecord, list, record, same, text } from './schema.js';
11
+ import { parsePrivateJson } from './parser.js';
12
+ import { ControllerFailure, refuse } from './errors.js';
13
+ import { verifierOperationId } from './progress.js';
14
+ import { checkedDetail, checkedFindings, checkedMetrics, signGateVerdict, signPayload, validateGateUrlOverrides, verifyGateSignature, verifySignedPayload, } from './gate.js';
15
+ import { ownedBytes } from './verifier-protocol.js';
16
+ const EMPTY_SHA256_HEX = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
17
+ const LONE_SURROGATE_PATTERN = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;
18
+ const VERDICT_STATUSES = ['pending', 'approved', 'denied', 'expired'];
19
+ const MAX_PREFLIGHT_DISPATCH_ID = 'd'.repeat(64);
20
+ const MAX_PREFLIGHT_DISPATCH_GENERATION = 999_999;
21
+ export const LWTREE01_MAGIC = 'LWTREE01';
22
+ const BASE_TREE_BUNDLE_MAGIC = Buffer.from(LWTREE01_MAGIC, 'ascii');
23
+ export const BENCHMARK_REQUEST_BYTES = 65_536;
24
+ export const BENCHMARK_RESPONSE_BYTES = 65_536;
25
+ export const BENCHMARK_OUTPUT_BYTES = 262_144;
26
+ const preparations = new WeakMap();
27
+ const observations = new WeakMap();
28
+ export function authenticatedBenchmarkGate(value) {
29
+ const trusted = observations.get(value);
30
+ if (!trusted)
31
+ refuse('EVIDENCE_UNAVAILABLE', '', 'verification');
32
+ return trusted;
33
+ }
34
+ export function signBenchmarkVerdict(secret, verdict) {
35
+ return signGateVerdict(secret, verdict);
36
+ }
37
+ export function verifyBenchmarkSignature(secret, verdict, expectedHex) {
38
+ return verifyGateSignature(secret, verdict, expectedHex);
39
+ }
40
+ export function expectedBenchmarkOutputArtifactRef(slotId, item, phase = 'recovery') {
41
+ const logicalName = `.loopwright-verifier/${slotId}/${item.name}`;
42
+ const res = digestArtifactFromMetadata(logicalName, {
43
+ digest: item.digest,
44
+ byteLength: item.byteLength,
45
+ uri: 'cas://sha256/' + item.digest.hex,
46
+ ...(item.mediaType !== undefined ? { mediaType: item.mediaType } : {}),
47
+ });
48
+ if (!res.ok)
49
+ refuse('ARTIFACT_INVALID', '', phase);
50
+ return freeze(res.value);
51
+ }
52
+ export function checkedVerifierArtifactRef(raw, phase = 'recovery') {
53
+ if (!isRecord(raw))
54
+ refuse('ARTIFACT_INVALID', '', phase);
55
+ const hasUri = Object.hasOwn(raw, 'uri') && raw.uri !== undefined;
56
+ const hasMediaType = Object.hasOwn(raw, 'mediaType') && raw.mediaType !== undefined;
57
+ let fields;
58
+ try {
59
+ fields = record(raw, [
60
+ 'name',
61
+ 'digest',
62
+ 'byteLength',
63
+ ...(hasUri ? ['uri'] : []),
64
+ ...(hasMediaType ? ['mediaType'] : []),
65
+ ]);
66
+ }
67
+ catch {
68
+ refuse('ARTIFACT_INVALID', '', phase);
69
+ }
70
+ if (typeof fields.name !== 'string' || !isVerifierNamespacePath(fields.name)) {
71
+ refuse('ARTIFACT_INVALID', '', phase);
72
+ }
73
+ const res = digestArtifactFromMetadata(fields.name, {
74
+ digest: fields.digest,
75
+ byteLength: fields.byteLength,
76
+ ...(hasUri ? { uri: fields.uri } : {}),
77
+ ...(hasMediaType ? { mediaType: fields.mediaType } : {}),
78
+ });
79
+ if (!res.ok)
80
+ refuse('ARTIFACT_INVALID', '', phase);
81
+ return freeze(res.value);
82
+ }
83
+ function readFiniteMetric(metrics, key) {
84
+ if (!Object.hasOwn(metrics, key))
85
+ return undefined;
86
+ const raw = metrics[key];
87
+ if (typeof raw !== 'number' || !Number.isFinite(raw))
88
+ return undefined;
89
+ return Object.is(raw, -0) ? 0 : raw;
90
+ }
91
+ export function evaluateBenchmarkThresholds(rules, metrics) {
92
+ if (rules.length === 0)
93
+ return true;
94
+ if (metrics === undefined)
95
+ return false;
96
+ for (const rule of rules) {
97
+ const value = readFiniteMetric(metrics, rule.metric);
98
+ if (value === undefined)
99
+ return false;
100
+ if (rule.kind === 'bounds') {
101
+ if (rule.min !== undefined && value < rule.min)
102
+ return false;
103
+ if (rule.max !== undefined && value > rule.max)
104
+ return false;
105
+ continue;
106
+ }
107
+ const baseline = readFiniteMetric(metrics, rule.baselineMetric);
108
+ if (baseline === undefined)
109
+ return false;
110
+ if (rule.operator === 'min_ratio') {
111
+ if (!(baseline > 0))
112
+ return false;
113
+ const ratio = value / baseline;
114
+ if (Number.isNaN(ratio) || ratio < rule.threshold)
115
+ return false;
116
+ }
117
+ else if (rule.operator === 'max_ratio') {
118
+ if (!(baseline > 0))
119
+ return false;
120
+ const ratio = value / baseline;
121
+ if (Number.isNaN(ratio) || ratio > rule.threshold)
122
+ return false;
123
+ }
124
+ else {
125
+ const delta = value - baseline;
126
+ if (Number.isNaN(delta) || delta > rule.threshold)
127
+ return false;
128
+ }
129
+ }
130
+ return true;
131
+ }
132
+ function checkedPrintableText(raw, max) {
133
+ const s = text(raw, '', max);
134
+ if (s.length < 1 || s.trim() !== s || /[\r\n\t\p{C}]/u.test(s) || LONE_SURROGATE_PATTERN.test(s)) {
135
+ refuse('ARTIFACT_INVALID', '', 'verification');
136
+ }
137
+ return s;
138
+ }
139
+ function checkedPrintableAscii(raw, max) {
140
+ const s = text(raw, '', max);
141
+ if (s.length < 1 || s.trim() !== s || !/^[\x20-\x7E]+$/.test(s)) {
142
+ refuse('ARTIFACT_INVALID', '', 'verification');
143
+ }
144
+ return s;
145
+ }
146
+ export function checkedHardwareProvenance(raw) {
147
+ if (!isRecord(raw))
148
+ refuse('ARTIFACT_INVALID', '', 'verification');
149
+ const hasTopology = Object.hasOwn(raw, 'topology') && raw.topology !== undefined;
150
+ const fields = record(raw, [
151
+ 'targetCellId',
152
+ 'probeKind',
153
+ 'vendor',
154
+ 'deviceModel',
155
+ 'accelerator',
156
+ 'isolationMode',
157
+ 'deviceCount',
158
+ 'driverVersion',
159
+ 'runtimeVersion',
160
+ 'workloadDigest',
161
+ 'clockLockMode',
162
+ ...(hasTopology ? ['topology'] : []),
163
+ ]);
164
+ const targetCellId = id(fields.targetCellId);
165
+ const probeKind = text(fields.probeKind, '', 32);
166
+ if (probeKind !== 'physical' && probeKind !== 'synthetic_fixture')
167
+ refuse('ARTIFACT_INVALID', '', 'verification');
168
+ const vendor = checkedPrintableText(fields.vendor, 128);
169
+ const deviceModel = checkedPrintableText(fields.deviceModel, 128);
170
+ const accelerator = checkedPrintableAscii(fields.accelerator, 64);
171
+ const isolationMode = text(fields.isolationMode, '', 32);
172
+ if (isolationMode !== 'whole_device' && isolationMode !== 'sliced')
173
+ refuse('ARTIFACT_INVALID', '', 'verification');
174
+ const deviceCount = integer(fields.deviceCount, 1, 64);
175
+ const driverVersion = checkedPrintableText(fields.driverVersion, 128);
176
+ const runtimeVersion = checkedPrintableText(fields.runtimeVersion, 128);
177
+ const topology = hasTopology ? checkedPrintableText(fields.topology, 128) : undefined;
178
+ const workloadDigest = digestValue(fields.workloadDigest);
179
+ const clockLockMode = text(fields.clockLockMode, '', 16);
180
+ if (clockLockMode !== 'locked' && clockLockMode !== 'unlocked' && clockLockMode !== 'unknown') {
181
+ refuse('ARTIFACT_INVALID', '', 'verification');
182
+ }
183
+ const out = Object.create(null);
184
+ out.targetCellId = targetCellId;
185
+ out.probeKind = probeKind;
186
+ out.vendor = vendor;
187
+ out.deviceModel = deviceModel;
188
+ out.accelerator = accelerator;
189
+ out.isolationMode = isolationMode;
190
+ out.deviceCount = deviceCount;
191
+ out.driverVersion = driverVersion;
192
+ out.runtimeVersion = runtimeVersion;
193
+ if (topology !== undefined)
194
+ out.topology = topology;
195
+ out.workloadDigest = workloadDigest;
196
+ out.clockLockMode = clockLockMode;
197
+ return freeze(out);
198
+ }
199
+ function checkedOutputArtifacts(raw, slotId) {
200
+ const items = list(raw, '', VERIFIER_ARTIFACT_LIMITS.maxFilesPerSlot);
201
+ const seenNames = new Set();
202
+ let totalBytes = 0;
203
+ const out = [];
204
+ for (const item of items) {
205
+ if (!isRecord(item))
206
+ refuse('ARTIFACT_INVALID', '', 'verification');
207
+ const hasMediaType = Object.hasOwn(item, 'mediaType') && item.mediaType !== undefined;
208
+ const fields = record(item, [
209
+ 'name',
210
+ 'digest',
211
+ 'byteLength',
212
+ ...(hasMediaType ? ['mediaType'] : []),
213
+ ]);
214
+ const rawName = text(fields.name, '', 1024);
215
+ if (rawName.length < 1 || LONE_SURROGATE_PATTERN.test(rawName) || isVerifierNamespacePath(rawName)) {
216
+ refuse('ARTIFACT_INVALID', '', 'verification');
217
+ }
218
+ const validRel = validateRelativePath(rawName);
219
+ if (!validRel.ok || validRel.value.split('/').some(seg => seg.toLowerCase() === '.git')) {
220
+ refuse('ARTIFACT_INVALID', '', 'verification');
221
+ }
222
+ const nameKey = validRel.value.toLowerCase();
223
+ if (seenNames.has(nameKey))
224
+ refuse('ARTIFACT_INVALID', '', 'verification');
225
+ seenNames.add(nameKey);
226
+ const digest = digestValue(fields.digest);
227
+ const byteLength = integer(fields.byteLength, 0, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
228
+ if ((byteLength === 0) !== (digest.hex === EMPTY_SHA256_HEX)) {
229
+ refuse('ARTIFACT_INVALID', '', 'verification');
230
+ }
231
+ if (byteLength > VERIFIER_ARTIFACT_LIMITS.maxTotalBytes - totalBytes) {
232
+ refuse('ARTIFACT_INVALID', '', 'verification');
233
+ }
234
+ totalBytes += byteLength;
235
+ let mediaTypeVal;
236
+ if (hasMediaType) {
237
+ if (fields.mediaType === null) {
238
+ mediaTypeVal = null;
239
+ }
240
+ else {
241
+ const mt = text(fields.mediaType, '', 128);
242
+ if (mt.length < 1 || LONE_SURROGATE_PATTERN.test(mt))
243
+ refuse('ARTIFACT_INVALID', '', 'verification');
244
+ mediaTypeVal = mt;
245
+ }
246
+ }
247
+ const logicalName = `.loopwright-verifier/${slotId}/${validRel.value}`;
248
+ const refCheck = digestArtifactFromMetadata(logicalName, {
249
+ digest,
250
+ byteLength,
251
+ uri: 'cas://sha256/' + digest.hex,
252
+ ...(hasMediaType ? { mediaType: mediaTypeVal } : {}),
253
+ });
254
+ if (!refCheck.ok)
255
+ refuse('ARTIFACT_INVALID', '', 'verification');
256
+ const copy = Object.create(null);
257
+ copy.name = validRel.value;
258
+ copy.digest = digest;
259
+ copy.byteLength = byteLength;
260
+ if (hasMediaType)
261
+ copy.mediaType = mediaTypeVal;
262
+ out.push(freeze(copy));
263
+ }
264
+ return freeze(out);
265
+ }
266
+ export function checkedBenchmarkVerdict(raw, expected) {
267
+ try {
268
+ if (!isRecord(raw))
269
+ refuse('ARTIFACT_INVALID', '', 'verification');
270
+ const hasPreemption = Object.hasOwn(raw, 'retryablePreemption') && raw.retryablePreemption !== undefined;
271
+ const hasDetail = Object.hasOwn(raw, 'detail') && raw.detail !== undefined;
272
+ const hasMetrics = Object.hasOwn(raw, 'metrics') && raw.metrics !== undefined;
273
+ const hasFindings = Object.hasOwn(raw, 'findings') && raw.findings !== undefined;
274
+ const hasProvenance = Object.hasOwn(raw, 'hardwareProvenance') && raw.hardwareProvenance !== undefined;
275
+ const hasOutputArtifacts = Object.hasOwn(raw, 'outputArtifacts') && raw.outputArtifacts !== undefined;
276
+ const value = record(raw, [
277
+ 'version',
278
+ 'kind',
279
+ 'storeId',
280
+ 'runId',
281
+ 'lockHash',
282
+ 'operationId',
283
+ 'dispatchId',
284
+ 'dispatchGeneration',
285
+ 'gateId',
286
+ 'checkId',
287
+ 'candidateDigest',
288
+ 'status',
289
+ 'reason',
290
+ 'expiresAtMs',
291
+ 'preemptionCount',
292
+ ...(hasPreemption ? ['retryablePreemption'] : []),
293
+ ...(hasDetail ? ['detail'] : []),
294
+ ...(hasMetrics ? ['metrics'] : []),
295
+ ...(hasFindings ? ['findings'] : []),
296
+ ...(hasProvenance ? ['hardwareProvenance'] : []),
297
+ ...(hasOutputArtifacts ? ['outputArtifacts'] : []),
298
+ ]);
299
+ const binding = {
300
+ version: 1,
301
+ kind: 'benchmark_verdict',
302
+ storeId: expected.storeId,
303
+ runId: expected.runId,
304
+ lockHash: expected.lockHash,
305
+ operationId: expected.operationId,
306
+ dispatchId: expected.dispatchId,
307
+ dispatchGeneration: expected.dispatchGeneration,
308
+ gateId: expected.gateId,
309
+ checkId: expected.checkId,
310
+ candidateDigest: expected.candidateDigest,
311
+ };
312
+ const stripped = {
313
+ version: value.version,
314
+ kind: value.kind,
315
+ storeId: value.storeId,
316
+ runId: value.runId,
317
+ lockHash: value.lockHash,
318
+ operationId: value.operationId,
319
+ dispatchId: value.dispatchId,
320
+ dispatchGeneration: value.dispatchGeneration,
321
+ gateId: value.gateId,
322
+ checkId: value.checkId,
323
+ candidateDigest: value.candidateDigest,
324
+ };
325
+ if (!same(stripped, binding) || !VERDICT_STATUSES.includes(value.status)) {
326
+ refuse('ARTIFACT_INVALID', '', 'verification');
327
+ }
328
+ if (value.reason !== null
329
+ && (value.status === 'pending'
330
+ || typeof value.reason !== 'string'
331
+ || value.reason.length < 1
332
+ || value.reason.length > 256
333
+ || LONE_SURROGATE_PATTERN.test(value.reason))) {
334
+ refuse('ARTIFACT_INVALID', '', 'verification');
335
+ }
336
+ if (!/^(?:0|[1-9][0-9]{0,17})$/.test(text(value.expiresAtMs, '', 19))) {
337
+ refuse('ARTIFACT_INVALID', '', 'verification');
338
+ }
339
+ const preemptionCount = integer(value.preemptionCount, 0, 16);
340
+ let retryablePreemption;
341
+ if (hasPreemption) {
342
+ if (typeof value.retryablePreemption !== 'boolean'
343
+ || value.status === 'pending'
344
+ || (value.retryablePreemption === true && value.status === 'approved')) {
345
+ refuse('ARTIFACT_INVALID', '', 'verification');
346
+ }
347
+ retryablePreemption = value.retryablePreemption;
348
+ }
349
+ const detail = hasDetail ? checkedDetail(value.detail) : undefined;
350
+ const metrics = hasMetrics ? checkedMetrics(value.metrics) : undefined;
351
+ const findings = hasFindings ? checkedFindings(value.findings) : undefined;
352
+ if (value.status === 'approved' && !hasProvenance) {
353
+ refuse('ARTIFACT_INVALID', '', 'verification');
354
+ }
355
+ const hardwareProvenance = hasProvenance ? checkedHardwareProvenance(value.hardwareProvenance) : undefined;
356
+ const slotId = typeof expected.slotId === 'string' && expected.slotId.length > 0
357
+ ? expected.slotId
358
+ : 'check.' + String(expected.checkId);
359
+ const outputArtifacts = hasOutputArtifacts ? checkedOutputArtifacts(value.outputArtifacts, slotId) : undefined;
360
+ if (value.status === 'pending' && outputArtifacts !== undefined && outputArtifacts.length > 0) {
361
+ refuse('ARTIFACT_INVALID', '', 'verification');
362
+ }
363
+ const out = Object.create(null);
364
+ out.status = value.status;
365
+ out.reason = value.reason;
366
+ out.expiresAtMs = value.expiresAtMs;
367
+ out.preemptionCount = preemptionCount;
368
+ if (retryablePreemption !== undefined)
369
+ out.retryablePreemption = retryablePreemption;
370
+ if (detail !== undefined)
371
+ out.detail = detail;
372
+ if (metrics !== undefined)
373
+ out.metrics = metrics;
374
+ if (findings !== undefined)
375
+ out.findings = findings;
376
+ if (hardwareProvenance !== undefined)
377
+ out.hardwareProvenance = hardwareProvenance;
378
+ if (outputArtifacts !== undefined)
379
+ out.outputArtifacts = outputArtifacts;
380
+ return freeze(out);
381
+ }
382
+ catch (error) {
383
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'ARTIFACT_INVALID')
384
+ throw error;
385
+ refuse('ARTIFACT_INVALID', '', 'verification');
386
+ }
387
+ }
388
+ export function resolveBenchmarkSlotMetadata(plan, slot) {
389
+ if (!isRecord(slot.handler.parameters))
390
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
391
+ const hasMaxPreemptions = Object.hasOwn(slot.handler.parameters, 'maxPreemptions');
392
+ const parameters = record(slot.handler.parameters, [
393
+ 'checkId',
394
+ 'endpointRef',
395
+ 'gateId',
396
+ 'heldOutWorkloadId',
397
+ ...(hasMaxPreemptions ? ['maxPreemptions'] : []),
398
+ ]);
399
+ if (parameters.checkId !== slot.checkId)
400
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
401
+ const endpointRef = id(parameters.endpointRef);
402
+ const gateId = text(parameters.gateId, '', 128);
403
+ if (gateId.length < 1 || gateId.trim() !== gateId || !/^[\x20-\x7E]+$/.test(gateId)) {
404
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
405
+ }
406
+ const heldOutWorkloadId = id(parameters.heldOutWorkloadId);
407
+ const maxPreemptions = hasMaxPreemptions ? integer(parameters.maxPreemptions, 0, 16) : 3;
408
+ const check = plan.task.spec.acceptance.checks.find(item => item.id === slot.checkId);
409
+ if (!check || !check.allowedEvidenceLevels.includes('hardware_execution') || !check.targetCellId) {
410
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
411
+ }
412
+ const cell = (plan.task.spec.target.matrix ?? []).find(item => item.id === check.targetCellId);
413
+ if (!cell || cell.hardware === undefined) {
414
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
415
+ }
416
+ const targetHardware = freeze({
417
+ accelerator: cell.hardware.accelerator,
418
+ isolationMode: cell.hardware.isolationMode,
419
+ ...(cell.hardware.deviceCount !== undefined ? { deviceCount: cell.hardware.deviceCount } : {}),
420
+ ...(cell.hardware.driverConstraint !== undefined ? { driverConstraint: cell.hardware.driverConstraint } : {}),
421
+ ...(cell.hardware.topology !== undefined ? { topology: cell.hardware.topology } : {}),
422
+ });
423
+ const metricThresholds = freeze((check.metricThresholds ?? []).map(rule => rule.kind === 'bounds'
424
+ ? freeze({
425
+ kind: 'bounds',
426
+ metric: rule.metric,
427
+ ...(rule.min !== undefined ? { min: rule.min } : {}),
428
+ ...(rule.max !== undefined ? { max: rule.max } : {}),
429
+ })
430
+ : freeze({
431
+ kind: 'comparative',
432
+ metric: rule.metric,
433
+ baselineMetric: rule.baselineMetric,
434
+ operator: rule.operator,
435
+ threshold: rule.threshold,
436
+ })));
437
+ return {
438
+ gateId,
439
+ endpointRef,
440
+ heldOutWorkloadId,
441
+ maxPreemptions,
442
+ targetCellId: check.targetCellId,
443
+ targetHardware,
444
+ allowSyntheticHardwareProbe: check.allowSyntheticHardwareProbe === true,
445
+ metricThresholds,
446
+ };
447
+ }
448
+ function resolveCandidateEntryModesMap(entryModes, phase = 'verification') {
449
+ const out = new Map();
450
+ if (entryModes === undefined)
451
+ return out;
452
+ if (entryModes instanceof Map) {
453
+ for (const [name, rawVal] of entryModes.entries()) {
454
+ if (typeof rawVal === 'string') {
455
+ if (rawVal !== '100644' && rawVal !== '100755')
456
+ refuse('ARTIFACT_INVALID', '', phase);
457
+ out.set(name, rawVal);
458
+ }
459
+ else if (isRecord(rawVal)) {
460
+ if (Object.hasOwn(rawVal, 'mode') && rawVal.mode !== undefined) {
461
+ if (rawVal.mode !== '100644' && rawVal.mode !== '100755')
462
+ refuse('ARTIFACT_INVALID', '', phase);
463
+ out.set(name, rawVal.mode);
464
+ }
465
+ }
466
+ else {
467
+ refuse('ARTIFACT_INVALID', '', phase);
468
+ }
469
+ }
470
+ return out;
471
+ }
472
+ if (!Array.isArray(entryModes))
473
+ refuse('ARTIFACT_INVALID', '', phase);
474
+ for (const item of entryModes) {
475
+ if (!isRecord(item) || typeof item.name !== 'string')
476
+ refuse('ARTIFACT_INVALID', '', phase);
477
+ if (Object.hasOwn(item, 'mode') && item.mode !== undefined) {
478
+ if (item.mode !== '100644' && item.mode !== '100755')
479
+ refuse('ARTIFACT_INVALID', '', phase);
480
+ out.set(item.name, item.mode);
481
+ }
482
+ }
483
+ return out;
484
+ }
485
+ export function checkedBenchmarkCandidateArtifacts(raw, phase = 'verification') {
486
+ if (!isRecord(raw))
487
+ refuse('ARTIFACT_INVALID', '', phase);
488
+ const hasBaseTree = Object.hasOwn(raw, 'baseTree') && raw.baseTree !== undefined;
489
+ const hasBaseTreeBundle = Object.hasOwn(raw, 'baseTreeBundle') && raw.baseTreeBundle !== undefined;
490
+ let obj;
491
+ try {
492
+ obj = record(raw, [
493
+ 'entries',
494
+ 'deleted',
495
+ ...(hasBaseTree ? ['baseTree'] : []),
496
+ ...(hasBaseTreeBundle ? ['baseTreeBundle'] : []),
497
+ ]);
498
+ }
499
+ catch {
500
+ refuse('ARTIFACT_INVALID', '', phase);
501
+ }
502
+ if (!hasBaseTree && hasBaseTreeBundle)
503
+ refuse('ARTIFACT_INVALID', '', phase);
504
+ const rawEntries = list(obj.entries, '', 4096);
505
+ const seenFolded = new Set();
506
+ const entries = [];
507
+ for (const rawEntry of rawEntries) {
508
+ if (!isRecord(rawEntry))
509
+ refuse('ARTIFACT_INVALID', '', phase);
510
+ const hasMode = Object.hasOwn(rawEntry, 'mode') && rawEntry.mode !== undefined;
511
+ let item;
512
+ try {
513
+ item = record(rawEntry, ['name', 'digest', 'byteLength', ...(hasMode ? ['mode'] : [])]);
514
+ }
515
+ catch {
516
+ refuse('ARTIFACT_INVALID', '', phase);
517
+ }
518
+ const rawName = text(item.name, '', LIMITS.path);
519
+ const rel = validateRelativePath(rawName);
520
+ if (!rel.ok || isVerifierNamespacePath(rel.value) || rel.value.split('/').some(seg => seg.toLowerCase() === '.git')) {
521
+ refuse('ARTIFACT_INVALID', '', phase);
522
+ }
523
+ const folded = rel.value.toLowerCase();
524
+ if (seenFolded.has(folded))
525
+ refuse('ARTIFACT_INVALID', '', phase);
526
+ seenFolded.add(folded);
527
+ const digest = digestValue(item.digest);
528
+ const byteLength = integer(item.byteLength, 0, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
529
+ if ((byteLength === 0) !== (digest.hex === EMPTY_SHA256_HEX)) {
530
+ refuse('ARTIFACT_INVALID', '', phase);
531
+ }
532
+ let normalizedMode;
533
+ if (hasMode) {
534
+ if (item.mode !== '100644' && item.mode !== '100755')
535
+ refuse('ARTIFACT_INVALID', '', phase);
536
+ normalizedMode = item.mode;
537
+ }
538
+ entries.push(freeze({
539
+ name: rel.value,
540
+ digest: freeze({ algorithm: digest.algorithm, hex: digest.hex }),
541
+ byteLength,
542
+ ...(normalizedMode === '100755' ? { mode: '100755' } : {}),
543
+ }));
544
+ }
545
+ const rawDeleted = list(obj.deleted, '', 4096);
546
+ const deleted = [];
547
+ for (const rawDel of rawDeleted) {
548
+ const rawName = text(rawDel, '', LIMITS.path);
549
+ const rel = validateRelativePath(rawName);
550
+ if (!rel.ok || isVerifierNamespacePath(rel.value) || rel.value.split('/').some(seg => seg.toLowerCase() === '.git')) {
551
+ refuse('ARTIFACT_INVALID', '', phase);
552
+ }
553
+ const folded = rel.value.toLowerCase();
554
+ if (seenFolded.has(folded))
555
+ refuse('ARTIFACT_INVALID', '', phase);
556
+ seenFolded.add(folded);
557
+ deleted.push(rel.value);
558
+ }
559
+ let baseTree;
560
+ if (hasBaseTree) {
561
+ let bt;
562
+ try {
563
+ bt = record(obj.baseTree, ['objectFormat', 'commitOid', 'treeOid']);
564
+ }
565
+ catch {
566
+ refuse('ARTIFACT_INVALID', '', phase);
567
+ }
568
+ if (bt.objectFormat !== 'sha1' && bt.objectFormat !== 'sha256')
569
+ refuse('ARTIFACT_INVALID', '', phase);
570
+ const oidRe = bt.objectFormat === 'sha1' ? /^[0-9a-f]{40}$/ : /^[0-9a-f]{64}$/;
571
+ const commitOid = text(bt.commitOid, '', 64);
572
+ const treeOid = text(bt.treeOid, '', 64);
573
+ if (!oidRe.test(commitOid) || !oidRe.test(treeOid))
574
+ refuse('ARTIFACT_INVALID', '', phase);
575
+ baseTree = freeze({ objectFormat: bt.objectFormat, commitOid, treeOid });
576
+ }
577
+ let baseTreeBundle;
578
+ if (hasBaseTreeBundle) {
579
+ let btb;
580
+ try {
581
+ btb = record(obj.baseTreeBundle, ['digest', 'byteLength']);
582
+ }
583
+ catch {
584
+ refuse('ARTIFACT_INVALID', '', phase);
585
+ }
586
+ const digest = digestValue(btb.digest);
587
+ const byteLength = integer(btb.byteLength, 12, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
588
+ baseTreeBundle = freeze({
589
+ digest: freeze({ algorithm: digest.algorithm, hex: digest.hex }),
590
+ byteLength,
591
+ });
592
+ }
593
+ return freeze({
594
+ entries: freeze(entries),
595
+ deleted: freeze(deleted),
596
+ ...(baseTree !== undefined ? { baseTree } : {}),
597
+ ...(baseTreeBundle !== undefined ? { baseTreeBundle } : {}),
598
+ });
599
+ }
600
+ export function buildCandidateArtifactsDescriptor(manifest, baseTreeBundle, entryModes) {
601
+ if (baseTreeBundle !== undefined && manifest.spec.baseTree === undefined) {
602
+ refuse('ARTIFACT_INVALID', '', 'verification');
603
+ }
604
+ const modeMap = resolveCandidateEntryModesMap(entryModes, 'verification');
605
+ return freeze({
606
+ entries: freeze(manifest.spec.entries.map(entry => {
607
+ const mode = modeMap.get(entry.name);
608
+ return freeze({
609
+ name: entry.name,
610
+ digest: freeze({ algorithm: entry.digest.algorithm, hex: entry.digest.hex }),
611
+ byteLength: entry.byteLength,
612
+ ...(mode === '100755' ? { mode: '100755' } : {}),
613
+ });
614
+ })),
615
+ deleted: freeze([...(manifest.spec.deleted ?? [])]),
616
+ ...(manifest.spec.baseTree !== undefined
617
+ ? {
618
+ baseTree: freeze({
619
+ objectFormat: manifest.spec.baseTree.objectFormat,
620
+ commitOid: manifest.spec.baseTree.commitOid,
621
+ treeOid: manifest.spec.baseTree.treeOid,
622
+ }),
623
+ }
624
+ : {}),
625
+ ...(baseTreeBundle !== undefined
626
+ ? {
627
+ baseTreeBundle: freeze({
628
+ digest: freeze({ algorithm: baseTreeBundle.digest.algorithm, hex: baseTreeBundle.digest.hex }),
629
+ byteLength: baseTreeBundle.byteLength,
630
+ }),
631
+ }
632
+ : {}),
633
+ });
634
+ }
635
+ export function expectedBenchmarkRequest(plan, slot, endpoint, subject, manifest, baseTreeBundle, entryModes) {
636
+ const meta = resolveBenchmarkSlotMetadata(plan, slot);
637
+ if (meta.endpointRef !== endpoint.id)
638
+ refuse('ARTIFACT_INVALID', '', 'verification');
639
+ return {
640
+ version: 1,
641
+ kind: 'benchmark_request',
642
+ gateId: meta.gateId,
643
+ checkId: slot.checkId,
644
+ candidateDigest: subject.candidateDigest.hex,
645
+ subject,
646
+ targetCellId: meta.targetCellId,
647
+ targetHardware: meta.targetHardware,
648
+ heldOutWorkloadId: meta.heldOutWorkloadId,
649
+ metricThresholds: meta.metricThresholds,
650
+ maxPreemptions: meta.maxPreemptions,
651
+ candidateArtifacts: buildCandidateArtifactsDescriptor(manifest, baseTreeBundle, entryModes),
652
+ };
653
+ }
654
+ function cancelledFailure(phase = 'verification') {
655
+ return new ControllerFailure({
656
+ version: 1,
657
+ code: 'CANCELLED',
658
+ phase,
659
+ path: '',
660
+ stateCode: null,
661
+ piCode: null,
662
+ effect: 'none',
663
+ retryable: false,
664
+ });
665
+ }
666
+ /**
667
+ * Deterministically seals surviving unchanged v2 base-tree entries into a digest-bound `LWTREE01`
668
+ * binary CAS blob (`<= 1 MiB` streaming via owned `git cat-file --batch`, `O_NOFOLLOW`, `0o400`, `fsync`, `nlink === 1`).
669
+ */
670
+ export async function sealBenchmarkBaseTreeBundle(source, manifest, artifacts, owner, signal, onProgress) {
671
+ if (source.version !== 2 || manifest.spec.baseTree === undefined)
672
+ return undefined;
673
+ if (signal.aborted)
674
+ throw cancelledFailure('verification');
675
+ await owner.assertCurrent();
676
+ const overlayNames = new Set(manifest.spec.entries.map(entry => entry.name));
677
+ const deletedNames = new Set(manifest.spec.deleted ?? []);
678
+ const surviving = (source.baselineEntries ?? [])
679
+ .filter(entry => !overlayNames.has(entry.name) && !deletedNames.has(entry.name))
680
+ .sort((a, b) => compareUtf16(a.name, b.name));
681
+ if (surviving.length === 0)
682
+ return undefined;
683
+ if (surviving.length > LIMITS.baselineEntries)
684
+ refuse('OUTPUT_LIMIT', '', 'verification');
685
+ const preparedEntries = [];
686
+ let expectedBundleBytes = 12; // 8-byte ASCII 'LWTREE01' + uint32BE count
687
+ let prevName = null;
688
+ const seenFolded = new Set();
689
+ for (const entry of surviving) {
690
+ if (prevName !== null && compareUtf16(prevName, entry.name) >= 0) {
691
+ refuse('ARTIFACT_INVALID', '', 'verification');
692
+ }
693
+ prevName = entry.name;
694
+ const validRel = validateRelativePath(entry.name);
695
+ if (!validRel.ok
696
+ || validRel.value !== entry.name
697
+ || isVerifierNamespacePath(entry.name)
698
+ || entry.name.split('/').some(seg => seg.toLowerCase() === '.git' || Buffer.byteLength(seg, 'utf8') > 255)) {
699
+ refuse('ARTIFACT_INVALID', '', 'verification');
700
+ }
701
+ const folded = entry.name.normalize('NFC').toLowerCase();
702
+ if (seenFolded.has(folded))
703
+ refuse('ARTIFACT_INVALID', '', 'verification');
704
+ seenFolded.add(folded);
705
+ if (entry.mode !== '100644' && entry.mode !== '100755') {
706
+ refuse('ARTIFACT_INVALID', '', 'verification');
707
+ }
708
+ if (!Number.isSafeInteger(entry.byteLength)
709
+ || Object.is(entry.byteLength, -0)
710
+ || entry.byteLength < 0
711
+ || entry.byteLength > 0xffff_ffff) {
712
+ refuse('OUTPUT_LIMIT', '', 'verification');
713
+ }
714
+ const pathBytes = Buffer.from(entry.name, 'utf8');
715
+ if (pathBytes.byteLength < 1 || pathBytes.byteLength > 4096) {
716
+ refuse('ARTIFACT_INVALID', '', 'verification');
717
+ }
718
+ const entryFramingAndBody = 4 + pathBytes.byteLength + 1 + 4 + entry.byteLength;
719
+ if (entryFramingAndBody > VERIFIER_ARTIFACT_LIMITS.maxFileBytes - expectedBundleBytes) {
720
+ refuse('OUTPUT_LIMIT', '', 'verification');
721
+ }
722
+ expectedBundleBytes += entryFramingAndBody;
723
+ preparedEntries.push({
724
+ name: entry.name,
725
+ pathBytes,
726
+ mode: entry.mode,
727
+ modeFlag: entry.mode === '100755' ? 1 : 0,
728
+ oid: entry.oid,
729
+ byteLength: entry.byteLength,
730
+ });
731
+ }
732
+ for (const folded of seenFolded) {
733
+ let slash = folded.indexOf('/');
734
+ while (slash !== -1) {
735
+ if (seenFolded.has(folded.slice(0, slash)))
736
+ refuse('ARTIFACT_INVALID', '', 'verification');
737
+ slash = folded.indexOf('/', slash + 1);
738
+ }
739
+ }
740
+ const blobsDir = join(artifacts.directory, 'blobs');
741
+ const sha256Dir = join(blobsDir, 'sha256');
742
+ await privateDirectory(blobsDir);
743
+ await privateDirectory(sha256Dir);
744
+ const releaseActivity = await owner.holdLocalActivity();
745
+ const tmpPath = join(sha256Dir, '.tmp-' + randomBytes(16).toString('hex'));
746
+ let tmpHandle = null;
747
+ const vaultChecker = artifacts.vault.createStreamChecker();
748
+ let vaultFinished = false;
749
+ let tmpClosed = false;
750
+ let tmpUnlinked = false;
751
+ let createdDev = -1;
752
+ let createdIno = -1;
753
+ try {
754
+ tmpHandle = await open(tmpPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
755
+ const handle = tmpHandle;
756
+ const createdInfo = await handle.stat();
757
+ createdDev = createdInfo.dev;
758
+ createdIno = createdInfo.ino;
759
+ if (!createdInfo.isFile()
760
+ || createdInfo.isSymbolicLink()
761
+ || createdInfo.uid !== process.getuid?.()
762
+ || createdInfo.nlink !== 1) {
763
+ refuse('ARTIFACT_INVALID', '', 'verification');
764
+ }
765
+ const bundleSha = createHash('sha256');
766
+ let writtenBundleBytes = 0;
767
+ const writeBundleSlice = async (raw) => {
768
+ for (let off = 0; off < raw.byteLength; off += STREAM_CHUNK_BYTES) {
769
+ if (signal.aborted)
770
+ throw cancelledFailure('verification');
771
+ if (onProgress)
772
+ await onProgress();
773
+ const sub = raw.subarray(off, Math.min(raw.byteLength, off + STREAM_CHUNK_BYTES));
774
+ writtenBundleBytes += sub.byteLength;
775
+ if (writtenBundleBytes > expectedBundleBytes || writtenBundleBytes > VERIFIER_ARTIFACT_LIMITS.maxFileBytes) {
776
+ refuse('OUTPUT_LIMIT', '', 'verification');
777
+ }
778
+ try {
779
+ vaultChecker.push(sub);
780
+ }
781
+ catch (error) {
782
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'CONFIG_CREDENTIAL_INVALID') {
783
+ refuse('ARTIFACT_INVALID', '', 'verification');
784
+ }
785
+ throw error;
786
+ }
787
+ bundleSha.update(sub);
788
+ await writeAllToHandle(handle, sub);
789
+ }
790
+ };
791
+ const headerBuf = Buffer.allocUnsafe(12);
792
+ BASE_TREE_BUNDLE_MAGIC.copy(headerBuf, 0);
793
+ headerBuf.writeUInt32BE(preparedEntries.length, 8);
794
+ await writeBundleSlice(headerBuf);
795
+ let entryIndex = 0;
796
+ await owner.streamGitBatch(source.directory, preparedEntries, async (_entry, readChunks) => {
797
+ const item = preparedEntries[entryIndex++];
798
+ if (signal.aborted)
799
+ throw cancelledFailure('verification');
800
+ const entryPrefix = Buffer.allocUnsafe(4 + item.pathBytes.byteLength + 1 + 4);
801
+ entryPrefix.writeUInt32BE(item.pathBytes.byteLength, 0);
802
+ item.pathBytes.copy(entryPrefix, 4);
803
+ entryPrefix[4 + item.pathBytes.byteLength] = item.modeFlag;
804
+ entryPrefix.writeUInt32BE(item.byteLength, 4 + item.pathBytes.byteLength + 1);
805
+ await writeBundleSlice(entryPrefix);
806
+ await readChunks(async (slice) => {
807
+ await writeBundleSlice(slice);
808
+ });
809
+ }, {
810
+ intentScope: { bundle: LWTREE01_MAGIC },
811
+ phase: 'verification',
812
+ signal,
813
+ timeoutMs: 120_000,
814
+ });
815
+ try {
816
+ vaultChecker.finish();
817
+ vaultFinished = true;
818
+ }
819
+ catch (error) {
820
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'CONFIG_CREDENTIAL_INVALID') {
821
+ refuse('ARTIFACT_INVALID', '', 'verification');
822
+ }
823
+ throw error;
824
+ }
825
+ if (writtenBundleBytes !== expectedBundleBytes) {
826
+ refuse('ARTIFACT_INVALID', '', 'verification');
827
+ }
828
+ const sha256Hex = bundleSha.digest('hex');
829
+ await handle.chmod(0o400);
830
+ await handle.sync();
831
+ const sealedInfo = await handle.stat();
832
+ if (!sealedInfo.isFile()
833
+ || sealedInfo.isSymbolicLink()
834
+ || sealedInfo.dev !== createdDev
835
+ || sealedInfo.ino !== createdIno
836
+ || sealedInfo.uid !== process.getuid?.()
837
+ || sealedInfo.nlink !== 1
838
+ || sealedInfo.size !== expectedBundleBytes
839
+ || (sealedInfo.mode & 0o7777) !== 0o400) {
840
+ refuse('ARTIFACT_INVALID', '', 'verification');
841
+ }
842
+ await owner.assertCurrent();
843
+ const beforeLink = await lstat(tmpPath).catch(() => null);
844
+ if (!beforeLink
845
+ || beforeLink.isSymbolicLink()
846
+ || !beforeLink.isFile()
847
+ || beforeLink.dev !== sealedInfo.dev
848
+ || beforeLink.ino !== sealedInfo.ino
849
+ || beforeLink.uid !== process.getuid?.()) {
850
+ tmpUnlinked = true;
851
+ refuse('ARTIFACT_INVALID', '', 'verification');
852
+ }
853
+ const finalHexPath = join(sha256Dir, sha256Hex);
854
+ let linked = false;
855
+ try {
856
+ await link(tmpPath, finalHexPath);
857
+ linked = true;
858
+ }
859
+ catch (error) {
860
+ if (error.code !== 'EEXIST')
861
+ throw error;
862
+ }
863
+ if (linked) {
864
+ await unlinkIfOwnedInode(tmpPath, sealedInfo.dev, sealedInfo.ino);
865
+ tmpUnlinked = true;
866
+ let finalVerifyHandle = null;
867
+ try {
868
+ finalVerifyHandle = await open(finalHexPath, constants.O_RDONLY | constants.O_NOFOLLOW);
869
+ const committed = await finalVerifyHandle.stat();
870
+ const pinned = await handle.stat();
871
+ if (committed.isSymbolicLink()
872
+ || !committed.isFile()
873
+ || committed.dev !== sealedInfo.dev
874
+ || committed.ino !== sealedInfo.ino
875
+ || committed.uid !== process.getuid?.()
876
+ || committed.nlink !== 1
877
+ || committed.size !== expectedBundleBytes
878
+ || (committed.mode & 0o7777) !== 0o400
879
+ || pinned.dev !== sealedInfo.dev
880
+ || pinned.ino !== sealedInfo.ino
881
+ || pinned.nlink !== 1) {
882
+ if (committed.dev === sealedInfo.dev && committed.ino === sealedInfo.ino && committed.uid === process.getuid?.()) {
883
+ await unlinkIfOwnedInode(finalHexPath, sealedInfo.dev, sealedInfo.ino);
884
+ }
885
+ refuse('ARTIFACT_INVALID', '', 'verification');
886
+ }
887
+ }
888
+ finally {
889
+ if (finalVerifyHandle)
890
+ await finalVerifyHandle.close().catch(() => { });
891
+ }
892
+ await handle.close();
893
+ tmpClosed = true;
894
+ }
895
+ else {
896
+ await handle.close();
897
+ tmpClosed = true;
898
+ await unlinkIfOwnedInode(tmpPath, sealedInfo.dev, sealedInfo.ino);
899
+ tmpUnlinked = true;
900
+ for (let attempt = 0; attempt < 20; attempt++) {
901
+ const st = await lstat(finalHexPath).catch(() => null);
902
+ if (!st || st.isSymbolicLink() || !st.isFile() || st.nlink <= 1)
903
+ break;
904
+ await new Promise(r => setTimeout(r, 5));
905
+ }
906
+ await streamVerifiedCasBlob(artifacts.directory, { sha256: sha256Hex, byteLength: expectedBundleBytes, path: finalHexPath }, async () => {
907
+ if (signal.aborted)
908
+ throw cancelledFailure('verification');
909
+ if (onProgress)
910
+ await onProgress();
911
+ }, 'verification');
912
+ }
913
+ await syncDirectory(sha256Dir);
914
+ return freeze({
915
+ digest: freeze({ algorithm: 'sha256', hex: sha256Hex }),
916
+ byteLength: expectedBundleBytes,
917
+ blobPath: finalHexPath,
918
+ });
919
+ }
920
+ finally {
921
+ if (!vaultFinished) {
922
+ try {
923
+ vaultChecker.finish();
924
+ }
925
+ catch {
926
+ // Ignore cleanup error after failure.
927
+ }
928
+ }
929
+ if (tmpHandle !== null && !tmpClosed) {
930
+ await tmpHandle.close().catch(() => { });
931
+ }
932
+ if (!tmpUnlinked && createdDev !== -1) {
933
+ await unlinkIfOwnedInode(tmpPath, createdDev, createdIno).catch(() => { });
934
+ }
935
+ releaseActivity();
936
+ }
937
+ }
938
+ /** Bounded deterministic `LWTREE01` binary bundle decoder. */
939
+ export function decodeBenchmarkBaseTreeBundle(bytes, maxBytes = VERIFIER_ARTIFACT_LIMITS.maxFileBytes) {
940
+ if (!(bytes instanceof Uint8Array)
941
+ || types.isProxy(bytes)
942
+ || types.isSharedArrayBuffer(bytes.buffer)
943
+ || bytes.byteLength < 12
944
+ || bytes.byteLength > maxBytes) {
945
+ refuse('ARTIFACT_INVALID', '', 'verification');
946
+ }
947
+ if (!Buffer.from(bytes.buffer, bytes.byteOffset, 8).equals(BASE_TREE_BUNDLE_MAGIC)) {
948
+ refuse('ARTIFACT_INVALID', '', 'verification');
949
+ }
950
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
951
+ const count = view.getUint32(8, false);
952
+ if (count > LIMITS.baselineEntries)
953
+ refuse('ARTIFACT_INVALID', '', 'verification');
954
+ const decoder = new TextDecoder('utf-8', { fatal: true });
955
+ const entries = [];
956
+ const seenFolded = new Set();
957
+ let prevName = null;
958
+ let offset = 12;
959
+ for (let i = 0; i < count; i++) {
960
+ if (offset + 4 > bytes.byteLength)
961
+ refuse('ARTIFACT_INVALID', '', 'verification');
962
+ const pathLen = view.getUint32(offset, false);
963
+ offset += 4;
964
+ if (pathLen < 1 || pathLen > 4096 || offset + pathLen + 5 > bytes.byteLength) {
965
+ refuse('ARTIFACT_INVALID', '', 'verification');
966
+ }
967
+ let name;
968
+ try {
969
+ name = decoder.decode(bytes.subarray(offset, offset + pathLen));
970
+ }
971
+ catch {
972
+ refuse('ARTIFACT_INVALID', '', 'verification');
973
+ }
974
+ offset += pathLen;
975
+ const validRel = validateRelativePath(name);
976
+ if (!validRel.ok
977
+ || validRel.value !== name
978
+ || isVerifierNamespacePath(name)
979
+ || name.split('/').some(seg => seg.toLowerCase() === '.git' || Buffer.byteLength(seg, 'utf8') > 255)
980
+ || (prevName !== null && compareUtf16(prevName, name) >= 0)) {
981
+ refuse('ARTIFACT_INVALID', '', 'verification');
982
+ }
983
+ prevName = name;
984
+ const folded = name.normalize('NFC').toLowerCase();
985
+ if (seenFolded.has(folded))
986
+ refuse('ARTIFACT_INVALID', '', 'verification');
987
+ seenFolded.add(folded);
988
+ const modeFlag = bytes[offset];
989
+ offset += 1;
990
+ if (modeFlag !== 0 && modeFlag !== 1)
991
+ refuse('ARTIFACT_INVALID', '', 'verification');
992
+ const contentLen = view.getUint32(offset, false);
993
+ offset += 4;
994
+ if (contentLen > bytes.byteLength - offset)
995
+ refuse('ARTIFACT_INVALID', '', 'verification');
996
+ const content = bytes.slice(offset, offset + contentLen);
997
+ offset += contentLen;
998
+ entries.push(freeze({
999
+ name,
1000
+ mode: modeFlag === 1 ? '100755' : '100644',
1001
+ bytes: content,
1002
+ }));
1003
+ }
1004
+ if (offset !== bytes.byteLength)
1005
+ refuse('ARTIFACT_INVALID', '', 'verification');
1006
+ for (const folded of seenFolded) {
1007
+ let slash = folded.indexOf('/');
1008
+ while (slash !== -1) {
1009
+ if (seenFolded.has(folded.slice(0, slash)))
1010
+ refuse('ARTIFACT_INVALID', '', 'verification');
1011
+ slash = folded.indexOf('/', slash + 1);
1012
+ }
1013
+ }
1014
+ return freeze(entries);
1015
+ }
1016
+ export function resolveBenchmarkBaseUrl(endpoint, gateUrlOverrides, phase = 'verification') {
1017
+ let transportUrl = endpoint.url;
1018
+ if (gateUrlOverrides && Object.hasOwn(gateUrlOverrides, endpoint.id) && gateUrlOverrides[endpoint.id] !== undefined) {
1019
+ const overrideUrl = gateUrlOverrides[endpoint.id];
1020
+ validateGateUrlOverrides({ [endpoint.id]: overrideUrl }, phase, [endpoint]);
1021
+ transportUrl = overrideUrl;
1022
+ }
1023
+ return transportUrl.replace(/\/+$/, '');
1024
+ }
1025
+ async function readBoundedResponseBytes(response, maxBytes) {
1026
+ if (!response.body)
1027
+ return new Uint8Array(0);
1028
+ const reader = response.body.getReader();
1029
+ const chunks = [];
1030
+ let total = 0;
1031
+ try {
1032
+ for (;;) {
1033
+ const { done, value } = await reader.read();
1034
+ if (done)
1035
+ break;
1036
+ if (!value || value.byteLength === 0)
1037
+ continue;
1038
+ total += value.byteLength;
1039
+ if (total > maxBytes) {
1040
+ await reader.cancel().catch(() => { });
1041
+ return null;
1042
+ }
1043
+ chunks.push(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
1044
+ }
1045
+ }
1046
+ finally {
1047
+ reader.releaseLock();
1048
+ }
1049
+ if (chunks.length === 0)
1050
+ return new Uint8Array(0);
1051
+ if (chunks.length === 1)
1052
+ return chunks[0];
1053
+ const merged = new Uint8Array(total);
1054
+ let offset = 0;
1055
+ for (const chunk of chunks) {
1056
+ merged.set(chunk, offset);
1057
+ offset += chunk.byteLength;
1058
+ }
1059
+ return merged;
1060
+ }
1061
+ /** Rate-limits SQLite lease renewal callbacks during multi-chunk CAS scans without throttling cancellation checks. */
1062
+ export function createRateLimitedProgress(onProgress, minIntervalMs = 1_000) {
1063
+ if (!onProgress)
1064
+ return undefined;
1065
+ let lastRenewMs = performance.now();
1066
+ return async () => {
1067
+ const now = performance.now();
1068
+ if (now - lastRenewMs < minIntervalMs)
1069
+ return;
1070
+ lastRenewMs = now;
1071
+ await onProgress();
1072
+ };
1073
+ }
1074
+ export async function pullBenchmarkOutputBlobs(options) {
1075
+ const phase = options.phase ?? 'verification';
1076
+ const extraSecrets = [options.secret, ...(options.bearerToken !== null ? [options.bearerToken] : [])];
1077
+ const refs = [];
1078
+ const chunkProgress = createRateLimitedProgress(options.onBeforeEach, 1_000);
1079
+ for (const item of options.outputArtifacts) {
1080
+ options.onBeforeEach?.();
1081
+ const logicalName = `.loopwright-verifier/${options.slotId}/${item.name}`;
1082
+ if (options.reuseLocalFirst) {
1083
+ if (options.signal.aborted) {
1084
+ throw cancelledFailure(phase);
1085
+ }
1086
+ try {
1087
+ const reused = await options.artifacts.verifyOrReuseVerifierCasBlob({
1088
+ logicalName,
1089
+ expectedSha256: item.digest.hex,
1090
+ expectedByteLength: item.byteLength,
1091
+ mediaType: item.mediaType,
1092
+ maxBytes: VERIFIER_ARTIFACT_LIMITS.maxFileBytes,
1093
+ phase,
1094
+ extraSecrets,
1095
+ signal: options.signal,
1096
+ onProgress: chunkProgress,
1097
+ });
1098
+ if (options.signal.aborted) {
1099
+ throw cancelledFailure(phase);
1100
+ }
1101
+ if (reused !== null) {
1102
+ refs.push(reused.blobRef);
1103
+ continue;
1104
+ }
1105
+ }
1106
+ catch (error) {
1107
+ if (options.signal.aborted) {
1108
+ throw cancelledFailure(phase);
1109
+ }
1110
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'ARTIFACT_INVALID') {
1111
+ return { ok: false, casOutcome: 'artifact_invalid' };
1112
+ }
1113
+ throw error;
1114
+ }
1115
+ }
1116
+ const timeoutMs = options.resolveTimeoutMs();
1117
+ if (timeoutMs === null || timeoutMs <= 0) {
1118
+ return { ok: false, casOutcome: 'gate_timeout' };
1119
+ }
1120
+ const url = `${options.baseUrl}/${encodeURIComponent(options.operationId)}/blobs/${item.digest.hex}`;
1121
+ const headers = {
1122
+ 'x-loopwright-signature': signPayload(options.secret, `GET\n${options.operationId}\n${item.digest.hex}`),
1123
+ };
1124
+ if (options.bearerToken !== null)
1125
+ headers.authorization = 'Bearer ' + options.bearerToken;
1126
+ const composed = AbortSignal.any([options.signal, AbortSignal.timeout(timeoutMs)]);
1127
+ let response;
1128
+ try {
1129
+ response = await fetch(url, { method: 'GET', headers, redirect: 'error', signal: composed });
1130
+ }
1131
+ catch {
1132
+ if (options.signal.aborted) {
1133
+ throw new ControllerFailure({
1134
+ version: 1,
1135
+ code: 'CANCELLED',
1136
+ phase,
1137
+ path: '',
1138
+ stateCode: null,
1139
+ piCode: null,
1140
+ effect: 'none',
1141
+ retryable: false,
1142
+ });
1143
+ }
1144
+ const nextWindow = options.resolveTimeoutMs();
1145
+ return { ok: false, casOutcome: nextWindow === null || nextWindow <= 0 ? 'gate_timeout' : 'evidence_unavailable' };
1146
+ }
1147
+ if (response.status !== 200) {
1148
+ await response.body?.cancel().catch(() => { });
1149
+ return { ok: false, casOutcome: 'evidence_unavailable' };
1150
+ }
1151
+ const headerSha = response.headers.get('x-loopwright-blob-sha256') ?? '';
1152
+ const headerLen = response.headers.get('x-loopwright-blob-length') ?? '';
1153
+ const headerSig = response.headers.get('x-loopwright-signature') ?? '';
1154
+ const expectedSigned = `BLOB\n${options.operationId}\n${item.digest.hex}\n${String(item.byteLength)}`;
1155
+ if (headerSha !== item.digest.hex
1156
+ || headerLen !== String(item.byteLength)
1157
+ || !verifySignedPayload(options.secret, expectedSigned, headerSig)) {
1158
+ await response.body?.cancel().catch(() => { });
1159
+ return { ok: false, casOutcome: 'artifact_invalid' };
1160
+ }
1161
+ let streamTransportError = false;
1162
+ try {
1163
+ const pointer = await options.artifacts.ingestVerifiedCasBlobStream({
1164
+ logicalName,
1165
+ expectedSha256: item.digest.hex,
1166
+ expectedByteLength: item.byteLength,
1167
+ mediaType: item.mediaType,
1168
+ maxBytes: VERIFIER_ARTIFACT_LIMITS.maxFileBytes,
1169
+ phase,
1170
+ extraSecrets,
1171
+ signal: options.signal,
1172
+ onProgress: chunkProgress,
1173
+ }, async (consumeChunk) => {
1174
+ if (!response.body)
1175
+ return;
1176
+ const reader = response.body.getReader();
1177
+ try {
1178
+ for (;;) {
1179
+ let step;
1180
+ try {
1181
+ step = await reader.read();
1182
+ }
1183
+ catch (err) {
1184
+ streamTransportError = true;
1185
+ throw err;
1186
+ }
1187
+ if (step.done)
1188
+ break;
1189
+ if (step.value && step.value.byteLength > 0) {
1190
+ await consumeChunk(step.value);
1191
+ }
1192
+ }
1193
+ }
1194
+ finally {
1195
+ reader.releaseLock();
1196
+ }
1197
+ });
1198
+ refs.push(pointer.blobRef);
1199
+ }
1200
+ catch (error) {
1201
+ await response.body?.cancel().catch(() => { });
1202
+ if (options.signal.aborted) {
1203
+ throw new ControllerFailure({
1204
+ version: 1,
1205
+ code: 'CANCELLED',
1206
+ phase,
1207
+ path: '',
1208
+ stateCode: null,
1209
+ piCode: null,
1210
+ effect: 'none',
1211
+ retryable: false,
1212
+ });
1213
+ }
1214
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'ARTIFACT_INVALID' && !streamTransportError) {
1215
+ return { ok: false, casOutcome: 'artifact_invalid' };
1216
+ }
1217
+ if (streamTransportError) {
1218
+ const nextWindow = options.resolveTimeoutMs();
1219
+ return { ok: false, casOutcome: nextWindow === null || nextWindow <= 0 ? 'gate_timeout' : 'evidence_unavailable' };
1220
+ }
1221
+ throw error;
1222
+ }
1223
+ }
1224
+ return { ok: true, refs: freeze(refs), casOutcome: 'ok' };
1225
+ }
1226
+ export function isPreemptedBenchmarkVerdict(verdict) {
1227
+ return (verdict.status !== 'pending'
1228
+ && verdict.status !== 'approved'
1229
+ && (verdict.retryablePreemption === true || verdict.reason === 'BENCHMARK_PREEMPTED'));
1230
+ }
1231
+ export function shouldPullBenchmarkOutputs(input) {
1232
+ const { verdict } = input;
1233
+ if (verdict === null
1234
+ || verdict.outputArtifacts === undefined
1235
+ || verdict.outputArtifacts.length === 0
1236
+ || isPreemptedBenchmarkVerdict(verdict)) {
1237
+ return false;
1238
+ }
1239
+ if (verdict.status === 'denied') {
1240
+ return (verdict.hardwareProvenance === undefined
1241
+ || matchesHardwareTarget(input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, verdict.hardwareProvenance));
1242
+ }
1243
+ if (verdict.status === 'approved') {
1244
+ return (input.wallClockValid
1245
+ && matchesHardwareTarget(input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, verdict.hardwareProvenance)
1246
+ && evaluateBenchmarkThresholds(input.metricThresholds, verdict.metrics));
1247
+ }
1248
+ return false;
1249
+ }
1250
+ export async function collectPriorGenerationVerifierBudget(plan, artifacts, generation, excludeSlotId, inMemoryChecks, retainedReceipts) {
1251
+ let files = 0;
1252
+ let bytes = 0;
1253
+ for (const slot of plan.verifierSlots) {
1254
+ if (slot.id === excludeSlotId || slot.handler.implementation !== 'benchmark-gate.v1')
1255
+ continue;
1256
+ const mem = inMemoryChecks?.get(slot.id + ':' + generation);
1257
+ if (mem) {
1258
+ const obs = observations.get(mem);
1259
+ if (obs) {
1260
+ files += obs.verifierArtifacts.length;
1261
+ for (const ref of obs.verifierArtifacts)
1262
+ bytes += ref.byteLength;
1263
+ continue;
1264
+ }
1265
+ }
1266
+ const row = retainedReceipts?.find(item => item.slot === slot.id && item.generation === generation && item.output !== null && item.receipt !== null);
1267
+ if (!row || !row.output)
1268
+ continue;
1269
+ const rawOut = parsePrivateJson(await artifacts.read(row.output, BENCHMARK_OUTPUT_BYTES), BENCHMARK_OUTPUT_BYTES);
1270
+ if (!isRecord(rawOut) || !Array.isArray(rawOut.verifierArtifacts))
1271
+ continue;
1272
+ for (const rawRef of list(rawOut.verifierArtifacts, '', VERIFIER_ARTIFACT_LIMITS.maxFilesPerSlot)) {
1273
+ const ref = checkedVerifierArtifactRef(rawRef, 'recovery');
1274
+ files += 1;
1275
+ bytes += ref.byteLength;
1276
+ }
1277
+ }
1278
+ return freeze({ files, bytes });
1279
+ }
1280
+ export function computeBenchmarkDisposition(input) {
1281
+ const { verdict, timedOut, sawPreemption } = input;
1282
+ if (!verdict || verdict.status === 'pending') {
1283
+ if (timedOut) {
1284
+ if (sawPreemption) {
1285
+ return freeze({ status: 'blocked', reason: 'BENCHMARK_PREEMPTED', method: 'benchmark_transport', retryablePreemption: true });
1286
+ }
1287
+ return freeze({ status: 'blocked', reason: 'GATE_TIMEOUT', method: 'benchmark_transport' });
1288
+ }
1289
+ return freeze({ status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: 'benchmark_transport' });
1290
+ }
1291
+ if (isPreemptedBenchmarkVerdict(verdict)) {
1292
+ return freeze({ status: 'blocked', reason: 'BENCHMARK_PREEMPTED', method: 'benchmark-gate.v1', retryablePreemption: true });
1293
+ }
1294
+ const preemptionField = verdict.retryablePreemption !== undefined ? { retryablePreemption: verdict.retryablePreemption } : {};
1295
+ if (verdict.status === 'expired') {
1296
+ return freeze({
1297
+ status: 'blocked',
1298
+ reason: verdict.reason ?? 'EVIDENCE_UNAVAILABLE',
1299
+ method: 'benchmark-gate.v1',
1300
+ ...preemptionField,
1301
+ });
1302
+ }
1303
+ if (verdict.status === 'denied') {
1304
+ if (verdict.hardwareProvenance !== undefined
1305
+ && !matchesHardwareTarget(input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, verdict.hardwareProvenance)) {
1306
+ return freeze({ status: 'blocked', reason: 'HARDWARE_PROVENANCE_MISMATCH', method: 'benchmark-gate.v1', ...preemptionField });
1307
+ }
1308
+ if (input.casOutcome === 'artifact_invalid') {
1309
+ return freeze({ status: 'blocked', reason: 'ARTIFACT_INVALID', method: 'benchmark-gate.v1', ...preemptionField });
1310
+ }
1311
+ if (input.casOutcome === 'gate_timeout') {
1312
+ if (sawPreemption) {
1313
+ return freeze({ status: 'blocked', reason: 'BENCHMARK_PREEMPTED', method: 'benchmark_transport', retryablePreemption: true });
1314
+ }
1315
+ return freeze({ status: 'blocked', reason: 'GATE_TIMEOUT', method: 'benchmark_transport', ...preemptionField });
1316
+ }
1317
+ if (input.casOutcome === 'evidence_unavailable') {
1318
+ return freeze({ status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: 'benchmark_transport', ...preemptionField });
1319
+ }
1320
+ return freeze({
1321
+ status: 'failed',
1322
+ reason: verdict.reason ?? 'benchmark_denied',
1323
+ method: 'benchmark-gate.v1',
1324
+ ...preemptionField,
1325
+ });
1326
+ }
1327
+ // verdict.status === 'approved'
1328
+ if (input.casOutcome === 'artifact_invalid') {
1329
+ return freeze({ status: 'blocked', reason: 'ARTIFACT_INVALID', method: 'benchmark-gate.v1', ...preemptionField });
1330
+ }
1331
+ if (!input.wallClockValid) {
1332
+ return freeze({ status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: 'benchmark-gate.v1', ...preemptionField });
1333
+ }
1334
+ if (!matchesHardwareTarget(input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, verdict.hardwareProvenance)) {
1335
+ return freeze({ status: 'blocked', reason: 'HARDWARE_PROVENANCE_MISMATCH', method: 'benchmark-gate.v1', ...preemptionField });
1336
+ }
1337
+ if (!evaluateBenchmarkThresholds(input.metricThresholds, verdict.metrics)) {
1338
+ return freeze({ status: 'blocked', reason: 'METRIC_THRESHOLD_FAILED', method: 'benchmark-gate.v1', ...preemptionField });
1339
+ }
1340
+ if (input.casOutcome === 'gate_timeout') {
1341
+ if (sawPreemption) {
1342
+ return freeze({ status: 'blocked', reason: 'BENCHMARK_PREEMPTED', method: 'benchmark_transport', retryablePreemption: true });
1343
+ }
1344
+ return freeze({ status: 'blocked', reason: 'GATE_TIMEOUT', method: 'benchmark_transport', ...preemptionField });
1345
+ }
1346
+ if (input.casOutcome === 'evidence_unavailable') {
1347
+ return freeze({ status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: 'benchmark_transport', ...preemptionField });
1348
+ }
1349
+ return freeze({ status: 'passed', reason: null, method: 'benchmark-gate.v1', ...preemptionField });
1350
+ }
1351
+ function computeBoundedBackoffDelayMs(endpoint, operationId, attempt, remainingMonoMs, remainingMaxPollMs) {
1352
+ const exponential = Math.min(endpoint.pollMaxMs, endpoint.pollInitialMs * 2 ** Math.min(30, Math.max(0, attempt - 1)));
1353
+ const jitterSeed = endpoint.jitter
1354
+ ? parseInt(hash('loopwright.dev/controller/benchmark-jitter/v1\0'
1355
+ + canonical({ operationId, attempt })).hex.slice(0, 8), 16)
1356
+ : 0;
1357
+ const withJitter = exponential + (endpoint.jitter ? jitterSeed % (endpoint.jitter + 1) : 0);
1358
+ return Math.min(withJitter, remainingMonoMs, remainingMaxPollMs);
1359
+ }
1360
+ function sleep(ms, signal) {
1361
+ if (signal.aborted)
1362
+ return Promise.reject(cancelledFailure('verification'));
1363
+ return new Promise((resolve, reject) => {
1364
+ const onDone = () => {
1365
+ signal.removeEventListener('abort', abort);
1366
+ resolve();
1367
+ };
1368
+ const abort = () => {
1369
+ clearTimeout(timer);
1370
+ signal.removeEventListener('abort', abort);
1371
+ reject(cancelledFailure('verification'));
1372
+ };
1373
+ const timer = setTimeout(onDone, ms);
1374
+ signal.addEventListener('abort', abort, { once: true });
1375
+ });
1376
+ }
1377
+ export async function validateStoredBenchmarkProof(input) {
1378
+ const proof = record(parsePrivateJson(input.proofBytes, 1_048_576), ['version', 'output', 'receipt', 'evidence']);
1379
+ if (proof.version !== 1)
1380
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1381
+ const output = checkedRef(proof.output);
1382
+ const receiptRef = checkedRef(proof.receipt);
1383
+ const outputBytes = await input.artifacts.read(output, BENCHMARK_OUTPUT_BYTES);
1384
+ const saved = record(parsePrivateJson(Buffer.from(outputBytes), BENCHMARK_OUTPUT_BYTES), [
1385
+ 'version',
1386
+ 'binding',
1387
+ 'observation',
1388
+ 'verdict',
1389
+ 'responseBytes',
1390
+ 'responseSignature',
1391
+ 'verifierArtifacts',
1392
+ 'disposition',
1393
+ ]);
1394
+ const savedBinding = record(saved.binding, [
1395
+ 'planDigest',
1396
+ 'operationId',
1397
+ 'producerNonce',
1398
+ 'generation',
1399
+ 'endpoint',
1400
+ 'subject',
1401
+ 'requestBytesDigest',
1402
+ ]);
1403
+ if (saved.version !== 1
1404
+ || !same(savedBinding, {
1405
+ planDigest: input.plan.planDigest,
1406
+ operationId: input.operationId,
1407
+ producerNonce: input.producerNonce,
1408
+ generation: input.generation,
1409
+ endpoint: input.endpoint.id,
1410
+ subject: input.subject,
1411
+ requestBytesDigest: input.requestBytesDigest,
1412
+ })) {
1413
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1414
+ }
1415
+ const observation = record(saved.observation, [
1416
+ 'attempts',
1417
+ 'elapsedMs',
1418
+ 'transport',
1419
+ 'sawPreemption',
1420
+ 'wallClockValid',
1421
+ 'casOutcome',
1422
+ ]);
1423
+ integer(observation.attempts, 1, 65_536);
1424
+ integer(observation.elapsedMs, 0, Number.MAX_SAFE_INTEGER);
1425
+ if (!['completed', 'deadline'].includes(text(observation.transport))
1426
+ || typeof observation.sawPreemption !== 'boolean'
1427
+ || typeof observation.wallClockValid !== 'boolean'
1428
+ || !['ok', 'artifact_invalid', 'evidence_unavailable', 'gate_timeout'].includes(text(observation.casOutcome))) {
1429
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1430
+ }
1431
+ let verdict = null;
1432
+ if (saved.verdict !== null && typeof saved.responseBytes === 'string' && typeof saved.responseSignature === 'string') {
1433
+ const responseBytes = Buffer.from(saved.responseBytes, 'base64');
1434
+ if (responseBytes.byteLength > BENCHMARK_RESPONSE_BYTES)
1435
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1436
+ if (!verifySignedPayload(input.secret, responseBytes, saved.responseSignature)) {
1437
+ refuse('EVIDENCE_UNAVAILABLE', '', 'recovery');
1438
+ }
1439
+ const expected = {
1440
+ storeId: input.view.storeId,
1441
+ runId: input.view.runId,
1442
+ lockHash: input.view.lockHash,
1443
+ operationId: input.operationId,
1444
+ dispatchId: input.dispatch.dispatchId,
1445
+ dispatchGeneration: input.dispatch.generation,
1446
+ gateId: String(input.request.gateId),
1447
+ checkId: String(input.request.checkId),
1448
+ candidateDigest: String(input.request.candidateDigest),
1449
+ slotId: input.slot.id,
1450
+ };
1451
+ const parsed = checkedBenchmarkVerdict(parsePrivateJson(responseBytes, BENCHMARK_RESPONSE_BYTES), expected);
1452
+ if (!same(saved.verdict, parsed) || parsed.status === 'pending')
1453
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1454
+ verdict = parsed;
1455
+ }
1456
+ else if (saved.verdict !== null || saved.responseBytes !== null || saved.responseSignature !== null) {
1457
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1458
+ }
1459
+ const savedRefsRaw = list(saved.verifierArtifacts, '', VERIFIER_ARTIFACT_LIMITS.maxFilesPerSlot);
1460
+ const parsedSavedRefs = savedRefsRaw.map(rawRef => checkedVerifierArtifactRef(rawRef, 'recovery'));
1461
+ const extraSecrets = [input.secret, ...(input.bearerToken !== null ? [input.bearerToken] : [])];
1462
+ const priorBudget = input.priorBudget ?? { files: 0, bytes: 0 };
1463
+ const totalLimits = input.totalLimits ?? VERIFIER_ARTIFACT_LIMITS;
1464
+ const casOutcome = observation.casOutcome;
1465
+ const expectedPull = shouldPullBenchmarkOutputs({
1466
+ verdict,
1467
+ wallClockValid: observation.wallClockValid,
1468
+ targetHardware: input.targetHardware,
1469
+ targetCellId: input.targetCellId,
1470
+ allowSyntheticHardwareProbe: input.allowSyntheticHardwareProbe,
1471
+ metricThresholds: input.metricThresholds,
1472
+ });
1473
+ const expectedOutputs = verdict?.outputArtifacts ?? [];
1474
+ if (casOutcome !== 'ok' || !expectedPull) {
1475
+ if (parsedSavedRefs.length !== 0)
1476
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1477
+ }
1478
+ else {
1479
+ if (parsedSavedRefs.length !== expectedOutputs.length)
1480
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1481
+ for (let idx = 0; idx < expectedOutputs.length; idx++) {
1482
+ const expOut = expectedOutputs[idx];
1483
+ const obsRef = parsedSavedRefs[idx];
1484
+ const expectedCanonicalRef = expectedBenchmarkOutputArtifactRef(input.slot.id, expOut, 'recovery');
1485
+ if (!same(obsRef, expectedCanonicalRef)) {
1486
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1487
+ }
1488
+ }
1489
+ }
1490
+ // Prevalidate cross-slot file count and aggregate byte budget across ALL proposed refs BEFORE hashing/reusing any local CAS blob.
1491
+ if (priorBudget.files + parsedSavedRefs.length > totalLimits.maxTotalFiles) {
1492
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1493
+ }
1494
+ let proposedBytes = 0;
1495
+ for (const ref of parsedSavedRefs) {
1496
+ if (ref.byteLength > totalLimits.maxTotalBytes - priorBudget.bytes - proposedBytes) {
1497
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1498
+ }
1499
+ proposedBytes += ref.byteLength;
1500
+ }
1501
+ const verifierCasRefs = [];
1502
+ let localCasInvalid = false;
1503
+ for (let idx = 0; idx < parsedSavedRefs.length; idx++) {
1504
+ if (input.signal?.aborted) {
1505
+ refuse('CANCELLED', '', 'recovery');
1506
+ }
1507
+ if (input.onProgress) {
1508
+ await input.onProgress();
1509
+ }
1510
+ const ref = parsedSavedRefs[idx];
1511
+ const expOut = expectedOutputs[idx];
1512
+ let verified;
1513
+ try {
1514
+ verified = await input.artifacts.verifyOrReuseVerifierCasBlob({
1515
+ logicalName: ref.name,
1516
+ expectedSha256: ref.digest.hex,
1517
+ expectedByteLength: ref.byteLength,
1518
+ mediaType: expOut.mediaType,
1519
+ maxBytes: VERIFIER_ARTIFACT_LIMITS.maxFileBytes,
1520
+ phase: 'recovery',
1521
+ extraSecrets,
1522
+ signal: input.signal,
1523
+ onProgress: input.onProgress,
1524
+ });
1525
+ }
1526
+ catch (error) {
1527
+ if (error instanceof ControllerFailure
1528
+ && (error.diagnostic.code === 'CANCELLED'
1529
+ || error.diagnostic.code === 'AUTHORITY_REFUSED'
1530
+ || error.diagnostic.code === 'OWNER_BUSY')) {
1531
+ throw error;
1532
+ }
1533
+ if (input.allowInvalidLocalCasSettlement === true
1534
+ && error instanceof ControllerFailure
1535
+ && error.diagnostic.code === 'ARTIFACT_INVALID') {
1536
+ localCasInvalid = true;
1537
+ break;
1538
+ }
1539
+ throw error;
1540
+ }
1541
+ if (!verified || !same(verified.blobRef, ref)) {
1542
+ if (input.allowInvalidLocalCasSettlement === true) {
1543
+ localCasInvalid = true;
1544
+ break;
1545
+ }
1546
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1547
+ }
1548
+ verifierCasRefs.push(verified.blobRef);
1549
+ }
1550
+ if (input.signal?.aborted) {
1551
+ refuse('CANCELLED', '', 'recovery');
1552
+ }
1553
+ if (input.onProgress) {
1554
+ await input.onProgress();
1555
+ }
1556
+ const dispositioned = computeBenchmarkDisposition({
1557
+ verdict,
1558
+ timedOut: observation.transport === 'deadline',
1559
+ sawPreemption: observation.sawPreemption,
1560
+ wallClockValid: observation.wallClockValid,
1561
+ targetHardware: input.targetHardware,
1562
+ targetCellId: input.targetCellId,
1563
+ allowSyntheticHardwareProbe: input.allowSyntheticHardwareProbe,
1564
+ metricThresholds: input.metricThresholds,
1565
+ casOutcome,
1566
+ });
1567
+ if (!same(saved.disposition, dispositioned))
1568
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1569
+ const suffix = hash(input.operationId + '\0' + input.producerNonce).hex.slice(0, 40);
1570
+ const evidenceArtifacts = localCasInvalid ? parsedSavedRefs : verifierCasRefs;
1571
+ const evidenceSpec = {
1572
+ checkId: input.slot.checkId,
1573
+ observedStatus: dispositioned.status,
1574
+ producerId: 'loopwright.benchmark-gate.v1',
1575
+ method: dispositioned.method,
1576
+ level: 'hardware_execution',
1577
+ subject: input.subject,
1578
+ artifacts: [output, ...evidenceArtifacts],
1579
+ reason: dispositioned.reason,
1580
+ ...(verdict && Object.hasOwn(verdict, 'detail') ? { detail: verdict.detail } : {}),
1581
+ ...(verdict?.metrics !== undefined ? { metrics: verdict.metrics } : {}),
1582
+ ...(verdict?.findings !== undefined ? { findings: verdict.findings } : {}),
1583
+ ...(verdict?.hardwareProvenance !== undefined ? { hardwareProvenance: verdict.hardwareProvenance } : {}),
1584
+ };
1585
+ const evidence = validateDocument({ apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: evidenceSpec }, 'Evidence');
1586
+ if (!evidence.ok || !same(evidence.value, proof.evidence))
1587
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1588
+ const receipt = {
1589
+ receiptId: 'receipt.' + suffix,
1590
+ outcome: dispositioned.method === 'benchmark-gate.v1' ? 'succeeded' : 'failed',
1591
+ evidence: {
1592
+ evidenceId: 'receipt-evidence.' + suffix,
1593
+ producerId: 'loopwright.benchmark-gate.v1',
1594
+ method: dispositioned.method,
1595
+ subject: {
1596
+ storeId: input.view.storeId,
1597
+ runId: input.view.runId,
1598
+ lockHash: input.view.lockHash,
1599
+ operationId: input.operationId,
1600
+ requestId: null,
1601
+ intentDigest: input.operation.intentDigest,
1602
+ dispatchGeneration: input.dispatch.generation,
1603
+ dispatchId: input.dispatch.dispatchId,
1604
+ },
1605
+ artifact: output,
1606
+ },
1607
+ };
1608
+ if (!same(parsePrivateJson(await input.artifacts.read(receiptRef, 65_536), 65_536), receipt)) {
1609
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1610
+ }
1611
+ return {
1612
+ output,
1613
+ outputBytes,
1614
+ receiptRef,
1615
+ receipt,
1616
+ evidence: evidence.value,
1617
+ verdict,
1618
+ verifierCasRefs: freeze(localCasInvalid ? [] : verifierCasRefs),
1619
+ localCasInvalid,
1620
+ disposition: dispositioned,
1621
+ observation: freeze({
1622
+ attempts: observation.attempts,
1623
+ elapsedMs: observation.elapsedMs,
1624
+ transport: observation.transport,
1625
+ sawPreemption: observation.sawPreemption,
1626
+ wallClockValid: observation.wallClockValid,
1627
+ casOutcome,
1628
+ }),
1629
+ responseBytesBase64: typeof saved.responseBytes === 'string' ? saved.responseBytes : null,
1630
+ responseSignature: typeof saved.responseSignature === 'string' ? saved.responseSignature : null,
1631
+ };
1632
+ }
1633
+ function validateCandidateFilesForStaging(manifest, files) {
1634
+ if (files.length !== manifest.spec.entries.length) {
1635
+ refuse('ARTIFACT_INVALID', '', 'verification');
1636
+ }
1637
+ const byName = new Map();
1638
+ for (const file of files) {
1639
+ if (byName.has(file.name))
1640
+ refuse('ARTIFACT_INVALID', '', 'verification');
1641
+ byName.set(file.name, file);
1642
+ }
1643
+ const out = new Map();
1644
+ for (const entry of manifest.spec.entries) {
1645
+ const file = byName.get(entry.name);
1646
+ if (!file)
1647
+ refuse('ARTIFACT_INVALID', '', 'verification');
1648
+ const rawFileRec = file;
1649
+ if (Object.hasOwn(rawFileRec, 'mode') && rawFileRec.mode !== undefined && rawFileRec.mode !== '100644' && rawFileRec.mode !== '100755') {
1650
+ refuse('ARTIFACT_INVALID', '', 'verification');
1651
+ }
1652
+ if ('bytes' in file) {
1653
+ if ('blobPath' in file)
1654
+ refuse('ARTIFACT_INVALID', '', 'verification');
1655
+ const copy = ownedBytes(file.bytes, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
1656
+ if (copy.byteLength !== entry.byteLength || hash(copy).hex !== entry.digest.hex) {
1657
+ refuse('ARTIFACT_INVALID', '', 'verification');
1658
+ }
1659
+ out.set(entry.name, {
1660
+ name: entry.name,
1661
+ bytes: copy,
1662
+ ...(file.mode !== undefined ? { mode: file.mode } : {}),
1663
+ });
1664
+ }
1665
+ else {
1666
+ if (typeof file.blobPath !== 'string'
1667
+ || !isAbsolute(file.blobPath)
1668
+ || file.blobPath.length > 4096
1669
+ || /[\0\r\n]/.test(file.blobPath)
1670
+ || file.byteLength !== entry.byteLength
1671
+ || !same(file.digest, entry.digest)) {
1672
+ refuse('ARTIFACT_INVALID', '', 'verification');
1673
+ }
1674
+ out.set(entry.name, file);
1675
+ }
1676
+ }
1677
+ return out;
1678
+ }
1679
+ /** Authenticated remote benchmark gate client with streaming HTTP CAS staging/retrieval and Relay preemption safety. */
1680
+ export class BenchmarkGate {
1681
+ store;
1682
+ authority;
1683
+ artifacts;
1684
+ plan;
1685
+ lock;
1686
+ resolveCredential;
1687
+ currentSubject;
1688
+ onWait;
1689
+ gateUrlOverrides;
1690
+ resolvePriorVerifierBudget;
1691
+ verifierTotalLimits;
1692
+ constructor(store, authority, artifacts, plan, lock, resolveCredential, currentSubject, onWait = null, gateUrlOverrides, resolvePriorVerifierBudget, verifierTotalLimits) {
1693
+ this.store = store;
1694
+ this.authority = authority;
1695
+ this.artifacts = artifacts;
1696
+ this.plan = plan;
1697
+ this.lock = lock;
1698
+ this.resolveCredential = resolveCredential;
1699
+ this.currentSubject = currentSubject;
1700
+ this.onWait = onWait;
1701
+ this.gateUrlOverrides = gateUrlOverrides;
1702
+ this.resolvePriorVerifierBudget = resolvePriorVerifierBudget;
1703
+ this.verifierTotalLimits = verifierTotalLimits;
1704
+ }
1705
+ #identity() {
1706
+ const view = stateValue(this.store.inspect());
1707
+ if (view.storeId !== this.authority.storeId
1708
+ || view.runId !== this.lock.spec.runId
1709
+ || !same(view.lockHash, this.lock.spec.lockHash)
1710
+ || this.artifacts.owner.runId !== view.runId
1711
+ || !same(this.artifacts.owner.planDigest, this.plan.planDigest)) {
1712
+ refuse('AUTHORITY_REFUSED', '', 'verification');
1713
+ }
1714
+ return view;
1715
+ }
1716
+ #permit(permit, expected, target) {
1717
+ stateValue(this.store.renew(this.authority));
1718
+ const view = stateValue(this.store.inspect());
1719
+ const operation = stateValue(this.store.getOperation(permit.operationId));
1720
+ if (!same(this.currentSubject(), expected)
1721
+ || permit.generation !== this.authority.generation
1722
+ || permit.clockEpoch !== view.clock.basis.clockEpoch
1723
+ || view.storeId !== permit.storeId
1724
+ || view.runId !== permit.runId
1725
+ || !same(view.lockHash, permit.lockHash)
1726
+ || BigInt(view.clock.sampledNow.monotonicMs) >= BigInt(permit.notAfterMonotonicMs)
1727
+ || BigInt(view.clock.sampledNow.monotonicMs) >= BigInt(view.clock.basis.taskDeadlineMonotonicMs)
1728
+ || operation.state !== 'dispatch_uncertain'
1729
+ || operation.dispatch?.dispatchId !== permit.dispatchId
1730
+ || operation.intent.targetIdentity !== target) {
1731
+ refuse('AUTHORITY_REFUSED', '', 'verification');
1732
+ }
1733
+ }
1734
+ async #marker(operationId, nonce, kind, value) {
1735
+ await this.artifacts.owner.assertCurrent();
1736
+ const name = 'benchmark-producer-' + hash(operationId + '\0' + nonce).hex + '.' + kind + '.json';
1737
+ const path = join(this.artifacts.directory, name);
1738
+ await publishAtomicMarker(path, value, this.artifacts.vault, 'verification');
1739
+ }
1740
+ async #putSingleBlob(baseUrl, operationId, secret, bearerToken, file, sha256Hex, byteLength, signal, timeoutMs) {
1741
+ const url = `${baseUrl}/${encodeURIComponent(operationId)}/blobs/${sha256Hex}`;
1742
+ const headers = {
1743
+ 'content-type': 'application/octet-stream',
1744
+ 'content-length': String(byteLength),
1745
+ 'x-loopwright-blob-sha256': sha256Hex,
1746
+ 'x-loopwright-blob-length': String(byteLength),
1747
+ 'x-loopwright-signature': signPayload(secret, `PUT\n${operationId}\n${sha256Hex}\n${String(byteLength)}`),
1748
+ };
1749
+ if (bearerToken !== null)
1750
+ headers.authorization = 'Bearer ' + bearerToken;
1751
+ const composed = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
1752
+ if ('bytes' in file) {
1753
+ const raw = file.bytes;
1754
+ if (raw.byteLength !== byteLength || hash(raw).hex !== sha256Hex) {
1755
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1756
+ }
1757
+ let offset = 0;
1758
+ const body = byteLength === 0
1759
+ ? new Uint8Array(0)
1760
+ : new ReadableStream({
1761
+ pull(controller) {
1762
+ if (offset >= raw.byteLength) {
1763
+ controller.close();
1764
+ return;
1765
+ }
1766
+ const end = Math.min(raw.byteLength, offset + STREAM_CHUNK_BYTES);
1767
+ controller.enqueue(raw.subarray(offset, end));
1768
+ offset = end;
1769
+ if (offset >= raw.byteLength)
1770
+ controller.close();
1771
+ },
1772
+ });
1773
+ const init = {
1774
+ method: 'PUT',
1775
+ headers,
1776
+ body,
1777
+ redirect: 'error',
1778
+ signal: composed,
1779
+ ...(byteLength > 0 ? { duplex: 'half' } : {}),
1780
+ };
1781
+ try {
1782
+ const res = await fetch(url, init);
1783
+ await res.body?.cancel().catch(() => { });
1784
+ return res.status === 200 || res.status === 201 || res.status === 204 ? 'ok' : 'invalid';
1785
+ }
1786
+ catch {
1787
+ if (signal.aborted) {
1788
+ throw new ControllerFailure({
1789
+ version: 1,
1790
+ code: 'CANCELLED',
1791
+ phase: 'verification',
1792
+ path: '',
1793
+ stateCode: null,
1794
+ piCode: null,
1795
+ effect: 'none',
1796
+ retryable: false,
1797
+ });
1798
+ }
1799
+ return 'network';
1800
+ }
1801
+ }
1802
+ const canonicalBlobPath = await resolveCanonicalCasBlobPath(this.artifacts.directory, sha256Hex, file.blobPath, 'verification');
1803
+ let before;
1804
+ try {
1805
+ before = await lstat(canonicalBlobPath);
1806
+ }
1807
+ catch {
1808
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1809
+ }
1810
+ if (before.isSymbolicLink()
1811
+ || !before.isFile()
1812
+ || before.nlink !== 1
1813
+ || before.uid !== process.getuid?.()
1814
+ || (before.mode & 0o7777) !== 0o400
1815
+ || before.size !== byteLength) {
1816
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1817
+ }
1818
+ let handle;
1819
+ try {
1820
+ handle = await open(canonicalBlobPath, constants.O_RDONLY | constants.O_NOFOLLOW);
1821
+ }
1822
+ catch {
1823
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1824
+ }
1825
+ let closed = false;
1826
+ const closeHandle = async () => {
1827
+ if (!closed) {
1828
+ closed = true;
1829
+ await handle.close().catch(() => { });
1830
+ }
1831
+ };
1832
+ let localCorrupt = false;
1833
+ try {
1834
+ const info = await handle.stat();
1835
+ if (!info.isFile()
1836
+ || info.nlink !== 1
1837
+ || info.dev !== before.dev
1838
+ || info.ino !== before.ino
1839
+ || info.uid !== process.getuid?.()
1840
+ || info.size !== byteLength
1841
+ || (info.mode & 0o7777) !== 0o400) {
1842
+ localCorrupt = true;
1843
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1844
+ }
1845
+ if (byteLength === 0) {
1846
+ if (sha256Hex !== EMPTY_SHA256_HEX) {
1847
+ localCorrupt = true;
1848
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1849
+ }
1850
+ await closeHandle();
1851
+ try {
1852
+ const res = await fetch(url, {
1853
+ method: 'PUT',
1854
+ headers,
1855
+ body: new Uint8Array(0),
1856
+ redirect: 'error',
1857
+ signal: composed,
1858
+ });
1859
+ await res.body?.cancel().catch(() => { });
1860
+ return res.status === 200 || res.status === 201 || res.status === 204 ? 'ok' : 'invalid';
1861
+ }
1862
+ catch {
1863
+ if (signal.aborted) {
1864
+ throw new ControllerFailure({
1865
+ version: 1,
1866
+ code: 'CANCELLED',
1867
+ phase: 'verification',
1868
+ path: '',
1869
+ stateCode: null,
1870
+ piCode: null,
1871
+ effect: 'none',
1872
+ retryable: false,
1873
+ });
1874
+ }
1875
+ return 'network';
1876
+ }
1877
+ }
1878
+ const sha = createHash('sha256');
1879
+ let offset = 0;
1880
+ const body = new ReadableStream({
1881
+ async pull(controller) {
1882
+ try {
1883
+ const toRead = Math.min(STREAM_CHUNK_BYTES, byteLength - offset);
1884
+ if (toRead <= 0) {
1885
+ controller.close();
1886
+ return;
1887
+ }
1888
+ const chunkBuf = Buffer.allocUnsafe(toRead);
1889
+ const { bytesRead } = await handle.read(chunkBuf, 0, toRead, offset);
1890
+ if (bytesRead <= 0) {
1891
+ localCorrupt = true;
1892
+ await closeHandle();
1893
+ controller.error(new Error('unexpected_eof'));
1894
+ return;
1895
+ }
1896
+ const slice = new Uint8Array(chunkBuf.buffer, chunkBuf.byteOffset, bytesRead);
1897
+ sha.update(slice);
1898
+ offset += bytesRead;
1899
+ controller.enqueue(slice);
1900
+ if (offset >= byteLength) {
1901
+ const probe = Buffer.allocUnsafe(1);
1902
+ const extra = (await handle.read(probe, 0, 1, offset)).bytesRead;
1903
+ const after = await handle.stat();
1904
+ await closeHandle();
1905
+ if (extra !== 0
1906
+ || offset !== byteLength
1907
+ || !after.isFile()
1908
+ || after.nlink !== 1
1909
+ || after.dev !== info.dev
1910
+ || after.ino !== info.ino
1911
+ || after.size !== info.size
1912
+ || after.mtimeMs !== info.mtimeMs
1913
+ || after.ctimeMs !== info.ctimeMs
1914
+ || (after.mode & 0o7777) !== 0o400
1915
+ || sha.digest('hex') !== sha256Hex) {
1916
+ localCorrupt = true;
1917
+ controller.error(new Error('cas_integrity_failed'));
1918
+ return;
1919
+ }
1920
+ controller.close();
1921
+ }
1922
+ }
1923
+ catch (err) {
1924
+ await closeHandle();
1925
+ controller.error(err);
1926
+ }
1927
+ },
1928
+ async cancel() {
1929
+ await closeHandle();
1930
+ },
1931
+ });
1932
+ const init = {
1933
+ method: 'PUT',
1934
+ headers,
1935
+ body,
1936
+ duplex: 'half',
1937
+ redirect: 'error',
1938
+ signal: composed,
1939
+ };
1940
+ const res = await fetch(url, init);
1941
+ await res.body?.cancel().catch(() => { });
1942
+ if (localCorrupt)
1943
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1944
+ return res.status === 200 || res.status === 201 || res.status === 204 ? 'ok' : 'invalid';
1945
+ }
1946
+ catch (error) {
1947
+ if (localCorrupt || (error instanceof ControllerFailure && error.diagnostic.code === 'ARTIFACT_INVALID')) {
1948
+ refuse('ARTIFACT_INVALID', file.name, 'verification');
1949
+ }
1950
+ if (signal.aborted) {
1951
+ throw new ControllerFailure({
1952
+ version: 1,
1953
+ code: 'CANCELLED',
1954
+ phase: 'verification',
1955
+ path: '',
1956
+ stateCode: null,
1957
+ piCode: null,
1958
+ effect: 'none',
1959
+ retryable: false,
1960
+ });
1961
+ }
1962
+ return 'network';
1963
+ }
1964
+ finally {
1965
+ await closeHandle();
1966
+ }
1967
+ }
1968
+ async #roundTrip(baseUrl, secret, bearerToken, requestBody, signal, binding, timeoutMs) {
1969
+ const headers = {
1970
+ 'content-type': 'application/json',
1971
+ 'x-loopwright-signature': signPayload(secret, requestBody),
1972
+ };
1973
+ if (bearerToken !== null)
1974
+ headers.authorization = 'Bearer ' + bearerToken;
1975
+ const composed = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
1976
+ let bytes;
1977
+ let signature;
1978
+ try {
1979
+ const response = await fetch(baseUrl, {
1980
+ method: 'POST',
1981
+ headers,
1982
+ body: new Uint8Array(requestBody),
1983
+ redirect: 'error',
1984
+ signal: composed,
1985
+ });
1986
+ if (response.status !== 200 || !(response.headers.get('content-type') ?? '').startsWith('application/json')) {
1987
+ await response.body?.cancel().catch(() => { });
1988
+ return { kind: 'invalid' };
1989
+ }
1990
+ signature = response.headers.get('x-loopwright-signature') ?? '';
1991
+ bytes = await readBoundedResponseBytes(response, BENCHMARK_RESPONSE_BYTES);
1992
+ }
1993
+ catch {
1994
+ if (signal.aborted) {
1995
+ throw new ControllerFailure({
1996
+ version: 1,
1997
+ code: 'CANCELLED',
1998
+ phase: 'verification',
1999
+ path: '',
2000
+ stateCode: null,
2001
+ piCode: null,
2002
+ effect: 'none',
2003
+ retryable: false,
2004
+ });
2005
+ }
2006
+ return { kind: 'network' };
2007
+ }
2008
+ if (bytes === null || bytes.byteLength > BENCHMARK_RESPONSE_BYTES || !verifySignedPayload(secret, bytes, signature)) {
2009
+ return { kind: 'invalid' };
2010
+ }
2011
+ try {
2012
+ const verdict = checkedBenchmarkVerdict(parsePrivateJson(Buffer.from(bytes), BENCHMARK_RESPONSE_BYTES), binding);
2013
+ return { kind: 'verdict', verdict, responseBytes: bytes, signature };
2014
+ }
2015
+ catch {
2016
+ return { kind: 'invalid' };
2017
+ }
2018
+ }
2019
+ async run(job, signal) {
2020
+ const data = preparations.get(job);
2021
+ if (!data || this.plan.verifierSlots.find(slot => slot.id === job.slotId) !== data.slot) {
2022
+ refuse('EVIDENCE_UNAVAILABLE', '', 'verification');
2023
+ }
2024
+ signal.throwIfAborted();
2025
+ await this.artifacts.owner.assertCurrent();
2026
+ if (!same(this.currentSubject(), data.subject))
2027
+ refuse('ARTIFACT_INVALID', '', 'verification');
2028
+ const done = await this.artifacts.owner.holdLocalActivity();
2029
+ try {
2030
+ const target = 'benchmark:' + job.slotId + ':' + job.generation + ':' + data.subject.candidateDigest.hex;
2031
+ const before = this.#identity();
2032
+ if (before.owner.mode !== 'active')
2033
+ refuse('AUTHORITY_REFUSED', '', 'verification');
2034
+ if (before.counts.dispatchedRequests
2035
+ || before.counts.unresolvedRequests
2036
+ || before.counts.unresolvedOperations
2037
+ || before.ledger.violations.length) {
2038
+ refuse('RECOVERY_REQUIRED', '', 'verification');
2039
+ }
2040
+ const baseUrl = resolveBenchmarkBaseUrl(data.endpoint, this.gateUrlOverrides, 'verification');
2041
+ const expectedBase = expectedBenchmarkRequest(this.plan, data.slot, data.endpoint, data.subject, data.manifest, data.baseTreeBundle, data.files);
2042
+ const worstCaseRequest = {
2043
+ ...expectedBase,
2044
+ storeId: before.storeId,
2045
+ runId: before.runId,
2046
+ lockHash: before.lockHash,
2047
+ operationId: job.operationId,
2048
+ dispatchId: MAX_PREFLIGHT_DISPATCH_ID,
2049
+ dispatchGeneration: Math.max(this.authority.generation, MAX_PREFLIGHT_DISPATCH_GENERATION),
2050
+ requestDigest: job.requestDigest.hex,
2051
+ };
2052
+ if (Buffer.byteLength(canonical(worstCaseRequest), 'utf8') > BENCHMARK_REQUEST_BYTES) {
2053
+ refuse('OUTPUT_LIMIT', '', 'verification');
2054
+ }
2055
+ stateValue(this.store.putIntent(this.authority, {
2056
+ operationId: job.operationId,
2057
+ nodeId: this.plan.orderedDAG[0].id,
2058
+ attemptId: 'job.' + hash(job.operationId + '\0' + job.producerNonce).hex.slice(0, 40),
2059
+ effect: 'read_only',
2060
+ requestDigest: job.requestDigest,
2061
+ targetIdentity: target,
2062
+ }));
2063
+ const dispatched = stateValue(this.store.authorizeOperationDispatch(this.authority, job.operationId));
2064
+ if (dispatched.kind !== 'new_dispatch')
2065
+ refuse('RECOVERY_REQUIRED', '', 'verification');
2066
+ const permit = dispatched.permit;
2067
+ const request = {
2068
+ ...expectedBase,
2069
+ storeId: before.storeId,
2070
+ runId: before.runId,
2071
+ lockHash: before.lockHash,
2072
+ operationId: job.operationId,
2073
+ dispatchId: permit.dispatchId,
2074
+ dispatchGeneration: permit.generation,
2075
+ requestDigest: job.requestDigest.hex,
2076
+ };
2077
+ const requestBody = Buffer.from(canonical(request), 'utf8');
2078
+ if (requestBody.byteLength > BENCHMARK_REQUEST_BYTES) {
2079
+ refuse('OUTPUT_LIMIT', '', 'verification');
2080
+ }
2081
+ const requestBytesDigest = hash(requestBody).hex;
2082
+ const intentDigest = stateValue(this.store.getOperation(job.operationId)).intentDigest;
2083
+ await this.#marker(job.operationId, job.producerNonce, 'binding', {
2084
+ version: 1,
2085
+ planDigest: this.plan.planDigest,
2086
+ operationId: job.operationId,
2087
+ producerNonce: job.producerNonce,
2088
+ requestDigest: job.requestDigest,
2089
+ requestBytesDigest,
2090
+ intentDigest,
2091
+ subject: data.subject,
2092
+ generation: job.generation,
2093
+ endpoint: data.endpoint.id,
2094
+ dispatchReceipt: {
2095
+ generation: permit.generation,
2096
+ dispatchId: permit.dispatchId,
2097
+ revision: permit.authorizedRevision,
2098
+ clockEpoch: permit.clockEpoch,
2099
+ },
2100
+ });
2101
+ const secret = this.resolveCredential(data.endpoint.signingCredentialRef);
2102
+ const bearerToken = data.endpoint.authCredentialRef !== null ? this.resolveCredential(data.endpoint.authCredentialRef) : null;
2103
+ const started = performance.now();
2104
+ const startMono = BigInt(before.clock.sampledNow.monotonicMs);
2105
+ const maxPollMono = startMono + BigInt(data.endpoint.maxPollMs);
2106
+ const permitCapMono = BigInt(permit.notAfterMonotonicMs) > 2000n
2107
+ ? BigInt(permit.notAfterMonotonicMs) - 2000n
2108
+ : BigInt(permit.notAfterMonotonicMs);
2109
+ const drain = BigInt(this.plan.controls.drainReserveMs);
2110
+ const taskCapMono = BigInt(before.clock.basis.taskDeadlineMonotonicMs) > drain + 2000n
2111
+ ? BigInt(before.clock.basis.taskDeadlineMonotonicMs) - drain - 2000n
2112
+ : BigInt(before.clock.basis.taskDeadlineMonotonicMs);
2113
+ const pollDeadlineMono = [maxPollMono, permitCapMono, taskCapMono].reduce((a, b) => (a < b ? a : b));
2114
+ const deadlineMs = Math.max(0, Number(pollDeadlineMono - startMono));
2115
+ const isPastPollDeadline = () => {
2116
+ const nowMono = BigInt(stateValue(this.store.inspect()).clock.sampledNow.monotonicMs);
2117
+ const elapsed = Math.ceil(performance.now() - started);
2118
+ return nowMono >= pollDeadlineMono || elapsed >= data.endpoint.maxPollMs;
2119
+ };
2120
+ const remainingWindowMs = () => {
2121
+ const nowMono = BigInt(stateValue(this.store.inspect()).clock.sampledNow.monotonicMs);
2122
+ const elapsed = Math.ceil(performance.now() - started);
2123
+ const remMono = Number(pollDeadlineMono - nowMono);
2124
+ const remPoll = data.endpoint.maxPollMs - elapsed;
2125
+ const windowMs = Math.min(data.endpoint.timeoutMs, remMono, remPoll);
2126
+ return windowMs <= 0 ? null : windowMs;
2127
+ };
2128
+ const waitWithBackoff = async (retryAttempt) => {
2129
+ if (signal.aborted)
2130
+ throw cancelledFailure('verification');
2131
+ const viewNow = stateValue(this.store.inspect());
2132
+ const nowMono = BigInt(viewNow.clock.sampledNow.monotonicMs);
2133
+ const elapsed = Math.ceil(performance.now() - started);
2134
+ if (nowMono >= pollDeadlineMono || elapsed >= data.endpoint.maxPollMs)
2135
+ return false;
2136
+ const delay = computeBoundedBackoffDelayMs(data.endpoint, job.operationId, retryAttempt, Number(pollDeadlineMono - nowMono), data.endpoint.maxPollMs - elapsed);
2137
+ if (delay <= 0)
2138
+ return false;
2139
+ if (this.onWait) {
2140
+ await this.onWait({
2141
+ operationId: job.operationId,
2142
+ gateId: String(request.gateId),
2143
+ elapsedMs: elapsed,
2144
+ nextPollMs: delay,
2145
+ deadlineMs,
2146
+ });
2147
+ }
2148
+ if (signal.aborted)
2149
+ throw cancelledFailure('verification');
2150
+ await sleep(delay, signal);
2151
+ return true;
2152
+ };
2153
+ // Stage baseTreeBundle (when present) and candidate overlay blobs via HMAC-authenticated PUT .../blobs/:sha256 before initial POST.
2154
+ let stagingFailedInvalid = false;
2155
+ let timedOut = false;
2156
+ let stageRetries = 0;
2157
+ let pollAttempts = 0;
2158
+ const stagedDigests = new Set();
2159
+ const blobsToStage = [];
2160
+ if (data.baseTreeBundle !== undefined) {
2161
+ blobsToStage.push({
2162
+ file: {
2163
+ name: '.base-tree-bundle',
2164
+ byteLength: data.baseTreeBundle.byteLength,
2165
+ digest: data.baseTreeBundle.digest,
2166
+ blobPath: data.baseTreeBundle.blobPath,
2167
+ },
2168
+ digestHex: data.baseTreeBundle.digest.hex,
2169
+ byteLength: data.baseTreeBundle.byteLength,
2170
+ });
2171
+ }
2172
+ for (const entry of data.manifest.spec.entries) {
2173
+ blobsToStage.push({
2174
+ file: data.files.get(entry.name),
2175
+ digestHex: entry.digest.hex,
2176
+ byteLength: entry.byteLength,
2177
+ });
2178
+ }
2179
+ for (const item of blobsToStage) {
2180
+ if (stagedDigests.has(item.digestHex))
2181
+ continue;
2182
+ for (;;) {
2183
+ this.#permit(permit, data.subject, target);
2184
+ const putTimeoutMs = remainingWindowMs();
2185
+ if (putTimeoutMs === null) {
2186
+ timedOut = true;
2187
+ break;
2188
+ }
2189
+ const stageRes = await this.#putSingleBlob(baseUrl, job.operationId, secret, bearerToken, item.file, item.digestHex, item.byteLength, signal, putTimeoutMs);
2190
+ if (isPastPollDeadline()) {
2191
+ timedOut = true;
2192
+ break;
2193
+ }
2194
+ if (stageRes === 'ok') {
2195
+ stagedDigests.add(item.digestHex);
2196
+ break;
2197
+ }
2198
+ if (stageRes === 'invalid') {
2199
+ stagingFailedInvalid = true;
2200
+ break;
2201
+ }
2202
+ stageRetries++;
2203
+ if (!(await waitWithBackoff(stageRetries))) {
2204
+ timedOut = true;
2205
+ break;
2206
+ }
2207
+ }
2208
+ if (timedOut || stagingFailedInvalid)
2209
+ break;
2210
+ }
2211
+ let outcome = stagingFailedInvalid ? { kind: 'invalid' } : { kind: 'network' };
2212
+ let sawPreemption = false;
2213
+ if (!timedOut && !stagingFailedInvalid) {
2214
+ for (;;) {
2215
+ this.#permit(permit, data.subject, target);
2216
+ const postTimeoutMs = remainingWindowMs();
2217
+ if (postTimeoutMs === null) {
2218
+ timedOut = true;
2219
+ outcome = { kind: 'network' };
2220
+ break;
2221
+ }
2222
+ outcome = await this.#roundTrip(baseUrl, secret, bearerToken, requestBody, signal, {
2223
+ storeId: before.storeId,
2224
+ runId: before.runId,
2225
+ lockHash: before.lockHash,
2226
+ operationId: job.operationId,
2227
+ dispatchId: permit.dispatchId,
2228
+ dispatchGeneration: permit.generation,
2229
+ gateId: String(request.gateId),
2230
+ checkId: String(request.checkId),
2231
+ candidateDigest: String(request.candidateDigest),
2232
+ slotId: data.slot.id,
2233
+ }, postTimeoutMs);
2234
+ pollAttempts++;
2235
+ if (isPastPollDeadline()) {
2236
+ if (outcome.kind === 'verdict'
2237
+ && (outcome.verdict.preemptionCount > 0 || isPreemptedBenchmarkVerdict(outcome.verdict))) {
2238
+ sawPreemption = true;
2239
+ }
2240
+ timedOut = true;
2241
+ outcome = { kind: 'network' };
2242
+ break;
2243
+ }
2244
+ if (outcome.kind === 'verdict') {
2245
+ if (outcome.verdict.preemptionCount > 0 || isPreemptedBenchmarkVerdict(outcome.verdict)) {
2246
+ sawPreemption = true;
2247
+ }
2248
+ if (outcome.verdict.status !== 'pending')
2249
+ break;
2250
+ }
2251
+ else if (outcome.kind === 'invalid') {
2252
+ break;
2253
+ }
2254
+ if (!(await waitWithBackoff(pollAttempts))) {
2255
+ timedOut = true;
2256
+ outcome = { kind: 'network' };
2257
+ break;
2258
+ }
2259
+ }
2260
+ }
2261
+ const settledVerdict = !timedOut && outcome.kind === 'verdict' && outcome.verdict.status !== 'pending' ? outcome.verdict : null;
2262
+ const checkFreshWallClock = (verdictToCheck) => {
2263
+ if (!verdictToCheck || verdictToCheck.status !== 'approved')
2264
+ return true;
2265
+ const viewNow = stateValue(this.store.inspect());
2266
+ const wall = BigInt(viewNow.clock.sampledNow.wallMs);
2267
+ const exp = BigInt(verdictToCheck.expiresAtMs);
2268
+ return exp >= wall && exp <= wall + 86400000n;
2269
+ };
2270
+ let wallClockValid = checkFreshWallClock(settledVerdict);
2271
+ let casOutcome = 'ok';
2272
+ let verifierCasRefs = freeze([]);
2273
+ const shouldPull = shouldPullBenchmarkOutputs({
2274
+ verdict: settledVerdict,
2275
+ wallClockValid,
2276
+ targetHardware: data.targetHardware,
2277
+ targetCellId: data.targetCellId,
2278
+ allowSyntheticHardwareProbe: data.allowSyntheticHardwareProbe,
2279
+ metricThresholds: data.metricThresholds,
2280
+ });
2281
+ if (shouldPull && settledVerdict?.outputArtifacts) {
2282
+ const priorBudget = this.resolvePriorVerifierBudget
2283
+ ? await this.resolvePriorVerifierBudget(job.generation, job.slotId)
2284
+ : { files: 0, bytes: 0 };
2285
+ const totalLimits = this.verifierTotalLimits ?? VERIFIER_ARTIFACT_LIMITS;
2286
+ const proposedFiles = settledVerdict.outputArtifacts.length;
2287
+ const proposedBytes = settledVerdict.outputArtifacts.reduce((sum, item) => sum + item.byteLength, 0);
2288
+ if (priorBudget.files + proposedFiles > totalLimits.maxTotalFiles
2289
+ || proposedBytes > totalLimits.maxTotalBytes - priorBudget.bytes) {
2290
+ casOutcome = 'artifact_invalid';
2291
+ }
2292
+ else {
2293
+ const pulled = await pullBenchmarkOutputBlobs({
2294
+ baseUrl,
2295
+ operationId: job.operationId,
2296
+ slotId: data.slot.id,
2297
+ secret,
2298
+ bearerToken,
2299
+ outputArtifacts: settledVerdict.outputArtifacts,
2300
+ artifacts: this.artifacts,
2301
+ signal,
2302
+ resolveTimeoutMs: remainingWindowMs,
2303
+ onBeforeEach: () => this.#permit(permit, data.subject, target),
2304
+ phase: 'verification',
2305
+ });
2306
+ if (isPastPollDeadline()) {
2307
+ timedOut = true;
2308
+ casOutcome = 'gate_timeout';
2309
+ }
2310
+ else if (pulled.ok) {
2311
+ verifierCasRefs = pulled.refs;
2312
+ }
2313
+ else {
2314
+ casOutcome = pulled.casOutcome;
2315
+ if (casOutcome === 'gate_timeout')
2316
+ timedOut = true;
2317
+ }
2318
+ }
2319
+ }
2320
+ // Re-sample wall-clock freshness immediately before final settlement (after any CAS I/O).
2321
+ if (!checkFreshWallClock(settledVerdict)) {
2322
+ wallClockValid = false;
2323
+ }
2324
+ const dispositioned = computeBenchmarkDisposition({
2325
+ verdict: settledVerdict,
2326
+ timedOut,
2327
+ sawPreemption,
2328
+ wallClockValid,
2329
+ targetHardware: data.targetHardware,
2330
+ targetCellId: data.targetCellId,
2331
+ allowSyntheticHardwareProbe: data.allowSyntheticHardwareProbe,
2332
+ metricThresholds: data.metricThresholds,
2333
+ casOutcome,
2334
+ });
2335
+ const view = stateValue(this.store.inspect());
2336
+ const suffix = hash(job.operationId + '\0' + job.producerNonce).hex.slice(0, 40);
2337
+ const retained = outcome.kind === 'verdict' && settledVerdict !== null ? outcome : null;
2338
+ const retainOutputs = casOutcome === 'ok'
2339
+ && shouldPullBenchmarkOutputs({
2340
+ verdict: settledVerdict,
2341
+ wallClockValid,
2342
+ targetHardware: data.targetHardware,
2343
+ targetCellId: data.targetCellId,
2344
+ allowSyntheticHardwareProbe: data.allowSyntheticHardwareProbe,
2345
+ metricThresholds: data.metricThresholds,
2346
+ });
2347
+ const effectiveRefs = retainOutputs ? verifierCasRefs : freeze([]);
2348
+ const totalAttempts = Math.max(1, pollAttempts + stageRetries);
2349
+ const output = await this.artifacts.json('benchmark-output', {
2350
+ version: 1,
2351
+ binding: {
2352
+ planDigest: this.plan.planDigest,
2353
+ operationId: job.operationId,
2354
+ producerNonce: job.producerNonce,
2355
+ generation: job.generation,
2356
+ endpoint: data.endpoint.id,
2357
+ subject: data.subject,
2358
+ requestBytesDigest,
2359
+ },
2360
+ observation: {
2361
+ attempts: totalAttempts,
2362
+ elapsedMs: Math.ceil(performance.now() - started),
2363
+ transport: timedOut ? 'deadline' : 'completed',
2364
+ sawPreemption,
2365
+ wallClockValid,
2366
+ casOutcome,
2367
+ },
2368
+ verdict: settledVerdict,
2369
+ responseBytes: retained ? Buffer.from(retained.responseBytes).toString('base64') : null,
2370
+ responseSignature: retained?.signature ?? null,
2371
+ verifierArtifacts: effectiveRefs,
2372
+ disposition: dispositioned,
2373
+ }, BENCHMARK_OUTPUT_BYTES);
2374
+ const evidenceSpec = {
2375
+ checkId: data.slot.checkId,
2376
+ observedStatus: dispositioned.status,
2377
+ producerId: 'loopwright.benchmark-gate.v1',
2378
+ method: dispositioned.method,
2379
+ level: 'hardware_execution',
2380
+ subject: data.subject,
2381
+ artifacts: [output, ...effectiveRefs],
2382
+ reason: dispositioned.reason,
2383
+ ...(settledVerdict && Object.hasOwn(settledVerdict, 'detail') ? { detail: settledVerdict.detail } : {}),
2384
+ ...(settledVerdict?.metrics !== undefined ? { metrics: settledVerdict.metrics } : {}),
2385
+ ...(settledVerdict?.findings !== undefined ? { findings: settledVerdict.findings } : {}),
2386
+ ...(settledVerdict?.hardwareProvenance !== undefined ? { hardwareProvenance: settledVerdict.hardwareProvenance } : {}),
2387
+ };
2388
+ const evidenceResult = validateDocument({ apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: evidenceSpec }, 'Evidence');
2389
+ if (!evidenceResult.ok)
2390
+ refuse('RECOVERY_REQUIRED', '', 'verification');
2391
+ const receipt = {
2392
+ receiptId: 'receipt.' + suffix,
2393
+ outcome: dispositioned.method === 'benchmark-gate.v1' ? 'succeeded' : 'failed',
2394
+ evidence: {
2395
+ evidenceId: 'receipt-evidence.' + suffix,
2396
+ producerId: 'loopwright.benchmark-gate.v1',
2397
+ method: dispositioned.method,
2398
+ subject: {
2399
+ storeId: view.storeId,
2400
+ runId: view.runId,
2401
+ lockHash: view.lockHash,
2402
+ operationId: job.operationId,
2403
+ requestId: null,
2404
+ intentDigest,
2405
+ dispatchGeneration: permit.generation,
2406
+ dispatchId: permit.dispatchId,
2407
+ },
2408
+ artifact: output,
2409
+ },
2410
+ };
2411
+ const receiptRef = await this.artifacts.json('benchmark-receipt', receipt, 65_536);
2412
+ await this.#marker(job.operationId, job.producerNonce, 'proof', {
2413
+ version: 1,
2414
+ output,
2415
+ receipt: receiptRef,
2416
+ evidence: evidenceResult.value,
2417
+ });
2418
+ let finalDisposition = dispositioned;
2419
+ let finalOutput = output;
2420
+ let finalEvidence = evidenceResult.value;
2421
+ let finalReceipt = receipt;
2422
+ let finalReceiptRef = receiptRef;
2423
+ let finalVerifierRefs = effectiveRefs;
2424
+ this.#permit(permit, data.subject, target);
2425
+ // Re-sample signed expiresAtMs after durable proof persistence, right at first SQLite confirmation.
2426
+ if (wallClockValid && !checkFreshWallClock(settledVerdict)) {
2427
+ const expiredDisposition = computeBenchmarkDisposition({
2428
+ verdict: settledVerdict,
2429
+ timedOut,
2430
+ sawPreemption,
2431
+ wallClockValid: false,
2432
+ targetHardware: data.targetHardware,
2433
+ targetCellId: data.targetCellId,
2434
+ allowSyntheticHardwareProbe: data.allowSyntheticHardwareProbe,
2435
+ metricThresholds: data.metricThresholds,
2436
+ casOutcome,
2437
+ });
2438
+ const expiredOutput = await this.artifacts.json('benchmark-output', {
2439
+ version: 1,
2440
+ binding: {
2441
+ planDigest: this.plan.planDigest,
2442
+ operationId: job.operationId,
2443
+ producerNonce: job.producerNonce,
2444
+ generation: job.generation,
2445
+ endpoint: data.endpoint.id,
2446
+ subject: data.subject,
2447
+ requestBytesDigest,
2448
+ },
2449
+ observation: {
2450
+ attempts: totalAttempts,
2451
+ elapsedMs: Math.ceil(performance.now() - started),
2452
+ transport: timedOut ? 'deadline' : 'completed',
2453
+ sawPreemption,
2454
+ wallClockValid: false,
2455
+ casOutcome,
2456
+ },
2457
+ verdict: settledVerdict,
2458
+ responseBytes: retained ? Buffer.from(retained.responseBytes).toString('base64') : null,
2459
+ responseSignature: retained?.signature ?? null,
2460
+ verifierArtifacts: [],
2461
+ disposition: expiredDisposition,
2462
+ }, BENCHMARK_OUTPUT_BYTES);
2463
+ const expiredEvidenceSpec = {
2464
+ checkId: data.slot.checkId,
2465
+ observedStatus: expiredDisposition.status,
2466
+ producerId: 'loopwright.benchmark-gate.v1',
2467
+ method: expiredDisposition.method,
2468
+ level: 'hardware_execution',
2469
+ subject: data.subject,
2470
+ artifacts: [expiredOutput],
2471
+ reason: expiredDisposition.reason,
2472
+ ...(settledVerdict && Object.hasOwn(settledVerdict, 'detail') ? { detail: settledVerdict.detail } : {}),
2473
+ ...(settledVerdict?.metrics !== undefined ? { metrics: settledVerdict.metrics } : {}),
2474
+ ...(settledVerdict?.findings !== undefined ? { findings: settledVerdict.findings } : {}),
2475
+ ...(settledVerdict?.hardwareProvenance !== undefined ? { hardwareProvenance: settledVerdict.hardwareProvenance } : {}),
2476
+ };
2477
+ const expiredEvidenceRes = validateDocument({ apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: expiredEvidenceSpec }, 'Evidence');
2478
+ if (!expiredEvidenceRes.ok)
2479
+ refuse('RECOVERY_REQUIRED', '', 'verification');
2480
+ const expiredReceipt = {
2481
+ receiptId: 'receipt.' + suffix,
2482
+ outcome: expiredDisposition.method === 'benchmark-gate.v1' ? 'succeeded' : 'failed',
2483
+ evidence: {
2484
+ evidenceId: 'receipt-evidence.' + suffix,
2485
+ producerId: 'loopwright.benchmark-gate.v1',
2486
+ method: expiredDisposition.method,
2487
+ subject: {
2488
+ storeId: view.storeId,
2489
+ runId: view.runId,
2490
+ lockHash: view.lockHash,
2491
+ operationId: job.operationId,
2492
+ requestId: null,
2493
+ intentDigest,
2494
+ dispatchGeneration: permit.generation,
2495
+ dispatchId: permit.dispatchId,
2496
+ },
2497
+ artifact: expiredOutput,
2498
+ },
2499
+ };
2500
+ const expiredReceiptRef = await this.artifacts.json('benchmark-receipt', expiredReceipt, 65_536);
2501
+ const proofPath = join(this.artifacts.directory, 'benchmark-producer-' + hash(job.operationId + '\0' + job.producerNonce).hex + '.proof.json');
2502
+ await this.artifacts.owner.assertCurrent();
2503
+ await overwriteAtomicMarker(proofPath, {
2504
+ version: 1,
2505
+ output: expiredOutput,
2506
+ receipt: expiredReceiptRef,
2507
+ evidence: expiredEvidenceRes.value,
2508
+ }, this.artifacts.vault, 'verification');
2509
+ this.#permit(permit, data.subject, target);
2510
+ const finalExpiredView = stateValue(this.store.inspect());
2511
+ if (finalExpiredView.clockStatus !== 'trusted')
2512
+ refuse('RECOVERY_REQUIRED', '', 'verification');
2513
+ finalDisposition = expiredDisposition;
2514
+ finalOutput = expiredOutput;
2515
+ finalEvidence = expiredEvidenceRes.value;
2516
+ finalReceipt = expiredReceipt;
2517
+ finalReceiptRef = expiredReceiptRef;
2518
+ finalVerifierRefs = freeze([]);
2519
+ }
2520
+ if (signal.aborted)
2521
+ throw cancelledFailure('verification');
2522
+ stateValue(this.store.recordOperationReceipt(this.authority, job.operationId, finalReceipt));
2523
+ const value = freeze({
2524
+ slotId: job.slotId,
2525
+ checkId: data.slot.checkId,
2526
+ generation: job.generation,
2527
+ operationId: job.operationId,
2528
+ producerNonce: job.producerNonce,
2529
+ status: finalDisposition.status,
2530
+ reason: finalDisposition.reason,
2531
+ output: finalOutput,
2532
+ receipt: finalReceiptRef,
2533
+ });
2534
+ observations.set(value, {
2535
+ evidence: freeze(finalEvidence),
2536
+ subject: data.subject,
2537
+ outputBytes: await this.artifacts.read(finalOutput, BENCHMARK_OUTPUT_BYTES),
2538
+ receipt: freeze(finalReceipt),
2539
+ planDigest: this.plan.planDigest,
2540
+ requestDigest: job.requestDigest,
2541
+ artifactsDirectory: this.artifacts.directory,
2542
+ verifierArtifacts: finalVerifierRefs,
2543
+ retryablePreemption: finalDisposition.retryablePreemption === true,
2544
+ header: {
2545
+ handlerDigest: data.slot.handler.digest,
2546
+ handler: 'benchmark-gate.v1',
2547
+ candidate: { ref: { digest: data.candidateDigest, byteLength: data.candidateBytes } },
2548
+ },
2549
+ });
2550
+ return value;
2551
+ }
2552
+ finally {
2553
+ done();
2554
+ }
2555
+ }
2556
+ /** Re-authenticates retained producer proof and verified CAS artifacts without sending any replacement network request. */
2557
+ async restore(job, signal) {
2558
+ if (signal?.aborted)
2559
+ throw cancelledFailure('recovery');
2560
+ const data = preparations.get(job);
2561
+ if (!data || this.plan.verifierSlots.find(slot => slot.id === job.slotId) !== data.slot) {
2562
+ refuse('EVIDENCE_UNAVAILABLE', '', 'recovery');
2563
+ }
2564
+ await this.artifacts.owner.assertCurrent();
2565
+ if (!same(this.currentSubject(), data.subject))
2566
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2567
+ const operation = stateValue(this.store.getOperation(job.operationId));
2568
+ const view = this.#identity();
2569
+ const dispatch = operation.dispatch;
2570
+ const attemptId = 'job.' + hash(job.operationId + '\0' + job.producerNonce).hex.slice(0, 40);
2571
+ if (!dispatch
2572
+ || view.clockStatus !== 'trusted'
2573
+ || operation.intent.effect !== 'read_only'
2574
+ || operation.linkedRequestId !== null
2575
+ || !same(operation.intent.requestDigest, job.requestDigest)
2576
+ || operation.intent.attemptId !== attemptId
2577
+ || operation.intent.nodeId !== this.plan.orderedDAG[0].id
2578
+ || operation.intent.targetIdentity !== 'benchmark:' + job.slotId + ':' + job.generation + ':' + data.subject.candidateDigest.hex) {
2579
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2580
+ }
2581
+ await cleanMarkerTempFilesInDirectory(this.artifacts.directory, this.artifacts.owner);
2582
+ const prefix = join(this.artifacts.directory, 'benchmark-producer-' + hash(job.operationId + '\0' + job.producerNonce).hex);
2583
+ let bindingBytes;
2584
+ try {
2585
+ bindingBytes = await readBoundedFile(prefix + '.binding.json', 1_048_576, true, 0o600);
2586
+ }
2587
+ catch (error) {
2588
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'REGISTRY_UNTRUSTED') {
2589
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2590
+ }
2591
+ throw error;
2592
+ }
2593
+ const binding = record(parsePrivateJson(bindingBytes, 1_048_576), [
2594
+ 'version',
2595
+ 'planDigest',
2596
+ 'operationId',
2597
+ 'producerNonce',
2598
+ 'requestDigest',
2599
+ 'requestBytesDigest',
2600
+ 'intentDigest',
2601
+ 'subject',
2602
+ 'generation',
2603
+ 'endpoint',
2604
+ 'dispatchReceipt',
2605
+ ]);
2606
+ const proofPath = prefix + '.proof.json';
2607
+ let proofExists = false;
2608
+ try {
2609
+ await lstat(proofPath);
2610
+ proofExists = true;
2611
+ }
2612
+ catch (error) {
2613
+ if (error.code !== 'ENOENT') {
2614
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2615
+ }
2616
+ }
2617
+ if (!proofExists) {
2618
+ if (signal?.aborted)
2619
+ throw cancelledFailure('recovery');
2620
+ if (operation.state === 'dispatch_uncertain') {
2621
+ return await this.#settleTimeout(job, data, bindingBytes, view, dispatch, operation.intentDigest, signal);
2622
+ }
2623
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2624
+ }
2625
+ let proofBytes;
2626
+ try {
2627
+ proofBytes = await readBoundedFile(proofPath, 1_048_576, true, 0o600);
2628
+ }
2629
+ catch (error) {
2630
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'REGISTRY_UNTRUSTED') {
2631
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2632
+ }
2633
+ throw error;
2634
+ }
2635
+ const receiptBinding = record(binding.dispatchReceipt, ['generation', 'dispatchId', 'revision', 'clockEpoch']);
2636
+ if (receiptBinding.generation !== dispatch.generation
2637
+ || receiptBinding.dispatchId !== dispatch.dispatchId
2638
+ || receiptBinding.revision !== dispatch.revision
2639
+ || receiptBinding.clockEpoch !== view.clock.basis.clockEpoch) {
2640
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2641
+ }
2642
+ const request = {
2643
+ ...expectedBenchmarkRequest(this.plan, data.slot, data.endpoint, data.subject, data.manifest, data.baseTreeBundle, data.files),
2644
+ storeId: view.storeId,
2645
+ runId: view.runId,
2646
+ lockHash: view.lockHash,
2647
+ operationId: job.operationId,
2648
+ dispatchId: dispatch.dispatchId,
2649
+ dispatchGeneration: dispatch.generation,
2650
+ requestDigest: job.requestDigest.hex,
2651
+ };
2652
+ const requestBytesDigest = hash(Buffer.from(canonical(request))).hex;
2653
+ if (binding.version !== 1
2654
+ || !same(binding.planDigest, this.plan.planDigest)
2655
+ || binding.operationId !== job.operationId
2656
+ || binding.producerNonce !== job.producerNonce
2657
+ || binding.generation !== job.generation
2658
+ || !same(binding.subject, data.subject)
2659
+ || !same(binding.requestDigest, job.requestDigest)
2660
+ || !same(binding.intentDigest, operation.intentDigest)
2661
+ || binding.endpoint !== data.endpoint.id
2662
+ || !same(binding.requestBytesDigest, requestBytesDigest)
2663
+ || !same(binding.dispatchReceipt, {
2664
+ generation: dispatch.generation,
2665
+ dispatchId: dispatch.dispatchId,
2666
+ revision: dispatch.revision,
2667
+ clockEpoch: view.clock.basis.clockEpoch,
2668
+ })) {
2669
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2670
+ }
2671
+ const secret = this.resolveCredential(data.endpoint.signingCredentialRef);
2672
+ const bearerToken = data.endpoint.authCredentialRef !== null ? this.resolveCredential(data.endpoint.authCredentialRef) : null;
2673
+ const priorBudget = this.resolvePriorVerifierBudget
2674
+ ? await this.resolvePriorVerifierBudget(job.generation, job.slotId)
2675
+ : { files: 0, bytes: 0 };
2676
+ const restoreProgress = createRateLimitedProgress(() => {
2677
+ if (signal?.aborted)
2678
+ throw cancelledFailure('recovery');
2679
+ stateValue(this.store.renew(this.authority));
2680
+ }, 1_000);
2681
+ const validated = await validateStoredBenchmarkProof({
2682
+ proofBytes,
2683
+ artifacts: this.artifacts,
2684
+ plan: this.plan,
2685
+ slot: data.slot,
2686
+ endpoint: data.endpoint,
2687
+ targetHardware: data.targetHardware,
2688
+ targetCellId: data.targetCellId,
2689
+ allowSyntheticHardwareProbe: data.allowSyntheticHardwareProbe,
2690
+ metricThresholds: data.metricThresholds,
2691
+ view,
2692
+ operation,
2693
+ dispatch,
2694
+ operationId: job.operationId,
2695
+ producerNonce: job.producerNonce,
2696
+ generation: job.generation,
2697
+ subject: data.subject,
2698
+ request,
2699
+ requestBytesDigest,
2700
+ secret,
2701
+ bearerToken,
2702
+ priorBudget,
2703
+ signal,
2704
+ onProgress: restoreProgress,
2705
+ allowInvalidLocalCasSettlement: operation.state !== 'confirmed',
2706
+ ...(this.verifierTotalLimits !== undefined ? { totalLimits: this.verifierTotalLimits } : {}),
2707
+ });
2708
+ if (signal?.aborted)
2709
+ throw cancelledFailure('recovery');
2710
+ await this.artifacts.owner.assertCurrent();
2711
+ if (!same(this.currentSubject(), data.subject))
2712
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2713
+ if (signal?.aborted)
2714
+ throw cancelledFailure('recovery');
2715
+ stateValue(this.store.renew(this.authority));
2716
+ if (operation.state === 'confirmed') {
2717
+ if (!same(operation.reconciliation ?? operation.initialReceipt, validated.receipt)) {
2718
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2719
+ }
2720
+ }
2721
+ else {
2722
+ // Operation still needs FIRST SQLite confirmation: settle invalid local CAS or expired approval
2723
+ // cleanly instead of stranding dispatch_uncertain or confirming an expired approval.
2724
+ const postValidateView = stateValue(this.store.inspect());
2725
+ const currentWallMs = BigInt(postValidateView.clock.sampledNow.wallMs);
2726
+ const currentlyFresh = validated.verdict === null
2727
+ || validated.verdict.status !== 'approved'
2728
+ || (BigInt(validated.verdict.expiresAtMs) >= currentWallMs
2729
+ && BigInt(validated.verdict.expiresAtMs) <= currentWallMs + 86400000n);
2730
+ if (validated.localCasInvalid) {
2731
+ return await this.#settleSupersededUnconfirmedProof(job, data, proofPath, postValidateView, dispatch, operation.intentDigest, requestBytesDigest, validated, {
2732
+ casOutcome: 'artifact_invalid',
2733
+ wallClockValid: validated.observation.wallClockValid && currentlyFresh,
2734
+ }, signal);
2735
+ }
2736
+ if (!currentlyFresh && validated.observation.wallClockValid) {
2737
+ return await this.#settleSupersededUnconfirmedProof(job, data, proofPath, postValidateView, dispatch, operation.intentDigest, requestBytesDigest, validated, {
2738
+ casOutcome: validated.observation.casOutcome,
2739
+ wallClockValid: false,
2740
+ }, signal);
2741
+ }
2742
+ if (signal?.aborted)
2743
+ throw cancelledFailure('recovery');
2744
+ stateValue(this.store.reconcileOperation(this.authority, job.operationId, validated.receipt));
2745
+ }
2746
+ const value = freeze({
2747
+ slotId: job.slotId,
2748
+ checkId: data.slot.checkId,
2749
+ generation: job.generation,
2750
+ operationId: job.operationId,
2751
+ producerNonce: job.producerNonce,
2752
+ status: validated.disposition.status,
2753
+ reason: validated.disposition.reason,
2754
+ output: validated.output,
2755
+ receipt: validated.receiptRef,
2756
+ });
2757
+ observations.set(value, {
2758
+ evidence: freeze(validated.evidence),
2759
+ subject: data.subject,
2760
+ outputBytes: validated.outputBytes,
2761
+ receipt: freeze(validated.receipt),
2762
+ planDigest: this.plan.planDigest,
2763
+ requestDigest: job.requestDigest,
2764
+ artifactsDirectory: this.artifacts.directory,
2765
+ verifierArtifacts: validated.verifierCasRefs,
2766
+ retryablePreemption: validated.disposition.retryablePreemption === true,
2767
+ header: {
2768
+ handlerDigest: data.slot.handler.digest,
2769
+ handler: 'benchmark-gate.v1',
2770
+ candidate: { ref: { digest: data.candidateDigest, byteLength: data.candidateBytes } },
2771
+ },
2772
+ });
2773
+ return value;
2774
+ }
2775
+ async #settleSupersededUnconfirmedProof(job, data, proofPath, view, dispatch, intentDigest, requestBytesDigest, validated, override, signal) {
2776
+ const supersededDisposition = computeBenchmarkDisposition({
2777
+ verdict: validated.verdict,
2778
+ timedOut: validated.observation.transport === 'deadline',
2779
+ sawPreemption: validated.observation.sawPreemption,
2780
+ wallClockValid: override.wallClockValid,
2781
+ targetHardware: data.targetHardware,
2782
+ targetCellId: data.targetCellId,
2783
+ allowSyntheticHardwareProbe: data.allowSyntheticHardwareProbe,
2784
+ metricThresholds: data.metricThresholds,
2785
+ casOutcome: override.casOutcome,
2786
+ });
2787
+ const suffix = hash(job.operationId + '\0' + job.producerNonce).hex.slice(0, 40);
2788
+ const supersededOutput = await this.artifacts.json('benchmark-output', {
2789
+ version: 1,
2790
+ binding: {
2791
+ planDigest: this.plan.planDigest,
2792
+ operationId: job.operationId,
2793
+ producerNonce: job.producerNonce,
2794
+ generation: job.generation,
2795
+ endpoint: data.endpoint.id,
2796
+ subject: data.subject,
2797
+ requestBytesDigest,
2798
+ },
2799
+ observation: {
2800
+ attempts: validated.observation.attempts,
2801
+ elapsedMs: validated.observation.elapsedMs,
2802
+ transport: validated.observation.transport,
2803
+ sawPreemption: validated.observation.sawPreemption,
2804
+ wallClockValid: override.wallClockValid,
2805
+ casOutcome: override.casOutcome,
2806
+ },
2807
+ verdict: validated.verdict,
2808
+ responseBytes: validated.responseBytesBase64,
2809
+ responseSignature: validated.responseSignature,
2810
+ verifierArtifacts: [],
2811
+ disposition: supersededDisposition,
2812
+ }, BENCHMARK_OUTPUT_BYTES);
2813
+ const evidenceSpec = {
2814
+ checkId: data.slot.checkId,
2815
+ observedStatus: supersededDisposition.status,
2816
+ producerId: 'loopwright.benchmark-gate.v1',
2817
+ method: supersededDisposition.method,
2818
+ level: 'hardware_execution',
2819
+ subject: data.subject,
2820
+ artifacts: [supersededOutput],
2821
+ reason: supersededDisposition.reason,
2822
+ ...(validated.verdict && Object.hasOwn(validated.verdict, 'detail') ? { detail: validated.verdict.detail } : {}),
2823
+ ...(validated.verdict?.metrics !== undefined ? { metrics: validated.verdict.metrics } : {}),
2824
+ ...(validated.verdict?.findings !== undefined ? { findings: validated.verdict.findings } : {}),
2825
+ ...(validated.verdict?.hardwareProvenance !== undefined ? { hardwareProvenance: validated.verdict.hardwareProvenance } : {}),
2826
+ };
2827
+ const evidenceResult = validateDocument({ apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: evidenceSpec }, 'Evidence');
2828
+ if (!evidenceResult.ok)
2829
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2830
+ const supersededReceipt = {
2831
+ receiptId: 'receipt.' + suffix,
2832
+ outcome: supersededDisposition.method === 'benchmark-gate.v1' ? 'succeeded' : 'failed',
2833
+ evidence: {
2834
+ evidenceId: 'receipt-evidence.' + suffix,
2835
+ producerId: 'loopwright.benchmark-gate.v1',
2836
+ method: supersededDisposition.method,
2837
+ subject: {
2838
+ storeId: view.storeId,
2839
+ runId: view.runId,
2840
+ lockHash: view.lockHash,
2841
+ operationId: job.operationId,
2842
+ requestId: null,
2843
+ intentDigest,
2844
+ dispatchGeneration: dispatch.generation,
2845
+ dispatchId: dispatch.dispatchId,
2846
+ },
2847
+ artifact: supersededOutput,
2848
+ },
2849
+ };
2850
+ const supersededReceiptRef = await this.artifacts.json('benchmark-receipt', supersededReceipt, 65_536);
2851
+ await this.artifacts.owner.assertCurrent();
2852
+ await overwriteAtomicMarker(proofPath, {
2853
+ version: 1,
2854
+ output: supersededOutput,
2855
+ receipt: supersededReceiptRef,
2856
+ evidence: evidenceResult.value,
2857
+ }, this.artifacts.vault, 'recovery');
2858
+ if (signal?.aborted)
2859
+ throw cancelledFailure('recovery');
2860
+ stateValue(this.store.renew(this.authority));
2861
+ const finalSupersededView = stateValue(this.store.inspect());
2862
+ if (finalSupersededView.clockStatus !== 'trusted')
2863
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2864
+ if (signal?.aborted)
2865
+ throw cancelledFailure('recovery');
2866
+ stateValue(this.store.reconcileOperation(this.authority, job.operationId, supersededReceipt));
2867
+ const value = freeze({
2868
+ slotId: job.slotId,
2869
+ checkId: data.slot.checkId,
2870
+ generation: job.generation,
2871
+ operationId: job.operationId,
2872
+ producerNonce: job.producerNonce,
2873
+ status: supersededDisposition.status,
2874
+ reason: supersededDisposition.reason,
2875
+ output: supersededOutput,
2876
+ receipt: supersededReceiptRef,
2877
+ });
2878
+ observations.set(value, {
2879
+ evidence: freeze(evidenceResult.value),
2880
+ subject: data.subject,
2881
+ outputBytes: await this.artifacts.read(supersededOutput, BENCHMARK_OUTPUT_BYTES),
2882
+ receipt: freeze(supersededReceipt),
2883
+ planDigest: this.plan.planDigest,
2884
+ requestDigest: job.requestDigest,
2885
+ artifactsDirectory: this.artifacts.directory,
2886
+ verifierArtifacts: freeze([]),
2887
+ retryablePreemption: supersededDisposition.retryablePreemption === true,
2888
+ header: {
2889
+ handlerDigest: data.slot.handler.digest,
2890
+ handler: 'benchmark-gate.v1',
2891
+ candidate: { ref: { digest: data.candidateDigest, byteLength: data.candidateBytes } },
2892
+ },
2893
+ });
2894
+ return value;
2895
+ }
2896
+ /** Interrupted read-only benchmark operations without a proof settle fail-closed as blocked GATE_TIMEOUT without replacement POSTs. */
2897
+ async #settleTimeout(job, data, bindingBytes, view, dispatch, intentDigest, signal) {
2898
+ if (signal?.aborted)
2899
+ throw cancelledFailure('recovery');
2900
+ await this.artifacts.owner.assertCurrent();
2901
+ if (!same(this.currentSubject(), data.subject))
2902
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2903
+ stateValue(this.store.renew(this.authority));
2904
+ const binding = record(parsePrivateJson(bindingBytes, 1_048_576), [
2905
+ 'version',
2906
+ 'planDigest',
2907
+ 'operationId',
2908
+ 'producerNonce',
2909
+ 'requestDigest',
2910
+ 'requestBytesDigest',
2911
+ 'intentDigest',
2912
+ 'subject',
2913
+ 'generation',
2914
+ 'endpoint',
2915
+ 'dispatchReceipt',
2916
+ ]);
2917
+ const request = {
2918
+ ...expectedBenchmarkRequest(this.plan, data.slot, data.endpoint, data.subject, data.manifest, data.baseTreeBundle, data.files),
2919
+ storeId: view.storeId,
2920
+ runId: view.runId,
2921
+ lockHash: view.lockHash,
2922
+ operationId: job.operationId,
2923
+ dispatchId: dispatch.dispatchId,
2924
+ dispatchGeneration: dispatch.generation,
2925
+ requestDigest: job.requestDigest.hex,
2926
+ };
2927
+ const requestBytesDigest = hash(Buffer.from(canonical(request))).hex;
2928
+ const receiptBinding = record(binding.dispatchReceipt, ['generation', 'dispatchId', 'revision', 'clockEpoch']);
2929
+ if (receiptBinding.generation !== dispatch.generation
2930
+ || receiptBinding.dispatchId !== dispatch.dispatchId
2931
+ || receiptBinding.revision !== dispatch.revision
2932
+ || receiptBinding.clockEpoch !== view.clock.basis.clockEpoch
2933
+ || binding.version !== 1
2934
+ || !same(binding.planDigest, this.plan.planDigest)
2935
+ || binding.operationId !== job.operationId
2936
+ || binding.producerNonce !== job.producerNonce
2937
+ || binding.generation !== job.generation
2938
+ || !same(binding.subject, data.subject)
2939
+ || !same(binding.requestDigest, job.requestDigest)
2940
+ || !same(binding.intentDigest, intentDigest)
2941
+ || binding.endpoint !== data.endpoint.id
2942
+ || !same(binding.requestBytesDigest, requestBytesDigest)
2943
+ || !same(binding.dispatchReceipt, {
2944
+ generation: dispatch.generation,
2945
+ dispatchId: dispatch.dispatchId,
2946
+ revision: dispatch.revision,
2947
+ clockEpoch: view.clock.basis.clockEpoch,
2948
+ })) {
2949
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2950
+ }
2951
+ const dispositioned = freeze({
2952
+ status: 'blocked',
2953
+ reason: 'GATE_TIMEOUT',
2954
+ method: 'benchmark_transport',
2955
+ });
2956
+ const suffix = hash(job.operationId + '\0' + job.producerNonce).hex.slice(0, 40);
2957
+ const output = await this.artifacts.json('benchmark-output', {
2958
+ version: 1,
2959
+ binding: {
2960
+ planDigest: this.plan.planDigest,
2961
+ operationId: job.operationId,
2962
+ producerNonce: job.producerNonce,
2963
+ generation: job.generation,
2964
+ endpoint: data.endpoint.id,
2965
+ subject: data.subject,
2966
+ requestBytesDigest,
2967
+ },
2968
+ observation: {
2969
+ attempts: 1,
2970
+ elapsedMs: 0,
2971
+ transport: 'deadline',
2972
+ sawPreemption: false,
2973
+ wallClockValid: true,
2974
+ casOutcome: 'gate_timeout',
2975
+ },
2976
+ verdict: null,
2977
+ responseBytes: null,
2978
+ responseSignature: null,
2979
+ verifierArtifacts: [],
2980
+ disposition: dispositioned,
2981
+ }, 65_536);
2982
+ const evidenceResult = validateDocument({
2983
+ apiVersion: 'loopwright.dev/v1alpha1',
2984
+ kind: 'Evidence',
2985
+ metadata: { id: 'evidence.' + suffix },
2986
+ spec: {
2987
+ checkId: data.slot.checkId,
2988
+ observedStatus: 'blocked',
2989
+ producerId: 'loopwright.benchmark-gate.v1',
2990
+ method: 'benchmark_transport',
2991
+ level: 'hardware_execution',
2992
+ subject: data.subject,
2993
+ artifacts: [output],
2994
+ reason: 'GATE_TIMEOUT',
2995
+ },
2996
+ }, 'Evidence');
2997
+ if (!evidenceResult.ok)
2998
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
2999
+ const receipt = {
3000
+ receiptId: 'receipt.' + suffix,
3001
+ outcome: 'failed',
3002
+ evidence: {
3003
+ evidenceId: 'receipt-evidence.' + suffix,
3004
+ producerId: 'loopwright.benchmark-gate.v1',
3005
+ method: 'benchmark_transport',
3006
+ subject: {
3007
+ storeId: view.storeId,
3008
+ runId: view.runId,
3009
+ lockHash: view.lockHash,
3010
+ operationId: job.operationId,
3011
+ requestId: null,
3012
+ intentDigest: binding.intentDigest,
3013
+ dispatchGeneration: dispatch.generation,
3014
+ dispatchId: dispatch.dispatchId,
3015
+ },
3016
+ artifact: output,
3017
+ },
3018
+ };
3019
+ const receiptRef = await this.artifacts.json('benchmark-receipt', receipt, 65_536);
3020
+ if (signal?.aborted)
3021
+ throw cancelledFailure('recovery');
3022
+ await this.#marker(job.operationId, job.producerNonce, 'proof', {
3023
+ version: 1,
3024
+ output,
3025
+ receipt: receiptRef,
3026
+ evidence: evidenceResult.value,
3027
+ });
3028
+ if (signal?.aborted)
3029
+ throw cancelledFailure('recovery');
3030
+ stateValue(this.store.renew(this.authority));
3031
+ const finalTimeoutView = stateValue(this.store.inspect());
3032
+ if (finalTimeoutView.clockStatus !== 'trusted')
3033
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
3034
+ if (signal?.aborted)
3035
+ throw cancelledFailure('recovery');
3036
+ stateValue(this.store.reconcileOperation(this.authority, job.operationId, receipt));
3037
+ const value = freeze({
3038
+ slotId: job.slotId,
3039
+ checkId: data.slot.checkId,
3040
+ generation: job.generation,
3041
+ operationId: job.operationId,
3042
+ producerNonce: job.producerNonce,
3043
+ status: 'blocked',
3044
+ reason: 'GATE_TIMEOUT',
3045
+ output,
3046
+ receipt: receiptRef,
3047
+ });
3048
+ observations.set(value, {
3049
+ evidence: freeze(evidenceResult.value),
3050
+ subject: data.subject,
3051
+ outputBytes: await this.artifacts.read(output, 65_536),
3052
+ receipt: freeze(receipt),
3053
+ planDigest: this.plan.planDigest,
3054
+ requestDigest: job.requestDigest,
3055
+ artifactsDirectory: this.artifacts.directory,
3056
+ verifierArtifacts: freeze([]),
3057
+ retryablePreemption: false,
3058
+ header: {
3059
+ handlerDigest: data.slot.handler.digest,
3060
+ handler: 'benchmark-gate.v1',
3061
+ candidate: { ref: { digest: data.candidateDigest, byteLength: data.candidateBytes } },
3062
+ },
3063
+ });
3064
+ return value;
3065
+ }
3066
+ }
3067
+ /** Pure preparation: no intent, permit, timer, credential or network operation. */
3068
+ export function prepareBenchmarkGate(plan, lock, slotId, candidate, generation, producerNonce, gateEndpoints, baseTreeBundle) {
3069
+ if (!same(plan.task, lock.spec.contract) || !/^[a-f0-9]{32}$/.test(producerNonce)) {
3070
+ refuse('ARTIFACT_INVALID', '', 'verification');
3071
+ }
3072
+ integer(generation, 0, plan.capacity.V - 1);
3073
+ const slot = plan.verifierSlots.find(item => item.id === slotId);
3074
+ if (!slot || slot.handler.implementation !== 'benchmark-gate.v1' || slot.handler.kind !== 'check') {
3075
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
3076
+ }
3077
+ const overlayOpts = lock.spec.contract.spec.budgets.overlay
3078
+ ? { overlay: lock.spec.contract.spec.budgets.overlay }
3079
+ : undefined;
3080
+ const subject = bindSubject(lock, candidate.manifest, overlayOpts);
3081
+ if (!subject.ok)
3082
+ refuse('ARTIFACT_INVALID', '', 'verification');
3083
+ const validatedFiles = validateCandidateFilesForStaging(candidate.manifest, candidate.files);
3084
+ let validatedBundle;
3085
+ if (baseTreeBundle !== undefined) {
3086
+ if (candidate.manifest.spec.baseTree === undefined
3087
+ || typeof baseTreeBundle.blobPath !== 'string'
3088
+ || !isAbsolute(baseTreeBundle.blobPath)
3089
+ || baseTreeBundle.blobPath.length > 4096
3090
+ || /[\0\r\n]/.test(baseTreeBundle.blobPath)) {
3091
+ refuse('ARTIFACT_INVALID', '', 'verification');
3092
+ }
3093
+ const checkedDigest = digestValue(baseTreeBundle.digest);
3094
+ const checkedBytes = integer(baseTreeBundle.byteLength, 12, VERIFIER_ARTIFACT_LIMITS.maxFileBytes);
3095
+ validatedBundle = freeze({
3096
+ digest: checkedDigest,
3097
+ byteLength: checkedBytes,
3098
+ blobPath: baseTreeBundle.blobPath,
3099
+ });
3100
+ }
3101
+ const meta = resolveBenchmarkSlotMetadata(plan, slot);
3102
+ const endpoint = gateEndpoints.find(item => item.id === meta.endpointRef);
3103
+ if (!endpoint)
3104
+ refuse('CONFIG_REFERENCE', '/registry/spec/gateEndpoints', 'verification');
3105
+ const candidateArtifacts = buildCandidateArtifactsDescriptor(candidate.manifest, validatedBundle, validatedFiles);
3106
+ const requestDigest = hash('loopwright.dev/controller/benchmark-request/v1\0'
3107
+ + canonical({
3108
+ planDigest: plan.planDigest,
3109
+ slotId,
3110
+ generation,
3111
+ gateId: meta.gateId,
3112
+ checkId: slot.checkId,
3113
+ targetCellId: meta.targetCellId,
3114
+ targetHardware: meta.targetHardware,
3115
+ heldOutWorkloadId: meta.heldOutWorkloadId,
3116
+ metricThresholds: meta.metricThresholds,
3117
+ maxPreemptions: meta.maxPreemptions,
3118
+ candidateArtifacts,
3119
+ subject: subject.value,
3120
+ producerNonce,
3121
+ }));
3122
+ const value = freeze({
3123
+ version: 1,
3124
+ slotId,
3125
+ generation,
3126
+ operationId: verifierOperationId(lock.spec.runId, slotId, generation),
3127
+ producerNonce,
3128
+ requestDigest,
3129
+ });
3130
+ preparations.set(value, {
3131
+ slot,
3132
+ endpoint,
3133
+ subject: subject.value,
3134
+ manifest: candidate.manifest,
3135
+ files: validatedFiles,
3136
+ ...(validatedBundle !== undefined ? { baseTreeBundle: validatedBundle } : {}),
3137
+ targetCellId: meta.targetCellId,
3138
+ targetHardware: meta.targetHardware,
3139
+ allowSyntheticHardwareProbe: meta.allowSyntheticHardwareProbe,
3140
+ heldOutWorkloadId: meta.heldOutWorkloadId,
3141
+ metricThresholds: meta.metricThresholds,
3142
+ maxPreemptions: meta.maxPreemptions,
3143
+ candidateDigest: hash(canonical(candidate.manifest)),
3144
+ candidateBytes: Buffer.byteLength(canonical(candidate.manifest)),
3145
+ });
3146
+ return value;
3147
+ }