@gpustack/loopwright 0.0.0-stage → 0.0.3

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 +2094 -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 +1648 -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 +2642 -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 +7335 -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 +3025 -0
  476. package/package-lock.json +3025 -0
  477. package/package.json +52 -4
@@ -0,0 +1,1796 @@
1
+ import { createServer } from 'node:http';
2
+ import { execFile, spawn } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { constants } from 'node:fs';
5
+ import { chmod, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { promisify } from 'node:util';
9
+ import { signPayload, verifySignedPayload } from '@loopwright/controller';
10
+ import { OVERLAY_LIMITS, identifyManifest } from '@loopwright/core';
11
+ import { verifyFrozenCorpus } from './corpus.js';
12
+ import { PythonBridge } from './python-bridge.js';
13
+ import { RunnerTaskpackError } from './types.js';
14
+ const execFileAsync = promisify(execFile);
15
+ const CAS_CHUNK_BYTES = 1_048_576;
16
+ const MAX_PROPOSAL_BYTES = 1_048_576;
17
+ const MAX_WORKSPACE_NDJSON_BYTES = 67_108_864;
18
+ const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
19
+ const GIT_OID_RE = /^[0-9a-f]{40,64}$/i;
20
+ const CLEAN_GIT_ENV = {
21
+ HOME: '/nonexistent',
22
+ GIT_CONFIG_GLOBAL: '/dev/null',
23
+ GIT_CONFIG_NOSYSTEM: '1',
24
+ GIT_TERMINAL_PROMPT: '0',
25
+ PATH: '/usr/bin:/bin',
26
+ };
27
+ function isProtectedGitHubPath(relPath, allowWorkflowWrites) {
28
+ const segments = relPath.split('/');
29
+ if (segments[0]?.toLowerCase() !== '.github')
30
+ return false;
31
+ if (!allowWorkflowWrites)
32
+ return true;
33
+ // Even when allowWorkflowWrites is true, non-workflow .github/** paths remain strictly protected.
34
+ return segments.length < 3 || segments[1]?.toLowerCase() !== 'workflows';
35
+ }
36
+ function isStructurallySafeCandidatePath(relPath) {
37
+ if (typeof relPath !== 'string' || relPath.length === 0)
38
+ return false;
39
+ if (relPath.includes('\0') || relPath.includes('\\') || relPath.startsWith('/') || relPath.endsWith('/'))
40
+ return false;
41
+ const segments = relPath.split('/');
42
+ if (segments.some(seg => seg === '' || seg === '.' || seg === '..'))
43
+ return false;
44
+ if (segments.some(seg => seg.toLowerCase() === '.git'))
45
+ return false;
46
+ return true;
47
+ }
48
+ function isSafeCandidatePath(relPath, policy) {
49
+ if (!isStructurallySafeCandidatePath(relPath))
50
+ return false;
51
+ const policyProfile = policy.policyProfile ?? 'github';
52
+ if (policyProfile === 'github' && isProtectedGitHubPath(relPath, policy.allowWorkflowWrites === true)) {
53
+ return false;
54
+ }
55
+ return true;
56
+ }
57
+ function hasSymlinkAncestor(relPath, symlinks) {
58
+ if (symlinks.size === 0)
59
+ return false;
60
+ const segments = relPath.split('/');
61
+ let prefix = '';
62
+ for (let i = 0; i < segments.length - 1; i++) {
63
+ prefix = i === 0 ? segments[0] : `${prefix}/${segments[i]}`;
64
+ if (symlinks.has(prefix))
65
+ return true;
66
+ }
67
+ return false;
68
+ }
69
+ async function readGitBlobDigests(repository, oids) {
70
+ const results = new Map();
71
+ if (oids.length === 0)
72
+ return results;
73
+ return await new Promise((resolve) => {
74
+ let settled = false;
75
+ const finish = (value) => {
76
+ if (settled)
77
+ return;
78
+ settled = true;
79
+ clearTimeout(timer);
80
+ resolve(value);
81
+ };
82
+ const child = spawn('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'cat-file', '--batch'], { cwd: repository, env: CLEAN_GIT_ENV, stdio: ['pipe', 'pipe', 'pipe'] });
83
+ const timer = setTimeout(() => {
84
+ try {
85
+ child.kill('SIGKILL');
86
+ }
87
+ catch { /* ignore */ }
88
+ finish(null);
89
+ }, 30_000);
90
+ timer.unref();
91
+ let state = 'header';
92
+ let headerChunks = [];
93
+ let headerLen = 0;
94
+ let oidIndex = 0;
95
+ let currentOid = '';
96
+ let currentSize = 0;
97
+ let remaining = 0;
98
+ let currentHash = null;
99
+ let failed = false;
100
+ const abort = () => {
101
+ failed = true;
102
+ try {
103
+ child.kill('SIGKILL');
104
+ }
105
+ catch { /* ignore */ }
106
+ finish(null);
107
+ };
108
+ const processChunk = (chunk) => {
109
+ let offset = 0;
110
+ while (offset < chunk.length && !failed) {
111
+ if (state === 'header') {
112
+ const nl = chunk.indexOf(0x0a, offset);
113
+ if (nl === -1) {
114
+ const slice = chunk.subarray(offset);
115
+ headerLen += slice.length;
116
+ if (headerLen > 256) {
117
+ abort();
118
+ return;
119
+ }
120
+ headerChunks.push(Buffer.from(slice));
121
+ return;
122
+ }
123
+ const slice = chunk.subarray(offset, nl);
124
+ headerLen += slice.length;
125
+ if (headerLen > 256) {
126
+ abort();
127
+ return;
128
+ }
129
+ headerChunks.push(Buffer.from(slice));
130
+ const headerLine = Buffer.concat(headerChunks, headerLen).toString('ascii');
131
+ headerChunks = [];
132
+ headerLen = 0;
133
+ offset = nl + 1;
134
+ const expectedOid = oids[oidIndex];
135
+ if (expectedOid === undefined) {
136
+ abort();
137
+ return;
138
+ }
139
+ const parts = headerLine.split(' ');
140
+ if (parts.length !== 3 || parts[0] !== expectedOid || parts[1] !== 'blob') {
141
+ abort();
142
+ return;
143
+ }
144
+ const size = Number(parts[2]);
145
+ if (!Number.isSafeInteger(size) || size < 0 || String(size) !== parts[2]) {
146
+ abort();
147
+ return;
148
+ }
149
+ currentOid = expectedOid;
150
+ currentSize = size;
151
+ remaining = size;
152
+ currentHash = createHash('sha256');
153
+ oidIndex += 1;
154
+ if (remaining === 0) {
155
+ results.set(currentOid, { byteLength: 0, sha256: currentHash.digest('hex') });
156
+ currentHash = null;
157
+ state = 'trailer';
158
+ }
159
+ else {
160
+ state = 'body';
161
+ }
162
+ }
163
+ else if (state === 'body') {
164
+ const take = Math.min(remaining, chunk.length - offset);
165
+ currentHash.update(chunk.subarray(offset, offset + take));
166
+ offset += take;
167
+ remaining -= take;
168
+ if (remaining === 0) {
169
+ results.set(currentOid, { byteLength: currentSize, sha256: currentHash.digest('hex') });
170
+ currentHash = null;
171
+ state = 'trailer';
172
+ }
173
+ }
174
+ else {
175
+ if (chunk[offset] !== 0x0a) {
176
+ abort();
177
+ return;
178
+ }
179
+ offset += 1;
180
+ state = 'header';
181
+ }
182
+ }
183
+ };
184
+ child.stdout.on('data', (chunk) => processChunk(chunk));
185
+ child.stderr.resume();
186
+ child.on('error', () => abort());
187
+ child.stdin.on('error', () => { });
188
+ child.on('close', (code) => {
189
+ if (failed || code !== 0 || state !== 'header' || headerLen !== 0 || oidIndex !== oids.length || results.size !== oids.length) {
190
+ finish(null);
191
+ return;
192
+ }
193
+ finish(results);
194
+ });
195
+ child.stdin.end(oids.join('\n') + '\n', 'ascii');
196
+ });
197
+ }
198
+ async function readBaselineGitTree(repository, revision) {
199
+ if (typeof repository !== 'string' || repository.length === 0)
200
+ return null;
201
+ if (typeof revision !== 'string' || !GIT_OID_RE.test(revision))
202
+ return null;
203
+ let treeOutput;
204
+ try {
205
+ const out = await execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'ls-tree', '-r', '-z', '--full-tree', revision], { cwd: repository, env: CLEAN_GIT_ENV, timeout: 15_000, encoding: 'utf8', maxBuffer: 33_554_432 });
206
+ treeOutput = out.stdout;
207
+ }
208
+ catch {
209
+ return null;
210
+ }
211
+ const pendingRegular = [];
212
+ const uniqueOids = [];
213
+ const seenOids = new Set();
214
+ const symlinks = new Set();
215
+ for (const record of treeOutput.split('\0')) {
216
+ if (record.length === 0)
217
+ continue;
218
+ const tabIndex = record.indexOf('\t');
219
+ if (tabIndex === -1)
220
+ return null;
221
+ const meta = record.slice(0, tabIndex).split(/\s+/);
222
+ const entryPath = record.slice(tabIndex + 1);
223
+ if (meta.length !== 3 || entryPath.length === 0)
224
+ return null;
225
+ const mode = meta[0];
226
+ const kind = meta[1];
227
+ const oid = meta[2];
228
+ if (mode === '120000' && kind === 'blob') {
229
+ symlinks.add(entryPath);
230
+ continue;
231
+ }
232
+ if ((mode === '100644' || mode === '100755') && kind === 'blob') {
233
+ if (!GIT_OID_RE.test(oid))
234
+ return null;
235
+ pendingRegular.push({ path: entryPath, mode, oid });
236
+ if (!seenOids.has(oid)) {
237
+ seenOids.add(oid);
238
+ uniqueOids.push(oid);
239
+ }
240
+ }
241
+ }
242
+ const blobStats = await readGitBlobDigests(repository, uniqueOids);
243
+ if (blobStats === null)
244
+ return null;
245
+ const regularFiles = new Map();
246
+ for (const item of pendingRegular) {
247
+ const stat = blobStats.get(item.oid);
248
+ if (stat === undefined)
249
+ return null;
250
+ regularFiles.set(item.path, { mode: item.mode, byteLength: stat.byteLength, sha256: stat.sha256 });
251
+ }
252
+ return { regularFiles, symlinks };
253
+ }
254
+ async function readBaselineRegularFileSize(repository, revision, relPath) {
255
+ if (typeof repository !== 'string' || repository.length === 0)
256
+ return null;
257
+ if (typeof revision !== 'string' || !GIT_OID_RE.test(revision))
258
+ return null;
259
+ if (!isStructurallySafeCandidatePath(relPath))
260
+ return null;
261
+ const segments = relPath.split('/');
262
+ let prefix = '';
263
+ for (let i = 0; i < segments.length - 1; i += 1) {
264
+ prefix = i === 0 ? segments[0] : `${prefix}/${segments[i]}`;
265
+ let parentOut;
266
+ try {
267
+ const res = await execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'ls-tree', '-d', '-z', revision, '--', prefix], { cwd: repository, env: CLEAN_GIT_ENV, timeout: 15_000, encoding: 'utf8', maxBuffer: 65_536 });
268
+ parentOut = res.stdout;
269
+ }
270
+ catch {
271
+ return null;
272
+ }
273
+ const records = parentOut.split('\0').filter(r => r.length > 0);
274
+ if (records.length !== 1)
275
+ return null;
276
+ const tabIndex = records[0].indexOf('\t');
277
+ if (tabIndex === -1)
278
+ return null;
279
+ const meta = records[0].slice(0, tabIndex).trim().split(/\s+/);
280
+ const entryPath = records[0].slice(tabIndex + 1);
281
+ if (meta.length !== 3
282
+ || meta[0] !== '040000'
283
+ || meta[1] !== 'tree'
284
+ || !GIT_OID_RE.test(meta[2])
285
+ || entryPath !== prefix) {
286
+ return null;
287
+ }
288
+ }
289
+ let fileOut;
290
+ try {
291
+ const res = await execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'ls-tree', '-z', '-l', revision, '--', relPath], { cwd: repository, env: CLEAN_GIT_ENV, timeout: 15_000, encoding: 'utf8', maxBuffer: 65_536 });
292
+ fileOut = res.stdout;
293
+ }
294
+ catch {
295
+ return null;
296
+ }
297
+ const records = fileOut.split('\0').filter(r => r.length > 0);
298
+ if (records.length !== 1)
299
+ return null;
300
+ const tabIndex = records[0].indexOf('\t');
301
+ if (tabIndex === -1)
302
+ return null;
303
+ const meta = records[0].slice(0, tabIndex).trim().split(/\s+/);
304
+ const entryPath = records[0].slice(tabIndex + 1);
305
+ if (meta.length !== 4 || entryPath !== relPath)
306
+ return null;
307
+ const [mode, kind, oid, sizeStr] = meta;
308
+ if ((mode !== '100644' && mode !== '100755') || kind !== 'blob' || !GIT_OID_RE.test(oid)) {
309
+ return null;
310
+ }
311
+ const size = Number(sizeStr);
312
+ if (!Number.isSafeInteger(size) || size < 0 || String(size) !== sizeStr) {
313
+ return null;
314
+ }
315
+ return size;
316
+ }
317
+ async function verifyBaselineGitAnchor(repository, revision, baseTree) {
318
+ if (typeof repository !== 'string' || repository.length === 0)
319
+ return false;
320
+ if (typeof revision !== 'string' || !GIT_OID_RE.test(revision))
321
+ return false;
322
+ try {
323
+ const [formatRes, commitRes, treeRes] = await Promise.all([
324
+ execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'rev-parse', '--show-object-format'], { cwd: repository, env: CLEAN_GIT_ENV, timeout: 15_000, encoding: 'utf8', maxBuffer: 65_536 }),
325
+ execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'rev-parse', '--verify', `${revision}^{commit}`], { cwd: repository, env: CLEAN_GIT_ENV, timeout: 15_000, encoding: 'utf8', maxBuffer: 65_536 }),
326
+ execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'rev-parse', '--verify', `${revision}^{tree}`], { cwd: repository, env: CLEAN_GIT_ENV, timeout: 15_000, encoding: 'utf8', maxBuffer: 65_536 }),
327
+ ]);
328
+ const actualObjectFormat = formatRes.stdout.trim();
329
+ const actualCommitOid = commitRes.stdout.trim();
330
+ const actualTreeOid = treeRes.stdout.trim();
331
+ return (actualObjectFormat === baseTree.objectFormat
332
+ && actualCommitOid === baseTree.commitOid
333
+ && actualTreeOid === baseTree.treeOid);
334
+ }
335
+ catch {
336
+ return false;
337
+ }
338
+ }
339
+ function isPlainObject(value) {
340
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
341
+ return false;
342
+ const proto = Object.getPrototypeOf(value);
343
+ return proto === Object.prototype || proto === null;
344
+ }
345
+ /** Canonical JSON with sorted keys, matching the controller's snapshot byte domain. */
346
+ function canonical(value) {
347
+ if (value === null || typeof value !== 'object')
348
+ return JSON.stringify(value);
349
+ if (Array.isArray(value))
350
+ return '[' + value.map(canonical).join(',') + ']';
351
+ const record = value;
352
+ return '{' + Object.keys(record).sort().map(key => JSON.stringify(key) + ':' + canonical(record[key])).join(',') + '}';
353
+ }
354
+ const MAX_REQUEST_BYTES = 131072;
355
+ const FAKE_SERVER_DRIVER = `import json, sys, threading
356
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
357
+ from pathlib import Path
358
+ config = json.loads(sys.stdin.read())
359
+ sys.path.insert(0, config["vendorRoot"] + "/tests/auto_sync/fixtures/github")
360
+ sys.path.insert(0, config["vendorRoot"])
361
+ from service import FakeGitHub
362
+ from tools.auto_sync.publish import GitHub
363
+ fake = FakeGitHub(Path(config["repoDir"]), config["repository"], config["bot"])
364
+ fake.__enter__()
365
+ api = GitHub("fake-write-token", config["bot"], api_url=fake.url)
366
+ state = {"event": None}
367
+
368
+ class Control(BaseHTTPRequestHandler):
369
+ def _reply(self, payload, status=200):
370
+ body = json.dumps(payload).encode()
371
+ self.send_response(status)
372
+ self.send_header("content-type", "application/json")
373
+ self.send_header("content-length", str(len(body)))
374
+ self.end_headers()
375
+ self.wfile.write(body)
376
+
377
+ def do_GET(self):
378
+ if self.path == "/state":
379
+ pulls = api.request("GET", "/repos/" + config["repository"] + "/pulls")
380
+ enriched = []
381
+ for p in pulls:
382
+ html_url = p.get("html_url")
383
+ if not isinstance(html_url, str) or not html_url:
384
+ html_url = fake.url + "/repos/" + config["repository"] + "/pulls/" + str(p["number"])
385
+ body = p.get("body") or ""
386
+ head_sha = p["head"]["sha"]
387
+ commit_message = ""
388
+ try:
389
+ commit_message = api.request("GET", "/repos/" + config["repository"] + "/commits/" + head_sha).get("commit", {}).get("message", "")
390
+ except Exception:
391
+ commit_message = ""
392
+ enriched.append({"number": p["number"], "head_sha": head_sha, "head_ref": p["head"].get("ref"), "body": body, "commit_message": commit_message, "html_url": html_url})
393
+ self._reply({"pulls": enriched, "comments": fake.comments})
394
+ else:
395
+ self._reply({"error": "unknown control route"}, 404)
396
+
397
+ def do_POST(self):
398
+ if self.path == "/comment-event":
399
+ length = int(self.headers.get("content-length", "0"))
400
+ body = json.loads(self.rfile.read(length).decode())
401
+ if state["event"] is not None and state["event"]["comment"]["body"] == body["body"] and ("commentId" not in body or body["commentId"] is None or state["event"]["comment"]["id"] == body["commentId"]):
402
+ pass
403
+ else:
404
+ ev = fake.comment_event(body["body"])
405
+ if isinstance(body.get("commentId"), int):
406
+ ev["comment"]["id"] = body["commentId"]
407
+ fake.comments[-1]["id"] = body["commentId"]
408
+ state["event"] = ev
409
+ self._reply({"ok": True, "event": state["event"]})
410
+ elif self.path == "/human-commit":
411
+ length = int(self.headers.get("content-length", "0"))
412
+ body = json.loads(self.rfile.read(length).decode())
413
+ sha = fake.human_commit(body.get("path", "README.md"), body.get("content", "# Human edit\\n"))
414
+ self._reply({"ok": True, "sha": sha})
415
+ else:
416
+ self._reply({"error": "unknown control route"}, 404)
417
+
418
+ def log_message(self, *args):
419
+ pass
420
+
421
+ control = ThreadingHTTPServer(("127.0.0.1", 0), Control)
422
+ print(json.dumps({"fakePort": fake.server.server_port, "controlPort": control.server_port}), flush=True)
423
+ control.serve_forever()
424
+ `;
425
+ export const GATE_DRIVER = `import hashlib, json, os, shutil, stat, subprocess, sys, tempfile
426
+ from pathlib import Path
427
+
428
+ CHUNK_BYTES = 1048576
429
+ MAX_PROPOSAL_BYTES = 1048576
430
+
431
+ def fail(msg):
432
+ print(json.dumps({"ok": False, "error": msg}))
433
+ sys.exit(0)
434
+
435
+ config = json.loads(sys.stdin.read())
436
+ sys.path.insert(0, config["vendorRoot"])
437
+ from tools.auto_sync.assemble import assemble
438
+ from tools.auto_sync.proposal import validate_proposal
439
+ from tools.auto_sync.checks import validate_candidate
440
+ work = Path(tempfile.mkdtemp(prefix="runner-gate-"))
441
+ try:
442
+ repo = work / "target"
443
+ git_env = {
444
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
445
+ "HOME": "/nonexistent",
446
+ "GIT_CONFIG_GLOBAL": "/dev/null",
447
+ "GIT_CONFIG_NOSYSTEM": "1",
448
+ "GIT_TERMINAL_PROMPT": "0",
449
+ }
450
+ subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "protocol.file.allow=always", "clone", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "-q", "--no-hardlinks", "--", config["repository"], str(repo)], env=git_env, check=True)
451
+ subprocess.run(["git", "-C", str(repo), "-c", "core.hooksPath=/dev/null", "checkout", "-q", "-B", "pr-head", config["identity"]["head_sha"]], env=git_env, check=True)
452
+ repo_real = repo.resolve()
453
+
454
+ index_path = Path(config["candidateIndexPath"])
455
+ idx_lstat = os.lstat(index_path)
456
+ if stat.S_ISLNK(idx_lstat.st_mode) or not stat.S_ISREG(idx_lstat.st_mode):
457
+ fail("candidate index must be a regular file")
458
+ with open(index_path, "r", encoding="utf-8") as index_fh:
459
+ index_doc = json.load(index_fh)
460
+ if not isinstance(index_doc, dict) or index_doc.get("version") != 1 or not isinstance(index_doc.get("entries"), list):
461
+ fail("candidate index schema invalid")
462
+ deleted = index_doc.get("deleted", [])
463
+ if not isinstance(deleted, list):
464
+ fail("candidate index deleted schema invalid")
465
+
466
+ deleted_paths = set()
467
+ for del_path in deleted:
468
+ if not isinstance(del_path, str) or not del_path or "\\x00" in del_path or "\\\\" in del_path or del_path.startswith("/") or del_path.endswith("/"):
469
+ fail("candidate deleted path invalid")
470
+ segs = del_path.split("/")
471
+ rel = Path(del_path)
472
+ if rel.is_absolute() or any(s in ("", ".", "..") for s in segs) or ".." in rel.parts or ".git" in [p.lower() for p in rel.parts]:
473
+ fail("candidate deleted path escapes or targets .git: %s" % del_path)
474
+ if del_path in deleted_paths:
475
+ fail("duplicate candidate deleted path: %s" % del_path)
476
+ deleted_paths.add(del_path)
477
+
478
+ for entry in index_doc["entries"]:
479
+ if not isinstance(entry, dict):
480
+ fail("candidate index entry invalid")
481
+ epath = entry.get("path")
482
+ if isinstance(epath, str) and epath in deleted_paths:
483
+ fail("candidate path appears in both entries and deleted: %s" % epath)
484
+
485
+ for del_path in deleted:
486
+ if config["identity"].get("mode") == "revise" and not del_path.startswith(".autosync/"):
487
+ continue
488
+ rel = Path(del_path)
489
+ cur = repo
490
+ parents_exist = True
491
+ for part in rel.parts[:-1]:
492
+ cur = cur / part
493
+ if not cur.exists() and not cur.is_symlink():
494
+ parents_exist = False
495
+ break
496
+ if cur.is_symlink() or not cur.is_dir():
497
+ fail("candidate deleted parent path is a symlink or non-directory: %s" % del_path)
498
+ if not parents_exist:
499
+ continue
500
+ target = repo / rel
501
+ if target.is_symlink():
502
+ fail("candidate deleted target is a symlink: %s" % del_path)
503
+ if target.exists() and target.is_dir():
504
+ fail("candidate deleted target is a directory: %s" % del_path)
505
+ parent_real = target.parent.resolve()
506
+ if parent_real != repo_real and repo_real not in parent_real.parents:
507
+ fail("candidate deleted target escapes repository root: %s" % del_path)
508
+ if target.exists():
509
+ tgt_lstat = os.lstat(target)
510
+ if stat.S_ISLNK(tgt_lstat.st_mode) or not stat.S_ISREG(tgt_lstat.st_mode):
511
+ fail("candidate deleted target is not a regular file: %s" % del_path)
512
+ target.unlink()
513
+ parent_cur = target.parent
514
+ while parent_cur != repo and parent_cur.resolve() != repo_real:
515
+ if parent_cur.is_symlink() or not parent_cur.is_dir():
516
+ break
517
+ try:
518
+ if any(parent_cur.iterdir()):
519
+ break
520
+ parent_cur.rmdir()
521
+ except OSError:
522
+ break
523
+ parent_cur = parent_cur.parent
524
+
525
+ for entry in index_doc["entries"]:
526
+ if not isinstance(entry, dict):
527
+ fail("candidate index entry invalid")
528
+ path = entry.get("path")
529
+ blob_path = entry.get("blobPath")
530
+ expected_len = entry.get("byteLength")
531
+ expected_sha = entry.get("sha256")
532
+ if not isinstance(path, str) or not path or not isinstance(blob_path, str) or not blob_path:
533
+ fail("candidate index entry missing path or blobPath")
534
+ if not isinstance(expected_len, int) or isinstance(expected_len, bool) or expected_len < 0:
535
+ fail("candidate index entry invalid byteLength")
536
+ if not isinstance(expected_sha, str) or len(expected_sha) != 64:
537
+ fail("candidate index entry invalid sha256")
538
+ if config["identity"].get("mode") == "revise" and not path.startswith(".autosync/"):
539
+ continue
540
+ rel = Path(path)
541
+ if rel.is_absolute() or ".." in rel.parts or "\\x00" in path or "\\\\" in path or ".git" in [p.lower() for p in rel.parts]:
542
+ fail("candidate path escapes the repository: %s" % path)
543
+
544
+ blob_lstat = os.lstat(blob_path)
545
+ if stat.S_ISLNK(blob_lstat.st_mode) or not stat.S_ISREG(blob_lstat.st_mode):
546
+ fail("candidate blob is not a regular file: %s" % path)
547
+ if blob_lstat.st_nlink != 1:
548
+ fail("candidate blob must have nlink == 1: %s" % path)
549
+ if blob_lstat.st_size != expected_len:
550
+ fail("candidate blob length mismatch: %s" % path)
551
+
552
+ target = repo / rel
553
+ cur = repo
554
+ for part in rel.parts[:-1]:
555
+ cur = cur / part
556
+ if cur.exists() or cur.is_symlink():
557
+ if cur.is_symlink() or not cur.is_dir():
558
+ fail("candidate parent path is a symlink or non-directory: %s" % path)
559
+ else:
560
+ cur.mkdir(mode=0o700)
561
+ if target.is_symlink():
562
+ fail("candidate target is a symlink: %s" % path)
563
+ if target.exists() and target.is_dir():
564
+ fail("candidate target is a directory: %s" % path)
565
+ if target.parent.resolve() != repo_real and repo_real not in target.parent.resolve().parents:
566
+ fail("candidate target escapes repository root: %s" % path)
567
+
568
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
569
+ src_fd = os.open(blob_path, flags)
570
+ dst_fd = -1
571
+ hasher = hashlib.sha256()
572
+ total = 0
573
+ try:
574
+ st_before = os.fstat(src_fd)
575
+ if not stat.S_ISREG(st_before.st_mode) or st_before.st_nlink != 1 or st_before.st_dev != blob_lstat.st_dev or st_before.st_ino != blob_lstat.st_ino or st_before.st_size != expected_len:
576
+ fail("candidate blob changed during open: %s" % path)
577
+ dst_flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
578
+ dst_fd = os.open(target, dst_flags, 0o600)
579
+ dst_stat = os.fstat(dst_fd)
580
+ if not stat.S_ISREG(dst_stat.st_mode):
581
+ fail("candidate destination is not a regular file: %s" % path)
582
+ with os.fdopen(src_fd, "rb", closefd=True) as src, os.fdopen(dst_fd, "wb", closefd=True) as dst:
583
+ src_fd = -1
584
+ dst_fd = -1
585
+ while True:
586
+ chunk = src.read(CHUNK_BYTES)
587
+ if not chunk:
588
+ break
589
+ total += len(chunk)
590
+ if total > expected_len:
591
+ fail("candidate blob grew past expected byteLength: %s" % path)
592
+ hasher.update(chunk)
593
+ dst.write(chunk)
594
+ st_after = os.fstat(src.fileno())
595
+ if not stat.S_ISREG(st_after.st_mode) or st_after.st_nlink != 1 or st_after.st_dev != st_before.st_dev or st_after.st_ino != st_before.st_ino or st_after.st_size != st_before.st_size or st_after.st_mtime_ns != st_before.st_mtime_ns:
596
+ fail("candidate blob mutated during copy: %s" % path)
597
+ finally:
598
+ if src_fd >= 0:
599
+ os.close(src_fd)
600
+ if dst_fd >= 0:
601
+ os.close(dst_fd)
602
+ if total != expected_len or hasher.hexdigest() != expected_sha:
603
+ fail("candidate blob sha256 mismatch: %s" % path)
604
+
605
+ proposal_file = repo / ".autosync" / "proposal.json"
606
+ prop_lstat = os.lstat(proposal_file)
607
+ if stat.S_ISLNK(prop_lstat.st_mode) or not stat.S_ISREG(prop_lstat.st_mode):
608
+ fail("proposal file is not a regular file")
609
+ if prop_lstat.st_size > MAX_PROPOSAL_BYTES:
610
+ fail("proposal file exceeds %d byte limit" % MAX_PROPOSAL_BYTES)
611
+ prop_fd = os.open(str(proposal_file), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
612
+ with os.fdopen(prop_fd, "rb", closefd=True) as prop_fh:
613
+ raw_proposal = prop_fh.read(MAX_PROPOSAL_BYTES + 1)
614
+ if len(raw_proposal) > MAX_PROPOSAL_BYTES:
615
+ fail("proposal file exceeds %d byte limit" % MAX_PROPOSAL_BYTES)
616
+ proposal = json.loads(raw_proposal.decode("utf-8"))
617
+ assembled = assemble(proposal, repo)
618
+ normalized = validate_proposal(assembled, config["identity"], engine_prereleases=set(config["enginePrereleases"]), prerelease_packages=set(config["prereleasePackages"]))
619
+ checked = validate_candidate(repo, normalized, config["identity"], sources=config["sources"], ascend_pairs=config["ascendPairs"], engine_prereleases=set(config["enginePrereleases"]), prerelease_packages=set(config["prereleasePackages"]))
620
+ accepted = len([g for g in checked.get("groups", []) if g.get("status") == "ready"])
621
+ if accepted == 0:
622
+ fail("zero accepted groups: %s" % json.dumps(checked.get("rejected", []))[:200])
623
+ print(json.dumps({"ok": True, "checked": checked})[:900000])
624
+ except Exception as error:
625
+ print(json.dumps({"ok": False, "error": "%s: %s" % (type(error).__name__, str(error)[:200])}))
626
+ finally:
627
+ shutil.rmtree(work, ignore_errors=True)
628
+ `;
629
+ const PUBLISH_DRIVER = `import json, shutil, subprocess, sys, tempfile
630
+ from pathlib import Path
631
+ config = json.loads(sys.stdin.read())
632
+ sys.path.insert(0, config["vendorRoot"])
633
+ from tools.auto_sync.publish import GitHub, prepare_context, publish
634
+ work = Path(tempfile.mkdtemp(prefix="runner-publish-"))
635
+ try:
636
+ repo = work / "target"
637
+ subprocess.run(["git", "clone", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "-q", "--no-hardlinks", config["snapshotPath"], str(repo)], check=True)
638
+ subprocess.run(["git", "-C", str(repo), "-c", "core.hooksPath=/dev/null", "checkout", "-q", "-B", "pr-head", config["headSha"]], check=True)
639
+ artifact = config["checked"]
640
+ api = GitHub("fake-write-token", config["bot"], api_url=config["fakeUrl"])
641
+ event = config.get("event")
642
+ context = prepare_context(api, config["repository"], config["defaultSha"], event)
643
+ result = publish(api, str(repo), context, artifact, sources=config["sources"], ascend_pairs=config["ascendPairs"], engine_prereleases=set(config["enginePrereleases"]), prerelease_packages=set(config["prereleasePackages"]))
644
+ reduced = {key: value for key, value in result.items() if key not in ("checked", "revalidation")}
645
+ print(json.dumps({"result": reduced})[:200000])
646
+ except Exception as error:
647
+ print(json.dumps({"failed": "%s: %s" % (type(error).__name__, str(error)[:200])}))
648
+ finally:
649
+ shutil.rmtree(work, ignore_errors=True)
650
+ `;
651
+ /**
652
+ * Deterministic candidate digest: the git tree at headSha (or `baseTree` overlay when provided) overlaid with
653
+ * the proposal document and any extra candidate files, identified through ArtifactManifest discipline.
654
+ */
655
+ export async function computeRunnerCandidateDigest(options) {
656
+ const files = new Map();
657
+ if (options.baseTree === undefined) {
658
+ const tree = await execFileAsync('/usr/bin/git', ['ls-tree', '-rz', '--full-tree', options.headSha], { cwd: options.repositorySnapshot, encoding: 'utf8', maxBuffer: 33554432 });
659
+ for (const line of tree.stdout.split('\0')) {
660
+ if (line.trim() === '')
661
+ continue;
662
+ const metadata = line.split('\t');
663
+ if (metadata.length !== 2)
664
+ continue;
665
+ const info = metadata[0].split(/\s+/);
666
+ const blobSha = info[2];
667
+ const path = metadata[1];
668
+ const blob = await execFileAsync('/usr/bin/git', ['cat-file', 'blob', blobSha], { cwd: options.repositorySnapshot, maxBuffer: 33554432, encoding: 'buffer' });
669
+ files.set(path, blob.stdout);
670
+ }
671
+ }
672
+ if (options.proposalJson != null && options.proposalJson !== '') {
673
+ files.set('.autosync/proposal.json', Buffer.from(options.proposalJson, 'utf8'));
674
+ }
675
+ if (options.candidateFiles !== undefined) {
676
+ for (const [path, content] of Object.entries(options.candidateFiles)) {
677
+ files.set(path, typeof content === 'string' ? Buffer.from(content, 'utf8') : Buffer.from(content));
678
+ }
679
+ }
680
+ const entries = [...files.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([name, bytes]) => ({ name, digest: { algorithm: 'sha256', hex: createHash('sha256').update(bytes).digest('hex') }, byteLength: bytes.byteLength }));
681
+ const spec = options.baseTree !== undefined
682
+ ? { baseTree: options.baseTree, entries, deleted: [] }
683
+ : { entries };
684
+ const identified = identifyManifest({ apiVersion: 'loopwright.dev/v1alpha1', kind: 'ArtifactManifest', metadata: { id: 'candidate' }, spec }, options.overlay !== undefined ? { overlay: options.overlay } : undefined);
685
+ if (!identified.ok)
686
+ throw new RunnerTaskpackError('SERVICE_FAULT', `candidate manifest rejected: ${JSON.stringify(identified.errors).slice(0, 200)}`);
687
+ return { digest: identified.value.digest.hex, files };
688
+ }
689
+ function validatorRegistrationFingerprint(registration) {
690
+ return canonical({
691
+ policyProfile: registration.policyProfile ?? 'github',
692
+ allowWorkflowWrites: registration.allowWorkflowWrites === true,
693
+ upstreamSources: registration.upstreamSources,
694
+ ascendPairs: registration.ascendPairs,
695
+ enginePrereleases: registration.enginePrereleases,
696
+ prereleasePackages: registration.prereleasePackages,
697
+ });
698
+ }
699
+ function verifyAndParse(body, secret, signature, kinds) {
700
+ if (signature === undefined)
701
+ return null;
702
+ if (!verifySignedPayload(secret, body, signature))
703
+ return null;
704
+ let parsed;
705
+ try {
706
+ parsed = JSON.parse(body.toString('utf8'));
707
+ }
708
+ catch {
709
+ return null;
710
+ }
711
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
712
+ return null;
713
+ const value = parsed;
714
+ if (value.version !== 1 || !kinds.includes(String(value.kind)))
715
+ return null;
716
+ for (const field of ['storeId', 'runId', 'operationId', 'dispatchId'])
717
+ if (typeof value[field] !== 'string' || value[field] === '')
718
+ return null;
719
+ const lock = value.lockHash;
720
+ const lockOk = typeof lock === 'string' ? /^[0-9a-f]{64}$/.test(lock) : lock !== null && typeof lock === 'object' && lock.algorithm === 'sha256' && typeof lock.hex === 'string' && /^[0-9a-f]{64}$/.test(String(lock.hex));
721
+ if (!lockOk)
722
+ return null;
723
+ if (typeof value.dispatchGeneration !== 'number' || !Number.isSafeInteger(value.dispatchGeneration))
724
+ return null;
725
+ return value;
726
+ }
727
+ function respondJson(response, bytes, signature) {
728
+ response.writeHead(200, { 'content-type': 'application/json', 'content-length': String(bytes.byteLength), 'x-loopwright-signature': signature });
729
+ response.end(bytes);
730
+ }
731
+ function verdictDocument(binding, extra) {
732
+ return Buffer.from(JSON.stringify({ version: 1, kind: 'gate_verdict', ...binding, ...extra }));
733
+ }
734
+ function receiptDocument(binding, extra) {
735
+ return Buffer.from(JSON.stringify({ version: 1, kind: 'publication_receipt', ...binding, ...extra }));
736
+ }
737
+ async function headRevision(repository) {
738
+ try {
739
+ const outcome = await execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'rev-parse', 'HEAD'], { cwd: repository, timeout: 5000, encoding: 'utf8', env: { HOME: '/nonexistent', GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0', PATH: '/usr/bin:/bin' } });
740
+ return outcome.stdout.trim();
741
+ }
742
+ catch {
743
+ return '';
744
+ }
745
+ }
746
+ async function resolveVerifiedCasSha256Dir(runRoot, runId) {
747
+ if (!runRoot || !runId || runId.includes('/') || runId.includes('\\') || runId === '.' || runId === '..') {
748
+ return null;
749
+ }
750
+ try {
751
+ const canonicalRunRoot = await realpath(runRoot);
752
+ const runDir = join(canonicalRunRoot, runId);
753
+ const artifactsDir = join(runDir, 'artifacts');
754
+ const blobsDir = join(artifactsDir, 'blobs');
755
+ const sha256Dir = join(blobsDir, 'sha256');
756
+ for (const dir of [runDir, artifactsDir, blobsDir, sha256Dir]) {
757
+ const info = await lstat(dir);
758
+ if (info.isSymbolicLink() || !info.isDirectory())
759
+ return null;
760
+ }
761
+ return sha256Dir;
762
+ }
763
+ catch {
764
+ return null;
765
+ }
766
+ }
767
+ async function readBoundedRegularFile(filePath, maxBytes) {
768
+ let linfo;
769
+ try {
770
+ linfo = await lstat(filePath);
771
+ }
772
+ catch {
773
+ return null;
774
+ }
775
+ if (linfo.isSymbolicLink() || !linfo.isFile() || linfo.size > maxBytes)
776
+ return null;
777
+ let fd;
778
+ try {
779
+ fd = await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
780
+ }
781
+ catch {
782
+ return null;
783
+ }
784
+ try {
785
+ const before = await fd.stat();
786
+ if (!before.isFile() || before.dev !== linfo.dev || before.ino !== linfo.ino || before.size > maxBytes)
787
+ return null;
788
+ const chunks = [];
789
+ const chunkBuf = Buffer.allocUnsafe(Math.min(CAS_CHUNK_BYTES, Math.max(1, before.size + 1)));
790
+ let totalRead = 0;
791
+ for (;;) {
792
+ const part = await fd.read(chunkBuf, 0, chunkBuf.length, totalRead);
793
+ if (part.bytesRead === 0)
794
+ break;
795
+ totalRead += part.bytesRead;
796
+ if (totalRead > maxBytes)
797
+ return null;
798
+ chunks.push(Buffer.from(chunkBuf.subarray(0, part.bytesRead)));
799
+ }
800
+ const after = await fd.stat();
801
+ if (!after.isFile() || after.dev !== before.dev || after.ino !== before.ino || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) {
802
+ return null;
803
+ }
804
+ return Buffer.concat(chunks, totalRead);
805
+ }
806
+ finally {
807
+ await fd.close();
808
+ }
809
+ }
810
+ async function verifyCasBlobFile(blobPath, expectedLength, expectedDigest) {
811
+ let linfo;
812
+ try {
813
+ linfo = await lstat(blobPath);
814
+ }
815
+ catch {
816
+ return false;
817
+ }
818
+ if (linfo.isSymbolicLink()
819
+ || !linfo.isFile()
820
+ || linfo.nlink !== 1
821
+ || (linfo.mode & 0o222) !== 0
822
+ || linfo.size !== expectedLength) {
823
+ return false;
824
+ }
825
+ let fd;
826
+ try {
827
+ fd = await open(blobPath, constants.O_RDONLY | constants.O_NOFOLLOW);
828
+ }
829
+ catch {
830
+ return false;
831
+ }
832
+ try {
833
+ const before = await fd.stat();
834
+ if (!before.isFile()
835
+ || before.nlink !== 1
836
+ || (before.mode & 0o222) !== 0
837
+ || before.dev !== linfo.dev
838
+ || before.ino !== linfo.ino
839
+ || before.size !== expectedLength) {
840
+ return false;
841
+ }
842
+ const hash = createHash('sha256');
843
+ const chunkBuf = Buffer.allocUnsafe(Math.min(CAS_CHUNK_BYTES, Math.max(1, expectedLength + 1)));
844
+ let bytesRead = 0;
845
+ for (;;) {
846
+ const part = await fd.read(chunkBuf, 0, chunkBuf.length, bytesRead);
847
+ if (part.bytesRead === 0)
848
+ break;
849
+ bytesRead += part.bytesRead;
850
+ if (bytesRead > expectedLength)
851
+ return false;
852
+ hash.update(chunkBuf.subarray(0, part.bytesRead));
853
+ }
854
+ const after = await fd.stat();
855
+ if (!after.isFile()
856
+ || after.nlink !== 1
857
+ || (after.mode & 0o222) !== 0
858
+ || after.dev !== before.dev
859
+ || after.ino !== before.ino
860
+ || after.size !== before.size
861
+ || after.mtimeMs !== before.mtimeMs
862
+ || after.ctimeMs !== before.ctimeMs) {
863
+ return false;
864
+ }
865
+ return bytesRead === expectedLength && hash.digest('hex') === expectedDigest;
866
+ }
867
+ finally {
868
+ await fd.close();
869
+ }
870
+ }
871
+ function parseEntryRef(value) {
872
+ if (!isPlainObject(value))
873
+ return null;
874
+ if (typeof value.name !== 'string' || value.name.length === 0)
875
+ return null;
876
+ if (!isPlainObject(value.digest))
877
+ return null;
878
+ if (value.digest.algorithm !== 'sha256' || typeof value.digest.hex !== 'string' || !SHA256_HEX_RE.test(value.digest.hex))
879
+ return null;
880
+ if (typeof value.byteLength !== 'number' || !Number.isSafeInteger(value.byteLength) || value.byteLength < 0)
881
+ return null;
882
+ return { name: value.name, digest: value.digest.hex, byteLength: value.byteLength };
883
+ }
884
+ /** Reconstruct verified candidate entries and deleted paths from v2 `blob_ref` or legacy v1 `chunk` checkpoint snapshots without buffering large CAS blobs in RAM. */
885
+ export async function candidateEntriesFromRunArtifacts(runRoot, runId, candidateDigest, overlay, pathPolicy, baselineRepository) {
886
+ const effectivePolicy = {
887
+ policyProfile: pathPolicy?.policyProfile ?? 'github',
888
+ allowWorkflowWrites: pathPolicy?.allowWorkflowWrites === true,
889
+ };
890
+ let checkpoints;
891
+ try {
892
+ checkpoints = join(runRoot, runId, 'artifacts', 'pi-checkpoints');
893
+ }
894
+ catch {
895
+ return null;
896
+ }
897
+ let files;
898
+ try {
899
+ files = await readdir(checkpoints);
900
+ }
901
+ catch {
902
+ return null;
903
+ }
904
+ let verifiedSha256Dir = null;
905
+ for (const name of files.filter(file => file.endsWith('.workspace.ndjson')).sort()) {
906
+ const bytes = await readBoundedRegularFile(join(checkpoints, name), MAX_WORKSPACE_NDJSON_BYTES);
907
+ if (bytes === null)
908
+ continue;
909
+ const lines = bytes.toString('utf8').split('\n').filter(line => line.trim() !== '');
910
+ if (lines.length === 0)
911
+ continue;
912
+ let header;
913
+ try {
914
+ header = JSON.parse(lines[0]);
915
+ }
916
+ catch {
917
+ continue;
918
+ }
919
+ if (!isPlainObject(header) || header.type !== 'workspace_snapshot')
920
+ continue;
921
+ if (!isPlainObject(header.manifest) || !isPlainObject(header.manifest.spec))
922
+ continue;
923
+ const rawEntries = header.manifest.spec.entries;
924
+ if (!Array.isArray(rawEntries) || rawEntries.length > OVERLAY_LIMITS.maxMaxFiles)
925
+ continue;
926
+ const parsedEntries = [];
927
+ let validEntries = true;
928
+ for (const rawEntry of rawEntries) {
929
+ const parsed = parseEntryRef(rawEntry);
930
+ if (parsed === null) {
931
+ validEntries = false;
932
+ break;
933
+ }
934
+ parsedEntries.push({ name: parsed.name, digest: { algorithm: 'sha256', hex: parsed.digest }, byteLength: parsed.byteLength });
935
+ }
936
+ if (!validEntries)
937
+ continue;
938
+ // Identify the manifest the same way the controller does, then compare.
939
+ const identified = identifyManifest({
940
+ apiVersion: 'loopwright.dev/v1alpha1',
941
+ kind: 'ArtifactManifest',
942
+ metadata: { id: 'candidate' },
943
+ spec: {
944
+ ...(header.manifest.spec.baseTree !== undefined ? { baseTree: header.manifest.spec.baseTree } : {}),
945
+ entries: parsedEntries,
946
+ ...(header.manifest.spec.deleted !== undefined ? { deleted: header.manifest.spec.deleted } : {}),
947
+ },
948
+ }, overlay !== undefined ? { overlay } : undefined);
949
+ if (!identified.ok)
950
+ continue;
951
+ if (identified.value.digest.hex !== candidateDigest)
952
+ continue;
953
+ const baseTree = identified.value.manifest.spec.baseTree;
954
+ const manifestKind = baseTree !== undefined ? 'overlay' : 'snapshot';
955
+ if (manifestKind === 'snapshot' && identified.value.manifest.spec.deleted !== undefined) {
956
+ return null;
957
+ }
958
+ if (manifestKind === 'overlay' && baselineRepository !== undefined) {
959
+ const anchorMatches = await verifyBaselineGitAnchor(baselineRepository.repository, baselineRepository.revision, baseTree);
960
+ if (!anchorMatches)
961
+ return null;
962
+ }
963
+ const expectedByName = new Map(identified.value.manifest.spec.entries.map(entry => [entry.name, entry]));
964
+ const validatedDeleted = [];
965
+ if (manifestKind === 'overlay') {
966
+ for (const entryName of expectedByName.keys()) {
967
+ if (!isSafeCandidatePath(entryName, effectivePolicy))
968
+ return null;
969
+ }
970
+ const rawDeleted = identified.value.manifest.spec.deleted ?? [];
971
+ const seenDeleted = new Set();
972
+ for (const delPath of rawDeleted) {
973
+ if (!isSafeCandidatePath(delPath, effectivePolicy))
974
+ return null;
975
+ if (expectedByName.has(delPath) || seenDeleted.has(delPath))
976
+ return null;
977
+ seenDeleted.add(delPath);
978
+ validatedDeleted.push(delPath);
979
+ }
980
+ }
981
+ else {
982
+ for (const entryName of expectedByName.keys()) {
983
+ if (!isStructurallySafeCandidatePath(entryName))
984
+ return null;
985
+ if (baselineRepository === undefined && !isSafeCandidatePath(entryName, effectivePolicy))
986
+ return null;
987
+ }
988
+ }
989
+ const reconstructed = new Map();
990
+ let snapshotMode = 'unset';
991
+ let current = null;
992
+ let complete = 0;
993
+ let ended = false;
994
+ for (const line of lines.slice(1)) {
995
+ if (ended)
996
+ return null;
997
+ let parsedRow;
998
+ try {
999
+ parsedRow = JSON.parse(line);
1000
+ }
1001
+ catch {
1002
+ return null;
1003
+ }
1004
+ if (!isPlainObject(parsedRow))
1005
+ return null;
1006
+ const row = parsedRow;
1007
+ if (row.type === 'file') {
1008
+ if (current !== null)
1009
+ return null;
1010
+ const ref = parseEntryRef(row.ref);
1011
+ if (ref === null)
1012
+ return null;
1013
+ const expected = expectedByName.get(ref.name);
1014
+ if (expected === undefined || expected.digest.hex !== ref.digest || expected.byteLength !== ref.byteLength)
1015
+ return null;
1016
+ if (reconstructed.has(ref.name))
1017
+ return null;
1018
+ current = {
1019
+ name: ref.name,
1020
+ digest: ref.digest,
1021
+ length: ref.byteLength,
1022
+ sawBlobRef: false,
1023
+ sawChunk: false,
1024
+ casBlobPath: null,
1025
+ chunks: [],
1026
+ chunkBytes: 0,
1027
+ };
1028
+ continue;
1029
+ }
1030
+ if (row.type === 'blob_ref') {
1031
+ if (current === null || snapshotMode === 'chunk' || current.sawBlobRef || current.sawChunk)
1032
+ return null;
1033
+ snapshotMode = 'blob_ref';
1034
+ current.sawBlobRef = true;
1035
+ const ref = parseEntryRef(row.ref);
1036
+ if (ref === null || ref.name !== current.name || ref.digest !== current.digest || ref.byteLength !== current.length)
1037
+ return null;
1038
+ const blobRefRaw = row.blobRef;
1039
+ if (!isPlainObject(blobRefRaw))
1040
+ return null;
1041
+ const blobRefParsed = parseEntryRef(blobRefRaw);
1042
+ if (blobRefParsed === null
1043
+ || blobRefParsed.name !== current.name
1044
+ || blobRefParsed.digest !== current.digest
1045
+ || blobRefParsed.byteLength !== current.length
1046
+ || blobRefRaw.uri !== `cas://sha256/${current.digest}`) {
1047
+ return null;
1048
+ }
1049
+ if (verifiedSha256Dir === null) {
1050
+ verifiedSha256Dir = await resolveVerifiedCasSha256Dir(runRoot, runId);
1051
+ if (verifiedSha256Dir === null)
1052
+ return null;
1053
+ }
1054
+ const blobPath = join(verifiedSha256Dir, current.digest);
1055
+ if (!(await verifyCasBlobFile(blobPath, current.length, current.digest)))
1056
+ return null;
1057
+ current.casBlobPath = blobPath;
1058
+ continue;
1059
+ }
1060
+ if (row.type === 'chunk') {
1061
+ if (current === null || snapshotMode === 'blob_ref' || current.sawBlobRef)
1062
+ return null;
1063
+ if (typeof row.data !== 'string')
1064
+ return null;
1065
+ snapshotMode = 'chunk';
1066
+ current.sawChunk = true;
1067
+ const part = Buffer.from(row.data, 'base64');
1068
+ current.chunkBytes += part.byteLength;
1069
+ if (current.chunkBytes > current.length)
1070
+ return null;
1071
+ current.chunks.push(part);
1072
+ continue;
1073
+ }
1074
+ if (row.type === 'file_end') {
1075
+ if (current === null)
1076
+ return null;
1077
+ if (row.byteLength !== current.length || row.digest !== current.digest)
1078
+ return null;
1079
+ if (current.sawBlobRef) {
1080
+ if (current.casBlobPath === null)
1081
+ return null;
1082
+ reconstructed.set(current.name, {
1083
+ path: current.name,
1084
+ byteLength: current.length,
1085
+ sha256: current.digest,
1086
+ source: { kind: 'cas_file', blobPath: current.casBlobPath },
1087
+ });
1088
+ }
1089
+ else {
1090
+ if (snapshotMode === 'blob_ref')
1091
+ return null;
1092
+ snapshotMode = 'chunk';
1093
+ const bytes2 = Buffer.concat(current.chunks, current.chunkBytes);
1094
+ if (bytes2.byteLength !== current.length || createHash('sha256').update(bytes2).digest('hex') !== current.digest)
1095
+ return null;
1096
+ reconstructed.set(current.name, {
1097
+ path: current.name,
1098
+ byteLength: current.length,
1099
+ sha256: current.digest,
1100
+ source: { kind: 'inline', bytes: bytes2 },
1101
+ });
1102
+ }
1103
+ current = null;
1104
+ complete += 1;
1105
+ continue;
1106
+ }
1107
+ if (row.type === 'end') {
1108
+ if (current !== null)
1109
+ return null;
1110
+ if (row.files !== complete || complete !== parsedEntries.length || reconstructed.size !== parsedEntries.length)
1111
+ return null;
1112
+ ended = true;
1113
+ continue;
1114
+ }
1115
+ return null;
1116
+ }
1117
+ if (!ended || current !== null || complete !== parsedEntries.length || reconstructed.size !== parsedEntries.length) {
1118
+ return null;
1119
+ }
1120
+ if (manifestKind === 'overlay') {
1121
+ return { manifestKind, baseTree, entries: reconstructed, deleted: validatedDeleted };
1122
+ }
1123
+ if (baselineRepository === undefined) {
1124
+ return { manifestKind, entries: reconstructed, deleted: validatedDeleted };
1125
+ }
1126
+ const baseline = await readBaselineGitTree(baselineRepository.repository, baselineRepository.revision);
1127
+ if (baseline === null)
1128
+ return null;
1129
+ const effectiveDeleted = [];
1130
+ for (const basePath of baseline.regularFiles.keys()) {
1131
+ if (reconstructed.has(basePath))
1132
+ continue;
1133
+ if (!isSafeCandidatePath(basePath, effectivePolicy))
1134
+ return null;
1135
+ effectiveDeleted.push(basePath);
1136
+ }
1137
+ effectiveDeleted.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1138
+ const changedEntries = new Map();
1139
+ for (const [entryPath, entry] of reconstructed.entries()) {
1140
+ if (baseline.symlinks.has(entryPath) || hasSymlinkAncestor(entryPath, baseline.symlinks)) {
1141
+ return null;
1142
+ }
1143
+ const base = baseline.regularFiles.get(entryPath);
1144
+ const isUnchangedBaseline = base !== undefined
1145
+ && base.byteLength === entry.byteLength
1146
+ && base.sha256 === entry.sha256;
1147
+ if (isUnchangedBaseline) {
1148
+ if (entryPath === '.autosync/proposal.json') {
1149
+ changedEntries.set(entryPath, entry);
1150
+ }
1151
+ continue;
1152
+ }
1153
+ if (!isSafeCandidatePath(entryPath, effectivePolicy))
1154
+ return null;
1155
+ changedEntries.set(entryPath, entry);
1156
+ }
1157
+ return { manifestKind, entries: changedEntries, deleted: effectiveDeleted };
1158
+ }
1159
+ return null;
1160
+ }
1161
+ /**
1162
+ * Loopback-only authenticated runner validation gate and publication service over the vendored frozen validators.
1163
+ * The gate validates the bound candidate snapshot (never the operator's pre-registered proposal), runs frozen
1164
+ * assemble -> validate_proposal -> validate_candidate, denies zero-accepted-group candidates, and the publisher
1165
+ * passes the gate-verified artifact to frozen publish with honest outcome mapping.
1166
+ */
1167
+ export async function startRunnerTaskpackService(options) {
1168
+ const bridge = options.bridge ?? new PythonBridge();
1169
+ const ownedBridge = options.bridge === undefined;
1170
+ const scratch = await mkdtemp(join(await (await import('node:fs/promises')).realpath(tmpdir()), 'runner-service-'));
1171
+ await chmod(scratch, 0o700);
1172
+ const verifiedCorpus = await verifyFrozenCorpus(options.corpusRoot);
1173
+ const gateSecret = options.gateSecret, publicationSecret = options.publicationSecret;
1174
+ const registrations = new Map();
1175
+ const checkedCache = new Map();
1176
+ const idempotentReceipts = new Map();
1177
+ const replayBindings = new Map();
1178
+ const fakeRepository = options.fakeRepository ?? 'example-org/runtime-runner';
1179
+ if (options.stateFilePath !== undefined) {
1180
+ try {
1181
+ const persisted = JSON.parse(await readFile(options.stateFilePath, 'utf8'));
1182
+ for (const [key, value] of persisted.receipts ?? [])
1183
+ idempotentReceipts.set(key, { requestDigest: value.requestDigest, bytes: Buffer.from(value.bytes, 'base64'), signature: value.signature });
1184
+ }
1185
+ catch { /* fresh state when the file is absent or unreadable */ }
1186
+ }
1187
+ const persistState = async () => {
1188
+ if (options.stateFilePath === undefined)
1189
+ return;
1190
+ const receipts = [...idempotentReceipts.entries()].map(([key, value]) => [key, { requestDigest: value.requestDigest, bytes: value.bytes.toString('base64'), signature: value.signature }]);
1191
+ await writeFile(options.stateFilePath, JSON.stringify({ receipts }), { mode: 0o600 }).catch(() => undefined);
1192
+ };
1193
+ const fakeServerScript = join(scratch, 'fake-server.py');
1194
+ await writeFile(fakeServerScript, FAKE_SERVER_DRIVER, { mode: 0o600 });
1195
+ const fakeDoubles = new Map();
1196
+ const trackedChildren = new Set();
1197
+ let activeFakeKey = null;
1198
+ function terminateResidentChild(child) {
1199
+ trackedChildren.delete(child);
1200
+ child.removeAllListeners('exit');
1201
+ child.stdout?.destroy();
1202
+ child.stderr?.destroy();
1203
+ if (child.exitCode !== null || child.signalCode !== null)
1204
+ return Promise.resolve();
1205
+ return new Promise(resolve => {
1206
+ const done = () => { clearTimeout(killTimer); resolve(); };
1207
+ child.once('exit', done);
1208
+ try {
1209
+ if (child.pid !== undefined)
1210
+ process.kill(-child.pid, 'SIGTERM');
1211
+ else
1212
+ child.kill('SIGTERM');
1213
+ }
1214
+ catch {
1215
+ child.kill('SIGTERM');
1216
+ }
1217
+ const killTimer = setTimeout(() => {
1218
+ try {
1219
+ if (child.pid !== undefined)
1220
+ process.kill(-child.pid, 'SIGKILL');
1221
+ else
1222
+ child.kill('SIGKILL');
1223
+ }
1224
+ catch {
1225
+ child.kill('SIGKILL');
1226
+ }
1227
+ done();
1228
+ }, 250);
1229
+ killTimer.unref();
1230
+ });
1231
+ }
1232
+ async function ensureFakeDouble(snapshotPath) {
1233
+ const existing = fakeDoubles.get(snapshotPath);
1234
+ if (existing !== undefined) {
1235
+ activeFakeKey = snapshotPath;
1236
+ return;
1237
+ }
1238
+ const gitEnv = { HOME: scratch, PATH: '/usr/bin:/bin', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0' };
1239
+ const fakeRepoDir = join(await mkdtemp(join(scratch, 'fake-repo-')), 'repository');
1240
+ await execFileAsync('/usr/bin/git', ['clone', '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', '-q', '--no-hardlinks', snapshotPath, fakeRepoDir], { env: gitEnv, encoding: 'utf8' });
1241
+ const child = await bridge.residentSpawn([fakeServerScript], {
1242
+ stdin: JSON.stringify({ vendorRoot: verifiedCorpus.root, repoDir: fakeRepoDir, repository: fakeRepository, bot: 'runner-sync[bot]' }),
1243
+ });
1244
+ trackedChildren.add(child);
1245
+ child.stderr?.resume();
1246
+ let ready;
1247
+ try {
1248
+ const readyJson = await new Promise((resolve, reject) => {
1249
+ let buffered = '';
1250
+ const cleanup = () => {
1251
+ clearTimeout(timer);
1252
+ child.stdout?.off('data', onData);
1253
+ child.off('exit', onExit);
1254
+ };
1255
+ const timer = setTimeout(() => {
1256
+ cleanup();
1257
+ reject(new RunnerTaskpackError('SERVICE_FAULT', 'github service double did not become ready'));
1258
+ }, 30000);
1259
+ const onData = (chunk) => {
1260
+ buffered += chunk.toString('utf8');
1261
+ if (buffered.includes('\n')) {
1262
+ cleanup();
1263
+ resolve(buffered.slice(0, buffered.indexOf('\n')));
1264
+ }
1265
+ };
1266
+ const onExit = (code) => {
1267
+ cleanup();
1268
+ reject(new RunnerTaskpackError('SERVICE_FAULT', `github service double exited early (${String(code)})`));
1269
+ };
1270
+ child.stdout.on('data', onData);
1271
+ child.once('exit', onExit);
1272
+ });
1273
+ ready = JSON.parse(readyJson);
1274
+ }
1275
+ catch (error) {
1276
+ await terminateResidentChild(child);
1277
+ throw error;
1278
+ }
1279
+ child.stdout?.resume();
1280
+ child.stdout?.unref?.();
1281
+ child.stderr?.unref?.();
1282
+ child.unref();
1283
+ fakeDoubles.set(snapshotPath, { child, fakeUrl: `http://127.0.0.1:${ready.fakePort}`, controlPort: ready.controlPort, source: snapshotPath, fakeRepoDir });
1284
+ activeFakeKey = snapshotPath;
1285
+ }
1286
+ function activeDouble(snapshotPath) {
1287
+ if (snapshotPath !== undefined) {
1288
+ const instance = fakeDoubles.get(snapshotPath);
1289
+ if (instance === undefined)
1290
+ return null;
1291
+ activeFakeKey = snapshotPath;
1292
+ return { fakeUrl: instance.fakeUrl, controlPort: instance.controlPort };
1293
+ }
1294
+ if (activeFakeKey === null)
1295
+ return null;
1296
+ const instance = fakeDoubles.get(activeFakeKey);
1297
+ return instance === undefined ? null : { fakeUrl: instance.fakeUrl, controlPort: instance.controlPort };
1298
+ }
1299
+ function ensureFakeRepoDir(snapshotPath) {
1300
+ const instance = fakeDoubles.get(snapshotPath);
1301
+ if (instance !== undefined)
1302
+ return instance.fakeRepoDir;
1303
+ return snapshotPath;
1304
+ }
1305
+ async function controlGetState(snapshotPath) {
1306
+ const active = activeDouble(snapshotPath);
1307
+ if (active === null)
1308
+ return { pulls: [], comments: [] };
1309
+ const response = await fetch(`http://127.0.0.1:${active.controlPort}/state`);
1310
+ if (!response.ok)
1311
+ throw new RunnerTaskpackError('SERVICE_FAULT', 'github service double state query failed');
1312
+ return await response.json();
1313
+ }
1314
+ function lookupBinding(request) {
1315
+ const rawLock = request.lockHash;
1316
+ const lockHash = typeof rawLock === 'string' ? rawLock : typeof rawLock === 'object' && rawLock !== null ? String(rawLock.hex ?? '') : '';
1317
+ const binding = { storeId: String(request.storeId), runId: String(request.runId), lockHash, operationId: String(request.operationId), dispatchId: String(request.dispatchId), dispatchGeneration: Number(request.dispatchGeneration) };
1318
+ if (!/^[0-9a-f]{64}$/.test(binding.lockHash))
1319
+ return null;
1320
+ return binding;
1321
+ }
1322
+ function registrationFor(normalized) {
1323
+ return registrations.get(`${normalized.storeId}|${normalized.runId}`);
1324
+ }
1325
+ async function resolveCandidateEntries(_request, registration, candidateDigest, baselineRepository) {
1326
+ const pathPolicy = {
1327
+ policyProfile: registration.policyProfile ?? 'github',
1328
+ allowWorkflowWrites: registration.allowWorkflowWrites === true,
1329
+ };
1330
+ if (registration.runRoot !== undefined) {
1331
+ const fromRun = await candidateEntriesFromRunArtifacts(registration.runRoot, registration.runId, candidateDigest, registration.overlay, pathPolicy, baselineRepository);
1332
+ if (fromRun !== null)
1333
+ return fromRun;
1334
+ return null;
1335
+ }
1336
+ if (registration.candidateFiles !== undefined) {
1337
+ for (const path of Object.keys(registration.candidateFiles)) {
1338
+ if (!isSafeCandidatePath(path, pathPolicy))
1339
+ return null;
1340
+ }
1341
+ }
1342
+ const expected = await computeRunnerCandidateDigest({
1343
+ repositorySnapshot: registration.repositorySnapshot,
1344
+ headSha: registration.identity.headSha,
1345
+ ...(registration.proposalJson !== undefined ? { proposalJson: registration.proposalJson } : {}),
1346
+ ...(registration.candidateFiles === undefined ? {} : { candidateFiles: registration.candidateFiles }),
1347
+ ...(registration.overlay !== undefined ? { overlay: registration.overlay } : {}),
1348
+ });
1349
+ if (expected.digest !== candidateDigest)
1350
+ return null;
1351
+ const entries = new Map();
1352
+ for (const [path, bytes] of expected.files.entries()) {
1353
+ entries.set(path, {
1354
+ path,
1355
+ byteLength: bytes.byteLength,
1356
+ sha256: createHash('sha256').update(bytes).digest('hex'),
1357
+ source: { kind: 'inline', bytes },
1358
+ });
1359
+ }
1360
+ return { manifestKind: 'snapshot', entries, deleted: [] };
1361
+ }
1362
+ async function handleGate(request) {
1363
+ for (const field of ['gateId', 'checkId', 'candidateDigest', 'requestDigest']) {
1364
+ const value = request[field];
1365
+ if (typeof value !== 'string' || value.length === 0 || value.length > 128)
1366
+ return null;
1367
+ }
1368
+ if (String(request.gateId) !== 'runner-candidate-validation' || String(request.checkId) !== 'runner-candidate-validation')
1369
+ return null;
1370
+ const subject = request.subject;
1371
+ if (subject === null || typeof subject !== 'object' || Array.isArray(subject))
1372
+ return null;
1373
+ const binding = { ...lookupBinding(request), lockHash: request.lockHash };
1374
+ if (binding === undefined)
1375
+ return null;
1376
+ const normalized = lookupBinding(request);
1377
+ if (normalized === null)
1378
+ return null;
1379
+ const replayKey = `${normalized.storeId}|${normalized.runId}|${normalized.dispatchId}|${normalized.operationId}`;
1380
+ const seenDigest = replayBindings.get(replayKey);
1381
+ if (seenDigest !== undefined && seenDigest !== String(request.requestDigest))
1382
+ return null;
1383
+ replayBindings.set(replayKey, String(request.requestDigest));
1384
+ const candidateDigest = String(request.candidateDigest);
1385
+ const verdictBase = { gateId: String(request.gateId), checkId: String(request.checkId), candidateDigest };
1386
+ const registration = registrationFor(normalized);
1387
+ if (registration === undefined) {
1388
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'candidate not registered for this run binding', expiresAtMs: String(Date.now() + 60000) }) };
1389
+ }
1390
+ if (registration.candidateDigest != null && registration.candidateDigest !== candidateDigest) {
1391
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'candidate digest differs from the pinned registration', expiresAtMs: String(Date.now() + 60000) }) };
1392
+ }
1393
+ const subjectCandidate = subject.candidateDigest;
1394
+ const subjectCandidateHex = typeof subjectCandidate === 'string' ? subjectCandidate : subjectCandidate !== null && typeof subjectCandidate === 'object' ? String(subjectCandidate.hex ?? '') : undefined;
1395
+ if (subjectCandidateHex !== undefined && subjectCandidateHex !== '' && subjectCandidateHex !== candidateDigest) {
1396
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'subject candidate digest differs from the request binding', expiresAtMs: String(Date.now() + 60000) }) };
1397
+ }
1398
+ const subjectRepository = subject.repository;
1399
+ if (subjectRepository !== undefined && String(subjectRepository) !== registration.identity.repository) {
1400
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'subject repository differs from the registered identity', expiresAtMs: String(Date.now() + 60000) }) };
1401
+ }
1402
+ const isRevise = registration.identity.mode === 'revise' && registration.identity.prHeadSha != null;
1403
+ const gateRepoSource = isRevise ? (activeDouble(registration.repositorySnapshot) ? ensureFakeRepoDir(registration.repositorySnapshot) : registration.repositorySnapshot) : registration.repositorySnapshot;
1404
+ const gateHeadSha = isRevise ? registration.identity.prHeadSha : registration.identity.headSha;
1405
+ const candidateSnapshot = await resolveCandidateEntries(request, registration, candidateDigest, {
1406
+ repository: gateRepoSource,
1407
+ revision: gateHeadSha,
1408
+ });
1409
+ if (candidateSnapshot === null) {
1410
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'candidate digest does not match registered candidate snapshot', expiresAtMs: String(Date.now() + 60000) }) };
1411
+ }
1412
+ const candidateEntries = candidateSnapshot.entries;
1413
+ const metaFields = registration.gateVerdictMetadata !== undefined
1414
+ ? {
1415
+ ...(Object.hasOwn(registration.gateVerdictMetadata, 'detail') ? { detail: registration.gateVerdictMetadata.detail } : {}),
1416
+ ...(registration.gateVerdictMetadata.metrics !== undefined ? { metrics: registration.gateVerdictMetadata.metrics } : {}),
1417
+ ...(registration.gateVerdictMetadata.findings !== undefined ? { findings: registration.gateVerdictMetadata.findings } : {}),
1418
+ }
1419
+ : {};
1420
+ const proposalEntry = candidateEntries.get('.autosync/proposal.json');
1421
+ let proposalByteLength = proposalEntry !== undefined ? proposalEntry.byteLength : null;
1422
+ if (proposalByteLength === null
1423
+ && candidateSnapshot.manifestKind === 'overlay'
1424
+ && !candidateSnapshot.deleted.includes('.autosync/proposal.json')) {
1425
+ proposalByteLength = await readBaselineRegularFileSize(gateRepoSource, gateHeadSha, '.autosync/proposal.json');
1426
+ }
1427
+ if (proposalByteLength === null) {
1428
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'candidate snapshot omits .autosync/proposal.json', expiresAtMs: String(Date.now() + 60000), ...metaFields }) };
1429
+ }
1430
+ if (proposalByteLength > MAX_PROPOSAL_BYTES) {
1431
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'candidate .autosync/proposal.json exceeds 1 MiB limit', expiresAtMs: String(Date.now() + 60000), ...metaFields }) };
1432
+ }
1433
+ const key = `${normalized.storeId}|${normalized.runId}|${candidateDigest}`;
1434
+ const rawCached = checkedCache.get(key);
1435
+ const cached = rawCached !== undefined
1436
+ && validatorRegistrationFingerprint(rawCached.registration) === validatorRegistrationFingerprint(registration)
1437
+ ? rawCached
1438
+ : undefined;
1439
+ if (cached === undefined) {
1440
+ const gateTempDir = await mkdtemp(join(scratch, 'gate-index-'));
1441
+ await chmod(gateTempDir, 0o700);
1442
+ let outcome;
1443
+ try {
1444
+ const inlineBlobsDir = join(gateTempDir, 'inline-blobs');
1445
+ let inlineDirReady = false;
1446
+ const materializedInline = new Map();
1447
+ const indexEntries = [];
1448
+ const sortedEntries = [...candidateEntries.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
1449
+ for (const entry of sortedEntries) {
1450
+ let blobPath;
1451
+ if (entry.source.kind === 'cas_file') {
1452
+ blobPath = entry.source.blobPath;
1453
+ }
1454
+ else {
1455
+ const existing = materializedInline.get(entry.sha256);
1456
+ if (existing !== undefined) {
1457
+ blobPath = existing;
1458
+ }
1459
+ else {
1460
+ if (!inlineDirReady) {
1461
+ await mkdir(inlineBlobsDir, { mode: 0o700 });
1462
+ inlineDirReady = true;
1463
+ }
1464
+ const inlinePath = join(inlineBlobsDir, entry.sha256);
1465
+ const handle = await open(inlinePath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
1466
+ try {
1467
+ let offset = 0;
1468
+ while (offset < entry.source.bytes.byteLength) {
1469
+ const written = await handle.write(entry.source.bytes, offset, entry.source.bytes.byteLength - offset);
1470
+ if (written.bytesWritten <= 0)
1471
+ throw new RunnerTaskpackError('SERVICE_FAULT', 'short write materializing inline gate blob');
1472
+ offset += written.bytesWritten;
1473
+ }
1474
+ await handle.chmod(0o400);
1475
+ }
1476
+ finally {
1477
+ await handle.close();
1478
+ }
1479
+ materializedInline.set(entry.sha256, inlinePath);
1480
+ blobPath = inlinePath;
1481
+ }
1482
+ }
1483
+ indexEntries.push({ path: entry.path, blobPath, byteLength: entry.byteLength, sha256: entry.sha256 });
1484
+ }
1485
+ const sortedDeleted = [...candidateSnapshot.deleted].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1486
+ const candidateIndexPath = join(gateTempDir, 'candidate-index.json');
1487
+ await writeFile(candidateIndexPath, JSON.stringify({ version: 1, entries: indexEntries, deleted: sortedDeleted }), { mode: 0o600 });
1488
+ outcome = await bridge.run(GATE_DRIVER, {
1489
+ timeoutMs: 180000,
1490
+ stdin: JSON.stringify({
1491
+ vendorRoot: (await verifyFrozenCorpus(options.corpusRoot)).root,
1492
+ repository: gateRepoSource,
1493
+ identity: { repository: registration.identity.repository, default_sha: registration.identity.defaultSha, head_sha: gateHeadSha, mode: registration.identity.mode, pr_number: registration.identity.prNumber, command_id: registration.identity.commandId, command_digest: registration.identity.commandDigest },
1494
+ candidateIndexPath,
1495
+ sources: registration.upstreamSources,
1496
+ ascendPairs: registration.ascendPairs,
1497
+ enginePrereleases: registration.enginePrereleases,
1498
+ prereleasePackages: registration.prereleasePackages,
1499
+ }),
1500
+ });
1501
+ }
1502
+ finally {
1503
+ await rm(gateTempDir, { recursive: true, force: true }).catch(() => undefined);
1504
+ }
1505
+ if (outcome.exitCode !== 0) {
1506
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: `validator transport failed: ${outcome.stderr.slice(0, 180)}`, expiresAtMs: String(Date.now() + 60000), ...metaFields }) };
1507
+ }
1508
+ let report;
1509
+ try {
1510
+ report = JSON.parse(outcome.stdout);
1511
+ }
1512
+ catch {
1513
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: 'validator produced unreadable output', expiresAtMs: String(Date.now() + 60000), ...metaFields }) };
1514
+ }
1515
+ if (report.ok !== true || report.checked === null || typeof report.checked !== 'object') {
1516
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'denied', reason: String(report.error ?? 'candidate validation failed').slice(0, 256), expiresAtMs: String(Date.now() + 60000), ...metaFields }) };
1517
+ }
1518
+ const checked = report.checked;
1519
+ const patchDigest = typeof checked.patch_digest === 'string' ? checked.patch_digest : null;
1520
+ checkedCache.set(key, { registration, candidateDigest, checked, patchDigest });
1521
+ if (options.headMutation !== undefined && options.headMutation.repository === registration.repositorySnapshot) {
1522
+ await execFileAsync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', '-c', 'user.name=Human Committer', '-c', 'user.email=human@example.invalid', 'commit', '--allow-empty', '-qm', options.headMutation.message], { cwd: registration.repositorySnapshot, env: { HOME: scratch, PATH: '/usr/bin:/bin', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' } }).catch(() => undefined);
1523
+ }
1524
+ }
1525
+ return { bytes: verdictDocument(binding, { ...verdictBase, status: 'approved', reason: null, expiresAtMs: String(Date.now() + 3600000), ...metaFields }) };
1526
+ }
1527
+ class ChaosDrop extends Error {
1528
+ constructor() { super('chaos drop after write'); }
1529
+ }
1530
+ async function handlePublish(request) {
1531
+ for (const field of ['idempotencyKey', 'candidateDigest', 'requestDigest', 'targetBranch', 'headBranch', 'title', 'baseRevision', 'sourceRevision']) {
1532
+ const value = request[field];
1533
+ if (typeof value !== 'string' || value.length === 0 || value.length > 256)
1534
+ return null;
1535
+ }
1536
+ const normalized = lookupBinding(request);
1537
+ if (normalized === null)
1538
+ return null;
1539
+ const binding = { ...normalized, lockHash: request.lockHash };
1540
+ const idempotencyKey = String(request.idempotencyKey);
1541
+ const candidateDigest = String(request.candidateDigest);
1542
+ const requestDigest = String(request.requestDigest);
1543
+ const replay = idempotentReceipts.get(idempotencyKey);
1544
+ if (replay !== undefined) {
1545
+ if (replay.requestDigest !== requestDigest)
1546
+ return null;
1547
+ return { bytes: replay.bytes };
1548
+ }
1549
+ const base = { idempotencyKey, candidateDigest };
1550
+ const settle = (outcome, externalUrl, reason) => {
1551
+ const bytes = receiptDocument(binding, { ...base, outcome, externalUrl, reason: reason === null ? null : reason.slice(0, 256) });
1552
+ idempotentReceipts.set(idempotencyKey, { requestDigest, bytes, signature: signPayload(publicationSecret, bytes) });
1553
+ void persistState();
1554
+ return { bytes };
1555
+ };
1556
+ const rawCached = checkedCache.get(`${normalized.storeId}|${normalized.runId}|${candidateDigest}`);
1557
+ // The gate-verified artifact is bound to the candidate digest; a re-registered binding (for example a
1558
+ // moved prHeadSha) refreshes the identity used for publication guards without re-running the gate,
1559
+ // provided its host policy profile and workflow-write authority have not changed.
1560
+ const registration = registrationFor(normalized) ?? rawCached?.registration;
1561
+ const cached = rawCached !== undefined
1562
+ && registration !== undefined
1563
+ && validatorRegistrationFingerprint(rawCached.registration) === validatorRegistrationFingerprint(registration)
1564
+ ? rawCached
1565
+ : undefined;
1566
+ if (cached === undefined || registration === undefined)
1567
+ return settle('not_executed', null, 'gate_revalidation_required: no gate-verified artifact for this binding');
1568
+ if (registration.candidateDigest != null && registration.candidateDigest !== candidateDigest) {
1569
+ return settle('not_executed', null, 'candidate_pin_mismatch: request candidate differs from the registered candidate digest');
1570
+ }
1571
+ if (String(request.baseRevision) !== registration.identity.defaultSha || String(request.sourceRevision) !== registration.identity.headSha) {
1572
+ return settle('not_executed', null, 'revision_binding_mismatch: request revisions differ from the registered identity');
1573
+ }
1574
+ const head = await headRevision(registration.repositorySnapshot);
1575
+ if (![registration.identity.defaultSha, registration.identity.headSha].includes(head)) {
1576
+ return settle('not_executed', null, `head_changed_before_publish: snapshot head ${head.slice(0, 12)} is outside the bound revisions`);
1577
+ }
1578
+ if (registration.identity.mode === 'revise') {
1579
+ const { prNumber, commandId, commandDigest } = registration.identity;
1580
+ if (prNumber === null || commandId === null || commandDigest === null || registration.reviseCommentBody === undefined) {
1581
+ return settle('not_executed', null, 'revise_binding_invalid: revise registration is missing its command binding');
1582
+ }
1583
+ const bodyDigest = createHash('sha256').update(Buffer.from(registration.reviseCommentBody, 'utf8')).digest('hex');
1584
+ if (bodyDigest !== commandDigest)
1585
+ return settle('not_executed', null, 'revise_binding_invalid: command body digest differs from the registered command digest');
1586
+ const state = await controlGetState(registration.repositorySnapshot);
1587
+ const managed = state.pulls.find(pull => pull.number === prNumber);
1588
+ if (managed === undefined)
1589
+ return settle('not_executed', null, 'revise_head_changed: the managed pull request is no longer open');
1590
+ const expectedPrHead = registration.identity.prHeadSha ?? (registration.identity.headSha !== registration.identity.defaultSha ? registration.identity.headSha : null);
1591
+ if (expectedPrHead !== null && managed.head_sha !== expectedPrHead) {
1592
+ return settle('not_executed', null, `revise_head_changed: managed pull request head ${managed.head_sha.slice(0, 12)} moved past the bound head`);
1593
+ }
1594
+ const commandMarkerPattern = new RegExp(`"command_id"\\s*:\\s*${commandId}\\b`);
1595
+ const recordedText = [managed.body, managed.commit_message, ...state.comments.map(c => c.body)].join('\n');
1596
+ if (commandMarkerPattern.test(recordedText)) {
1597
+ return settle('not_executed', null, 'duplicate_command_id: this command id was already applied to the managed pull request');
1598
+ }
1599
+ }
1600
+ const publishOutcome = await bridge.run(PUBLISH_DRIVER, {
1601
+ timeoutMs: 240000,
1602
+ stdin: JSON.stringify({
1603
+ vendorRoot: (await verifyFrozenCorpus(options.corpusRoot)).root,
1604
+ fakeUrl: activeDouble(registration.repositorySnapshot)?.fakeUrl ?? '',
1605
+ bot: 'runner-sync[bot]',
1606
+ snapshotPath: (registration.identity.mode === 'revise' && registration.identity.prHeadSha != null) ? (activeDouble(registration.repositorySnapshot) ? ensureFakeRepoDir(registration.repositorySnapshot) : registration.repositorySnapshot) : registration.repositorySnapshot,
1607
+ repository: registration.identity.repository,
1608
+ defaultSha: registration.identity.defaultSha,
1609
+ headSha: (registration.identity.mode === 'revise' && registration.identity.prHeadSha != null) ? registration.identity.prHeadSha : registration.identity.headSha,
1610
+ event: registration.identity.mode === 'revise' ? await commentEvent(registration) : null,
1611
+ checked: cached.checked,
1612
+ sources: registration.upstreamSources,
1613
+ ascendPairs: registration.ascendPairs,
1614
+ enginePrereleases: registration.enginePrereleases,
1615
+ prereleasePackages: registration.prereleasePackages,
1616
+ }),
1617
+ });
1618
+ if (publishOutcome.timedOut)
1619
+ return settle('failed', null, 'publisher timeout: the frozen publish helper exceeded its budget');
1620
+ if (publishOutcome.exitCode !== 0)
1621
+ return settle('failed', null, `publisher transport failed: ${publishOutcome.stderr.slice(0, 180)}`);
1622
+ let report;
1623
+ try {
1624
+ report = JSON.parse(publishOutcome.stdout);
1625
+ }
1626
+ catch {
1627
+ return settle('failed', null, 'publisher produced unreadable output');
1628
+ }
1629
+ if (typeof report.failed === 'string')
1630
+ return settle('failed', null, `publisher error: ${report.failed}`);
1631
+ const status = String(report.result?.status ?? 'unknown');
1632
+ if (status === 'published' || status === 'duplicate') {
1633
+ const state = await controlGetState(registration.repositorySnapshot);
1634
+ const prNumber = typeof report.result?.pr_number === 'number' ? report.result.pr_number : null;
1635
+ const landed = state.pulls.find(pull => pull.number === prNumber) ?? state.pulls[state.pulls.length - 1] ?? null;
1636
+ const receipt = settle('succeeded', landed?.html_url ?? null, status === 'duplicate' ? 'converged with an already-landed managed pull request' : null);
1637
+ if (options.publicationChaos === 'drop_after_write')
1638
+ throw new ChaosDrop();
1639
+ return receipt;
1640
+ }
1641
+ if (status === 'failed')
1642
+ return settle('failed', null, `publish failed: ${String(report.result?.reason ?? 'frozen publish reported failure')}`);
1643
+ if (status === 'ignored' || status === 'no_changes')
1644
+ return settle('not_executed', null, `${status}: ${String(report.result?.reason ?? 'no remote write occurred')}`);
1645
+ if (status === 'deferred')
1646
+ return settle('not_executed', null, `deferred: ${String(report.result?.reason ?? 'publication deferred')}`);
1647
+ return settle('failed', null, `unknown publish status: ${status}: ${String(report.result?.reason ?? '')}`);
1648
+ }
1649
+ async function commentEvent(registration) {
1650
+ const active = activeDouble(registration.repositorySnapshot);
1651
+ if (active === null)
1652
+ throw new RunnerTaskpackError('SERVICE_FAULT', 'github service double is not running');
1653
+ const body = registration.reviseCommentBody ?? '/auto-sync\nRevise the managed proposal.';
1654
+ const response = await fetch(`http://127.0.0.1:${active.controlPort}/comment-event`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ body, commentId: registration.identity.commandId }) });
1655
+ if (!response.ok)
1656
+ throw new RunnerTaskpackError('SERVICE_FAULT', 'comment event preparation failed');
1657
+ return (await response.json()).event;
1658
+ }
1659
+ const server = createServer((incoming, response) => {
1660
+ void (async () => {
1661
+ const signature = incoming.headers['x-loopwright-signature'];
1662
+ const chunks = [];
1663
+ let size = 0;
1664
+ for await (const chunk of incoming) {
1665
+ size += chunk.byteLength;
1666
+ if (size > MAX_REQUEST_BYTES) {
1667
+ response.writeHead(413).end();
1668
+ return;
1669
+ }
1670
+ chunks.push(chunk);
1671
+ }
1672
+ const body = Buffer.concat(chunks);
1673
+ const route = incoming.url?.split('?')[0] ?? '';
1674
+ if (route === '/gate' && incoming.method === 'POST') {
1675
+ const parsed = verifyAndParse(body, gateSecret, typeof signature === 'string' ? signature : undefined, ['gate_request']);
1676
+ if (parsed === null) {
1677
+ response.writeHead(403).end();
1678
+ return;
1679
+ }
1680
+ const outcome = await handleGate(parsed);
1681
+ if (outcome === null) {
1682
+ response.writeHead(400).end();
1683
+ return;
1684
+ }
1685
+ respondJson(response, outcome.bytes, signPayload(gateSecret, outcome.bytes));
1686
+ return;
1687
+ }
1688
+ if (route === '/publish' && incoming.method === 'POST') {
1689
+ const parsed = verifyAndParse(body, publicationSecret, typeof signature === 'string' ? signature : undefined, ['publication_request']);
1690
+ if (parsed === null) {
1691
+ response.writeHead(403).end();
1692
+ return;
1693
+ }
1694
+ try {
1695
+ const outcome = await handlePublish(parsed);
1696
+ if (outcome === null) {
1697
+ response.writeHead(400).end();
1698
+ return;
1699
+ }
1700
+ respondJson(response, outcome.bytes, signPayload(publicationSecret, outcome.bytes));
1701
+ }
1702
+ catch {
1703
+ if (options.publicationChaos === 'drop_after_write') {
1704
+ response.destroy();
1705
+ return;
1706
+ }
1707
+ response.writeHead(500).end();
1708
+ }
1709
+ return;
1710
+ }
1711
+ response.writeHead(404).end();
1712
+ })().catch(() => { try {
1713
+ response.writeHead(500).end();
1714
+ }
1715
+ catch { /* socket gone */ } });
1716
+ });
1717
+ const port = options.port ?? 0;
1718
+ await new Promise(resolve => server.listen(port, '127.0.0.1', resolve));
1719
+ const address = server.address();
1720
+ if (address === null || typeof address === 'string')
1721
+ throw new RunnerTaskpackError('SERVICE_FAULT', 'loopback listener failed to bind');
1722
+ const boundPort = address.port;
1723
+ let closed = false;
1724
+ return {
1725
+ gateUrl: `http://127.0.0.1:${boundPort}/gate`,
1726
+ publicationUrl: `http://127.0.0.1:${boundPort}/publish`,
1727
+ port: boundPort,
1728
+ registerCandidate(registration) {
1729
+ registrations.set(`${registration.storeId}|${registration.runId}`, registration);
1730
+ return ensureFakeDouble(registration.repositorySnapshot);
1731
+ },
1732
+ async fakePullCount() {
1733
+ return (await controlGetState()).pulls.length;
1734
+ },
1735
+ async fakePullHeadSha(prNumber) {
1736
+ return (await controlGetState()).pulls.find(pull => pull.number === prNumber)?.head_sha ?? null;
1737
+ },
1738
+ async fakeHumanCommit(path, content) {
1739
+ const active = activeDouble();
1740
+ if (active === null)
1741
+ throw new RunnerTaskpackError('SERVICE_FAULT', 'github service double is not running');
1742
+ const response = await fetch(`http://127.0.0.1:${active.controlPort}/human-commit`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path, content }) });
1743
+ if (!response.ok)
1744
+ throw new RunnerTaskpackError('SERVICE_FAULT', 'human commit preparation failed');
1745
+ return (await response.json()).sha;
1746
+ },
1747
+ checkedFor(runId) {
1748
+ const entries = [...checkedCache.entries()].filter(([key]) => key.includes(`|${runId}|`));
1749
+ if (entries.length === 0)
1750
+ return null;
1751
+ const [, last] = entries[entries.length - 1];
1752
+ const checked = last.checked;
1753
+ const acceptedGroups = Array.isArray(checked.groups) ? checked.groups.filter(g => g.status === 'ready').length : 0;
1754
+ return { candidateDigest: last.candidateDigest, acceptedGroups, patchDigest: last.patchDigest };
1755
+ },
1756
+ async deriveOperatorReceipt(input) {
1757
+ const state = await controlGetState();
1758
+ const cached = checkedCache.get(`${input.storeId}|${input.runId}|${input.candidateDigest}`) ?? [...checkedCache.entries()].find(([key]) => key.endsWith(`|${input.runId}|${input.candidateDigest}`))?.[1];
1759
+ const expectedBranch = `loopwright-runner-${input.runId}`;
1760
+ const patchDigest = cached?.patchDigest ?? null;
1761
+ const matched = state.pulls.find(pull => (typeof pull.head_ref === 'string' && pull.head_ref === expectedBranch) ||
1762
+ (patchDigest !== null && (pull.commit_message + '\n' + pull.body).includes(patchDigest))) ?? null;
1763
+ const bodyObj = {
1764
+ version: 1,
1765
+ kind: 'publication_receipt',
1766
+ storeId: input.storeId,
1767
+ runId: input.runId,
1768
+ lockHash: input.lockHash ?? '',
1769
+ operationId: input.operationId,
1770
+ dispatchId: input.dispatchId,
1771
+ dispatchGeneration: input.dispatchGeneration,
1772
+ idempotencyKey: input.idempotencyKey,
1773
+ candidateDigest: input.candidateDigest,
1774
+ outcome: matched === null ? 'not_executed' : 'succeeded',
1775
+ externalUrl: matched?.html_url ?? null,
1776
+ reason: matched === null ? 'no pull request matching the bound candidate landed in the service double' : null,
1777
+ };
1778
+ const signature = signPayload(publicationSecret, canonical(bodyObj));
1779
+ const bytes = Buffer.from(JSON.stringify({ ...bodyObj, signature }));
1780
+ return { bytes, signature };
1781
+ },
1782
+ async close() {
1783
+ if (closed)
1784
+ return;
1785
+ closed = true;
1786
+ server.closeAllConnections();
1787
+ await new Promise((resolve, reject) => server.close(error => error === undefined ? resolve() : reject(error)));
1788
+ const children = new Set([...trackedChildren, ...[...fakeDoubles.values()].map(instance => instance.child)]);
1789
+ await Promise.all([...children].map(child => terminateResidentChild(child)));
1790
+ fakeDoubles.clear();
1791
+ if (ownedBridge)
1792
+ await bridge.dispose();
1793
+ await rm(scratch, { recursive: true, force: true });
1794
+ },
1795
+ };
1796
+ }