@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,1654 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { constants as fsConstants, existsSync } from 'node:fs';
3
+ import { chmod, mkdir, mkdtemp, open, readdir, readFile, realpath, rename, rm, unlink, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { canonical as canonicalMemory, DEFAULT_MEMORY_MAX_ENTRIES, DEFAULT_MEMORY_TTL_DAYS, digestEqual, isMemoryManagedPath, loadMemoryStore, MAX_MEMORY_ENTRY_FILE_BYTES, MAX_MEMORY_INDEX_FILE_BYTES, MemoryDiagnosticError, resolveSettledCycleContext, } from '@loopwright/memory';
7
+ import { applyAndValidateTurnkeyMemoryCAS, assertCleanArtifact, buildCleanGitEnv, buildEmptyMemorySummary, buildGitAuthEnv, buildUpstreamMemoryVersions, COMMIT_SHA_PATTERN, DEFAULT_GIT_COMMIT_IDENTITY, execGit, execGitDetailed, fetchBoundedText, finalizeLocalTurnkeyMemory, finalizeTurnkeyProposal, hasSymlinkAtOrAbove, isPlainRecord, listTreeEntriesAtRevision, MAX_REASON_CODEPOINTS, projectMemoryTargetMatrixCell, readRegularJsonBounded, removePathsFromIndex, REPOSITORY_FULL_NAME_PATTERN, resolveManifestControlRoot, resolveSafeRunDirectory, resolveTaskpackMemoryLocation, resolveVerifiedSettledRun, SAFE_BRANCH_PATTERN, sanitizeReportText, scrubTurnkeyReason, stageEntriesInIndex, truncateCodePoints, validateGitCommitIdentity, validateGitRemoteSource, verifyDescriptorAndBudgetSkip, verifyRetainedRunDescriptorIfPresent, } from '@loopwright/taskpack';
8
+ import { GitHubAppError } from './types.js';
9
+ import { findOpenMemoryPullRequest } from './upstreams.js';
10
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
11
+ const MEMORY_PUBLICATION_RECEIPT_FILE = 'memory-publication.json';
12
+ const MAX_RECEIPT_BYTES = 65_536;
13
+ const MAX_MANAGED_MEMORY_FILES = 2_049;
14
+ const MAX_MEMORY_INDEX_BLOB_BYTES = MAX_MEMORY_INDEX_FILE_BYTES;
15
+ const MAX_MEMORY_ENTRY_BLOB_BYTES = MAX_MEMORY_ENTRY_FILE_BYTES;
16
+ function isSafeBranchName(name) {
17
+ return SAFE_BRANCH_PATTERN.test(name) && !name.includes('..') && !name.startsWith('-');
18
+ }
19
+ function parsePerRunMemoryReceipt(parsed) {
20
+ if (!isPlainRecord(parsed) || parsed['version'] !== 1) {
21
+ throw new GitHubAppError('ACTION_INPUT_INVALID', 'corrupt memory publication receipt; manual reconciliation required');
22
+ }
23
+ const state = parsed['state'];
24
+ const status = parsed['status'];
25
+ const repository = parsed['repository'];
26
+ const taskpack = parsed['taskpack'];
27
+ const targetBranch = parsed['targetBranch'];
28
+ const directory = parsed['directory'];
29
+ const proposalId = parsed['proposalId'];
30
+ const entryCount = parsed['entryCount'];
31
+ const rebased = parsed['rebased'];
32
+ const branchName = parsed['branchName'];
33
+ const headOid = parsed['headOid'];
34
+ const pullRequestUrl = parsed['pullRequestUrl'];
35
+ const pullRequestNumber = parsed['pullRequestNumber'];
36
+ const reason = parsed['reason'];
37
+ const updatedAtMs = parsed['updatedAtMs'];
38
+ if ((state !== 'uncertain' && state !== 'completed')
39
+ || (status !== 'published' && status !== 'updated' && status !== 'reconcile_required')
40
+ || typeof repository !== 'string' || repository.length === 0
41
+ || typeof taskpack !== 'string' || taskpack.length === 0
42
+ || typeof targetBranch !== 'string' || targetBranch.length === 0
43
+ || typeof directory !== 'string' || directory.length === 0
44
+ || typeof proposalId !== 'string' || proposalId.length === 0
45
+ || typeof entryCount !== 'number' || !Number.isSafeInteger(entryCount) || entryCount < 0
46
+ || typeof rebased !== 'boolean'
47
+ || typeof branchName !== 'string' || branchName.length === 0
48
+ || typeof headOid !== 'string' || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(headOid)
49
+ || (pullRequestUrl !== null && typeof pullRequestUrl !== 'string')
50
+ || (pullRequestNumber !== null && (typeof pullRequestNumber !== 'number' || !Number.isSafeInteger(pullRequestNumber) || pullRequestNumber <= 0))
51
+ || (reason !== null && typeof reason !== 'string')
52
+ || typeof updatedAtMs !== 'number' || !Number.isFinite(updatedAtMs)) {
53
+ throw new GitHubAppError('ACTION_INPUT_INVALID', 'corrupt memory publication receipt; manual reconciliation required');
54
+ }
55
+ if (state === 'completed' && (status === 'reconcile_required' || pullRequestUrl === null || pullRequestNumber === null)) {
56
+ throw new GitHubAppError('ACTION_INPUT_INVALID', 'corrupt completed memory publication receipt; manual reconciliation required');
57
+ }
58
+ return {
59
+ version: 1,
60
+ state,
61
+ status,
62
+ repository,
63
+ taskpack,
64
+ targetBranch,
65
+ directory,
66
+ proposalId,
67
+ entryCount,
68
+ rebased,
69
+ branchName,
70
+ headOid: headOid.toLowerCase(),
71
+ pullRequestUrl,
72
+ pullRequestNumber,
73
+ reason,
74
+ updatedAtMs,
75
+ };
76
+ }
77
+ function serializeScrubbedReceipt(receipt, scrubber) {
78
+ const sanitized = {
79
+ ...receipt,
80
+ pullRequestUrl: receipt.pullRequestUrl !== null ? scrubber.scrub(receipt.pullRequestUrl) : null,
81
+ reason: receipt.reason !== null
82
+ ? truncateCodePoints(sanitizeReportText(receipt.reason, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS)
83
+ : null,
84
+ };
85
+ const bytes = Buffer.from(`${JSON.stringify(sanitized, null, 2)}\n`, 'utf8');
86
+ assertCleanArtifact(bytes, scrubber, `/${MEMORY_PUBLICATION_RECEIPT_FILE}`);
87
+ return bytes;
88
+ }
89
+ async function readPerRunMemoryReceipt(runRoot, runId) {
90
+ const runDir = await resolveSafeRunDirectory(runRoot, runId, false);
91
+ if (runDir === null)
92
+ return null;
93
+ const raw = await readRegularJsonBounded(join(runDir, MEMORY_PUBLICATION_RECEIPT_FILE), MAX_RECEIPT_BYTES, 'memory publication receipt');
94
+ return raw.exists ? parsePerRunMemoryReceipt(raw.value) : null;
95
+ }
96
+ async function claimPerRunMemoryReceipt(runRoot, runId, receipt, scrubber) {
97
+ const runDir = await resolveSafeRunDirectory(runRoot, runId, true);
98
+ if (runDir === null) {
99
+ throw new GitHubAppError('ACTION_INPUT_INVALID', 'unable to resolve run directory for memory publication receipt');
100
+ }
101
+ const receiptPath = join(runDir, MEMORY_PUBLICATION_RECEIPT_FILE);
102
+ const payload = serializeScrubbedReceipt(receipt, scrubber);
103
+ let handle;
104
+ try {
105
+ handle = await open(receiptPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600);
106
+ }
107
+ catch (err) {
108
+ if (err.code === 'EEXIST') {
109
+ return { claimed: false };
110
+ }
111
+ throw err;
112
+ }
113
+ try {
114
+ await handle.writeFile(payload);
115
+ await handle.sync();
116
+ }
117
+ catch (err) {
118
+ await handle.close().catch(() => undefined);
119
+ await unlink(receiptPath).catch(() => undefined);
120
+ throw err;
121
+ }
122
+ await handle.close();
123
+ return { claimed: true, runDir };
124
+ }
125
+ async function updatePerRunMemoryReceipt(runDir, receipt, scrubber) {
126
+ const receiptPath = join(runDir, MEMORY_PUBLICATION_RECEIPT_FILE);
127
+ const tempPath = `${receiptPath}.tmp.${randomBytes(6).toString('hex')}`;
128
+ const payload = serializeScrubbedReceipt(receipt, scrubber);
129
+ const handle = await open(tempPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600);
130
+ try {
131
+ await handle.writeFile(payload);
132
+ await handle.sync();
133
+ }
134
+ catch (err) {
135
+ await handle.close().catch(() => undefined);
136
+ await unlink(tempPath).catch(() => undefined);
137
+ throw err;
138
+ }
139
+ await handle.close();
140
+ await rename(tempPath, receiptPath);
141
+ }
142
+ function validateReceiptBindings(receipt, expected) {
143
+ if (receipt.repository.toLowerCase() !== expected.repositoryFullName.toLowerCase()) {
144
+ return `MEMORY_SCOPE_VIOLATION: retained memory receipt repository "${receipt.repository}" does not match "${expected.repositoryFullName}"`;
145
+ }
146
+ if (receipt.taskpack !== expected.taskpack) {
147
+ return `MEMORY_SCOPE_VIOLATION: retained memory receipt taskpack "${receipt.taskpack}" does not match "${expected.taskpack}"`;
148
+ }
149
+ if (receipt.targetBranch !== expected.targetBranch) {
150
+ return `MEMORY_SCOPE_VIOLATION: retained memory receipt targetBranch "${receipt.targetBranch}" does not match "${expected.targetBranch}"`;
151
+ }
152
+ if (receipt.directory !== expected.memoryDirectory) {
153
+ return `MEMORY_SCOPE_VIOLATION: retained memory receipt directory "${receipt.directory}" does not match "${expected.memoryDirectory}"`;
154
+ }
155
+ if (receipt.branchName !== expected.memoryBranch) {
156
+ return `MEMORY_SCOPE_VIOLATION: retained memory receipt branchName "${receipt.branchName}" does not match "${expected.memoryBranch}"`;
157
+ }
158
+ return null;
159
+ }
160
+ async function extractOpenMemoryManagedFiles(cloneDir, revision, taskpack, memoryRoot, memoryDirectory, cleanGitEnv) {
161
+ const memTree = await listTreeEntriesAtRevision(cloneDir, revision, cleanGitEnv);
162
+ if (hasSymlinkAtOrAbove(memoryDirectory, memTree, memTree)) {
163
+ throw new GitHubAppError('TASKPACK_SCOPE_VIOLATION', `open memory branch contains symlink at or above "${memoryDirectory}"`);
164
+ }
165
+ const managedEntries = [...memTree.entries()].filter(([path]) => isMemoryManagedPath(taskpack, path, memoryRoot));
166
+ if (managedEntries.length === 0 || managedEntries.length > MAX_MANAGED_MEMORY_FILES) {
167
+ throw new GitHubAppError('ACTION_INPUT_INVALID', `open memory branch carries an invalid managed file count (${managedEntries.length})`);
168
+ }
169
+ const indexRelPath = `${memoryDirectory}/index.json`;
170
+ const files = [];
171
+ for (const [path, entry] of managedEntries) {
172
+ if (entry.type !== 'blob' || entry.mode !== '100644' || hasSymlinkAtOrAbove(path, memTree, memTree)) {
173
+ throw new GitHubAppError('TASKPACK_SCOPE_VIOLATION', `open memory branch carries unsafe entry "${path}"`);
174
+ }
175
+ const maxBlobBytes = path === indexRelPath ? MAX_MEMORY_INDEX_BLOB_BYTES : MAX_MEMORY_ENTRY_BLOB_BYTES;
176
+ const bytes = await execGit(cloneDir, ['cat-file', 'blob', entry.oid], { env: cleanGitEnv, maxStdoutBytes: maxBlobBytes, timeoutMs: 15_000 });
177
+ files.push({ path, bytes });
178
+ }
179
+ return files;
180
+ }
181
+ async function materializeMemoryFilesInClone(cloneDir, memoryDirectory, files) {
182
+ await rm(join(cloneDir, memoryDirectory), { recursive: true, force: true });
183
+ await mkdir(join(cloneDir, memoryDirectory, 'entries'), { recursive: true, mode: 0o700 });
184
+ for (const file of files) {
185
+ await mkdir(dirname(join(cloneDir, file.path)), { recursive: true, mode: 0o700 });
186
+ await writeFile(join(cloneDir, file.path), file.bytes, { mode: 0o600 });
187
+ }
188
+ }
189
+ async function isSquashOrRebaseMergedMemoryBranch(options) {
190
+ const { cloneDir, baseRevision, currentTargetTip, pinnedRemoteMemoryOid, remoteRef, taskpack, repositoryFullName, memoryRoot, memoryDirectory, cleanGitEnv, } = options;
191
+ const branchBaseOid = await execGit(cloneDir, ['merge-base', pinnedRemoteMemoryOid, currentTargetTip], { env: cleanGitEnv, timeoutMs: 5_000 }).then(buf => buf.toString('utf8').trim().toLowerCase(), () => '');
192
+ if (!COMMIT_SHA_PATTERN.test(branchBaseOid)) {
193
+ return false;
194
+ }
195
+ const diffRaw = await execGit(cloneDir, ['diff', '--name-only', branchBaseOid, pinnedRemoteMemoryOid, '--'], { env: cleanGitEnv, timeoutMs: 10_000 }).then(buf => buf.toString('utf8'), () => '');
196
+ const diffPaths = diffRaw.split('\n').map(line => line.trim()).filter(Boolean);
197
+ if (diffPaths.length === 0 || diffPaths.some(path => !isMemoryManagedPath(taskpack, path, memoryRoot))) {
198
+ return false;
199
+ }
200
+ try {
201
+ await execGit(cloneDir, ['reset', '--hard', branchBaseOid], { env: cleanGitEnv, timeoutMs: 15_000 });
202
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 });
203
+ const branchBaseStore = (await loadMemoryStore(cloneDir, taskpack, repositoryFullName, memoryRoot)).index;
204
+ await execGit(cloneDir, ['reset', '--hard', currentTargetTip], { env: cleanGitEnv, timeoutMs: 15_000 });
205
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 });
206
+ const targetTipStore = (await loadMemoryStore(cloneDir, taskpack, repositoryFullName, memoryRoot)).index;
207
+ const remoteFiles = await extractOpenMemoryManagedFiles(cloneDir, remoteRef, taskpack, memoryRoot, memoryDirectory, cleanGitEnv);
208
+ await materializeMemoryFilesInClone(cloneDir, memoryDirectory, remoteFiles);
209
+ const remoteMemStore = (await loadMemoryStore(cloneDir, taskpack, repositoryFullName, memoryRoot)).index;
210
+ if (digestEqual(remoteMemStore.storeDigest, targetTipStore.storeDigest)) {
211
+ return true;
212
+ }
213
+ if (remoteMemStore.entries.length === 0
214
+ && remoteMemStore.retired.length === 0
215
+ && branchBaseStore.entries.length === 0
216
+ && branchBaseStore.retired.length === 0) {
217
+ return false;
218
+ }
219
+ const entriesEqual = (candidate, expected) => candidate !== undefined && canonicalMemory(candidate) === canonicalMemory(expected);
220
+ const branchBaseById = new Map();
221
+ for (const entry of branchBaseStore.entries) {
222
+ branchBaseById.set(entry.id, entry);
223
+ }
224
+ const branchBaseRetiredById = new Map();
225
+ for (const row of branchBaseStore.retired) {
226
+ branchBaseRetiredById.set(row.entry.id, row);
227
+ }
228
+ const targetCurrentById = new Map();
229
+ for (const entry of targetTipStore.entries) {
230
+ targetCurrentById.set(entry.id, entry);
231
+ }
232
+ const targetRetiredById = new Map();
233
+ for (const row of targetTipStore.retired) {
234
+ targetRetiredById.set(row.entry.id, row);
235
+ }
236
+ const remoteCurrentById = new Map();
237
+ for (const entry of remoteMemStore.entries) {
238
+ remoteCurrentById.set(entry.id, entry);
239
+ }
240
+ let hasRemoteChanges = false;
241
+ for (const entry of remoteMemStore.entries) {
242
+ if (entriesEqual(branchBaseById.get(entry.id), entry)) {
243
+ continue;
244
+ }
245
+ hasRemoteChanges = true;
246
+ const exactActiveOnTarget = entriesEqual(targetCurrentById.get(entry.id), entry);
247
+ const targetRetired = targetRetiredById.get(entry.id);
248
+ const landedThenRetiredOnTarget = entriesEqual(targetRetired?.entry, entry)
249
+ && !entriesEqual(branchBaseRetiredById.get(entry.id)?.entry, entry);
250
+ if (!exactActiveOnTarget && !landedThenRetiredOnTarget) {
251
+ return false;
252
+ }
253
+ }
254
+ for (const baseEntry of branchBaseStore.entries) {
255
+ if (remoteCurrentById.has(baseEntry.id))
256
+ continue;
257
+ hasRemoteChanges = true;
258
+ if (entriesEqual(targetCurrentById.get(baseEntry.id), baseEntry)) {
259
+ return false;
260
+ }
261
+ }
262
+ const remoteRetiredById = new Map();
263
+ for (const row of remoteMemStore.retired) {
264
+ remoteRetiredById.set(row.entry.id, row);
265
+ }
266
+ for (const row of remoteMemStore.retired) {
267
+ const priorRetired = branchBaseRetiredById.get(row.entry.id);
268
+ if (priorRetired !== undefined && canonicalMemory(priorRetired) === canonicalMemory(row)) {
269
+ continue;
270
+ }
271
+ hasRemoteChanges = true;
272
+ if (entriesEqual(targetCurrentById.get(row.entry.id), row.entry)) {
273
+ return false;
274
+ }
275
+ const landedRetired = targetRetiredById.get(row.entry.id);
276
+ if (landedRetired !== undefined) {
277
+ const exactRetiredRecordMatch = canonicalMemory(landedRetired) === canonicalMemory(row);
278
+ const remoteReplacement = remoteCurrentById.get(row.entry.id);
279
+ const replacementLaterRetiredOnTarget = remoteReplacement !== undefined && entriesEqual(landedRetired.entry, remoteReplacement);
280
+ if (!exactRetiredRecordMatch && !replacementLaterRetiredOnTarget) {
281
+ return false;
282
+ }
283
+ }
284
+ else if (targetTipStore.retired.length > 0) {
285
+ return false;
286
+ }
287
+ }
288
+ for (const baseRetired of branchBaseStore.retired) {
289
+ if (remoteRetiredById.has(baseRetired.entry.id))
290
+ continue;
291
+ hasRemoteChanges = true;
292
+ const targetRetired = targetRetiredById.get(baseRetired.entry.id);
293
+ if (targetRetired !== undefined) {
294
+ const remoteReplacement = remoteCurrentById.get(baseRetired.entry.id);
295
+ const replacementLaterRetiredOnTarget = remoteReplacement !== undefined && entriesEqual(targetRetired.entry, remoteReplacement);
296
+ if (!replacementLaterRetiredOnTarget) {
297
+ return false;
298
+ }
299
+ }
300
+ }
301
+ return hasRemoteChanges;
302
+ }
303
+ catch {
304
+ return false;
305
+ }
306
+ finally {
307
+ await execGit(cloneDir, ['reset', '--hard', baseRevision], { env: cleanGitEnv, timeoutMs: 15_000 }).catch(() => undefined);
308
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 }).catch(() => undefined);
309
+ }
310
+ }
311
+ function validateMemoryPullRequestApiResponse(parsedPr, expected) {
312
+ if (!isPlainRecord(parsedPr)) {
313
+ return {
314
+ ok: false,
315
+ canConfirmViaReadOnlyGet: false,
316
+ prNumber: null,
317
+ prUrl: null,
318
+ reason: 'memory pull request API returned a 2xx response without a valid JSON object',
319
+ };
320
+ }
321
+ const prUrl = typeof parsedPr['html_url'] === 'string' && parsedPr['html_url'].trim().length > 0
322
+ ? expected.scrubber.scrub(parsedPr['html_url'].trim())
323
+ : null;
324
+ const prNumber = typeof parsedPr['number'] === 'number'
325
+ && Number.isSafeInteger(parsedPr['number'])
326
+ && parsedPr['number'] > 0
327
+ ? parsedPr['number']
328
+ : null;
329
+ if (prUrl === null || prNumber === null) {
330
+ return {
331
+ ok: false,
332
+ canConfirmViaReadOnlyGet: false,
333
+ prNumber: null,
334
+ prUrl: null,
335
+ reason: 'memory pull request API returned a 2xx response without valid JSON number and html_url',
336
+ };
337
+ }
338
+ if (expected.existingPrNumber !== null && prNumber !== expected.existingPrNumber) {
339
+ return {
340
+ ok: false,
341
+ canConfirmViaReadOnlyGet: false,
342
+ prNumber,
343
+ prUrl,
344
+ reason: `memory pull request API returned unexpected PR number #${prNumber} (expected #${expected.existingPrNumber})`,
345
+ };
346
+ }
347
+ if (parsedPr['state'] !== 'open') {
348
+ return {
349
+ ok: false,
350
+ canConfirmViaReadOnlyGet: false,
351
+ prNumber,
352
+ prUrl,
353
+ reason: `memory pull request API returned non-open PR state "${String(parsedPr['state'] ?? '')}"`,
354
+ };
355
+ }
356
+ const head = isPlainRecord(parsedPr['head']) ? parsedPr['head'] : null;
357
+ const base = isPlainRecord(parsedPr['base']) ? parsedPr['base'] : null;
358
+ const headRepo = head !== null && isPlainRecord(head['repo']) ? head['repo'] : null;
359
+ const baseRepo = base !== null && isPlainRecord(base['repo']) ? base['repo'] : null;
360
+ const expectedRepoLower = expected.repositoryFullName.toLowerCase();
361
+ if (head === null
362
+ || head['ref'] !== expected.memoryBranch
363
+ || headRepo === null
364
+ || typeof headRepo['full_name'] !== 'string'
365
+ || headRepo['full_name'].toLowerCase() !== expectedRepoLower) {
366
+ return {
367
+ ok: false,
368
+ canConfirmViaReadOnlyGet: false,
369
+ prNumber,
370
+ prUrl,
371
+ reason: `memory pull request API response head binding did not match "${expected.repositoryFullName}:${expected.memoryBranch}"`,
372
+ };
373
+ }
374
+ if (base === null
375
+ || base['ref'] !== expected.targetBranch
376
+ || baseRepo === null
377
+ || typeof baseRepo['full_name'] !== 'string'
378
+ || baseRepo['full_name'].toLowerCase() !== expectedRepoLower) {
379
+ return {
380
+ ok: false,
381
+ canConfirmViaReadOnlyGet: false,
382
+ prNumber,
383
+ prUrl,
384
+ reason: `memory pull request API response base binding did not match "${expected.repositoryFullName}:${expected.targetBranch}"`,
385
+ };
386
+ }
387
+ if (typeof headRepo['id'] === 'number'
388
+ && typeof baseRepo['id'] === 'number'
389
+ && headRepo['id'] !== baseRepo['id']) {
390
+ return {
391
+ ok: false,
392
+ canConfirmViaReadOnlyGet: false,
393
+ prNumber,
394
+ prUrl,
395
+ reason: 'memory pull request API response head.repo.id did not match base.repo.id',
396
+ };
397
+ }
398
+ if (typeof head['sha'] !== 'string' || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(head['sha'])) {
399
+ return {
400
+ ok: false,
401
+ canConfirmViaReadOnlyGet: true,
402
+ prNumber,
403
+ prUrl,
404
+ reason: 'memory pull request API response omitted a valid head.sha commit digest',
405
+ };
406
+ }
407
+ if (head['sha'].toLowerCase() !== expected.headOid.toLowerCase()) {
408
+ return {
409
+ ok: false,
410
+ canConfirmViaReadOnlyGet: true,
411
+ prNumber,
412
+ prUrl,
413
+ reason: 'memory pull request API response head.sha did not match pushed memory commit',
414
+ };
415
+ }
416
+ return { ok: true, prNumber, prUrl };
417
+ }
418
+ /**
419
+ * Fault-isolated post-settlement memory finalization and 5-gate CAS application.
420
+ *
421
+ * - `apply: 'separate-pull-request'` clones into an isolated scratch directory and
422
+ * publishes `loopwright/memory/<taskpack>/<targetBranch>` without mutating
423
+ * `repositoryRoot`, `.git/worktrees`, primary `RunResult`, or the candidate PR branch.
424
+ * - `apply: 'inline-with-candidate'` skips unless a candidate PR was published for
425
+ * this run, then appends a host-signed memory-only commit onto the published
426
+ * candidate PR branch with `--force-with-lease` protection and zero second PR.
427
+ * - `apply: 'local-only'` and `apply: 'disabled'` delegate to `@loopwright/taskpack`
428
+ * under `policyProfile: 'github'`.
429
+ */
430
+ export async function finalizeAndPublishTurnkeyMemory(options) {
431
+ const scrubber = options.scrubber;
432
+ const nowMs = options.nowMs ?? Date.now();
433
+ let memoryDirectory = options.manifest.spec.memory.directory;
434
+ let trackedProposalId = null;
435
+ let trackedEntryCount = 0;
436
+ let trackedRebased = false;
437
+ let trackedBranchName = null;
438
+ let trackedPrUrl = null;
439
+ let trackedPrNumber = null;
440
+ let mutationDispatched = false;
441
+ try {
442
+ const resolvedLocation = resolveTaskpackMemoryLocation(options.manifest, options.taskpackPath);
443
+ const { controlRoot, memoryRoot } = resolvedLocation;
444
+ memoryDirectory = resolvedLocation.memoryDirectory;
445
+ const { manifestPath } = resolveManifestControlRoot(options.manifest, options.taskpackPath);
446
+ const taskpack = options.manifest.metadata.name;
447
+ const targetBranch = options.manifest.spec.publication.targetBranch ?? 'main';
448
+ const defaultMemoryBranch = `loopwright/memory/${taskpack}/${targetBranch}`;
449
+ const memoryApply = options.manifest.spec.memory.apply;
450
+ const isInlineMode = memoryApply === 'inline-with-candidate';
451
+ const candidatePublication = isInlineMode ? (options.candidatePublication ?? null) : null;
452
+ const memoryBranch = isInlineMode && candidatePublication !== null
453
+ ? candidatePublication.branchName
454
+ : defaultMemoryBranch;
455
+ if (memoryApply === 'disabled') {
456
+ return buildEmptyMemorySummary(memoryDirectory, 'skipped', 'memory_apply_disabled');
457
+ }
458
+ if (!REPOSITORY_FULL_NAME_PATTERN.test(options.repositoryFullName)) {
459
+ return buildEmptyMemorySummary(memoryDirectory, 'skipped', 'repositoryFullName is not an org/repo slug');
460
+ }
461
+ if (memoryApply === 'local-only') {
462
+ return await finalizeLocalTurnkeyMemory({
463
+ runRoot: options.runRoot,
464
+ runId: options.runId,
465
+ repositoryRoot: options.repositoryRoot,
466
+ repositoryFullName: options.repositoryFullName,
467
+ manifest: options.manifest,
468
+ taskpackPath: options.taskpackPath,
469
+ baseRevision: options.baseRevision,
470
+ policyProfile: 'github',
471
+ upstreamRecords: options.upstreamRecords,
472
+ targetMatrix: options.targetMatrix,
473
+ scrubber,
474
+ nowMs,
475
+ });
476
+ }
477
+ if (!COMMIT_SHA_PATTERN.test(options.baseRevision)) {
478
+ return buildEmptyMemorySummary(memoryDirectory, 'failed', 'baseRevision is not a 40-hex commit SHA');
479
+ }
480
+ const ttlDays = options.manifest.spec.memory.ttlDays ?? DEFAULT_MEMORY_TTL_DAYS;
481
+ const ttlMs = ttlDays * MS_PER_DAY;
482
+ const maxEntries = options.manifest.spec.memory.maxEntries ?? DEFAULT_MEMORY_MAX_ENTRIES;
483
+ const checkCodeFingerprint = options.manifest.spec.memory.checkCodeFingerprint === true;
484
+ const checkUpstreamVersions = options.manifest.spec.memory.checkUpstreamVersions === true;
485
+ const manifestMatrix = options.manifest.spec.target?.matrix;
486
+ const rawTargetMatrix = options.targetMatrix !== undefined
487
+ ? options.targetMatrix
488
+ : (manifestMatrix !== undefined && manifestMatrix !== null && manifestMatrix.length === 1 ? manifestMatrix[0] : null);
489
+ const targetMatrix = projectMemoryTargetMatrixCell(rawTargetMatrix);
490
+ const expectedBindings = {
491
+ runId: options.runId,
492
+ repositoryFullName: options.repositoryFullName,
493
+ taskpack,
494
+ baseRevision: options.baseRevision,
495
+ };
496
+ const finalizerConfig = {
497
+ taskpack,
498
+ memoryRoot,
499
+ memoryWritable: [options.manifest.spec.memory.directory],
500
+ onNoModelBudget: options.manifest.spec.memory.onNoModelBudget,
501
+ curator: null,
502
+ requireCuratorReview: false,
503
+ nowMs,
504
+ ttlMs,
505
+ maxEntries,
506
+ checkCodeFingerprint,
507
+ checkUpstreamVersions,
508
+ targetMatrix,
509
+ upstreamVersions: buildUpstreamMemoryVersions(options.upstreamRecords),
510
+ };
511
+ // 0. Check per-run publication receipt before any replay or external mutation.
512
+ let existingReceipt = null;
513
+ try {
514
+ existingReceipt = await readPerRunMemoryReceipt(options.runRoot, options.runId);
515
+ }
516
+ catch (receiptErr) {
517
+ const msg = receiptErr instanceof Error ? receiptErr.message : String(receiptErr);
518
+ return buildEmptyMemorySummary(memoryDirectory, 'reconcile_required', scrubTurnkeyReason(msg, scrubber), {
519
+ branchName: memoryBranch,
520
+ });
521
+ }
522
+ if (existingReceipt !== null) {
523
+ if (existingReceipt.state === 'uncertain') {
524
+ return Object.freeze({
525
+ status: 'reconcile_required',
526
+ directory: existingReceipt.directory,
527
+ proposalId: existingReceipt.proposalId,
528
+ entryCount: existingReceipt.entryCount,
529
+ rebased: existingReceipt.rebased,
530
+ branchName: existingReceipt.branchName,
531
+ pullRequestUrl: existingReceipt.pullRequestUrl,
532
+ pullRequestNumber: existingReceipt.pullRequestNumber,
533
+ reason: existingReceipt.reason ?? 'memory publication outcome is uncertain from a prior attempt; reconcile before replaying',
534
+ });
535
+ }
536
+ const expectedReceiptBranch = isInlineMode
537
+ ? (candidatePublication?.branchName ?? null)
538
+ : memoryBranch;
539
+ if (expectedReceiptBranch === null) {
540
+ return Object.freeze({
541
+ status: 'refused',
542
+ directory: existingReceipt.directory,
543
+ proposalId: existingReceipt.proposalId,
544
+ entryCount: 0,
545
+ rebased: existingReceipt.rebased,
546
+ branchName: existingReceipt.branchName,
547
+ pullRequestUrl: existingReceipt.pullRequestUrl,
548
+ pullRequestNumber: existingReceipt.pullRequestNumber,
549
+ reason: scrubTurnkeyReason('inline memory receipt cannot be replayed without matching candidate pull request publication', scrubber),
550
+ });
551
+ }
552
+ let inlineMismatchReason = null;
553
+ if (isInlineMode && (expectedReceiptBranch === targetBranch || !isSafeBranchName(expectedReceiptBranch))) {
554
+ inlineMismatchReason = `inline memory receipt branch "${expectedReceiptBranch}" is invalid or targets "${targetBranch}"`;
555
+ }
556
+ const retainedRunMismatch = await verifyRetainedRunDescriptorIfPresent(options.runRoot, expectedBindings);
557
+ const bindingMismatchReason = inlineMismatchReason
558
+ ?? validateReceiptBindings(existingReceipt, {
559
+ repositoryFullName: options.repositoryFullName,
560
+ taskpack,
561
+ targetBranch,
562
+ memoryDirectory,
563
+ memoryBranch: expectedReceiptBranch,
564
+ })
565
+ ?? retainedRunMismatch;
566
+ if (bindingMismatchReason !== null) {
567
+ return Object.freeze({
568
+ status: 'refused',
569
+ directory: existingReceipt.directory,
570
+ proposalId: existingReceipt.proposalId,
571
+ entryCount: 0,
572
+ rebased: existingReceipt.rebased,
573
+ branchName: existingReceipt.branchName,
574
+ pullRequestUrl: existingReceipt.pullRequestUrl,
575
+ pullRequestNumber: existingReceipt.pullRequestNumber,
576
+ reason: scrubTurnkeyReason(bindingMismatchReason, scrubber),
577
+ });
578
+ }
579
+ return Object.freeze({
580
+ status: existingReceipt.status === 'updated' ? 'updated' : 'published',
581
+ directory: existingReceipt.directory,
582
+ proposalId: existingReceipt.proposalId,
583
+ entryCount: existingReceipt.entryCount,
584
+ rebased: existingReceipt.rebased,
585
+ branchName: existingReceipt.branchName,
586
+ pullRequestUrl: existingReceipt.pullRequestUrl,
587
+ pullRequestNumber: existingReceipt.pullRequestNumber,
588
+ reason: null,
589
+ });
590
+ }
591
+ if (isInlineMode) {
592
+ if (options.manifest.spec.publication.mode !== 'pull_request') {
593
+ return buildEmptyMemorySummary(memoryDirectory, 'skipped', 'publication.mode is disabled; inline memory skipped');
594
+ }
595
+ if (candidatePublication === null) {
596
+ return buildEmptyMemorySummary(memoryDirectory, 'skipped', 'no_candidate_pull_request');
597
+ }
598
+ if (candidatePublication.runId !== options.runId) {
599
+ return buildEmptyMemorySummary(memoryDirectory, 'refused', 'candidate publication runId does not match settled runId', {
600
+ branchName: candidatePublication.branchName,
601
+ pullRequestUrl: candidatePublication.pullRequestUrl,
602
+ pullRequestNumber: candidatePublication.pullRequestNumber,
603
+ });
604
+ }
605
+ if (!COMMIT_SHA_PATTERN.test(candidatePublication.headSha)) {
606
+ return buildEmptyMemorySummary(memoryDirectory, 'failed', 'candidate publication headSha is not a 40-hex commit SHA', {
607
+ branchName: candidatePublication.branchName,
608
+ pullRequestUrl: candidatePublication.pullRequestUrl,
609
+ pullRequestNumber: candidatePublication.pullRequestNumber,
610
+ });
611
+ }
612
+ if (!isSafeBranchName(candidatePublication.branchName)) {
613
+ return buildEmptyMemorySummary(memoryDirectory, 'failed', `unsafe candidate branch name "${candidatePublication.branchName}"`);
614
+ }
615
+ if (candidatePublication.branchName === targetBranch) {
616
+ return buildEmptyMemorySummary(memoryDirectory, 'refused', `refusing to append inline memory directly onto target branch "${targetBranch}"`, {
617
+ branchName: candidatePublication.branchName,
618
+ pullRequestUrl: candidatePublication.pullRequestUrl,
619
+ pullRequestNumber: candidatePublication.pullRequestNumber,
620
+ });
621
+ }
622
+ trackedBranchName = candidatePublication.branchName;
623
+ trackedPrUrl = candidatePublication.pullRequestUrl;
624
+ trackedPrNumber = candidatePublication.pullRequestNumber;
625
+ }
626
+ // 1. Validate working-tree memory path segments on repositoryRoot before cloning.
627
+ await loadMemoryStore(options.repositoryRoot, taskpack, options.repositoryFullName, memoryRoot);
628
+ // 2. Verify retained run descriptor and respect manifest.spec.memory.onNoModelBudget === 'skip'.
629
+ const preCloneSkip = await verifyDescriptorAndBudgetSkip({
630
+ runRoot: options.runRoot,
631
+ runId: options.runId,
632
+ repositoryRoot: options.repositoryRoot,
633
+ expectedBindings,
634
+ finalizerConfig,
635
+ memoryDirectory,
636
+ scrubber,
637
+ });
638
+ if (preCloneSkip !== null)
639
+ return preCloneSkip;
640
+ const rawScratch = await mkdtemp(join(tmpdir(), 'loopwright-mem-'));
641
+ await chmod(rawScratch, 0o700);
642
+ const memoryScratch = await realpath(rawScratch);
643
+ const cloneDir = join(memoryScratch, 'repo');
644
+ const cleanGitEnv = buildCleanGitEnv();
645
+ try {
646
+ await execGit(memoryScratch, ['-c', 'protocol.file.allow=always', 'clone', '--shared', '--no-checkout', '--', options.repositoryRoot, cloneDir], { env: cleanGitEnv, timeoutMs: 25_000 });
647
+ await execGit(cloneDir, ['checkout', '--force', options.baseRevision, '--'], { env: cleanGitEnv, timeoutMs: 25_000 });
648
+ const settledPreOutcome = await resolveVerifiedSettledRun({
649
+ runRoot: options.runRoot,
650
+ runId: options.runId,
651
+ repository: cloneDir,
652
+ expectedBindings,
653
+ memoryDirectory,
654
+ scrubber,
655
+ });
656
+ if (!settledPreOutcome.ok)
657
+ return settledPreOutcome.summary;
658
+ const settledPre = settledPreOutcome.settled;
659
+ const primaryRunCompleted = settledPre.incident === null
660
+ && settledPre.result !== null
661
+ && settledPre.result.spec.status === 'completed';
662
+ const primaryRunSucceeded = primaryRunCompleted
663
+ || (settledPre.incident === null
664
+ && settledPre.result !== null
665
+ && settledPre.result.spec.status === 'no_change');
666
+ if (isInlineMode && !primaryRunCompleted) {
667
+ return buildEmptyMemorySummary(memoryDirectory, 'skipped', 'candidate_run_not_completed', {
668
+ branchName: candidatePublication?.branchName ?? null,
669
+ pullRequestUrl: candidatePublication?.pullRequestUrl ?? null,
670
+ pullRequestNumber: candidatePublication?.pullRequestNumber ?? null,
671
+ });
672
+ }
673
+ if (memoryApply === 'separate-pull-request'
674
+ && options.manifest.spec.memory.publishOnFailure !== true
675
+ && !primaryRunSucceeded) {
676
+ return buildEmptyMemorySummary(memoryDirectory, 'skipped', 'failure_publication_disabled');
677
+ }
678
+ const gitAuthEnv = buildGitAuthEnv(options.githubToken);
679
+ let resolvedRemote = options.remoteUrl?.trim() || undefined;
680
+ if (resolvedRemote === undefined) {
681
+ const originUrl = await execGit(options.repositoryRoot, ['remote', 'get-url', '--', 'origin'], { env: cleanGitEnv, timeoutMs: 5_000 }).then(buf => buf.toString('utf8').trim(), () => '');
682
+ if (originUrl.length > 0) {
683
+ resolvedRemote = originUrl;
684
+ }
685
+ }
686
+ const memoryBranchSafe = isSafeBranchName(memoryBranch);
687
+ const targetBranchSafe = isSafeBranchName(targetBranch);
688
+ const apiBaseUrl = (options.apiBaseUrl?.trim() || options.runtimeEnv?.['GITHUB_API_URL']?.trim() || '').replace(/\/+$/, '');
689
+ const hasGitHubCredentials = typeof options.githubToken === 'string' && options.githubToken.trim().length > 0;
690
+ const publicationModeEnabled = options.manifest.spec.publication.mode === 'pull_request'
691
+ && (memoryApply === 'separate-pull-request' || isInlineMode);
692
+ let remoteKind;
693
+ let protocolArgs = ['-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never'];
694
+ const remotePublicationRequested = publicationModeEnabled && (isInlineMode
695
+ ? true
696
+ : (apiBaseUrl.length > 0 && hasGitHubCredentials));
697
+ if (resolvedRemote !== undefined) {
698
+ try {
699
+ remoteKind = validateGitRemoteSource(resolvedRemote);
700
+ protocolArgs = remoteKind === 'local-dir'
701
+ ? ['-c', 'protocol.file.allow=always', '-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never']
702
+ : ['-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never'];
703
+ }
704
+ catch (remoteErr) {
705
+ if (remotePublicationRequested) {
706
+ const detail = remoteErr instanceof Error ? remoteErr.message : String(remoteErr);
707
+ return Object.freeze({
708
+ status: 'failed',
709
+ directory: memoryDirectory,
710
+ proposalId: null,
711
+ entryCount: 0,
712
+ rebased: false,
713
+ branchName: isInlineMode ? memoryBranch : null,
714
+ pullRequestUrl: candidatePublication?.pullRequestUrl ?? null,
715
+ pullRequestNumber: candidatePublication?.pullRequestNumber ?? null,
716
+ reason: truncateCodePoints(sanitizeReportText(detail, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS),
717
+ });
718
+ }
719
+ resolvedRemote = undefined;
720
+ }
721
+ }
722
+ const inlineRemoteReady = isInlineMode
723
+ && resolvedRemote !== undefined
724
+ && (remoteKind === 'local-dir' || hasGitHubCredentials);
725
+ const canPublishRemote = isInlineMode
726
+ ? (publicationModeEnabled && inlineRemoteReady && memoryBranchSafe)
727
+ : (remotePublicationRequested && memoryBranchSafe && resolvedRemote !== undefined);
728
+ let currentTargetTip = options.baseRevision;
729
+ let parentCommit = options.baseRevision;
730
+ let openMemoryPr = null;
731
+ let expectedRemoteOid = '';
732
+ let openMemoryManagedFiles = null;
733
+ if (isInlineMode && canPublishRemote && resolvedRemote !== undefined && candidatePublication !== null) {
734
+ const expectedCandidateHead = candidatePublication.headSha.toLowerCase();
735
+ const candidateFetchRes = await execGitDetailed(cloneDir, [...protocolArgs, 'fetch', '--quiet', '--', resolvedRemote, `refs/heads/${memoryBranch}:refs/remotes/candidate/head`], { env: gitAuthEnv, timeoutMs: 15_000 });
736
+ if (candidateFetchRes.spawnError !== null
737
+ || candidateFetchRes.stdoutOverflow
738
+ || candidateFetchRes.timedOut
739
+ || candidateFetchRes.signal !== null
740
+ || candidateFetchRes.code !== 0) {
741
+ const stderrText = candidateFetchRes.stderr.toString('utf8').trim();
742
+ return Object.freeze({
743
+ status: 'failed',
744
+ directory: memoryDirectory,
745
+ proposalId: null,
746
+ entryCount: 0,
747
+ rebased: false,
748
+ branchName: memoryBranch,
749
+ pullRequestUrl: candidatePublication.pullRequestUrl,
750
+ pullRequestNumber: candidatePublication.pullRequestNumber,
751
+ reason: truncateCodePoints(sanitizeReportText(`failed to fetch remote candidate branch "${memoryBranch}" for inline memory commit${stderrText.length > 0 ? `: ${stderrText}` : ''}`, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS),
752
+ });
753
+ }
754
+ const fetchedCandidateHead = (await execGit(cloneDir, ['rev-parse', '--verify', 'refs/remotes/candidate/head^{commit}'], { env: cleanGitEnv, timeoutMs: 5_000 })).toString('utf8').trim().toLowerCase();
755
+ if (fetchedCandidateHead !== expectedCandidateHead) {
756
+ return Object.freeze({
757
+ status: 'refused',
758
+ directory: memoryDirectory,
759
+ proposalId: null,
760
+ entryCount: 0,
761
+ rebased: false,
762
+ branchName: memoryBranch,
763
+ pullRequestUrl: candidatePublication.pullRequestUrl,
764
+ pullRequestNumber: candidatePublication.pullRequestNumber,
765
+ reason: `MEMORY_CAS_CONFLICT: candidate pull request branch "${memoryBranch}" moved concurrently before inline memory commit`,
766
+ });
767
+ }
768
+ const baseRevEntries = await listTreeEntriesAtRevision(cloneDir, options.baseRevision, cleanGitEnv);
769
+ const candidateEntries = await listTreeEntriesAtRevision(cloneDir, expectedCandidateHead, cleanGitEnv);
770
+ const baseManagedMap = new Map();
771
+ for (const [path, entry] of baseRevEntries) {
772
+ if (isMemoryManagedPath(taskpack, path, memoryRoot)) {
773
+ baseManagedMap.set(path, `${entry.mode}:${entry.oid}`);
774
+ }
775
+ }
776
+ const candidateManagedMap = new Map();
777
+ for (const [path, entry] of candidateEntries) {
778
+ if (isMemoryManagedPath(taskpack, path, memoryRoot)) {
779
+ candidateManagedMap.set(path, `${entry.mode}:${entry.oid}`);
780
+ }
781
+ }
782
+ let managedMemoryModifiedByCandidate = baseManagedMap.size !== candidateManagedMap.size;
783
+ if (!managedMemoryModifiedByCandidate) {
784
+ for (const [path, sig] of baseManagedMap) {
785
+ if (candidateManagedMap.get(path) !== sig) {
786
+ managedMemoryModifiedByCandidate = true;
787
+ break;
788
+ }
789
+ }
790
+ }
791
+ if (managedMemoryModifiedByCandidate) {
792
+ return Object.freeze({
793
+ status: 'refused',
794
+ directory: memoryDirectory,
795
+ proposalId: null,
796
+ entryCount: 0,
797
+ rebased: false,
798
+ branchName: memoryBranch,
799
+ pullRequestUrl: candidatePublication.pullRequestUrl,
800
+ pullRequestNumber: candidatePublication.pullRequestNumber,
801
+ reason: `MEMORY_CAS_CONFLICT: candidate pull request branch "${memoryBranch}" already modified managed memory paths`,
802
+ });
803
+ }
804
+ parentCommit = expectedCandidateHead;
805
+ expectedRemoteOid = expectedCandidateHead;
806
+ }
807
+ else if (!isInlineMode && canPublishRemote && resolvedRemote !== undefined) {
808
+ if (!targetBranchSafe) {
809
+ return Object.freeze({
810
+ status: 'failed',
811
+ directory: memoryDirectory,
812
+ proposalId: null,
813
+ entryCount: 0,
814
+ rebased: false,
815
+ branchName: null,
816
+ pullRequestUrl: null,
817
+ pullRequestNumber: null,
818
+ reason: `targetBranch "${targetBranch}" is not a safe git branch name`,
819
+ });
820
+ }
821
+ const targetFetchRes = await execGitDetailed(cloneDir, [...protocolArgs, 'fetch', '--quiet', '--', resolvedRemote, `refs/heads/${targetBranch}:refs/remotes/target/tip`], { env: gitAuthEnv, timeoutMs: 15_000 });
822
+ if (targetFetchRes.spawnError !== null
823
+ || targetFetchRes.stdoutOverflow
824
+ || targetFetchRes.timedOut
825
+ || targetFetchRes.signal !== null
826
+ || targetFetchRes.code !== 0) {
827
+ const stderrText = targetFetchRes.stderr.toString('utf8').trim();
828
+ return Object.freeze({
829
+ status: 'failed',
830
+ directory: memoryDirectory,
831
+ proposalId: null,
832
+ entryCount: 0,
833
+ rebased: false,
834
+ branchName: null,
835
+ pullRequestUrl: null,
836
+ pullRequestNumber: null,
837
+ reason: truncateCodePoints(sanitizeReportText(`failed to fetch remote target branch "${targetBranch}" for memory CAS${stderrText.length > 0 ? `: ${stderrText}` : ''}`, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS),
838
+ });
839
+ }
840
+ const fetchedTip = (await execGit(cloneDir, ['rev-parse', '--verify', 'refs/remotes/target/tip^{commit}'], { env: cleanGitEnv, timeoutMs: 5_000 })).toString('utf8').trim().toLowerCase();
841
+ if (!COMMIT_SHA_PATTERN.test(fetchedTip)) {
842
+ return Object.freeze({
843
+ status: 'failed',
844
+ directory: memoryDirectory,
845
+ proposalId: null,
846
+ entryCount: 0,
847
+ rebased: false,
848
+ branchName: null,
849
+ pullRequestUrl: null,
850
+ pullRequestNumber: null,
851
+ reason: `remote target branch "${targetBranch}" did not resolve to a valid commit SHA`,
852
+ });
853
+ }
854
+ currentTargetTip = fetchedTip;
855
+ parentCommit = fetchedTip;
856
+ }
857
+ else if (!isInlineMode && publicationModeEnabled && resolvedRemote !== undefined && targetBranchSafe) {
858
+ const fetchedTip = await execGit(cloneDir, [...protocolArgs, 'fetch', '--quiet', '--', resolvedRemote, `refs/heads/${targetBranch}:refs/remotes/target/tip`], { env: gitAuthEnv, timeoutMs: 15_000 }).then(async () => (await execGit(cloneDir, ['rev-parse', '--verify', 'refs/remotes/target/tip^{commit}'], { env: cleanGitEnv, timeoutMs: 5_000 })).toString('utf8').trim().toLowerCase(), () => '');
859
+ if (COMMIT_SHA_PATTERN.test(fetchedTip)) {
860
+ currentTargetTip = fetchedTip;
861
+ parentCommit = fetchedTip;
862
+ }
863
+ }
864
+ if (!isInlineMode && canPublishRemote && resolvedRemote !== undefined) {
865
+ trackedBranchName = memoryBranch;
866
+ const lsRemoteOut = (await execGit(cloneDir, [...protocolArgs, 'ls-remote', '--', resolvedRemote, `refs/heads/${memoryBranch}`], { env: gitAuthEnv, timeoutMs: 15_000 })).toString('utf8').trim();
867
+ const pinnedRemoteMemoryOid = lsRemoteOut.length > 0
868
+ ? (lsRemoteOut.split(/\s+/)[0] ?? '').toLowerCase()
869
+ : '';
870
+ if (pinnedRemoteMemoryOid.length > 0 && !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(pinnedRemoteMemoryOid)) {
871
+ return Object.freeze({
872
+ status: 'failed',
873
+ directory: memoryDirectory,
874
+ proposalId: null,
875
+ entryCount: 0,
876
+ rebased: false,
877
+ branchName: memoryBranch,
878
+ pullRequestUrl: null,
879
+ pullRequestNumber: null,
880
+ reason: `invalid remote OID for refs/heads/${memoryBranch}`,
881
+ });
882
+ }
883
+ openMemoryPr = await findOpenMemoryPullRequest({
884
+ apiBaseUrl,
885
+ repositoryFullName: options.repositoryFullName,
886
+ targetBranch,
887
+ memoryBranch,
888
+ githubToken: options.githubToken,
889
+ fetchImpl: options.fetchImpl,
890
+ scrubber,
891
+ env: options.runtimeEnv,
892
+ });
893
+ trackedPrUrl = openMemoryPr?.htmlUrl ?? null;
894
+ trackedPrNumber = openMemoryPr?.number ?? null;
895
+ if (openMemoryPr !== null) {
896
+ if (pinnedRemoteMemoryOid.length === 0) {
897
+ return Object.freeze({
898
+ status: 'refused',
899
+ directory: memoryDirectory,
900
+ proposalId: null,
901
+ entryCount: 0,
902
+ rebased: false,
903
+ branchName: memoryBranch,
904
+ pullRequestUrl: openMemoryPr.htmlUrl,
905
+ pullRequestNumber: openMemoryPr.number,
906
+ reason: `MEMORY_CAS_CONFLICT: open memory pull request #${openMemoryPr.number} branch "${memoryBranch}" is missing on remote`,
907
+ });
908
+ }
909
+ if (openMemoryPr.headSha.length > 0
910
+ && openMemoryPr.headSha !== '0'.repeat(40)
911
+ && openMemoryPr.headSha.toLowerCase() !== pinnedRemoteMemoryOid) {
912
+ return Object.freeze({
913
+ status: 'refused',
914
+ directory: memoryDirectory,
915
+ proposalId: null,
916
+ entryCount: 0,
917
+ rebased: false,
918
+ branchName: memoryBranch,
919
+ pullRequestUrl: openMemoryPr.htmlUrl,
920
+ pullRequestNumber: openMemoryPr.number,
921
+ reason: `MEMORY_CAS_CONFLICT: open memory pull request #${openMemoryPr.number} head moved concurrently`,
922
+ });
923
+ }
924
+ await execGit(cloneDir, [...protocolArgs, 'fetch', '--quiet', '--', resolvedRemote, `refs/heads/${memoryBranch}:refs/remotes/memory/open`], { env: gitAuthEnv, timeoutMs: 15_000 });
925
+ const fetchedOpenOid = (await execGit(cloneDir, ['rev-parse', '--verify', 'refs/remotes/memory/open^{commit}'], { env: cleanGitEnv, timeoutMs: 5_000 })).toString('utf8').trim().toLowerCase();
926
+ if (fetchedOpenOid !== pinnedRemoteMemoryOid) {
927
+ return Object.freeze({
928
+ status: 'refused',
929
+ directory: memoryDirectory,
930
+ proposalId: null,
931
+ entryCount: 0,
932
+ rebased: false,
933
+ branchName: memoryBranch,
934
+ pullRequestUrl: openMemoryPr.htmlUrl,
935
+ pullRequestNumber: openMemoryPr.number,
936
+ reason: `MEMORY_CAS_CONFLICT: open memory branch "${memoryBranch}" moved while fetching`,
937
+ });
938
+ }
939
+ expectedRemoteOid = pinnedRemoteMemoryOid;
940
+ const baseRevStore = (await loadMemoryStore(cloneDir, taskpack, options.repositoryFullName, memoryRoot)).index;
941
+ let targetTipStore = baseRevStore;
942
+ if (currentTargetTip !== options.baseRevision) {
943
+ await execGit(cloneDir, ['reset', '--hard', currentTargetTip], { env: cleanGitEnv, timeoutMs: 15_000 });
944
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 });
945
+ targetTipStore = (await loadMemoryStore(cloneDir, taskpack, options.repositoryFullName, memoryRoot)).index;
946
+ await execGit(cloneDir, ['reset', '--hard', options.baseRevision], { env: cleanGitEnv, timeoutMs: 15_000 });
947
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 });
948
+ }
949
+ let memPrParentStore = baseRevStore;
950
+ const openParentOid = await execGit(cloneDir, ['rev-parse', '--verify', 'refs/remotes/memory/open^^{commit}'], { env: cleanGitEnv, timeoutMs: 5_000 }).then(buf => buf.toString('utf8').trim().toLowerCase(), () => '');
951
+ if (COMMIT_SHA_PATTERN.test(openParentOid) && openParentOid !== options.baseRevision) {
952
+ await execGit(cloneDir, ['reset', '--hard', openParentOid], { env: cleanGitEnv, timeoutMs: 15_000 });
953
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 });
954
+ memPrParentStore = (await loadMemoryStore(cloneDir, taskpack, options.repositoryFullName, memoryRoot)).index;
955
+ await execGit(cloneDir, ['reset', '--hard', options.baseRevision], { env: cleanGitEnv, timeoutMs: 15_000 });
956
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 });
957
+ }
958
+ openMemoryManagedFiles = await extractOpenMemoryManagedFiles(cloneDir, 'refs/remotes/memory/open', taskpack, memoryRoot, memoryDirectory, cleanGitEnv);
959
+ await materializeMemoryFilesInClone(cloneDir, memoryDirectory, openMemoryManagedFiles);
960
+ const memPrStore = (await loadMemoryStore(cloneDir, taskpack, options.repositoryFullName, memoryRoot)).index;
961
+ if (!digestEqual(memPrParentStore.storeDigest, targetTipStore.storeDigest)
962
+ && !digestEqual(memPrStore.storeDigest, targetTipStore.storeDigest)) {
963
+ return Object.freeze({
964
+ status: 'refused',
965
+ directory: memoryDirectory,
966
+ proposalId: null,
967
+ entryCount: 0,
968
+ rebased: false,
969
+ branchName: memoryBranch,
970
+ pullRequestUrl: openMemoryPr.htmlUrl,
971
+ pullRequestNumber: openMemoryPr.number,
972
+ reason: 'MEMORY_CAS_CONFLICT: target branch memory store diverged from open memory pull request; merge or rebase the open memory PR first',
973
+ });
974
+ }
975
+ }
976
+ else if (pinnedRemoteMemoryOid.length > 0) {
977
+ await execGit(cloneDir, [...protocolArgs, 'fetch', '--quiet', '--', resolvedRemote, `refs/heads/${memoryBranch}:refs/remotes/memory/remote`], { env: gitAuthEnv, timeoutMs: 15_000 });
978
+ const fetchedRemoteOid = (await execGit(cloneDir, ['rev-parse', '--verify', 'refs/remotes/memory/remote^{commit}'], { env: cleanGitEnv, timeoutMs: 5_000 })).toString('utf8').trim().toLowerCase();
979
+ if (fetchedRemoteOid !== pinnedRemoteMemoryOid) {
980
+ return Object.freeze({
981
+ status: 'refused',
982
+ directory: memoryDirectory,
983
+ proposalId: null,
984
+ entryCount: 0,
985
+ rebased: false,
986
+ branchName: memoryBranch,
987
+ pullRequestUrl: null,
988
+ pullRequestNumber: null,
989
+ reason: `MEMORY_CAS_CONFLICT: remote memory branch "${memoryBranch}" moved while fetching`,
990
+ });
991
+ }
992
+ const isAncestorOfTarget = await execGit(cloneDir, ['merge-base', '--is-ancestor', pinnedRemoteMemoryOid, currentTargetTip], { env: cleanGitEnv, timeoutMs: 5_000 }).then(() => true, () => false);
993
+ const isLandedInTarget = isAncestorOfTarget || await isSquashOrRebaseMergedMemoryBranch({
994
+ cloneDir,
995
+ baseRevision: options.baseRevision,
996
+ currentTargetTip,
997
+ pinnedRemoteMemoryOid,
998
+ remoteRef: 'refs/remotes/memory/remote',
999
+ taskpack,
1000
+ repositoryFullName: options.repositoryFullName,
1001
+ memoryRoot,
1002
+ memoryDirectory,
1003
+ cleanGitEnv,
1004
+ });
1005
+ if (!isLandedInTarget) {
1006
+ return Object.freeze({
1007
+ status: 'reconcile_required',
1008
+ directory: memoryDirectory,
1009
+ proposalId: null,
1010
+ entryCount: 0,
1011
+ rebased: false,
1012
+ branchName: memoryBranch,
1013
+ pullRequestUrl: null,
1014
+ pullRequestNumber: null,
1015
+ reason: `remote memory branch "${memoryBranch}" exists without an open pull request and is not merged into "${targetBranch}"; reconcile before publishing`,
1016
+ });
1017
+ }
1018
+ expectedRemoteOid = pinnedRemoteMemoryOid;
1019
+ }
1020
+ }
1021
+ const baseStore = (await loadMemoryStore(cloneDir, taskpack, options.repositoryFullName, memoryRoot)).index;
1022
+ const finalizedOutcome = await finalizeTurnkeyProposal({
1023
+ runRoot: options.runRoot,
1024
+ runId: options.runId,
1025
+ repository: cloneDir,
1026
+ baseStore,
1027
+ finalizerConfig,
1028
+ memoryDirectory,
1029
+ scrubber,
1030
+ });
1031
+ if (finalizedOutcome.proposal !== null) {
1032
+ trackedProposalId = finalizedOutcome.proposal.proposalId;
1033
+ trackedEntryCount = finalizedOutcome.proposal.operations.length;
1034
+ }
1035
+ if (!finalizedOutcome.ok)
1036
+ return finalizedOutcome.summary;
1037
+ const finalized = { proposal: finalizedOutcome.proposal };
1038
+ if (currentTargetTip !== options.baseRevision) {
1039
+ await execGit(cloneDir, ['reset', '--hard', currentTargetTip], { env: cleanGitEnv, timeoutMs: 15_000 });
1040
+ await execGit(cloneDir, ['clean', '-fdx'], { env: cleanGitEnv, timeoutMs: 15_000 });
1041
+ if (openMemoryManagedFiles !== null) {
1042
+ await materializeMemoryFilesInClone(cloneDir, memoryDirectory, openMemoryManagedFiles);
1043
+ }
1044
+ }
1045
+ const settled = await resolveSettledCycleContext({
1046
+ kind: 'run_directory',
1047
+ runRoot: options.runRoot,
1048
+ runId: options.runId,
1049
+ repository: cloneDir,
1050
+ });
1051
+ const casResult = await applyAndValidateTurnkeyMemoryCAS({
1052
+ repository: cloneDir,
1053
+ taskpack,
1054
+ proposal: finalized.proposal,
1055
+ settled,
1056
+ scrubber,
1057
+ manifest: options.manifest,
1058
+ controlRoot,
1059
+ manifestPath,
1060
+ memoryRoot,
1061
+ memoryDirectory,
1062
+ targetBranch,
1063
+ currentRevision: currentTargetTip,
1064
+ baseStore,
1065
+ nowMs,
1066
+ maxEntries,
1067
+ outsideScopeReason: 'memory pull request specification touched paths outside the managed memory directory',
1068
+ policyProfile: 'github',
1069
+ });
1070
+ trackedRebased = casResult.rebased;
1071
+ if (!casResult.ok)
1072
+ return casResult.summary;
1073
+ if (!memoryBranchSafe) {
1074
+ return Object.freeze({
1075
+ status: 'failed',
1076
+ directory: memoryDirectory,
1077
+ proposalId: finalized.proposal.proposalId,
1078
+ entryCount: finalized.proposal.operations.length,
1079
+ rebased: casResult.rebased,
1080
+ branchName: null,
1081
+ pullRequestUrl: null,
1082
+ pullRequestNumber: null,
1083
+ reason: `unsafe memory branch name "${memoryBranch}"`,
1084
+ });
1085
+ }
1086
+ if (options.manifest.spec.publication.mode !== 'pull_request') {
1087
+ return Object.freeze({
1088
+ status: 'local_only',
1089
+ directory: memoryDirectory,
1090
+ proposalId: finalized.proposal.proposalId,
1091
+ entryCount: finalized.proposal.operations.length,
1092
+ rebased: casResult.rebased,
1093
+ branchName: null,
1094
+ pullRequestUrl: null,
1095
+ pullRequestNumber: null,
1096
+ reason: 'publication.mode is disabled; remote memory branch writes skipped',
1097
+ });
1098
+ }
1099
+ if ((isInlineMode && !inlineRemoteReady)
1100
+ || (!isInlineMode && (options.manifest.spec.memory.apply !== 'separate-pull-request'
1101
+ || resolvedRemote === undefined
1102
+ || apiBaseUrl.length === 0
1103
+ || !hasGitHubCredentials))) {
1104
+ return Object.freeze({
1105
+ status: 'local_only',
1106
+ directory: memoryDirectory,
1107
+ proposalId: finalized.proposal.proposalId,
1108
+ entryCount: finalized.proposal.operations.length,
1109
+ rebased: casResult.rebased,
1110
+ branchName: isInlineMode ? null : memoryBranch,
1111
+ pullRequestUrl: null,
1112
+ pullRequestNumber: null,
1113
+ reason: isInlineMode
1114
+ ? 'GitHub credentials or git remote unavailable for inline memory commit'
1115
+ : 'GitHub credentials, API URL, or git remote unavailable for separate memory PR publication',
1116
+ });
1117
+ }
1118
+ if (resolvedRemote === undefined) {
1119
+ return Object.freeze({
1120
+ status: 'local_only',
1121
+ directory: memoryDirectory,
1122
+ proposalId: finalized.proposal.proposalId,
1123
+ entryCount: finalized.proposal.operations.length,
1124
+ rebased: casResult.rebased,
1125
+ branchName: isInlineMode ? null : memoryBranch,
1126
+ pullRequestUrl: null,
1127
+ pullRequestNumber: null,
1128
+ reason: 'git remote unavailable for memory publication',
1129
+ });
1130
+ }
1131
+ const commitIdentity = options.gitCommitIdentity !== undefined
1132
+ ? validateGitCommitIdentity(options.gitCommitIdentity)
1133
+ : DEFAULT_GIT_COMMIT_IDENTITY;
1134
+ const memIndexFile = join(memoryScratch, 'mem-index');
1135
+ const gitClone = (args, extraOpts) => execGit(cloneDir, args, { env: gitAuthEnv, ...extraOpts });
1136
+ const gitWithMemIndex = (args, extraOpts) => execGit(cloneDir, args, { env: { ...gitAuthEnv, GIT_INDEX_FILE: memIndexFile }, ...extraOpts });
1137
+ const baseTreeOid = (await gitClone(['rev-parse', '--verify', '--end-of-options', `${parentCommit}^{tree}`])).toString('utf8').trim();
1138
+ await gitWithMemIndex(['read-tree', `${parentCommit}^{tree}`]);
1139
+ const baseEntries = await listTreeEntriesAtRevision(cloneDir, parentCommit, cleanGitEnv);
1140
+ const existingBaseManagedPaths = [...baseEntries.keys()].filter(path => isMemoryManagedPath(taskpack, path, memoryRoot));
1141
+ for (const existingPath of existingBaseManagedPaths) {
1142
+ if (hasSymlinkAtOrAbove(existingPath, baseEntries, baseEntries)) {
1143
+ return Object.freeze({
1144
+ status: 'refused',
1145
+ directory: memoryDirectory,
1146
+ proposalId: finalized.proposal.proposalId,
1147
+ entryCount: 0,
1148
+ rebased: casResult.rebased,
1149
+ branchName: memoryBranch,
1150
+ pullRequestUrl: null,
1151
+ pullRequestNumber: null,
1152
+ reason: `refusing to overwrite symlinked memory path "${existingPath}"`,
1153
+ });
1154
+ }
1155
+ }
1156
+ await removePathsFromIndex(cloneDir, memIndexFile, existingBaseManagedPaths, gitAuthEnv);
1157
+ await loadMemoryStore(cloneDir, taskpack, options.repositoryFullName, memoryRoot);
1158
+ const postCasFiles = [];
1159
+ const indexRelPath = `${memoryDirectory}/index.json`;
1160
+ postCasFiles.push({ path: indexRelPath, bytes: await readFile(join(cloneDir, indexRelPath)) });
1161
+ const entriesDirAbs = join(cloneDir, memoryDirectory, 'entries');
1162
+ if (existsSync(entriesDirAbs)) {
1163
+ const entryDirents = (await readdir(entriesDirAbs, { withFileTypes: true }))
1164
+ .filter(dirent => dirent.isFile() && dirent.name.endsWith('.md'))
1165
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1166
+ for (const dirent of entryDirents) {
1167
+ const entryRelPath = `${memoryDirectory}/entries/${dirent.name}`;
1168
+ if (isMemoryManagedPath(taskpack, entryRelPath, memoryRoot)) {
1169
+ postCasFiles.push({ path: entryRelPath, bytes: await readFile(join(cloneDir, entryRelPath)) });
1170
+ }
1171
+ }
1172
+ }
1173
+ if (postCasFiles.length > MAX_MANAGED_MEMORY_FILES) {
1174
+ return Object.freeze({
1175
+ status: 'refused',
1176
+ directory: memoryDirectory,
1177
+ proposalId: finalized.proposal.proposalId,
1178
+ entryCount: 0,
1179
+ rebased: casResult.rebased,
1180
+ branchName: memoryBranch,
1181
+ pullRequestUrl: null,
1182
+ pullRequestNumber: null,
1183
+ reason: `managed memory file count (${postCasFiles.length}) exceeds supported ceiling (${MAX_MANAGED_MEMORY_FILES})`,
1184
+ });
1185
+ }
1186
+ const stagedMemoryEntries = [];
1187
+ for (const file of postCasFiles) {
1188
+ const maxAllowedBytes = file.path === indexRelPath ? MAX_MEMORY_INDEX_BLOB_BYTES : MAX_MEMORY_ENTRY_BLOB_BYTES;
1189
+ if (file.bytes.byteLength > maxAllowedBytes) {
1190
+ return Object.freeze({
1191
+ status: 'refused',
1192
+ directory: memoryDirectory,
1193
+ proposalId: finalized.proposal.proposalId,
1194
+ entryCount: 0,
1195
+ rebased: casResult.rebased,
1196
+ branchName: memoryBranch,
1197
+ pullRequestUrl: null,
1198
+ pullRequestNumber: null,
1199
+ reason: `managed memory file "${file.path}" (${file.bytes.byteLength} bytes) exceeds supported ceiling (${maxAllowedBytes} bytes)`,
1200
+ });
1201
+ }
1202
+ if (hasSymlinkAtOrAbove(file.path, baseEntries, baseEntries)) {
1203
+ return Object.freeze({
1204
+ status: 'refused',
1205
+ directory: memoryDirectory,
1206
+ proposalId: finalized.proposal.proposalId,
1207
+ entryCount: 0,
1208
+ rebased: casResult.rebased,
1209
+ branchName: memoryBranch,
1210
+ pullRequestUrl: null,
1211
+ pullRequestNumber: null,
1212
+ reason: `refusing to overwrite symlinked memory path "${file.path}"`,
1213
+ });
1214
+ }
1215
+ assertCleanArtifact(file.bytes, scrubber, `/${file.path}`);
1216
+ const blobOid = (await gitClone(['hash-object', '-w', '--stdin'], { input: file.bytes })).toString('utf8').trim();
1217
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(blobOid)) {
1218
+ throw new GitHubAppError('ACTION_INPUT_INVALID', `git hash-object returned invalid oid for "${file.path}"`);
1219
+ }
1220
+ stagedMemoryEntries.push({ path: file.path, mode: '100644', oid: blobOid });
1221
+ }
1222
+ await stageEntriesInIndex(cloneDir, memIndexFile, stagedMemoryEntries, gitAuthEnv);
1223
+ const treeOid = (await gitWithMemIndex(['write-tree'])).toString('utf8').trim();
1224
+ if (treeOid === baseTreeOid) {
1225
+ return Object.freeze({
1226
+ status: 'no_entries',
1227
+ directory: memoryDirectory,
1228
+ proposalId: finalized.proposal.proposalId,
1229
+ entryCount: 0,
1230
+ rebased: casResult.rebased,
1231
+ branchName: memoryBranch,
1232
+ pullRequestUrl: isInlineMode ? candidatePublication?.pullRequestUrl ?? null : openMemoryPr?.htmlUrl ?? null,
1233
+ pullRequestNumber: isInlineMode ? candidatePublication?.pullRequestNumber ?? null : openMemoryPr?.number ?? null,
1234
+ reason: isInlineMode
1235
+ ? 'memory tree already matches candidate branch'
1236
+ : 'memory tree already matches target branch',
1237
+ });
1238
+ }
1239
+ if (!isInlineMode && openMemoryPr !== null) {
1240
+ const existingOpenTreeOid = (await gitClone(['rev-parse', '--verify', '--end-of-options', 'refs/remotes/memory/open^{tree}'])).toString('utf8').trim();
1241
+ const existingOpenParentOid = await gitClone(['rev-parse', '--verify', '--end-of-options', 'refs/remotes/memory/open^^{commit}']).then(buf => buf.toString('utf8').trim().toLowerCase(), () => '');
1242
+ if (treeOid === existingOpenTreeOid && existingOpenParentOid === currentTargetTip) {
1243
+ return Object.freeze({
1244
+ status: 'no_entries',
1245
+ directory: memoryDirectory,
1246
+ proposalId: finalized.proposal.proposalId,
1247
+ entryCount: 0,
1248
+ rebased: casResult.rebased,
1249
+ branchName: memoryBranch,
1250
+ pullRequestUrl: openMemoryPr.htmlUrl,
1251
+ pullRequestNumber: openMemoryPr.number,
1252
+ reason: 'open memory pull request already matches proposed tree',
1253
+ });
1254
+ }
1255
+ }
1256
+ const cleanInline = (value) => truncateCodePoints(scrubber.scrub(value).replace(/[\r\n]+/g, ' ').trim(), 72);
1257
+ const cleanTitle = cleanInline(casResult.pullRequest.title);
1258
+ const cleanBody = scrubber.scrub(casResult.pullRequest.body).replace(/\r\n?/g, '\n').trim();
1259
+ const upsertsCount = finalized.proposal.operations.filter(op => op.kind === 'upsert').length;
1260
+ const retireCount = finalized.proposal.operations.length - upsertsCount;
1261
+ const commitBody = [
1262
+ cleanInline(`- Taskpack: ${taskpack}`),
1263
+ `- Operations: ${finalized.proposal.operations.length} (${upsertsCount} upsert, ${retireCount} retire)`,
1264
+ cleanInline(`- Run: ${options.runId}`),
1265
+ ].join('\n');
1266
+ const signoffLine = `Signed-off-by: ${commitIdentity.name} <${commitIdentity.email}>`;
1267
+ const hasExactSignoff = cleanTitle === signoffLine;
1268
+ const skipCiParagraph = options.manifest.spec.memory.skipCi === true ? '\n\n[skip ci]' : '';
1269
+ const commitMessage = hasExactSignoff
1270
+ ? `${cleanTitle}\n\n${commitBody}${skipCiParagraph}\n`
1271
+ : `${cleanTitle}\n\n${commitBody}${skipCiParagraph}\n\n${signoffLine}\n`;
1272
+ const headOid = (await gitClone([
1273
+ '-c', `user.name=${commitIdentity.name}`,
1274
+ '-c', `user.email=${commitIdentity.email}`,
1275
+ 'commit-tree',
1276
+ treeOid,
1277
+ '-p',
1278
+ parentCommit,
1279
+ ], { input: commitMessage })).toString('utf8').trim().toLowerCase();
1280
+ trackedBranchName = memoryBranch;
1281
+ const existingPrUrl = isInlineMode ? (candidatePublication?.pullRequestUrl ?? null) : (openMemoryPr?.htmlUrl ?? null);
1282
+ const existingPrNumber = isInlineMode ? (candidatePublication?.pullRequestNumber ?? null) : (openMemoryPr?.number ?? null);
1283
+ const baseReceiptRecord = {
1284
+ version: 1,
1285
+ repository: options.repositoryFullName,
1286
+ taskpack,
1287
+ targetBranch,
1288
+ directory: memoryDirectory,
1289
+ proposalId: finalized.proposal.proposalId,
1290
+ entryCount: finalized.proposal.operations.length,
1291
+ rebased: casResult.rebased,
1292
+ branchName: memoryBranch,
1293
+ headOid,
1294
+ };
1295
+ const claimed = await claimPerRunMemoryReceipt(options.runRoot, options.runId, {
1296
+ ...baseReceiptRecord,
1297
+ state: 'uncertain',
1298
+ status: 'reconcile_required',
1299
+ pullRequestUrl: existingPrUrl,
1300
+ pullRequestNumber: existingPrNumber,
1301
+ reason: isInlineMode ? 'inline memory branch push in flight' : 'memory branch push in flight',
1302
+ updatedAtMs: Date.now(),
1303
+ }, scrubber);
1304
+ if (!claimed.claimed) {
1305
+ return Object.freeze({
1306
+ status: 'reconcile_required',
1307
+ directory: memoryDirectory,
1308
+ proposalId: finalized.proposal.proposalId,
1309
+ entryCount: finalized.proposal.operations.length,
1310
+ rebased: casResult.rebased,
1311
+ branchName: memoryBranch,
1312
+ pullRequestUrl: existingPrUrl,
1313
+ pullRequestNumber: existingPrNumber,
1314
+ reason: 'memory publication already in flight or unresolved for this run',
1315
+ });
1316
+ }
1317
+ const { runDir } = claimed;
1318
+ mutationDispatched = true;
1319
+ const pushResult = await execGitDetailed(cloneDir, [
1320
+ ...protocolArgs,
1321
+ 'push',
1322
+ '--porcelain',
1323
+ `--force-with-lease=refs/heads/${memoryBranch}:${expectedRemoteOid}`,
1324
+ '--',
1325
+ resolvedRemote,
1326
+ `${headOid}:refs/heads/${memoryBranch}`,
1327
+ ], { env: gitAuthEnv, timeoutMs: 25_000 });
1328
+ if (pushResult.spawnError !== null
1329
+ || pushResult.stdoutOverflow
1330
+ || pushResult.timedOut
1331
+ || pushResult.code !== 0
1332
+ || pushResult.signal !== null) {
1333
+ const expectedTargetRef = `refs/heads/${memoryBranch}`;
1334
+ const stdoutLines = pushResult.stdout.toString('utf8').split(/\r?\n/);
1335
+ let sawStaleLeaseRefRejection = false;
1336
+ let sawAnyRefUpdate = false;
1337
+ let sawDoneFooter = false;
1338
+ for (const rawLine of stdoutLines) {
1339
+ if (rawLine === 'Done') {
1340
+ sawDoneFooter = true;
1341
+ continue;
1342
+ }
1343
+ const tabParts = rawLine.split('\t');
1344
+ if (tabParts.length >= 3 && tabParts[0].length === 1) {
1345
+ const flag = tabParts[0];
1346
+ const fromTo = tabParts[1];
1347
+ const summary = tabParts.slice(2).join('\t').trim();
1348
+ const colonIdx = fromTo.indexOf(':');
1349
+ if (flag === ' ' || flag === '+' || flag === '-' || flag === '*' || flag === '=') {
1350
+ sawAnyRefUpdate = true;
1351
+ }
1352
+ else if (flag === '!'
1353
+ && colonIdx > 0
1354
+ && fromTo.slice(0, colonIdx).toLowerCase() === headOid
1355
+ && fromTo.slice(colonIdx + 1) === expectedTargetRef
1356
+ && /^\[rejected\]\s*\(stale info\)$/i.test(summary)) {
1357
+ sawStaleLeaseRefRejection = true;
1358
+ }
1359
+ }
1360
+ }
1361
+ let verifiedNotAtHead = false;
1362
+ if (pushResult.spawnError === null
1363
+ && !pushResult.stdoutOverflow
1364
+ && !pushResult.timedOut
1365
+ && pushResult.signal === null
1366
+ && pushResult.code === 1
1367
+ && sawStaleLeaseRefRejection
1368
+ && sawDoneFooter
1369
+ && !sawAnyRefUpdate) {
1370
+ const verifyRemote = await execGitDetailed(cloneDir, [...protocolArgs, 'ls-remote', '--', resolvedRemote, expectedTargetRef], { env: gitAuthEnv, timeoutMs: 10_000 });
1371
+ if (verifyRemote.spawnError === null
1372
+ && !verifyRemote.stdoutOverflow
1373
+ && !verifyRemote.timedOut
1374
+ && verifyRemote.signal === null
1375
+ && verifyRemote.code === 0) {
1376
+ const observedRemoteOid = verifyRemote.stdout.toString('utf8').trim().split(/\s+/)[0]?.toLowerCase() ?? '';
1377
+ if (observedRemoteOid !== headOid) {
1378
+ verifiedNotAtHead = true;
1379
+ }
1380
+ }
1381
+ }
1382
+ if (verifiedNotAtHead) {
1383
+ mutationDispatched = false;
1384
+ await unlink(join(runDir, MEMORY_PUBLICATION_RECEIPT_FILE)).catch(() => undefined);
1385
+ return Object.freeze({
1386
+ status: 'refused',
1387
+ directory: memoryDirectory,
1388
+ proposalId: finalized.proposal.proposalId,
1389
+ entryCount: 0,
1390
+ rebased: casResult.rebased,
1391
+ branchName: memoryBranch,
1392
+ pullRequestUrl: existingPrUrl,
1393
+ pullRequestNumber: existingPrNumber,
1394
+ reason: isInlineMode
1395
+ ? 'MEMORY_CAS_CONFLICT: remote candidate pull request branch moved concurrently (force-with-lease rejected)'
1396
+ : 'MEMORY_CAS_CONFLICT: remote memory branch moved concurrently (force-with-lease rejected)',
1397
+ });
1398
+ }
1399
+ const stderrText = pushResult.stderr.toString('utf8').trim();
1400
+ const rawPushDetail = pushResult.spawnError !== null
1401
+ ? `git push failed to spawn: ${pushResult.spawnError}`
1402
+ : pushResult.stdoutOverflow
1403
+ ? 'git push output exceeded maximum buffer size'
1404
+ : pushResult.timedOut
1405
+ ? 'git push timed out after 25000ms'
1406
+ : `git push exited with ${pushResult.code ?? pushResult.signal}${stderrText.length > 0 ? `: ${stderrText}` : ''}`;
1407
+ const scrubbedPushReason = truncateCodePoints(sanitizeReportText(rawPushDetail, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS);
1408
+ await updatePerRunMemoryReceipt(runDir, {
1409
+ ...baseReceiptRecord,
1410
+ state: 'uncertain',
1411
+ status: 'reconcile_required',
1412
+ pullRequestUrl: existingPrUrl,
1413
+ pullRequestNumber: existingPrNumber,
1414
+ reason: scrubbedPushReason,
1415
+ updatedAtMs: Date.now(),
1416
+ }, scrubber);
1417
+ return Object.freeze({
1418
+ status: 'reconcile_required',
1419
+ directory: memoryDirectory,
1420
+ proposalId: finalized.proposal.proposalId,
1421
+ entryCount: finalized.proposal.operations.length,
1422
+ rebased: casResult.rebased,
1423
+ branchName: memoryBranch,
1424
+ pullRequestUrl: existingPrUrl,
1425
+ pullRequestNumber: existingPrNumber,
1426
+ reason: scrubbedPushReason,
1427
+ });
1428
+ }
1429
+ if (isInlineMode) {
1430
+ await updatePerRunMemoryReceipt(runDir, {
1431
+ ...baseReceiptRecord,
1432
+ state: 'completed',
1433
+ status: 'updated',
1434
+ pullRequestUrl: existingPrUrl,
1435
+ pullRequestNumber: existingPrNumber,
1436
+ reason: null,
1437
+ updatedAtMs: Date.now(),
1438
+ }, scrubber);
1439
+ return Object.freeze({
1440
+ status: 'updated',
1441
+ directory: memoryDirectory,
1442
+ proposalId: finalized.proposal.proposalId,
1443
+ entryCount: finalized.proposal.operations.length,
1444
+ rebased: casResult.rebased,
1445
+ branchName: memoryBranch,
1446
+ pullRequestUrl: existingPrUrl,
1447
+ pullRequestNumber: existingPrNumber,
1448
+ reason: null,
1449
+ });
1450
+ }
1451
+ const isUpdate = openMemoryPr !== null;
1452
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1453
+ const apiHeaders = {
1454
+ accept: 'application/vnd.github+json',
1455
+ 'content-type': 'application/json',
1456
+ 'user-agent': 'loopwright-github-app',
1457
+ authorization: `Bearer ${options.githubToken}`,
1458
+ };
1459
+ const prEndpoint = openMemoryPr !== null
1460
+ ? `${apiBaseUrl}/repos/${options.repositoryFullName}/pulls/${openMemoryPr.number}`
1461
+ : `${apiBaseUrl}/repos/${options.repositoryFullName}/pulls`;
1462
+ let prRes;
1463
+ try {
1464
+ prRes = await fetchBoundedText(prEndpoint, fetchImpl, apiHeaders, 15_000, scrubber, {
1465
+ method: isUpdate ? 'PATCH' : 'POST',
1466
+ body: JSON.stringify(isUpdate
1467
+ ? { title: cleanTitle, body: cleanBody }
1468
+ : { title: cleanTitle, head: memoryBranch, base: targetBranch, body: cleanBody }),
1469
+ });
1470
+ }
1471
+ catch (transportErr) {
1472
+ const rawMsg = transportErr instanceof Error ? transportErr.message : String(transportErr);
1473
+ const transportReason = truncateCodePoints(sanitizeReportText(`memory pull request API transport error: ${rawMsg}`, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS);
1474
+ await updatePerRunMemoryReceipt(runDir, {
1475
+ ...baseReceiptRecord,
1476
+ state: 'uncertain',
1477
+ status: 'reconcile_required',
1478
+ pullRequestUrl: openMemoryPr?.htmlUrl ?? null,
1479
+ pullRequestNumber: openMemoryPr?.number ?? null,
1480
+ reason: transportReason,
1481
+ updatedAtMs: Date.now(),
1482
+ }, scrubber);
1483
+ return Object.freeze({
1484
+ status: 'reconcile_required',
1485
+ directory: memoryDirectory,
1486
+ proposalId: finalized.proposal.proposalId,
1487
+ entryCount: finalized.proposal.operations.length,
1488
+ rebased: casResult.rebased,
1489
+ branchName: memoryBranch,
1490
+ pullRequestUrl: openMemoryPr?.htmlUrl ?? null,
1491
+ pullRequestNumber: openMemoryPr?.number ?? null,
1492
+ reason: transportReason,
1493
+ });
1494
+ }
1495
+ if (!prRes.ok) {
1496
+ const httpErrReason = truncateCodePoints(sanitizeReportText(`memory pull request API failed (${prRes.status}): ${prRes.text}`, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS);
1497
+ await updatePerRunMemoryReceipt(runDir, {
1498
+ ...baseReceiptRecord,
1499
+ state: 'uncertain',
1500
+ status: 'reconcile_required',
1501
+ pullRequestUrl: openMemoryPr?.htmlUrl ?? null,
1502
+ pullRequestNumber: openMemoryPr?.number ?? null,
1503
+ reason: httpErrReason,
1504
+ updatedAtMs: Date.now(),
1505
+ }, scrubber);
1506
+ return Object.freeze({
1507
+ status: 'reconcile_required',
1508
+ directory: memoryDirectory,
1509
+ proposalId: finalized.proposal.proposalId,
1510
+ entryCount: finalized.proposal.operations.length,
1511
+ rebased: casResult.rebased,
1512
+ branchName: memoryBranch,
1513
+ pullRequestUrl: openMemoryPr?.htmlUrl ?? null,
1514
+ pullRequestNumber: openMemoryPr?.number ?? null,
1515
+ reason: httpErrReason,
1516
+ });
1517
+ }
1518
+ let parsedPr;
1519
+ try {
1520
+ parsedPr = JSON.parse(prRes.text);
1521
+ }
1522
+ catch {
1523
+ parsedPr = null;
1524
+ }
1525
+ let validatedPr = validateMemoryPullRequestApiResponse(parsedPr, {
1526
+ repositoryFullName: options.repositoryFullName,
1527
+ targetBranch,
1528
+ memoryBranch,
1529
+ headOid,
1530
+ existingPrNumber: openMemoryPr?.number ?? null,
1531
+ scrubber,
1532
+ });
1533
+ if (!validatedPr.ok && validatedPr.canConfirmViaReadOnlyGet && validatedPr.prNumber !== null) {
1534
+ const confirmUrl = `${apiBaseUrl}/repos/${options.repositoryFullName}/pulls/${validatedPr.prNumber}`;
1535
+ const readHeaders = {
1536
+ accept: 'application/vnd.github+json',
1537
+ 'user-agent': 'loopwright-github-app',
1538
+ authorization: `Bearer ${options.githubToken}`,
1539
+ };
1540
+ const readRes = await fetchBoundedText(confirmUrl, fetchImpl, readHeaders, 10_000, scrubber, { method: 'GET' }).catch(() => null);
1541
+ if (readRes !== null && readRes.ok) {
1542
+ let parsedGetPr;
1543
+ try {
1544
+ parsedGetPr = JSON.parse(readRes.text);
1545
+ }
1546
+ catch {
1547
+ parsedGetPr = null;
1548
+ }
1549
+ const revalidated = validateMemoryPullRequestApiResponse(parsedGetPr, {
1550
+ repositoryFullName: options.repositoryFullName,
1551
+ targetBranch,
1552
+ memoryBranch,
1553
+ headOid,
1554
+ existingPrNumber: validatedPr.prNumber,
1555
+ scrubber,
1556
+ });
1557
+ if (revalidated.ok) {
1558
+ const checkRemote = await execGitDetailed(cloneDir, [...protocolArgs, 'ls-remote', '--', resolvedRemote, `refs/heads/${memoryBranch}`], { env: gitAuthEnv, timeoutMs: 10_000 });
1559
+ const remoteStillMatches = checkRemote.spawnError === null
1560
+ && !checkRemote.stdoutOverflow
1561
+ && !checkRemote.timedOut
1562
+ && checkRemote.signal === null
1563
+ && checkRemote.code === 0
1564
+ && (checkRemote.stdout.toString('utf8').trim().split(/\s+/)[0]?.toLowerCase() ?? '') === headOid;
1565
+ if (remoteStillMatches) {
1566
+ validatedPr = revalidated;
1567
+ }
1568
+ }
1569
+ }
1570
+ }
1571
+ if (!validatedPr.ok) {
1572
+ const parseErrReason = validatedPr.reason;
1573
+ await updatePerRunMemoryReceipt(runDir, {
1574
+ ...baseReceiptRecord,
1575
+ state: 'uncertain',
1576
+ status: 'reconcile_required',
1577
+ pullRequestUrl: openMemoryPr?.htmlUrl ?? null,
1578
+ pullRequestNumber: openMemoryPr?.number ?? null,
1579
+ reason: parseErrReason,
1580
+ updatedAtMs: Date.now(),
1581
+ }, scrubber);
1582
+ return Object.freeze({
1583
+ status: 'reconcile_required',
1584
+ directory: memoryDirectory,
1585
+ proposalId: finalized.proposal.proposalId,
1586
+ entryCount: finalized.proposal.operations.length,
1587
+ rebased: casResult.rebased,
1588
+ branchName: memoryBranch,
1589
+ pullRequestUrl: openMemoryPr?.htmlUrl ?? null,
1590
+ pullRequestNumber: openMemoryPr?.number ?? null,
1591
+ reason: parseErrReason,
1592
+ });
1593
+ }
1594
+ const settledStatus = isUpdate ? 'updated' : 'published';
1595
+ await updatePerRunMemoryReceipt(runDir, {
1596
+ ...baseReceiptRecord,
1597
+ state: 'completed',
1598
+ status: settledStatus,
1599
+ pullRequestUrl: validatedPr.prUrl,
1600
+ pullRequestNumber: validatedPr.prNumber,
1601
+ reason: null,
1602
+ updatedAtMs: Date.now(),
1603
+ }, scrubber);
1604
+ return Object.freeze({
1605
+ status: settledStatus,
1606
+ directory: memoryDirectory,
1607
+ proposalId: finalized.proposal.proposalId,
1608
+ entryCount: finalized.proposal.operations.length,
1609
+ rebased: casResult.rebased,
1610
+ branchName: memoryBranch,
1611
+ pullRequestUrl: validatedPr.prUrl,
1612
+ pullRequestNumber: validatedPr.prNumber,
1613
+ reason: null,
1614
+ });
1615
+ }
1616
+ finally {
1617
+ await rm(memoryScratch, { recursive: true, force: true }).catch(() => undefined);
1618
+ }
1619
+ }
1620
+ catch (error) {
1621
+ const detail = error instanceof MemoryDiagnosticError
1622
+ ? `${error.code} at ${error.path}: ${error.detail}`
1623
+ : error instanceof Error
1624
+ ? error.message
1625
+ : String(error);
1626
+ const sanitizedReason = truncateCodePoints(sanitizeReportText(detail, { scrub: text => scrubber.scrub(text), singleLine: true }), MAX_REASON_CODEPOINTS);
1627
+ if (mutationDispatched) {
1628
+ return Object.freeze({
1629
+ status: 'reconcile_required',
1630
+ directory: memoryDirectory,
1631
+ proposalId: trackedProposalId,
1632
+ entryCount: trackedEntryCount,
1633
+ rebased: trackedRebased,
1634
+ branchName: trackedBranchName,
1635
+ pullRequestUrl: trackedPrUrl,
1636
+ pullRequestNumber: trackedPrNumber,
1637
+ reason: sanitizedReason,
1638
+ });
1639
+ }
1640
+ const isRefusal = error instanceof MemoryDiagnosticError
1641
+ || (error instanceof GitHubAppError && error.code === 'TASKPACK_SCOPE_VIOLATION');
1642
+ return Object.freeze({
1643
+ status: isRefusal ? 'refused' : 'failed',
1644
+ directory: memoryDirectory,
1645
+ proposalId: trackedProposalId,
1646
+ entryCount: isRefusal ? 0 : trackedEntryCount,
1647
+ rebased: trackedRebased,
1648
+ branchName: trackedBranchName,
1649
+ pullRequestUrl: trackedPrUrl,
1650
+ pullRequestNumber: trackedPrNumber,
1651
+ reason: sanitizedReason,
1652
+ });
1653
+ }
1654
+ }