@gpustack/loopwright 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (477) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +356 -2
  3. package/bin/loopwright.js +3 -0
  4. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
  5. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
  6. package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
  7. package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
  8. package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
  9. package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
  10. package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
  11. package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
  12. package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
  13. package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
  14. package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
  15. package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
  16. package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
  17. package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
  18. package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
  19. package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
  20. package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
  21. package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
  22. package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
  23. package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
  24. package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
  25. package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
  26. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
  27. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
  28. package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
  29. package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
  30. package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
  31. package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
  32. package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
  33. package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
  34. package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
  35. package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
  36. package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
  37. package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
  38. package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
  39. package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
  40. package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
  41. package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
  42. package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
  43. package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
  44. package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
  45. package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
  46. package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
  47. package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
  48. package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
  49. package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
  50. package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
  51. package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
  52. package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
  53. package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
  54. package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
  55. package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
  56. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
  57. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
  58. package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
  59. package/node_modules/@loopwright/agent-pi/dist/host-session.js +2083 -0
  60. package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
  61. package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
  62. package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
  63. package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
  64. package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
  65. package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
  66. package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
  67. package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
  68. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
  69. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
  70. package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
  71. package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
  72. package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
  73. package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
  74. package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
  75. package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
  76. package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
  77. package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
  78. package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
  79. package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
  80. package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
  81. package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
  82. package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
  83. package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
  84. package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
  85. package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
  86. package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
  87. package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
  88. package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
  89. package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
  90. package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
  91. package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
  92. package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
  93. package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
  94. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
  95. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
  96. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
  97. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
  98. package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
  99. package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
  100. package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
  101. package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
  102. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
  103. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
  104. package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
  105. package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
  106. package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
  107. package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
  108. package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
  109. package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
  110. package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
  111. package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
  112. package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
  113. package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
  114. package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
  115. package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
  116. package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
  117. package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
  118. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
  119. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
  120. package/node_modules/@loopwright/agent-pi/package.json +24 -0
  121. package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
  122. package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
  123. package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
  124. package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
  125. package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
  126. package/node_modules/@loopwright/cli/dist/closure.js +230 -0
  127. package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
  128. package/node_modules/@loopwright/cli/dist/draft.js +106 -0
  129. package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
  130. package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
  131. package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
  132. package/node_modules/@loopwright/cli/dist/index.js +5 -0
  133. package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
  134. package/node_modules/@loopwright/cli/dist/main.js +1855 -0
  135. package/node_modules/@loopwright/cli/package.json +16 -0
  136. package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
  137. package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
  138. package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
  139. package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
  140. package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
  141. package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
  142. package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
  143. package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
  144. package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
  145. package/node_modules/@loopwright/controller/dist/capture.js +587 -0
  146. package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
  147. package/node_modules/@loopwright/controller/dist/compile.js +402 -0
  148. package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
  149. package/node_modules/@loopwright/controller/dist/config.js +255 -0
  150. package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
  151. package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
  152. package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
  153. package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
  154. package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
  155. package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
  156. package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
  157. package/node_modules/@loopwright/controller/dist/errors.js +41 -0
  158. package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
  159. package/node_modules/@loopwright/controller/dist/events.js +228 -0
  160. package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
  161. package/node_modules/@loopwright/controller/dist/files.js +386 -0
  162. package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
  163. package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
  164. package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
  165. package/node_modules/@loopwright/controller/dist/gate.js +640 -0
  166. package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
  167. package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
  168. package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
  169. package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
  170. package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
  171. package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
  172. package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
  173. package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
  174. package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
  175. package/node_modules/@loopwright/controller/dist/index.js +21 -0
  176. package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
  177. package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
  178. package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
  179. package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
  180. package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
  181. package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
  182. package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
  183. package/node_modules/@loopwright/controller/dist/parser.js +200 -0
  184. package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
  185. package/node_modules/@loopwright/controller/dist/progress.js +904 -0
  186. package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
  187. package/node_modules/@loopwright/controller/dist/publication.js +329 -0
  188. package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
  189. package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
  190. package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
  191. package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
  192. package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
  193. package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
  194. package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
  195. package/node_modules/@loopwright/controller/dist/registry.js +374 -0
  196. package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
  197. package/node_modules/@loopwright/controller/dist/repair.js +102 -0
  198. package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
  199. package/node_modules/@loopwright/controller/dist/report.js +596 -0
  200. package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
  201. package/node_modules/@loopwright/controller/dist/retained.js +193 -0
  202. package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
  203. package/node_modules/@loopwright/controller/dist/rules.js +110 -0
  204. package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
  205. package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
  206. package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
  207. package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
  208. package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
  209. package/node_modules/@loopwright/controller/dist/schema.js +78 -0
  210. package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
  211. package/node_modules/@loopwright/controller/dist/source.js +872 -0
  212. package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
  213. package/node_modules/@loopwright/controller/dist/step.js +1776 -0
  214. package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
  215. package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
  216. package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
  217. package/node_modules/@loopwright/controller/dist/submission.js +292 -0
  218. package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
  219. package/node_modules/@loopwright/controller/dist/types.js +9 -0
  220. package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
  221. package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
  222. package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
  223. package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
  224. package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
  225. package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
  226. package/node_modules/@loopwright/controller/package.json +12 -0
  227. package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
  228. package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
  229. package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
  230. package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
  231. package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
  232. package/node_modules/@loopwright/core/dist/boundary.js +484 -0
  233. package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
  234. package/node_modules/@loopwright/core/dist/contracts.js +694 -0
  235. package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
  236. package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
  237. package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
  238. package/node_modules/@loopwright/core/dist/evidence.js +85 -0
  239. package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
  240. package/node_modules/@loopwright/core/dist/graph.js +44 -0
  241. package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
  242. package/node_modules/@loopwright/core/dist/identity.js +80 -0
  243. package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
  244. package/node_modules/@loopwright/core/dist/index.js +39 -0
  245. package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
  246. package/node_modules/@loopwright/core/dist/limits.js +59 -0
  247. package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
  248. package/node_modules/@loopwright/core/dist/results.js +98 -0
  249. package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
  250. package/node_modules/@loopwright/core/dist/scope.js +154 -0
  251. package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
  252. package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
  253. package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
  254. package/node_modules/@loopwright/core/dist/usage.js +56 -0
  255. package/node_modules/@loopwright/core/package.json +12 -0
  256. package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
  257. package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
  258. package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
  259. package/node_modules/@loopwright/decisions/dist/client.js +292 -0
  260. package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
  261. package/node_modules/@loopwright/decisions/dist/index.js +8 -0
  262. package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
  263. package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
  264. package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
  265. package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
  266. package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
  267. package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
  268. package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
  269. package/node_modules/@loopwright/decisions/dist/router.js +248 -0
  270. package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
  271. package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
  272. package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
  273. package/node_modules/@loopwright/decisions/dist/types.js +80 -0
  274. package/node_modules/@loopwright/decisions/package.json +12 -0
  275. package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
  276. package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
  277. package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
  278. package/node_modules/@loopwright/github-app/dist/config.js +297 -0
  279. package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
  280. package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
  281. package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
  282. package/node_modules/@loopwright/github-app/dist/index.js +13 -0
  283. package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
  284. package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
  285. package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
  286. package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
  287. package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
  288. package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
  289. package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
  290. package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
  291. package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
  292. package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
  293. package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
  294. package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
  295. package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
  296. package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
  297. package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
  298. package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
  299. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
  300. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
  301. package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
  302. package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
  303. package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
  304. package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
  305. package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
  306. package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
  307. package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
  308. package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
  309. package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
  310. package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
  311. package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
  312. package/node_modules/@loopwright/github-app/dist/types.js +14 -0
  313. package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
  314. package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
  315. package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
  316. package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
  317. package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
  318. package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
  319. package/node_modules/@loopwright/github-app/package.json +12 -0
  320. package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
  321. package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
  322. package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
  323. package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
  324. package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
  325. package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
  326. package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
  327. package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
  328. package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
  329. package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
  330. package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
  331. package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
  332. package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
  333. package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
  334. package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
  335. package/node_modules/@loopwright/hardware-runner/dist/worker.js +1646 -0
  336. package/node_modules/@loopwright/hardware-runner/package.json +12 -0
  337. package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
  338. package/node_modules/@loopwright/memory/dist/cas.js +510 -0
  339. package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
  340. package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
  341. package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
  342. package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
  343. package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
  344. package/node_modules/@loopwright/memory/dist/index.js +8 -0
  345. package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
  346. package/node_modules/@loopwright/memory/dist/schema.js +510 -0
  347. package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
  348. package/node_modules/@loopwright/memory/dist/selector.js +157 -0
  349. package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
  350. package/node_modules/@loopwright/memory/dist/store.js +554 -0
  351. package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
  352. package/node_modules/@loopwright/memory/dist/types.js +8 -0
  353. package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
  354. package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
  355. package/node_modules/@loopwright/memory/package.json +12 -0
  356. package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
  357. package/node_modules/@loopwright/state/dist/admission.js +199 -0
  358. package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
  359. package/node_modules/@loopwright/state/dist/boundary.js +194 -0
  360. package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
  361. package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
  362. package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
  363. package/node_modules/@loopwright/state/dist/clock.js +27 -0
  364. package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
  365. package/node_modules/@loopwright/state/dist/connection.js +391 -0
  366. package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
  367. package/node_modules/@loopwright/state/dist/errors.js +34 -0
  368. package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
  369. package/node_modules/@loopwright/state/dist/index.js +1 -0
  370. package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
  371. package/node_modules/@loopwright/state/dist/journal.js +72 -0
  372. package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
  373. package/node_modules/@loopwright/state/dist/model.js +58 -0
  374. package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
  375. package/node_modules/@loopwright/state/dist/ownership.js +45 -0
  376. package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
  377. package/node_modules/@loopwright/state/dist/pages.js +41 -0
  378. package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
  379. package/node_modules/@loopwright/state/dist/receipts.js +97 -0
  380. package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
  381. package/node_modules/@loopwright/state/dist/schema.js +41 -0
  382. package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
  383. package/node_modules/@loopwright/state/dist/settlement.js +129 -0
  384. package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
  385. package/node_modules/@loopwright/state/dist/store.js +100 -0
  386. package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
  387. package/node_modules/@loopwright/state/dist/types.js +1 -0
  388. package/node_modules/@loopwright/state/package.json +12 -0
  389. package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
  390. package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
  391. package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
  392. package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
  393. package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
  394. package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
  395. package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
  396. package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
  397. package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
  398. package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
  399. package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
  400. package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
  401. package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
  402. package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
  403. package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
  404. package/node_modules/@loopwright/taskpack/dist/sandbox.js +2605 -0
  405. package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
  406. package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
  407. package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
  408. package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
  409. package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
  410. package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
  411. package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
  412. package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
  413. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
  414. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
  415. package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
  416. package/node_modules/@loopwright/taskpack/dist/turnkey.js +7313 -0
  417. package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
  418. package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
  419. package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
  420. package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
  421. package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
  422. package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
  423. package/node_modules/@loopwright/taskpack/package.json +12 -0
  424. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
  425. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
  426. package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
  427. package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
  428. package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
  429. package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
  430. package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
  431. package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
  432. package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
  433. package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
  434. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
  435. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
  436. package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
  437. package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
  438. package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
  439. package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
  440. package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
  441. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
  442. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
  443. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
  444. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
  445. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
  446. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
  447. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
  448. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
  449. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
  450. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
  451. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
  452. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
  453. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
  454. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
  455. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
  456. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
  457. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
  458. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
  459. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
  460. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
  461. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
  462. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
  463. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
  464. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
  465. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
  466. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
  467. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
  468. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
  469. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
  470. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
  471. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
  472. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
  473. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
  474. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
  475. package/node_modules/package-lock.json +3021 -0
  476. package/package-lock.json +3021 -0
  477. package/package.json +52 -4
@@ -0,0 +1,2242 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { constants as fsConstants, existsSync, lstatSync, statSync } from 'node:fs';
4
+ import { lstat, open, stat } from 'node:fs/promises';
5
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { SecretScrubber } from './scrubber.js';
8
+ import { parseJsonSubset, tryNormalizeRelativePath } from './schema.js';
9
+ import { REPOSITORY_FULL_NAME_PATTERN, TaskpackError, } from './types.js';
10
+ const execFileAsync = promisify(execFile);
11
+ const MAX_RESPONSE_BYTES = 1_048_576;
12
+ const MAX_PROPOSAL_BYTES = 262_144;
13
+ const MAX_VERSION_PATH_LENGTH = 256;
14
+ const MAX_VERSION_PATH_SEGMENTS = 32;
15
+ const MAX_RECORD_METADATA_KEYS = 32;
16
+ const MAX_RECORD_METADATA_BYTES = 8_192;
17
+ export const COMMIT_SHA_PATTERN = /^[0-9a-f]{40}$/i;
18
+ const SAFE_GIT_REF_PATTERN = /^[A-Za-z0-9_./@^~{}-]{1,256}$/;
19
+ const SEMVER_TAG_PATTERN = /^v?(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/i;
20
+ const STRICT_SEMVER_PATTERN = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
21
+ const PRERELEASE_VERSION_TAG_PATTERN = /^v?\d+(?:\.\d+)+(?:[._-]?(?:alpha|beta|rc|dev|pre|preview|nightly|canary)\d*|[ab]\d+)(?:[._-]|$)/i;
22
+ const FORBIDDEN_PATH_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
23
+ const UPSTREAM_STATUSES = new Set([
24
+ 'available',
25
+ 'up_to_date',
26
+ 'held_back',
27
+ 'failed',
28
+ 'blocked',
29
+ ]);
30
+ const GIT_CANDIDATE_PATHS = Object.freeze([
31
+ '/usr/bin/git',
32
+ '/opt/homebrew/bin/git',
33
+ '/usr/local/bin/git',
34
+ ]);
35
+ export const DEFAULT_GIT_COMMIT_IDENTITY = Object.freeze({
36
+ name: 'github-actions[bot]',
37
+ email: '41898282+github-actions[bot]@users.noreply.github.com',
38
+ });
39
+ const MAX_GIT_IDENTITY_FIELD_LENGTH = 256;
40
+ const SIMPLE_EMAIL_PATTERN = /^[^\s<>@]+@[^\s<>@]+$/;
41
+ async function resolveAuthHeaders(githubToken, authHeaders, baseHeaders, scrubber) {
42
+ const headers = { ...baseHeaders };
43
+ const resolvedExtra = typeof authHeaders === 'function' ? await authHeaders() : authHeaders;
44
+ if (resolvedExtra !== undefined) {
45
+ for (const [key, value] of Object.entries(resolvedExtra)) {
46
+ headers[key] = value;
47
+ const lower = key.toLowerCase();
48
+ if (lower === 'authorization' || lower === 'x-api-key' || lower === 'api-key') {
49
+ scrubber.register(value);
50
+ const bearerMatch = /^Bearer\s+(.+)$/i.exec(value);
51
+ if (bearerMatch?.[1])
52
+ scrubber.register(bearerMatch[1].trim());
53
+ }
54
+ }
55
+ }
56
+ const resolvedToken = (typeof githubToken === 'function' ? await githubToken() : githubToken)?.trim();
57
+ if (resolvedToken && resolvedToken.length > 0) {
58
+ scrubber.register(resolvedToken);
59
+ if (!Object.keys(headers).some(k => k.toLowerCase() === 'authorization')) {
60
+ headers['authorization'] = `Bearer ${resolvedToken}`;
61
+ }
62
+ }
63
+ return headers;
64
+ }
65
+ function hasDisallowedGitIdentityChars(text) {
66
+ for (let i = 0; i < text.length; i += 1) {
67
+ const code = text.charCodeAt(i);
68
+ if (code <= 0x1f || code === 0x7f || code === 0x3c || code === 0x3e) {
69
+ return true;
70
+ }
71
+ }
72
+ return false;
73
+ }
74
+ export function validateGitAuthorName(raw) {
75
+ if (typeof raw !== 'string' || hasDisallowedGitIdentityChars(raw)) {
76
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'git-author-name must not contain control characters (CR/LF/NUL) or angle brackets (< or >)');
77
+ }
78
+ const trimmed = raw.trim();
79
+ if (trimmed.length === 0 || trimmed.length > MAX_GIT_IDENTITY_FIELD_LENGTH) {
80
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git-author-name must be 1..${MAX_GIT_IDENTITY_FIELD_LENGTH} printable characters`);
81
+ }
82
+ return trimmed;
83
+ }
84
+ export function validateGitAuthorEmail(raw) {
85
+ if (typeof raw !== 'string' || hasDisallowedGitIdentityChars(raw)) {
86
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'git-author-email must not contain control characters (CR/LF/NUL) or angle brackets (< or >)');
87
+ }
88
+ const trimmed = raw.trim();
89
+ if (trimmed.length === 0
90
+ || trimmed.length > MAX_GIT_IDENTITY_FIELD_LENGTH
91
+ || !SIMPLE_EMAIL_PATTERN.test(trimmed)) {
92
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git-author-email must be a valid email address (1..${MAX_GIT_IDENTITY_FIELD_LENGTH} chars without whitespace or angle brackets)`);
93
+ }
94
+ return trimmed;
95
+ }
96
+ export function validateGitCommitIdentity(identity) {
97
+ return Object.freeze({
98
+ name: validateGitAuthorName(identity.name),
99
+ email: validateGitAuthorEmail(identity.email),
100
+ });
101
+ }
102
+ export function parseOptionalGitIdentityInput(explicitValue, envValue, validator) {
103
+ const raw = explicitValue !== undefined ? explicitValue : envValue;
104
+ if (raw === undefined || raw === '')
105
+ return undefined;
106
+ return validator(raw);
107
+ }
108
+ export function resolveGitExecutable() {
109
+ for (const candidate of GIT_CANDIDATE_PATHS) {
110
+ if (existsSync(candidate))
111
+ return candidate;
112
+ }
113
+ return 'git';
114
+ }
115
+ export function buildCleanGitEnv(extra) {
116
+ return {
117
+ PATH: process.env['PATH'] ?? '/usr/local/bin:/usr/bin:/bin',
118
+ HOME: '/nonexistent',
119
+ GIT_CONFIG_NOSYSTEM: '1',
120
+ GIT_CONFIG_GLOBAL: '/dev/null',
121
+ GIT_TERMINAL_PROMPT: '0',
122
+ GIT_PROTOCOL_FROM_USER: '0',
123
+ ...extra,
124
+ };
125
+ }
126
+ function defaultApiBaseUrl(explicit, env) {
127
+ const candidate = explicit?.trim() || env?.['GITHUB_API_URL']?.trim() || 'https://api.github.com';
128
+ return candidate.replace(/\/+$/, '');
129
+ }
130
+ export function isPlainRecord(value) {
131
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
132
+ return false;
133
+ const proto = Object.getPrototypeOf(value);
134
+ return proto === Object.prototype || proto === null;
135
+ }
136
+ export function assertNoSymlinkSegments(baseDir, targetPath) {
137
+ const resolvedBase = resolve(baseDir);
138
+ const resolvedTarget = resolve(targetPath);
139
+ const rel = relative(resolvedBase, resolvedTarget);
140
+ if (rel.startsWith('..') || isAbsolute(rel)) {
141
+ throw new TaskpackError('ACTION_INPUT_INVALID', `path "${targetPath}" escapes root "${baseDir}"`);
142
+ }
143
+ const parts = rel.split(sep).filter(part => part.length > 0 && part !== '.');
144
+ let cursor = resolvedBase;
145
+ for (const part of parts) {
146
+ cursor = join(cursor, part);
147
+ const stats = lstatSync(cursor, { throwIfNoEntry: false });
148
+ if (stats === undefined)
149
+ continue;
150
+ if (stats.isSymbolicLink()) {
151
+ throw new TaskpackError('ACTION_INPUT_INVALID', `symlink segment disallowed at "${cursor}"`);
152
+ }
153
+ }
154
+ }
155
+ async function readBoundedLocalFile(baseDir, relPath, maxBytes) {
156
+ const resolvedBase = resolve(baseDir);
157
+ const fullPath = resolve(resolvedBase, relPath);
158
+ assertNoSymlinkSegments(resolvedBase, fullPath);
159
+ const info = await stat(fullPath);
160
+ if (!info.isFile()) {
161
+ throw new TaskpackError('ACTION_INPUT_INVALID', `expected regular file at "${relPath}"`);
162
+ }
163
+ if (info.size > maxBytes) {
164
+ throw new TaskpackError('ACTION_INPUT_INVALID', `file "${relPath}" exceeds maximum allowed ${maxBytes} bytes`);
165
+ }
166
+ const handle = await open(fullPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
167
+ try {
168
+ const openedStats = await handle.stat();
169
+ if (!openedStats.isFile() || openedStats.size > maxBytes) {
170
+ throw new TaskpackError('ACTION_INPUT_INVALID', `file "${relPath}" is not a bounded regular file`);
171
+ }
172
+ return await handle.readFile();
173
+ }
174
+ finally {
175
+ await handle.close();
176
+ }
177
+ }
178
+ export async function fetchBoundedText(url, fetchImpl, headers, timeoutMs, scrubber, requestOptions) {
179
+ const controller = new AbortController();
180
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
181
+ timer.unref?.();
182
+ try {
183
+ const response = await fetchImpl(url, {
184
+ method: requestOptions?.method ?? 'GET',
185
+ headers,
186
+ ...(requestOptions?.body !== undefined ? { body: requestOptions.body } : {}),
187
+ redirect: 'error',
188
+ signal: controller.signal,
189
+ });
190
+ const rawContentLength = typeof response.headers?.get === 'function'
191
+ ? response.headers.get('content-length')
192
+ : null;
193
+ if (rawContentLength !== null && /^\d+$/.test(rawContentLength.trim())) {
194
+ const declaredBytes = Number(rawContentLength.trim());
195
+ if (!Number.isSafeInteger(declaredBytes) || declaredBytes > MAX_RESPONSE_BYTES) {
196
+ await response.body?.cancel?.().catch(() => undefined);
197
+ throw new TaskpackError('ACTION_INPUT_INVALID', `response from "${scrubber.scrub(url)}" exceeded ${MAX_RESPONSE_BYTES} bytes`);
198
+ }
199
+ }
200
+ const reader = response.body?.getReader();
201
+ if (!reader) {
202
+ if (typeof response.arrayBuffer === 'function') {
203
+ const buf = Buffer.from(await response.arrayBuffer());
204
+ if (buf.byteLength > MAX_RESPONSE_BYTES) {
205
+ throw new TaskpackError('ACTION_INPUT_INVALID', `response from "${scrubber.scrub(url)}" exceeded ${MAX_RESPONSE_BYTES} bytes`);
206
+ }
207
+ return { status: response.status, ok: response.ok, text: buf.toString('utf8') };
208
+ }
209
+ const text = await response.text();
210
+ if (Buffer.byteLength(text, 'utf8') > MAX_RESPONSE_BYTES) {
211
+ throw new TaskpackError('ACTION_INPUT_INVALID', `response from "${scrubber.scrub(url)}" exceeded ${MAX_RESPONSE_BYTES} bytes`);
212
+ }
213
+ return { status: response.status, ok: response.ok, text };
214
+ }
215
+ const chunks = [];
216
+ let total = 0;
217
+ for (;;) {
218
+ const { done, value } = await reader.read();
219
+ if (done)
220
+ break;
221
+ total += value.byteLength;
222
+ if (total > MAX_RESPONSE_BYTES) {
223
+ await reader.cancel().catch(() => undefined);
224
+ throw new TaskpackError('ACTION_INPUT_INVALID', `response from "${scrubber.scrub(url)}" exceeded ${MAX_RESPONSE_BYTES} bytes`);
225
+ }
226
+ chunks.push(Buffer.from(value));
227
+ }
228
+ return { status: response.status, ok: response.ok, text: Buffer.concat(chunks).toString('utf8') };
229
+ }
230
+ finally {
231
+ clearTimeout(timer);
232
+ }
233
+ }
234
+ async function fetchJson(url, fetchImpl, headers, timeoutMs, scrubber) {
235
+ const result = await fetchBoundedText(url, fetchImpl, headers, timeoutMs, scrubber);
236
+ if (result.text.trim().length === 0) {
237
+ return { status: result.status, ok: result.ok, data: null, rawText: '' };
238
+ }
239
+ try {
240
+ return { status: result.status, ok: result.ok, data: JSON.parse(result.text), rawText: result.text };
241
+ }
242
+ catch (error) {
243
+ const detail = error instanceof Error ? error.message : String(error);
244
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid JSON from "${scrubber.scrub(url)}": ${scrubber.scrub(detail)}`);
245
+ }
246
+ }
247
+ const MAX_RECORD_METADATA_DEPTH = 12;
248
+ const MAX_VERSION_STRING_LENGTH = 256;
249
+ const MAX_UPSTREAM_ID_LENGTH = 128;
250
+ function sanitizeSingleLine(text) {
251
+ return text.replace(/[\0\r\n]+/g, ' ').trim();
252
+ }
253
+ function validateVersionStringField(value, label, maxLength = MAX_VERSION_STRING_LENGTH) {
254
+ if (typeof value !== 'string') {
255
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} must be a string`);
256
+ }
257
+ const trimmed = value.trim();
258
+ if (trimmed.length === 0 || trimmed.length > maxLength || /[\0\r\n]/.test(value)) {
259
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} must be a single-line non-empty string of at most ${maxLength} characters`);
260
+ }
261
+ return trimmed;
262
+ }
263
+ /**
264
+ * Normalize `version` / `targetVersion` for `held_back` upstream records so `version` NEVER
265
+ * substitutes a skipped target version into reviewed-memory metadata when `currentVersion` is known
266
+ * (or omits `version` if `currentVersion` is unknown).
267
+ */
268
+ export function normalizeHeldBackVersions(status, version, currentVersion, targetVersion) {
269
+ if (status !== 'held_back') {
270
+ return { version, targetVersion };
271
+ }
272
+ if (currentVersion !== undefined) {
273
+ const skipped = targetVersion ?? (version !== undefined && version !== currentVersion ? version : undefined);
274
+ return { version: currentVersion, targetVersion: skipped };
275
+ }
276
+ if (version !== undefined) {
277
+ return { version: undefined, targetVersion: targetVersion ?? version };
278
+ }
279
+ return { version: undefined, targetVersion };
280
+ }
281
+ function validateBoundedMetadataValue(value, label, depth) {
282
+ if (depth > MAX_RECORD_METADATA_DEPTH) {
283
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} exceeds maximum nesting depth ${MAX_RECORD_METADATA_DEPTH}`);
284
+ }
285
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
286
+ return value;
287
+ }
288
+ if (typeof value === 'number') {
289
+ if (!Number.isFinite(value) || Object.is(value, -0)) {
290
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} contains non-finite number`);
291
+ }
292
+ return value;
293
+ }
294
+ if (Array.isArray(value)) {
295
+ return Object.freeze(value.map((item, idx) => validateBoundedMetadataValue(item, `${label}[${idx}]`, depth + 1)));
296
+ }
297
+ if (isPlainRecord(value)) {
298
+ const out = Object.create(null);
299
+ for (const key of Object.keys(value)) {
300
+ if (FORBIDDEN_PATH_KEYS.has(key)) {
301
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} contains forbidden key "${key}"`);
302
+ }
303
+ out[key] = validateBoundedMetadataValue(value[key], `${label}.${key}`, depth + 1);
304
+ }
305
+ return Object.freeze(out);
306
+ }
307
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} contains unsupported non-JSON value`);
308
+ }
309
+ function validateBoundedMetadataRecord(raw, label) {
310
+ if (!isPlainRecord(raw)) {
311
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} must be a plain JSON object`);
312
+ }
313
+ const entries = Object.keys(raw);
314
+ if (entries.length > MAX_RECORD_METADATA_KEYS) {
315
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} exceeds ${MAX_RECORD_METADATA_KEYS} entries`);
316
+ }
317
+ const out = validateBoundedMetadataValue(raw, label, 1);
318
+ let serialized;
319
+ try {
320
+ serialized = JSON.stringify(out);
321
+ }
322
+ catch {
323
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} is not JSON-serializable`);
324
+ }
325
+ if (Buffer.byteLength(serialized, 'utf8') > MAX_RECORD_METADATA_BYTES) {
326
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${label} exceeds ${MAX_RECORD_METADATA_BYTES} bytes`);
327
+ }
328
+ return out;
329
+ }
330
+ export function parseUpstreamRecordsJson(rawJson) {
331
+ if (typeof rawJson !== 'string' || Buffer.byteLength(rawJson, 'utf8') > MAX_RESPONSE_BYTES) {
332
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson must be a string of at most ${MAX_RESPONSE_BYTES} bytes`);
333
+ }
334
+ let parsed;
335
+ try {
336
+ parsed = parseJsonSubset(rawJson, {
337
+ maxNodes: 8_192,
338
+ maxDepth: MAX_RECORD_METADATA_DEPTH,
339
+ maxCollection: 256,
340
+ maxString: 32_768,
341
+ diagPath: '/upstreamRecordsJson',
342
+ });
343
+ }
344
+ catch (error) {
345
+ const detail = error instanceof Error ? error.message : String(error);
346
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson is not valid JSON: ${detail}`);
347
+ }
348
+ if (!Array.isArray(parsed)) {
349
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'upstreamRecordsJson must be a JSON array');
350
+ }
351
+ const records = [];
352
+ for (const [index, entry] of parsed.entries()) {
353
+ if (!isPlainRecord(entry)) {
354
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson[${index}] must be an object`);
355
+ }
356
+ const rawUpstreamId = entry['upstreamId'];
357
+ const status = entry['status'];
358
+ const rawVersion = entry['version'];
359
+ const rawCurrentVersion = entry['currentVersion'];
360
+ const rawTargetVersion = entry['targetVersion'];
361
+ const recentVersions = entry['recentVersions'];
362
+ const watchedPaths = entry['watchedPaths'];
363
+ const rawGroupId = entry['groupId'];
364
+ const rawUnderlyingStatus = entry['underlyingStatus'];
365
+ const reason = entry['reason'];
366
+ const metadata = entry['metadata'];
367
+ const upstreamId = validateVersionStringField(rawUpstreamId, `upstreamRecordsJson[${index}].upstreamId`, MAX_UPSTREAM_ID_LENGTH);
368
+ if (typeof status !== 'string' || !UPSTREAM_STATUSES.has(status)) {
369
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson[${index}].status is invalid`);
370
+ }
371
+ const version = rawVersion !== undefined
372
+ ? validateVersionStringField(rawVersion, `upstreamRecordsJson[${index}].version`)
373
+ : undefined;
374
+ const currentVersion = rawCurrentVersion !== undefined
375
+ ? validateVersionStringField(rawCurrentVersion, `upstreamRecordsJson[${index}].currentVersion`)
376
+ : undefined;
377
+ const targetVersion = rawTargetVersion !== undefined
378
+ ? validateVersionStringField(rawTargetVersion, `upstreamRecordsJson[${index}].targetVersion`)
379
+ : undefined;
380
+ if (recentVersions !== undefined
381
+ && (!Array.isArray(recentVersions) || recentVersions.some(item => typeof item !== 'string' || item.trim().length === 0 || item.length > MAX_VERSION_STRING_LENGTH || /[\0\r\n]/.test(item)))) {
382
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson[${index}].recentVersions must be an array of bounded single-line strings`);
383
+ }
384
+ if (watchedPaths !== undefined
385
+ && (!Array.isArray(watchedPaths) || watchedPaths.some(item => typeof item !== 'string' || item.length === 0 || item.length > 1024 || /[\0\r\n]/.test(item)))) {
386
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson[${index}].watchedPaths must be an array of non-empty strings`);
387
+ }
388
+ const groupId = rawGroupId !== undefined
389
+ ? validateVersionStringField(rawGroupId, `upstreamRecordsJson[${index}].groupId`, MAX_UPSTREAM_ID_LENGTH)
390
+ : undefined;
391
+ let underlyingStatus;
392
+ if (rawUnderlyingStatus !== undefined) {
393
+ if (rawUnderlyingStatus !== 'failed' && rawUnderlyingStatus !== 'blocked') {
394
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson[${index}].underlyingStatus must be "failed" or "blocked"`);
395
+ }
396
+ underlyingStatus = rawUnderlyingStatus;
397
+ }
398
+ if (reason !== undefined && (typeof reason !== 'string' || reason.length > 2048)) {
399
+ throw new TaskpackError('ACTION_INPUT_INVALID', `upstreamRecordsJson[${index}].reason must be a string of at most 2048 characters`);
400
+ }
401
+ const validatedMetadata = metadata !== undefined
402
+ ? validateBoundedMetadataRecord(metadata, `upstreamRecordsJson[${index}].metadata`)
403
+ : undefined;
404
+ const typedStatus = status;
405
+ const normalized = normalizeHeldBackVersions(typedStatus, version, currentVersion, targetVersion);
406
+ records.push({
407
+ upstreamId,
408
+ status: typedStatus,
409
+ ...(normalized.version !== undefined ? { version: normalized.version } : {}),
410
+ ...(currentVersion !== undefined ? { currentVersion } : {}),
411
+ ...(normalized.targetVersion !== undefined ? { targetVersion: normalized.targetVersion } : {}),
412
+ ...(recentVersions !== undefined ? { recentVersions: Object.freeze([...recentVersions]) } : {}),
413
+ ...(watchedPaths !== undefined ? { watchedPaths: Object.freeze([...watchedPaths]) } : {}),
414
+ ...(groupId !== undefined ? { groupId } : {}),
415
+ ...(underlyingStatus !== undefined ? { underlyingStatus } : {}),
416
+ ...(reason !== undefined ? { reason } : {}),
417
+ ...(validatedMetadata !== undefined ? { metadata: validatedMetadata } : {}),
418
+ });
419
+ }
420
+ return Object.freeze(records);
421
+ }
422
+ function parseVersionPathSegments(versionPath) {
423
+ if (typeof versionPath !== 'string'
424
+ || versionPath.length === 0
425
+ || versionPath.length > MAX_VERSION_PATH_LENGTH
426
+ || /[\0\r\n]/.test(versionPath)) {
427
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid versionPath selector "${String(versionPath)}"`);
428
+ }
429
+ const segments = [];
430
+ let cursor;
431
+ if (versionPath.startsWith('$')) {
432
+ cursor = 1;
433
+ if (cursor === versionPath.length) {
434
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'versionPath "$" must select a property or index');
435
+ }
436
+ }
437
+ else {
438
+ const firstMatch = /^[A-Za-z0-9_-]+/.exec(versionPath);
439
+ if (firstMatch === null) {
440
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid versionPath selector "${versionPath}"`);
441
+ }
442
+ const firstKey = firstMatch[0];
443
+ if (FORBIDDEN_PATH_KEYS.has(firstKey)) {
444
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath must not access forbidden property "${firstKey}"`);
445
+ }
446
+ segments.push({ kind: 'key', value: firstKey });
447
+ cursor = firstKey.length;
448
+ }
449
+ while (cursor < versionPath.length) {
450
+ if (segments.length >= MAX_VERSION_PATH_SEGMENTS) {
451
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath exceeds ${MAX_VERSION_PATH_SEGMENTS} segments`);
452
+ }
453
+ const rest = versionPath.slice(cursor);
454
+ if (rest.startsWith('.')) {
455
+ const dotMatch = /^\.([A-Za-z0-9_-]+)/.exec(rest);
456
+ if (dotMatch === null) {
457
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid dot segment in versionPath "${versionPath}"`);
458
+ }
459
+ const key = dotMatch[1];
460
+ if (FORBIDDEN_PATH_KEYS.has(key)) {
461
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath must not access forbidden property "${key}"`);
462
+ }
463
+ segments.push({ kind: 'key', value: key });
464
+ cursor += dotMatch[0].length;
465
+ }
466
+ else if (rest.startsWith('[')) {
467
+ const idxMatch = /^\[(\d+)\]/.exec(rest);
468
+ if (idxMatch !== null) {
469
+ const index = Number.parseInt(idxMatch[1], 10);
470
+ if (!Number.isSafeInteger(index) || index < 0) {
471
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid array index in versionPath "${versionPath}"`);
472
+ }
473
+ segments.push({ kind: 'index', value: index });
474
+ cursor += idxMatch[0].length;
475
+ continue;
476
+ }
477
+ const singleQuoteMatch = /^\['([^'\r\n]+)'\]/.exec(rest);
478
+ if (singleQuoteMatch !== null) {
479
+ const key = singleQuoteMatch[1];
480
+ if (FORBIDDEN_PATH_KEYS.has(key)) {
481
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath must not access forbidden property "${key}"`);
482
+ }
483
+ segments.push({ kind: 'key', value: key });
484
+ cursor += singleQuoteMatch[0].length;
485
+ continue;
486
+ }
487
+ const doubleQuoteMatch = /^\["([^"\r\n]+)"\]/.exec(rest);
488
+ if (doubleQuoteMatch !== null) {
489
+ const key = doubleQuoteMatch[1];
490
+ if (FORBIDDEN_PATH_KEYS.has(key)) {
491
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath must not access forbidden property "${key}"`);
492
+ }
493
+ segments.push({ kind: 'key', value: key });
494
+ cursor += doubleQuoteMatch[0].length;
495
+ continue;
496
+ }
497
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid bracket segment in versionPath "${versionPath}"`);
498
+ }
499
+ else {
500
+ throw new TaskpackError('ACTION_INPUT_INVALID', `unexpected token in versionPath "${versionPath}" at offset ${cursor}`);
501
+ }
502
+ }
503
+ if (segments.length === 0) {
504
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath "${versionPath}" selects no segments`);
505
+ }
506
+ return segments;
507
+ }
508
+ /**
509
+ * Safely traverse a parsed JSON value using a bounded dot/bracket `versionPath` selector
510
+ * (e.g. `dist-tags.latest`, `$.data.releases[0].version`, `packages['@scope/pkg'].version`),
511
+ * refusing prototype-chain keys (`__proto__`, `constructor`, `prototype`).
512
+ */
513
+ export function extractJsonVersionPath(data, versionPath) {
514
+ const segments = parseVersionPathSegments(versionPath);
515
+ let current = data;
516
+ for (const segment of segments) {
517
+ if (segment.kind === 'index') {
518
+ if (!Array.isArray(current) || segment.value < 0 || segment.value >= current.length) {
519
+ return undefined;
520
+ }
521
+ current = current[segment.value];
522
+ }
523
+ else {
524
+ if (!isPlainRecord(current) || !Object.hasOwn(current, segment.value)) {
525
+ return undefined;
526
+ }
527
+ current = current[segment.value];
528
+ }
529
+ }
530
+ if (typeof current !== 'string')
531
+ return undefined;
532
+ if (/[\0\r\n]/.test(current)) {
533
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath "${versionPath}" resolved to a multiline or NUL-containing string`);
534
+ }
535
+ const trimmed = current.trim();
536
+ if (trimmed.length === 0)
537
+ return undefined;
538
+ if (trimmed.length > MAX_VERSION_STRING_LENGTH) {
539
+ throw new TaskpackError('ACTION_INPUT_INVALID', `versionPath "${versionPath}" resolved value exceeds ${MAX_VERSION_STRING_LENGTH} characters`);
540
+ }
541
+ return trimmed;
542
+ }
543
+ function parseStrictSemver(raw) {
544
+ const match = STRICT_SEMVER_PATTERN.exec(raw.trim());
545
+ if (match === null)
546
+ return null;
547
+ return {
548
+ major: BigInt(match[1]),
549
+ minor: BigInt(match[2]),
550
+ patch: BigInt(match[3]),
551
+ prerelease: match[4] !== undefined ? match[4].split('.') : [],
552
+ };
553
+ }
554
+ /**
555
+ * Compare two strict SemVer 2.0.0 strings (`major.minor.patch[-prerelease][+build]`).
556
+ * Returns `< 0` when `a < b`, `0` when equal precedence, `> 0` when `a > b`, or `null` if either is not strict SemVer.
557
+ */
558
+ export function compareStrictSemver(a, b) {
559
+ const semA = parseStrictSemver(a);
560
+ const semB = parseStrictSemver(b);
561
+ if (semA === null || semB === null)
562
+ return null;
563
+ if (semA.major !== semB.major)
564
+ return semA.major < semB.major ? -1 : 1;
565
+ if (semA.minor !== semB.minor)
566
+ return semA.minor < semB.minor ? -1 : 1;
567
+ if (semA.patch !== semB.patch)
568
+ return semA.patch < semB.patch ? -1 : 1;
569
+ if (semA.prerelease.length === 0 && semB.prerelease.length === 0)
570
+ return 0;
571
+ if (semA.prerelease.length === 0)
572
+ return 1;
573
+ if (semB.prerelease.length === 0)
574
+ return -1;
575
+ const len = Math.min(semA.prerelease.length, semB.prerelease.length);
576
+ for (let i = 0; i < len; i += 1) {
577
+ const idA = semA.prerelease[i];
578
+ const idB = semB.prerelease[i];
579
+ const isNumA = /^\d+$/.test(idA);
580
+ const isNumB = /^\d+$/.test(idB);
581
+ if (isNumA && isNumB) {
582
+ const nA = BigInt(idA);
583
+ const nB = BigInt(idB);
584
+ if (nA !== nB)
585
+ return nA < nB ? -1 : 1;
586
+ }
587
+ else if (isNumA !== isNumB) {
588
+ return isNumA ? -1 : 1;
589
+ }
590
+ else if (idA !== idB) {
591
+ return idA < idB ? -1 : 1;
592
+ }
593
+ }
594
+ return semA.prerelease.length - semB.prerelease.length;
595
+ }
596
+ function normalizePackageJsonVersionSpec(rawSpec) {
597
+ const trimmed = rawSpec.trim();
598
+ if (trimmed.length === 0
599
+ || /[\0\r\n\s<>]|[*xX]|\|\|/.test(trimmed)
600
+ || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(trimmed)) {
601
+ return undefined;
602
+ }
603
+ const stripped = trimmed.replace(/^[~^=]+/, '');
604
+ if (stripped.length === 0 || parseSemverTag(stripped) === null) {
605
+ return undefined;
606
+ }
607
+ return stripped;
608
+ }
609
+ function extractNpmPackageNameFromSource(source) {
610
+ try {
611
+ const parsed = new URL(source);
612
+ if (parsed.hostname !== 'registry.npmjs.org')
613
+ return undefined;
614
+ const rawPath = parsed.pathname.replace(/^\/+|\/+$/g, '');
615
+ if (rawPath.length === 0)
616
+ return undefined;
617
+ const withoutLatest = rawPath.endsWith('/latest') ? rawPath.slice(0, -'/latest'.length) : rawPath;
618
+ return decodeURIComponent(withoutLatest);
619
+ }
620
+ catch {
621
+ return undefined;
622
+ }
623
+ }
624
+ function readPackageJsonBaselineVersions(packageJsonRaw, declaredUpstreams) {
625
+ const baselines = new Map();
626
+ if (!isPlainRecord(packageJsonRaw))
627
+ return baselines;
628
+ const deps = new Map();
629
+ for (const section of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {
630
+ const table = packageJsonRaw[section];
631
+ if (!isPlainRecord(table))
632
+ continue;
633
+ for (const [pkgName, spec] of Object.entries(table)) {
634
+ if (typeof spec !== 'string' || deps.has(pkgName))
635
+ continue;
636
+ const normalized = normalizePackageJsonVersionSpec(spec);
637
+ if (normalized !== undefined) {
638
+ deps.set(pkgName, normalized);
639
+ }
640
+ }
641
+ }
642
+ for (const upstream of declaredUpstreams) {
643
+ const direct = deps.get(upstream.id);
644
+ if (direct !== undefined) {
645
+ baselines.set(upstream.id, direct);
646
+ continue;
647
+ }
648
+ const pkgFromUrl = extractNpmPackageNameFromSource(upstream.source);
649
+ if (pkgFromUrl !== undefined) {
650
+ const fromUrl = deps.get(pkgFromUrl);
651
+ if (fromUrl !== undefined) {
652
+ baselines.set(upstream.id, fromUrl);
653
+ }
654
+ }
655
+ }
656
+ return baselines;
657
+ }
658
+ function readBaselineVersions(proposalRaw, declaredUpstreams) {
659
+ const versions = new Map();
660
+ if (!isPlainRecord(proposalRaw))
661
+ return versions;
662
+ const upstreamsField = proposalRaw['upstreams'];
663
+ if (Array.isArray(upstreamsField)) {
664
+ for (const item of upstreamsField) {
665
+ if (!isPlainRecord(item))
666
+ continue;
667
+ const id = typeof item['id'] === 'string'
668
+ ? item['id']
669
+ : typeof item['upstreamId'] === 'string'
670
+ ? item['upstreamId']
671
+ : undefined;
672
+ const version = item['version'];
673
+ if (id !== undefined && typeof version === 'string' && version.length > 0) {
674
+ versions.set(id, version);
675
+ }
676
+ }
677
+ }
678
+ else if (isPlainRecord(upstreamsField)) {
679
+ for (const [id, entry] of Object.entries(upstreamsField)) {
680
+ if (typeof entry === 'string' && entry.length > 0) {
681
+ versions.set(id, entry);
682
+ }
683
+ else if (isPlainRecord(entry) && typeof entry['version'] === 'string' && entry['version'].length > 0) {
684
+ versions.set(id, entry['version']);
685
+ }
686
+ }
687
+ }
688
+ const versionsField = proposalRaw['versions'];
689
+ if (isPlainRecord(versionsField)) {
690
+ for (const [id, entry] of Object.entries(versionsField)) {
691
+ if (typeof entry === 'string' && entry.length > 0 && !versions.has(id)) {
692
+ versions.set(id, entry);
693
+ }
694
+ }
695
+ }
696
+ if (versions.size === 0
697
+ && declaredUpstreams !== undefined
698
+ && declaredUpstreams.length === 1
699
+ && typeof proposalRaw['version'] === 'string'
700
+ && proposalRaw['version'].length > 0) {
701
+ versions.set(declaredUpstreams[0].id, proposalRaw['version']);
702
+ }
703
+ return versions;
704
+ }
705
+ export function validateGitRemoteSource(source, repositoryRoot) {
706
+ if (typeof source !== 'string'
707
+ || source.length === 0
708
+ || /[\0\r\n]/.test(source)
709
+ || source.startsWith('-')) {
710
+ throw new TaskpackError('ACTION_INPUT_INVALID', `unsafe git upstream source "${source}"`);
711
+ }
712
+ if (source.includes('://') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(source)) {
713
+ if (!source.startsWith('https://') || /\s/.test(source)) {
714
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git upstream source "${source}" uses disallowed scheme`);
715
+ }
716
+ let parsed;
717
+ try {
718
+ parsed = new URL(source);
719
+ }
720
+ catch {
721
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git upstream source "${source}" is not a valid https URL`);
722
+ }
723
+ if (parsed.protocol !== 'https:' || parsed.hostname.length === 0) {
724
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git upstream source "${source}" must be a valid https URL`);
725
+ }
726
+ return 'https';
727
+ }
728
+ const localPath = repositoryRoot !== undefined ? resolve(repositoryRoot, source) : source;
729
+ if (!existsSync(localPath) || !statSync(localPath).isDirectory()) {
730
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git upstream local source "${source}" must be an existing directory`);
731
+ }
732
+ return 'local-dir';
733
+ }
734
+ function parseSemverTag(tag) {
735
+ const match = SEMVER_TAG_PATTERN.exec(tag.trim());
736
+ if (!match)
737
+ return null;
738
+ const core = match[1].split('.').map(part => Number.parseInt(part, 10));
739
+ if (core.some(n => !Number.isSafeInteger(n)))
740
+ return null;
741
+ const prerelease = match[2] ? match[2].split('.') : [];
742
+ return { core, prerelease };
743
+ }
744
+ function compareNaturalChunks(a, b) {
745
+ const chunksA = a.match(/\d+|\D+/g) ?? [];
746
+ const chunksB = b.match(/\d+|\D+/g) ?? [];
747
+ const len = Math.min(chunksA.length, chunksB.length);
748
+ for (let i = 0; i < len; i += 1) {
749
+ const partA = chunksA[i];
750
+ const partB = chunksB[i];
751
+ const numA = /^\d+$/.test(partA);
752
+ const numB = /^\d+$/.test(partB);
753
+ if (numA && numB) {
754
+ const valA = BigInt(partA);
755
+ const valB = BigInt(partB);
756
+ if (valA !== valB)
757
+ return valA < valB ? -1 : 1;
758
+ }
759
+ else if (partA !== partB) {
760
+ return partA < partB ? -1 : 1;
761
+ }
762
+ }
763
+ return chunksA.length - chunksB.length;
764
+ }
765
+ export function isPrereleaseVersionTag(tag) {
766
+ const coreAndPre = tag.trim().split('+', 1)[0];
767
+ return PRERELEASE_VERSION_TAG_PATTERN.test(coreAndPre);
768
+ }
769
+ export function compareVersionTags(a, b) {
770
+ const semA = parseSemverTag(a);
771
+ const semB = parseSemverTag(b);
772
+ if (semA !== null && semB !== null) {
773
+ const maxLen = Math.max(semA.core.length, semB.core.length);
774
+ for (let i = 0; i < maxLen; i += 1) {
775
+ const valA = semA.core[i] ?? 0;
776
+ const valB = semB.core[i] ?? 0;
777
+ if (valA !== valB)
778
+ return valA - valB;
779
+ }
780
+ if (semA.prerelease.length === 0 && semB.prerelease.length === 0)
781
+ return 0;
782
+ if (semA.prerelease.length === 0)
783
+ return 1;
784
+ if (semB.prerelease.length === 0)
785
+ return -1;
786
+ const preLen = Math.min(semA.prerelease.length, semB.prerelease.length);
787
+ for (let i = 0; i < preLen; i += 1) {
788
+ const idA = semA.prerelease[i];
789
+ const idB = semB.prerelease[i];
790
+ const isNumA = /^\d+$/.test(idA);
791
+ const isNumB = /^\d+$/.test(idB);
792
+ if (isNumA && isNumB) {
793
+ const nA = BigInt(idA);
794
+ const nB = BigInt(idB);
795
+ if (nA !== nB)
796
+ return nA < nB ? -1 : 1;
797
+ }
798
+ else if (isNumA !== isNumB) {
799
+ return isNumA ? -1 : 1;
800
+ }
801
+ else if (idA !== idB) {
802
+ return idA < idB ? -1 : 1;
803
+ }
804
+ }
805
+ return semA.prerelease.length - semB.prerelease.length;
806
+ }
807
+ return compareNaturalChunks(a, b);
808
+ }
809
+ async function runGitLsRemote(args, timeoutMs, sourceKind) {
810
+ const gitBin = resolveGitExecutable();
811
+ const protocolArgs = sourceKind === 'local-dir'
812
+ ? ['-c', 'protocol.file.allow=always', '-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never']
813
+ : ['-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never'];
814
+ const { stdout } = await execFileAsync(gitBin, [...protocolArgs, ...args], {
815
+ env: buildCleanGitEnv(),
816
+ timeout: timeoutMs,
817
+ maxBuffer: MAX_RESPONSE_BYTES,
818
+ encoding: 'utf8',
819
+ });
820
+ return stdout;
821
+ }
822
+ function extractReleaseTag(record) {
823
+ if (typeof record['tag_name'] === 'string' && record['tag_name'].length > 0) {
824
+ return record['tag_name'];
825
+ }
826
+ if (typeof record['name'] === 'string' && record['name'].length > 0) {
827
+ return record['name'];
828
+ }
829
+ return undefined;
830
+ }
831
+ function collectReleaseTags(items, options) {
832
+ const tags = [];
833
+ for (const item of items) {
834
+ if (!isPlainRecord(item) || item['draft'] === true)
835
+ continue;
836
+ if (!options.allowPrerelease && item['prerelease'] === true)
837
+ continue;
838
+ const itemTag = extractReleaseTag(item);
839
+ if (itemTag === undefined)
840
+ continue;
841
+ if (options.rejectTagPrerelease && isPrereleaseVersionTag(itemTag))
842
+ continue;
843
+ if (!tags.includes(itemTag))
844
+ tags.push(itemTag);
845
+ }
846
+ return tags;
847
+ }
848
+ function selectLatestVersionTag(tags, upstream) {
849
+ const candidates = upstream.allowPrerelease === false
850
+ ? tags.filter(tag => !isPrereleaseVersionTag(tag))
851
+ : [...tags];
852
+ if (candidates.length === 0) {
853
+ throw new TaskpackError('ACTION_INPUT_INVALID', `no non-prerelease tags found for ${upstream.source}`);
854
+ }
855
+ candidates.sort(compareVersionTags);
856
+ return candidates[candidates.length - 1];
857
+ }
858
+ function validateHttpUpstreamUrl(source, kind) {
859
+ if (typeof source !== 'string' || source.length === 0 || /[\0\r\n\s]/.test(source)) {
860
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${kind} source "${source}" is not a valid URL`);
861
+ }
862
+ let parsedUrl;
863
+ try {
864
+ parsedUrl = new URL(source);
865
+ }
866
+ catch {
867
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${kind} source "${source}" is not a valid URL`);
868
+ }
869
+ if (parsedUrl.username.length > 0 || parsedUrl.password.length > 0) {
870
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${kind} source "${source}" must not embed URL credentials`);
871
+ }
872
+ if (parsedUrl.hash.length > 0) {
873
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${kind} source "${source}" must not contain a URL fragment`);
874
+ }
875
+ if (parsedUrl.protocol === 'https:') {
876
+ return parsedUrl;
877
+ }
878
+ if (parsedUrl.protocol === 'http:') {
879
+ const host = parsedUrl.hostname.toLowerCase();
880
+ const isLoopback = host === '127.0.0.1' || host === 'localhost' || host === '[::1]' || host === '::1';
881
+ if (isLoopback) {
882
+ return parsedUrl;
883
+ }
884
+ }
885
+ throw new TaskpackError('ACTION_INPUT_INVALID', `${kind} source "${source}" must use https:// (plain http:// is allowed only for loopback hosts)`);
886
+ }
887
+ async function resolveSingleUpstreamDetails(upstream, context) {
888
+ const { apiBaseUrl, githubHeaders, fetchImpl, timeoutMs, scrubber } = context;
889
+ switch (upstream.kind) {
890
+ case 'github-release': {
891
+ if (!REPOSITORY_FULL_NAME_PATTERN.test(upstream.source)) {
892
+ throw new TaskpackError('ACTION_INPUT_INVALID', `github-release upstream "${upstream.id}" source "${upstream.source}" must be owner/repo`);
893
+ }
894
+ const list30Url = `${apiBaseUrl}/repos/${upstream.source}/releases?per_page=30`;
895
+ if (upstream.allowPrerelease === true) {
896
+ const list30 = await fetchJson(list30Url, fetchImpl, githubHeaders, timeoutMs, scrubber);
897
+ if (list30.ok && Array.isArray(list30.data)) {
898
+ const tags = collectReleaseTags(list30.data, { allowPrerelease: true, rejectTagPrerelease: false });
899
+ if (tags.length > 0) {
900
+ return { version: tags[0], recentVersions: Object.freeze(tags.slice(0, 20)) };
901
+ }
902
+ }
903
+ const latestUrl = `${apiBaseUrl}/repos/${upstream.source}/releases/latest`;
904
+ const latest = await fetchJson(latestUrl, fetchImpl, githubHeaders, timeoutMs, scrubber);
905
+ if (latest.ok && isPlainRecord(latest.data)) {
906
+ const latestTag = extractReleaseTag(latest.data);
907
+ if (latestTag !== undefined)
908
+ return { version: latestTag };
909
+ }
910
+ const listUrl = `${apiBaseUrl}/repos/${upstream.source}/releases?per_page=1`;
911
+ const list = await fetchJson(listUrl, fetchImpl, githubHeaders, timeoutMs, scrubber);
912
+ if (list.ok && Array.isArray(list.data) && list.data.length > 0 && isPlainRecord(list.data[0])) {
913
+ const firstTag = extractReleaseTag(list.data[0]);
914
+ if (firstTag !== undefined)
915
+ return { version: firstTag };
916
+ }
917
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub releases lookup failed (${list.status}) for ${upstream.source}`);
918
+ }
919
+ const rejectTagPrerelease = upstream.allowPrerelease === false;
920
+ const latestUrl = `${apiBaseUrl}/repos/${upstream.source}/releases/latest`;
921
+ const latest = await fetchJson(latestUrl, fetchImpl, githubHeaders, timeoutMs, scrubber);
922
+ let rejectedLatestTag = false;
923
+ if (latest.ok && isPlainRecord(latest.data) && latest.data['prerelease'] !== true) {
924
+ const latestTag = extractReleaseTag(latest.data);
925
+ if (latestTag !== undefined) {
926
+ if (rejectTagPrerelease && isPrereleaseVersionTag(latestTag)) {
927
+ rejectedLatestTag = true;
928
+ }
929
+ else {
930
+ let recentVersions;
931
+ try {
932
+ const list30 = await fetchJson(list30Url, fetchImpl, githubHeaders, timeoutMs, scrubber);
933
+ if (list30.ok && Array.isArray(list30.data)) {
934
+ const tags = collectReleaseTags(list30.data, { allowPrerelease: false, rejectTagPrerelease });
935
+ if (tags.length > 0) {
936
+ recentVersions = Object.freeze([latestTag, ...tags.filter(item => item !== latestTag)].slice(0, 20));
937
+ }
938
+ }
939
+ }
940
+ catch {
941
+ // Best-effort history enrichment; primary /releases/latest result stands.
942
+ }
943
+ return recentVersions !== undefined ? { version: latestTag, recentVersions } : { version: latestTag };
944
+ }
945
+ }
946
+ }
947
+ if (rejectedLatestTag) {
948
+ const list30 = await fetchJson(list30Url, fetchImpl, githubHeaders, timeoutMs, scrubber);
949
+ if (!list30.ok || !Array.isArray(list30.data)) {
950
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub releases lookup failed (${list30.status}) for ${upstream.source}`);
951
+ }
952
+ const stableTags = collectReleaseTags(list30.data, { allowPrerelease: false, rejectTagPrerelease: true });
953
+ if (stableTags.length > 0) {
954
+ const bestVersion = [...stableTags].sort(compareVersionTags).at(-1);
955
+ return {
956
+ version: bestVersion,
957
+ recentVersions: Object.freeze([bestVersion, ...stableTags.filter(item => item !== bestVersion)].slice(0, 20)),
958
+ };
959
+ }
960
+ throw new TaskpackError('ACTION_INPUT_INVALID', `no non-prerelease releases found for ${upstream.source}`);
961
+ }
962
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub release lookup failed (${latest.status}) for ${upstream.source}`);
963
+ }
964
+ case 'git-tag': {
965
+ if (REPOSITORY_FULL_NAME_PATTERN.test(upstream.source)) {
966
+ const url = `${apiBaseUrl}/repos/${upstream.source}/tags?per_page=100`;
967
+ const res = await fetchJson(url, fetchImpl, githubHeaders, timeoutMs, scrubber);
968
+ if (!res.ok || !Array.isArray(res.data) || res.data.length === 0) {
969
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub tags lookup failed (${res.status}) for ${upstream.source}`);
970
+ }
971
+ const tagNames = [];
972
+ let fallbackSha;
973
+ for (const item of res.data) {
974
+ if (!isPlainRecord(item))
975
+ continue;
976
+ if (typeof item['name'] === 'string' && item['name'].length > 0) {
977
+ tagNames.push(item['name']);
978
+ }
979
+ else if (fallbackSha === undefined) {
980
+ const commit = isPlainRecord(item['commit']) ? item['commit'] : undefined;
981
+ if (commit && typeof commit['sha'] === 'string' && commit['sha'].length > 0) {
982
+ fallbackSha = commit['sha'];
983
+ }
984
+ }
985
+ }
986
+ if (tagNames.length > 0) {
987
+ return { version: selectLatestVersionTag(tagNames, upstream) };
988
+ }
989
+ if (fallbackSha !== undefined)
990
+ return { version: fallbackSha };
991
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub tags payload lacked tag name for ${upstream.source}`);
992
+ }
993
+ const sourceKind = validateGitRemoteSource(upstream.source, context.repositoryRoot);
994
+ const gitSource = sourceKind === 'local-dir' && context.repositoryRoot !== undefined
995
+ ? resolve(context.repositoryRoot, upstream.source)
996
+ : upstream.source;
997
+ const stdout = await runGitLsRemote(['ls-remote', '--tags', '--refs', '--', gitSource], timeoutMs, sourceKind);
998
+ const tags = stdout
999
+ .split(/\r?\n/)
1000
+ .map(line => line.trim())
1001
+ .filter(line => line.length > 0)
1002
+ .map(line => {
1003
+ const tabIdx = line.indexOf('\t');
1004
+ const refPart = tabIdx >= 0 ? line.slice(tabIdx + 1) : line;
1005
+ return refPart.replace(/^refs\/tags\//, '');
1006
+ })
1007
+ .filter(tag => tag.length > 0);
1008
+ if (tags.length === 0) {
1009
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git ls-remote returned no tags for ${upstream.source}`);
1010
+ }
1011
+ return { version: selectLatestVersionTag(tags, upstream) };
1012
+ }
1013
+ case 'git-commit': {
1014
+ if (REPOSITORY_FULL_NAME_PATTERN.test(upstream.source)) {
1015
+ const url = `${apiBaseUrl}/repos/${upstream.source}/commits?per_page=1`;
1016
+ const res = await fetchJson(url, fetchImpl, githubHeaders, timeoutMs, scrubber);
1017
+ if (!res.ok || !Array.isArray(res.data) || res.data.length === 0 || !isPlainRecord(res.data[0])) {
1018
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub commits lookup failed (${res.status}) for ${upstream.source}`);
1019
+ }
1020
+ const sha = res.data[0]['sha'];
1021
+ if (typeof sha === 'string' && sha.length > 0)
1022
+ return { version: sha };
1023
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub commits payload lacked sha for ${upstream.source}`);
1024
+ }
1025
+ const sourceKind = validateGitRemoteSource(upstream.source, context.repositoryRoot);
1026
+ const gitSource = sourceKind === 'local-dir' && context.repositoryRoot !== undefined
1027
+ ? resolve(context.repositoryRoot, upstream.source)
1028
+ : upstream.source;
1029
+ const stdout = await runGitLsRemote(['ls-remote', '--', gitSource, 'HEAD', 'refs/heads/main', 'refs/heads/master'], timeoutMs, sourceKind);
1030
+ const refShas = new Map();
1031
+ let firstSha;
1032
+ for (const rawLine of stdout.split(/\r?\n/)) {
1033
+ const trimmed = rawLine.trim();
1034
+ if (trimmed.length === 0)
1035
+ continue;
1036
+ const parts = trimmed.split(/\s+/);
1037
+ const sha = parts[0];
1038
+ if (!sha) {
1039
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git ls-remote HEAD output malformed for ${upstream.source}`);
1040
+ }
1041
+ if (firstSha === undefined)
1042
+ firstSha = sha;
1043
+ const ref = parts[1];
1044
+ if (ref)
1045
+ refShas.set(ref, sha);
1046
+ }
1047
+ const sha = refShas.get('HEAD') ?? refShas.get('refs/heads/main') ?? refShas.get('refs/heads/master') ?? firstSha;
1048
+ if (sha === undefined) {
1049
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git ls-remote returned no HEAD for ${upstream.source}`);
1050
+ }
1051
+ return { version: sha };
1052
+ }
1053
+ case 'http-json': {
1054
+ validateHttpUpstreamUrl(upstream.source, 'http-json');
1055
+ const res = await fetchJson(upstream.source, fetchImpl, { accept: 'application/json', 'user-agent': 'loopwright-taskpack' }, timeoutMs, scrubber);
1056
+ if (!res.ok) {
1057
+ throw new TaskpackError('ACTION_INPUT_INVALID', `http-json fetch failed (${res.status}) for ${upstream.id}`);
1058
+ }
1059
+ if (upstream.versionPath !== undefined) {
1060
+ const extracted = extractJsonVersionPath(res.data, upstream.versionPath);
1061
+ if (extracted === undefined) {
1062
+ throw new TaskpackError('ACTION_INPUT_INVALID', `http-json versionPath "${upstream.versionPath}" did not resolve to a non-empty string for ${upstream.id}`);
1063
+ }
1064
+ return { version: extracted };
1065
+ }
1066
+ if (isPlainRecord(res.data)) {
1067
+ for (const key of ['version', 'tag_name', 'latest', 'sha']) {
1068
+ const candidate = res.data[key];
1069
+ if (typeof candidate === 'string' && candidate.trim().length > 0) {
1070
+ return { version: validateVersionStringField(candidate, `${upstream.id}.${key}`) };
1071
+ }
1072
+ }
1073
+ }
1074
+ return { version: createHash('sha256').update(res.rawText, 'utf8').digest('hex').slice(0, 16) };
1075
+ }
1076
+ case 'custom-table': {
1077
+ let rawBytes;
1078
+ if (upstream.source.startsWith('http://') || upstream.source.startsWith('https://')) {
1079
+ validateHttpUpstreamUrl(upstream.source, 'custom-table');
1080
+ const res = await fetchBoundedText(upstream.source, fetchImpl, { accept: 'application/json, text/plain;q=0.9', 'user-agent': 'loopwright-taskpack' }, timeoutMs, scrubber);
1081
+ if (!res.ok) {
1082
+ throw new TaskpackError('ACTION_INPUT_INVALID', `custom-table fetch failed (${res.status}) for ${upstream.id}`);
1083
+ }
1084
+ rawBytes = Buffer.from(res.text, 'utf8');
1085
+ }
1086
+ else {
1087
+ if (context.repositoryRoot === undefined) {
1088
+ throw new TaskpackError('ACTION_INPUT_INVALID', `repositoryRoot is required to read local custom-table "${upstream.source}"`);
1089
+ }
1090
+ rawBytes = await readBoundedLocalFile(context.repositoryRoot, upstream.source, MAX_RESPONSE_BYTES);
1091
+ }
1092
+ try {
1093
+ const parsed = JSON.parse(rawBytes.toString('utf8'));
1094
+ if (isPlainRecord(parsed) && typeof parsed['version'] === 'string' && parsed['version'].trim().length > 0) {
1095
+ return { version: parsed['version'].trim() };
1096
+ }
1097
+ }
1098
+ catch {
1099
+ // Non-JSON custom table: hash content below.
1100
+ }
1101
+ return { version: createHash('sha256').update(rawBytes).digest('hex').slice(0, 16) };
1102
+ }
1103
+ }
1104
+ }
1105
+ /**
1106
+ * Apply declarative `spec.upstreamGroups` (`lockstep` | `independent`) across resolved upstream
1107
+ * acquisition records (supports both HTTP-discovered and preflight-supplied records).
1108
+ */
1109
+ export function applyUpstreamGroups(records, groups, baselineVersions) {
1110
+ if (groups === undefined || groups.length === 0 || records.length === 0) {
1111
+ return Object.freeze([...records]);
1112
+ }
1113
+ const lookupBaseline = (upstreamId) => {
1114
+ if (baselineVersions === undefined)
1115
+ return undefined;
1116
+ if (baselineVersions instanceof Map)
1117
+ return baselineVersions.get(upstreamId);
1118
+ const val = baselineVersions[upstreamId];
1119
+ return typeof val === 'string' && val.length > 0 ? val : undefined;
1120
+ };
1121
+ const byId = new Map();
1122
+ for (const record of records) {
1123
+ byId.set(record.upstreamId, record);
1124
+ }
1125
+ const overrides = new Map();
1126
+ for (const group of groups) {
1127
+ if (group.policy === 'independent') {
1128
+ for (const memberId of group.members) {
1129
+ const member = byId.get(memberId);
1130
+ if (member === undefined || member.groupId === group.id)
1131
+ continue;
1132
+ overrides.set(member.upstreamId, Object.freeze({
1133
+ ...member,
1134
+ groupId: group.id,
1135
+ }));
1136
+ }
1137
+ continue;
1138
+ }
1139
+ const presentMembers = [];
1140
+ const issueReasons = [];
1141
+ for (const memberId of group.members) {
1142
+ const rec = byId.get(memberId);
1143
+ if (rec === undefined) {
1144
+ issueReasons.push(`missing upstream record for member "${memberId}"`);
1145
+ }
1146
+ else {
1147
+ presentMembers.push(rec);
1148
+ }
1149
+ }
1150
+ for (const member of presentMembers) {
1151
+ if (member.status === 'held_back' || member.status === 'blocked' || member.status === 'failed') {
1152
+ const detail = member.reason !== undefined && member.reason.length > 0 ? ` (${sanitizeSingleLine(member.reason)})` : '';
1153
+ issueReasons.push(`member "${member.upstreamId}" is ${member.status}${detail}`);
1154
+ }
1155
+ else if (typeof member.version !== 'string' || member.version.trim().length === 0) {
1156
+ issueReasons.push(`member "${member.upstreamId}" has no resolved target version`);
1157
+ }
1158
+ }
1159
+ if (issueReasons.length === 0) {
1160
+ const anyAvailable = presentMembers.some(member => member.status === 'available');
1161
+ if (anyAvailable) {
1162
+ const distinctTargetVersions = new Set(presentMembers.map(member => member.version));
1163
+ if (distinctTargetVersions.size > 1) {
1164
+ const breakdown = presentMembers
1165
+ .map(member => `${member.upstreamId}=${member.version ?? 'unknown'}[${member.status}]`)
1166
+ .join(', ');
1167
+ issueReasons.push(`member target versions disagree (${breakdown})`);
1168
+ }
1169
+ }
1170
+ }
1171
+ if (issueReasons.length > 0) {
1172
+ const groupReason = `lockstep group "${group.id}" held back: ${issueReasons.join('; ')}`;
1173
+ for (const memberId of group.members) {
1174
+ const member = byId.get(memberId);
1175
+ if (member === undefined)
1176
+ continue;
1177
+ const preservedCurrent = member.currentVersion
1178
+ ?? lookupBaseline(member.upstreamId)
1179
+ ?? (member.status === 'up_to_date' ? member.version : undefined);
1180
+ const skippedTarget = member.targetVersion
1181
+ ?? (member.status === 'available' ? member.version : undefined);
1182
+ const underlyingStatus = member.status === 'failed' || member.status === 'blocked'
1183
+ ? member.status
1184
+ : member.underlyingStatus;
1185
+ overrides.set(member.upstreamId, Object.freeze({
1186
+ upstreamId: member.upstreamId,
1187
+ status: 'held_back',
1188
+ ...(preservedCurrent !== undefined ? { version: preservedCurrent, currentVersion: preservedCurrent } : {}),
1189
+ ...(skippedTarget !== undefined ? { targetVersion: skippedTarget } : {}),
1190
+ ...(member.recentVersions !== undefined ? { recentVersions: member.recentVersions } : {}),
1191
+ ...(member.watchedPaths !== undefined ? { watchedPaths: member.watchedPaths } : {}),
1192
+ ...(member.metadata !== undefined ? { metadata: member.metadata } : {}),
1193
+ ...(underlyingStatus !== undefined ? { underlyingStatus } : {}),
1194
+ groupId: group.id,
1195
+ reason: groupReason,
1196
+ }));
1197
+ }
1198
+ }
1199
+ else {
1200
+ for (const member of presentMembers) {
1201
+ if (member.groupId === group.id)
1202
+ continue;
1203
+ overrides.set(member.upstreamId, Object.freeze({
1204
+ ...member,
1205
+ groupId: group.id,
1206
+ }));
1207
+ }
1208
+ }
1209
+ }
1210
+ if (overrides.size === 0) {
1211
+ return Object.freeze([...records]);
1212
+ }
1213
+ return Object.freeze(records.map(record => overrides.get(record.upstreamId) ?? record));
1214
+ }
1215
+ /** Propagate declared `watchedPaths` onto resolved upstream acquisition records without mutating inputs. */
1216
+ export function attachUpstreamContext(records, descriptors) {
1217
+ if (records.length === 0 || descriptors.length === 0) {
1218
+ return Object.freeze([...records]);
1219
+ }
1220
+ const byId = new Map();
1221
+ for (const descriptor of descriptors) {
1222
+ byId.set(descriptor.id, descriptor);
1223
+ }
1224
+ return Object.freeze(records.map(record => {
1225
+ const desc = byId.get(record.upstreamId);
1226
+ if (desc === undefined || (record.watchedPaths !== undefined && record.watchedPaths.length > 0)) {
1227
+ return record;
1228
+ }
1229
+ return Object.freeze({
1230
+ ...record,
1231
+ watchedPaths: Object.freeze([...desc.watchedPaths]),
1232
+ });
1233
+ }));
1234
+ }
1235
+ /** Evaluate overall intake disposition across upstream acquisition records. */
1236
+ export function evaluateUpstreamIntakeDisposition(records, options) {
1237
+ const available = Object.freeze(records.filter(record => record.status === 'available'));
1238
+ const heldBack = Object.freeze(records.filter(record => record.status === 'held_back'));
1239
+ const upToDate = Object.freeze(records.filter(record => record.status === 'up_to_date'));
1240
+ const failures = Object.freeze(records.filter(record => record.status === 'failed'
1241
+ || record.status === 'blocked'
1242
+ || record.underlyingStatus === 'failed'
1243
+ || record.underlyingStatus === 'blocked'));
1244
+ if (available.length === 0 && failures.length > 0) {
1245
+ const failedSummary = failures
1246
+ .map(record => {
1247
+ const statusLabel = record.underlyingStatus ?? record.status;
1248
+ const detail = record.reason !== undefined && record.reason.length > 0 ? `: ${sanitizeSingleLine(record.reason)}` : '';
1249
+ return `${record.upstreamId}(${statusLabel}${detail})`;
1250
+ })
1251
+ .join('; ');
1252
+ return Object.freeze({
1253
+ disposition: 'blocked',
1254
+ reason: `upstream acquisition blocked: ${failedSummary}`,
1255
+ available,
1256
+ heldBack,
1257
+ upToDate,
1258
+ failures,
1259
+ });
1260
+ }
1261
+ if (options?.force !== true && available.length === 0) {
1262
+ const reason = heldBack.length > 0
1263
+ ? `no updates ready; held_back: ${heldBack.map(record => `${record.upstreamId}${record.reason ? ` (${sanitizeSingleLine(record.reason)})` : ''}`).join('; ')}`
1264
+ : 'no subscription reports an available update';
1265
+ return Object.freeze({
1266
+ disposition: 'no_change',
1267
+ reason,
1268
+ available,
1269
+ heldBack,
1270
+ upToDate,
1271
+ failures,
1272
+ });
1273
+ }
1274
+ if (options?.force !== true && options?.managedPrMatchesDiscoveredState === true) {
1275
+ return Object.freeze({
1276
+ disposition: 'no_change',
1277
+ reason: 'an open managed pull request already matches the discovered state',
1278
+ available,
1279
+ heldBack,
1280
+ upToDate,
1281
+ failures,
1282
+ });
1283
+ }
1284
+ const availablePart = available.length > 0
1285
+ ? `available: ${available.map(r => `${r.upstreamId}=${sanitizeSingleLine(r.version ?? 'unknown')}`).join(', ')}`
1286
+ : 'forced candidate run';
1287
+ const heldBackPart = heldBack.length > 0
1288
+ ? `; held_back: ${heldBack.map(r => `${r.upstreamId}${r.currentVersion ? `@${sanitizeSingleLine(r.currentVersion)}` : ''}`).join(', ')}`
1289
+ : '';
1290
+ return Object.freeze({
1291
+ disposition: 'candidate',
1292
+ reason: `${availablePart}${heldBackPart}`,
1293
+ available,
1294
+ heldBack,
1295
+ upToDate,
1296
+ failures,
1297
+ });
1298
+ }
1299
+ /**
1300
+ * Build deterministic sorted `{ upstreamId: version }` metadata for reviewed memory while keeping
1301
+ * `held_back` upstreams pinned to `currentVersion` (never substituting a skipped target version).
1302
+ */
1303
+ export function buildUpstreamMemoryVersions(records) {
1304
+ const out = Object.create(null);
1305
+ if (records === undefined || records.length === 0) {
1306
+ return Object.freeze(out);
1307
+ }
1308
+ const sorted = [...records].sort((a, b) => (a.upstreamId < b.upstreamId ? -1 : a.upstreamId > b.upstreamId ? 1 : 0));
1309
+ let count = 0;
1310
+ for (const record of sorted) {
1311
+ if (count >= 128)
1312
+ break;
1313
+ let chosen;
1314
+ if (record.status === 'held_back') {
1315
+ chosen = record.currentVersion;
1316
+ }
1317
+ else if (record.status === 'failed' || record.status === 'blocked') {
1318
+ chosen = record.currentVersion;
1319
+ }
1320
+ else {
1321
+ chosen = record.version ?? record.currentVersion;
1322
+ }
1323
+ if (typeof chosen === 'string' && chosen.length > 0 && chosen.length <= 256) {
1324
+ out[record.upstreamId] = chosen;
1325
+ count += 1;
1326
+ }
1327
+ }
1328
+ return Object.freeze(out);
1329
+ }
1330
+ /** Format a concise multi-line upstream summary including `held_back` reasons and `watchedPaths`. */
1331
+ export function formatUpstreamSummary(records, descriptors) {
1332
+ const enriched = descriptors !== undefined ? attachUpstreamContext(records, descriptors) : records;
1333
+ if (enriched.length === 0)
1334
+ return 'upstreams: none';
1335
+ const lines = enriched.map(record => {
1336
+ const parts = [`- ${record.upstreamId}: status=${record.status}`];
1337
+ if (record.currentVersion !== undefined) {
1338
+ parts.push(`current=${record.currentVersion}`);
1339
+ }
1340
+ if (record.status === 'held_back') {
1341
+ if (record.targetVersion !== undefined) {
1342
+ parts.push(`skippedTarget=${record.targetVersion}`);
1343
+ }
1344
+ }
1345
+ else if (record.version !== undefined) {
1346
+ parts.push(`version=${record.version}`);
1347
+ }
1348
+ if (record.groupId !== undefined) {
1349
+ parts.push(`group=${record.groupId}`);
1350
+ }
1351
+ if (record.watchedPaths !== undefined && record.watchedPaths.length > 0) {
1352
+ parts.push(`watchedPaths=[${record.watchedPaths.join(', ')}]`);
1353
+ }
1354
+ if (record.reason !== undefined && record.reason.length > 0) {
1355
+ parts.push(`reason=${sanitizeSingleLine(record.reason)}`);
1356
+ }
1357
+ return parts.join(' ');
1358
+ });
1359
+ return lines.join('\n');
1360
+ }
1361
+ async function readOptionalLocalJsonFile(repositoryRoot, relPath, maxBytes, parseJson) {
1362
+ const resolvedBase = resolve(repositoryRoot);
1363
+ const fullPath = resolve(resolvedBase, relPath);
1364
+ assertNoSymlinkSegments(resolvedBase, fullPath);
1365
+ try {
1366
+ const info = await lstat(fullPath);
1367
+ if (info.isSymbolicLink()) {
1368
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `baseline file "${relPath}" must not be a symbolic link`);
1369
+ }
1370
+ }
1371
+ catch (error) {
1372
+ if (error instanceof TaskpackError)
1373
+ throw error;
1374
+ const code = error?.code;
1375
+ if (code === 'ENOENT') {
1376
+ return undefined;
1377
+ }
1378
+ if (code === 'ELOOP') {
1379
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `baseline file "${relPath}" traverses a symbolic link`);
1380
+ }
1381
+ const detail = error instanceof Error ? error.message : String(error);
1382
+ throw new TaskpackError('ACTION_INPUT_INVALID', `failed to inspect baseline file "${relPath}": ${detail}`);
1383
+ }
1384
+ let bytes;
1385
+ try {
1386
+ bytes = await readBoundedLocalFile(repositoryRoot, relPath, maxBytes);
1387
+ }
1388
+ catch (error) {
1389
+ if (error instanceof TaskpackError)
1390
+ throw error;
1391
+ const code = error?.code;
1392
+ if (code === 'ENOENT') {
1393
+ return undefined;
1394
+ }
1395
+ if (code === 'ELOOP') {
1396
+ throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `baseline file "${relPath}" traverses a symbolic link`);
1397
+ }
1398
+ const detail = error instanceof Error ? error.message : String(error);
1399
+ throw new TaskpackError('ACTION_INPUT_INVALID', `failed to read baseline file "${relPath}": ${detail}`);
1400
+ }
1401
+ if (!parseJson) {
1402
+ return undefined;
1403
+ }
1404
+ try {
1405
+ return JSON.parse(bytes.toString('utf8'));
1406
+ }
1407
+ catch (error) {
1408
+ const detail = error instanceof Error ? error.message : String(error);
1409
+ throw new TaskpackError('ACTION_INPUT_INVALID', `baseline file "${relPath}" contains malformed JSON: ${detail}`);
1410
+ }
1411
+ }
1412
+ export function extractBaselineVersionsFromDocument(manifest, parsed, sourceKind) {
1413
+ return sourceKind === 'proposal'
1414
+ ? readBaselineVersions(parsed, manifest.spec.upstreams)
1415
+ : readPackageJsonBaselineVersions(parsed, manifest.spec.upstreams);
1416
+ }
1417
+ /**
1418
+ * Load baseline upstream versions from `spec.proposal.path` (or `package.json` when `spec.proposal`
1419
+ * is omitted), merged with any explicit `baselineVersions` overrides.
1420
+ */
1421
+ export async function loadRepositoryBaselineVersions(manifest, repositoryRoot, explicitBaselines) {
1422
+ const baselines = new Map();
1423
+ if (repositoryRoot !== undefined) {
1424
+ const proposal = manifest.spec.proposal;
1425
+ if (proposal !== undefined) {
1426
+ const isJsonProposal = proposal.path.toLowerCase().endsWith('.json');
1427
+ const parsed = await readOptionalLocalJsonFile(repositoryRoot, proposal.path, MAX_PROPOSAL_BYTES, isJsonProposal);
1428
+ if (parsed !== undefined) {
1429
+ for (const [id, ver] of readBaselineVersions(parsed, manifest.spec.upstreams)) {
1430
+ baselines.set(id, ver);
1431
+ }
1432
+ }
1433
+ }
1434
+ else {
1435
+ const parsed = await readOptionalLocalJsonFile(repositoryRoot, 'package.json', MAX_PROPOSAL_BYTES, true);
1436
+ if (parsed !== undefined) {
1437
+ for (const [id, ver] of readPackageJsonBaselineVersions(parsed, manifest.spec.upstreams)) {
1438
+ baselines.set(id, ver);
1439
+ }
1440
+ }
1441
+ }
1442
+ }
1443
+ if (explicitBaselines !== undefined) {
1444
+ if (explicitBaselines instanceof Map) {
1445
+ for (const [id, ver] of explicitBaselines.entries()) {
1446
+ if (typeof ver === 'string' && ver.length > 0)
1447
+ baselines.set(id, ver);
1448
+ }
1449
+ }
1450
+ else {
1451
+ for (const [id, ver] of Object.entries(explicitBaselines)) {
1452
+ if (typeof ver === 'string' && ver.length > 0)
1453
+ baselines.set(id, ver);
1454
+ }
1455
+ }
1456
+ }
1457
+ return baselines;
1458
+ }
1459
+ /**
1460
+ * Discover upstream states declared by a Taskpack manifest and compare against
1461
+ * any existing proposal file (or `package.json` / explicit `baselineVersions` when `spec.proposal`
1462
+ * is omitted), enforcing `http-json` `versionPath`, `monotonicSemver`, and `spec.upstreamGroups`.
1463
+ */
1464
+ export async function discoverTaskpackUpstreams(manifest, options = {}) {
1465
+ if (options.upstreamRecordsJson !== undefined && options.upstreamRecordsJson.trim().length > 0) {
1466
+ const parsed = parseUpstreamRecordsJson(options.upstreamRecordsJson);
1467
+ const withContext = options.includeMetadata === true
1468
+ ? attachUpstreamContext(parsed, manifest.spec.upstreams)
1469
+ : parsed;
1470
+ const baselines = manifest.spec.upstreamGroups !== undefined && manifest.spec.upstreamGroups.length > 0
1471
+ ? await loadRepositoryBaselineVersions(manifest, options.skipWorkingTreeBaselines === true ? undefined : options.repositoryRoot, options.baselineVersions)
1472
+ : undefined;
1473
+ return applyUpstreamGroups(withContext, manifest.spec.upstreamGroups, baselines);
1474
+ }
1475
+ if (manifest.spec.upstreams.length === 0) {
1476
+ return Object.freeze([]);
1477
+ }
1478
+ const scrubber = options.scrubber ?? new SecretScrubber();
1479
+ const apiBaseUrl = defaultApiBaseUrl(options.apiBaseUrl, options.env);
1480
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1481
+ const timeoutMs = options.timeoutMs ?? 15_000;
1482
+ const githubHeaders = await resolveAuthHeaders(options.githubToken, options.authHeaders, { accept: 'application/vnd.github+json', 'user-agent': 'loopwright-taskpack' }, scrubber);
1483
+ const baselines = await loadRepositoryBaselineVersions(manifest, options.skipWorkingTreeBaselines === true ? undefined : options.repositoryRoot, options.baselineVersions);
1484
+ const includeMetadata = options.includeMetadata === true;
1485
+ const records = [];
1486
+ for (const upstream of manifest.spec.upstreams) {
1487
+ const baseline = baselines.get(upstream.id);
1488
+ try {
1489
+ const resolved = await resolveSingleUpstreamDetails(upstream, {
1490
+ repositoryRoot: options.repositoryRoot,
1491
+ apiBaseUrl,
1492
+ githubHeaders,
1493
+ fetchImpl,
1494
+ timeoutMs,
1495
+ scrubber,
1496
+ });
1497
+ let status;
1498
+ let effectiveVersion = resolved.version;
1499
+ let targetVersion;
1500
+ let reason;
1501
+ if (upstream.kind === 'http-json') {
1502
+ const monotonic = upstream.monotonicSemver ?? true;
1503
+ if (baseline === undefined) {
1504
+ status = 'available';
1505
+ }
1506
+ else if (baseline === resolved.version) {
1507
+ status = 'up_to_date';
1508
+ }
1509
+ else if (monotonic) {
1510
+ const strictCmp = compareStrictSemver(resolved.version, baseline);
1511
+ if (strictCmp !== null && strictCmp < 0) {
1512
+ status = 'held_back';
1513
+ effectiveVersion = baseline;
1514
+ targetVersion = resolved.version;
1515
+ reason = `downgrade prevented by monotonicSemver: fetched ${resolved.version} is lower than current ${baseline}`;
1516
+ }
1517
+ else if (strictCmp === 0 && !baseline.includes('+') && !resolved.version.includes('+')) {
1518
+ status = 'up_to_date';
1519
+ }
1520
+ else {
1521
+ status = 'available';
1522
+ }
1523
+ }
1524
+ else {
1525
+ status = 'available';
1526
+ }
1527
+ }
1528
+ else {
1529
+ const isSemverTagKind = upstream.kind === 'github-release' || upstream.kind === 'git-tag';
1530
+ const cmp = isSemverTagKind && baseline !== undefined && parseSemverTag(baseline) !== null && parseSemverTag(resolved.version) !== null
1531
+ ? compareVersionTags(resolved.version, baseline)
1532
+ : null;
1533
+ const upToDateBySemver = cmp !== null && (cmp < 0
1534
+ || (cmp === 0 && !baseline.includes('+') && !resolved.version.includes('+')));
1535
+ status = baseline !== undefined && (baseline === resolved.version || upToDateBySemver)
1536
+ ? 'up_to_date'
1537
+ : 'available';
1538
+ }
1539
+ const emitMetadata = includeMetadata || status === 'held_back';
1540
+ records.push({
1541
+ upstreamId: upstream.id,
1542
+ status,
1543
+ ...(effectiveVersion !== undefined ? { version: effectiveVersion } : {}),
1544
+ ...(emitMetadata && baseline !== undefined ? { currentVersion: baseline } : {}),
1545
+ ...(targetVersion !== undefined ? { targetVersion } : {}),
1546
+ ...(resolved.recentVersions !== undefined ? { recentVersions: resolved.recentVersions } : {}),
1547
+ ...(includeMetadata ? { watchedPaths: Object.freeze([...upstream.watchedPaths]) } : {}),
1548
+ ...(reason !== undefined ? { reason } : {}),
1549
+ });
1550
+ }
1551
+ catch (error) {
1552
+ const detail = error instanceof Error ? error.message : String(error);
1553
+ records.push({
1554
+ upstreamId: upstream.id,
1555
+ status: 'failed',
1556
+ ...(includeMetadata && baseline !== undefined ? { currentVersion: baseline } : {}),
1557
+ ...(includeMetadata ? { watchedPaths: Object.freeze([...upstream.watchedPaths]) } : {}),
1558
+ reason: scrubber.scrub(detail),
1559
+ });
1560
+ }
1561
+ }
1562
+ return applyUpstreamGroups(Object.freeze(records), manifest.spec.upstreamGroups, baselines);
1563
+ }
1564
+ /**
1565
+ * Taskpack 2.0 upstream discovery entrypoint returning enriched records (with `watchedPaths`,
1566
+ * `currentVersion`, `targetVersion`, `groupId`), evaluated disposition, prompt summary, and
1567
+ * reviewed-memory version map (`held_back` pinned to `currentVersion`).
1568
+ */
1569
+ export async function discoverTaskpackUpstreamsV2(manifest, options = {}) {
1570
+ const records = await discoverTaskpackUpstreams(manifest, {
1571
+ ...options,
1572
+ includeMetadata: true,
1573
+ });
1574
+ const evaluated = evaluateUpstreamIntakeDisposition(records, {
1575
+ force: options.force,
1576
+ managedPrMatchesDiscoveredState: options.managedPrMatchesDiscoveredState,
1577
+ });
1578
+ return Object.freeze({
1579
+ records,
1580
+ disposition: evaluated.disposition,
1581
+ reason: evaluated.reason,
1582
+ summary: formatUpstreamSummary(records, manifest.spec.upstreams),
1583
+ memoryVersions: buildUpstreamMemoryVersions(records),
1584
+ });
1585
+ }
1586
+ export const MEMORY_PULL_REQUEST_BRANCH_PREFIX = 'loopwright/memory/';
1587
+ /**
1588
+ * Look up an open pull request against `targetBranch` whose head ref begins
1589
+ * with `headBranchPrefix`.
1590
+ */
1591
+ export async function findOpenManagedPullRequest(options) {
1592
+ if (!REPOSITORY_FULL_NAME_PATTERN.test(options.repositoryFullName)) {
1593
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid repositoryFullName "${options.repositoryFullName}"`);
1594
+ }
1595
+ const scrubber = options.scrubber ?? new SecretScrubber();
1596
+ const apiBaseUrl = defaultApiBaseUrl(options.apiBaseUrl, options.env);
1597
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1598
+ const timeoutMs = options.timeoutMs ?? 15_000;
1599
+ const headers = await resolveAuthHeaders(options.githubToken, options.authHeaders, { accept: 'application/vnd.github+json', 'user-agent': 'loopwright-taskpack' }, scrubber);
1600
+ let confirmedAbsence = false;
1601
+ for (let page = 1; page <= 5; page += 1) {
1602
+ const url = `${apiBaseUrl}/repos/${options.repositoryFullName}/pulls?state=open&base=${encodeURIComponent(options.targetBranch)}&per_page=100&page=${page}`;
1603
+ const res = await fetchJson(url, fetchImpl, headers, timeoutMs, scrubber);
1604
+ if (!res.ok) {
1605
+ throw new TaskpackError('ACTION_INPUT_INVALID', `open pull requests lookup failed (${res.status}) for ${options.repositoryFullName}`);
1606
+ }
1607
+ if (!Array.isArray(res.data)) {
1608
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'GitHub pulls response must be an array');
1609
+ }
1610
+ for (const item of res.data) {
1611
+ if (!isPlainRecord(item))
1612
+ continue;
1613
+ const head = isPlainRecord(item['head']) ? item['head'] : undefined;
1614
+ const base = isPlainRecord(item['base']) ? item['base'] : undefined;
1615
+ const headRepo = head?.['repo'];
1616
+ const headRepoValid = headRepo === undefined || headRepo === null || (isPlainRecord(headRepo)
1617
+ && headRepo['fork'] !== true
1618
+ && typeof headRepo['full_name'] === 'string'
1619
+ && headRepo['full_name'].toLowerCase() === options.repositoryFullName.toLowerCase());
1620
+ if (!headRepoValid)
1621
+ continue;
1622
+ const headRef = head?.['ref'];
1623
+ const headSha = head?.['sha'];
1624
+ const baseRef = base?.['ref'];
1625
+ const baseSha = base?.['sha'];
1626
+ const prNumber = item['number'];
1627
+ const htmlUrl = item['html_url'];
1628
+ const title = item['title'];
1629
+ const body = item['body'];
1630
+ if (typeof headRef === 'string'
1631
+ && headRef.startsWith(options.headBranchPrefix)
1632
+ && (options.headBranchPrefix.startsWith(MEMORY_PULL_REQUEST_BRANCH_PREFIX) || !headRef.startsWith(MEMORY_PULL_REQUEST_BRANCH_PREFIX))
1633
+ && typeof headSha === 'string'
1634
+ && typeof baseRef === 'string'
1635
+ && typeof baseSha === 'string'
1636
+ && typeof prNumber === 'number'
1637
+ && Number.isSafeInteger(prNumber)
1638
+ && prNumber > 0
1639
+ && typeof htmlUrl === 'string'
1640
+ && typeof title === 'string') {
1641
+ return {
1642
+ number: prNumber,
1643
+ htmlUrl,
1644
+ headRef,
1645
+ headSha,
1646
+ baseRef,
1647
+ baseSha,
1648
+ title,
1649
+ body: typeof body === 'string' ? body : null,
1650
+ };
1651
+ }
1652
+ }
1653
+ if (res.data.length < 100) {
1654
+ confirmedAbsence = true;
1655
+ break;
1656
+ }
1657
+ }
1658
+ if (!confirmedAbsence) {
1659
+ throw new TaskpackError('ACTION_INPUT_INVALID', `open pull requests lookup exhausted pagination (500 open pull requests) for ${options.repositoryFullName} without confirming absence`);
1660
+ }
1661
+ return null;
1662
+ }
1663
+ /**
1664
+ * Look up an existing open dedicated memory pull request whose same-repository
1665
+ * `head.ref` exactly equals `memoryBranch` targeting `targetBranch`.
1666
+ */
1667
+ export async function findOpenMemoryPullRequest(options) {
1668
+ if (!REPOSITORY_FULL_NAME_PATTERN.test(options.repositoryFullName)) {
1669
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid repositoryFullName "${options.repositoryFullName}"`);
1670
+ }
1671
+ const scrubber = options.scrubber ?? new SecretScrubber();
1672
+ const apiBaseUrl = defaultApiBaseUrl(options.apiBaseUrl, options.env);
1673
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1674
+ const timeoutMs = options.timeoutMs ?? 15_000;
1675
+ const headers = await resolveAuthHeaders(options.githubToken, options.authHeaders, { accept: 'application/vnd.github+json', 'user-agent': 'loopwright-taskpack' }, scrubber);
1676
+ const slashIndex = options.repositoryFullName.indexOf('/');
1677
+ const owner = options.repositoryFullName.slice(0, slashIndex);
1678
+ const headQuery = `${owner}:${options.memoryBranch}`;
1679
+ let confirmedAbsence = false;
1680
+ for (let page = 1; page <= 5; page += 1) {
1681
+ const url = `${apiBaseUrl}/repos/${options.repositoryFullName}/pulls?state=open&head=${encodeURIComponent(headQuery)}&base=${encodeURIComponent(options.targetBranch)}&per_page=100&page=${page}`;
1682
+ const res = await fetchJson(url, fetchImpl, headers, timeoutMs, scrubber);
1683
+ if (!res.ok) {
1684
+ throw new TaskpackError('ACTION_INPUT_INVALID', `open memory pull requests lookup failed (${res.status}) for ${options.repositoryFullName}`);
1685
+ }
1686
+ if (!Array.isArray(res.data)) {
1687
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'GitHub pulls response must be an array');
1688
+ }
1689
+ for (const item of res.data) {
1690
+ if (!isPlainRecord(item))
1691
+ continue;
1692
+ if (item['state'] !== undefined && item['state'] !== 'open')
1693
+ continue;
1694
+ const head = isPlainRecord(item['head']) ? item['head'] : undefined;
1695
+ const base = isPlainRecord(item['base']) ? item['base'] : undefined;
1696
+ const headRepo = head?.['repo'];
1697
+ const baseRepo = base?.['repo'];
1698
+ const headRepoValid = isPlainRecord(headRepo)
1699
+ && typeof headRepo['full_name'] === 'string'
1700
+ && headRepo['full_name'].toLowerCase() === options.repositoryFullName.toLowerCase();
1701
+ if (!headRepoValid)
1702
+ continue;
1703
+ if (baseRepo !== undefined) {
1704
+ if (!isPlainRecord(baseRepo)
1705
+ || typeof baseRepo['full_name'] !== 'string'
1706
+ || baseRepo['full_name'].toLowerCase() !== options.repositoryFullName.toLowerCase()) {
1707
+ continue;
1708
+ }
1709
+ if (typeof headRepo['id'] === 'number'
1710
+ && typeof baseRepo['id'] === 'number'
1711
+ && headRepo['id'] !== baseRepo['id']) {
1712
+ continue;
1713
+ }
1714
+ }
1715
+ const headRef = head?.['ref'];
1716
+ const headSha = head?.['sha'];
1717
+ const baseRef = base?.['ref'];
1718
+ const baseSha = base?.['sha'];
1719
+ const prNumber = item['number'];
1720
+ const htmlUrl = item['html_url'];
1721
+ const title = item['title'];
1722
+ const body = item['body'];
1723
+ if (typeof headRef === 'string'
1724
+ && headRef === options.memoryBranch
1725
+ && typeof headSha === 'string'
1726
+ && typeof baseRef === 'string'
1727
+ && baseRef === options.targetBranch
1728
+ && typeof prNumber === 'number'
1729
+ && Number.isSafeInteger(prNumber)
1730
+ && prNumber > 0
1731
+ && typeof htmlUrl === 'string') {
1732
+ return {
1733
+ number: prNumber,
1734
+ htmlUrl,
1735
+ headRef,
1736
+ headSha,
1737
+ baseRef,
1738
+ baseSha: typeof baseSha === 'string' ? baseSha : '',
1739
+ title: typeof title === 'string' ? title : '',
1740
+ body: typeof body === 'string' ? body : null,
1741
+ };
1742
+ }
1743
+ }
1744
+ if (res.data.length < 100) {
1745
+ confirmedAbsence = true;
1746
+ break;
1747
+ }
1748
+ }
1749
+ if (!confirmedAbsence) {
1750
+ throw new TaskpackError('ACTION_INPUT_INVALID', `open memory pull requests lookup exhausted pagination (500 open pull requests) for ${options.repositoryFullName} without confirming absence`);
1751
+ }
1752
+ return null;
1753
+ }
1754
+ function extractPrNumberFromPayload(payload) {
1755
+ if (!isPlainRecord(payload))
1756
+ return undefined;
1757
+ const pr = payload['pull_request'];
1758
+ if (isPlainRecord(pr) && typeof pr['number'] === 'number' && Number.isSafeInteger(pr['number']) && pr['number'] > 0) {
1759
+ return pr['number'];
1760
+ }
1761
+ const issue = payload['issue'];
1762
+ if (isPlainRecord(issue)
1763
+ && isPlainRecord(issue['pull_request'])
1764
+ && typeof issue['number'] === 'number'
1765
+ && Number.isSafeInteger(issue['number'])
1766
+ && issue['number'] > 0) {
1767
+ return issue['number'];
1768
+ }
1769
+ return undefined;
1770
+ }
1771
+ function extractRepositoryIdFromPayload(payload) {
1772
+ if (!isPlainRecord(payload))
1773
+ return undefined;
1774
+ const repo = payload['repository'];
1775
+ if (isPlainRecord(repo) && typeof repo['id'] === 'number' && Number.isSafeInteger(repo['id']) && repo['id'] > 0) {
1776
+ return repo['id'];
1777
+ }
1778
+ return undefined;
1779
+ }
1780
+ /**
1781
+ * Verify and resolve a Git commit reference or SHA against local `repositoryRoot`
1782
+ * using `git rev-parse --verify` so nonexistent SHAs and missing refs fail closed.
1783
+ */
1784
+ export async function resolveGitCommitSha(repositoryRoot, ref, timeoutMs = 15_000) {
1785
+ if (!SAFE_GIT_REF_PATTERN.test(ref) || ref.startsWith('-')) {
1786
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid git revision reference "${ref}"`);
1787
+ }
1788
+ const gitBin = resolveGitExecutable();
1789
+ try {
1790
+ const { stdout } = await execFileAsync(gitBin, ['-C', repositoryRoot, 'rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`], { env: buildCleanGitEnv(), timeout: timeoutMs, maxBuffer: 4096, encoding: 'utf8' });
1791
+ const sha = stdout.trim().toLowerCase();
1792
+ if (!COMMIT_SHA_PATTERN.test(sha)) {
1793
+ throw new TaskpackError('ACTION_INPUT_INVALID', `git rev-parse returned invalid commit sha "${sha}" for "${ref}"`);
1794
+ }
1795
+ return sha;
1796
+ }
1797
+ catch (error) {
1798
+ if (error instanceof TaskpackError)
1799
+ throw error;
1800
+ const detail = error instanceof Error ? error.message : String(error);
1801
+ throw new TaskpackError('ACTION_INPUT_INVALID', `failed to resolve git revision "${ref}": ${detail}`);
1802
+ }
1803
+ }
1804
+ async function resolveGitRevisionSha(repositoryRoot, ref, timeoutMs) {
1805
+ if (COMMIT_SHA_PATTERN.test(ref)) {
1806
+ return ref.toLowerCase();
1807
+ }
1808
+ return resolveGitCommitSha(repositoryRoot, ref, timeoutMs);
1809
+ }
1810
+ export function shouldPreserveExplicitSourceRevision(options) {
1811
+ return options.eventName === 'issue_comment'
1812
+ && options.explicitSourceRevision !== undefined
1813
+ && options.explicitSourceRevision.trim().length > 0
1814
+ && options.commentCommand === 'retry';
1815
+ }
1816
+ /**
1817
+ * Resolve `baseRevision` and `sourceRevision` to 40-hex commit SHAs (using PR API
1818
+ * on comment/review events when needed and `git rev-parse --verify` locally), and
1819
+ * resolve positive `repositoryId`.
1820
+ */
1821
+ export async function resolveRepositoryAndRevisions(options) {
1822
+ const scrubber = options.scrubber ?? new SecretScrubber();
1823
+ const apiBaseUrl = options.apiBaseUrl?.trim() || options.env?.['GITHUB_API_URL']?.trim();
1824
+ const normalizedApiBase = apiBaseUrl ? apiBaseUrl.replace(/\/+$/, '') : undefined;
1825
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1826
+ const timeoutMs = options.timeoutMs ?? 15_000;
1827
+ const headers = await resolveAuthHeaders(options.githubToken, options.authHeaders, { accept: 'application/vnd.github+json', 'user-agent': 'loopwright-taskpack' }, scrubber);
1828
+ let baseRev = options.baseRevision;
1829
+ let sourceRev = options.sourceRevision ?? options.baseRevision;
1830
+ let resolvedFromPr = false;
1831
+ const preserveExplicitOnComment = options.preserveExplicitSourceRevision === true
1832
+ && options.sourceRevision !== undefined
1833
+ && options.sourceRevision.trim().length > 0;
1834
+ if (!preserveExplicitOnComment && (options.eventName === 'issue_comment' || options.eventName === 'pull_request_review')) {
1835
+ const prNumber = extractPrNumberFromPayload(options.eventPayload);
1836
+ const payloadPr = isPlainRecord(options.eventPayload) && isPlainRecord(options.eventPayload['pull_request'])
1837
+ ? options.eventPayload['pull_request']
1838
+ : undefined;
1839
+ if (prNumber !== undefined && normalizedApiBase !== undefined) {
1840
+ if (!REPOSITORY_FULL_NAME_PATTERN.test(options.repositoryFullName)) {
1841
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid repositoryFullName "${options.repositoryFullName}" for pull request lookup`);
1842
+ }
1843
+ const res = await fetchJson(`${normalizedApiBase}/repos/${options.repositoryFullName}/pulls/${prNumber}`, fetchImpl, headers, timeoutMs, scrubber);
1844
+ if (!res.ok || !isPlainRecord(res.data)) {
1845
+ throw new TaskpackError('ACTION_INPUT_INVALID', `pull request #${prNumber} lookup failed (${res.status}) for ${options.repositoryFullName}`);
1846
+ }
1847
+ const baseObj = isPlainRecord(res.data['base']) ? res.data['base'] : undefined;
1848
+ const headObj = isPlainRecord(res.data['head']) ? res.data['head'] : undefined;
1849
+ const fetchedBaseSha = baseObj?.['sha'];
1850
+ const fetchedHeadSha = headObj?.['sha'];
1851
+ if (typeof fetchedBaseSha !== 'string'
1852
+ || !COMMIT_SHA_PATTERN.test(fetchedBaseSha)
1853
+ || typeof fetchedHeadSha !== 'string'
1854
+ || !COMMIT_SHA_PATTERN.test(fetchedHeadSha)) {
1855
+ throw new TaskpackError('ACTION_INPUT_INVALID', `pull request #${prNumber} response missing valid 40-hex base/head SHAs`);
1856
+ }
1857
+ baseRev = fetchedBaseSha.toLowerCase();
1858
+ sourceRev = fetchedHeadSha.toLowerCase();
1859
+ resolvedFromPr = true;
1860
+ }
1861
+ else if (payloadPr !== undefined) {
1862
+ const baseObj = isPlainRecord(payloadPr['base']) ? payloadPr['base'] : undefined;
1863
+ const headObj = isPlainRecord(payloadPr['head']) ? payloadPr['head'] : undefined;
1864
+ const payloadBaseSha = baseObj?.['sha'];
1865
+ const payloadHeadSha = headObj?.['sha'];
1866
+ if (baseObj !== undefined || headObj !== undefined) {
1867
+ if (typeof payloadBaseSha !== 'string'
1868
+ || !COMMIT_SHA_PATTERN.test(payloadBaseSha)
1869
+ || typeof payloadHeadSha !== 'string'
1870
+ || !COMMIT_SHA_PATTERN.test(payloadHeadSha)) {
1871
+ throw new TaskpackError('ACTION_INPUT_INVALID', 'event pull_request payload base/head SHAs must be 40-hex commit SHAs');
1872
+ }
1873
+ baseRev = payloadBaseSha.toLowerCase();
1874
+ sourceRev = payloadHeadSha.toLowerCase();
1875
+ resolvedFromPr = true;
1876
+ }
1877
+ }
1878
+ }
1879
+ const resolvedBase = await resolveGitRevisionSha(options.repositoryRoot, baseRev, timeoutMs);
1880
+ const verifyExplicitSourceLocally = !resolvedFromPr
1881
+ && options.sourceRevision !== undefined
1882
+ && options.sourceRevision.trim().length > 0
1883
+ && existsSync(join(options.repositoryRoot, '.git'));
1884
+ let resolvedSource;
1885
+ if (verifyExplicitSourceLocally) {
1886
+ resolvedSource = await resolveGitCommitSha(options.repositoryRoot, sourceRev, timeoutMs);
1887
+ }
1888
+ else if (sourceRev === baseRev) {
1889
+ resolvedSource = resolvedBase;
1890
+ }
1891
+ else {
1892
+ resolvedSource = await resolveGitRevisionSha(options.repositoryRoot, sourceRev, timeoutMs);
1893
+ }
1894
+ let repositoryId;
1895
+ const envRepoIdRaw = options.env?.['GITHUB_REPOSITORY_ID']?.trim();
1896
+ if (envRepoIdRaw !== undefined && /^\d+$/.test(envRepoIdRaw)) {
1897
+ const parsed = Number.parseInt(envRepoIdRaw, 10);
1898
+ if (Number.isSafeInteger(parsed) && parsed > 0) {
1899
+ repositoryId = parsed;
1900
+ }
1901
+ }
1902
+ if (repositoryId === undefined) {
1903
+ repositoryId = extractRepositoryIdFromPayload(options.eventPayload);
1904
+ }
1905
+ if (repositoryId === undefined) {
1906
+ if (normalizedApiBase !== undefined) {
1907
+ if (!REPOSITORY_FULL_NAME_PATTERN.test(options.repositoryFullName)) {
1908
+ throw new TaskpackError('ACTION_INPUT_INVALID', `invalid repositoryFullName "${options.repositoryFullName}" for repository ID lookup`);
1909
+ }
1910
+ const res = await fetchJson(`${normalizedApiBase}/repos/${options.repositoryFullName}`, fetchImpl, headers, timeoutMs, scrubber);
1911
+ if (!res.ok
1912
+ || !isPlainRecord(res.data)
1913
+ || typeof res.data['id'] !== 'number'
1914
+ || !Number.isSafeInteger(res.data['id'])
1915
+ || res.data['id'] <= 0) {
1916
+ throw new TaskpackError('ACTION_INPUT_INVALID', `GitHub repository lookup failed (${res.status}) or returned invalid repository id for ${options.repositoryFullName}`);
1917
+ }
1918
+ repositoryId = res.data['id'];
1919
+ }
1920
+ else {
1921
+ repositoryId = 1;
1922
+ }
1923
+ }
1924
+ return {
1925
+ repositoryId,
1926
+ baseRevision: resolvedBase,
1927
+ sourceRevision: resolvedSource,
1928
+ };
1929
+ }
1930
+ function parsePositiveSafeInt(raw) {
1931
+ if (typeof raw === 'number') {
1932
+ return Number.isSafeInteger(raw) && raw > 0 ? raw : null;
1933
+ }
1934
+ const trimmed = String(raw).trim();
1935
+ if (!/^\d+$/.test(trimmed)) {
1936
+ return null;
1937
+ }
1938
+ const parsed = Number.parseInt(trimmed, 10);
1939
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
1940
+ }
1941
+ async function resolveGitHubAuthInternal(options, resolveCommitIdentity) {
1942
+ const scrubber = options.scrubber ?? new SecretScrubber();
1943
+ const explicitName = parseOptionalGitIdentityInput(options.gitAuthorName, options.env?.['INPUT_GIT-AUTHOR-NAME'], validateGitAuthorName);
1944
+ const explicitEmail = parseOptionalGitIdentityInput(options.gitAuthorEmail, options.env?.['INPUT_GIT-AUTHOR-EMAIL'], validateGitAuthorEmail);
1945
+ const shouldLookupDynamicIdentity = resolveCommitIdentity && (explicitName === undefined || explicitEmail === undefined);
1946
+ const finalizeIdentity = (resolved) => Object.freeze({
1947
+ name: explicitName ?? resolved.name,
1948
+ email: explicitEmail ?? resolved.email,
1949
+ });
1950
+ const rawPrivateKey = options.appPrivateKey?.trim() || options.env?.['INPUT_GITHUB-APP-PRIVATE-KEY']?.trim() || undefined;
1951
+ if (rawPrivateKey !== undefined) {
1952
+ scrubber.register(rawPrivateKey);
1953
+ }
1954
+ const ambientToken = options.env?.['GITHUB_TOKEN']?.trim() || undefined;
1955
+ if (ambientToken !== undefined) {
1956
+ scrubber.register(ambientToken);
1957
+ }
1958
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1959
+ const resolveNoreplyIdentityFromUserEndpoint = async (url, bearerToken) => {
1960
+ try {
1961
+ const res = await fetchJson(url, fetchImpl, {
1962
+ accept: 'application/vnd.github+json',
1963
+ authorization: `Bearer ${bearerToken}`,
1964
+ 'user-agent': 'loopwright-taskpack',
1965
+ }, 10_000, scrubber);
1966
+ if (!res.ok || !isPlainRecord(res.data))
1967
+ return undefined;
1968
+ const id = res.data['id'];
1969
+ const login = res.data['login'];
1970
+ if (typeof id !== 'number'
1971
+ || !Number.isSafeInteger(id)
1972
+ || id <= 0
1973
+ || typeof login !== 'string'
1974
+ || login.trim().length === 0) {
1975
+ return undefined;
1976
+ }
1977
+ const cleanLogin = login.trim();
1978
+ return validateGitCommitIdentity({
1979
+ name: cleanLogin,
1980
+ email: `${id}+${cleanLogin}@users.noreply.github.com`,
1981
+ });
1982
+ }
1983
+ catch {
1984
+ return undefined;
1985
+ }
1986
+ };
1987
+ // 1) Explicit token input
1988
+ const explicitToken = options.githubToken?.trim() || options.env?.['INPUT_GITHUB-TOKEN']?.trim() || undefined;
1989
+ if (explicitToken !== undefined) {
1990
+ scrubber.register(explicitToken);
1991
+ let resolvedIdentity = DEFAULT_GIT_COMMIT_IDENTITY;
1992
+ if (shouldLookupDynamicIdentity) {
1993
+ const explicitApiBase = (options.apiBaseUrl?.trim() || options.env?.['GITHUB_API_URL']?.trim())?.replace(/\/+$/, '');
1994
+ if (explicitApiBase && explicitApiBase.length > 0) {
1995
+ resolvedIdentity = (await resolveNoreplyIdentityFromUserEndpoint(`${explicitApiBase}/user`, explicitToken))
1996
+ ?? DEFAULT_GIT_COMMIT_IDENTITY;
1997
+ }
1998
+ }
1999
+ return {
2000
+ token: explicitToken,
2001
+ gitCommitIdentity: finalizeIdentity(resolvedIdentity),
2002
+ };
2003
+ }
2004
+ // 2) GitHub App credentials via injected JWT signer
2005
+ const rawAppId = options.appId !== undefined && (typeof options.appId === 'number' || options.appId.trim().length > 0)
2006
+ ? options.appId
2007
+ : (options.env?.['INPUT_GITHUB-APP-ID']?.trim() || undefined);
2008
+ const rawInstallationId = options.appInstallationId !== undefined
2009
+ && (typeof options.appInstallationId === 'number' || options.appInstallationId.trim().length > 0)
2010
+ ? options.appInstallationId
2011
+ : (options.env?.['INPUT_GITHUB-APP-INSTALLATION-ID']?.trim() || undefined);
2012
+ if (rawAppId !== undefined && rawPrivateKey !== undefined) {
2013
+ if (options.createAppJwt === undefined) {
2014
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', 'createAppJwt callback is required to mint GitHub App installation tokens');
2015
+ }
2016
+ const appId = parsePositiveSafeInt(rawAppId);
2017
+ if (appId === null) {
2018
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', 'GitHub App ID must be a positive integer');
2019
+ }
2020
+ let installationId;
2021
+ if (rawInstallationId !== undefined) {
2022
+ const parsedInstallationId = parsePositiveSafeInt(rawInstallationId);
2023
+ if (parsedInstallationId === null) {
2024
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', 'GitHub App installation ID must be a positive integer');
2025
+ }
2026
+ installationId = parsedInstallationId;
2027
+ }
2028
+ const apiBaseUrl = defaultApiBaseUrl(options.apiBaseUrl, options.env);
2029
+ const jwt = options.createAppJwt({
2030
+ appId,
2031
+ privateKeyPem: rawPrivateKey,
2032
+ nowSeconds: Math.floor(Date.now() / 1000),
2033
+ });
2034
+ scrubber.register(jwt);
2035
+ let appSlug;
2036
+ if (installationId === undefined) {
2037
+ const repoFullName = options.repositoryFullName?.trim() ?? '';
2038
+ if (!REPOSITORY_FULL_NAME_PATTERN.test(repoFullName)) {
2039
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', `repositoryFullName matching "owner/repo" is required to auto-discover GitHub App installation (got "${scrubber.scrub(repoFullName)}")`);
2040
+ }
2041
+ const [owner, repo] = repoFullName.split('/');
2042
+ if (owner === '.' || owner === '..' || repo === '.' || repo === '..') {
2043
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', `invalid repositoryFullName "${scrubber.scrub(repoFullName)}" for GitHub App installation lookup`);
2044
+ }
2045
+ const installRes = await fetchBoundedText(`${apiBaseUrl}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/installation`, fetchImpl, {
2046
+ accept: 'application/vnd.github+json',
2047
+ authorization: `Bearer ${jwt}`,
2048
+ 'user-agent': 'loopwright-taskpack',
2049
+ }, 15_000, scrubber);
2050
+ if (!installRes.ok) {
2051
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', `failed to discover GitHub App installation for ${repoFullName} (${installRes.status}): ${scrubber.scrub(installRes.text)}`);
2052
+ }
2053
+ let installParsed;
2054
+ try {
2055
+ installParsed = JSON.parse(installRes.text);
2056
+ }
2057
+ catch (error) {
2058
+ const detail = error instanceof Error ? error.message : String(error);
2059
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', `invalid GitHub App installation JSON: ${scrubber.scrub(detail)}`);
2060
+ }
2061
+ if (!isPlainRecord(installParsed)
2062
+ || typeof installParsed['id'] !== 'number'
2063
+ || !Number.isSafeInteger(installParsed['id'])
2064
+ || installParsed['id'] <= 0) {
2065
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', `GitHub App installation response for ${repoFullName} missing positive integer id`);
2066
+ }
2067
+ installationId = installParsed['id'];
2068
+ if (typeof installParsed['app_slug'] === 'string' && installParsed['app_slug'].trim().length > 0) {
2069
+ appSlug = installParsed['app_slug'].trim();
2070
+ }
2071
+ }
2072
+ const bodyPayload = {};
2073
+ if (options.permissions !== undefined) {
2074
+ bodyPayload['permissions'] = options.permissions;
2075
+ }
2076
+ if (options.repositoryId !== undefined && Number.isSafeInteger(options.repositoryId) && options.repositoryId > 0) {
2077
+ bodyPayload['repository_ids'] = [options.repositoryId];
2078
+ }
2079
+ else if (options.repositoryFullName && REPOSITORY_FULL_NAME_PATTERN.test(options.repositoryFullName)) {
2080
+ bodyPayload['repositories'] = [options.repositoryFullName.split('/')[1]];
2081
+ }
2082
+ const res = await fetchBoundedText(`${apiBaseUrl}/app/installations/${installationId}/access_tokens`, fetchImpl, {
2083
+ accept: 'application/vnd.github+json',
2084
+ authorization: `Bearer ${jwt}`,
2085
+ 'content-type': 'application/json',
2086
+ 'user-agent': 'loopwright-taskpack',
2087
+ }, 15_000, scrubber, { method: 'POST', body: JSON.stringify(bodyPayload) });
2088
+ if (!res.ok) {
2089
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', `failed to mint installation token (${res.status}): ${scrubber.scrub(res.text)}`);
2090
+ }
2091
+ let parsed;
2092
+ try {
2093
+ parsed = JSON.parse(res.text);
2094
+ }
2095
+ catch (error) {
2096
+ const detail = error instanceof Error ? error.message : String(error);
2097
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', `invalid GitHub App access_tokens JSON: ${scrubber.scrub(detail)}`);
2098
+ }
2099
+ if (!isPlainRecord(parsed) || typeof parsed['token'] !== 'string' || parsed['token'].length === 0) {
2100
+ throw new TaskpackError('TOKEN_BROKER_CONFIG_INVALID', 'GitHub App access_tokens response missing token');
2101
+ }
2102
+ const mintedToken = parsed['token'];
2103
+ scrubber.register(mintedToken);
2104
+ let resolvedIdentity = DEFAULT_GIT_COMMIT_IDENTITY;
2105
+ if (shouldLookupDynamicIdentity) {
2106
+ if (appSlug === undefined) {
2107
+ try {
2108
+ const appRes = await fetchJson(`${apiBaseUrl}/app`, fetchImpl, {
2109
+ accept: 'application/vnd.github+json',
2110
+ authorization: `Bearer ${jwt}`,
2111
+ 'user-agent': 'loopwright-taskpack',
2112
+ }, 10_000, scrubber);
2113
+ if (appRes.ok && isPlainRecord(appRes.data) && typeof appRes.data['slug'] === 'string' && appRes.data['slug'].trim().length > 0) {
2114
+ appSlug = appRes.data['slug'].trim();
2115
+ }
2116
+ }
2117
+ catch {
2118
+ // Best-effort lookup; fall back to default DCO-valid bot identity.
2119
+ }
2120
+ }
2121
+ if (appSlug !== undefined && appSlug.length > 0) {
2122
+ const botLogin = appSlug.endsWith('[bot]') ? appSlug : `${appSlug}[bot]`;
2123
+ resolvedIdentity = (await resolveNoreplyIdentityFromUserEndpoint(`${apiBaseUrl}/users/${encodeURIComponent(botLogin)}`, mintedToken)) ?? DEFAULT_GIT_COMMIT_IDENTITY;
2124
+ }
2125
+ }
2126
+ return {
2127
+ token: mintedToken,
2128
+ installationId,
2129
+ ...(appSlug !== undefined ? { appSlug } : {}),
2130
+ gitCommitIdentity: finalizeIdentity(resolvedIdentity),
2131
+ };
2132
+ }
2133
+ // 3) Ambient fallback (env.GITHUB_TOKEN)
2134
+ if (ambientToken !== undefined) {
2135
+ let resolvedIdentity = DEFAULT_GIT_COMMIT_IDENTITY;
2136
+ if (shouldLookupDynamicIdentity) {
2137
+ const explicitApiBase = (options.apiBaseUrl?.trim() || options.env?.['GITHUB_API_URL']?.trim())?.replace(/\/+$/, '');
2138
+ if (explicitApiBase && explicitApiBase.length > 0) {
2139
+ resolvedIdentity = (await resolveNoreplyIdentityFromUserEndpoint(`${explicitApiBase}/user`, ambientToken))
2140
+ ?? DEFAULT_GIT_COMMIT_IDENTITY;
2141
+ }
2142
+ }
2143
+ return {
2144
+ token: ambientToken,
2145
+ gitCommitIdentity: finalizeIdentity(resolvedIdentity),
2146
+ };
2147
+ }
2148
+ return {
2149
+ token: undefined,
2150
+ gitCommitIdentity: finalizeIdentity(DEFAULT_GIT_COMMIT_IDENTITY),
2151
+ };
2152
+ }
2153
+ /** Resolve GitHub authentication credentials and a DCO-valid Git commit identity (with injectable `createAppJwt`). */
2154
+ export async function resolveGitHubAuth(options) {
2155
+ return resolveGitHubAuthInternal(options, true);
2156
+ }
2157
+ /** Resolve a GitHub token using explicit input, injected GitHub App JWT signer, or ambient `GITHUB_TOKEN`. */
2158
+ export async function resolveGitHubToken(options) {
2159
+ const resolved = await resolveGitHubAuthInternal(options, false);
2160
+ return resolved.token;
2161
+ }
2162
+ /**
2163
+ * Determine whether an existing open managed PR already carries the discovered
2164
+ * upstream versions by reading the proposal file at `openManagedPr.headSha`.
2165
+ */
2166
+ export async function checkManagedPrMatchesDiscoveredState(options) {
2167
+ const { openManagedPr, manifest, records } = options;
2168
+ if (openManagedPr === null || records.length === 0) {
2169
+ return false;
2170
+ }
2171
+ if (!COMMIT_SHA_PATTERN.test(openManagedPr.headSha)) {
2172
+ return false;
2173
+ }
2174
+ if (records.some(record => record.status === 'failed' || record.status === 'blocked')) {
2175
+ return false;
2176
+ }
2177
+ const available = records.filter(record => record.status === 'available');
2178
+ if (available.length === 0) {
2179
+ return false;
2180
+ }
2181
+ if (manifest.spec.proposal === undefined) {
2182
+ return false;
2183
+ }
2184
+ const proposalPath = manifest.spec.proposal.path;
2185
+ if (tryNormalizeRelativePath(proposalPath) === undefined || proposalPath.startsWith('-')) {
2186
+ return false;
2187
+ }
2188
+ let proposalText;
2189
+ const timeoutMs = options.timeoutMs ?? 15_000;
2190
+ try {
2191
+ const gitBin = resolveGitExecutable();
2192
+ const { stdout } = await execFileAsync(gitBin, ['-C', options.repositoryRoot, 'show', `${openManagedPr.headSha}:${proposalPath}`], { env: buildCleanGitEnv(), timeout: timeoutMs, maxBuffer: MAX_PROPOSAL_BYTES, encoding: 'utf8' });
2193
+ proposalText = stdout;
2194
+ }
2195
+ catch {
2196
+ const apiBase = options.apiBaseUrl?.trim() || options.env?.['GITHUB_API_URL']?.trim();
2197
+ if (apiBase && REPOSITORY_FULL_NAME_PATTERN.test(options.repositoryFullName)) {
2198
+ const scrubber = options.scrubber ?? new SecretScrubber();
2199
+ const encodedPath = proposalPath.split('/').map(seg => encodeURIComponent(seg)).join('/');
2200
+ const headers = await resolveAuthHeaders(options.githubToken, options.authHeaders, { accept: 'application/vnd.github.raw+json', 'user-agent': 'loopwright-taskpack' }, scrubber);
2201
+ try {
2202
+ const res = await fetchBoundedText(`${apiBase.replace(/\/+$/, '')}/repos/${options.repositoryFullName}/contents/${encodedPath}?ref=${encodeURIComponent(openManagedPr.headSha)}`, options.fetchImpl ?? globalThis.fetch, headers, timeoutMs, scrubber);
2203
+ if (res.ok && Buffer.byteLength(res.text, 'utf8') <= MAX_PROPOSAL_BYTES) {
2204
+ proposalText = res.text;
2205
+ }
2206
+ }
2207
+ catch {
2208
+ proposalText = undefined;
2209
+ }
2210
+ }
2211
+ }
2212
+ if (proposalText === undefined || proposalText.trim().length === 0) {
2213
+ return false;
2214
+ }
2215
+ let parsedProposal;
2216
+ try {
2217
+ parsedProposal = JSON.parse(proposalText);
2218
+ }
2219
+ catch {
2220
+ return false;
2221
+ }
2222
+ const prVersions = readBaselineVersions(parsedProposal, manifest.spec.upstreams);
2223
+ if (prVersions.size === 0) {
2224
+ return false;
2225
+ }
2226
+ for (const record of available) {
2227
+ if (typeof record.version !== 'string' || record.version.length === 0) {
2228
+ return false;
2229
+ }
2230
+ if (prVersions.get(record.upstreamId) !== record.version) {
2231
+ return false;
2232
+ }
2233
+ }
2234
+ for (const record of records) {
2235
+ if (record.status === 'up_to_date' && typeof record.version === 'string' && prVersions.has(record.upstreamId)) {
2236
+ if (prVersions.get(record.upstreamId) !== record.version) {
2237
+ return false;
2238
+ }
2239
+ }
2240
+ }
2241
+ return true;
2242
+ }