@gpustack/loopwright 0.0.0-stage → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (477) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +356 -2
  3. package/bin/loopwright.js +3 -0
  4. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
  5. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
  6. package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
  7. package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
  8. package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
  9. package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
  10. package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
  11. package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
  12. package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
  13. package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
  14. package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
  15. package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
  16. package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
  17. package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
  18. package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
  19. package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
  20. package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
  21. package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
  22. package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
  23. package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
  24. package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
  25. package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
  26. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
  27. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
  28. package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
  29. package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
  30. package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
  31. package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
  32. package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
  33. package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
  34. package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
  35. package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
  36. package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
  37. package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
  38. package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
  39. package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
  40. package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
  41. package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
  42. package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
  43. package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
  44. package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
  45. package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
  46. package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
  47. package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
  48. package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
  49. package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
  50. package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
  51. package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
  52. package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
  53. package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
  54. package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
  55. package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
  56. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
  57. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
  58. package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
  59. package/node_modules/@loopwright/agent-pi/dist/host-session.js +2094 -0
  60. package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
  61. package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
  62. package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
  63. package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
  64. package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
  65. package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
  66. package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
  67. package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
  68. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
  69. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
  70. package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
  71. package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
  72. package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
  73. package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
  74. package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
  75. package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
  76. package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
  77. package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
  78. package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
  79. package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
  80. package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
  81. package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
  82. package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
  83. package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
  84. package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
  85. package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
  86. package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
  87. package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
  88. package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
  89. package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
  90. package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
  91. package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
  92. package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
  93. package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
  94. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
  95. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
  96. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
  97. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
  98. package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
  99. package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
  100. package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
  101. package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
  102. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
  103. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
  104. package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
  105. package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
  106. package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
  107. package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
  108. package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
  109. package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
  110. package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
  111. package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
  112. package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
  113. package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
  114. package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
  115. package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
  116. package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
  117. package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
  118. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
  119. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
  120. package/node_modules/@loopwright/agent-pi/package.json +24 -0
  121. package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
  122. package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
  123. package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
  124. package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
  125. package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
  126. package/node_modules/@loopwright/cli/dist/closure.js +230 -0
  127. package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
  128. package/node_modules/@loopwright/cli/dist/draft.js +106 -0
  129. package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
  130. package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
  131. package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
  132. package/node_modules/@loopwright/cli/dist/index.js +5 -0
  133. package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
  134. package/node_modules/@loopwright/cli/dist/main.js +1855 -0
  135. package/node_modules/@loopwright/cli/package.json +16 -0
  136. package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
  137. package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
  138. package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
  139. package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
  140. package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
  141. package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
  142. package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
  143. package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
  144. package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
  145. package/node_modules/@loopwright/controller/dist/capture.js +587 -0
  146. package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
  147. package/node_modules/@loopwright/controller/dist/compile.js +402 -0
  148. package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
  149. package/node_modules/@loopwright/controller/dist/config.js +255 -0
  150. package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
  151. package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
  152. package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
  153. package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
  154. package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
  155. package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
  156. package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
  157. package/node_modules/@loopwright/controller/dist/errors.js +41 -0
  158. package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
  159. package/node_modules/@loopwright/controller/dist/events.js +228 -0
  160. package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
  161. package/node_modules/@loopwright/controller/dist/files.js +386 -0
  162. package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
  163. package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
  164. package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
  165. package/node_modules/@loopwright/controller/dist/gate.js +640 -0
  166. package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
  167. package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
  168. package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
  169. package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
  170. package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
  171. package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
  172. package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
  173. package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
  174. package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
  175. package/node_modules/@loopwright/controller/dist/index.js +21 -0
  176. package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
  177. package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
  178. package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
  179. package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
  180. package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
  181. package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
  182. package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
  183. package/node_modules/@loopwright/controller/dist/parser.js +200 -0
  184. package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
  185. package/node_modules/@loopwright/controller/dist/progress.js +904 -0
  186. package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
  187. package/node_modules/@loopwright/controller/dist/publication.js +329 -0
  188. package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
  189. package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
  190. package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
  191. package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
  192. package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
  193. package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
  194. package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
  195. package/node_modules/@loopwright/controller/dist/registry.js +374 -0
  196. package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
  197. package/node_modules/@loopwright/controller/dist/repair.js +102 -0
  198. package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
  199. package/node_modules/@loopwright/controller/dist/report.js +596 -0
  200. package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
  201. package/node_modules/@loopwright/controller/dist/retained.js +193 -0
  202. package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
  203. package/node_modules/@loopwright/controller/dist/rules.js +110 -0
  204. package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
  205. package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
  206. package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
  207. package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
  208. package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
  209. package/node_modules/@loopwright/controller/dist/schema.js +78 -0
  210. package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
  211. package/node_modules/@loopwright/controller/dist/source.js +872 -0
  212. package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
  213. package/node_modules/@loopwright/controller/dist/step.js +1776 -0
  214. package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
  215. package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
  216. package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
  217. package/node_modules/@loopwright/controller/dist/submission.js +292 -0
  218. package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
  219. package/node_modules/@loopwright/controller/dist/types.js +9 -0
  220. package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
  221. package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
  222. package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
  223. package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
  224. package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
  225. package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
  226. package/node_modules/@loopwright/controller/package.json +12 -0
  227. package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
  228. package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
  229. package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
  230. package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
  231. package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
  232. package/node_modules/@loopwright/core/dist/boundary.js +484 -0
  233. package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
  234. package/node_modules/@loopwright/core/dist/contracts.js +694 -0
  235. package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
  236. package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
  237. package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
  238. package/node_modules/@loopwright/core/dist/evidence.js +85 -0
  239. package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
  240. package/node_modules/@loopwright/core/dist/graph.js +44 -0
  241. package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
  242. package/node_modules/@loopwright/core/dist/identity.js +80 -0
  243. package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
  244. package/node_modules/@loopwright/core/dist/index.js +39 -0
  245. package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
  246. package/node_modules/@loopwright/core/dist/limits.js +59 -0
  247. package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
  248. package/node_modules/@loopwright/core/dist/results.js +98 -0
  249. package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
  250. package/node_modules/@loopwright/core/dist/scope.js +154 -0
  251. package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
  252. package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
  253. package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
  254. package/node_modules/@loopwright/core/dist/usage.js +56 -0
  255. package/node_modules/@loopwright/core/package.json +12 -0
  256. package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
  257. package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
  258. package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
  259. package/node_modules/@loopwright/decisions/dist/client.js +292 -0
  260. package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
  261. package/node_modules/@loopwright/decisions/dist/index.js +8 -0
  262. package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
  263. package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
  264. package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
  265. package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
  266. package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
  267. package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
  268. package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
  269. package/node_modules/@loopwright/decisions/dist/router.js +248 -0
  270. package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
  271. package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
  272. package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
  273. package/node_modules/@loopwright/decisions/dist/types.js +80 -0
  274. package/node_modules/@loopwright/decisions/package.json +12 -0
  275. package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
  276. package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
  277. package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
  278. package/node_modules/@loopwright/github-app/dist/config.js +297 -0
  279. package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
  280. package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
  281. package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
  282. package/node_modules/@loopwright/github-app/dist/index.js +13 -0
  283. package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
  284. package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
  285. package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
  286. package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
  287. package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
  288. package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
  289. package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
  290. package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
  291. package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
  292. package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
  293. package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
  294. package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
  295. package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
  296. package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
  297. package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
  298. package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
  299. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
  300. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
  301. package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
  302. package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
  303. package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
  304. package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
  305. package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
  306. package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
  307. package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
  308. package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
  309. package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
  310. package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
  311. package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
  312. package/node_modules/@loopwright/github-app/dist/types.js +14 -0
  313. package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
  314. package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
  315. package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
  316. package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
  317. package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
  318. package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
  319. package/node_modules/@loopwright/github-app/package.json +12 -0
  320. package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
  321. package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
  322. package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
  323. package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
  324. package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
  325. package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
  326. package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
  327. package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
  328. package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
  329. package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
  330. package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
  331. package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
  332. package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
  333. package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
  334. package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
  335. package/node_modules/@loopwright/hardware-runner/dist/worker.js +1648 -0
  336. package/node_modules/@loopwright/hardware-runner/package.json +12 -0
  337. package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
  338. package/node_modules/@loopwright/memory/dist/cas.js +510 -0
  339. package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
  340. package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
  341. package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
  342. package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
  343. package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
  344. package/node_modules/@loopwright/memory/dist/index.js +8 -0
  345. package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
  346. package/node_modules/@loopwright/memory/dist/schema.js +510 -0
  347. package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
  348. package/node_modules/@loopwright/memory/dist/selector.js +157 -0
  349. package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
  350. package/node_modules/@loopwright/memory/dist/store.js +554 -0
  351. package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
  352. package/node_modules/@loopwright/memory/dist/types.js +8 -0
  353. package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
  354. package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
  355. package/node_modules/@loopwright/memory/package.json +12 -0
  356. package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
  357. package/node_modules/@loopwright/state/dist/admission.js +199 -0
  358. package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
  359. package/node_modules/@loopwright/state/dist/boundary.js +194 -0
  360. package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
  361. package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
  362. package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
  363. package/node_modules/@loopwright/state/dist/clock.js +27 -0
  364. package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
  365. package/node_modules/@loopwright/state/dist/connection.js +391 -0
  366. package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
  367. package/node_modules/@loopwright/state/dist/errors.js +34 -0
  368. package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
  369. package/node_modules/@loopwright/state/dist/index.js +1 -0
  370. package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
  371. package/node_modules/@loopwright/state/dist/journal.js +72 -0
  372. package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
  373. package/node_modules/@loopwright/state/dist/model.js +58 -0
  374. package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
  375. package/node_modules/@loopwright/state/dist/ownership.js +45 -0
  376. package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
  377. package/node_modules/@loopwright/state/dist/pages.js +41 -0
  378. package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
  379. package/node_modules/@loopwright/state/dist/receipts.js +97 -0
  380. package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
  381. package/node_modules/@loopwright/state/dist/schema.js +41 -0
  382. package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
  383. package/node_modules/@loopwright/state/dist/settlement.js +129 -0
  384. package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
  385. package/node_modules/@loopwright/state/dist/store.js +100 -0
  386. package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
  387. package/node_modules/@loopwright/state/dist/types.js +1 -0
  388. package/node_modules/@loopwright/state/package.json +12 -0
  389. package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
  390. package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
  391. package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
  392. package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
  393. package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
  394. package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
  395. package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
  396. package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
  397. package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
  398. package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
  399. package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
  400. package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
  401. package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
  402. package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
  403. package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
  404. package/node_modules/@loopwright/taskpack/dist/sandbox.js +2642 -0
  405. package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
  406. package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
  407. package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
  408. package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
  409. package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
  410. package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
  411. package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
  412. package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
  413. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
  414. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
  415. package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
  416. package/node_modules/@loopwright/taskpack/dist/turnkey.js +7335 -0
  417. package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
  418. package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
  419. package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
  420. package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
  421. package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
  422. package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
  423. package/node_modules/@loopwright/taskpack/package.json +12 -0
  424. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
  425. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
  426. package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
  427. package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
  428. package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
  429. package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
  430. package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
  431. package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
  432. package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
  433. package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
  434. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
  435. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
  436. package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
  437. package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
  438. package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
  439. package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
  440. package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
  441. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
  442. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
  443. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
  444. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
  445. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
  446. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
  447. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
  448. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
  449. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
  450. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
  451. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
  452. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
  453. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
  454. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
  455. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
  456. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
  457. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
  458. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
  459. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
  460. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
  461. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
  462. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
  463. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
  464. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
  465. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
  466. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
  467. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
  468. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
  469. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
  470. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
  471. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
  472. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
  473. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
  474. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
  475. package/node_modules/package-lock.json +3025 -0
  476. package/package-lock.json +3025 -0
  477. package/package.json +52 -4
@@ -0,0 +1,1712 @@
1
+ import { constants, existsSync, promises as fsPromises } from 'node:fs';
2
+ import { chmod, lstat, open, mkdir, realpath, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
3
+ import { basename, join, resolve } from 'node:path';
4
+ import { randomBytes, createHash } from 'node:crypto';
5
+ import { LIMITS, OVERLAY_LIMITS, digestArtifact, digestArtifactFromMetadata, identifyManifest, isWritablePath, resolveOverlayLimits, } from '@loopwright/core';
6
+ import { canonical, freeze, object, list } from './boundary.js';
7
+ import { CAS_CHUNK_BYTES, streamCopyVerifiedBlob } from './cas.js';
8
+ import { refuse, PiFailure } from './errors.js';
9
+ export const DEFAULT_OVERLAY_MANIFEST_MAX_BYTES = 32_768;
10
+ const EXTRA_OVERLAY_MANIFEST_BYTES_PER_FILE = 512;
11
+ const MAX_OVERLAY_MANIFEST_BYTES = 4_194_304;
12
+ export function overlayManifestMaxBytes(maxFiles) {
13
+ if (maxFiles <= OVERLAY_LIMITS.defaultMaxFiles) {
14
+ return DEFAULT_OVERLAY_MANIFEST_MAX_BYTES;
15
+ }
16
+ return Math.min(MAX_OVERLAY_MANIFEST_BYTES, DEFAULT_OVERLAY_MANIFEST_MAX_BYTES + (maxFiles - OVERLAY_LIMITS.defaultMaxFiles) * EXTRA_OVERLAY_MANIFEST_BYTES_PER_FILE);
17
+ }
18
+ export function resolveCandidateOverlayLimits(overlayInput) {
19
+ const resolved = resolveOverlayLimits(overlayInput);
20
+ if (!resolved.ok)
21
+ refuse('INPUT_INVALID', '/lock/spec/contract/spec/budgets/overlay');
22
+ return Object.freeze({
23
+ maxFiles: resolved.value.maxFiles,
24
+ maxBytes: resolved.value.maxBytes,
25
+ manifestMaxBytes: overlayManifestMaxBytes(resolved.value.maxFiles),
26
+ });
27
+ }
28
+ export function gitBlobOid(objectFormat, bytes) {
29
+ return createHash(objectFormat).update(`blob ${bytes.byteLength}\0`).update(bytes).digest('hex');
30
+ }
31
+ const absent = (error) => error.code === 'ENOENT';
32
+ const dirNotEmpty = (error) => {
33
+ const code = error.code;
34
+ return code === 'ENOTEMPTY' || code === 'EEXIST';
35
+ };
36
+ function artifact(path, bytes) {
37
+ const value = digestArtifact(path, bytes);
38
+ if (!value.ok)
39
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
40
+ return value.value;
41
+ }
42
+ function artifactFromMetadata(path, byteLength, sha256Hex) {
43
+ const value = digestArtifactFromMetadata(path, { digest: { algorithm: 'sha256', hex: sha256Hex }, byteLength });
44
+ if (!value.ok)
45
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
46
+ return value.value;
47
+ }
48
+ async function streamHashDescriptor(descriptor, expectedSize, before, phase, options) {
49
+ const sha256 = options.computeSha256 ? createHash('sha256') : null;
50
+ const gitHash = options.gitObjectFormat
51
+ ? createHash(options.gitObjectFormat).update(`blob ${expectedSize}\0`)
52
+ : null;
53
+ const chunkBuf = Buffer.allocUnsafe(CAS_CHUNK_BYTES);
54
+ let totalRead = 0;
55
+ for (;;) {
56
+ const part = await descriptor.read(chunkBuf, 0, chunkBuf.length, totalRead);
57
+ if (part.bytesRead === 0)
58
+ break;
59
+ const slice = chunkBuf.subarray(0, part.bytesRead);
60
+ totalRead += slice.length;
61
+ if (totalRead > expectedSize)
62
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
63
+ sha256?.update(slice);
64
+ gitHash?.update(slice);
65
+ }
66
+ const after = await descriptor.stat({ bigint: true });
67
+ if (!after.isFile()
68
+ || Number(after.nlink) !== 1
69
+ || after.dev !== before.dev
70
+ || after.ino !== before.ino
71
+ || after.size !== before.size
72
+ || after.mtimeNs !== before.mtimeNs
73
+ || after.ctimeNs !== before.ctimeNs
74
+ || totalRead !== expectedSize) {
75
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
76
+ }
77
+ return {
78
+ sha256Hex: sha256 ? sha256.digest('hex') : null,
79
+ gitOid: gitHash ? gitHash.digest('hex') : null,
80
+ };
81
+ }
82
+ async function materializeArtifactEntry(targetPath, file, mode) {
83
+ if ('bytes' in file) {
84
+ await writeFile(targetPath, file.bytes, { flag: 'wx', mode });
85
+ await chmod(targetPath, mode);
86
+ return;
87
+ }
88
+ await streamCopyVerifiedBlob(file.blobPath, targetPath, { byteLength: file.byteLength, sha256Hex: file.digest.hex }, mode);
89
+ }
90
+ function compareUtf16(a, b) {
91
+ return a < b ? -1 : a > b ? 1 : 0;
92
+ }
93
+ function normalizePathKey(path) {
94
+ return path.normalize('NFC').toLowerCase();
95
+ }
96
+ function isPrefixCollision(aNorm, bNorm) {
97
+ return aNorm.startsWith(bNorm + '/') || bNorm.startsWith(aNorm + '/');
98
+ }
99
+ function fingerprintFromStat(info) {
100
+ return {
101
+ mode: Number(info.mode),
102
+ size: Number(info.size),
103
+ dev: Number(info.dev),
104
+ ino: Number(info.ino),
105
+ mtimeNs: info.mtimeNs,
106
+ };
107
+ }
108
+ function sameFingerprint(a, b) {
109
+ return a.mode === b.mode && a.size === b.size && a.dev === b.dev && a.ino === b.ino && a.mtimeNs === b.mtimeNs;
110
+ }
111
+ const preBootBaselineStats = new WeakMap();
112
+ function verifyUntouchedBaselineIdentity(info, entry, phase = 'admission') {
113
+ if (!info.isFile()
114
+ || info.isSymbolicLink()
115
+ || Number(info.nlink) !== 1
116
+ || Number(info.uid) !== (process.getuid?.() ?? Number(info.uid))
117
+ || Number(info.size) !== entry.byteLength) {
118
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
119
+ }
120
+ }
121
+ function verifyUntouchedBaselineStat(info, entry) {
122
+ const expectedMode = entry.mode === '100755' ? 0o555 : 0o444;
123
+ verifyUntouchedBaselineIdentity(info, entry, 'admission');
124
+ if ((Number(info.mode) & 0o777) !== expectedMode) {
125
+ refuse('RECOVERY_REQUIRED', '/candidate');
126
+ }
127
+ return fingerprintFromStat(info);
128
+ }
129
+ async function scanOverlayTree(root, expectedFiles) {
130
+ const stats = new Map();
131
+ const seen = new Set();
132
+ const visit = async (dir, prefix) => {
133
+ const dirInfo = await lstat(dir, { bigint: true });
134
+ if (!dirInfo.isDirectory() || dirInfo.isSymbolicLink() || Number(dirInfo.uid) !== (process.getuid?.() ?? Number(dirInfo.uid))) {
135
+ refuse('RECOVERY_REQUIRED', '/candidate');
136
+ }
137
+ const entries = await fsPromises.readdir(dir);
138
+ for (const entry of entries) {
139
+ const name = prefix ? prefix + '/' + entry : entry;
140
+ const fullPath = join(dir, entry);
141
+ const info = await lstat(fullPath, { bigint: true });
142
+ if (info.isSymbolicLink())
143
+ refuse('RECOVERY_REQUIRED', '/candidate');
144
+ if (info.isDirectory()) {
145
+ await visit(fullPath, name);
146
+ continue;
147
+ }
148
+ if (!info.isFile())
149
+ refuse('RECOVERY_REQUIRED', '/candidate');
150
+ const expected = expectedFiles.get(name);
151
+ if (!expected)
152
+ refuse('RECOVERY_REQUIRED', '/candidate');
153
+ seen.add(name);
154
+ if (expected.kind === 'artifact') {
155
+ if (Number(info.nlink) !== 1
156
+ || Number(info.uid) !== (process.getuid?.() ?? Number(info.uid))
157
+ || Number(info.size) !== expected.byteLength
158
+ || (Number(info.mode) & 0o777) !== expected.mode) {
159
+ refuse('RECOVERY_REQUIRED', '/candidate');
160
+ }
161
+ }
162
+ else {
163
+ stats.set(name, verifyUntouchedBaselineStat(info, expected.entry));
164
+ }
165
+ }
166
+ };
167
+ await visit(root, '');
168
+ if (seen.size !== expectedFiles.size) {
169
+ refuse('RECOVERY_REQUIRED', '/candidate');
170
+ }
171
+ return stats;
172
+ }
173
+ /** Prune empty ancestor subdirectories created/emptied below `root`, never touching `root` itself. */
174
+ export async function pruneEmptyDirectories(root, filePath, onPrune) {
175
+ const pruned = new Set();
176
+ const segments = filePath.split('/').slice(0, -1);
177
+ for (let i = segments.length; i >= 1; i--) {
178
+ const dirPath = join(root, ...segments.slice(0, i));
179
+ try {
180
+ await rmdir(dirPath);
181
+ const resolved = resolve(dirPath);
182
+ pruned.add(resolved);
183
+ onPrune?.(resolved);
184
+ }
185
+ catch (error) {
186
+ if (dirNotEmpty(error))
187
+ break;
188
+ if (absent(error))
189
+ continue;
190
+ throw error;
191
+ }
192
+ }
193
+ return pruned;
194
+ }
195
+ /** Recursively lock (`0o555` bottom-up) or unlock (`0o755` top-down) a real directory tree without following symlinks. */
196
+ export async function setDirectoryTreeMode(dir, mode) {
197
+ const info = await lstat(dir);
198
+ if (!info.isDirectory() || info.isSymbolicLink())
199
+ refuse('RECOVERY_REQUIRED');
200
+ if (mode & 0o200) {
201
+ await chmod(dir, mode);
202
+ }
203
+ const entries = await fsPromises.readdir(dir);
204
+ for (const entry of entries) {
205
+ const childPath = join(dir, entry);
206
+ const childInfo = await lstat(childPath);
207
+ if (childInfo.isSymbolicLink())
208
+ refuse('RECOVERY_REQUIRED');
209
+ if (childInfo.isDirectory()) {
210
+ await setDirectoryTreeMode(childPath, mode);
211
+ }
212
+ }
213
+ if (!(mode & 0o200)) {
214
+ await chmod(dir, mode);
215
+ }
216
+ }
217
+ /** Materialize candidate directory from classic artifacts or a staged `tree_overlay` baseline, locking dirs to `0o555`. */
218
+ export async function materializeCandidateDirectory(candidateDir, input) {
219
+ const baseline = input.candidate.baseline;
220
+ const manifest = input.candidate.manifest;
221
+ if (!baseline) {
222
+ await mkdir(candidateDir, { mode: 0o755 });
223
+ for (const file of input.candidate.artifacts) {
224
+ const path = join(candidateDir, file.name);
225
+ await mkdir(resolve(path, '..'), { recursive: true, mode: 0o755 });
226
+ await materializeArtifactEntry(path, file, 0o444);
227
+ }
228
+ await setDirectoryTreeMode(candidateDir, 0o555);
229
+ return;
230
+ }
231
+ const baseInfo = await lstat(baseline.directory);
232
+ if (!baseInfo.isDirectory() || baseInfo.isSymbolicLink())
233
+ refuse('RECOVERY_REQUIRED', '/candidate');
234
+ await rename(baseline.directory, candidateDir);
235
+ await setDirectoryTreeMode(candidateDir, 0o755);
236
+ const baselineMap = new Map(baseline.entries.map(entry => [entry.name, entry]));
237
+ const deletedSet = new Set(manifest.spec.deleted ?? []);
238
+ const artifactMap = new Map(input.candidate.artifacts.map(file => [file.name, file]));
239
+ for (const deletedPath of deletedSet) {
240
+ const deletedTarget = join(candidateDir, deletedPath);
241
+ const deletedInfo = await lstat(deletedTarget).catch(() => null);
242
+ if (!deletedInfo || !deletedInfo.isFile() || deletedInfo.isSymbolicLink()) {
243
+ refuse('RECOVERY_REQUIRED', '/candidate');
244
+ }
245
+ await unlink(deletedTarget);
246
+ await pruneEmptyDirectories(candidateDir, deletedPath);
247
+ }
248
+ for (const file of input.candidate.artifacts) {
249
+ const targetPath = join(candidateDir, file.name);
250
+ const parent = resolve(targetPath, '..');
251
+ await mkdir(parent, { recursive: true, mode: 0o755 });
252
+ const targetMode = baselineMap.get(file.name)?.mode === '100755' ? 0o555 : 0o444;
253
+ const temporary = join(parent, '.lw-init-' + randomBytes(12).toString('hex'));
254
+ await materializeArtifactEntry(temporary, file, targetMode);
255
+ await rename(temporary, targetPath);
256
+ }
257
+ const expectedFiles = new Map();
258
+ for (const entry of baseline.entries) {
259
+ if (deletedSet.has(entry.name) || artifactMap.has(entry.name))
260
+ continue;
261
+ expectedFiles.set(entry.name, { kind: 'baseline', entry });
262
+ }
263
+ for (const file of input.candidate.artifacts) {
264
+ const mode = baselineMap.get(file.name)?.mode === '100755' ? 0o555 : 0o444;
265
+ const byteLength = 'bytes' in file ? file.bytes.byteLength : file.byteLength;
266
+ expectedFiles.set(file.name, { kind: 'artifact', byteLength, mode });
267
+ }
268
+ await scanOverlayTree(candidateDir, expectedFiles);
269
+ await setDirectoryTreeMode(candidateDir, 0o555);
270
+ const preBootStats = new Map();
271
+ for (const [name, expected] of expectedFiles) {
272
+ if (expected.kind !== 'baseline')
273
+ continue;
274
+ const info = await lstat(join(candidateDir, name), { bigint: true });
275
+ preBootStats.set(name, verifyUntouchedBaselineStat(info, expected.entry));
276
+ }
277
+ preBootBaselineStats.set(baseline, { root: resolve(candidateDir), stats: preBootStats });
278
+ }
279
+ /** One trusted mutation owner; containers have only a read-only mount of this directory. */
280
+ export class Candidate {
281
+ root;
282
+ input;
283
+ #isOverlay;
284
+ #objectFormat;
285
+ #overlayLimits;
286
+ #files;
287
+ #deleted;
288
+ #baseline;
289
+ #baselineNorm = new Map();
290
+ #baselineStats = new Map();
291
+ #verifiedBaseline = new Set();
292
+ #baselineStatsCaptured = false;
293
+ #enforceLockedDirs = false;
294
+ #lockedDirs = new Set();
295
+ #unlockDepth = 0;
296
+ #lastPrunedDirectories = new Set();
297
+ #changes = new WeakMap();
298
+ #deleteChanges = new WeakSet();
299
+ #used = new WeakSet();
300
+ #total;
301
+ #captureDirCache = null;
302
+ constructor(root, input) {
303
+ this.root = root;
304
+ this.input = input;
305
+ const baseTree = input.candidate.manifest.spec.baseTree;
306
+ this.#isOverlay = baseTree !== undefined;
307
+ this.#objectFormat = baseTree?.objectFormat ?? null;
308
+ this.#overlayLimits = resolveCandidateOverlayLimits(input.lock.spec.contract.spec.budgets.overlay);
309
+ this.#files = new Map(input.candidate.manifest.spec.entries.map(entry => [entry.name, freeze(structuredClone(entry))]));
310
+ this.#deleted = new Set(input.candidate.manifest.spec.deleted ?? []);
311
+ this.#baseline = new Map((input.candidate.baseline?.entries ?? []).map(entry => [entry.name, entry]));
312
+ for (const entry of this.#baseline.values()) {
313
+ this.#baselineNorm.set(normalizePathKey(entry.name), entry.name);
314
+ }
315
+ this.#total = [...this.#files.values()].reduce((total, value) => total + value.byteLength, 0);
316
+ }
317
+ #effectiveOverlayMaxEntries() {
318
+ return Math.min(this.#overlayLimits.maxFiles, this.input.policy.limits.candidateEntries);
319
+ }
320
+ #activeBaselineDirs() {
321
+ const dirs = new Set();
322
+ for (const name of this.#baseline.keys()) {
323
+ if (this.#deleted.has(name))
324
+ continue;
325
+ const norm = normalizePathKey(name);
326
+ let slash = norm.indexOf('/');
327
+ while (slash !== -1) {
328
+ dirs.add(norm.slice(0, slash));
329
+ slash = norm.indexOf('/', slash + 1);
330
+ }
331
+ }
332
+ return dirs;
333
+ }
334
+ clearLastPrunedDirectories() {
335
+ this.#lastPrunedDirectories.clear();
336
+ }
337
+ consumeLastPrunedDirectories() {
338
+ const copy = new Set(this.#lastPrunedDirectories);
339
+ this.#lastPrunedDirectories.clear();
340
+ return copy;
341
+ }
342
+ assertWritable(name) {
343
+ this.#writable(name);
344
+ }
345
+ isWritable(name) {
346
+ const contract = this.input.lock.spec.contract, allowed = isWritablePath(contract, name);
347
+ // Retain core glob semantics and add conservative protection for aliases on case-insensitive hosts.
348
+ const protectedOnly = { ...contract, spec: { ...contract.spec, scope: { writable: ['**'], protected: contract.spec.scope.protected.map(pattern => pattern.toLowerCase()) } } };
349
+ const folded = isWritablePath(protectedOnly, name.toLowerCase());
350
+ return Boolean(allowed.ok && allowed.value && folded.ok && folded.value);
351
+ }
352
+ #scopeDeniedError(verb, path) {
353
+ const scope = this.input.lock.spec.contract.spec.scope;
354
+ const writableList = scope.writable.length > 0 ? scope.writable.join(', ') : '(none)';
355
+ const protectedList = scope.protected.length > 0 ? scope.protected.join(', ') : '(none)';
356
+ return freeze({
357
+ kind: 'error',
358
+ targetPath: path,
359
+ message: `Cannot ${verb} ${path}: path is outside writable scope (writable: ${writableList}; protected: ${protectedList}).`,
360
+ });
361
+ }
362
+ #hasTopLevelCandidateEntry() {
363
+ for (const key of this.#files.keys()) {
364
+ if (key === 'candidate' || key.startsWith('candidate/'))
365
+ return true;
366
+ }
367
+ if (!this.#deleted.has('candidate') && this.#baseline.has('candidate')) {
368
+ return true;
369
+ }
370
+ if (this.#activeBaselineDirs().has('candidate')) {
371
+ return true;
372
+ }
373
+ if (this.root.length > 0 && existsSync(join(this.root, 'candidate'))) {
374
+ return true;
375
+ }
376
+ return false;
377
+ }
378
+ #matchSiblingToolScratchCandidate(raw, requireTrailingSlash) {
379
+ if (this.root.length === 0)
380
+ return null;
381
+ const resolvedRoot = resolve(this.root);
382
+ const parentDir = resolve(resolvedRoot, '..');
383
+ const bases = [parentDir];
384
+ if (basename(parentDir) === 'sdk-' + this.input.sessionId) {
385
+ bases.push(resolve(parentDir, '..'));
386
+ }
387
+ for (const base of bases) {
388
+ const toolPrefix = base === '/' ? '/tool-' : base + '/tool-';
389
+ if (!raw.startsWith(toolPrefix))
390
+ continue;
391
+ const rest = raw.slice(toolPrefix.length);
392
+ const slashIdx = rest.indexOf('/');
393
+ if (slashIdx <= 0)
394
+ continue;
395
+ const seg = rest.slice(0, slashIdx);
396
+ if (seg === '.' || seg === '..' || seg.includes('\0'))
397
+ continue;
398
+ const afterSeg = rest.slice(slashIdx);
399
+ if (afterSeg.startsWith('/scratch/candidate/')) {
400
+ return afterSeg.slice('/scratch/candidate/'.length);
401
+ }
402
+ if (!requireTrailingSlash && afterSeg === '/scratch/candidate') {
403
+ return '';
404
+ }
405
+ }
406
+ return null;
407
+ }
408
+ #stripCandidateRootPrefix(raw) {
409
+ if (raw.startsWith('/workspace/candidate/')) {
410
+ return { rest: raw.slice('/workspace/candidate/'.length), stripped: true };
411
+ }
412
+ if (raw.startsWith('/scratch/candidate/')) {
413
+ return { rest: raw.slice('/scratch/candidate/'.length), stripped: true };
414
+ }
415
+ if (this.root.length > 0) {
416
+ const rootPrefix = resolve(this.root) + '/';
417
+ if (raw.startsWith(rootPrefix)) {
418
+ return { rest: raw.slice(rootPrefix.length), stripped: true };
419
+ }
420
+ const scratchRel = this.#matchSiblingToolScratchCandidate(raw, true);
421
+ if (scratchRel !== null) {
422
+ return { rest: scratchRel, stripped: true };
423
+ }
424
+ }
425
+ return { rest: raw, stripped: false };
426
+ }
427
+ #isRootCandidateDirectoryAlias(raw) {
428
+ if (raw === '.'
429
+ || raw === './'
430
+ || raw === '/workspace/candidate'
431
+ || raw === '/workspace/candidate/'
432
+ || raw === '/scratch/candidate'
433
+ || raw === '/scratch/candidate/') {
434
+ return true;
435
+ }
436
+ if (this.root.length > 0) {
437
+ const resolvedRoot = resolve(this.root);
438
+ if (raw === resolvedRoot || raw === resolvedRoot + '/') {
439
+ return true;
440
+ }
441
+ if (this.#matchSiblingToolScratchCandidate(raw, false) === '') {
442
+ return true;
443
+ }
444
+ }
445
+ if ((raw === 'candidate' || raw === './candidate' || raw === 'candidate/' || raw === './candidate/')
446
+ && !this.#hasTopLevelCandidateEntry()) {
447
+ return true;
448
+ }
449
+ return false;
450
+ }
451
+ async captureBaselineStats() {
452
+ if (!this.#isOverlay)
453
+ return;
454
+ this.#baselineStats.clear();
455
+ const baseline = this.input.candidate.baseline;
456
+ const preBoot = baseline ? preBootBaselineStats.get(baseline) : undefined;
457
+ if (preBoot && preBoot.root === resolve(this.root)) {
458
+ this.#enforceLockedDirs = true;
459
+ for (const [name, fingerprint] of preBoot.stats) {
460
+ this.#baselineStats.set(name, fingerprint);
461
+ }
462
+ this.#baselineStatsCaptured = true;
463
+ return;
464
+ }
465
+ const expectedFiles = new Map();
466
+ for (const [name, entry] of this.#baseline) {
467
+ if (this.#files.has(name) || this.#deleted.has(name))
468
+ continue;
469
+ expectedFiles.set(name, { kind: 'baseline', entry });
470
+ }
471
+ for (const [name, ref] of this.#files) {
472
+ const mode = this.#baseline.get(name)?.mode === '100755' ? 0o555 : 0o444;
473
+ expectedFiles.set(name, { kind: 'artifact', byteLength: ref.byteLength, mode });
474
+ }
475
+ const scanned = await scanOverlayTree(this.root, expectedFiles);
476
+ for (const [name, fingerprint] of scanned) {
477
+ this.#baselineStats.set(name, fingerprint);
478
+ }
479
+ this.#baselineStatsCaptured = true;
480
+ }
481
+ #assertHardPathSegments(raw) {
482
+ if (typeof raw !== 'string' || raw.length === 0 || raw.includes('\0') || raw.includes('\\') || raw.includes('//')) {
483
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
484
+ }
485
+ for (const segment of raw.split('/')) {
486
+ if (segment === '..' || segment.toLowerCase() === '.git' || Buffer.byteLength(segment, 'utf8') > 255) {
487
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
488
+ }
489
+ }
490
+ }
491
+ normalize(raw) {
492
+ this.#assertHardPathSegments(raw);
493
+ const { rest, stripped } = this.#stripCandidateRootPrefix(raw);
494
+ let name = rest;
495
+ while (name.startsWith('./')) {
496
+ name = name.slice(2);
497
+ }
498
+ if (!stripped && name.startsWith('candidate/') && !this.#hasTopLevelCandidateEntry()) {
499
+ name = name.slice('candidate/'.length);
500
+ while (name.startsWith('./')) {
501
+ name = name.slice(2);
502
+ }
503
+ }
504
+ artifact(name, new Uint8Array());
505
+ return name;
506
+ }
507
+ enforceHardPathInvariants(raw, options) {
508
+ if (typeof raw !== 'string')
509
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
510
+ if (options?.allowRootAlias && this.#isRootCandidateDirectoryAlias(raw))
511
+ return '.';
512
+ const hadTrailingSlash = raw.length > 1 && raw.endsWith('/') && !raw.endsWith('//');
513
+ return this.normalize(hadTrailingSlash ? raw.slice(0, -1) : raw);
514
+ }
515
+ /**
516
+ * Classify candidate-tool paths for softArgumentErrors while keeping traversal/.git/malformed paths hard-denied.
517
+ * Calling `enforceHardPathInvariants` on the `ok` path is load-bearing for `digestArtifact` path invariants
518
+ * (`normalized` is returned for direct callers while `Execution` re-normalizes downstream).
519
+ */
520
+ classifySoftToolPath(raw, options) {
521
+ this.#assertHardPathSegments(raw);
522
+ if (options?.allowRootAlias && this.#isRootCandidateDirectoryAlias(raw)) {
523
+ return freeze({ kind: 'ok', normalized: '.' });
524
+ }
525
+ const { stripped } = this.#stripCandidateRootPrefix(raw);
526
+ if (!stripped && raw.startsWith('/') && !this.#isRootCandidateDirectoryAlias(raw)) {
527
+ return freeze({
528
+ kind: 'soft_outside_candidate',
529
+ message: `Cannot access "${raw}": path is outside the candidate workspace. Pass a repository-relative path inside candidateDir, or use "bash" to inspect allowed host stage/scratch files.`,
530
+ });
531
+ }
532
+ const normalized = this.enforceHardPathInvariants(raw, options);
533
+ return freeze({ kind: 'ok', normalized });
534
+ }
535
+ #writable(name) {
536
+ if (!this.isWritable(name))
537
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
538
+ }
539
+ #directoryProtected(name) {
540
+ const contract = this.input.lock.spec.contract;
541
+ const projected = { ...contract, spec: { ...contract.spec, scope: { writable: ['**'], protected: contract.spec.scope.protected.map(pattern => pattern.toLowerCase()) } } };
542
+ const allowed = isWritablePath(projected, name.toLowerCase());
543
+ if (!allowed.ok || !allowed.value)
544
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
545
+ }
546
+ #checkWriteCollisions(path) {
547
+ const norm = normalizePathKey(path);
548
+ for (const existing of this.#files.keys()) {
549
+ if (existing === path)
550
+ continue;
551
+ const existingNorm = normalizePathKey(existing);
552
+ if (existingNorm === norm || isPrefixCollision(existingNorm, norm)) {
553
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
554
+ }
555
+ }
556
+ if (!this.#isOverlay)
557
+ return;
558
+ for (const deleted of this.#deleted) {
559
+ if (deleted === path)
560
+ continue;
561
+ const deletedNorm = normalizePathKey(deleted);
562
+ if (deletedNorm === norm || isPrefixCollision(deletedNorm, norm)) {
563
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
564
+ }
565
+ }
566
+ const baseExact = this.#baselineNorm.get(norm);
567
+ if (baseExact !== undefined && baseExact !== path) {
568
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
569
+ }
570
+ if (this.#activeBaselineDirs().has(norm)) {
571
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
572
+ }
573
+ let slash = norm.indexOf('/');
574
+ while (slash !== -1) {
575
+ if (this.#baselineNorm.has(norm.slice(0, slash))) {
576
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
577
+ }
578
+ slash = norm.indexOf('/', slash + 1);
579
+ }
580
+ }
581
+ #dirEntryLimit(includeTemp) {
582
+ const baseLimit = this.#isOverlay
583
+ ? LIMITS.baselineEntries + this.#overlayLimits.maxFiles
584
+ : this.input.policy.limits.candidateEntries;
585
+ return includeTemp ? baseLimit + 1 : baseLimit;
586
+ }
587
+ #buildOverlayManifest(entriesMap, deletedSet) {
588
+ const entries = [...entriesMap.values()].sort((a, b) => compareUtf16(a.name, b.name));
589
+ const deleted = [...deletedSet].sort(compareUtf16);
590
+ return {
591
+ apiVersion: 'loopwright.dev/v1alpha1',
592
+ kind: 'ArtifactManifest',
593
+ metadata: { id: 'candidate' },
594
+ spec: {
595
+ baseTree: this.input.candidate.manifest.spec.baseTree,
596
+ entries,
597
+ deleted,
598
+ },
599
+ };
600
+ }
601
+ async #isCanonicalDir(path, resolved, childInfo) {
602
+ try {
603
+ return await realpath(path) === resolved;
604
+ }
605
+ catch (error) {
606
+ if (error.code === 'EACCES' && resolved !== '/') {
607
+ const parent = resolve(resolved, '..');
608
+ if (await realpath(parent) !== parent)
609
+ return false;
610
+ const [parentStat, childStat] = await Promise.all([
611
+ lstat(parent, { bigint: true }),
612
+ childInfo ?? lstat(path, { bigint: true }),
613
+ ]);
614
+ if (!childStat.isDirectory() || childStat.isSymbolicLink() || childStat.dev !== parentStat.dev) {
615
+ return false;
616
+ }
617
+ // Safe under unprivileged containment where bind mounts cannot be introduced:
618
+ // parent is canonical, child is a non-symlink on the same device (no mount point),
619
+ // exact entry presence blocks case-alias tricks, and callers immediately heal search
620
+ // bits and re-verify realpath(path) === resolved.
621
+ try {
622
+ return (await fsPromises.readdir(parent)).includes(basename(resolved));
623
+ }
624
+ catch (readdirError) {
625
+ if (readdirError.code === 'EACCES')
626
+ return false;
627
+ throw readdirError;
628
+ }
629
+ }
630
+ throw error;
631
+ }
632
+ }
633
+ async #chmodDirectoryNoFollow(path, expectedInfo, targetMode) {
634
+ const uid = process.getuid?.();
635
+ if ((Number(expectedInfo.mode) & 0o400) === 0) {
636
+ const recheck = await lstat(path, { bigint: true });
637
+ if (!recheck.isDirectory()
638
+ || recheck.isSymbolicLink()
639
+ || (uid !== undefined && Number(recheck.uid) !== uid)
640
+ || recheck.dev !== expectedInfo.dev
641
+ || recheck.ino !== expectedInfo.ino) {
642
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
643
+ }
644
+ // Grant read+search (0o500) so the directory stays traversable during the window before open(O_RDONLY | O_DIRECTORY | O_NOFOLLOW).
645
+ await chmod(path, 0o500);
646
+ const granted = await lstat(path, { bigint: true });
647
+ if (!granted.isDirectory()
648
+ || granted.isSymbolicLink()
649
+ || (uid !== undefined && Number(granted.uid) !== uid)
650
+ || granted.dev !== expectedInfo.dev
651
+ || granted.ino !== expectedInfo.ino
652
+ || (Number(granted.mode) & 0o777) !== 0o500) {
653
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
654
+ }
655
+ }
656
+ const descriptor = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
657
+ try {
658
+ const current = await descriptor.stat({ bigint: true });
659
+ if (!current.isDirectory()
660
+ || (uid !== undefined && Number(current.uid) !== uid)
661
+ || current.dev !== expectedInfo.dev
662
+ || current.ino !== expectedInfo.ino) {
663
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
664
+ }
665
+ await descriptor.chmod(targetMode);
666
+ const healed = await descriptor.stat({ bigint: true });
667
+ if (!healed.isDirectory()
668
+ || (uid !== undefined && Number(healed.uid) !== uid)
669
+ || healed.dev !== expectedInfo.dev
670
+ || healed.ino !== expectedInfo.ino
671
+ || (Number(healed.mode) & 0o777) !== targetMode) {
672
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
673
+ }
674
+ }
675
+ finally {
676
+ await descriptor.close();
677
+ }
678
+ }
679
+ async #directory(path) {
680
+ const resolved = resolve(path);
681
+ const value = await lstat(path, { bigint: true });
682
+ if (!value.isDirectory() || value.isSymbolicLink() || Number(value.uid) !== process.getuid?.()) {
683
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
684
+ }
685
+ const modeBits = Number(value.mode) & 0o777;
686
+ if (modeBits === 0o555) {
687
+ this.#lockedDirs.add(resolved);
688
+ if (resolved === resolve(this.root))
689
+ this.#enforceLockedDirs = true;
690
+ }
691
+ if (!await this.#isCanonicalDir(path, resolved, value)) {
692
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
693
+ }
694
+ if (this.#unlockDepth === 0) {
695
+ const needsHeal = (modeBits & 0o022) !== 0
696
+ || (modeBits & 0o500) !== 0o500
697
+ || ((this.#enforceLockedDirs || this.#lockedDirs.has(resolved)) && modeBits !== 0o555);
698
+ if (needsHeal) {
699
+ await this.#chmodDirectoryNoFollow(path, value, 0o555);
700
+ if (await realpath(path) !== resolved) {
701
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
702
+ }
703
+ this.#lockedDirs.add(resolved);
704
+ }
705
+ }
706
+ }
707
+ async withCapturePassCache(fn) {
708
+ if (this.#captureDirCache !== null) {
709
+ return await fn();
710
+ }
711
+ this.#captureDirCache = new Map();
712
+ try {
713
+ return await fn();
714
+ }
715
+ finally {
716
+ this.#captureDirCache = null;
717
+ }
718
+ }
719
+ #buildCaptureDirMap(entries) {
720
+ const dirMap = new Map();
721
+ for (const value of entries) {
722
+ const lower = value.toLowerCase();
723
+ if (dirMap.has(lower)) {
724
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
725
+ }
726
+ dirMap.set(lower, value);
727
+ }
728
+ return dirMap;
729
+ }
730
+ async #readCaptureDirMap(parent) {
731
+ const key = resolve(parent);
732
+ const cached = this.#captureDirCache.get(key);
733
+ if (cached !== undefined)
734
+ return cached;
735
+ const entries = await fsPromises.readdir(parent);
736
+ if (entries.length > this.#dirEntryLimit(true))
737
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
738
+ const dirMap = this.#buildCaptureDirMap(entries);
739
+ this.#captureDirCache.set(key, dirMap);
740
+ return dirMap;
741
+ }
742
+ async #entry(parent, segment) {
743
+ let found;
744
+ if (this.#captureDirCache !== null) {
745
+ const dirMap = await this.#readCaptureDirMap(parent);
746
+ found = dirMap.get(segment.toLowerCase());
747
+ }
748
+ else {
749
+ const entries = await fsPromises.readdir(parent);
750
+ if (entries.length > this.#dirEntryLimit(true))
751
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
752
+ found = entries.find(value => value.toLowerCase() === segment.toLowerCase());
753
+ }
754
+ if (found && found !== segment)
755
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
756
+ if (found)
757
+ return true;
758
+ try {
759
+ await lstat(join(parent, segment));
760
+ }
761
+ catch (error) {
762
+ if (absent(error))
763
+ return false;
764
+ throw error;
765
+ }
766
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
767
+ }
768
+ async #parent(name, create, guard = () => { }, onCreateDir) {
769
+ await this.#directory(this.root);
770
+ let parent = this.root, prefix = '';
771
+ for (const segment of name.split('/').slice(0, -1)) {
772
+ prefix = prefix ? prefix + '/' + segment : segment;
773
+ const path = join(parent, segment);
774
+ if (!await this.#entry(parent, segment)) {
775
+ if (!create)
776
+ return null;
777
+ this.#directoryProtected(prefix);
778
+ guard();
779
+ await mkdir(path, { mode: 0o755 });
780
+ onCreateDir?.(path);
781
+ }
782
+ await this.#directory(path);
783
+ parent = path;
784
+ }
785
+ return parent;
786
+ }
787
+ async #openRegularReadOnlyNoFollow(path, info, phase, allowReadUnlock = true) {
788
+ if (allowReadUnlock && (Number(info.mode) & 0o400) === 0) {
789
+ const uid = process.getuid?.();
790
+ const recheck = await lstat(path, { bigint: true });
791
+ if (!recheck.isFile()
792
+ || recheck.isSymbolicLink()
793
+ || Number(recheck.nlink) !== 1
794
+ || (uid !== undefined && Number(recheck.uid) !== uid)
795
+ || recheck.dev !== info.dev
796
+ || recheck.ino !== info.ino) {
797
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
798
+ }
799
+ // Restore minimum read bit only; final expected mode (0o444/0o555) is applied via fchmod after O_NOFOLLOW + content verification.
800
+ await chmod(path, 0o400);
801
+ const granted = await lstat(path, { bigint: true });
802
+ if (!granted.isFile()
803
+ || granted.isSymbolicLink()
804
+ || Number(granted.nlink) !== 1
805
+ || (uid !== undefined && Number(granted.uid) !== uid)
806
+ || granted.dev !== info.dev
807
+ || granted.ino !== info.ino
808
+ || (Number(granted.mode) & 0o777) !== 0o400) {
809
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
810
+ }
811
+ }
812
+ return await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
813
+ }
814
+ async #verifyAndHealBaselineFile(name, path, expected, info, phase, mode, allowOversize) {
815
+ verifyUntouchedBaselineIdentity(info, expected, phase);
816
+ if (!allowOversize && expected.byteLength > this.input.policy.limits.fileBytes) {
817
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
818
+ }
819
+ if (mode === 'bytes' && expected.byteLength > LIMITS.artifactBytes) {
820
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
821
+ }
822
+ const expectedMode = expected.mode === '100755' ? 0o555 : 0o444;
823
+ const expectedStat = this.#baselineStats.get(name);
824
+ const infoFingerprint = fingerprintFromStat(info);
825
+ if (expectedStat) {
826
+ if (infoFingerprint.dev !== expectedStat.dev
827
+ || infoFingerprint.ino !== expectedStat.ino
828
+ || infoFingerprint.size !== expectedStat.size) {
829
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
830
+ }
831
+ }
832
+ else if (this.#baselineStatsCaptured) {
833
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
834
+ }
835
+ const modeMatches = (Number(info.mode) & 0o777) === expectedMode;
836
+ const fastStatMatches = Boolean(expectedStat
837
+ && this.#verifiedBaseline.has(name)
838
+ && modeMatches
839
+ && sameFingerprint(expectedStat, infoFingerprint));
840
+ if (fastStatMatches && mode === 'verify_only') {
841
+ return null;
842
+ }
843
+ const descriptor = await this.#openRegularReadOnlyNoFollow(path, info, phase);
844
+ try {
845
+ const current = await descriptor.stat({ bigint: true });
846
+ if (!current.isFile()
847
+ || current.isSymbolicLink()
848
+ || Number(current.nlink) !== 1
849
+ || Number(current.uid) !== (process.getuid?.() ?? Number(current.uid))
850
+ || current.dev !== info.dev
851
+ || current.ino !== info.ino
852
+ || Number(current.size) !== expected.byteLength) {
853
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
854
+ }
855
+ if (!allowOversize && Number(current.size) > this.input.policy.limits.fileBytes) {
856
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
857
+ }
858
+ if (mode === 'bytes' && Number(current.size) > LIMITS.artifactBytes) {
859
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
860
+ }
861
+ const fdFingerprint = fingerprintFromStat(current);
862
+ if (mode === 'bytes') {
863
+ if (fastStatMatches && sameFingerprint(infoFingerprint, fdFingerprint)) {
864
+ return await descriptor.readFile();
865
+ }
866
+ const bytes = await descriptor.readFile();
867
+ if (bytes.length !== expected.byteLength || gitBlobOid(this.#objectFormat, bytes) !== expected.oid) {
868
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
869
+ }
870
+ let finalFingerprint = fdFingerprint;
871
+ if ((Number(current.mode) & 0o777) !== expectedMode) {
872
+ await descriptor.chmod(expectedMode);
873
+ const healed = await descriptor.stat({ bigint: true });
874
+ if (!healed.isFile()
875
+ || Number(healed.nlink) !== 1
876
+ || healed.dev !== info.dev
877
+ || healed.ino !== info.ino
878
+ || Number(healed.size) !== expected.byteLength
879
+ || (Number(healed.mode) & 0o777) !== expectedMode) {
880
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
881
+ }
882
+ finalFingerprint = fingerprintFromStat(healed);
883
+ }
884
+ this.#baselineStats.set(name, finalFingerprint);
885
+ this.#verifiedBaseline.add(name);
886
+ return bytes;
887
+ }
888
+ const needGitCheck = !(fastStatMatches && sameFingerprint(infoFingerprint, fdFingerprint));
889
+ const hashed = await streamHashDescriptor(descriptor, expected.byteLength, current, phase, {
890
+ computeSha256: mode === 'ref',
891
+ gitObjectFormat: needGitCheck ? this.#objectFormat : undefined,
892
+ });
893
+ if (needGitCheck && hashed.gitOid !== expected.oid) {
894
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
895
+ }
896
+ if (needGitCheck) {
897
+ let finalFingerprint = fdFingerprint;
898
+ if ((Number(current.mode) & 0o777) !== expectedMode) {
899
+ await descriptor.chmod(expectedMode);
900
+ const healed = await descriptor.stat({ bigint: true });
901
+ if (!healed.isFile()
902
+ || Number(healed.nlink) !== 1
903
+ || healed.dev !== info.dev
904
+ || healed.ino !== info.ino
905
+ || Number(healed.size) !== expected.byteLength
906
+ || (Number(healed.mode) & 0o777) !== expectedMode) {
907
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase });
908
+ }
909
+ finalFingerprint = fingerprintFromStat(healed);
910
+ }
911
+ this.#baselineStats.set(name, finalFingerprint);
912
+ this.#verifiedBaseline.add(name);
913
+ }
914
+ return mode === 'ref' ? artifactFromMetadata(name, expected.byteLength, hashed.sha256Hex) : null;
915
+ }
916
+ finally {
917
+ await descriptor.close();
918
+ }
919
+ }
920
+ async #verifyCurrentRef(name) {
921
+ const parent = await this.#parent(name, false);
922
+ const knownOverlay = this.#files.get(name);
923
+ const baseEntry = this.#isOverlay && !this.#deleted.has(name) ? this.#baseline.get(name) : undefined;
924
+ const isKnown = knownOverlay !== undefined || baseEntry !== undefined;
925
+ if (parent === null || !await this.#entry(parent, name.split('/').at(-1))) {
926
+ if (isKnown)
927
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
928
+ return null;
929
+ }
930
+ const path = join(this.root, name);
931
+ const info = await lstat(path, { bigint: true });
932
+ if (!info.isFile()
933
+ || info.isSymbolicLink()
934
+ || Number(info.nlink) !== 1
935
+ || Number(info.uid) !== process.getuid?.()
936
+ || Number(info.size) > this.input.policy.limits.fileBytes
937
+ || (baseEntry !== undefined && baseEntry.byteLength > this.input.policy.limits.fileBytes)) {
938
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
939
+ }
940
+ if (!isKnown)
941
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
942
+ if (knownOverlay !== undefined) {
943
+ const expectedOverlayMode = this.#baseline.get(name)?.mode === '100755' ? 0o555 : 0o444;
944
+ const descriptor = await this.#openRegularReadOnlyNoFollow(path, info, 'tool', this.#isOverlay || this.#enforceLockedDirs);
945
+ try {
946
+ const current = await descriptor.stat({ bigint: true });
947
+ if (!current.isFile() || Number(current.nlink) !== 1 || current.dev !== info.dev || current.ino !== info.ino || Number(current.size) > this.input.policy.limits.fileBytes) {
948
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
949
+ }
950
+ if (Number(current.size) !== knownOverlay.byteLength) {
951
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
952
+ }
953
+ const hashed = await streamHashDescriptor(descriptor, knownOverlay.byteLength, current, 'tool', { computeSha256: true });
954
+ const actualRef = artifactFromMetadata(name, knownOverlay.byteLength, hashed.sha256Hex);
955
+ if (canonical(actualRef) !== canonical(knownOverlay))
956
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
957
+ if ((this.#isOverlay || this.#enforceLockedDirs) && (Number(current.mode) & 0o777) !== expectedOverlayMode) {
958
+ await descriptor.chmod(expectedOverlayMode);
959
+ }
960
+ return actualRef;
961
+ }
962
+ finally {
963
+ await descriptor.close();
964
+ }
965
+ }
966
+ return (await this.#verifyAndHealBaselineFile(name, path, baseEntry, info, 'tool', 'ref', false));
967
+ }
968
+ async #currentBytes(name) {
969
+ const parent = await this.#parent(name, false);
970
+ const knownOverlay = this.#files.get(name);
971
+ const baseEntry = this.#isOverlay && !this.#deleted.has(name) ? this.#baseline.get(name) : undefined;
972
+ const isKnown = knownOverlay !== undefined || baseEntry !== undefined;
973
+ if (parent === null || !await this.#entry(parent, name.split('/').at(-1))) {
974
+ if (isKnown)
975
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
976
+ return null;
977
+ }
978
+ const path = join(this.root, name);
979
+ const info = await lstat(path, { bigint: true });
980
+ const editMaxBytes = Math.min(this.input.policy.limits.fileBytes, LIMITS.artifactBytes);
981
+ if (!info.isFile()
982
+ || info.isSymbolicLink()
983
+ || Number(info.nlink) !== 1
984
+ || Number(info.uid) !== process.getuid?.()
985
+ || Number(info.size) > editMaxBytes
986
+ || (baseEntry !== undefined && baseEntry.byteLength > editMaxBytes)) {
987
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
988
+ }
989
+ if (!isKnown)
990
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
991
+ if (knownOverlay !== undefined) {
992
+ const expectedOverlayMode = this.#baseline.get(name)?.mode === '100755' ? 0o555 : 0o444;
993
+ const descriptor = await this.#openRegularReadOnlyNoFollow(path, info, 'tool', this.#isOverlay || this.#enforceLockedDirs);
994
+ try {
995
+ const current = await descriptor.stat({ bigint: true });
996
+ if (!current.isFile() || Number(current.nlink) !== 1 || current.dev !== info.dev || current.ino !== info.ino || Number(current.size) > editMaxBytes) {
997
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
998
+ }
999
+ const bytes = await descriptor.readFile();
1000
+ if (canonical(artifact(name, bytes)) !== canonical(knownOverlay))
1001
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1002
+ if ((this.#isOverlay || this.#enforceLockedDirs) && (Number(current.mode) & 0o777) !== expectedOverlayMode) {
1003
+ await descriptor.chmod(expectedOverlayMode);
1004
+ }
1005
+ return bytes;
1006
+ }
1007
+ finally {
1008
+ await descriptor.close();
1009
+ }
1010
+ }
1011
+ return (await this.#verifyAndHealBaselineFile(name, path, baseEntry, info, 'tool', 'bytes', false));
1012
+ }
1013
+ async #listDirectoryEntries(dirPath) {
1014
+ await this.#directory(dirPath);
1015
+ const entries = await fsPromises.readdir(dirPath);
1016
+ if (entries.length > this.#dirEntryLimit(false))
1017
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1018
+ const visible = entries.filter(entry => entry.toLowerCase() !== '.git').sort(compareUtf16);
1019
+ const shown = visible.slice(0, 200);
1020
+ const formatted = [];
1021
+ for (const entry of shown) {
1022
+ const childInfo = await lstat(join(dirPath, entry));
1023
+ if (childInfo.isSymbolicLink())
1024
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1025
+ formatted.push(childInfo.isDirectory() ? entry + '/' : entry);
1026
+ }
1027
+ if (visible.length > shown.length) {
1028
+ formatted.push(`... (${visible.length - shown.length} more entries)`);
1029
+ }
1030
+ return formatted.length > 0 ? formatted.join('\n') : '(empty directory)';
1031
+ }
1032
+ async checkRead(raw) {
1033
+ const path = this.normalize(raw), ref = await this.#verifyCurrentRef(path);
1034
+ if (!ref)
1035
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1036
+ return freeze({ path, ref });
1037
+ }
1038
+ async inspectReadTarget(raw) {
1039
+ if (typeof raw !== 'string')
1040
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1041
+ if (this.#isRootCandidateDirectoryAlias(raw)) {
1042
+ const listing = await this.#listDirectoryEntries(this.root);
1043
+ return freeze({
1044
+ kind: 'error',
1045
+ targetPath: '.',
1046
+ message: `Path "." is a directory, not a file. Entries:\n${listing}`,
1047
+ });
1048
+ }
1049
+ const hadTrailingSlash = raw.length > 1 && raw.endsWith('/') && !raw.endsWith('//');
1050
+ const path = this.normalize(hadTrailingSlash ? raw.slice(0, -1) : raw);
1051
+ const knownOverlay = this.#files.get(path);
1052
+ const baseEntry = this.#isOverlay && !this.#deleted.has(path) ? this.#baseline.get(path) : undefined;
1053
+ const isKnown = knownOverlay !== undefined || baseEntry !== undefined;
1054
+ const parent = await this.#parent(path, false);
1055
+ const leaf = path.split('/').at(-1);
1056
+ if (parent === null || !await this.#entry(parent, leaf)) {
1057
+ if (isKnown)
1058
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1059
+ return freeze({ kind: 'error', targetPath: path, message: `File not found: ${path}` });
1060
+ }
1061
+ const fullPath = join(this.root, path);
1062
+ const info = await lstat(fullPath, { bigint: true });
1063
+ if (info.isSymbolicLink() || Number(info.uid) !== process.getuid?.()) {
1064
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1065
+ }
1066
+ if (info.isDirectory()) {
1067
+ if (isKnown)
1068
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1069
+ const listing = await this.#listDirectoryEntries(fullPath);
1070
+ return freeze({
1071
+ kind: 'error',
1072
+ targetPath: path,
1073
+ message: `Path "${path}" is a directory, not a file. Entries:\n${listing}`,
1074
+ });
1075
+ }
1076
+ if (hadTrailingSlash) {
1077
+ return freeze({
1078
+ kind: 'error',
1079
+ targetPath: path,
1080
+ message: `Path "${path}" is a file, not a directory.`,
1081
+ });
1082
+ }
1083
+ const checked = await this.checkRead(path);
1084
+ return freeze({ kind: 'file', path: checked.path, ref: checked.ref });
1085
+ }
1086
+ #prepare(path, old, bytes) {
1087
+ this.#checkWriteCollisions(path);
1088
+ const after = artifact(path, bytes), limits = this.input.policy.limits;
1089
+ const capacity = limits.artifactBytes - limits.sessionBytes - this.input.resources.reduce((total, item) => total + item.bytes.length, 0);
1090
+ if (bytes.length > limits.fileBytes)
1091
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1092
+ if (!this.#isOverlay) {
1093
+ if (this.#total - (old?.byteLength ?? 0) + bytes.length > capacity || !old && this.#files.size >= limits.candidateEntries) {
1094
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1095
+ }
1096
+ }
1097
+ else {
1098
+ const baseEntry = this.#baseline.get(path);
1099
+ const revertsToBaseline = baseEntry !== undefined && gitBlobOid(this.#objectFormat, bytes) === baseEntry.oid;
1100
+ const prevOverlayBytes = this.#overlayByteLength(path);
1101
+ const nextOverlayBytes = revertsToBaseline ? 0 : bytes.length;
1102
+ const projectedTotal = this.#total - prevOverlayBytes + nextOverlayBytes;
1103
+ if (projectedTotal > this.#overlayLimits.maxBytes || projectedTotal > capacity) {
1104
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1105
+ }
1106
+ const addsOverlayEntry = !revertsToBaseline && !this.#files.has(path);
1107
+ if (addsOverlayEntry && this.#files.size >= this.#effectiveOverlayMaxEntries()) {
1108
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1109
+ }
1110
+ const nextOverlay = new Map(this.#files);
1111
+ const nextDeleted = new Set(this.#deleted);
1112
+ nextDeleted.delete(path);
1113
+ if (revertsToBaseline)
1114
+ nextOverlay.delete(path);
1115
+ else
1116
+ nextOverlay.set(path, after);
1117
+ const projectedManifest = this.#buildOverlayManifest(nextOverlay, nextDeleted);
1118
+ if (Buffer.byteLength(canonical(projectedManifest)) > this.#overlayLimits.manifestMaxBytes) {
1119
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1120
+ }
1121
+ }
1122
+ const change = freeze({ path, before: old, after });
1123
+ this.#changes.set(change, bytes);
1124
+ return change;
1125
+ }
1126
+ #overlayByteLength(path) {
1127
+ return this.#files.get(path)?.byteLength ?? 0;
1128
+ }
1129
+ async prepareWrite(raw, content) {
1130
+ const path = this.normalize(raw);
1131
+ this.#writable(path);
1132
+ if (typeof content !== 'string' || new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(content)) !== content) {
1133
+ refuse('TOOL_DENIED', '/content', { phase: 'tool' });
1134
+ }
1135
+ return this.#prepare(path, await this.#verifyCurrentRef(path), Buffer.from(content));
1136
+ }
1137
+ async prepareEdit(raw, input) {
1138
+ const path = this.normalize(raw);
1139
+ this.#writable(path);
1140
+ const before = await this.#currentBytes(path);
1141
+ if (!before)
1142
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1143
+ let text;
1144
+ try {
1145
+ text = new TextDecoder('utf-8', { fatal: true }).decode(before);
1146
+ }
1147
+ catch {
1148
+ refuse('TOOL_DENIED', '/edits', { phase: 'tool' });
1149
+ }
1150
+ const ranges = list(input, 32, '/edits').map(value => {
1151
+ const entry = object(value, ['oldText', 'newText'], '/edits');
1152
+ if (typeof entry.oldText !== 'string' || !entry.oldText || typeof entry.newText !== 'string' || Buffer.from(entry.newText).toString('utf8') !== entry.newText) {
1153
+ refuse('TOOL_DENIED', '/edits', { phase: 'tool' });
1154
+ }
1155
+ const index = text.indexOf(entry.oldText);
1156
+ if (index < 0 || text.indexOf(entry.oldText, index + 1) >= 0)
1157
+ refuse('TOOL_DENIED', '/edits', { phase: 'tool' });
1158
+ return { start: index, end: index + entry.oldText.length, replacement: entry.newText };
1159
+ }).sort((a, b) => a.start - b.start);
1160
+ if (!ranges.length || ranges.some((range, index) => index > 0 && ranges[index - 1].end > range.start)) {
1161
+ refuse('TOOL_DENIED', '/edits', { phase: 'tool' });
1162
+ }
1163
+ let offset = 0, result = '';
1164
+ for (const range of ranges) {
1165
+ result += text.slice(offset, range.start) + range.replacement;
1166
+ offset = range.end;
1167
+ }
1168
+ result += text.slice(offset);
1169
+ return this.#prepare(path, artifact(path, before), Buffer.from(result));
1170
+ }
1171
+ async prepareDelete(raw) {
1172
+ const path = this.normalize(raw);
1173
+ this.#writable(path);
1174
+ const old = await this.#verifyCurrentRef(path);
1175
+ if (!old)
1176
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1177
+ if (this.#isOverlay && this.#baseline.has(path)) {
1178
+ const nextOverlay = new Map(this.#files);
1179
+ nextOverlay.delete(path);
1180
+ const nextDeleted = new Set(this.#deleted);
1181
+ nextDeleted.add(path);
1182
+ if (nextDeleted.size > this.#overlayLimits.maxFiles) {
1183
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1184
+ }
1185
+ const projectedManifest = this.#buildOverlayManifest(nextOverlay, nextDeleted);
1186
+ if (Buffer.byteLength(canonical(projectedManifest)) > this.#overlayLimits.manifestMaxBytes) {
1187
+ refuse('OUTPUT_LIMIT', '/candidate', { phase: 'tool' });
1188
+ }
1189
+ }
1190
+ const change = freeze({ path, before: old, after: null, deleted: true });
1191
+ this.#deleteChanges.add(change);
1192
+ return change;
1193
+ }
1194
+ async tryPrepareWrite(raw, content, options) {
1195
+ if (typeof content !== 'string' || new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(content)) !== content) {
1196
+ refuse('TOOL_DENIED', '/content', { phase: 'tool' });
1197
+ }
1198
+ const hadTrailingSlash = typeof raw === 'string' && raw.length > 1 && raw.endsWith('/') && !raw.endsWith('//');
1199
+ const path = this.normalize(hadTrailingSlash ? raw.slice(0, -1) : raw);
1200
+ if (!this.isWritable(path)) {
1201
+ if (options?.softScopeError)
1202
+ return this.#scopeDeniedError('write', path);
1203
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1204
+ }
1205
+ if (!options?.softScopeError) {
1206
+ if (hadTrailingSlash)
1207
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1208
+ return freeze({ kind: 'change', change: await this.prepareWrite(path, content) });
1209
+ }
1210
+ const knownOverlay = this.#files.get(path);
1211
+ const baseEntry = this.#isOverlay && !this.#deleted.has(path) ? this.#baseline.get(path) : undefined;
1212
+ const isKnown = knownOverlay !== undefined || baseEntry !== undefined;
1213
+ const parent = await this.#parent(path, false);
1214
+ const leaf = path.split('/').at(-1);
1215
+ if (parent !== null && await this.#entry(parent, leaf)) {
1216
+ const targetStat = await lstat(join(this.root, path));
1217
+ if (!targetStat.isSymbolicLink() && targetStat.isDirectory()) {
1218
+ if (isKnown)
1219
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1220
+ return freeze({
1221
+ kind: 'error',
1222
+ targetPath: path,
1223
+ message: `Cannot write ${path}: path is a directory, not a file.`,
1224
+ });
1225
+ }
1226
+ }
1227
+ if (hadTrailingSlash) {
1228
+ return freeze({
1229
+ kind: 'error',
1230
+ targetPath: path,
1231
+ message: `Cannot write ${path}: path is a directory, not a file.`,
1232
+ });
1233
+ }
1234
+ return freeze({ kind: 'change', change: this.#prepare(path, await this.#verifyCurrentRef(path), Buffer.from(content)) });
1235
+ }
1236
+ async tryPrepareEdit(raw, input, options) {
1237
+ const hadTrailingSlash = typeof raw === 'string' && raw.length > 1 && raw.endsWith('/') && !raw.endsWith('//');
1238
+ const path = this.normalize(hadTrailingSlash ? raw.slice(0, -1) : raw);
1239
+ let validatedEntries;
1240
+ if (options?.softArgumentError) {
1241
+ let items;
1242
+ try {
1243
+ items = list(input, 32, '/edits');
1244
+ if (items.length < 1)
1245
+ throw new Error('empty-edits');
1246
+ }
1247
+ catch {
1248
+ return freeze({
1249
+ kind: 'error',
1250
+ targetPath: path,
1251
+ message: `Invalid arguments for tool "edit" on ${path}: "edits" must be an array of 1..32 {"oldText": "...", "newText": "..."} objects.`,
1252
+ });
1253
+ }
1254
+ validatedEntries = [];
1255
+ for (const [idx, value] of items.entries()) {
1256
+ let entry;
1257
+ try {
1258
+ entry = object(value, ['oldText', 'newText'], '/edits');
1259
+ }
1260
+ catch {
1261
+ return freeze({
1262
+ kind: 'error',
1263
+ targetPath: path,
1264
+ message: `Invalid arguments for tool "edit" on ${path}: edits[${idx}] must be an object with exact string fields {"oldText": "...", "newText": "..."}.`,
1265
+ });
1266
+ }
1267
+ if (typeof entry.oldText !== 'string'
1268
+ || typeof entry.newText !== 'string'
1269
+ || Buffer.from(entry.oldText).toString('utf8') !== entry.oldText
1270
+ || Buffer.from(entry.newText).toString('utf8') !== entry.newText) {
1271
+ return freeze({
1272
+ kind: 'error',
1273
+ targetPath: path,
1274
+ message: `Invalid arguments for tool "edit" on ${path}: edits[${idx}].oldText and edits[${idx}].newText must be valid UTF-8 strings.`,
1275
+ });
1276
+ }
1277
+ validatedEntries.push({ oldText: entry.oldText, newText: entry.newText });
1278
+ }
1279
+ }
1280
+ else {
1281
+ const items = list(input, 32, '/edits');
1282
+ validatedEntries = items.map(value => {
1283
+ const entry = object(value, ['oldText', 'newText'], '/edits');
1284
+ if (typeof entry.oldText !== 'string' || typeof entry.newText !== 'string' || Buffer.from(entry.newText).toString('utf8') !== entry.newText) {
1285
+ refuse('TOOL_DENIED', '/edits', { phase: 'tool' });
1286
+ }
1287
+ return { oldText: entry.oldText, newText: entry.newText };
1288
+ });
1289
+ }
1290
+ if (!this.isWritable(path)) {
1291
+ if (options?.softScopeError)
1292
+ return this.#scopeDeniedError('edit', path);
1293
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1294
+ }
1295
+ const knownOverlay = this.#files.get(path);
1296
+ const baseEntry = this.#isOverlay && !this.#deleted.has(path) ? this.#baseline.get(path) : undefined;
1297
+ const isKnown = knownOverlay !== undefined || baseEntry !== undefined;
1298
+ const parent = await this.#parent(path, false);
1299
+ const leaf = path.split('/').at(-1);
1300
+ if (parent === null || !await this.#entry(parent, leaf)) {
1301
+ if (isKnown)
1302
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1303
+ return freeze({
1304
+ kind: 'error',
1305
+ targetPath: path,
1306
+ message: `Cannot edit ${path}: file does not exist (use write to create new files).`,
1307
+ });
1308
+ }
1309
+ const targetStat = await lstat(join(this.root, path));
1310
+ if (!targetStat.isSymbolicLink() && targetStat.isDirectory()) {
1311
+ if (isKnown)
1312
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1313
+ return freeze({
1314
+ kind: 'error',
1315
+ targetPath: path,
1316
+ message: `Cannot edit ${path}: path is a directory, not a file.`,
1317
+ });
1318
+ }
1319
+ if (hadTrailingSlash) {
1320
+ return freeze({
1321
+ kind: 'error',
1322
+ targetPath: path,
1323
+ message: `Cannot edit ${path}: trailing slash is not allowed for file paths.`,
1324
+ });
1325
+ }
1326
+ const before = await this.#currentBytes(path);
1327
+ if (!before) {
1328
+ return freeze({
1329
+ kind: 'error',
1330
+ targetPath: path,
1331
+ message: `Cannot edit ${path}: file does not exist (use write to create new files).`,
1332
+ });
1333
+ }
1334
+ let text;
1335
+ try {
1336
+ text = new TextDecoder('utf-8', { fatal: true }).decode(before);
1337
+ }
1338
+ catch {
1339
+ return freeze({
1340
+ kind: 'error',
1341
+ targetPath: path,
1342
+ message: `Cannot edit ${path}: file is not valid UTF-8 text.`,
1343
+ });
1344
+ }
1345
+ if (validatedEntries.length === 0) {
1346
+ return freeze({
1347
+ kind: 'error',
1348
+ targetPath: path,
1349
+ message: `Edit failed on ${path}: edits list must not be empty.`,
1350
+ });
1351
+ }
1352
+ const ranges = [];
1353
+ for (const [editIndex, entry] of validatedEntries.entries()) {
1354
+ if (entry.oldText.length === 0) {
1355
+ return freeze({
1356
+ kind: 'error',
1357
+ targetPath: path,
1358
+ message: `Edit failed on ${path}: edits[${editIndex}].oldText must not be empty.`,
1359
+ });
1360
+ }
1361
+ const index = text.indexOf(entry.oldText);
1362
+ if (index < 0) {
1363
+ return freeze({
1364
+ kind: 'error',
1365
+ targetPath: path,
1366
+ message: `Edit failed on ${path}: edits[${editIndex}].oldText was not found in the file. Read the target lines and retry with exact text.`,
1367
+ });
1368
+ }
1369
+ if (text.indexOf(entry.oldText, index + 1) >= 0) {
1370
+ return freeze({
1371
+ kind: 'error',
1372
+ targetPath: path,
1373
+ message: `Edit failed on ${path}: edits[${editIndex}].oldText matched multiple locations. Include more surrounding lines so oldText is unique.`,
1374
+ });
1375
+ }
1376
+ ranges.push({ start: index, end: index + entry.oldText.length, replacement: entry.newText });
1377
+ }
1378
+ ranges.sort((a, b) => a.start - b.start);
1379
+ if (ranges.some((range, index) => index > 0 && ranges[index - 1].end > range.start)) {
1380
+ return freeze({
1381
+ kind: 'error',
1382
+ targetPath: path,
1383
+ message: `Edit failed on ${path}: multiple edits overlap. Merge overlapping edits and retry.`,
1384
+ });
1385
+ }
1386
+ let offset = 0;
1387
+ let result = '';
1388
+ for (const range of ranges) {
1389
+ result += text.slice(offset, range.start) + range.replacement;
1390
+ offset = range.end;
1391
+ }
1392
+ result += text.slice(offset);
1393
+ return freeze({ kind: 'change', change: this.#prepare(path, artifact(path, before), Buffer.from(result)) });
1394
+ }
1395
+ async tryPrepareDelete(raw, options) {
1396
+ const hadTrailingSlash = typeof raw === 'string' && raw.length > 1 && raw.endsWith('/') && !raw.endsWith('//');
1397
+ const path = this.normalize(hadTrailingSlash ? raw.slice(0, -1) : raw);
1398
+ if (!this.isWritable(path)) {
1399
+ if (options?.softScopeError)
1400
+ return this.#scopeDeniedError('delete', path);
1401
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1402
+ }
1403
+ const knownOverlay = this.#files.get(path);
1404
+ const baseEntry = this.#isOverlay && !this.#deleted.has(path) ? this.#baseline.get(path) : undefined;
1405
+ const isKnown = knownOverlay !== undefined || baseEntry !== undefined;
1406
+ const parent = await this.#parent(path, false);
1407
+ const leaf = path.split('/').at(-1);
1408
+ if (parent === null || !await this.#entry(parent, leaf)) {
1409
+ if (isKnown)
1410
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1411
+ return freeze({
1412
+ kind: 'error',
1413
+ targetPath: path,
1414
+ message: `Cannot delete ${path}: file does not exist.`,
1415
+ });
1416
+ }
1417
+ const targetStat = await lstat(join(this.root, path));
1418
+ if (!targetStat.isSymbolicLink() && targetStat.isDirectory()) {
1419
+ if (isKnown)
1420
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1421
+ return freeze({
1422
+ kind: 'error',
1423
+ targetPath: path,
1424
+ message: `Cannot delete ${path}: path is a directory, not a file.`,
1425
+ });
1426
+ }
1427
+ if (hadTrailingSlash) {
1428
+ return freeze({
1429
+ kind: 'error',
1430
+ targetPath: path,
1431
+ message: `Cannot delete ${path}: trailing slash is not allowed for file paths.`,
1432
+ });
1433
+ }
1434
+ return freeze({ kind: 'change', change: await this.prepareDelete(path) });
1435
+ }
1436
+ async #withUnlockedAncestors(relPath, isDelete, fn) {
1437
+ // Unlock existing canonical ancestors root-to-leaf inside try, then relock unlocked/created directories leaf-to-root afterward.
1438
+ const unlocked = [];
1439
+ const createdDirs = [];
1440
+ const prunedDirs = new Set();
1441
+ let result;
1442
+ let opFailed = false;
1443
+ let opError;
1444
+ this.#unlockDepth++;
1445
+ try {
1446
+ const segments = relPath.split('/').slice(0, -1);
1447
+ let currentDir = this.root;
1448
+ for (let i = 0; i <= segments.length; i++) {
1449
+ if (i > 0)
1450
+ currentDir = join(currentDir, segments[i - 1]);
1451
+ let info;
1452
+ try {
1453
+ info = await lstat(currentDir, { bigint: true });
1454
+ }
1455
+ catch (error) {
1456
+ if (absent(error))
1457
+ break;
1458
+ throw error;
1459
+ }
1460
+ const resolved = resolve(currentDir);
1461
+ if (!info.isDirectory() || info.isSymbolicLink() || Number(info.uid) !== process.getuid?.() || !await this.#isCanonicalDir(currentDir, resolved, info)) {
1462
+ // Stop unlocking at non-canonical or unexpected ancestor; inner checks refuse while the leaf-to-root relock loop restores any unlocked ancestors.
1463
+ break;
1464
+ }
1465
+ const modeBits = Number(info.mode) & 0o777;
1466
+ if (modeBits === 0o555) {
1467
+ this.#lockedDirs.add(resolved);
1468
+ if (resolved === resolve(this.root))
1469
+ this.#enforceLockedDirs = true;
1470
+ }
1471
+ if ((modeBits & 0o022) !== 0 || (modeBits & 0o500) !== 0o500 || (modeBits & 0o200) === 0) {
1472
+ await this.#chmodDirectoryNoFollow(currentDir, info, 0o755);
1473
+ if (await realpath(currentDir) !== resolved)
1474
+ break;
1475
+ unlocked.push(currentDir);
1476
+ }
1477
+ else if ((this.#enforceLockedDirs || this.#lockedDirs.has(resolved)) && modeBits !== 0o555) {
1478
+ unlocked.push(currentDir);
1479
+ }
1480
+ }
1481
+ result = await fn({
1482
+ onCreateDir: dir => { if (unlocked.length > 0)
1483
+ createdDirs.push(dir); },
1484
+ onPruneDir: dir => { prunedDirs.add(dir); },
1485
+ });
1486
+ }
1487
+ catch (error) {
1488
+ opFailed = true;
1489
+ opError = error;
1490
+ }
1491
+ finally {
1492
+ this.#unlockDepth--;
1493
+ }
1494
+ let relockError = null;
1495
+ const toRelock = [...unlocked, ...createdDirs];
1496
+ for (let i = toRelock.length - 1; i >= 0; i--) {
1497
+ const dir = toRelock[i];
1498
+ try {
1499
+ const preRelock = await lstat(dir, { bigint: true });
1500
+ if (!preRelock.isDirectory() || preRelock.isSymbolicLink()) {
1501
+ relockError ??= new PiFailure({ code: 'RECOVERY_REQUIRED', path: '/candidate', phase: 'tool', retryable: false, effect: 'possible', requestId: null, operationId: null, stateErrorCode: null });
1502
+ continue;
1503
+ }
1504
+ await this.#chmodDirectoryNoFollow(dir, preRelock, 0o555);
1505
+ }
1506
+ catch (error) {
1507
+ if (isDelete && dir !== this.root && prunedDirs.has(resolve(dir)) && absent(error))
1508
+ continue;
1509
+ relockError ??= error;
1510
+ }
1511
+ }
1512
+ if (opFailed)
1513
+ throw opError;
1514
+ if (relockError !== null)
1515
+ throw relockError;
1516
+ return result;
1517
+ }
1518
+ async commit(change, guard) {
1519
+ const isDelete = this.#deleteChanges.has(change);
1520
+ const bytes = this.#changes.get(change);
1521
+ if ((!isDelete && !bytes) || this.#used.has(change))
1522
+ refuse('TOOL_DENIED', '/operation', { phase: 'tool' });
1523
+ this.#used.add(change);
1524
+ const path = this.normalize(change.path);
1525
+ this.#writable(path);
1526
+ if (isDelete) {
1527
+ this.#lastPrunedDirectories.clear();
1528
+ return this.#withUnlockedAncestors(path, true, async ({ onPruneDir }) => {
1529
+ const parent = await this.#parent(path, false);
1530
+ if (!parent)
1531
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1532
+ const before = await this.#verifyCurrentRef(path);
1533
+ if (canonical(before) !== canonical(change.before))
1534
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1535
+ guard();
1536
+ const targetPath = join(this.root, path);
1537
+ await unlink(targetPath);
1538
+ await pruneEmptyDirectories(this.root, path, dir => {
1539
+ this.#lastPrunedDirectories.add(dir);
1540
+ onPruneDir(dir);
1541
+ });
1542
+ await this.#syncDeepestSurvivingDirectory(path);
1543
+ const prevOverlayBytes = this.#overlayByteLength(path);
1544
+ this.#total -= prevOverlayBytes;
1545
+ this.#files.delete(path);
1546
+ this.#baselineStats.delete(path);
1547
+ this.#verifiedBaseline.delete(path);
1548
+ if (this.#isOverlay && this.#baseline.has(path)) {
1549
+ this.#deleted.add(path);
1550
+ }
1551
+ return null;
1552
+ });
1553
+ }
1554
+ const writeBytes = bytes;
1555
+ return this.#withUnlockedAncestors(path, false, async ({ onCreateDir }) => {
1556
+ const parent = await this.#parent(path, true, guard, onCreateDir);
1557
+ if (!parent)
1558
+ refuse('TOOL_DENIED', '/path', { phase: 'tool' });
1559
+ const before = await this.#verifyCurrentRef(path);
1560
+ if (canonical(before) !== canonical(change.before))
1561
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1562
+ const baseEntry = this.#baseline.get(path);
1563
+ const fileMode = baseEntry?.mode === '100755' ? 0o555 : 0o444;
1564
+ const temporary = join(parent, '.lw-write-' + randomBytes(16).toString('hex'));
1565
+ guard();
1566
+ const descriptor = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, fileMode);
1567
+ try {
1568
+ try {
1569
+ await descriptor.writeFile(writeBytes);
1570
+ await descriptor.chmod(fileMode);
1571
+ await descriptor.sync();
1572
+ }
1573
+ finally {
1574
+ await descriptor.close();
1575
+ }
1576
+ await this.#parent(path, false);
1577
+ const latest = await this.#verifyCurrentRef(path);
1578
+ if (canonical(latest) !== canonical(change.before)) {
1579
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1580
+ }
1581
+ guard();
1582
+ const targetPath = join(this.root, path);
1583
+ await rename(temporary, targetPath);
1584
+ const directory = await open(parent, constants.O_RDONLY | constants.O_NOFOLLOW);
1585
+ try {
1586
+ await directory.sync();
1587
+ }
1588
+ finally {
1589
+ await directory.close();
1590
+ }
1591
+ const prevOverlayBytes = this.#overlayByteLength(path);
1592
+ if (this.#isOverlay) {
1593
+ this.#deleted.delete(path);
1594
+ const revertsToBaseline = baseEntry !== undefined && gitBlobOid(this.#objectFormat, writeBytes) === baseEntry.oid;
1595
+ if (revertsToBaseline) {
1596
+ this.#total -= prevOverlayBytes;
1597
+ this.#files.delete(path);
1598
+ const info = await lstat(targetPath, { bigint: true });
1599
+ this.#baselineStats.set(path, fingerprintFromStat(info));
1600
+ this.#verifiedBaseline.add(path);
1601
+ }
1602
+ else {
1603
+ this.#total += writeBytes.length - prevOverlayBytes;
1604
+ this.#files.set(path, change.after);
1605
+ this.#baselineStats.delete(path);
1606
+ this.#verifiedBaseline.delete(path);
1607
+ }
1608
+ }
1609
+ else {
1610
+ this.#total += writeBytes.length - prevOverlayBytes;
1611
+ this.#files.set(path, change.after);
1612
+ }
1613
+ return change.after;
1614
+ }
1615
+ finally {
1616
+ await unlink(temporary).catch(error => { if (!absent(error))
1617
+ throw error; });
1618
+ }
1619
+ });
1620
+ }
1621
+ async #syncDeepestSurvivingDirectory(filePath) {
1622
+ const segments = filePath.split('/').slice(0, -1);
1623
+ for (let i = segments.length; i >= 0; i--) {
1624
+ const dirPath = i === 0 ? this.root : join(this.root, ...segments.slice(0, i));
1625
+ try {
1626
+ const dir = await open(dirPath, constants.O_RDONLY | constants.O_NOFOLLOW);
1627
+ try {
1628
+ await dir.sync();
1629
+ }
1630
+ finally {
1631
+ await dir.close();
1632
+ }
1633
+ return;
1634
+ }
1635
+ catch (error) {
1636
+ if (absent(error) && i > 0)
1637
+ continue;
1638
+ throw error;
1639
+ }
1640
+ }
1641
+ }
1642
+ async manifest() {
1643
+ return await this.withCapturePassCache(async () => {
1644
+ let seenOverlay = 0;
1645
+ let seenBaseline = 0;
1646
+ const visit = async (parent, prefix) => {
1647
+ await this.#directory(parent);
1648
+ const entries = await fsPromises.readdir(parent);
1649
+ if (entries.length > this.#dirEntryLimit(false))
1650
+ refuse('OUTPUT_LIMIT', '/candidate');
1651
+ if (this.#captureDirCache !== null) {
1652
+ this.#captureDirCache.set(resolve(parent), this.#buildCaptureDirMap(entries));
1653
+ }
1654
+ for (const entry of entries) {
1655
+ const name = prefix ? prefix + '/' + entry : entry;
1656
+ const fullPath = join(parent, entry);
1657
+ const info = await lstat(fullPath, { bigint: true });
1658
+ this.normalize(name);
1659
+ if (info.isSymbolicLink())
1660
+ refuse('RECOVERY_REQUIRED', '/candidate');
1661
+ if (info.isDirectory()) {
1662
+ await visit(fullPath, name);
1663
+ continue;
1664
+ }
1665
+ if (this.#files.has(name)) {
1666
+ await this.#verifyCurrentRef(name);
1667
+ seenOverlay++;
1668
+ continue;
1669
+ }
1670
+ if (this.#isOverlay && !this.#deleted.has(name)) {
1671
+ const baseEntry = this.#baseline.get(name);
1672
+ if (baseEntry) {
1673
+ await this.#verifyAndHealBaselineFile(name, fullPath, baseEntry, info, 'admission', 'verify_only', true);
1674
+ seenBaseline++;
1675
+ continue;
1676
+ }
1677
+ }
1678
+ refuse('RECOVERY_REQUIRED', '/candidate');
1679
+ }
1680
+ };
1681
+ await visit(this.root, '');
1682
+ let expectedBaseline = 0;
1683
+ if (this.#isOverlay) {
1684
+ for (const name of this.#baseline.keys()) {
1685
+ if (!this.#files.has(name) && !this.#deleted.has(name))
1686
+ expectedBaseline++;
1687
+ }
1688
+ }
1689
+ if (seenOverlay !== this.#files.size || seenBaseline !== expectedBaseline) {
1690
+ refuse('RECOVERY_REQUIRED', '/candidate');
1691
+ }
1692
+ if (this.#isOverlay) {
1693
+ const manifest = this.#buildOverlayManifest(this.#files, this.#deleted);
1694
+ if (manifest.spec.entries.length > this.#effectiveOverlayMaxEntries()
1695
+ || (manifest.spec.deleted?.length ?? 0) > this.#overlayLimits.maxFiles
1696
+ || this.#total > this.#overlayLimits.maxBytes
1697
+ || Buffer.byteLength(canonical(manifest)) > this.#overlayLimits.manifestMaxBytes) {
1698
+ refuse('OUTPUT_LIMIT', '/candidate');
1699
+ }
1700
+ const identified = identifyManifest(manifest, {
1701
+ overlay: { maxFiles: this.#overlayLimits.maxFiles, maxBytes: this.#overlayLimits.maxBytes },
1702
+ });
1703
+ if (!identified.ok) {
1704
+ refuse('OUTPUT_LIMIT', '/candidate');
1705
+ }
1706
+ return freeze(manifest);
1707
+ }
1708
+ const entries = [...this.#files.values()].sort((a, b) => compareUtf16(a.name, b.name));
1709
+ return freeze({ apiVersion: 'loopwright.dev/v1alpha1', kind: 'ArtifactManifest', metadata: { id: 'candidate' }, spec: { entries } });
1710
+ });
1711
+ }
1712
+ }