@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,1847 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { constants as fsConstants } from 'node:fs';
4
+ import { chmod, lstat, mkdir, mkdtemp, open, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
7
+ import { digestArtifact, OVERLAY_LIMITS, } from '@loopwright/core';
8
+ import { collectControlRootSiblingPaths, collectGitHubSiblingPaths, } from './sandbox.js';
9
+ import { compileScopePatterns, effectiveProtectedPaths, extractTaskpackResourcePaths, isAllowedCandidateWrite, isProtectedCandidatePath, normalizeCandidateRelativePath, pathCoveredBy, resolveBaselineAlignmentConfig, resolveManifestControlRoot, } from './schema.js';
10
+ import { SecretScrubber } from './scrubber.js';
11
+ import { BASELINE_CONFLICT_REASON, BASELINE_CONFLICT_RESOURCE_ID, BASELINE_CONFLICT_RESOURCE_PATH, TaskpackError, } from './types.js';
12
+ import { buildCleanGitEnv, COMMIT_SHA_PATTERN, resolveGitExecutable, } from './upstreams.js';
13
+ export { BASELINE_CONFLICT_REASON, compileScopePatterns, isAllowedCandidateWrite, isProtectedCandidatePath, normalizeCandidateRelativePath, };
14
+ /**
15
+ * Line-anchored matcher for residual Git conflict markers (`<<<<<<<`, `|||||||`, `>>>>>>>`).
16
+ * Intentionally excludes standalone 7-character `=======` lines so Markdown/RST setext headings
17
+ * are not falsely flagged when no conflict open/ancestor/close marker is present.
18
+ */
19
+ export const BASELINE_CONFLICT_MARKER_PATTERN = /^(?:<{7,}(?:[ \t].*)?|\|{7,}(?:[ \t].*)?|>{7,}(?:[ \t].*)?)\r?$/m;
20
+ export const MAX_GIT_LIST_BYTES = 16 * 1024 * 1024;
21
+ const MAX_GIT_STDOUT_BYTES = MAX_GIT_LIST_BYTES;
22
+ const MAX_GIT_STDERR_BYTES = 262_144;
23
+ const MAX_CARRY_BLOB_BYTES = 64 * 1024 * 1024;
24
+ const DEFAULT_GIT_OBJECTS_MAX_FILES = 262_144;
25
+ const DEFAULT_GIT_OBJECTS_MAX_BYTES = 4 * 1024 * 1024 * 1024;
26
+ const MAX_GIT_OBJECTS_DEPTH = 16;
27
+ const MAX_GIT_ALTERNATES_BYTES = 65_536;
28
+ const MAX_COMMON_DIR_STDOUT_BYTES = 4_096;
29
+ const MAX_OID_STDOUT_BYTES = 256;
30
+ const MAX_SIZE_STDOUT_BYTES = 128;
31
+ const MIN_BLOB_STDOUT_HEADROOM_BYTES = 1_024;
32
+ const BLOB_STDOUT_PADDING_BYTES = 64;
33
+ const GIT_VERIFY_TIMEOUT_MS = 10_000;
34
+ const GIT_SHORT_OP_TIMEOUT_MS = 15_000;
35
+ const GIT_DEFAULT_TIMEOUT_MS = 20_000;
36
+ const GIT_MERGE_TREE_TIMEOUT_MS = 30_000;
37
+ const CONFLICT_BLOB_READ_MULTIPLIER = 8;
38
+ const MIN_CONFLICT_BLOB_READ_CAP_BYTES = 1_048_576;
39
+ const MAX_CONFLICT_SUMMARY_PATHS = 8;
40
+ const CONFLICT_CONTEXT_LINES = 2;
41
+ const MAX_MERGE_FILE_EXIT_CONFLICTS = 127;
42
+ const MAX_PATH_SEGMENT_BYTES = 255;
43
+ const OID_HEX_PATTERN = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
44
+ const SHA1_OID_HEX_PATTERN = /^[0-9a-f]{40}$/;
45
+ const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
46
+ const STREAM_CHUNK_BYTES = 1_048_576;
47
+ class BlobSizeCeilingExceededError extends TaskpackError {
48
+ actualBytes;
49
+ ceilingBytes;
50
+ constructor(oid, actualBytes, ceilingBytes) {
51
+ super('ACTION_INPUT_INVALID', `blob ${oid} (${actualBytes} bytes) exceeds ${ceilingBytes} byte ceiling`);
52
+ this.actualBytes = actualBytes;
53
+ this.ceilingBytes = ceilingBytes;
54
+ }
55
+ }
56
+ function compareLexical(a, b) {
57
+ if (a === b)
58
+ return 0;
59
+ return a < b ? -1 : 1;
60
+ }
61
+ function isSpecialGitTreeEntry(entry) {
62
+ return entry?.mode === '120000' || entry?.mode === '160000';
63
+ }
64
+ /** True when `path` or any directory prefix of `path` is a symlink (`120000`) or submodule (`160000`) in either tree. */
65
+ export function hasSymlinkAtOrAbove(path, baseEntries, sourceEntries) {
66
+ if (isSpecialGitTreeEntry(baseEntries.get(path)) || isSpecialGitTreeEntry(sourceEntries.get(path))) {
67
+ return true;
68
+ }
69
+ let slash = path.indexOf('/');
70
+ while (slash !== -1) {
71
+ const prefix = path.slice(0, slash);
72
+ if (isSpecialGitTreeEntry(baseEntries.get(prefix)) || isSpecialGitTreeEntry(sourceEntries.get(prefix))) {
73
+ return true;
74
+ }
75
+ slash = path.indexOf('/', slash + 1);
76
+ }
77
+ return false;
78
+ }
79
+ function normalizeGitRelativePath(raw) {
80
+ const clean = normalizeCandidateRelativePath(raw);
81
+ for (const part of clean.split('/')) {
82
+ if (part.toLowerCase() === '.git' || Buffer.byteLength(part, 'utf8') > MAX_PATH_SEGMENT_BYTES) {
83
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid path segment in "${raw}"`);
84
+ }
85
+ }
86
+ if (!digestArtifact(clean, new Uint8Array()).ok) {
87
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid artifact path "${raw}"`);
88
+ }
89
+ return clean;
90
+ }
91
+ /**
92
+ * Single source of truth deriving compiled `writablePaths`, `protectedPaths`, and control-plane
93
+ * sibling inventories directly from a `TaskpackManifest` (shared across `alignBaselineRevisions`
94
+ * and `compileDeclarativeTaskpack` without constructing stub `TaskContract` documents).
95
+ */
96
+ export function deriveManifestCompiledScope(options) {
97
+ const { manifest, repositoryRoot, taskpackPath, baseRevision, sourceRevision } = options;
98
+ const policyProfile = options.policyProfile ?? options.hostPolicy?.policyProfile ?? 'local';
99
+ const allowWorkflowWrites = (policyProfile === 'github'
100
+ && manifest.spec.execution?.capabilities.allowWorkflowWrites === true
101
+ && options.hostPolicy?.allowWorkflowWrites === true);
102
+ const { controlRoot, manifestPath } = resolveManifestControlRoot(manifest, taskpackPath);
103
+ const proposalPath = manifest.spec.proposal?.path;
104
+ const commandScripts = Object.freeze(manifest.spec.verification.localChecks.flatMap(check => (check.implementation === 'command.v1' && typeof check.parameters?.['script'] === 'string' && check.parameters['script'].length > 0
105
+ ? [check.parameters['script']]
106
+ : [])));
107
+ const allManifestInstructions = extractTaskpackResourcePaths([
108
+ ...(manifest.spec.instructions ?? []),
109
+ ...(manifest.spec.roles?.flatMap(r => r.instructions ?? []) ?? []),
110
+ ]);
111
+ const allManifestSkills = extractTaskpackResourcePaths([
112
+ ...(manifest.spec.skills ?? []),
113
+ ...(manifest.spec.roles?.flatMap(r => r.skills ?? []) ?? []),
114
+ ]);
115
+ const relativeToolchainPaths = Object.freeze(manifest.spec.verification.localChecks.flatMap(c => {
116
+ if (c.implementation !== 'command.v1')
117
+ return [];
118
+ const raw = c.parameters?.['toolchainPaths'];
119
+ return Array.isArray(raw) ? raw.filter((p) => typeof p === 'string' && !p.startsWith('/')) : [];
120
+ }));
121
+ const githubSiblings = options.githubSiblings ?? (policyProfile === 'github'
122
+ ? collectGitHubSiblingPaths({
123
+ repositoryRoot,
124
+ gitRevisions: [sourceRevision, baseRevision],
125
+ })
126
+ : Object.freeze([]));
127
+ const controlRootSiblingSet = options.controlRootSiblingSet ?? (proposalPath !== undefined
128
+ ? collectControlRootSiblingPaths({
129
+ repositoryRoot,
130
+ controlRoot,
131
+ proposalPath,
132
+ gitRevisions: [sourceRevision, baseRevision],
133
+ })
134
+ : Object.freeze({ prioritySiblings: Object.freeze([]), regularSiblings: Object.freeze([]) }));
135
+ const fullProtected = effectiveProtectedPaths(manifest.spec.scope.protected, {
136
+ policyProfile,
137
+ controlRoot,
138
+ manifestPath,
139
+ digestsLockfile: manifest.spec.execution?.digests.lockfile,
140
+ instructions: allManifestInstructions.length > 0 ? allManifestInstructions : undefined,
141
+ skills: allManifestSkills.length > 0 ? allManifestSkills : undefined,
142
+ preflightScript: manifest.spec.preflight?.script,
143
+ commandScripts,
144
+ toolchainPaths: relativeToolchainPaths.length > 0 ? relativeToolchainPaths : undefined,
145
+ proposalPath,
146
+ extraProtectedPaths: options.extraProtectedPaths,
147
+ priorityControlRootSiblings: controlRootSiblingSet.prioritySiblings,
148
+ controlRootSiblings: controlRootSiblingSet.regularSiblings,
149
+ allowWorkflowWrites,
150
+ githubSiblings,
151
+ });
152
+ const exactWritable = proposalPath !== undefined && pathCoveredBy(proposalPath, controlRoot)
153
+ ? new Set([proposalPath])
154
+ : undefined;
155
+ const writablePaths = compileScopePatterns(manifest.spec.scope.writable, 'writable', { exactEntries: exactWritable });
156
+ const protectedPaths = compileScopePatterns(fullProtected, 'protected');
157
+ return Object.freeze({
158
+ policyProfile,
159
+ allowWorkflowWrites,
160
+ controlRoot,
161
+ manifestPath,
162
+ proposalPath,
163
+ commandScripts,
164
+ allManifestInstructions,
165
+ allManifestSkills,
166
+ relativeToolchainPaths,
167
+ githubSiblings,
168
+ controlRootSiblingSet,
169
+ writablePaths,
170
+ protectedPaths,
171
+ });
172
+ }
173
+ /** Build a validated `CandidateScopeSnapshot` (`{ writablePaths, protectedPaths }`) directly from a `TaskpackManifest`. */
174
+ export function buildScopeSnapshotFromManifest(options) {
175
+ const derived = deriveManifestCompiledScope(options);
176
+ return Object.freeze({
177
+ writablePaths: derived.writablePaths,
178
+ protectedPaths: derived.protectedPaths,
179
+ });
180
+ }
181
+ /** True when `contract.spec.trustedContext.resources` stages the baseline conflict context resource. */
182
+ export function hasBaselineConflictResource(contract) {
183
+ return contract.spec.trustedContext.resources.some(res => res.id === BASELINE_CONFLICT_RESOURCE_ID);
184
+ }
185
+ /**
186
+ * True when `content` contains line-anchored Git conflict markers (`<<<<<<<`, `|||||||`, `>>>>>>>`).
187
+ * Decodes `Uint8Array` permissively so NUL bytes cannot hide conflict markers on adjacent lines,
188
+ * while ignoring standalone 7-character `=======` Markdown/RST setext underlines.
189
+ */
190
+ export function containsResidualGitConflictMarkers(content) {
191
+ const text = typeof content === 'string'
192
+ ? content
193
+ : new TextDecoder('utf-8', { fatal: false }).decode(content);
194
+ return BASELINE_CONFLICT_MARKER_PATTERN.test(text);
195
+ }
196
+ async function runIsolatedGit(repositoryRoot, args, env, options) {
197
+ const gitBin = resolveGitExecutable();
198
+ const timeoutMs = options?.timeoutMs ?? GIT_DEFAULT_TIMEOUT_MS;
199
+ const maxStdoutBytes = options?.maxStdoutBytes ?? MAX_GIT_STDOUT_BYTES;
200
+ return await new Promise(resolvePromise => {
201
+ const child = spawn(gitBin, [
202
+ '-c', 'core.hooksPath=/dev/null',
203
+ '-c', 'merge.renames=false',
204
+ '-c', 'gc.auto=0',
205
+ '-c', 'core.logAllRefUpdates=false',
206
+ '-c', 'protocol.file.allow=never',
207
+ '-c', 'protocol.ext.allow=never',
208
+ '-c', 'protocol.ssh.allow=never',
209
+ '-C', repositoryRoot,
210
+ ...args,
211
+ ], { env, stdio: ['pipe', 'pipe', 'pipe'] });
212
+ const stdoutChunks = [];
213
+ const stderrChunks = [];
214
+ let stdoutBytes = 0;
215
+ let stderrBytes = 0;
216
+ let settled = false;
217
+ let timedOut = false;
218
+ let stdoutOverflow = false;
219
+ const timer = setTimeout(() => {
220
+ timedOut = true;
221
+ child.kill('SIGKILL');
222
+ }, timeoutMs);
223
+ timer.unref?.();
224
+ const finish = (res) => {
225
+ if (settled)
226
+ return;
227
+ settled = true;
228
+ clearTimeout(timer);
229
+ resolvePromise(res);
230
+ };
231
+ child.stdin.on('error', () => undefined);
232
+ child.stdout.on('data', (chunk) => {
233
+ stdoutBytes += chunk.byteLength;
234
+ if (stdoutBytes > maxStdoutBytes) {
235
+ stdoutOverflow = true;
236
+ child.kill('SIGKILL');
237
+ return;
238
+ }
239
+ stdoutChunks.push(chunk);
240
+ });
241
+ child.stderr.on('data', (chunk) => {
242
+ if (stderrBytes >= MAX_GIT_STDERR_BYTES)
243
+ return;
244
+ const take = Math.min(chunk.byteLength, MAX_GIT_STDERR_BYTES - stderrBytes);
245
+ stderrBytes += take;
246
+ stderrChunks.push(chunk.subarray(0, take));
247
+ });
248
+ child.on('error', err => {
249
+ finish({
250
+ code: null,
251
+ signal: null,
252
+ timedOut,
253
+ stdoutOverflow,
254
+ spawnError: err.message,
255
+ stdout: Buffer.concat(stdoutChunks),
256
+ stderr: Buffer.concat(stderrChunks),
257
+ });
258
+ });
259
+ child.on('close', (code, signal) => {
260
+ finish({
261
+ code,
262
+ signal,
263
+ timedOut,
264
+ stdoutOverflow,
265
+ spawnError: null,
266
+ stdout: Buffer.concat(stdoutChunks),
267
+ stderr: Buffer.concat(stderrChunks),
268
+ });
269
+ });
270
+ if (options?.input !== undefined) {
271
+ const payload = Buffer.isBuffer(options.input) ? options.input : Buffer.from(options.input, 'utf8');
272
+ if (payload.byteLength > 0) {
273
+ child.stdin.end(payload);
274
+ return;
275
+ }
276
+ }
277
+ child.stdin.end();
278
+ });
279
+ }
280
+ async function execIsolatedGitChecked(repositoryRoot, args, env, options) {
281
+ const res = await runIsolatedGit(repositoryRoot, args, env, options);
282
+ if (res.spawnError !== null) {
283
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git ${args[0] ?? 'command'} failed to spawn: ${res.spawnError}`);
284
+ }
285
+ if (res.stdoutOverflow) {
286
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git ${args[0] ?? 'command'} output exceeded limit`);
287
+ }
288
+ if (res.timedOut) {
289
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git ${args[0] ?? 'command'} timed out`);
290
+ }
291
+ if (res.code !== 0 || res.signal !== null) {
292
+ const stderrText = res.stderr.toString('utf8').trim();
293
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git ${args[0] ?? 'command'} exited with ${String(res.code ?? res.signal)}${stderrText ? `: ${stderrText}` : ''}`);
294
+ }
295
+ return res.stdout;
296
+ }
297
+ async function cleanupPrivateTempDir(privateTempDir, scrubber, onLog) {
298
+ const unlockDirs = async (dir) => {
299
+ await chmod(dir, 0o700).catch(() => undefined);
300
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
301
+ for (const entry of entries) {
302
+ if (entry.isDirectory()) {
303
+ await unlockDirs(join(dir, entry.name));
304
+ }
305
+ else if (entry.isFile()) {
306
+ await chmod(join(dir, entry.name), 0o600).catch(() => undefined);
307
+ }
308
+ }
309
+ };
310
+ await unlockDirs(privateTempDir).catch(() => undefined);
311
+ try {
312
+ await rm(privateTempDir, { recursive: true, force: true });
313
+ }
314
+ catch (error) {
315
+ const detail = error instanceof Error ? error.message : String(error);
316
+ onLog?.(scrubber.scrub(`baseline-align warning: failed to remove temporary directory: ${detail}`));
317
+ }
318
+ }
319
+ async function assertObjectsDirNoSymlinks(objectsDir) {
320
+ let seenFiles = 0;
321
+ let totalBytes = 0;
322
+ const walk = async (cur, depth) => {
323
+ if (depth > MAX_GIT_OBJECTS_DEPTH) {
324
+ throw new TaskpackError('ACTION_INPUT_INVALID', `.git/objects exceeds maximum directory depth ${MAX_GIT_OBJECTS_DEPTH}`);
325
+ }
326
+ const st = await lstat(cur);
327
+ if (st.isSymbolicLink()) {
328
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `symbolic link "${cur}" is forbidden inside .git/objects`);
329
+ }
330
+ if (!st.isDirectory()) {
331
+ throw new TaskpackError('ACTION_INPUT_INVALID', `.git/objects path "${cur}" must be a directory`);
332
+ }
333
+ const names = (await readdir(cur)).sort();
334
+ for (const name of names) {
335
+ const child = join(cur, name);
336
+ const childStat = await lstat(child);
337
+ if (childStat.isSymbolicLink()) {
338
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `symbolic link "${child}" is forbidden inside .git/objects`);
339
+ }
340
+ if (childStat.isDirectory()) {
341
+ await walk(child, depth + 1);
342
+ }
343
+ else if (childStat.isFile()) {
344
+ seenFiles += 1;
345
+ totalBytes += childStat.size;
346
+ if (seenFiles > DEFAULT_GIT_OBJECTS_MAX_FILES || totalBytes > DEFAULT_GIT_OBJECTS_MAX_BYTES) {
347
+ throw new TaskpackError('ACTION_INPUT_INVALID', '.git/objects exceeds object file or byte ceiling');
348
+ }
349
+ }
350
+ }
351
+ };
352
+ await walk(objectsDir, 0);
353
+ }
354
+ export async function resolveReadOnlyAlternateObjectDirs(repositoryRoot) {
355
+ const dotGitStat = await lstat(join(repositoryRoot, '.git')).catch(() => null);
356
+ if (dotGitStat === null || dotGitStat.isSymbolicLink()) {
357
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'repository .git must exist and must not be a symbolic link');
358
+ }
359
+ const cleanEnv = buildCleanGitEnv({
360
+ GIT_CONFIG_NOSYSTEM: '1',
361
+ GIT_CONFIG_GLOBAL: '/dev/null',
362
+ });
363
+ const commonDirRaw = (await execIsolatedGitChecked(repositoryRoot, ['rev-parse', '--path-format=absolute', '--git-common-dir'], cleanEnv, { timeoutMs: GIT_VERIFY_TIMEOUT_MS, maxStdoutBytes: MAX_COMMON_DIR_STDOUT_BYTES })).toString('utf8').trim();
364
+ if (commonDirRaw.length === 0 || !isAbsolute(commonDirRaw)) {
365
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'failed to resolve repository git-common-dir');
366
+ }
367
+ const commonStat = await lstat(commonDirRaw);
368
+ if (commonStat.isSymbolicLink() || !commonStat.isDirectory()) {
369
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'repository git-common-dir must be a non-symlink directory');
370
+ }
371
+ const hostObjectsDir = join(commonDirRaw, 'objects');
372
+ await assertObjectsDirNoSymlinks(hostObjectsDir);
373
+ const realHostObjects = await realpath(hostObjectsDir);
374
+ const alternates = [realHostObjects];
375
+ const alternatesFile = join(hostObjectsDir, 'info', 'alternates');
376
+ const altStat = await lstat(alternatesFile).catch(() => null);
377
+ if (altStat !== null) {
378
+ if (altStat.isSymbolicLink() || !altStat.isFile() || altStat.size > MAX_GIT_ALTERNATES_BYTES) {
379
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'invalid .git/objects/info/alternates file');
380
+ }
381
+ const rawAlternates = await readFile(alternatesFile, 'utf8');
382
+ for (const rawLine of rawAlternates.split(/\r?\n/)) {
383
+ const trimmed = rawLine.trim();
384
+ if (trimmed.length === 0 || trimmed.startsWith('#'))
385
+ continue;
386
+ const resolvedAlt = isAbsolute(trimmed) ? resolve(trimmed) : resolve(hostObjectsDir, trimmed);
387
+ const st = await lstat(resolvedAlt).catch(() => null);
388
+ if (st !== null && !st.isSymbolicLink() && st.isDirectory()) {
389
+ alternates.push(await realpath(resolvedAlt));
390
+ }
391
+ }
392
+ }
393
+ return Object.freeze([...new Set(alternates)]);
394
+ }
395
+ /** List all Git tree entries (`ls-tree -r -z --full-tree`) at `revision` using bounded isolated Git execution. */
396
+ export async function listTreeEntriesAtRevision(repositoryRoot, revision, env) {
397
+ const stdout = await execIsolatedGitChecked(repositoryRoot, ['ls-tree', '-r', '-z', '--full-tree', revision], env, { maxStdoutBytes: MAX_GIT_STDOUT_BYTES, timeoutMs: GIT_MERGE_TREE_TIMEOUT_MS });
398
+ if (stdout.byteLength > 0 && stdout.at(-1) !== 0) {
399
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'git ls-tree output exceeded boundary');
400
+ }
401
+ const entries = new Map();
402
+ const text = stdout.byteLength > 0 ? new TextDecoder('utf-8', { fatal: true }).decode(stdout) : '';
403
+ for (const part of text.split('\0')) {
404
+ if (part.length === 0)
405
+ continue;
406
+ const tabIdx = part.indexOf('\t');
407
+ if (tabIdx <= 0)
408
+ continue;
409
+ const fields = part.slice(0, tabIdx).split(' ');
410
+ const path = part.slice(tabIdx + 1);
411
+ if (fields[0] !== undefined && fields[1] !== undefined && fields[2] !== undefined) {
412
+ entries.set(path, { mode: fields[0], type: fields[1], oid: fields[2] });
413
+ }
414
+ }
415
+ return entries;
416
+ }
417
+ async function readBlobSizeIsolated(repositoryRoot, oid, env) {
418
+ const raw = (await execIsolatedGitChecked(repositoryRoot, ['cat-file', '-s', oid], env, { timeoutMs: GIT_SHORT_OP_TIMEOUT_MS, maxStdoutBytes: MAX_SIZE_STDOUT_BYTES })).toString('utf8').trim();
419
+ const size = Number(raw);
420
+ if (!Number.isSafeInteger(size) || size < 0) {
421
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid git blob size for ${oid}`);
422
+ }
423
+ return size;
424
+ }
425
+ async function readVerifiedBlobIsolated(repositoryRoot, oid, maxBytes, env) {
426
+ const size = await readBlobSizeIsolated(repositoryRoot, oid, env);
427
+ if (size > maxBytes) {
428
+ throw new BlobSizeCeilingExceededError(oid, size, maxBytes);
429
+ }
430
+ const bytes = await execIsolatedGitChecked(repositoryRoot, ['cat-file', 'blob', oid], env, {
431
+ timeoutMs: GIT_MERGE_TREE_TIMEOUT_MS,
432
+ maxStdoutBytes: Math.max(MIN_BLOB_STDOUT_HEADROOM_BYTES, size + BLOB_STDOUT_PADDING_BYTES),
433
+ });
434
+ if (bytes.byteLength !== size) {
435
+ throw new TaskpackError('ACTION_INPUT_INVALID', `blob ${oid} byteLength mismatch`);
436
+ }
437
+ const algo = oid.length === 64 ? 'sha256' : 'sha1';
438
+ const actualOid = createHash(algo).update(`blob ${bytes.byteLength}\0`).update(bytes).digest('hex');
439
+ if (actualOid !== oid) {
440
+ throw new TaskpackError('ACTION_INPUT_INVALID', `blob ${oid} digest verification failed`);
441
+ }
442
+ return bytes;
443
+ }
444
+ async function computeBlobSha256Isolated(repositoryRoot, oid, env, maxBytes = OVERLAY_LIMITS.maxMaxBytes) {
445
+ const bytes = await readVerifiedBlobIsolated(repositoryRoot, oid, maxBytes, env);
446
+ return {
447
+ sha256: createHash('sha256').update(bytes).digest('hex'),
448
+ byteLength: bytes.byteLength,
449
+ };
450
+ }
451
+ function parseMergeTreeWriteTreeOutput(stdout, clean) {
452
+ const decoded = new TextDecoder('utf-8', { fatal: false }).decode(stdout);
453
+ const tokens = decoded.split('\0');
454
+ const treeCandidate = (tokens[0] ?? '').trim();
455
+ if (!OID_HEX_PATTERN.test(treeCandidate)) {
456
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'git merge-tree --write-tree returned an invalid tree OID');
457
+ }
458
+ if (clean) {
459
+ return {
460
+ mergedTreeOid: treeCandidate,
461
+ rawConflictPaths: Object.freeze([]),
462
+ messages: Object.freeze([]),
463
+ };
464
+ }
465
+ const rawPaths = [];
466
+ let cursor = 1;
467
+ while (cursor < tokens.length && tokens[cursor] !== '') {
468
+ rawPaths.push(tokens[cursor]);
469
+ cursor += 1;
470
+ }
471
+ if (cursor < tokens.length && tokens[cursor] === '') {
472
+ cursor += 1;
473
+ }
474
+ const messages = [];
475
+ while (cursor < tokens.length && tokens[cursor] !== '') {
476
+ const countStr = tokens[cursor];
477
+ if (!/^\d+$/.test(countStr))
478
+ break;
479
+ const pathCount = Number.parseInt(countStr, 10);
480
+ if (!Number.isSafeInteger(pathCount) || cursor + 2 + pathCount >= tokens.length) {
481
+ break;
482
+ }
483
+ const paths = tokens.slice(cursor + 1, cursor + 1 + pathCount);
484
+ const conflictType = tokens[cursor + 1 + pathCount];
485
+ const message = tokens[cursor + 2 + pathCount];
486
+ if (conflictType.startsWith('CONFLICT')) {
487
+ messages.push(Object.freeze({
488
+ paths: Object.freeze(paths),
489
+ conflictType,
490
+ message,
491
+ }));
492
+ }
493
+ cursor += 3 + pathCount;
494
+ }
495
+ return {
496
+ mergedTreeOid: treeCandidate,
497
+ rawConflictPaths: Object.freeze(rawPaths),
498
+ messages: Object.freeze(messages),
499
+ };
500
+ }
501
+ function stripCollisionSuffix(rawPath, baseEntries, sourceEntries) {
502
+ if (baseEntries.has(rawPath) || sourceEntries.has(rawPath))
503
+ return rawPath;
504
+ const tildeMatch = /^(.+)~[0-9a-f]{40,64}$/.exec(rawPath);
505
+ if (tildeMatch !== null) {
506
+ const stripped = tildeMatch[1];
507
+ if (baseEntries.has(stripped)
508
+ || sourceEntries.has(stripped)
509
+ || [...baseEntries.keys()].some(k => k.startsWith(`${stripped}/`))
510
+ || [...sourceEntries.keys()].some(k => k.startsWith(`${stripped}/`))) {
511
+ return stripped;
512
+ }
513
+ }
514
+ return rawPath;
515
+ }
516
+ async function runIndexThreeWayMergeFallback(options) {
517
+ const { repositoryRoot, baseRevision, sourceRevision, mergeBase, privateTempDir, isolatedEnv, retainConflictText } = options;
518
+ const indexFile = join(privateTempDir, 'fallback-index');
519
+ const indexEnv = {
520
+ ...isolatedEnv,
521
+ GIT_INDEX_FILE: indexFile,
522
+ };
523
+ const emptyTreeOid = (await execIsolatedGitChecked(repositoryRoot, ['mktree'], indexEnv, { input: '' })).toString('utf8').trim();
524
+ const baseAncestorTree = mergeBase !== null ? `${mergeBase}^{tree}` : emptyTreeOid;
525
+ await execIsolatedGitChecked(repositoryRoot, ['read-tree', '-m', '--aggressive', baseAncestorTree, `${baseRevision}^{tree}`, `${sourceRevision}^{tree}`], indexEnv);
526
+ const unmergedRaw = (await execIsolatedGitChecked(repositoryRoot, ['ls-files', '-u', '-z'], indexEnv)).toString('utf8');
527
+ const stagesByPath = new Map();
528
+ for (const record of unmergedRaw.split('\0')) {
529
+ if (record.length === 0)
530
+ continue;
531
+ const tabIdx = record.indexOf('\t');
532
+ if (tabIdx <= 0)
533
+ continue;
534
+ const meta = record.slice(0, tabIdx).split(/\s+/);
535
+ const path = record.slice(tabIdx + 1);
536
+ const mode = meta[0];
537
+ const oid = meta[1];
538
+ const stageNum = Number.parseInt(meta[2] ?? '0', 10);
539
+ if (!stagesByPath.has(path)) {
540
+ stagesByPath.set(path, new Map());
541
+ }
542
+ stagesByPath.get(path).set(stageNum, { mode, oid });
543
+ }
544
+ const conflictPaths = [];
545
+ const conflictMessages = [];
546
+ const extractedHunksByPath = new Map();
547
+ const conflictedStage2ByPath = new Map();
548
+ const mergeScratchDir = join(privateTempDir, 'merge-files');
549
+ await mkdir(mergeScratchDir, { recursive: true, mode: 0o700 });
550
+ let retainedConflictHunkBytes = 0;
551
+ for (const [path, stageMap] of [...stagesByPath.entries()].sort((a, b) => compareLexical(a[0], b[0]))) {
552
+ const s1 = stageMap.get(1);
553
+ const s2 = stageMap.get(2);
554
+ const s3 = stageMap.get(3);
555
+ // Stage-1-only entry: path deleted cleanly without opposing modification -> resolved deletion!
556
+ if (s1 !== undefined && s2 === undefined && s3 === undefined) {
557
+ await execIsolatedGitChecked(repositoryRoot, ['update-index', '--force-remove', '-z', '--stdin'], indexEnv, { input: `${path}\0` });
558
+ continue;
559
+ }
560
+ const allRegular = [s1, s2, s3].every(s => s === undefined || s.mode === '100644' || s.mode === '100755');
561
+ if (!allRegular || (s2 === undefined && s3 === undefined)) {
562
+ conflictPaths.push(path);
563
+ conflictedStage2ByPath.set(path, s2);
564
+ conflictMessages.push({
565
+ paths: [path],
566
+ conflictType: 'CONFLICT (special)',
567
+ message: `CONFLICT (special): non-regular merge conflict in ${path}`,
568
+ });
569
+ continue;
570
+ }
571
+ if (s2 === undefined || s3 === undefined) {
572
+ conflictPaths.push(path);
573
+ conflictedStage2ByPath.set(path, s2);
574
+ conflictMessages.push({
575
+ paths: [path],
576
+ conflictType: 'CONFLICT (modify/delete)',
577
+ message: `CONFLICT (modify/delete): ${path}`,
578
+ });
579
+ continue;
580
+ }
581
+ // Resolve trivial content cases (one side unchanged from ancestor, or both sides identical OID)
582
+ // BEFORE binary NUL checks so a mode-only change on one side + binary byte edit on the other
583
+ // resolves cleanly just like native `git merge-tree --write-tree`.
584
+ const trivialOid = s1 !== undefined
585
+ ? (s2.oid === s1.oid ? s3.oid : (s3.oid === s1.oid || s2.oid === s3.oid ? s2.oid : null))
586
+ : (s2.oid === s3.oid ? s2.oid : null);
587
+ if (trivialOid !== null) {
588
+ const resolvedMode = s1 !== undefined
589
+ ? (s1.mode === s2.mode
590
+ ? (s3.mode === '100755' ? '100755' : '100644')
591
+ : (s1.mode === s3.mode || s2.mode === s3.mode
592
+ ? (s2.mode === '100755' ? '100755' : '100644')
593
+ : null))
594
+ : (s2.mode === s3.mode ? (s2.mode === '100755' ? '100755' : '100644') : null);
595
+ if (resolvedMode === null) {
596
+ conflictPaths.push(path);
597
+ conflictedStage2ByPath.set(path, s2);
598
+ conflictMessages.push({
599
+ paths: [path],
600
+ conflictType: 'CONFLICT (distinct modes)',
601
+ message: `CONFLICT (distinct modes): ${path}`,
602
+ });
603
+ continue;
604
+ }
605
+ await execIsolatedGitChecked(repositoryRoot, ['update-index', '--force-remove', '-z', '--stdin'], indexEnv, { input: `${path}\0` });
606
+ await execIsolatedGitChecked(repositoryRoot, ['update-index', '-z', '--index-info'], indexEnv, { input: `${resolvedMode} blob ${trivialOid}\t${path}\0` });
607
+ continue;
608
+ }
609
+ const baseBytes = s1 !== undefined
610
+ ? await readVerifiedBlobIsolated(repositoryRoot, s1.oid, MAX_CARRY_BLOB_BYTES, indexEnv)
611
+ : Buffer.alloc(0);
612
+ const targetBytes = await readVerifiedBlobIsolated(repositoryRoot, s2.oid, MAX_CARRY_BLOB_BYTES, indexEnv);
613
+ const sourceBytes = await readVerifiedBlobIsolated(repositoryRoot, s3.oid, MAX_CARRY_BLOB_BYTES, indexEnv);
614
+ if (baseBytes.includes(0) || targetBytes.includes(0) || sourceBytes.includes(0)) {
615
+ conflictPaths.push(path);
616
+ conflictedStage2ByPath.set(path, s2);
617
+ conflictMessages.push({
618
+ paths: [path],
619
+ conflictType: 'CONFLICT (binary)',
620
+ message: `CONFLICT (binary): binary merge conflict in ${path}`,
621
+ });
622
+ continue;
623
+ }
624
+ const fBase = join(mergeScratchDir, 'anc');
625
+ const fTarget = join(mergeScratchDir, 'tgt');
626
+ const fSource = join(mergeScratchDir, 'src');
627
+ await writeFile(fBase, baseBytes, { mode: 0o600 });
628
+ await writeFile(fTarget, targetBytes, { mode: 0o600 });
629
+ await writeFile(fSource, sourceBytes, { mode: 0o600 });
630
+ const mergeRes = await runIsolatedGit(repositoryRoot, [
631
+ 'merge-file',
632
+ '-p',
633
+ '-L', baseRevision,
634
+ '-L', mergeBase ?? 'merge-base',
635
+ '-L', sourceRevision,
636
+ fTarget,
637
+ fBase,
638
+ fSource,
639
+ ], indexEnv, { maxStdoutBytes: MAX_CARRY_BLOB_BYTES });
640
+ if (mergeRes.code === 0 && mergeRes.signal === null && !mergeRes.timedOut && !mergeRes.stdoutOverflow) {
641
+ const mergedOid = (await execIsolatedGitChecked(repositoryRoot, ['hash-object', '-w', '--stdin'], indexEnv, { input: mergeRes.stdout })).toString('utf8').trim();
642
+ const mergedMode = s1?.mode === s2.mode && (s3.mode === '100644' || s3.mode === '100755')
643
+ ? s3.mode
644
+ : (s2.mode === '100755' ? '100755' : '100644');
645
+ await execIsolatedGitChecked(repositoryRoot, ['update-index', '--force-remove', '-z', '--stdin'], indexEnv, { input: `${path}\0` });
646
+ await execIsolatedGitChecked(repositoryRoot, ['update-index', '-z', '--index-info'], indexEnv, { input: `${mergedMode} blob ${mergedOid}\t${path}\0` });
647
+ }
648
+ else if (mergeRes.code !== null && mergeRes.code > 0 && mergeRes.code <= MAX_MERGE_FILE_EXIT_CONFLICTS) {
649
+ conflictPaths.push(path);
650
+ conflictedStage2ByPath.set(path, s2);
651
+ if (retainConflictText !== undefined && conflictPaths.length <= retainConflictText.maxConflictFiles) {
652
+ if (mergeRes.stdoutOverflow || mergeRes.stdout.includes(0)) {
653
+ extractedHunksByPath.set(path, 'failed');
654
+ }
655
+ else {
656
+ let mergedConflictText;
657
+ try {
658
+ mergedConflictText = new TextDecoder('utf-8', { fatal: true }).decode(mergeRes.stdout);
659
+ }
660
+ catch {
661
+ mergedConflictText = null;
662
+ }
663
+ if (mergedConflictText === null) {
664
+ extractedHunksByPath.set(path, 'failed');
665
+ }
666
+ else {
667
+ const remainingBudget = Math.max(0, retainConflictText.maxTotalConflictBytes - retainedConflictHunkBytes);
668
+ const extracted = extractConflictHunksFromMergedText(mergedConflictText, retainConflictText.scrubber, remainingBudget);
669
+ if (extracted !== null) {
670
+ extractedHunksByPath.set(path, extracted);
671
+ retainedConflictHunkBytes += extracted.totalHunkBytes;
672
+ }
673
+ else {
674
+ extractedHunksByPath.set(path, 'failed');
675
+ }
676
+ }
677
+ }
678
+ }
679
+ conflictMessages.push({
680
+ paths: [path],
681
+ conflictType: s1 === undefined ? 'CONFLICT (add/add)' : 'CONFLICT (contents)',
682
+ message: `CONFLICT (content): Merge conflict in ${path}`,
683
+ });
684
+ }
685
+ else {
686
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git merge-file failed for "${path}"`);
687
+ }
688
+ }
689
+ // Always resolve remaining unmerged index entries in the private temp index so `git write-tree`
690
+ // materializes a real merged tree preserving all clean 3-way merges and `baseRevision`-only edits/additions!
691
+ for (const [path, s2] of conflictedStage2ByPath.entries()) {
692
+ await execIsolatedGitChecked(repositoryRoot, ['update-index', '--force-remove', '-z', '--stdin'], indexEnv, { input: `${path}\0` });
693
+ if (s2 !== undefined && (s2.mode === '100644' || s2.mode === '100755')) {
694
+ await execIsolatedGitChecked(repositoryRoot, ['update-index', '-z', '--index-info'], indexEnv, { input: `${s2.mode} blob ${s2.oid}\t${path}\0` });
695
+ }
696
+ }
697
+ const mergedTreeOid = (await execIsolatedGitChecked(repositoryRoot, ['write-tree'], indexEnv)).toString('utf8').trim();
698
+ if (conflictPaths.length > 0) {
699
+ return {
700
+ clean: false,
701
+ mergeBase,
702
+ mergedTreeOid,
703
+ conflictPaths: Object.freeze([...new Set(conflictPaths)].sort(compareLexical)),
704
+ conflictMessages: Object.freeze(conflictMessages),
705
+ extractedHunksByPath,
706
+ };
707
+ }
708
+ return {
709
+ clean: true,
710
+ mergeBase,
711
+ mergedTreeOid,
712
+ conflictPaths: Object.freeze([]),
713
+ conflictMessages: Object.freeze([]),
714
+ extractedHunksByPath,
715
+ };
716
+ }
717
+ async function runIsolatedThreeWayMergeProbe(options) {
718
+ const { repositoryRoot, baseRevision, sourceRevision, privateTempDir, isolatedEnv, baseEntries, sourceEntries, forceIndexFallback, retainConflictText, } = options;
719
+ const mbRes = await runIsolatedGit(repositoryRoot, ['merge-base', baseRevision, sourceRevision], isolatedEnv, { timeoutMs: GIT_SHORT_OP_TIMEOUT_MS, maxStdoutBytes: MAX_OID_STDOUT_BYTES });
720
+ if (mbRes.spawnError !== null || mbRes.timedOut || mbRes.stdoutOverflow || mbRes.signal !== null) {
721
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git merge-base failed (${String(mbRes.spawnError ?? mbRes.signal ?? 'timeout/overflow')})`);
722
+ }
723
+ const mbTrimmed = mbRes.stdout.toString('utf8').trim();
724
+ let mergeBase;
725
+ if (mbRes.code === 0) {
726
+ if (!OID_HEX_PATTERN.test(mbTrimmed)) {
727
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'git merge-base returned an invalid commit OID');
728
+ }
729
+ mergeBase = mbTrimmed;
730
+ }
731
+ else if (mbRes.code === 1 && mbTrimmed.length === 0) {
732
+ mergeBase = null;
733
+ }
734
+ else {
735
+ const stderrText = mbRes.stderr.toString('utf8').trim();
736
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git merge-base exited with ${String(mbRes.code)}${stderrText ? `: ${stderrText}` : ''}`);
737
+ }
738
+ if (forceIndexFallback === true) {
739
+ return await runIndexThreeWayMergeFallback({
740
+ repositoryRoot,
741
+ baseRevision,
742
+ sourceRevision,
743
+ mergeBase,
744
+ privateTempDir,
745
+ isolatedEnv,
746
+ retainConflictText,
747
+ });
748
+ }
749
+ const mtRes = await runIsolatedGit(repositoryRoot, [
750
+ 'merge-tree',
751
+ '--write-tree',
752
+ '--messages',
753
+ '--name-only',
754
+ '--allow-unrelated-histories',
755
+ '-z',
756
+ baseRevision,
757
+ sourceRevision,
758
+ ], isolatedEnv, { timeoutMs: GIT_MERGE_TREE_TIMEOUT_MS, maxStdoutBytes: MAX_GIT_STDOUT_BYTES });
759
+ if (mtRes.code === 129 || mtRes.stderr.toString('utf8').includes('unknown option')) {
760
+ return await runIndexThreeWayMergeFallback({
761
+ repositoryRoot,
762
+ baseRevision,
763
+ sourceRevision,
764
+ mergeBase,
765
+ privateTempDir,
766
+ isolatedEnv,
767
+ retainConflictText,
768
+ });
769
+ }
770
+ if (mtRes.spawnError !== null || mtRes.timedOut || mtRes.stdoutOverflow || (mtRes.code !== 0 && mtRes.code !== 1)) {
771
+ const stderrText = mtRes.stderr.toString('utf8').trim();
772
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git merge-tree --write-tree failed (${String(mtRes.code ?? mtRes.signal)})${stderrText ? `: ${stderrText}` : ''}`);
773
+ }
774
+ const clean = mtRes.code === 0;
775
+ const parsed = parseMergeTreeWriteTreeOutput(mtRes.stdout, clean);
776
+ const normalizedConflictSet = new Set();
777
+ for (const rawPath of parsed.rawConflictPaths) {
778
+ normalizedConflictSet.add(stripCollisionSuffix(rawPath, baseEntries, sourceEntries));
779
+ }
780
+ for (const msg of parsed.messages) {
781
+ for (const rawPath of msg.paths) {
782
+ normalizedConflictSet.add(stripCollisionSuffix(rawPath, baseEntries, sourceEntries));
783
+ }
784
+ }
785
+ const conflictPaths = [...normalizedConflictSet].sort(compareLexical);
786
+ return {
787
+ clean: clean && conflictPaths.length === 0,
788
+ mergeBase,
789
+ mergedTreeOid: parsed.mergedTreeOid,
790
+ conflictPaths: Object.freeze(conflictPaths),
791
+ conflictMessages: parsed.messages,
792
+ extractedHunksByPath: new Map(),
793
+ };
794
+ }
795
+ function extractConflictHunksFromMergedText(mergedConflictText, scrubber, maxConflictBytes) {
796
+ const normalized = mergedConflictText.replace(/\r\n?/g, '\n');
797
+ const lines = normalized.split('\n');
798
+ const hunks = [];
799
+ let totalHunkBytes = 0;
800
+ let i = 0;
801
+ const openMarkerRe = /^<{7}(?: |$)/;
802
+ const closeMarkerRe = /^>{7}(?: |$)/;
803
+ while (i < lines.length) {
804
+ const line = lines[i];
805
+ if (openMarkerRe.test(line)) {
806
+ const startIdx = i;
807
+ let endIdx = -1;
808
+ let depth = 1;
809
+ for (let j = i + 1; j < lines.length; j += 1) {
810
+ const cur = lines[j];
811
+ if (openMarkerRe.test(cur)) {
812
+ depth += 1;
813
+ }
814
+ else if (closeMarkerRe.test(cur)) {
815
+ depth -= 1;
816
+ if (depth === 0) {
817
+ endIdx = j;
818
+ break;
819
+ }
820
+ }
821
+ }
822
+ if (endIdx === -1) {
823
+ return null;
824
+ }
825
+ const contextBefore = Math.max(0, startIdx - CONFLICT_CONTEXT_LINES);
826
+ const contextAfter = Math.min(lines.length - 1, endIdx + CONFLICT_CONTEXT_LINES);
827
+ const rawBlock = lines.slice(contextBefore, contextAfter + 1).join('\n');
828
+ const scrubbedBlock = scrubber.scrub(rawBlock);
829
+ scrubber.assertClean(scrubbedBlock, BASELINE_CONFLICT_RESOURCE_PATH);
830
+ const blockBytes = Buffer.byteLength(scrubbedBlock, 'utf8');
831
+ totalHunkBytes += blockBytes;
832
+ if (totalHunkBytes > maxConflictBytes) {
833
+ return null;
834
+ }
835
+ hunks.push(Object.freeze({
836
+ index: hunks.length,
837
+ startLine: contextBefore + 1,
838
+ endLine: contextAfter + 1,
839
+ block: scrubbedBlock,
840
+ }));
841
+ i = endIdx + 1;
842
+ continue;
843
+ }
844
+ i += 1;
845
+ }
846
+ if (hunks.length === 0)
847
+ return null;
848
+ return {
849
+ hunks: Object.freeze(hunks),
850
+ totalHunkBytes,
851
+ };
852
+ }
853
+ async function computeWritableCarryDeltaFromMergedTree(options) {
854
+ const { repositoryRoot, snapshot, baseEntries, sourceEntries, mergedEntries, excludedConflictPaths, isolatedEnv, } = options;
855
+ const carryRemovals = [];
856
+ for (const [path, baseEntry] of [...baseEntries.entries()].sort((a, b) => compareLexical(a[0], b[0]))) {
857
+ if (excludedConflictPaths.has(path))
858
+ continue;
859
+ if (baseEntry.mode !== '100644' && baseEntry.mode !== '100755')
860
+ continue;
861
+ const mergedEntry = mergedEntries.get(path);
862
+ if (mergedEntry !== undefined && (mergedEntry.mode === '100644' || mergedEntry.mode === '100755')) {
863
+ continue;
864
+ }
865
+ if (!isAllowedCandidateWrite(path, snapshot))
866
+ continue;
867
+ if (hasSymlinkAtOrAbove(path, baseEntries, sourceEntries))
868
+ continue;
869
+ normalizeGitRelativePath(path);
870
+ carryRemovals.push(path);
871
+ }
872
+ const carryUpdates = [];
873
+ let totalCarryBytes = 0;
874
+ for (const [path, mergedEntry] of [...mergedEntries.entries()].sort((a, b) => compareLexical(a[0], b[0]))) {
875
+ if (excludedConflictPaths.has(path))
876
+ continue;
877
+ if (mergedEntry.mode !== '100644' && mergedEntry.mode !== '100755')
878
+ continue;
879
+ const baseEntry = baseEntries.get(path);
880
+ if (baseEntry !== undefined && baseEntry.mode === mergedEntry.mode && baseEntry.oid === mergedEntry.oid) {
881
+ continue;
882
+ }
883
+ if (!isAllowedCandidateWrite(path, snapshot))
884
+ continue;
885
+ if (hasSymlinkAtOrAbove(path, baseEntries, sourceEntries))
886
+ continue;
887
+ normalizeGitRelativePath(path);
888
+ const sourceEntry = sourceEntries.get(path);
889
+ if (sourceEntry !== undefined && sourceEntry.oid === mergedEntry.oid) {
890
+ carryUpdates.push(Object.freeze({
891
+ path,
892
+ mode: mergedEntry.mode,
893
+ oid: mergedEntry.oid,
894
+ }));
895
+ continue;
896
+ }
897
+ const remainingCarryBytes = MAX_CARRY_BLOB_BYTES - totalCarryBytes;
898
+ if (remainingCarryBytes <= 0) {
899
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: synthesized 3-way carry blobs exceed aggregate ${MAX_CARRY_BLOB_BYTES} byte budget`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
900
+ }
901
+ const mergedBytes = await readVerifiedBlobIsolated(repositoryRoot, mergedEntry.oid, remainingCarryBytes, isolatedEnv);
902
+ totalCarryBytes += mergedBytes.byteLength;
903
+ const sha256 = createHash('sha256').update(mergedBytes).digest('hex');
904
+ carryUpdates.push(Object.freeze({
905
+ path,
906
+ mode: mergedEntry.mode,
907
+ oid: mergedEntry.oid,
908
+ byteLength: mergedBytes.byteLength,
909
+ sha256,
910
+ bytes: mergedBytes,
911
+ }));
912
+ }
913
+ return {
914
+ carryRemovals: Object.freeze(carryRemovals),
915
+ carryUpdates: Object.freeze(carryUpdates),
916
+ };
917
+ }
918
+ /**
919
+ * Run an isolated 3-way baseline alignment probe in a private temporary `GIT_OBJECT_DIRECTORY`
920
+ * (with read-only `GIT_ALTERNATE_OBJECT_DIRECTORIES`, hooks disabled, and rename detection disabled),
921
+ * guaranteeing ZERO new objects, ref mutations, or working-tree mutations in the host repository.
922
+ */
923
+ export async function alignBaselineRevisions(options) {
924
+ const policy = resolveBaselineAlignmentConfig(options.manifest?.spec.baselineAlignment, options.baselineAlignment);
925
+ const scrubber = options.scrubber ?? new SecretScrubber();
926
+ const baseRevision = options.baseRevision.trim();
927
+ const sourceRevision = options.sourceRevision.trim();
928
+ if (baseRevision === sourceRevision) {
929
+ return Object.freeze({
930
+ disposition: 'clean',
931
+ status: 'same_revision',
932
+ policy,
933
+ baseRevision,
934
+ sourceRevision,
935
+ mergeBase: baseRevision,
936
+ mergedTreeOid: null,
937
+ carryRemovals: Object.freeze([]),
938
+ carryUpdates: Object.freeze([]),
939
+ conflictPaths: Object.freeze([]),
940
+ conflicts: Object.freeze([]),
941
+ conflictResource: null,
942
+ });
943
+ }
944
+ if (!COMMIT_SHA_PATTERN.test(baseRevision) && !OID_HEX_PATTERN.test(baseRevision)) {
945
+ throw new TaskpackError('ACTION_INPUT_INVALID', `baseRevision "${baseRevision}" must be a full commit SHA`);
946
+ }
947
+ if (!COMMIT_SHA_PATTERN.test(sourceRevision) && !OID_HEX_PATTERN.test(sourceRevision)) {
948
+ throw new TaskpackError('ACTION_INPUT_INVALID', `sourceRevision "${sourceRevision}" must be a full commit SHA`);
949
+ }
950
+ const repositoryRoot = await realpath(options.repositoryRoot);
951
+ const alternateDirs = options.alternateObjectDirs ?? await resolveReadOnlyAlternateObjectDirs(repositoryRoot);
952
+ const scratchParent = options.scratchRoot !== undefined
953
+ ? await realpath(options.scratchRoot)
954
+ : await realpath(tmpdir());
955
+ const privateTempDir = await mkdtemp(join(scratchParent, 'lw-align-'));
956
+ await chmod(privateTempDir, 0o700);
957
+ const privateObjectsDir = join(privateTempDir, 'objects');
958
+ await mkdir(privateObjectsDir, { mode: 0o700 });
959
+ const isolatedEnv = buildCleanGitEnv({
960
+ GIT_OBJECT_DIRECTORY: privateObjectsDir,
961
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: alternateDirs.join(delimiter),
962
+ GIT_CONFIG_NOSYSTEM: '1',
963
+ GIT_CONFIG_GLOBAL: '/dev/null',
964
+ });
965
+ const makeBlocked = (detail, mergeBase, conflictPaths) => Object.freeze({
966
+ disposition: 'blocked',
967
+ status: 'blocked',
968
+ reason: BASELINE_CONFLICT_REASON,
969
+ detail: scrubber.scrub(detail),
970
+ policy,
971
+ baseRevision,
972
+ sourceRevision,
973
+ mergeBase,
974
+ mergedTreeOid: null,
975
+ carryRemovals: Object.freeze([]),
976
+ carryUpdates: Object.freeze([]),
977
+ conflictPaths: Object.freeze([...conflictPaths]),
978
+ conflicts: Object.freeze([]),
979
+ conflictResource: null,
980
+ });
981
+ try {
982
+ await execIsolatedGitChecked(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${baseRevision}^{commit}`], isolatedEnv, { timeoutMs: GIT_VERIFY_TIMEOUT_MS, maxStdoutBytes: MAX_OID_STDOUT_BYTES });
983
+ await execIsolatedGitChecked(repositoryRoot, ['rev-parse', '--verify', '--end-of-options', `${sourceRevision}^{commit}`], isolatedEnv, { timeoutMs: GIT_VERIFY_TIMEOUT_MS, maxStdoutBytes: MAX_OID_STDOUT_BYTES });
984
+ const scopeSnapshot = options.scope ?? (options.manifest !== undefined
985
+ ? buildScopeSnapshotFromManifest({
986
+ manifest: options.manifest,
987
+ repositoryRoot,
988
+ taskpackPath: options.taskpackPath,
989
+ baseRevision,
990
+ sourceRevision,
991
+ policyProfile: options.policyProfile,
992
+ hostPolicy: options.hostPolicy,
993
+ extraProtectedPaths: options.extraProtectedPaths,
994
+ })
995
+ : undefined);
996
+ const baseEntries = await listTreeEntriesAtRevision(repositoryRoot, baseRevision, isolatedEnv);
997
+ const sourceEntries = await listTreeEntriesAtRevision(repositoryRoot, sourceRevision, isolatedEnv);
998
+ const probe = await runIsolatedThreeWayMergeProbe({
999
+ repositoryRoot,
1000
+ baseRevision,
1001
+ sourceRevision,
1002
+ privateTempDir,
1003
+ isolatedEnv,
1004
+ baseEntries,
1005
+ sourceEntries,
1006
+ forceIndexFallback: options.forceIndexFallback,
1007
+ ...(policy.policy === 'extract-context'
1008
+ ? {
1009
+ retainConflictText: {
1010
+ maxConflictFiles: policy.maxConflictFiles,
1011
+ maxTotalConflictBytes: policy.maxConflictBytes,
1012
+ scrubber,
1013
+ },
1014
+ }
1015
+ : {}),
1016
+ });
1017
+ if (probe.clean && probe.mergedTreeOid !== null) {
1018
+ const mergedEntries = await listTreeEntriesAtRevision(repositoryRoot, probe.mergedTreeOid, isolatedEnv);
1019
+ const carry = scopeSnapshot !== undefined
1020
+ ? await computeWritableCarryDeltaFromMergedTree({
1021
+ repositoryRoot,
1022
+ snapshot: scopeSnapshot,
1023
+ baseEntries,
1024
+ sourceEntries,
1025
+ mergedEntries,
1026
+ excludedConflictPaths: new Set(),
1027
+ isolatedEnv,
1028
+ })
1029
+ : { carryRemovals: Object.freeze([]), carryUpdates: Object.freeze([]) };
1030
+ return Object.freeze({
1031
+ disposition: 'clean',
1032
+ status: 'merged_clean',
1033
+ policy,
1034
+ baseRevision,
1035
+ sourceRevision,
1036
+ mergeBase: probe.mergeBase,
1037
+ mergedTreeOid: probe.mergedTreeOid,
1038
+ carryRemovals: carry.carryRemovals,
1039
+ carryUpdates: carry.carryUpdates,
1040
+ conflictPaths: Object.freeze([]),
1041
+ conflicts: Object.freeze([]),
1042
+ conflictResource: null,
1043
+ });
1044
+ }
1045
+ if (policy.policy === 'off') {
1046
+ return Object.freeze({
1047
+ disposition: 'unmerged_off',
1048
+ status: 'conflicts_unmerged',
1049
+ policy,
1050
+ baseRevision,
1051
+ sourceRevision,
1052
+ mergeBase: probe.mergeBase,
1053
+ mergedTreeOid: probe.mergedTreeOid,
1054
+ carryRemovals: Object.freeze([]),
1055
+ carryUpdates: Object.freeze([]),
1056
+ conflictPaths: probe.conflictPaths,
1057
+ conflicts: Object.freeze([]),
1058
+ conflictResource: null,
1059
+ });
1060
+ }
1061
+ if (policy.policy === 'fail-fast') {
1062
+ return makeBlocked(`3-way baseline merge conflict between base ${baseRevision.slice(0, 12)} and source ${sourceRevision.slice(0, 12)} on ${probe.conflictPaths.length} path(s): ${probe.conflictPaths.slice(0, MAX_CONFLICT_SUMMARY_PATHS).join(', ')}`, probe.mergeBase, probe.conflictPaths);
1063
+ }
1064
+ if (scopeSnapshot === undefined) {
1065
+ return makeBlocked('extract-context baseline alignment requires a validated taskpack scope', probe.mergeBase, probe.conflictPaths);
1066
+ }
1067
+ if (probe.conflictPaths.length > policy.maxConflictFiles) {
1068
+ return makeBlocked(`conflicted file count (${probe.conflictPaths.length}) exceeds maxConflictFiles (${policy.maxConflictFiles})`, probe.mergeBase, probe.conflictPaths);
1069
+ }
1070
+ for (const msg of probe.conflictMessages) {
1071
+ if (msg.conflictType.includes('file/directory')
1072
+ || msg.conflictType.includes('submodule')
1073
+ || msg.conflictType.includes('symlink')
1074
+ || msg.conflictType.includes('distinct modes')
1075
+ || msg.conflictType.includes('binary')
1076
+ || msg.conflictType.includes('special')) {
1077
+ return makeBlocked(`unsupported structural or binary 3-way merge conflict (${msg.conflictType})`, probe.mergeBase, probe.conflictPaths);
1078
+ }
1079
+ }
1080
+ for (const rawPath of probe.conflictPaths) {
1081
+ let cleanPath;
1082
+ try {
1083
+ cleanPath = normalizeGitRelativePath(rawPath);
1084
+ }
1085
+ catch {
1086
+ return makeBlocked('conflicted path failed relative path validation', probe.mergeBase, probe.conflictPaths);
1087
+ }
1088
+ if (!isAllowedCandidateWrite(cleanPath, scopeSnapshot)
1089
+ || hasSymlinkAtOrAbove(cleanPath, baseEntries, sourceEntries)) {
1090
+ return makeBlocked(`conflicted path "${cleanPath}" is protected or outside writable scope`, probe.mergeBase, probe.conflictPaths);
1091
+ }
1092
+ }
1093
+ const mergeBaseEntries = probe.mergeBase !== null
1094
+ ? await listTreeEntriesAtRevision(repositoryRoot, probe.mergeBase, isolatedEnv)
1095
+ : new Map();
1096
+ const mergedTreeEntries = probe.mergedTreeOid !== null
1097
+ ? await listTreeEntriesAtRevision(repositoryRoot, probe.mergedTreeOid, isolatedEnv)
1098
+ : new Map();
1099
+ const perBlobReadCap = Math.max(policy.maxConflictBytes * CONFLICT_BLOB_READ_MULTIPLIER, MIN_CONFLICT_BLOB_READ_CAP_BYTES);
1100
+ const extractedFiles = [];
1101
+ let cumulativeHunkBytes = 0;
1102
+ const readOptionalConflictBlobInfo = async (entry) => {
1103
+ if (entry === undefined)
1104
+ return { sha256: null, byteLength: 0 };
1105
+ try {
1106
+ return await computeBlobSha256Isolated(repositoryRoot, entry.oid, isolatedEnv, perBlobReadCap);
1107
+ }
1108
+ catch (error) {
1109
+ if (error instanceof BlobSizeCeilingExceededError) {
1110
+ return 'ceiling_exceeded';
1111
+ }
1112
+ throw error;
1113
+ }
1114
+ };
1115
+ for (const conflictPath of probe.conflictPaths) {
1116
+ const mbEntry = mergeBaseEntries.get(conflictPath);
1117
+ const targetEntry = baseEntries.get(conflictPath);
1118
+ const sourceEntry = sourceEntries.get(conflictPath);
1119
+ if ((mbEntry !== undefined && mbEntry.mode !== '100644' && mbEntry.mode !== '100755')
1120
+ || (targetEntry !== undefined && targetEntry.mode !== '100644' && targetEntry.mode !== '100755')
1121
+ || (sourceEntry !== undefined && sourceEntry.mode !== '100644' && sourceEntry.mode !== '100755')) {
1122
+ return makeBlocked(`conflicted path "${conflictPath}" has non-regular file mode`, probe.mergeBase, probe.conflictPaths);
1123
+ }
1124
+ const baseInfo = await readOptionalConflictBlobInfo(mbEntry);
1125
+ const targetInfo = await readOptionalConflictBlobInfo(targetEntry);
1126
+ const sourceInfo = await readOptionalConflictBlobInfo(sourceEntry);
1127
+ if (baseInfo === 'ceiling_exceeded' || targetInfo === 'ceiling_exceeded' || sourceInfo === 'ceiling_exceeded') {
1128
+ return makeBlocked(`conflicted blob for "${conflictPath}" exceeds read ceiling`, probe.mergeBase, probe.conflictPaths);
1129
+ }
1130
+ let conflictKind;
1131
+ let fileHunks;
1132
+ let fileHunkBytes;
1133
+ if (targetEntry === undefined || sourceEntry === undefined) {
1134
+ conflictKind = targetEntry === undefined ? 'delete_modify' : 'modify_delete';
1135
+ const survivingOid = targetEntry?.oid ?? sourceEntry?.oid;
1136
+ if (survivingOid === undefined) {
1137
+ return makeBlocked(`conflicted path "${conflictPath}" missing surviving blob`, probe.mergeBase, probe.conflictPaths);
1138
+ }
1139
+ let survivingBytes;
1140
+ try {
1141
+ survivingBytes = await readVerifiedBlobIsolated(repositoryRoot, survivingOid, perBlobReadCap, isolatedEnv);
1142
+ }
1143
+ catch (error) {
1144
+ if (error instanceof BlobSizeCeilingExceededError) {
1145
+ return makeBlocked(`conflicted blob for "${conflictPath}" exceeds read ceiling`, probe.mergeBase, probe.conflictPaths);
1146
+ }
1147
+ throw error;
1148
+ }
1149
+ if (survivingBytes.includes(0)) {
1150
+ return makeBlocked(`binary conflict in "${conflictPath}" cannot be extracted`, probe.mergeBase, probe.conflictPaths);
1151
+ }
1152
+ let survivingText;
1153
+ try {
1154
+ survivingText = new TextDecoder('utf-8', { fatal: true }).decode(survivingBytes);
1155
+ }
1156
+ catch {
1157
+ return makeBlocked(`non-UTF-8 conflict in "${conflictPath}" cannot be extracted`, probe.mergeBase, probe.conflictPaths);
1158
+ }
1159
+ const rawBlock = targetEntry === undefined
1160
+ ? `<<<<<<< ${baseRevision} (deleted on target branch)\n=======\n${survivingText.replace(/\r\n?/g, '\n').trimEnd()}\n>>>>>>> ${sourceRevision}`
1161
+ : `<<<<<<< ${baseRevision}\n${survivingText.replace(/\r\n?/g, '\n').trimEnd()}\n=======\n>>>>>>> ${sourceRevision} (deleted on source branch)`;
1162
+ const scrubbedBlock = scrubber.scrub(rawBlock);
1163
+ scrubber.assertClean(scrubbedBlock, BASELINE_CONFLICT_RESOURCE_PATH);
1164
+ fileHunkBytes = Buffer.byteLength(scrubbedBlock, 'utf8');
1165
+ if (cumulativeHunkBytes + fileHunkBytes > policy.maxConflictBytes) {
1166
+ return makeBlocked(`extracted conflict bytes exceed maxConflictBytes (${policy.maxConflictBytes})`, probe.mergeBase, probe.conflictPaths);
1167
+ }
1168
+ const lineCount = Math.max(1, survivingText.split(/\r?\n/).length);
1169
+ fileHunks = Object.freeze([
1170
+ Object.freeze({
1171
+ index: 0,
1172
+ startLine: 1,
1173
+ endLine: lineCount,
1174
+ block: scrubbedBlock,
1175
+ }),
1176
+ ]);
1177
+ }
1178
+ else {
1179
+ conflictKind = mbEntry === undefined ? 'add_add' : 'content';
1180
+ const preExtracted = probe.extractedHunksByPath.get(conflictPath);
1181
+ if (preExtracted === 'failed') {
1182
+ return makeBlocked(`conflict hunks in "${conflictPath}" could not be extracted within maxConflictBytes (${policy.maxConflictBytes})`, probe.mergeBase, probe.conflictPaths);
1183
+ }
1184
+ if (preExtracted !== undefined) {
1185
+ if (cumulativeHunkBytes + preExtracted.totalHunkBytes > policy.maxConflictBytes) {
1186
+ return makeBlocked(`conflict hunks in "${conflictPath}" exceed maxConflictBytes (${policy.maxConflictBytes})`, probe.mergeBase, probe.conflictPaths);
1187
+ }
1188
+ fileHunks = preExtracted.hunks;
1189
+ fileHunkBytes = preExtracted.totalHunkBytes;
1190
+ }
1191
+ else {
1192
+ const mergedConflictEntry = mergedTreeEntries.get(conflictPath);
1193
+ if (mergedConflictEntry === undefined || (mergedConflictEntry.mode !== '100644' && mergedConflictEntry.mode !== '100755')) {
1194
+ return makeBlocked(`conflicted tree entry missing for "${conflictPath}"`, probe.mergeBase, probe.conflictPaths);
1195
+ }
1196
+ let rawMergedConflictBytes;
1197
+ try {
1198
+ rawMergedConflictBytes = await readVerifiedBlobIsolated(repositoryRoot, mergedConflictEntry.oid, perBlobReadCap, isolatedEnv);
1199
+ }
1200
+ catch (error) {
1201
+ if (error instanceof BlobSizeCeilingExceededError) {
1202
+ return makeBlocked(`conflicted blob for "${conflictPath}" exceeds read ceiling`, probe.mergeBase, probe.conflictPaths);
1203
+ }
1204
+ throw error;
1205
+ }
1206
+ if (rawMergedConflictBytes.includes(0)) {
1207
+ return makeBlocked(`binary merge conflict in "${conflictPath}" cannot be extracted`, probe.mergeBase, probe.conflictPaths);
1208
+ }
1209
+ let mergedConflictText;
1210
+ try {
1211
+ mergedConflictText = new TextDecoder('utf-8', { fatal: true }).decode(rawMergedConflictBytes);
1212
+ }
1213
+ catch {
1214
+ return makeBlocked(`non-UTF-8 merge conflict in "${conflictPath}" cannot be extracted`, probe.mergeBase, probe.conflictPaths);
1215
+ }
1216
+ const extracted = extractConflictHunksFromMergedText(mergedConflictText, scrubber, policy.maxConflictBytes - cumulativeHunkBytes);
1217
+ if (extracted === null) {
1218
+ return makeBlocked(`conflict hunks in "${conflictPath}" could not be extracted within maxConflictBytes (${policy.maxConflictBytes})`, probe.mergeBase, probe.conflictPaths);
1219
+ }
1220
+ fileHunks = extracted.hunks;
1221
+ fileHunkBytes = extracted.totalHunkBytes;
1222
+ }
1223
+ }
1224
+ cumulativeHunkBytes += fileHunkBytes;
1225
+ if (cumulativeHunkBytes > policy.maxConflictBytes) {
1226
+ return makeBlocked(`extracted conflict bytes (${cumulativeHunkBytes}) exceed maxConflictBytes (${policy.maxConflictBytes})`, probe.mergeBase, probe.conflictPaths);
1227
+ }
1228
+ extractedFiles.push(Object.freeze({
1229
+ path: conflictPath,
1230
+ conflictKind,
1231
+ baseSha256: baseInfo.sha256,
1232
+ targetSha256: targetInfo.sha256,
1233
+ sourceSha256: sourceInfo.sha256,
1234
+ byteLength: fileHunkBytes,
1235
+ hunks: fileHunks,
1236
+ }));
1237
+ }
1238
+ const document = Object.freeze({
1239
+ version: 1,
1240
+ baseRevision,
1241
+ sourceRevision,
1242
+ mergeBase: probe.mergeBase,
1243
+ conflictCount: extractedFiles.length,
1244
+ totalHunkBytes: cumulativeHunkBytes,
1245
+ conflicts: Object.freeze(extractedFiles),
1246
+ });
1247
+ const serializedJson = `${scrubber.scrub(JSON.stringify(document, null, 2))}\n`;
1248
+ scrubber.assertClean(serializedJson, BASELINE_CONFLICT_RESOURCE_PATH);
1249
+ const resourceBytes = Buffer.from(serializedJson, 'utf8');
1250
+ if (resourceBytes.byteLength > policy.maxConflictBytes) {
1251
+ return makeBlocked(`serialized conflict context (${resourceBytes.byteLength} bytes) exceeds maxConflictBytes (${policy.maxConflictBytes})`, probe.mergeBase, probe.conflictPaths);
1252
+ }
1253
+ const sha256 = createHash('sha256').update(resourceBytes).digest('hex');
1254
+ const conflictResource = Object.freeze({
1255
+ id: BASELINE_CONFLICT_RESOURCE_ID,
1256
+ kind: 'document',
1257
+ path: BASELINE_CONFLICT_RESOURCE_PATH,
1258
+ bytes: resourceBytes,
1259
+ sha256,
1260
+ byteLength: resourceBytes.byteLength,
1261
+ document,
1262
+ extractedPaths: probe.conflictPaths,
1263
+ });
1264
+ const cleanCarry = probe.mergedTreeOid !== null
1265
+ ? await computeWritableCarryDeltaFromMergedTree({
1266
+ repositoryRoot,
1267
+ snapshot: scopeSnapshot,
1268
+ baseEntries,
1269
+ sourceEntries,
1270
+ mergedEntries: mergedTreeEntries,
1271
+ excludedConflictPaths: new Set(probe.conflictPaths),
1272
+ isolatedEnv,
1273
+ })
1274
+ : { carryRemovals: Object.freeze([]), carryUpdates: Object.freeze([]) };
1275
+ return Object.freeze({
1276
+ disposition: 'extracted',
1277
+ status: 'conflicts_extracted',
1278
+ policy,
1279
+ baseRevision,
1280
+ sourceRevision,
1281
+ mergeBase: probe.mergeBase,
1282
+ mergedTreeOid: probe.mergedTreeOid,
1283
+ carryRemovals: cleanCarry.carryRemovals,
1284
+ carryUpdates: cleanCarry.carryUpdates,
1285
+ conflictPaths: probe.conflictPaths,
1286
+ conflicts: Object.freeze(extractedFiles),
1287
+ conflictResource,
1288
+ });
1289
+ }
1290
+ finally {
1291
+ await cleanupPrivateTempDir(privateTempDir, scrubber, options.onLog);
1292
+ }
1293
+ }
1294
+ async function readCandidateFileVerifiedBytes(file, maxBytes = MAX_CARRY_BLOB_BYTES) {
1295
+ if (file.kind === 'inline') {
1296
+ if (file.bytes.byteLength > maxBytes) {
1297
+ throw new TaskpackError('ACTION_INPUT_INVALID', `candidate file "${file.name}" (${file.bytes.byteLength} bytes) exceeds reconciliation ceiling (${maxBytes} bytes)`);
1298
+ }
1299
+ return {
1300
+ bytes: file.bytes,
1301
+ sha256: createHash('sha256').update(file.bytes).digest('hex'),
1302
+ };
1303
+ }
1304
+ if (file.byteLength > maxBytes) {
1305
+ throw new TaskpackError('ACTION_INPUT_INVALID', `CAS blob for "${file.name}" (${file.byteLength} bytes) exceeds reconciliation ceiling (${maxBytes} bytes)`);
1306
+ }
1307
+ const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0;
1308
+ const before = await lstat(file.canonicalBlobPath);
1309
+ if (before.isSymbolicLink() || !before.isFile() || before.nlink !== 1 || before.size !== file.byteLength) {
1310
+ throw new TaskpackError('ACTION_INPUT_INVALID', `CAS blob for "${file.name}" failed lstat/nlink verification`);
1311
+ }
1312
+ const handle = await open(file.canonicalBlobPath, fsConstants.O_RDONLY | noFollow);
1313
+ try {
1314
+ const stat = await handle.stat();
1315
+ if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== before.dev || stat.ino !== before.ino || stat.size !== file.byteLength) {
1316
+ throw new TaskpackError('ACTION_INPUT_INVALID', `CAS blob for "${file.name}" changed identity before conflict check`);
1317
+ }
1318
+ const bytes = Buffer.allocUnsafe(file.byteLength);
1319
+ const hash = createHash('sha256');
1320
+ let offset = 0;
1321
+ while (offset < file.byteLength) {
1322
+ const toRead = Math.min(STREAM_CHUNK_BYTES, file.byteLength - offset);
1323
+ const { bytesRead } = await handle.read(bytes, offset, toRead, offset);
1324
+ if (bytesRead <= 0)
1325
+ break;
1326
+ hash.update(bytes.subarray(offset, offset + bytesRead));
1327
+ offset += bytesRead;
1328
+ }
1329
+ const sha256 = hash.digest('hex');
1330
+ if (offset !== file.byteLength || sha256 !== file.sha256) {
1331
+ throw new TaskpackError('ACTION_INPUT_INVALID', `CAS blob for "${file.name}" failed SHA-256 verification`);
1332
+ }
1333
+ return {
1334
+ bytes,
1335
+ sha256,
1336
+ };
1337
+ }
1338
+ finally {
1339
+ await handle.close();
1340
+ }
1341
+ }
1342
+ /**
1343
+ * Verify that every extracted baseline conflict path was explicitly updated or deleted by the candidate
1344
+ * and contains ZERO residual Git conflict markers (`<<<<<<<`, `|||||||`, `>>>>>>>`).
1345
+ */
1346
+ export async function assertExtractedConflictsResolved(options) {
1347
+ if (options.extractedConflictPaths.length === 0)
1348
+ return;
1349
+ const filesByPath = new Map();
1350
+ for (const file of options.candidateFiles) {
1351
+ const clean = normalizeGitRelativePath(file.name);
1352
+ filesByPath.set(clean, file);
1353
+ }
1354
+ const deletedSet = new Set((options.candidateDeletedPaths ?? []).map(p => normalizeGitRelativePath(p)));
1355
+ for (const rawPath of options.extractedConflictPaths) {
1356
+ const conflictPath = normalizeGitRelativePath(rawPath);
1357
+ if (!isAllowedCandidateWrite(conflictPath, options.snapshot)) {
1358
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: extracted conflict path "${conflictPath}" is outside writable scope`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1359
+ }
1360
+ const updatedFile = filesByPath.get(conflictPath);
1361
+ const wasDeleted = deletedSet.has(conflictPath) && updatedFile === undefined;
1362
+ if (wasDeleted) {
1363
+ continue;
1364
+ }
1365
+ if (updatedFile === undefined) {
1366
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: unresolved baseline conflict in "${conflictPath}" (must be updated or deleted by candidate)`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1367
+ }
1368
+ const { bytes, sha256 } = await readCandidateFileVerifiedBytes(updatedFile);
1369
+ const originalSourceSha = options.sourceSha256ByPath?.get(conflictPath);
1370
+ if (originalSourceSha !== undefined && sha256 === originalSourceSha) {
1371
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: unresolved baseline conflict in "${conflictPath}" (candidate left sourceRevision content unchanged)`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1372
+ }
1373
+ if (containsResidualGitConflictMarkers(bytes)) {
1374
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: candidate file "${conflictPath}" still contains residual Git conflict markers`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1375
+ }
1376
+ }
1377
+ }
1378
+ /**
1379
+ * Shared 3-way carry helper for `startLocalCommandGateServer` (`@loopwright/taskpack`) and `publisher.ts`
1380
+ * (`@loopwright/github-app`): computes verified 3-way merged writable carry blobs in a private temporary
1381
+ * `GIT_OBJECT_DIRECTORY`, preserving disjoint same-file edits on `baseRevision` and `sourceRevision` while
1382
+ * failing closed on unmerged conflicts (`policy: 'off'`) or unresolved `extract-context` conflicts.
1383
+ */
1384
+ export async function computeThreeWaySourceRevisionCarryDelta(options) {
1385
+ const scrubber = options.scrubber ?? new SecretScrubber();
1386
+ const baseRevision = options.baseRevision.trim();
1387
+ const sourceRevision = options.sourceRevision.trim();
1388
+ if (baseRevision === sourceRevision) {
1389
+ if (options.extractedConflictPaths !== undefined && options.extractedConflictPaths.length > 0) {
1390
+ await assertExtractedConflictsResolved({
1391
+ extractedConflictPaths: options.extractedConflictPaths,
1392
+ snapshot: options.snapshot,
1393
+ candidateFiles: options.candidateFiles ?? [],
1394
+ candidateDeletedPaths: options.candidateDeletedPaths,
1395
+ });
1396
+ }
1397
+ return Object.freeze({
1398
+ carryRemovals: Object.freeze([]),
1399
+ carryUpdates: Object.freeze([]),
1400
+ mergeBase: baseRevision,
1401
+ mergedTreeOid: null,
1402
+ resolvedConflictPaths: Object.freeze([...(options.extractedConflictPaths ?? [])]),
1403
+ });
1404
+ }
1405
+ const repositoryRoot = await realpath(options.repositoryRoot);
1406
+ const alternateDirs = options.alternateObjectDirs ?? await resolveReadOnlyAlternateObjectDirs(repositoryRoot);
1407
+ const scratchParent = options.scratchRoot !== undefined
1408
+ ? await realpath(options.scratchRoot)
1409
+ : await realpath(tmpdir());
1410
+ const privateTempDir = await mkdtemp(join(scratchParent, 'lw-carry3-'));
1411
+ await chmod(privateTempDir, 0o700);
1412
+ const privateObjectsDir = join(privateTempDir, 'objects');
1413
+ await mkdir(privateObjectsDir, { mode: 0o700 });
1414
+ const isolatedEnv = buildCleanGitEnv({
1415
+ GIT_OBJECT_DIRECTORY: privateObjectsDir,
1416
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: alternateDirs.join(delimiter),
1417
+ GIT_CONFIG_NOSYSTEM: '1',
1418
+ GIT_CONFIG_GLOBAL: '/dev/null',
1419
+ });
1420
+ try {
1421
+ const baseEntries = options.baseEntries ?? await listTreeEntriesAtRevision(repositoryRoot, baseRevision, isolatedEnv);
1422
+ const sourceEntries = options.sourceEntries ?? await listTreeEntriesAtRevision(repositoryRoot, sourceRevision, isolatedEnv);
1423
+ const probe = await runIsolatedThreeWayMergeProbe({
1424
+ repositoryRoot,
1425
+ baseRevision,
1426
+ sourceRevision,
1427
+ privateTempDir,
1428
+ isolatedEnv,
1429
+ baseEntries,
1430
+ sourceEntries,
1431
+ forceIndexFallback: options.forceIndexFallback,
1432
+ });
1433
+ const writableConflicts = probe.conflictPaths.filter(path => isAllowedCandidateWrite(path, options.snapshot) && !hasSymlinkAtOrAbove(path, baseEntries, sourceEntries));
1434
+ const extractContextActive = (options.snapshot.contract !== undefined && hasBaselineConflictResource(options.snapshot.contract))
1435
+ || (options.extractedConflictPaths !== undefined && options.extractedConflictPaths.length > 0);
1436
+ if (writableConflicts.length > 0 && !extractContextActive) {
1437
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: unmerged 3-way baseline conflict on writable path(s): ${writableConflicts.slice(0, MAX_CONFLICT_SUMMARY_PATHS).join(', ')}`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1438
+ }
1439
+ const requiredConflictPaths = extractContextActive
1440
+ ? [...new Set([...(options.extractedConflictPaths ?? []), ...writableConflicts])].sort(compareLexical)
1441
+ : [];
1442
+ if (requiredConflictPaths.length > 0) {
1443
+ if (options.extractedConflictPaths !== undefined && options.extractedConflictPaths.length > 0) {
1444
+ const allowedExtracted = new Set(options.extractedConflictPaths);
1445
+ for (const wc of writableConflicts) {
1446
+ if (!allowedExtracted.has(wc)) {
1447
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: unexpected unmerged conflict "${wc}" outside extracted conflict set`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1448
+ }
1449
+ }
1450
+ }
1451
+ const sourceSha256ByPath = new Map();
1452
+ for (const path of requiredConflictPaths) {
1453
+ const srcEntry = sourceEntries.get(path);
1454
+ if (srcEntry !== undefined && (srcEntry.mode === '100644' || srcEntry.mode === '100755')) {
1455
+ const info = await computeBlobSha256Isolated(repositoryRoot, srcEntry.oid, isolatedEnv);
1456
+ sourceSha256ByPath.set(path, info.sha256);
1457
+ }
1458
+ }
1459
+ await assertExtractedConflictsResolved({
1460
+ extractedConflictPaths: requiredConflictPaths,
1461
+ snapshot: options.snapshot,
1462
+ candidateFiles: options.candidateFiles ?? [],
1463
+ candidateDeletedPaths: options.candidateDeletedPaths,
1464
+ sourceSha256ByPath,
1465
+ });
1466
+ }
1467
+ if (probe.mergedTreeOid === null) {
1468
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: missing verified 3-way merged tree for baseline carry resolution`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1469
+ }
1470
+ const mergedEntries = await listTreeEntriesAtRevision(repositoryRoot, probe.mergedTreeOid, isolatedEnv);
1471
+ const carry = await computeWritableCarryDeltaFromMergedTree({
1472
+ repositoryRoot,
1473
+ snapshot: options.snapshot,
1474
+ baseEntries,
1475
+ sourceEntries,
1476
+ mergedEntries,
1477
+ excludedConflictPaths: new Set(probe.conflictPaths),
1478
+ isolatedEnv,
1479
+ });
1480
+ return Object.freeze({
1481
+ carryRemovals: carry.carryRemovals,
1482
+ carryUpdates: carry.carryUpdates,
1483
+ mergeBase: probe.mergeBase,
1484
+ mergedTreeOid: probe.mergedTreeOid,
1485
+ resolvedConflictPaths: Object.freeze(requiredConflictPaths),
1486
+ });
1487
+ }
1488
+ finally {
1489
+ await cleanupPrivateTempDir(privateTempDir, scrubber, options.onLog);
1490
+ }
1491
+ }
1492
+ /**
1493
+ * Reconcile candidate overlay files (authored against `sourceRevision`) with `baseRevision` and
1494
+ * 3-way merged carry blobs (`ancestor = sourceRevision`, `ours = effective 3-way merged baseline`,
1495
+ * `theirs = candidate`) in a private temporary directory with ZERO host `.git/objects` writes.
1496
+ *
1497
+ * Preserves disjoint `baseRevision` lines when the candidate edits other regions of the same file,
1498
+ * passes `extractedConflictPaths` through untouched (already reconciled by the candidate), and fails
1499
+ * closed with `reason: 'baseline_merge_conflict'` when a candidate edit or deletion conflicts with `baseRevision`.
1500
+ */
1501
+ export async function mergeCandidateOverlayWithCarry(options) {
1502
+ const baseRevision = options.baseRevision.trim();
1503
+ const sourceRevision = options.sourceRevision.trim();
1504
+ const deletedList = options.candidateDeletedPaths ?? [];
1505
+ if (baseRevision === sourceRevision || (options.overlayFiles.length === 0 && deletedList.length === 0)) {
1506
+ return options.overlayFiles;
1507
+ }
1508
+ const scrubber = options.scrubber ?? new SecretScrubber();
1509
+ const extractedSet = new Set((options.extractedConflictPaths ?? []).map(p => normalizeGitRelativePath(p)));
1510
+ const carryByPath = new Map(options.carryUpdates.map(u => [u.path, u]));
1511
+ const repositoryRoot = await realpath(options.repositoryRoot);
1512
+ const alternateDirs = options.alternateObjectDirs ?? await resolveReadOnlyAlternateObjectDirs(repositoryRoot);
1513
+ const scratchParent = options.scratchRoot !== undefined
1514
+ ? await realpath(options.scratchRoot)
1515
+ : await realpath(tmpdir());
1516
+ const privateTempDir = await mkdtemp(join(scratchParent, 'lw-cand-merge-'));
1517
+ await chmod(privateTempDir, 0o700);
1518
+ const privateObjectsDir = join(privateTempDir, 'objects');
1519
+ const mergeScratchDir = join(privateTempDir, 'files');
1520
+ await mkdir(privateObjectsDir, { mode: 0o700 });
1521
+ await mkdir(mergeScratchDir, { mode: 0o700 });
1522
+ const isolatedEnv = buildCleanGitEnv({
1523
+ GIT_OBJECT_DIRECTORY: privateObjectsDir,
1524
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: alternateDirs.join(delimiter),
1525
+ GIT_CONFIG_NOSYSTEM: '1',
1526
+ GIT_CONFIG_GLOBAL: '/dev/null',
1527
+ });
1528
+ try {
1529
+ const baseEntries = options.baseEntries ?? await listTreeEntriesAtRevision(repositoryRoot, baseRevision, isolatedEnv);
1530
+ const sourceEntries = options.sourceEntries ?? await listTreeEntriesAtRevision(repositoryRoot, sourceRevision, isolatedEnv);
1531
+ const maxTotalInlineBytes = Math.min(MAX_CARRY_BLOB_BYTES, options.snapshot.contract?.spec.budgets.overlay?.maxBytes ?? MAX_CARRY_BLOB_BYTES);
1532
+ let retainedInlineBytes = 0;
1533
+ const pushInlineReconciled = (target, entry) => {
1534
+ retainedInlineBytes += entry.bytes.byteLength;
1535
+ if (retainedInlineBytes > maxTotalInlineBytes) {
1536
+ throw new TaskpackError('ACTION_INPUT_INVALID', `reconciled candidate overlay inline bytes (${retainedInlineBytes}) exceed ceiling (${maxTotalInlineBytes})`);
1537
+ }
1538
+ target.push(entry);
1539
+ };
1540
+ for (const rawDel of deletedList) {
1541
+ const delPath = normalizeGitRelativePath(rawDel);
1542
+ if (extractedSet.has(delPath))
1543
+ continue;
1544
+ const srcEntry = sourceEntries.get(delPath);
1545
+ const carryEntry = carryByPath.get(delPath);
1546
+ const baseEntry = baseEntries.get(delPath);
1547
+ const effectiveTargetOid = carryEntry?.oid ?? baseEntry?.oid;
1548
+ const effectiveTargetMode = carryEntry?.mode ?? baseEntry?.mode;
1549
+ if (srcEntry !== undefined
1550
+ && effectiveTargetOid !== undefined
1551
+ && (effectiveTargetOid !== srcEntry.oid || effectiveTargetMode !== srcEntry.mode)) {
1552
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: candidate deletion of "${delPath}" conflicts with baseRevision modifications`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1553
+ }
1554
+ }
1555
+ const reconciled = [];
1556
+ for (const file of options.overlayFiles) {
1557
+ const cleanName = normalizeGitRelativePath(file.name);
1558
+ if (extractedSet.has(cleanName)) {
1559
+ reconciled.push(file);
1560
+ continue;
1561
+ }
1562
+ const srcEntry = sourceEntries.get(cleanName);
1563
+ const baseEntry = baseEntries.get(cleanName);
1564
+ const carryEntry = carryByPath.get(cleanName);
1565
+ let oursMode;
1566
+ let oursOid;
1567
+ let oursPreloadedBytes;
1568
+ if (carryEntry !== undefined) {
1569
+ oursMode = carryEntry.mode;
1570
+ oursOid = carryEntry.oid;
1571
+ oursPreloadedBytes = carryEntry.bytes;
1572
+ }
1573
+ else if (baseEntry !== undefined && (baseEntry.mode === '100644' || baseEntry.mode === '100755')) {
1574
+ oursMode = baseEntry.mode;
1575
+ oursOid = baseEntry.oid;
1576
+ }
1577
+ if (oursOid === undefined || oursMode === undefined) {
1578
+ if (srcEntry !== undefined) {
1579
+ const { bytes: candBytes } = await readCandidateFileVerifiedBytes(file);
1580
+ const srcBytes = (srcEntry.mode === '100644' || srcEntry.mode === '100755')
1581
+ ? await readVerifiedBlobIsolated(repositoryRoot, srcEntry.oid, MAX_CARRY_BLOB_BYTES, isolatedEnv)
1582
+ : null;
1583
+ const candModeMatches = file.mode === undefined || file.mode === srcEntry.mode;
1584
+ if (srcBytes === null || !candBytes.equals(srcBytes) || !candModeMatches) {
1585
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: candidate modification on "${cleanName}" conflicts with deletion on baseRevision`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1586
+ }
1587
+ continue;
1588
+ }
1589
+ reconciled.push(file);
1590
+ continue;
1591
+ }
1592
+ if (srcEntry !== undefined && srcEntry.oid === oursOid && srcEntry.mode === oursMode) {
1593
+ reconciled.push(file);
1594
+ continue;
1595
+ }
1596
+ const { bytes: theirsBytes } = await readCandidateFileVerifiedBytes(file);
1597
+ const oursBytes = oursPreloadedBytes !== undefined
1598
+ ? Buffer.from(oursPreloadedBytes)
1599
+ : await readVerifiedBlobIsolated(repositoryRoot, oursOid, MAX_CARRY_BLOB_BYTES, isolatedEnv);
1600
+ const ancBytes = srcEntry !== undefined && (srcEntry.mode === '100644' || srcEntry.mode === '100755')
1601
+ ? await readVerifiedBlobIsolated(repositoryRoot, srcEntry.oid, MAX_CARRY_BLOB_BYTES, isolatedEnv)
1602
+ : Buffer.alloc(0);
1603
+ const resolvedMode = file.mode !== undefined && (srcEntry === undefined || file.mode !== srcEntry.mode)
1604
+ ? file.mode
1605
+ : oursMode;
1606
+ if (oursBytes.equals(theirsBytes)) {
1607
+ if (file.mode === resolvedMode) {
1608
+ if (file.kind === 'inline') {
1609
+ pushInlineReconciled(reconciled, file);
1610
+ }
1611
+ else {
1612
+ reconciled.push(file);
1613
+ }
1614
+ }
1615
+ else {
1616
+ pushInlineReconciled(reconciled, {
1617
+ kind: 'inline',
1618
+ name: cleanName,
1619
+ mode: resolvedMode,
1620
+ bytes: oursBytes,
1621
+ });
1622
+ }
1623
+ continue;
1624
+ }
1625
+ if (srcEntry !== undefined && ancBytes.equals(theirsBytes)) {
1626
+ pushInlineReconciled(reconciled, {
1627
+ kind: 'inline',
1628
+ name: cleanName,
1629
+ mode: resolvedMode,
1630
+ bytes: oursBytes,
1631
+ });
1632
+ continue;
1633
+ }
1634
+ if (srcEntry !== undefined && srcEntry.oid === oursOid) {
1635
+ if (file.mode === resolvedMode) {
1636
+ if (file.kind === 'inline') {
1637
+ pushInlineReconciled(reconciled, file);
1638
+ }
1639
+ else {
1640
+ reconciled.push(file);
1641
+ }
1642
+ }
1643
+ else {
1644
+ pushInlineReconciled(reconciled, {
1645
+ kind: 'inline',
1646
+ name: cleanName,
1647
+ mode: resolvedMode,
1648
+ bytes: theirsBytes,
1649
+ });
1650
+ }
1651
+ continue;
1652
+ }
1653
+ if (ancBytes.includes(0) || oursBytes.includes(0) || theirsBytes.includes(0)) {
1654
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: binary candidate modification on "${cleanName}" conflicts with baseRevision changes`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1655
+ }
1656
+ const fOurs = join(mergeScratchDir, 'ours');
1657
+ const fAnc = join(mergeScratchDir, 'anc');
1658
+ const fTheirs = join(mergeScratchDir, 'theirs');
1659
+ await writeFile(fOurs, oursBytes, { mode: 0o600 });
1660
+ await writeFile(fAnc, ancBytes, { mode: 0o600 });
1661
+ await writeFile(fTheirs, theirsBytes, { mode: 0o600 });
1662
+ const remainingInlineBudget = Math.max(0, maxTotalInlineBytes - retainedInlineBytes);
1663
+ const mergeRes = await runIsolatedGit(repositoryRoot, [
1664
+ 'merge-file',
1665
+ '-p',
1666
+ '-L', baseRevision,
1667
+ '-L', sourceRevision,
1668
+ '-L', 'candidate',
1669
+ fOurs,
1670
+ fAnc,
1671
+ fTheirs,
1672
+ ], isolatedEnv, { maxStdoutBytes: remainingInlineBudget });
1673
+ if (mergeRes.code === 0 && mergeRes.signal === null && !mergeRes.timedOut && !mergeRes.stdoutOverflow) {
1674
+ const resolvedMode = file.mode !== undefined && (srcEntry === undefined || file.mode !== srcEntry.mode)
1675
+ ? file.mode
1676
+ : oursMode;
1677
+ pushInlineReconciled(reconciled, {
1678
+ kind: 'inline',
1679
+ name: cleanName,
1680
+ mode: resolvedMode,
1681
+ bytes: mergeRes.stdout,
1682
+ });
1683
+ }
1684
+ else if (mergeRes.stdoutOverflow) {
1685
+ throw new TaskpackError('ACTION_INPUT_INVALID', `reconciled candidate overlay inline bytes exceed ceiling (${maxTotalInlineBytes}) while merging "${cleanName}"`);
1686
+ }
1687
+ else if (mergeRes.code !== null && mergeRes.code > 0 && mergeRes.code <= MAX_MERGE_FILE_EXIT_CONFLICTS) {
1688
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `${BASELINE_CONFLICT_REASON}: candidate modification on "${cleanName}" conflicts with baseRevision changes`, '/spec/baselineAlignment', { reason: BASELINE_CONFLICT_REASON });
1689
+ }
1690
+ else {
1691
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git merge-file failed while reconciling candidate file "${cleanName}"`);
1692
+ }
1693
+ }
1694
+ return Object.freeze(reconciled);
1695
+ }
1696
+ finally {
1697
+ await cleanupPrivateTempDir(privateTempDir, scrubber, options.onLog);
1698
+ }
1699
+ }
1700
+ /**
1701
+ * Write any synthesized 3-way merged carry blobs (`entry.bytes !== undefined`) into the repository's
1702
+ * Git object store right before `stageEntriesInIndex` during branch publication, verifying OID parity.
1703
+ */
1704
+ export async function ensureCarryBlobsInGitObjectStore(options) {
1705
+ const objectFormat = options.objectFormat ?? 'sha1';
1706
+ const oidPattern = objectFormat === 'sha1' ? SHA1_OID_HEX_PATTERN : SHA256_HEX_PATTERN;
1707
+ const gitEnv = options.gitEnv ?? buildCleanGitEnv({
1708
+ GIT_CONFIG_NOSYSTEM: '1',
1709
+ GIT_CONFIG_GLOBAL: '/dev/null',
1710
+ });
1711
+ for (const entry of options.carryUpdates) {
1712
+ if (entry.bytes === undefined)
1713
+ continue;
1714
+ const buf = Buffer.from(entry.bytes);
1715
+ const expectedOid = createHash(objectFormat).update(`blob ${buf.byteLength}\0`).update(buf).digest('hex');
1716
+ if (!oidPattern.test(entry.oid) || expectedOid !== entry.oid) {
1717
+ throw new TaskpackError('ACTION_INPUT_INVALID', `3-way carry blob OID mismatch for "${entry.path}"`);
1718
+ }
1719
+ if (entry.sha256 !== undefined) {
1720
+ const actualSha256 = createHash('sha256').update(buf).digest('hex');
1721
+ if (actualSha256 !== entry.sha256) {
1722
+ throw new TaskpackError('ACTION_INPUT_INVALID', `3-way carry blob SHA-256 mismatch for "${entry.path}"`);
1723
+ }
1724
+ }
1725
+ const writtenOid = (await execIsolatedGitChecked(options.repositoryRoot, ['hash-object', '-w', '--stdin'], gitEnv, { input: buf, timeoutMs: GIT_MERGE_TREE_TIMEOUT_MS, maxStdoutBytes: MAX_OID_STDOUT_BYTES })).toString('utf8').trim();
1726
+ if (writtenOid !== entry.oid) {
1727
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git hash-object returned unexpected OID for carried "${entry.path}"`);
1728
+ }
1729
+ }
1730
+ }
1731
+ /**
1732
+ * Filter candidate snapshot files in classic full-snapshot mode (`baseTree === undefined`)
1733
+ * down to writable files that were actually added or modified relative to `sourceEntries`
1734
+ * (differing in Git blob OID or mode), matching v2 minimal-overlay semantics so untouched
1735
+ * `sourceRevision` files never overwrite verified 3-way merged carry blobs.
1736
+ */
1737
+ export async function filterModifiedCandidateOverlayFiles(files, snapshot, sourceEntries) {
1738
+ const modified = [];
1739
+ for (const file of files) {
1740
+ if (!isAllowedCandidateWrite(file.name, snapshot))
1741
+ continue;
1742
+ const sourceEntry = sourceEntries.get(file.name);
1743
+ if (sourceEntry !== undefined && (sourceEntry.mode === '100644' || sourceEntry.mode === '100755')) {
1744
+ const { bytes } = await readCandidateFileVerifiedBytes(file);
1745
+ const algo = sourceEntry.oid.length === 64 ? 'sha256' : 'sha1';
1746
+ const actualOid = createHash(algo)
1747
+ .update(`blob ${bytes.byteLength}\0`)
1748
+ .update(bytes)
1749
+ .digest('hex');
1750
+ const modeMatches = file.mode === undefined || file.mode === sourceEntry.mode;
1751
+ if (actualOid === sourceEntry.oid && modeMatches) {
1752
+ continue;
1753
+ }
1754
+ }
1755
+ modified.push(file);
1756
+ }
1757
+ return Object.freeze(modified);
1758
+ }
1759
+ /**
1760
+ * Pre-publication baseline alignment, 3-way carry computation, and candidate-overlay reconciliation
1761
+ * over an `InspectedCandidateSnapshot`. Returns both the verified 3-way carry delta (`carryRemovals`,
1762
+ * `carryUpdates`) and `reconciledOverlayFiles` ready for Git index staging.
1763
+ */
1764
+ export async function verifyCandidateBaselinePrePublication(options) {
1765
+ const { snapshot } = options;
1766
+ const resolvedRepoRoot = resolve(options.repositoryRoot);
1767
+ const repoStat = await lstat(resolvedRepoRoot).catch(() => null);
1768
+ if (repoStat === null || repoStat.isSymbolicLink() || !repoStat.isDirectory()) {
1769
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'repositoryRoot must be an existing non-symlink directory');
1770
+ }
1771
+ let baseEntries;
1772
+ let sourceEntries;
1773
+ if (snapshot.sourceRevision !== snapshot.baseRevision) {
1774
+ const cleanEnv = options.gitEnv ?? buildCleanGitEnv({
1775
+ GIT_CONFIG_NOSYSTEM: '1',
1776
+ GIT_CONFIG_GLOBAL: '/dev/null',
1777
+ });
1778
+ baseEntries = await listTreeEntriesAtRevision(options.repositoryRoot, snapshot.baseRevision, cleanEnv);
1779
+ sourceEntries = await listTreeEntriesAtRevision(options.repositoryRoot, snapshot.sourceRevision, cleanEnv);
1780
+ }
1781
+ let overlayFiles = snapshot.manifest.spec.baseTree !== undefined
1782
+ ? snapshot.files
1783
+ : snapshot.files.filter(file => isAllowedCandidateWrite(file.name, snapshot));
1784
+ const deletedPaths = [];
1785
+ if (snapshot.manifest.spec.baseTree !== undefined) {
1786
+ for (const rawDel of snapshot.manifest.spec.deleted ?? []) {
1787
+ deletedPaths.push(normalizeGitRelativePath(rawDel));
1788
+ }
1789
+ }
1790
+ else if (snapshot.sourceRevision !== snapshot.baseRevision && baseEntries !== undefined && sourceEntries !== undefined) {
1791
+ overlayFiles = await filterModifiedCandidateOverlayFiles(snapshot.files, snapshot, sourceEntries);
1792
+ const candidateNames = new Set(snapshot.files.map(f => f.name));
1793
+ for (const [sourceName, sourceEntry] of sourceEntries.entries()) {
1794
+ if (sourceEntry.mode !== '100644' && sourceEntry.mode !== '100755')
1795
+ continue;
1796
+ if (!candidateNames.has(sourceName)
1797
+ && isAllowedCandidateWrite(sourceName, snapshot)
1798
+ && !hasSymlinkAtOrAbove(sourceName, baseEntries, sourceEntries)) {
1799
+ deletedPaths.push(sourceName);
1800
+ }
1801
+ }
1802
+ }
1803
+ for (const rawRel of deletedPaths) {
1804
+ normalizeGitRelativePath(rawRel);
1805
+ }
1806
+ const realRepoRoot = await realpath(resolvedRepoRoot);
1807
+ const sharedAlternateDirs = snapshot.sourceRevision !== snapshot.baseRevision
1808
+ ? await resolveReadOnlyAlternateObjectDirs(realRepoRoot)
1809
+ : undefined;
1810
+ const carryDelta = await computeThreeWaySourceRevisionCarryDelta({
1811
+ repositoryRoot: options.repositoryRoot,
1812
+ baseRevision: snapshot.baseRevision,
1813
+ sourceRevision: snapshot.sourceRevision,
1814
+ snapshot,
1815
+ baseEntries,
1816
+ sourceEntries,
1817
+ candidateFiles: overlayFiles,
1818
+ candidateDeletedPaths: deletedPaths,
1819
+ extractedConflictPaths: options.extractedConflictPaths,
1820
+ scratchRoot: options.scratchRoot,
1821
+ alternateObjectDirs: sharedAlternateDirs,
1822
+ gitEnv: options.gitEnv,
1823
+ forceIndexFallback: options.forceIndexFallback,
1824
+ scrubber: options.scrubber,
1825
+ onLog: options.onLog,
1826
+ });
1827
+ const reconciledOverlayFiles = await mergeCandidateOverlayWithCarry({
1828
+ repositoryRoot: options.repositoryRoot,
1829
+ baseRevision: snapshot.baseRevision,
1830
+ sourceRevision: snapshot.sourceRevision,
1831
+ snapshot,
1832
+ overlayFiles,
1833
+ candidateDeletedPaths: deletedPaths,
1834
+ carryUpdates: carryDelta.carryUpdates,
1835
+ baseEntries,
1836
+ sourceEntries,
1837
+ extractedConflictPaths: carryDelta.resolvedConflictPaths,
1838
+ scratchRoot: options.scratchRoot,
1839
+ alternateObjectDirs: sharedAlternateDirs,
1840
+ scrubber: options.scrubber,
1841
+ onLog: options.onLog,
1842
+ });
1843
+ return Object.freeze({
1844
+ ...carryDelta,
1845
+ reconciledOverlayFiles,
1846
+ });
1847
+ }