@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,1776 @@
1
+ import { constants } from 'node:fs';
2
+ import { chmod, lstat, mkdir, open, readdir, realpath, rename, rm, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, join, relative, resolve } from 'node:path';
4
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
5
+ import { LIMITS, bindSubject, digestArtifact, digestArtifactFromMetadata, identifyManifest, isWritablePath } from '@loopwright/core';
6
+ import { reopenLocalRun } from '@loopwright/state';
7
+ import { approvedState } from './config.js';
8
+ import { compilePlan } from './compile.js';
9
+ import { ControllerFailure, refuse, result, safeDiagnostic } from './errors.js';
10
+ import { copyVerifiedFileReadOnly, inside, readBoundedFile, STREAM_CHUNK_BYTES } from './files.js';
11
+ import { parsePrivateJson } from './parser.js';
12
+ import { canonical, freeze, hash, id, integer, isRecord, list, record, same, text } from './schema.js';
13
+ import { ArtifactStore, privateDirectory, resolveCanonicalCasBlobPath, stateValue } from './storage.js';
14
+ import { ControllerOwner } from './ownership.js';
15
+ import { admitRetainedRun, CONSERVATIVE_LEGACY_HOST_POLICY, effectiveRunHostPolicy, hostProtectionFromPolicy, parsePersistedHostPolicy, validatePortPolicyFields, validatePortsAgainstHostPolicy, } from './retained.js';
16
+ import { reconcileInterruptedOperations, restoredCandidate, retainedPrimary } from './recovery.js';
17
+ import { ProgressStore, journal, stableId } from './progress.js';
18
+ import { adoptDelegatedCapture, captureDelegatedRole, nativeSessionId, } from './capture.js';
19
+ import { assertCanonicalMinimalOverlay, attachVerifiedCasSeal, canonicalizeCandidateManifest, compareUtf16, isHostProtectedPath, matchesScopePattern, materializeBaseline, overlayManifestBounds, restoreSource, } from './source.js';
20
+ import { isVerdictStep, normalizeSubmission, validateStepVerdictObject } from './submission.js';
21
+ import { evaluateControllerAcceptance, verifyControllerVerifierCasDescriptors, } from './acceptance.js';
22
+ import { descendants, nextNode } from './scheduler.js';
23
+ import { formatPolicy, reworkPrompt } from './repair.js';
24
+ import { countDelegatedBudgets, observeParentExhaustion, storeFactsCertain, refuseFromRoleOutcome } from './budget-observations.js';
25
+ import { validateGateUrlOverrides } from './gate.js';
26
+ import { appendHandoffPromptBlock, materializeContextFilesDir } from './handoff.js';
27
+ import { createCycle, Cycle, normalizeWatchedPaths, roleResourcesFor } from './controller.js';
28
+ import { incident } from './finalize.js';
29
+ import { CONTROLLER_LIMITS, } from './types.js';
30
+ function isWritableCandidateFile(name, scope, hostProtection) {
31
+ if (isHostProtectedPath(name, hostProtection))
32
+ return false;
33
+ if (scope.protected.some(pattern => matchesScopePattern(pattern, name)))
34
+ return false;
35
+ return scope.writable.some(pattern => matchesScopePattern(pattern, name));
36
+ }
37
+ async function writeAtomicPrivateJson(targetPath, value, vault) {
38
+ const bytes = Buffer.from(canonical(value));
39
+ if (bytes.byteLength > 2_097_152)
40
+ refuse('OUTPUT_LIMIT', '', 'execution');
41
+ vault.assertClean(bytes);
42
+ const tempPath = targetPath + '.' + randomBytes(6).toString('hex') + '.tmp';
43
+ const file = await open(tempPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
44
+ try {
45
+ await file.writeFile(bytes);
46
+ await file.sync();
47
+ }
48
+ finally {
49
+ await file.close();
50
+ }
51
+ await rename(tempPath, targetPath);
52
+ const parent = await open(dirname(targetPath), constants.O_RDONLY | constants.O_NOFOLLOW);
53
+ try {
54
+ await parent.sync();
55
+ }
56
+ finally {
57
+ await parent.close();
58
+ }
59
+ }
60
+ function normalizeRoleMcpServers(raw, phase) {
61
+ if (raw === undefined)
62
+ return undefined;
63
+ if (!isRecord(raw))
64
+ refuse('CONFIG_SCHEMA', '/roleMcpServers', phase);
65
+ const keys = Object.keys(raw);
66
+ if (keys.length > 16)
67
+ refuse('CONFIG_LIMIT', '/roleMcpServers', phase);
68
+ const out = {};
69
+ for (const key of keys) {
70
+ id(key, '/roleMcpServers');
71
+ const servers = list(raw[key], '/roleMcpServers/' + key, 32).map(s => id(s, '/roleMcpServers/' + key));
72
+ out[key] = freeze([...new Set(servers)]);
73
+ }
74
+ return freeze(out);
75
+ }
76
+ function normalizeMcpServersMetadata(raw, phase) {
77
+ if (raw === undefined)
78
+ return undefined;
79
+ const items = list(raw, '/mcpServers', 32).map((item, idx) => {
80
+ const fields = record(item, ['id', 'transport', 'toolNames'], `/mcpServers/${idx}`);
81
+ const srvId = id(fields.id, `/mcpServers/${idx}/id`);
82
+ const transportRaw = text(fields.transport, `/mcpServers/${idx}/transport`, 16);
83
+ if (transportRaw !== 'stdio' && transportRaw !== 'http')
84
+ refuse('CONFIG_SCHEMA', `/mcpServers/${idx}/transport`, phase);
85
+ const transport = transportRaw;
86
+ const toolNames = list(fields.toolNames, `/mcpServers/${idx}/toolNames`, 128).map(t => text(t, `/mcpServers/${idx}/toolNames`, 128));
87
+ return freeze({ id: srvId, transport, toolNames: freeze(toolNames) });
88
+ });
89
+ return freeze(items);
90
+ }
91
+ async function readStepMeta(directory, expectedHostPolicy = CONSERVATIVE_LEGACY_HOST_POLICY) {
92
+ const path = join(directory, 'step-meta.json');
93
+ try {
94
+ await lstat(path);
95
+ }
96
+ catch (error) {
97
+ if (error.code === 'ENOENT') {
98
+ const hostPolicy = expectedHostPolicy;
99
+ return freeze({
100
+ version: 1,
101
+ mode: 'candidate',
102
+ hostPolicy,
103
+ ...(hostPolicy.allowWorkflowWrites ? { allowWorkflowWrites: true } : {}),
104
+ });
105
+ }
106
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
107
+ }
108
+ let bytes;
109
+ let parsed;
110
+ try {
111
+ bytes = await readBoundedFile(path, 65_536, true);
112
+ parsed = parsePrivateJson(bytes, 65_536);
113
+ }
114
+ catch {
115
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
116
+ }
117
+ if (!isRecord(parsed))
118
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
119
+ const hasHostPolicy = Object.hasOwn(parsed, 'hostPolicy') && parsed.hostPolicy !== undefined;
120
+ const hasPolicyProfile = Object.hasOwn(parsed, 'policyProfile') && parsed.policyProfile !== undefined;
121
+ const allowedKeys = [
122
+ 'version',
123
+ 'mode',
124
+ ...(hasHostPolicy ? ['hostPolicy'] : []),
125
+ ...(hasPolicyProfile ? ['policyProfile'] : []),
126
+ ...(Object.hasOwn(parsed, 'allowWorkflowWrites') ? ['allowWorkflowWrites'] : []),
127
+ ...(Object.hasOwn(parsed, 'roleMcpServers') ? ['roleMcpServers'] : []),
128
+ ...(Object.hasOwn(parsed, 'mcpServers') ? ['mcpServers'] : []),
129
+ ...(Object.hasOwn(parsed, 'watchedPaths') ? ['watchedPaths'] : []),
130
+ ];
131
+ const raw = record(parsed, allowedKeys);
132
+ if (raw.version !== 1 || (raw.mode !== 'candidate' && raw.mode !== 'no-change'))
133
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
134
+ if (raw.allowWorkflowWrites !== undefined && typeof raw.allowWorkflowWrites !== 'boolean')
135
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
136
+ if (hasPolicyProfile && raw.policyProfile !== 'local' && raw.policyProfile !== 'github') {
137
+ refuse('RECOVERY_REQUIRED', '/policyProfile', 'recovery');
138
+ }
139
+ let hostPolicy;
140
+ if (hasHostPolicy) {
141
+ hostPolicy = parsePersistedHostPolicy(raw.hostPolicy, '/hostPolicy', 'recovery');
142
+ if (hasPolicyProfile && raw.policyProfile !== hostPolicy.policyProfile) {
143
+ refuse('RECOVERY_REQUIRED', '/policyProfile', 'recovery');
144
+ }
145
+ if (raw.allowWorkflowWrites !== undefined && raw.allowWorkflowWrites !== hostPolicy.allowWorkflowWrites) {
146
+ refuse('RECOVERY_REQUIRED', '/allowWorkflowWrites', 'recovery');
147
+ }
148
+ }
149
+ else if (hasPolicyProfile) {
150
+ hostPolicy = freeze({
151
+ policyProfile: raw.policyProfile,
152
+ allowWorkflowWrites: raw.allowWorkflowWrites === true,
153
+ });
154
+ }
155
+ else {
156
+ if (raw.allowWorkflowWrites === true) {
157
+ refuse('RECOVERY_REQUIRED', '/allowWorkflowWrites', 'recovery');
158
+ }
159
+ // Legacy step-meta.json omitting hostPolicy/policyProfile defaults conservatively to 'github' with allowWorkflowWrites: false.
160
+ hostPolicy = CONSERVATIVE_LEGACY_HOST_POLICY;
161
+ }
162
+ if (!same(expectedHostPolicy, hostPolicy)) {
163
+ refuse('RECOVERY_REQUIRED', '/hostPolicy', 'recovery');
164
+ }
165
+ const roleMcpServers = normalizeRoleMcpServers(raw.roleMcpServers, 'recovery');
166
+ const mcpServers = normalizeMcpServersMetadata(raw.mcpServers, 'recovery');
167
+ const watchedPaths = normalizeWatchedPaths(raw.watchedPaths, 'recovery');
168
+ return freeze({
169
+ version: 1,
170
+ mode: raw.mode,
171
+ hostPolicy,
172
+ ...(hostPolicy.allowWorkflowWrites ? { allowWorkflowWrites: true } : {}),
173
+ ...(roleMcpServers !== undefined ? { roleMcpServers } : {}),
174
+ ...(mcpServers !== undefined ? { mcpServers } : {}),
175
+ ...(watchedPaths !== undefined ? { watchedPaths } : {}),
176
+ });
177
+ }
178
+ async function readStepLease(directory) {
179
+ const path = join(directory, 'step-lease.json');
180
+ try {
181
+ await lstat(path);
182
+ }
183
+ catch (error) {
184
+ if (error.code === 'ENOENT')
185
+ return null;
186
+ refuse('RECOVERY_REQUIRED', '', 'execution');
187
+ }
188
+ const bytes = await readBoundedFile(path, 2_097_152, true);
189
+ const raw = record(parsePrivateJson(bytes, 2_097_152), ['version', 'runId', 'attemptId', 'ordinal', 'leaseDigest', 'prompt', 'contextFiles']);
190
+ if (raw.version !== 1 || !/^[0-9a-f]{64}$/.test(text(raw.leaseDigest)))
191
+ refuse('RECOVERY_REQUIRED', '', 'execution');
192
+ return {
193
+ version: 1,
194
+ runId: id(raw.runId),
195
+ attemptId: id(raw.attemptId),
196
+ ordinal: integer(raw.ordinal, 1, 256),
197
+ leaseDigest: text(raw.leaseDigest),
198
+ prompt: text(raw.prompt, '', 1_048_576),
199
+ contextFiles: list(raw.contextFiles, '', 64).map(item => text(item, '', 4096)),
200
+ };
201
+ }
202
+ function verifyLeaseToken(lease, runId, attemptId, ordinal, leaseToken) {
203
+ if (!lease || lease.runId !== runId || lease.attemptId !== attemptId || lease.ordinal !== ordinal || typeof leaseToken !== 'string' || !/^[0-9a-f]{64}$/.test(leaseToken)) {
204
+ refuse('AUTHORITY_REFUSED', '/leaseToken', 'execution');
205
+ }
206
+ const expected = Buffer.from(lease.leaseDigest, 'hex');
207
+ const observed = Buffer.from(hash(leaseToken).hex, 'hex');
208
+ if (expected.byteLength !== observed.byteLength || !timingSafeEqual(expected, observed)) {
209
+ refuse('AUTHORITY_REFUSED', '/leaseToken', 'execution');
210
+ }
211
+ }
212
+ async function cleanupRunWorkspaces(runRoot, runId, directory, artifacts) {
213
+ await unlink(join(directory, 'step-lease.json')).catch(() => { });
214
+ await rm(join(resolve(runRoot), 'workspaces', runId), { recursive: true, force: true }).catch(() => { });
215
+ if (artifacts) {
216
+ await artifacts.cleanCasTempFiles().catch(() => { });
217
+ }
218
+ }
219
+ async function resolveCurrentFileModes(context, head, candidateFiles) {
220
+ const modes = new Map();
221
+ if (context.source.version === 2) {
222
+ for (const entry of context.source.baselineEntries ?? [])
223
+ modes.set(entry.name, entry.mode);
224
+ }
225
+ else {
226
+ const rawSource = parsePrivateJson(await context.artifacts.read(context.descriptor.source, 262_144), 262_144);
227
+ for (const rawEntry of list(rawSource.entries, '', 256)) {
228
+ const entry = record(rawEntry, ['name', 'mode', 'oid', 'ref', 'artifact']);
229
+ const mode = text(entry.mode);
230
+ if (mode === '100644' || mode === '100755')
231
+ modes.set(text(entry.name), mode);
232
+ }
233
+ }
234
+ if (head && !same(head.progress.candidate.workspace, context.source.workspace)) {
235
+ let isDelegatedWorkspace = false;
236
+ const bounds = overlayManifestBounds(context.plan.budgets.overlay);
237
+ const maxWsBytes = Math.max(bounds.v2WorkspaceJsonMaxBytes, bounds.workspaceMaxBytes);
238
+ const wsBytes = await context.artifacts.read(head.progress.candidate.workspace, maxWsBytes);
239
+ try {
240
+ const parsed = parsePrivateJson(Buffer.from(wsBytes), maxWsBytes, bounds.collectionLimit);
241
+ if (isRecord(parsed) && (parsed.format === 'delegated-capture.v1' || parsed.format === 'delegated-capture.v2') && Array.isArray(parsed.overlay)) {
242
+ isDelegatedWorkspace = true;
243
+ for (const item of parsed.overlay) {
244
+ if (isRecord(item) && typeof item.name === 'string' && (item.mode === '100644' || item.mode === '100755')) {
245
+ modes.set(item.name, item.mode);
246
+ }
247
+ }
248
+ }
249
+ }
250
+ catch (error) {
251
+ if (!(error instanceof ControllerFailure && (error.diagnostic.code === 'CONFIG_SYNTAX' || error.diagnostic.code === 'ARTIFACT_INVALID'))) {
252
+ throw error;
253
+ }
254
+ // Non-JSON workspace (e.g., native Pi capture; parsePrivateJson wraps non-JSON syntax errors as ARTIFACT_INVALID).
255
+ }
256
+ if (!isDelegatedWorkspace && context.source.version === 1) {
257
+ // Native Pi classic (v1) materializes every file as 0o444 (100644) and capture records explicit 100644.
258
+ for (const entry of head.manifest.spec.entries) {
259
+ modes.set(entry.name, '100644');
260
+ }
261
+ }
262
+ }
263
+ if (candidateFiles) {
264
+ for (const file of candidateFiles) {
265
+ if (file.mode === '100644' || file.mode === '100755') {
266
+ modes.set(file.name, file.mode);
267
+ }
268
+ }
269
+ }
270
+ return modes;
271
+ }
272
+ async function materializeAttemptWorkspace(cycle, runRoot, attemptId, role, repair, hostProtection, activeResources, handoffExtracts = [], phase = 'execution') {
273
+ const { context } = cycle;
274
+ const { plan, loaded, source, owner, artifacts } = context;
275
+ const state = approvedState(loaded);
276
+ const excluded = [context.descriptor.repository, ...state.input.untrustedRoots];
277
+ const workspacesRoot = join(resolve(runRoot), 'workspaces');
278
+ const runWorkspaceDir = join(workspacesRoot, context.lock.spec.runId);
279
+ const attemptWorkspaceDir = join(runWorkspaceDir, attemptId);
280
+ const stagingWorkspaceDir = join(runWorkspaceDir, `.stage-${attemptId}`);
281
+ const stagingCandidateDir = join(stagingWorkspaceDir, 'candidate');
282
+ const stagingContextDir = join(stagingWorkspaceDir, 'context');
283
+ const candidateDir = join(attemptWorkspaceDir, 'candidate');
284
+ const contextDir = join(attemptWorkspaceDir, 'context');
285
+ await privateDirectory(workspacesRoot, excluded);
286
+ await privateDirectory(runWorkspaceDir, excluded);
287
+ await rm(stagingWorkspaceDir, { recursive: true, force: true });
288
+ await privateDirectory(stagingWorkspaceDir, excluded);
289
+ await privateDirectory(stagingCandidateDir, excluded);
290
+ await privateDirectory(stagingContextDir, excluded);
291
+ try {
292
+ const effectiveTools = repair === 'format' ? [] : role.policy.tools;
293
+ const readOnlyRole = repair === 'format' || !effectiveTools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash');
294
+ const modes = await resolveCurrentFileModes(context, cycle.head, cycle.candidate.files);
295
+ if (source.version === 2) {
296
+ await materializeBaseline(source, stagingCandidateDir, owner, cycle.deadline);
297
+ await chmod(stagingCandidateDir, 0o700);
298
+ const deletedSet = new Set(cycle.candidate.manifest.spec.deleted ?? []);
299
+ for (const delPath of deletedSet) {
300
+ await rm(join(stagingCandidateDir, delPath), { force: true });
301
+ }
302
+ for (const item of cycle.candidate.files) {
303
+ const targetPath = join(stagingCandidateDir, item.name);
304
+ await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 });
305
+ await rm(targetPath, { recursive: true, force: true });
306
+ if ('bytes' in item) {
307
+ const file = await open(targetPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
308
+ try {
309
+ await file.writeFile(item.bytes);
310
+ await file.sync();
311
+ }
312
+ finally {
313
+ await file.close();
314
+ }
315
+ }
316
+ else {
317
+ const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution');
318
+ await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, {
319
+ expectedBytes: item.byteLength,
320
+ expectedSha256: item.digest.hex,
321
+ mode: 0o600,
322
+ ownedSource: true,
323
+ requireReadOnlySource: true,
324
+ verifyCanonicalSource: true,
325
+ path: item.name,
326
+ phase: 'execution',
327
+ });
328
+ }
329
+ }
330
+ const allPaths = new Set();
331
+ for (const entry of source.baselineEntries ?? []) {
332
+ if (!deletedSet.has(entry.name))
333
+ allPaths.add(entry.name);
334
+ }
335
+ for (const file of cycle.candidate.files)
336
+ allPaths.add(file.name);
337
+ for (const relPath of allPaths) {
338
+ const gitMode = modes.get(relPath) ?? '100644';
339
+ const writable = !readOnlyRole && isWritableCandidateFile(relPath, plan.scope, hostProtection);
340
+ const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400);
341
+ await chmod(join(stagingCandidateDir, relPath), perm);
342
+ }
343
+ }
344
+ else {
345
+ for (const item of cycle.candidate.files) {
346
+ const targetPath = join(stagingCandidateDir, item.name);
347
+ await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 });
348
+ const gitMode = modes.get(item.name) ?? '100644';
349
+ const writable = !readOnlyRole && isWritableCandidateFile(item.name, plan.scope, hostProtection);
350
+ const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400);
351
+ if ('bytes' in item) {
352
+ const file = await open(targetPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, perm);
353
+ try {
354
+ await file.writeFile(item.bytes);
355
+ await file.chmod(perm);
356
+ await file.sync();
357
+ }
358
+ finally {
359
+ await file.close();
360
+ }
361
+ }
362
+ else {
363
+ const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution');
364
+ await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, {
365
+ expectedBytes: item.byteLength,
366
+ expectedSha256: item.digest.hex,
367
+ mode: perm,
368
+ ownedSource: true,
369
+ requireReadOnlySource: true,
370
+ verifyCanonicalSource: true,
371
+ path: item.name,
372
+ phase: 'execution',
373
+ });
374
+ }
375
+ }
376
+ }
377
+ const effectiveResources = activeResources ?? roleResourcesFor(loaded, plan, role.roleId);
378
+ const stagedContextFiles = await materializeContextFilesDir(stagingContextDir, effectiveResources, handoffExtracts, artifacts.directory, phase);
379
+ const backupWorkspaceDir = join(runWorkspaceDir, `.prev-${attemptId}`);
380
+ await rm(backupWorkspaceDir, { recursive: true, force: true });
381
+ let movedPriorAside = false;
382
+ if (await lstat(attemptWorkspaceDir).then(() => true, () => false)) {
383
+ await rename(attemptWorkspaceDir, backupWorkspaceDir);
384
+ movedPriorAside = true;
385
+ }
386
+ try {
387
+ await rename(stagingWorkspaceDir, attemptWorkspaceDir);
388
+ }
389
+ catch (renameError) {
390
+ if (movedPriorAside) {
391
+ await rename(backupWorkspaceDir, attemptWorkspaceDir).catch(() => undefined);
392
+ }
393
+ throw renameError;
394
+ }
395
+ if (movedPriorAside) {
396
+ await rm(backupWorkspaceDir, { recursive: true, force: true }).catch(() => undefined);
397
+ }
398
+ const contextFiles = stagedContextFiles.map(filePath => join(contextDir, relative(stagingContextDir, filePath)));
399
+ return { candidateDir, contextFiles };
400
+ }
401
+ catch (error) {
402
+ await rm(stagingWorkspaceDir, { recursive: true, force: true }).catch(() => undefined);
403
+ throw error;
404
+ }
405
+ }
406
+ async function buildStepYield(cycle, runRoot, attempt, role, prompt, contextFiles, leaseToken, meta) {
407
+ const { plan, lock, ports } = cycle.context;
408
+ const effectiveTools = attempt.repair === 'format' ? [] : role.policy.tools;
409
+ const roleMcpMap = meta.roleMcpServers ?? ports.roleMcpServers;
410
+ const declaredServers = meta.mcpServers ?? ports.mcpServers ?? [];
411
+ const allowedMcpServers = attempt.repair === 'format'
412
+ ? []
413
+ : roleMcpMap !== undefined
414
+ ? [...(roleMcpMap[role.roleId] ?? [])]
415
+ : role.policy.mcp.names.length > 0
416
+ ? [role.policy.mcp.serverId]
417
+ : [];
418
+ const mcpServers = attempt.repair === 'format' ? [] : declaredServers.filter(srv => allowedMcpServers.includes(srv.id));
419
+ const allowWorkflowWrites = meta.hostPolicy.allowWorkflowWrites;
420
+ const reworkEpoch = attempt.reworkEpoch ?? cycle.reworkEpoch;
421
+ const rework = attempt.repair === 'none' ? await cycle.activeReworkForNode(attempt.nodeId) : null;
422
+ const selection = {
423
+ provider: role.policy.selection.provider,
424
+ model: role.policy.selection.model,
425
+ thinking: role.policy.selection.thinking,
426
+ };
427
+ const candidateDir = join(resolve(runRoot), 'workspaces', lock.spec.runId, attempt.id, 'candidate');
428
+ return freeze({
429
+ kind: 'step',
430
+ status: 'awaiting_role',
431
+ runId: lock.spec.runId,
432
+ attemptId: attempt.id,
433
+ stepId: attempt.nodeId,
434
+ roleId: role.roleId,
435
+ purpose: attempt.purpose === 'reviewer' ? 'reviewer' : 'task',
436
+ repair: attempt.repair,
437
+ selection,
438
+ allowedTools: [...effectiveTools],
439
+ allowedMcpServers,
440
+ mcpServers,
441
+ scope: plan.scope,
442
+ allowWorkflowWrites,
443
+ candidateDir,
444
+ contextFiles: [...contextFiles],
445
+ prompt,
446
+ reworkEpoch,
447
+ rework,
448
+ submissionMode: plan.controls.submission.mode,
449
+ submissionPath: plan.controls.submission.path,
450
+ leaseToken,
451
+ });
452
+ }
453
+ async function yieldDelegatedRole(cycle, runRoot, nodeId, meta, repair = 'none', customPrompt) {
454
+ await cycle.guard();
455
+ const { plan, lock, store, artifacts, loaded, directory } = cycle.context;
456
+ const delegated = countDelegatedBudgets(plan, cycle.draft.attempts);
457
+ observeParentExhaustion(cycle.deadline.assert(), lock, delegated.modelCalls);
458
+ const node = plan.orderedDAG.find(item => item.id === nodeId);
459
+ if (!node || node.kind !== 'agent')
460
+ refuse('CAPABILITY_UNSUPPORTED', '', 'execution');
461
+ if (cycle.draft.attempts.length >= plan.capacity.A)
462
+ refuse('ATTEMPT_LIMIT', '', 'execution');
463
+ const originalRole = plan.roles.find(item => item.roleId === node.roleId);
464
+ const role = repair === 'format' ? { ...originalRole, policy: formatPolicy(originalRole.policy) } : originalRole;
465
+ const purpose = node.handler.implementation === 'pi.compact.v1' ? 'compaction' : node.handler.parameters.purpose === 'review' ? 'reviewer' : 'task';
466
+ if (purpose === 'compaction')
467
+ refuse('CAPABILITY_UNSUPPORTED', '', 'execution');
468
+ const nativeStepId = nodeId;
469
+ const ordinal = cycle.draft.attempts.length + 1;
470
+ const attemptEpoch = cycle.reworkEpoch;
471
+ const commandId = stableId(lock.spec.runId, nodeId, purpose, repair, ordinal);
472
+ const sessionId = nativeSessionId(lock.spec.runId, role.roleId, nativeStepId, role.policy, attemptEpoch);
473
+ const configured = text(loaded.registry.spec.handlers.find(handler => handler.id === node.handler.id)?.parameters.prompt);
474
+ // Verify base handler prompt digest FIRST before evaluating or appending any runtime handoff block.
475
+ if (node.handler.parameters.prompt !== '[private command sha256:' + hash(configured).hex + ']')
476
+ refuse('RECOVERY_REQUIRED', '', 'execution');
477
+ const preparedCtx = await cycle.prepareAttemptContext(nodeId, role, repair, purpose, attemptEpoch, meta.watchedPaths ?? cycle.context.ports.watchedPaths);
478
+ await cycle.adviseCapabilityRouting(nodeId, role, purpose, preparedCtx.activeResources);
479
+ const maxPromptBytes = Math.min(LIMITS.inputBytes, role.policy.limits.promptBytes);
480
+ const reworkCtx = repair === 'none' && customPrompt === undefined ? await cycle.activeReworkForNode(nodeId) : null;
481
+ const defaultPrompt = reworkCtx ? reworkPrompt(configured, reworkCtx, Math.min(CONTROLLER_LIMITS.reworkPromptMaxBytes, role.policy.limits.promptBytes)) : configured;
482
+ const basePrompt = customPrompt ?? defaultPrompt;
483
+ const promptText = repair !== 'format' && preparedCtx.resolvedHandoffs.length > 0
484
+ ? appendHandoffPromptBlock(basePrompt, preparedCtx.resolvedHandoffs, maxPromptBytes, 'execution')
485
+ : basePrompt;
486
+ const command = await artifacts.put('command', Buffer.from(promptText), maxPromptBytes);
487
+ const originalSubmission = cycle.draft.failures.at(-1)?.evidence ?? cycle.draft.submission;
488
+ const before = journal(store).view.counts;
489
+ const oldDigest = cycle.draft.candidate.digest;
490
+ observeParentExhaustion(cycle.deadline.assert(), lock, delegated.modelCalls);
491
+ const attempt = {
492
+ ordinal,
493
+ id: commandId,
494
+ nodeId,
495
+ nativeStepId,
496
+ sessionId,
497
+ purpose,
498
+ repair,
499
+ command,
500
+ before: { requests: before.requests, operations: before.operations },
501
+ finished: null,
502
+ ...(attemptEpoch > 0 ? { reworkEpoch: attemptEpoch } : {}),
503
+ activatedResourceIds: preparedCtx.activatedResourceIds,
504
+ ...(preparedCtx.handoffExtracts !== undefined ? { handoffExtracts: preparedCtx.handoffExtracts } : {}),
505
+ };
506
+ if (repair === 'format') {
507
+ await artifacts.json('format-intent', {
508
+ version: 1,
509
+ attemptId: commandId,
510
+ original: originalSubmission,
511
+ schema: isVerdictStep(node) ? 'step-verdict.v1' : 'submission.v1',
512
+ candidate: oldDigest,
513
+ output: 'new_assistant_representation',
514
+ }, 65_536);
515
+ }
516
+ await cycle.events.push(repair === 'none' ? 'role' : 'repair', null, nodeId, commandId);
517
+ await cycle.publish({
518
+ ...cycle.draft,
519
+ stage: { ...cycle.draft.stage, kind: 'role_pre' },
520
+ attempts: [...cycle.draft.attempts, attempt],
521
+ nodes: cycle.draft.nodes.map(item => (item.id === nodeId ? { ...item, state: 'running' } : item)),
522
+ }, 'role.' + ordinal + '.pre');
523
+ const hostProtection = hostProtectionFromPolicy(meta.hostPolicy);
524
+ const { contextFiles } = await materializeAttemptWorkspace(cycle, runRoot, commandId, role, repair, hostProtection, preparedCtx.activeResources, preparedCtx.handoffExtracts ?? [], 'execution');
525
+ const leaseToken = randomBytes(32).toString('hex');
526
+ await writeAtomicPrivateJson(join(directory, 'step-lease.json'), {
527
+ version: 1,
528
+ runId: lock.spec.runId,
529
+ attemptId: commandId,
530
+ ordinal,
531
+ leaseDigest: hash(leaseToken).hex,
532
+ prompt: promptText,
533
+ contextFiles,
534
+ }, artifacts.vault);
535
+ return await buildStepYield(cycle, runRoot, attempt, role, promptText, contextFiles, leaseToken, meta);
536
+ }
537
+ async function advanceStepCycle(cycle, runRoot, meta, options) {
538
+ const { plan } = cycle.context;
539
+ const isDelegatedNode = (nodeId) => {
540
+ const dagNode = plan.orderedDAG.find(item => item.id === nodeId);
541
+ const role = dagNode?.roleId ? plan.roles.find(item => item.roleId === dagNode.roleId) : undefined;
542
+ return role?.adapter === 'delegated' ? role : null;
543
+ };
544
+ if (!cycle.head) {
545
+ await cycle.bootstrap();
546
+ }
547
+ else if (!options?.postStructureFailure) {
548
+ const active = cycle.head.progress.attempts.at(-1);
549
+ if (active && active.finished === null) {
550
+ const delegatedRole = isDelegatedNode(active.nodeId);
551
+ if (delegatedRole) {
552
+ if (cycle.resumeAdoption === true) {
553
+ const effectiveRole = active.repair === 'format' ? { ...delegatedRole, policy: formatPolicy(delegatedRole.policy) } : delegatedRole;
554
+ const disallowMutations = active.repair === 'format' ||
555
+ !effectiveRole.policy.tools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash');
556
+ const captured = await adoptDelegatedCapture(cycle.context.store, cycle.context.artifacts, cycle.context.lock, effectiveRole, active, cycle.context.source, hostProtectionFromPolicy(meta.hostPolicy));
557
+ if (disallowMutations) {
558
+ const priorModes = await resolveCurrentFileModes(cycle.context, cycle.head, cycle.candidate.files);
559
+ for (const entry of captured.artifacts) {
560
+ if (entry.mode !== undefined && entry.mode !== (priorModes.get(entry.name) ?? '100644')) {
561
+ refuse('ARTIFACT_INVALID', '', 'recovery');
562
+ }
563
+ }
564
+ }
565
+ const failure = await cycle.completeCapture(active, captured, { ignoreArtifactPath: disallowMutations });
566
+ if (failure === 'SUBMISSION_AMBIGUOUS')
567
+ refuse(failure, '', 'verification');
568
+ if (failure === 'SUBMISSION_INVALID') {
569
+ const prompt = await cycle.formatRepairPrompt(active.nodeId);
570
+ return { kind: 'yield', step: await yieldDelegatedRole(cycle, runRoot, active.nodeId, meta, 'format', prompt) };
571
+ }
572
+ }
573
+ else {
574
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
575
+ }
576
+ }
577
+ else {
578
+ await cycle.resumeAttempt(cycle.resumeAdoption === true);
579
+ }
580
+ }
581
+ const retained = [...cycle.head.progress.verifierReceipts, ...cycle.head.progress.verifierRefusals].filter(row => row.generation === cycle.generation);
582
+ for (const row of retained)
583
+ await cycle.runVerifier(row.slot);
584
+ const lastAttempt = cycle.draft.attempts.at(-1);
585
+ if (lastAttempt?.finished?.nativeCheckpointId === null) {
586
+ await refuseFromRoleOutcome(cycle.context.artifacts, lastAttempt.finished.outcome, cycle.draft.candidate.manifest, () => cycle.markCandidateUnknown());
587
+ }
588
+ if (lastAttempt?.finished?.nativeCheckpointId &&
589
+ lastAttempt.purpose !== 'compaction' &&
590
+ !cycle.haltedVerdictStatus() &&
591
+ cycle.draft.nodes.find(node => node.id === lastAttempt.nodeId)?.state === 'failed') {
592
+ const delegatedRole = isDelegatedNode(lastAttempt.nodeId);
593
+ if (delegatedRole) {
594
+ const prompt = await cycle.formatRepairPrompt(lastAttempt.nodeId);
595
+ return { kind: 'yield', step: await yieldDelegatedRole(cycle, runRoot, lastAttempt.nodeId, meta, 'format', prompt) };
596
+ }
597
+ await cycle.repairFormat(lastAttempt.nodeId);
598
+ }
599
+ }
600
+ if (options?.postStructureFailure) {
601
+ const { nodeId, code } = options.postStructureFailure;
602
+ if (code === 'SUBMISSION_AMBIGUOUS')
603
+ refuse(code, '', 'verification');
604
+ if (code === 'SUBMISSION_INVALID') {
605
+ const prompt = await cycle.formatRepairPrompt(nodeId);
606
+ const delegatedRole = isDelegatedNode(nodeId);
607
+ if (delegatedRole) {
608
+ return { kind: 'yield', step: await yieldDelegatedRole(cycle, runRoot, nodeId, meta, 'format', prompt) };
609
+ }
610
+ await cycle.role(nodeId, 'format', prompt);
611
+ }
612
+ }
613
+ for (;;) {
614
+ for (;;) {
615
+ const node = nextNode(plan, cycle.draft.nodes);
616
+ if (!node)
617
+ break;
618
+ if (node.kind === 'agent') {
619
+ const delegatedRole = isDelegatedNode(node.id);
620
+ if (delegatedRole) {
621
+ return { kind: 'yield', step: await yieldDelegatedRole(cycle, runRoot, node.id, meta, 'none') };
622
+ }
623
+ await cycle.role(node.id);
624
+ }
625
+ else {
626
+ const slot = plan.verifierSlots.find(item => item.handler.id === node.handler.id);
627
+ if (!slot)
628
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
629
+ const epochBefore = cycle.reworkEpoch;
630
+ const checked = await cycle.runVerifier(slot.id);
631
+ const state = checked.status === 'passed' ? 'completed' : checked.status;
632
+ const actualState = cycle.draft.nodes.find(item => item.id === node.id).state;
633
+ const validCheckRework = node.onRework !== undefined &&
634
+ checked.status === 'failed' &&
635
+ ((cycle.reworkEpoch === epochBefore + 1 && actualState === 'pending') ||
636
+ (cycle.haltedVerdictStatus() === 'blocked' && actualState === 'blocked'));
637
+ if (actualState !== state && !validCheckRework)
638
+ refuse('RECOVERY_REQUIRED', '', 'execution');
639
+ }
640
+ }
641
+ await cycle.verifyEligible();
642
+ await cycle.ensureSubmissionForAcceptance();
643
+ const checks = cycle.currentChecks();
644
+ const preverified = await verifyControllerVerifierCasDescriptors(plan, checks, {
645
+ signal: cycle.deadline.abort.signal,
646
+ checkAuthority: async () => {
647
+ cycle.deadline.assert(true);
648
+ await cycle.context.owner.assertCurrent();
649
+ },
650
+ });
651
+ const verdictHalt = cycle.haltedVerdictStatus();
652
+ const acceptance = evaluateControllerAcceptance(plan, cycle.context.lock, cycle.candidate.manifest, cycle.candidate.files, cycle.generation, checks, cycle.submission.value, cycle.context.store, verdictHalt, cycle.draft.nodes.every(node => node.state === 'completed'), cycle.currentRefusals(), null, preverified);
653
+ if (verdictHalt === null && acceptance.result.spec.status === 'failed') {
654
+ const repairSpec = await cycle.prepareImplementationRepair();
655
+ if (repairSpec) {
656
+ if (repairSpec.role.adapter === 'delegated') {
657
+ return { kind: 'yield', step: await yieldDelegatedRole(cycle, runRoot, repairSpec.targetNodeId, meta, 'implementation', repairSpec.prompt) };
658
+ }
659
+ await cycle.role(repairSpec.targetNodeId, 'implementation', repairSpec.prompt);
660
+ continue;
661
+ }
662
+ }
663
+ const finalAcceptance = acceptance.result.spec.status === 'completed' ? await cycle.publishBoundary(acceptance) : acceptance;
664
+ return { kind: 'done', primary: finalAcceptance };
665
+ }
666
+ }
667
+ async function runStepTickWithCycle(context, runRoot, meta, restored, options) {
668
+ const cycle = new Cycle(context, restored?.head ?? null, restored?.candidate, restored?.adopt);
669
+ cycle.submission = restored?.submission ?? null;
670
+ if (restored?.advisoryObservations && restored.advisoryObservations.length > 0) {
671
+ cycle.advisoryObservations.push(...restored.advisoryObservations);
672
+ }
673
+ let yielded = null;
674
+ let primary = null;
675
+ try {
676
+ const outcome = await advanceStepCycle(cycle, runRoot, meta, options);
677
+ if (outcome.kind === 'yield') {
678
+ yielded = outcome.step;
679
+ }
680
+ else {
681
+ primary = outcome.primary;
682
+ }
683
+ }
684
+ catch (error) {
685
+ const diagnostic = safeDiagnostic(error, 'execution');
686
+ const facts = context.store.inspect();
687
+ const certain = facts.ok && storeFactsCertain(facts.value);
688
+ if (cycle.candidateKnown &&
689
+ facts.ok &&
690
+ (['DEADLINE', 'CANCELLED', 'BUDGET_EXHAUSTED', 'ATTEMPT_LIMIT', 'REPEAT_FAILURE'].includes(diagnostic.code) ||
691
+ (certain &&
692
+ ['CAPABILITY_UNSUPPORTED', 'MCP_AUTHENTICATION_REQUIRED', 'EVIDENCE_UNAVAILABLE', 'SUBMISSION_AMBIGUOUS', 'SUBMISSION_INVALID'].includes(diagnostic.code)))) {
693
+ const forced = diagnostic.code === 'DEADLINE'
694
+ ? 'expired'
695
+ : diagnostic.code === 'CANCELLED'
696
+ ? 'cancelled'
697
+ : ['SUBMISSION_AMBIGUOUS', 'SUBMISSION_INVALID'].includes(diagnostic.code)
698
+ ? 'failed'
699
+ : ['CAPABILITY_UNSUPPORTED', 'MCP_AUTHENTICATION_REQUIRED', 'EVIDENCE_UNAVAILABLE'].includes(diagnostic.code)
700
+ ? 'blocked'
701
+ : 'exhausted';
702
+ const forcedDiagnostic = ['CAPABILITY_UNSUPPORTED', 'MCP_AUTHENTICATION_REQUIRED', 'EVIDENCE_UNAVAILABLE', 'SUBMISSION_AMBIGUOUS', 'SUBMISSION_INVALID'].includes(diagnostic.code)
703
+ ? diagnostic.code
704
+ : null;
705
+ try {
706
+ const checks = cycle.currentChecks();
707
+ const preverified = await verifyControllerVerifierCasDescriptors(context.plan, checks, {
708
+ ...(diagnostic.code !== 'CANCELLED' && diagnostic.code !== 'DEADLINE' && !context.signal.aborted
709
+ ? { signal: context.signal }
710
+ : {}),
711
+ checkAuthority: () => context.owner.assertCurrent(),
712
+ });
713
+ primary = evaluateControllerAcceptance(context.plan, context.lock, cycle.candidate.manifest, cycle.candidate.files, cycle.generation, checks, cycle.submission?.value ?? null, context.store, forced, cycle.draft.nodes.every(node => node.state === 'completed'), cycle.currentRefusals(), forcedDiagnostic, preverified);
714
+ }
715
+ catch {
716
+ primary = incident(diagnostic, context.lock.spec.runId, context.lock.spec.lockHash, [context.descriptor.plan, context.source.inventory], cycle.candidateKnown ? ['authoritative_result'] : ['current_candidate', 'submission', 'authoritative_result'], 'complete');
717
+ }
718
+ }
719
+ else {
720
+ primary = incident(diagnostic, context.lock.spec.runId, context.lock.spec.lockHash, [context.descriptor.plan, context.source.inventory], cycle.candidateKnown ? ['authoritative_result'] : ['current_candidate', 'submission', 'authoritative_result'], 'complete');
721
+ }
722
+ }
723
+ if (yielded !== null) {
724
+ await cycle.deadline.dispose();
725
+ await cycle.events.suspend();
726
+ stateValue(context.store.release(context.authority));
727
+ stateValue(context.store.close());
728
+ await context.owner.release();
729
+ return yielded;
730
+ }
731
+ await cleanupRunWorkspaces(runRoot, context.lock.spec.runId, context.directory, context.artifacts);
732
+ try {
733
+ await cycle.deadline.dispose();
734
+ }
735
+ catch {
736
+ primary = incident({ version: 1, code: 'CLEANUP_FAILED', phase: 'finalization', path: '', stateCode: null, piCode: null, effect: 'possible', retryable: false }, context.lock.spec.runId, context.lock.spec.lockHash, [context.descriptor.plan, context.source.inventory], ['local_cleanup'], 'failed');
737
+ }
738
+ const settled = await cycle.terminal(primary);
739
+ let cleanup;
740
+ try {
741
+ const released = context.store.release(context.authority);
742
+ const closed = context.store.close();
743
+ cleanup = released.ok && closed.ok;
744
+ if (cleanup)
745
+ await context.owner.release();
746
+ }
747
+ catch {
748
+ cleanup = false;
749
+ }
750
+ if (!cleanup) {
751
+ return {
752
+ kind: 'incident',
753
+ version: 1,
754
+ incident: incident({ version: 1, code: 'CLEANUP_FAILED', phase: 'finalization', path: '', stateCode: null, piCode: null, effect: 'possible', retryable: false }, context.lock.spec.runId, context.lock.spec.lockHash, [context.descriptor.plan, context.source.inventory], ['owner_release', 'authoritative_cleanup'], 'pending'),
755
+ };
756
+ }
757
+ return settled;
758
+ }
759
+ async function reopenStepContext(input) {
760
+ validatePortPolicyFields(input.ports, input.phase);
761
+ const { directory, descriptor, lock, effectiveConfig, state, plan } = await admitRetainedRun({
762
+ runRoot: input.runRoot,
763
+ runId: input.runId,
764
+ ...(input.configuration ? { configuration: input.configuration } : {}),
765
+ ...(input.repository !== undefined ? { repository: input.repository } : {}),
766
+ ...(input.environment ? { environment: input.environment } : {}),
767
+ phase: input.phase,
768
+ });
769
+ const meta = await readStepMeta(directory, effectiveRunHostPolicy(descriptor));
770
+ const effectivePorts = validatePortsAgainstHostPolicy(input.ports, meta.hostPolicy, input.phase);
771
+ const effectiveDescriptor = descriptor.hostPolicy !== undefined ? descriptor : { ...descriptor, hostPolicy: meta.hostPolicy };
772
+ validateGateUrlOverrides(effectivePorts.gateUrlOverrides, input.phase, effectiveConfig.registry.spec.gateEndpoints);
773
+ let owner = null;
774
+ let store = null;
775
+ let authority = null;
776
+ let handedOff = false;
777
+ try {
778
+ owner = await ControllerOwner.acquire(directory, input.runId, plan.planDigest);
779
+ store = stateValue(reopenLocalRun(descriptor.identity));
780
+ const original = stateValue(store.inspect());
781
+ if (original.clockStatus !== 'trusted')
782
+ refuse('RECOVERY_REQUIRED', '', input.phase);
783
+ authority = stateValue(store.claim({
784
+ ownerId: 'controller.' + owner.nonce,
785
+ expectedGeneration: original.owner.generation,
786
+ expectedRevision: original.revision,
787
+ mode: 'recovery',
788
+ })).authority;
789
+ const artifacts = new ArtifactStore(join(directory, 'artifacts'), owner, state.vault);
790
+ await artifacts.cleanCasTempFiles();
791
+ const jsonPaths = [...new Set(plan.verifierSlots.filter(slot => ['json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1'].includes(slot.handler.implementation)).map(slot => text(slot.handler.parameters.path)))];
792
+ const source = await restoreSource(descriptor.repository, plan.task, owner, artifacts, descriptor.source, descriptor.sourceWorkspace, jsonPaths);
793
+ const progress = new ProgressStore(store, authority, artifacts, plan, lock, descriptor.plan, descriptor.source);
794
+ let head = await progress.read();
795
+ let context = {
796
+ loaded: effectiveConfig,
797
+ plan,
798
+ lock,
799
+ directory,
800
+ source,
801
+ store,
802
+ authority,
803
+ owner,
804
+ artifacts,
805
+ progress,
806
+ descriptor: effectiveDescriptor,
807
+ signal: input.signal ?? new AbortController().signal,
808
+ onEvent: undefined,
809
+ ports: effectivePorts,
810
+ };
811
+ const candidate = await restoredCandidate(context, head);
812
+ await reconcileInterruptedOperations(context, head, candidate, original.storeId);
813
+ head = await progress.read();
814
+ const decision = progress.decision(head);
815
+ const expired = decision !== 'terminal' &&
816
+ decision !== 'reconcile_required' &&
817
+ ((original.clock.remainingTaskMs.safeValue ?? 0) <= 0 ||
818
+ BigInt(original.clock.sampledNow.monotonicMs) >= BigInt(original.clock.basis.taskDeadlineMonotonicMs) - BigInt(plan.controls.drainReserveMs));
819
+ if (decision !== 'terminal' && decision !== 'reconcile_required' && !expired && !input.forceRecoveryMode) {
820
+ stateValue(store.release(authority));
821
+ authority = null;
822
+ const current = stateValue(store.inspect());
823
+ authority = stateValue(store.claim({
824
+ ownerId: 'controller.' + owner.nonce,
825
+ expectedGeneration: current.owner.generation,
826
+ expectedRevision: current.revision,
827
+ mode: 'active',
828
+ })).authority;
829
+ context = {
830
+ ...context,
831
+ authority,
832
+ progress: new ProgressStore(store, authority, artifacts, plan, lock, descriptor.plan, descriptor.source),
833
+ };
834
+ }
835
+ let submission = null;
836
+ if (head?.progress.submission) {
837
+ try {
838
+ submission = {
839
+ version: 1,
840
+ origin: plan.orderedDAG.some(node => node.kind === 'agent') ? 'assistant' : 'controller',
841
+ raw: head.progress.submission,
842
+ value: normalizeSubmission(await artifacts.read(head.progress.submission, 1_048_576), plan.task),
843
+ };
844
+ }
845
+ catch (error) {
846
+ if (!(error instanceof ControllerFailure) || error.diagnostic.code !== 'SUBMISSION_INVALID')
847
+ throw error;
848
+ }
849
+ }
850
+ handedOff = true;
851
+ return { context, meta, head, candidate, submission, decision, expired };
852
+ }
853
+ finally {
854
+ if (!handedOff) {
855
+ if (store) {
856
+ if (authority)
857
+ stateValue(store.release(authority));
858
+ stateValue(store.close());
859
+ }
860
+ if (owner)
861
+ await owner.release();
862
+ }
863
+ }
864
+ }
865
+ async function settleForcedStepRun(context, head, candidate, submission, runRoot, forcedStatus) {
866
+ await cleanupRunWorkspaces(runRoot, context.lock.spec.runId, context.directory, context.artifacts);
867
+ const cycle = new Cycle(context, head, candidate, false);
868
+ cycle.submission = submission;
869
+ let primary;
870
+ try {
871
+ if (!cycle.head)
872
+ await cycle.bootstrap();
873
+ const active = cycle.draft.attempts.at(-1);
874
+ if (active && active.finished === null && forcedStatus !== 'reconcile_required') {
875
+ const diagnostic = {
876
+ version: 1,
877
+ code: forcedStatus === 'expired' ? 'DEADLINE' : 'CANCELLED',
878
+ phase: 'execution',
879
+ path: '',
880
+ stateCode: null,
881
+ piCode: null,
882
+ effect: 'none',
883
+ retryable: false,
884
+ };
885
+ const after = stateValue(context.store.inspect()).counts;
886
+ const outcome = await context.artifacts.json('role-refusal', {
887
+ version: 1,
888
+ attemptId: active.id,
889
+ command: active.command,
890
+ diagnostic,
891
+ nativeOutcome: null,
892
+ currentCandidate: cycle.draft.candidate.manifest,
893
+ unavailable: [],
894
+ localCleanup: 'complete',
895
+ }, 65_536);
896
+ await cycle.publish({
897
+ ...cycle.draft,
898
+ stage: { ...cycle.draft.stage, kind: 'role_post' },
899
+ attempts: cycle.draft.attempts.map(item => item.id === active.id
900
+ ? { ...item, finished: { after: { requests: after.requests, operations: after.operations }, outcome, nativeCheckpointId: null } }
901
+ : item),
902
+ nodes: cycle.draft.nodes.map(item => item.id === active.nodeId
903
+ ? { ...item, state: 'failed' }
904
+ : descendants(context.plan, active.nodeId).includes(item.id) && item.state === 'pending'
905
+ ? { ...item, state: 'not_run' }
906
+ : item),
907
+ }, 'role.' + active.ordinal + '.post');
908
+ }
909
+ const retained = [
910
+ ...(cycle.head?.progress.verifierReceipts ?? []).filter(row => {
911
+ if (row.receipt !== null)
912
+ return true;
913
+ const op = context.store.getOperation(row.operationId);
914
+ return op.ok && op.value.dispatch !== null;
915
+ }),
916
+ ...(cycle.head?.progress.verifierRefusals ?? []),
917
+ ].filter(row => row.generation === cycle.generation);
918
+ for (const row of retained)
919
+ await cycle.runVerifier(row.slot);
920
+ const checks = cycle.currentChecks();
921
+ const preverified = await verifyControllerVerifierCasDescriptors(context.plan, checks, {
922
+ ...(!context.signal.aborted ? { signal: context.signal } : {}),
923
+ checkAuthority: () => context.owner.assertCurrent(),
924
+ });
925
+ primary = evaluateControllerAcceptance(context.plan, context.lock, cycle.candidate.manifest, cycle.candidate.files, cycle.generation, checks, cycle.submission?.value ?? null, context.store, forcedStatus === 'reconcile_required' ? null : forcedStatus, cycle.draft.nodes.every(node => node.state === 'completed'), cycle.currentRefusals(), null, preverified);
926
+ }
927
+ catch (error) {
928
+ primary = incident(safeDiagnostic(error, 'finalization'), context.lock.spec.runId, context.lock.spec.lockHash, [context.descriptor.plan, context.source.inventory], ['authoritative_result'], 'complete');
929
+ }
930
+ await cycle.deadline.dispose().catch(() => { });
931
+ const settled = await cycle.terminal(primary, 15_000);
932
+ try {
933
+ stateValue(context.store.release(context.authority));
934
+ stateValue(context.store.close());
935
+ await context.owner.release();
936
+ }
937
+ catch {
938
+ // Best-effort release on terminal drain/cancel.
939
+ }
940
+ return settled;
941
+ }
942
+ async function scanCandidateDirectory(candidateDir, source, task, previousDigest, previousModes, disallowMutations, overlayConfig, artifacts, hostProtection) {
943
+ const bounds = overlayManifestBounds(overlayConfig);
944
+ const v2BaseTree = source.version === 2 ? source.manifest.spec.baseTree : undefined;
945
+ const v2BaselineByPath = source.version === 2
946
+ ? new Map((source.baselineEntries ?? []).map(entry => [entry.name, entry]))
947
+ : undefined;
948
+ const v1BaselineByPath = source.version === 1
949
+ ? new Map(source.artifacts.map(artifact => [
950
+ artifact.name,
951
+ { byteLength: artifact.bytes.byteLength, mode: artifact.mode ?? '100644' },
952
+ ]))
953
+ : undefined;
954
+ let rootStat;
955
+ try {
956
+ rootStat = await lstat(candidateDir);
957
+ }
958
+ catch {
959
+ refuse('ARTIFACT_INVALID', '', 'execution');
960
+ }
961
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink())
962
+ refuse('ARTIFACT_INVALID', '', 'execution');
963
+ const scannedFiles = [];
964
+ const seenPaths = new Set();
965
+ const streamChunk = Buffer.allocUnsafe(STREAM_CHUNK_BYTES);
966
+ const probeByte = Buffer.allocUnsafe(1);
967
+ let entriesSeen = 0;
968
+ let knownOverlayFiles = 0;
969
+ let knownOverlayBytes = 0;
970
+ let knownClassicFiles = 0;
971
+ let knownClassicBytes = 0;
972
+ const visit = async (absDir, relPrefix, depth) => {
973
+ if (depth > 32)
974
+ refuse('ARTIFACT_INVALID', '', 'execution');
975
+ const dirEntries = await readdir(absDir, { withFileTypes: true });
976
+ entriesSeen += dirEntries.length;
977
+ if (entriesSeen > 131_072)
978
+ refuse('OUTPUT_LIMIT', '', 'execution');
979
+ dirEntries.sort((a, b) => compareUtf16(a.name, b.name));
980
+ for (const d of dirEntries) {
981
+ if (d.name.toLowerCase() === '.git' || Buffer.byteLength(d.name, 'utf8') > 255)
982
+ refuse('ARTIFACT_INVALID', '', 'execution');
983
+ const absPath = join(absDir, d.name);
984
+ const relPath = relPrefix ? `${relPrefix}/${d.name}` : d.name;
985
+ const st = await lstat(absPath);
986
+ if (st.isSymbolicLink())
987
+ refuse('ARTIFACT_INVALID', '', 'execution');
988
+ if (st.isDirectory()) {
989
+ await visit(absPath, relPath, depth + 1);
990
+ continue;
991
+ }
992
+ if (!st.isFile() || st.nlink !== 1)
993
+ refuse('ARTIFACT_INVALID', '', 'execution');
994
+ if (!digestArtifact(relPath, new Uint8Array()).ok)
995
+ refuse('ARTIFACT_INVALID', '', 'execution');
996
+ const fh = await open(absPath, constants.O_RDONLY | constants.O_NOFOLLOW);
997
+ let byteLength;
998
+ let mode;
999
+ let sha256;
1000
+ let gitOid;
1001
+ let sizeChangedOrAdded = false;
1002
+ try {
1003
+ const fst = await fh.stat();
1004
+ if (fst.dev !== st.dev || fst.ino !== st.ino || fst.nlink !== 1 || !fst.isFile() || fst.size !== st.size) {
1005
+ refuse('ARTIFACT_INVALID', '', 'execution');
1006
+ }
1007
+ if (source.version === 2) {
1008
+ const baseEntry = v2BaselineByPath.get(relPath);
1009
+ sizeChangedOrAdded = baseEntry === undefined || baseEntry.byteLength !== fst.size;
1010
+ if (sizeChangedOrAdded) {
1011
+ if (isHostProtectedPath(relPath, hostProtection)) {
1012
+ refuse('ARTIFACT_INVALID', '', 'execution');
1013
+ }
1014
+ if (fst.size > bounds.perFileMaxBytes ||
1015
+ knownOverlayFiles + 1 > bounds.maxFiles ||
1016
+ knownOverlayBytes + fst.size > bounds.maxBytes) {
1017
+ refuse('OUTPUT_LIMIT', '', 'execution');
1018
+ }
1019
+ knownOverlayFiles += 1;
1020
+ knownOverlayBytes += fst.size;
1021
+ }
1022
+ }
1023
+ else {
1024
+ const baseEntry = v1BaselineByPath.get(relPath);
1025
+ const observedMode = (fst.mode & 0o111) !== 0 ? '100755' : '100644';
1026
+ if ((baseEntry === undefined || baseEntry.byteLength !== fst.size || baseEntry.mode !== observedMode)
1027
+ && isHostProtectedPath(relPath, hostProtection)) {
1028
+ refuse('ARTIFACT_INVALID', '', 'execution');
1029
+ }
1030
+ if (fst.size > bounds.perFileMaxBytes ||
1031
+ knownClassicFiles + 1 > bounds.maxFiles ||
1032
+ knownClassicBytes + fst.size > bounds.maxBytes) {
1033
+ refuse('OUTPUT_LIMIT', '', 'execution');
1034
+ }
1035
+ knownClassicFiles += 1;
1036
+ knownClassicBytes += fst.size;
1037
+ }
1038
+ const shaHasher = createHash('sha256');
1039
+ const gitHasher = v2BaseTree !== undefined
1040
+ ? createHash(v2BaseTree.objectFormat === 'sha256' ? 'sha256' : 'sha1').update(`blob ${fst.size}\0`, 'utf8')
1041
+ : null;
1042
+ let offset = 0;
1043
+ while (offset < fst.size) {
1044
+ const toRead = Math.min(streamChunk.length, fst.size - offset);
1045
+ const { bytesRead } = await fh.read(streamChunk, 0, toRead, offset);
1046
+ if (bytesRead <= 0)
1047
+ break;
1048
+ const slice = streamChunk.subarray(0, bytesRead);
1049
+ shaHasher.update(slice);
1050
+ gitHasher?.update(slice);
1051
+ offset += bytesRead;
1052
+ }
1053
+ const { bytesRead: extraBytes } = await fh.read(probeByte, 0, 1, offset);
1054
+ const after = await fh.stat();
1055
+ if (extraBytes !== 0 ||
1056
+ offset !== fst.size ||
1057
+ after.dev !== fst.dev ||
1058
+ after.ino !== fst.ino ||
1059
+ after.nlink !== 1 ||
1060
+ !after.isFile() ||
1061
+ after.size !== fst.size ||
1062
+ after.mtimeMs !== fst.mtimeMs ||
1063
+ after.ctimeMs !== fst.ctimeMs) {
1064
+ refuse('ARTIFACT_INVALID', '', 'execution');
1065
+ }
1066
+ byteLength = fst.size;
1067
+ mode = (fst.mode & 0o111) !== 0 ? '100755' : '100644';
1068
+ sha256 = shaHasher.digest('hex');
1069
+ gitOid = gitHasher?.digest('hex');
1070
+ }
1071
+ finally {
1072
+ await fh.close();
1073
+ }
1074
+ if (source.version === 2 && !sizeChangedOrAdded) {
1075
+ const baseEntry = v2BaselineByPath.get(relPath);
1076
+ if (baseEntry !== undefined && gitOid !== baseEntry.oid) {
1077
+ if (isHostProtectedPath(relPath, hostProtection)) {
1078
+ refuse('ARTIFACT_INVALID', '', 'execution');
1079
+ }
1080
+ if (byteLength > bounds.perFileMaxBytes ||
1081
+ knownOverlayFiles + 1 > bounds.maxFiles ||
1082
+ knownOverlayBytes + byteLength > bounds.maxBytes) {
1083
+ refuse('OUTPUT_LIMIT', '', 'execution');
1084
+ }
1085
+ knownOverlayFiles += 1;
1086
+ knownOverlayBytes += byteLength;
1087
+ }
1088
+ }
1089
+ seenPaths.add(relPath);
1090
+ scannedFiles.push({ absPath, name: relPath, mode, byteLength, sha256, gitOid });
1091
+ }
1092
+ };
1093
+ await visit(candidateDir, '', 1);
1094
+ scannedFiles.sort((a, b) => compareUtf16(a.name, b.name));
1095
+ if (source.version === 2) {
1096
+ const baseTree = v2BaseTree;
1097
+ const baselineByPath = v2BaselineByPath;
1098
+ const deleted = [];
1099
+ for (const baseEntry of source.baselineEntries ?? []) {
1100
+ if (!seenPaths.has(baseEntry.name)) {
1101
+ if (isHostProtectedPath(baseEntry.name, hostProtection))
1102
+ refuse('ARTIFACT_INVALID', '', 'execution');
1103
+ deleted.push(baseEntry.name);
1104
+ }
1105
+ }
1106
+ deleted.sort(compareUtf16);
1107
+ const overlay = [];
1108
+ const files = [];
1109
+ const manifestEntries = [];
1110
+ let totalOverlayBytes = 0;
1111
+ for (const file of scannedFiles) {
1112
+ const baseEntry = baselineByPath.get(file.name);
1113
+ const expectedMode = previousModes.get(file.name) ?? baseEntry?.mode ?? '100644';
1114
+ if (baseEntry && file.gitOid === baseEntry.oid) {
1115
+ if (file.mode !== expectedMode) {
1116
+ refuse('ARTIFACT_INVALID', '', 'execution');
1117
+ }
1118
+ continue;
1119
+ }
1120
+ if (disallowMutations && file.mode !== expectedMode) {
1121
+ refuse('ARTIFACT_INVALID', '', 'execution');
1122
+ }
1123
+ const effectiveMode = disallowMutations ? expectedMode : file.mode;
1124
+ if (isHostProtectedPath(file.name, hostProtection))
1125
+ refuse('ARTIFACT_INVALID', '', 'execution');
1126
+ if (file.byteLength > bounds.perFileMaxBytes ||
1127
+ overlay.length >= bounds.maxFiles ||
1128
+ (totalOverlayBytes += file.byteLength) > bounds.maxBytes) {
1129
+ refuse('OUTPUT_LIMIT', '', 'execution');
1130
+ }
1131
+ const pointer = await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes, {
1132
+ gitObjectFormat: baseTree.objectFormat,
1133
+ });
1134
+ if (pointer.sha256 !== file.sha256
1135
+ || pointer.byteLength !== file.byteLength
1136
+ || (pointer.verifiedSeal !== undefined && file.gitOid !== undefined && pointer.verifiedSeal.gitOid !== file.gitOid)) {
1137
+ refuse('ARTIFACT_INVALID', '', 'execution');
1138
+ }
1139
+ const ref = digestArtifactFromMetadata(file.name, {
1140
+ digest: { algorithm: 'sha256', hex: pointer.sha256 },
1141
+ byteLength: pointer.byteLength,
1142
+ });
1143
+ if (!ref.ok)
1144
+ refuse('ARTIFACT_INVALID', '', 'execution');
1145
+ overlay.push({
1146
+ name: file.name,
1147
+ mode: effectiveMode,
1148
+ sha256: pointer.sha256,
1149
+ byteLength: pointer.byteLength,
1150
+ blobRef: pointer.blobRef,
1151
+ });
1152
+ const casFile = {
1153
+ name: file.name,
1154
+ byteLength: pointer.byteLength,
1155
+ digest: ref.value.digest,
1156
+ blobPath: pointer.path,
1157
+ mode: effectiveMode,
1158
+ };
1159
+ if (pointer.verifiedSeal !== undefined) {
1160
+ attachVerifiedCasSeal(casFile, pointer.verifiedSeal);
1161
+ }
1162
+ files.push(casFile);
1163
+ manifestEntries.push(ref.value);
1164
+ }
1165
+ const identified = identifyManifest(canonicalizeCandidateManifest({
1166
+ apiVersion: 'loopwright.dev/v1alpha1',
1167
+ kind: 'ArtifactManifest',
1168
+ metadata: { id: 'candidate' },
1169
+ spec: { baseTree, entries: manifestEntries, deleted },
1170
+ }), bounds.options);
1171
+ if (!identified.ok)
1172
+ refuse('ARTIFACT_INVALID', '', 'execution');
1173
+ if (disallowMutations && !same(identified.value.digest, previousDigest)) {
1174
+ refuse('ARTIFACT_INVALID', '', 'execution');
1175
+ }
1176
+ return { manifest: identified.value.manifest, files, overlay, deleted };
1177
+ }
1178
+ // source.version === 1 (classic mode)
1179
+ if (scannedFiles.length > bounds.maxFiles)
1180
+ refuse('OUTPUT_LIMIT', '', 'execution');
1181
+ let totalBytes = 0;
1182
+ const baselineByPath = new Map(source.artifacts.map(item => [
1183
+ item.name,
1184
+ { byteLength: item.bytes.byteLength, sha256: hash(item.bytes).hex, mode: item.mode ?? '100644' },
1185
+ ]));
1186
+ const scannedNames = new Set(scannedFiles.map(item => item.name));
1187
+ const deleted = [];
1188
+ for (const baseName of baselineByPath.keys()) {
1189
+ if (!scannedNames.has(baseName)) {
1190
+ if (isHostProtectedPath(baseName, hostProtection))
1191
+ refuse('ARTIFACT_INVALID', '', 'execution');
1192
+ deleted.push(baseName);
1193
+ }
1194
+ }
1195
+ deleted.sort(compareUtf16);
1196
+ const overlay = [];
1197
+ const files = [];
1198
+ const manifestEntries = [];
1199
+ for (const file of scannedFiles) {
1200
+ const baseInfo = baselineByPath.get(file.name);
1201
+ const expectedMode = previousModes.get(file.name) ?? baseInfo?.mode ?? '100644';
1202
+ if (disallowMutations && file.mode !== expectedMode) {
1203
+ refuse('ARTIFACT_INVALID', '', 'execution');
1204
+ }
1205
+ const effectiveMode = disallowMutations ? expectedMode : file.mode;
1206
+ const modeChangedFromBaseline = baseInfo !== undefined && baseInfo.mode !== effectiveMode;
1207
+ const modifiedOrAdded = baseInfo === undefined
1208
+ || baseInfo.byteLength !== file.byteLength
1209
+ || baseInfo.sha256 !== file.sha256
1210
+ || modeChangedFromBaseline;
1211
+ if (modifiedOrAdded && isHostProtectedPath(file.name, hostProtection)) {
1212
+ refuse('ARTIFACT_INVALID', '', 'execution');
1213
+ }
1214
+ if (modeChangedFromBaseline) {
1215
+ if (baseInfo.byteLength === file.byteLength && baseInfo.sha256 === file.sha256) {
1216
+ refuse('ARTIFACT_INVALID', '', 'execution');
1217
+ }
1218
+ const writable = isWritablePath(task, file.name);
1219
+ if (!writable.ok || !writable.value) {
1220
+ refuse('ARTIFACT_INVALID', '', 'execution');
1221
+ }
1222
+ }
1223
+ if (file.byteLength > bounds.perFileMaxBytes || (totalBytes += file.byteLength) > bounds.maxBytes) {
1224
+ refuse('OUTPUT_LIMIT', '', 'execution');
1225
+ }
1226
+ const pointer = !modifiedOrAdded
1227
+ ? (await artifacts.tryReuseCasBlob(file.name, file.sha256, file.byteLength))
1228
+ ?? await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes)
1229
+ : await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes);
1230
+ if (pointer.sha256 !== file.sha256 || pointer.byteLength !== file.byteLength) {
1231
+ refuse('ARTIFACT_INVALID', '', 'execution');
1232
+ }
1233
+ const ref = digestArtifactFromMetadata(file.name, {
1234
+ digest: { algorithm: 'sha256', hex: pointer.sha256 },
1235
+ byteLength: pointer.byteLength,
1236
+ });
1237
+ if (!ref.ok)
1238
+ refuse('ARTIFACT_INVALID', '', 'execution');
1239
+ overlay.push({
1240
+ name: file.name,
1241
+ mode: effectiveMode,
1242
+ sha256: pointer.sha256,
1243
+ byteLength: pointer.byteLength,
1244
+ blobRef: pointer.blobRef,
1245
+ });
1246
+ files.push({
1247
+ name: file.name,
1248
+ byteLength: pointer.byteLength,
1249
+ digest: ref.value.digest,
1250
+ blobPath: pointer.path,
1251
+ mode: effectiveMode,
1252
+ });
1253
+ manifestEntries.push(ref.value);
1254
+ }
1255
+ const identified = identifyManifest(canonicalizeCandidateManifest({
1256
+ apiVersion: 'loopwright.dev/v1alpha1',
1257
+ kind: 'ArtifactManifest',
1258
+ metadata: { id: 'candidate' },
1259
+ spec: { entries: manifestEntries },
1260
+ }), bounds.options);
1261
+ if (!identified.ok)
1262
+ refuse('ARTIFACT_INVALID', '', 'execution');
1263
+ if (disallowMutations && !same(identified.value.digest, previousDigest)) {
1264
+ refuse('ARTIFACT_INVALID', '', 'execution');
1265
+ }
1266
+ return { manifest: identified.value.manifest, files, overlay, deleted };
1267
+ }
1268
+ async function readExplicitSubmissionFile(path) {
1269
+ const rawTarget = resolve(text(path, '/submissionFile', 4096));
1270
+ let target;
1271
+ try {
1272
+ const stats = await lstat(rawTarget);
1273
+ if (!stats.isFile() || stats.isSymbolicLink() || stats.nlink !== 1 || stats.size > 65_536) {
1274
+ refuse(stats.size > 65_536 ? 'OUTPUT_LIMIT' : 'ARTIFACT_INVALID', '/submissionFile', 'execution');
1275
+ }
1276
+ target = join(await realpath(dirname(rawTarget)), basename(rawTarget));
1277
+ }
1278
+ catch (error) {
1279
+ if (error instanceof ControllerFailure)
1280
+ throw error;
1281
+ refuse('ARTIFACT_INVALID', '/submissionFile', 'execution');
1282
+ }
1283
+ const bytes = await readBoundedFile(target, 65_536, false);
1284
+ try {
1285
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
1286
+ }
1287
+ catch {
1288
+ refuse('SUBMISSION_INVALID', '/submissionFile', 'execution');
1289
+ }
1290
+ return new Uint8Array(bytes);
1291
+ }
1292
+ export function stepNext(input, ports = {}) {
1293
+ return result(async () => {
1294
+ const fields = Object.keys(input);
1295
+ record(input, fields);
1296
+ if (fields.some(key => !['configuration', 'repository', 'runRoot', 'runId', 'mode', 'reissueLease', 'policyProfile', 'allowWorkflowWrites', 'roleMcpServers', 'mcpServers', 'watchedPaths', 'environment', 'signal'].includes(key)) ||
1297
+ (input.mode !== undefined && input.mode !== 'candidate' && input.mode !== 'no-change') ||
1298
+ (input.reissueLease !== undefined && typeof input.reissueLease !== 'boolean') ||
1299
+ (input.policyProfile !== undefined && input.policyProfile !== 'local' && input.policyProfile !== 'github') ||
1300
+ (input.allowWorkflowWrites !== undefined && typeof input.allowWorkflowWrites !== 'boolean') ||
1301
+ (input.environment !== undefined && typeof input.environment !== 'function') ||
1302
+ (input.signal !== undefined && !(input.signal instanceof AbortSignal))) {
1303
+ refuse('CONFIG_SCHEMA', '', 'admission');
1304
+ }
1305
+ validatePortPolicyFields(ports, 'admission');
1306
+ if (input.policyProfile !== undefined && ports.policyProfile !== undefined && input.policyProfile !== ports.policyProfile) {
1307
+ refuse('CONFIG_SCHEMA', '/policyProfile', 'admission');
1308
+ }
1309
+ if (input.allowWorkflowWrites !== undefined && ports.allowWorkflowWrites !== undefined && input.allowWorkflowWrites !== ports.allowWorkflowWrites) {
1310
+ refuse('CONFIG_SCHEMA', '/allowWorkflowWrites', 'admission');
1311
+ }
1312
+ const normalizedRoleMcp = normalizeRoleMcpServers(input.roleMcpServers ?? ports.roleMcpServers, 'admission');
1313
+ const normalizedMcpServers = normalizeMcpServersMetadata(input.mcpServers ?? ports.mcpServers, 'admission');
1314
+ const normalizedWatched = normalizeWatchedPaths(input.watchedPaths ?? ports.watchedPaths, 'admission');
1315
+ validateGateUrlOverrides(ports.gateUrlOverrides, 'admission');
1316
+ if (input.signal?.aborted)
1317
+ refuse('CANCELLED', '', 'admission');
1318
+ const requestedPolicyProfile = input.policyProfile ?? ports.policyProfile;
1319
+ const requestedAllowWorkflowWrites = input.allowWorkflowWrites ?? ports.allowWorkflowWrites;
1320
+ const root = resolve(text(input.runRoot));
1321
+ const runId = id(input.runId);
1322
+ const directory = join(root, runId);
1323
+ const exists = await lstat(directory).then(() => true, () => false);
1324
+ if (!exists) {
1325
+ if (!input.configuration || input.repository === undefined)
1326
+ refuse('CONFIG_SCHEMA', '', 'admission');
1327
+ const compiled = await compilePlan(input.configuration);
1328
+ if (!compiled.ok)
1329
+ throw new ControllerFailure(compiled.error);
1330
+ validateGateUrlOverrides(ports.gateUrlOverrides, 'admission', input.configuration.registry.spec.gateEndpoints);
1331
+ if (input.mode === 'no-change' && !compiled.value.noChangeEligibility.available) {
1332
+ refuse('CAPABILITY_UNSUPPORTED', '/mode', 'admission');
1333
+ }
1334
+ const initialHostPolicy = freeze({
1335
+ policyProfile: requestedPolicyProfile ?? 'local',
1336
+ allowWorkflowWrites: requestedAllowWorkflowWrites === true,
1337
+ });
1338
+ const context = await createCycle({
1339
+ configuration: input.configuration,
1340
+ repository: input.repository,
1341
+ runRoot: input.runRoot,
1342
+ runId: input.runId,
1343
+ ...(input.signal ? { signal: input.signal } : {}),
1344
+ }, {
1345
+ ...ports,
1346
+ policyProfile: initialHostPolicy.policyProfile,
1347
+ allowWorkflowWrites: initialHostPolicy.allowWorkflowWrites,
1348
+ });
1349
+ const initialMeta = {
1350
+ version: 1,
1351
+ mode: input.mode ?? 'candidate',
1352
+ hostPolicy: initialHostPolicy,
1353
+ ...(initialHostPolicy.allowWorkflowWrites ? { allowWorkflowWrites: true } : {}),
1354
+ ...(normalizedRoleMcp !== undefined ? { roleMcpServers: normalizedRoleMcp } : {}),
1355
+ ...(normalizedMcpServers !== undefined ? { mcpServers: normalizedMcpServers } : {}),
1356
+ ...(normalizedWatched !== undefined ? { watchedPaths: normalizedWatched } : {}),
1357
+ };
1358
+ await writeAtomicPrivateJson(join(context.directory, 'step-meta.json'), initialMeta, context.artifacts.vault);
1359
+ const view = stateValue(context.store.inspect());
1360
+ const expiredAtStart = (view.clock.remainingTaskMs.safeValue ?? 0) <= 0 ||
1361
+ BigInt(view.clock.sampledNow.monotonicMs) >= BigInt(view.clock.basis.taskDeadlineMonotonicMs) - BigInt(context.plan.controls.drainReserveMs);
1362
+ if (expiredAtStart) {
1363
+ const bounds = overlayManifestBounds(context.plan.budgets.overlay);
1364
+ const initialManifestRef = await context.artifacts.json('manifest', context.source.manifest, bounds.manifestMaxBytes);
1365
+ return await settleForcedStepRun(context, null, { manifest: context.source.manifest, ref: initialManifestRef, files: context.source.artifacts, baselineProofs: context.source.baselineProofs }, null, input.runRoot, 'expired');
1366
+ }
1367
+ return await runStepTickWithCycle(context, input.runRoot, initialMeta);
1368
+ }
1369
+ const mergedReopenPorts = {
1370
+ ...ports,
1371
+ ...(requestedPolicyProfile !== undefined ? { policyProfile: requestedPolicyProfile } : {}),
1372
+ ...(requestedAllowWorkflowWrites !== undefined ? { allowWorkflowWrites: requestedAllowWorkflowWrites } : {}),
1373
+ };
1374
+ const reopened = await reopenStepContext({
1375
+ runRoot: input.runRoot,
1376
+ runId: input.runId,
1377
+ ...(input.configuration ? { configuration: input.configuration } : {}),
1378
+ ...(input.repository !== undefined ? { repository: input.repository } : {}),
1379
+ ...(input.environment ? { environment: input.environment } : {}),
1380
+ ...(input.signal ? { signal: input.signal } : {}),
1381
+ ports: mergedReopenPorts,
1382
+ phase: 'execution',
1383
+ });
1384
+ const { context, meta: existingMeta, head, candidate, submission, decision, expired } = reopened;
1385
+ if (input.mode !== undefined && input.mode !== existingMeta.mode) {
1386
+ stateValue(context.store.release(context.authority));
1387
+ stateValue(context.store.close());
1388
+ await context.owner.release();
1389
+ refuse('RECOVERY_REQUIRED', '/mode', 'execution');
1390
+ }
1391
+ const effectiveMeta = {
1392
+ ...existingMeta,
1393
+ ...(normalizedRoleMcp !== undefined ? { roleMcpServers: normalizedRoleMcp } : {}),
1394
+ ...(normalizedMcpServers !== undefined ? { mcpServers: normalizedMcpServers } : {}),
1395
+ ...(normalizedWatched !== undefined ? { watchedPaths: normalizedWatched } : {}),
1396
+ };
1397
+ if (decision === 'terminal') {
1398
+ try {
1399
+ return await retainedPrimary(context, head);
1400
+ }
1401
+ finally {
1402
+ stateValue(context.store.release(context.authority));
1403
+ stateValue(context.store.close());
1404
+ await context.owner.release();
1405
+ }
1406
+ }
1407
+ if (decision === 'reconcile_required') {
1408
+ return await settleForcedStepRun(context, head, candidate, submission, input.runRoot, 'reconcile_required');
1409
+ }
1410
+ if (expired) {
1411
+ return await settleForcedStepRun(context, head, candidate, submission, input.runRoot, 'expired');
1412
+ }
1413
+ const active = head?.progress.attempts.at(-1);
1414
+ const activeNode = active ? context.plan.orderedDAG.find(node => node.id === active.nodeId) : undefined;
1415
+ const activeRole = activeNode?.roleId ? context.plan.roles.find(role => role.roleId === activeNode.roleId) : undefined;
1416
+ if (head?.progress.stage.kind === 'role_pre' && active && active.finished === null && activeRole?.adapter === 'delegated' && decision !== 'adopt_capture') {
1417
+ if (!input.reissueLease) {
1418
+ stateValue(context.store.release(context.authority));
1419
+ stateValue(context.store.close());
1420
+ await context.owner.release();
1421
+ refuse('OWNER_BUSY', '', 'execution');
1422
+ }
1423
+ let cycle;
1424
+ let stepYield;
1425
+ let teardownError = null;
1426
+ try {
1427
+ const priorLease = await readStepLease(context.directory);
1428
+ const promptText = priorLease?.prompt ?? new TextDecoder('utf-8', { fatal: true }).decode(await context.artifacts.read(active.command, LIMITS.inputBytes));
1429
+ const effectiveRole = active.repair === 'format' ? { ...activeRole, policy: formatPolicy(activeRole.policy) } : activeRole;
1430
+ cycle = new Cycle(context, head, candidate, false);
1431
+ const activeResources = cycle.resolveRetainedActiveResources(effectiveRole.roleId, active);
1432
+ const hostProtection = hostProtectionFromPolicy(effectiveMeta.hostPolicy);
1433
+ const workspacesRoot = join(resolve(input.runRoot), 'workspaces');
1434
+ const runWorkspaceDir = join(workspacesRoot, context.lock.spec.runId);
1435
+ const attemptWorkspaceDir = join(runWorkspaceDir, active.id);
1436
+ const candidateDir = join(attemptWorkspaceDir, 'candidate');
1437
+ const contextDir = join(attemptWorkspaceDir, 'context');
1438
+ const isSafeExistingCandidateTree = async (rootDir) => {
1439
+ const rootSt = await lstat(rootDir).catch(() => null);
1440
+ if (rootSt === null || rootSt.isSymbolicLink() || !rootSt.isDirectory())
1441
+ return false;
1442
+ const stack = [rootDir];
1443
+ let visited = 0;
1444
+ const maxEntries = 65_536;
1445
+ while (stack.length > 0) {
1446
+ const dir = stack.pop();
1447
+ const names = await readdir(dir).catch(() => null);
1448
+ if (names === null)
1449
+ return false;
1450
+ for (const name of names) {
1451
+ visited += 1;
1452
+ if (visited > maxEntries)
1453
+ return false;
1454
+ const child = join(dir, name);
1455
+ if (!inside(child, rootDir))
1456
+ return false;
1457
+ const st = await lstat(child).catch(() => null);
1458
+ if (st === null || st.isSymbolicLink())
1459
+ return false;
1460
+ if (st.isDirectory()) {
1461
+ stack.push(child);
1462
+ }
1463
+ else if (!st.isFile() || st.nlink !== 1) {
1464
+ return false;
1465
+ }
1466
+ }
1467
+ }
1468
+ return true;
1469
+ };
1470
+ const candidateExists = await isSafeExistingCandidateTree(candidateDir);
1471
+ let contextFiles;
1472
+ if (!candidateExists) {
1473
+ const rematerialized = await materializeAttemptWorkspace(cycle, input.runRoot, active.id, effectiveRole, active.repair, hostProtection, activeResources, active.handoffExtracts ?? [], 'recovery');
1474
+ contextFiles = rematerialized.contextFiles;
1475
+ }
1476
+ else {
1477
+ const excluded = [context.descriptor.repository, ...approvedState(context.loaded).input.untrustedRoots];
1478
+ await privateDirectory(workspacesRoot, excluded);
1479
+ await privateDirectory(runWorkspaceDir, excluded);
1480
+ await privateDirectory(attemptWorkspaceDir, excluded);
1481
+ await rm(contextDir, { recursive: true, force: true });
1482
+ await privateDirectory(contextDir, excluded);
1483
+ contextFiles = await materializeContextFilesDir(contextDir, activeResources, active.handoffExtracts ?? [], context.artifacts.directory, 'recovery');
1484
+ }
1485
+ const newToken = randomBytes(32).toString('hex');
1486
+ await writeAtomicPrivateJson(join(context.directory, 'step-lease.json'), {
1487
+ version: 1,
1488
+ runId: context.lock.spec.runId,
1489
+ attemptId: active.id,
1490
+ ordinal: active.ordinal,
1491
+ leaseDigest: hash(newToken).hex,
1492
+ prompt: promptText,
1493
+ contextFiles,
1494
+ }, context.artifacts.vault);
1495
+ stepYield = await buildStepYield(cycle, input.runRoot, active, effectiveRole, promptText, contextFiles, newToken, effectiveMeta);
1496
+ }
1497
+ finally {
1498
+ if (cycle !== undefined) {
1499
+ try {
1500
+ await cycle.deadline.dispose();
1501
+ }
1502
+ catch (err) {
1503
+ teardownError ??= err;
1504
+ }
1505
+ try {
1506
+ await cycle.events.suspend();
1507
+ }
1508
+ catch (err) {
1509
+ teardownError ??= err;
1510
+ }
1511
+ }
1512
+ try {
1513
+ stateValue(context.store.release(context.authority));
1514
+ }
1515
+ catch (err) {
1516
+ teardownError ??= err;
1517
+ }
1518
+ try {
1519
+ stateValue(context.store.close());
1520
+ }
1521
+ catch (err) {
1522
+ teardownError ??= err;
1523
+ }
1524
+ try {
1525
+ await context.owner.release();
1526
+ }
1527
+ catch (err) {
1528
+ teardownError ??= err;
1529
+ }
1530
+ }
1531
+ if (teardownError !== null) {
1532
+ throw teardownError;
1533
+ }
1534
+ return stepYield;
1535
+ }
1536
+ return await runStepTickWithCycle(context, input.runRoot, effectiveMeta, {
1537
+ head,
1538
+ candidate,
1539
+ submission,
1540
+ adopt: decision === 'adopt_capture',
1541
+ });
1542
+ }, 'execution');
1543
+ }
1544
+ export function stepSubmit(input, ports = {}) {
1545
+ return result(async () => {
1546
+ const fields = Object.keys(input);
1547
+ record(input, fields);
1548
+ if (fields.some(key => !['runRoot', 'runId', 'leaseToken', 'submissionFile', 'verdict', 'status', 'reason', 'environment', 'signal'].includes(key)) ||
1549
+ (input.status !== undefined && !['completed', 'no_change', 'failed', 'blocked'].includes(input.status)) ||
1550
+ (input.reason !== undefined && typeof input.reason !== 'string') ||
1551
+ (input.submissionFile !== undefined && typeof input.submissionFile !== 'string') ||
1552
+ (input.verdict !== undefined && input.submissionFile !== undefined) ||
1553
+ (input.environment !== undefined && typeof input.environment !== 'function') ||
1554
+ (input.signal !== undefined && !(input.signal instanceof AbortSignal))) {
1555
+ refuse('CONFIG_SCHEMA', '', 'execution');
1556
+ }
1557
+ let explicitVerdictBytes = null;
1558
+ if (input.verdict !== undefined) {
1559
+ if (!isRecord(input.verdict))
1560
+ refuse('CONFIG_SCHEMA', '/verdict', 'execution');
1561
+ const parsedVerdict = validateStepVerdictObject(input.verdict, 'SUBMISSION_INVALID', 'execution');
1562
+ explicitVerdictBytes = new Uint8Array(Buffer.from(canonical(parsedVerdict), 'utf8'));
1563
+ }
1564
+ validateGateUrlOverrides(ports.gateUrlOverrides, 'execution');
1565
+ validatePortPolicyFields(ports, 'execution');
1566
+ if (input.signal?.aborted)
1567
+ refuse('CANCELLED', '', 'execution');
1568
+ const reopened = await reopenStepContext({
1569
+ runRoot: input.runRoot,
1570
+ runId: input.runId,
1571
+ ...(input.environment ? { environment: input.environment } : {}),
1572
+ ...(input.signal ? { signal: input.signal } : {}),
1573
+ ports,
1574
+ phase: 'execution',
1575
+ });
1576
+ const { context, meta, head, candidate, submission, decision, expired } = reopened;
1577
+ if (expired) {
1578
+ return await settleForcedStepRun(context, head, candidate, submission, input.runRoot, 'expired');
1579
+ }
1580
+ const releaseAndRefuse = async (code, path = '', phase = 'execution') => {
1581
+ stateValue(context.store.release(context.authority));
1582
+ stateValue(context.store.close());
1583
+ await context.owner.release();
1584
+ refuse(code, path, phase);
1585
+ };
1586
+ if (decision === 'terminal' || decision === 'reconcile_required') {
1587
+ return await releaseAndRefuse('AUTHORITY_REFUSED', '/leaseToken', 'execution');
1588
+ }
1589
+ const active = head?.progress.attempts.at(-1);
1590
+ const activeNode = active ? context.plan.orderedDAG.find(node => node.id === active.nodeId) : undefined;
1591
+ const originalRole = activeNode?.roleId ? context.plan.roles.find(role => role.roleId === activeNode.roleId) : undefined;
1592
+ if (!head || head.progress.stage.kind !== 'role_pre' || !active || active.finished !== null || !originalRole || originalRole.adapter !== 'delegated') {
1593
+ return await releaseAndRefuse('AUTHORITY_REFUSED', '/leaseToken', 'execution');
1594
+ }
1595
+ const lease = await readStepLease(context.directory);
1596
+ try {
1597
+ verifyLeaseToken(lease, context.lock.spec.runId, active.id, active.ordinal, input.leaseToken);
1598
+ }
1599
+ catch {
1600
+ return await releaseAndRefuse('AUTHORITY_REFUSED', '/leaseToken', 'execution');
1601
+ }
1602
+ const hostProtection = hostProtectionFromPolicy(meta.hostPolicy);
1603
+ const role = active.repair === 'format' ? { ...originalRole, policy: formatPolicy(originalRole.policy) } : originalRole;
1604
+ const disallowMutations = active.repair === 'format' ||
1605
+ !role.policy.tools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash');
1606
+ const candidateDir = join(resolve(input.runRoot), 'workspaces', context.lock.spec.runId, active.id, 'candidate');
1607
+ let previousModes;
1608
+ let scanned;
1609
+ let explicitSubmissionBytes = explicitVerdictBytes;
1610
+ try {
1611
+ previousModes = await resolveCurrentFileModes(context, head, candidate.files);
1612
+ scanned = await scanCandidateDirectory(candidateDir, context.source, context.plan.task, head.progress.candidate.digest, previousModes, disallowMutations, context.plan.budgets.overlay, context.artifacts, hostProtection);
1613
+ if (input.submissionFile !== undefined) {
1614
+ explicitSubmissionBytes = await readExplicitSubmissionFile(input.submissionFile);
1615
+ }
1616
+ }
1617
+ catch (error) {
1618
+ stateValue(context.store.release(context.authority));
1619
+ stateValue(context.store.close());
1620
+ await context.owner.release();
1621
+ throw error;
1622
+ }
1623
+ const unchangedFromBaseline = same(scanned.manifest, context.source.manifest);
1624
+ const effectiveStatus = input.status ?? (meta.mode === 'no-change' && unchangedFromBaseline ? 'no_change' : 'completed');
1625
+ const effectiveReason = input.reason ?? (effectiveStatus === 'failed' || effectiveStatus === 'blocked' ? 'delegated_' + effectiveStatus : null);
1626
+ let assistantText = null;
1627
+ let submissionBytes = null;
1628
+ const artifactSubmissionFile = context.plan.controls.submission.path === null ? undefined : scanned.files.find(file => file.name === context.plan.controls.submission.path);
1629
+ const ignoreArtifactPath = disallowMutations || explicitSubmissionBytes !== null || input.status !== undefined || input.reason !== undefined;
1630
+ if (explicitSubmissionBytes !== null) {
1631
+ assistantText = new TextDecoder('utf-8', { fatal: true }).decode(explicitSubmissionBytes);
1632
+ submissionBytes = explicitSubmissionBytes;
1633
+ }
1634
+ else if (artifactSubmissionFile === undefined || active.repair === 'format' || ignoreArtifactPath) {
1635
+ if (isVerdictStep(activeNode)) {
1636
+ const syntheticVerdict = {
1637
+ verdict: effectiveStatus === 'failed' ? 'fail' : effectiveStatus === 'blocked' ? 'human' : 'pass',
1638
+ summary: effectiveReason ?? 'Passed via step submit.',
1639
+ findings: [],
1640
+ };
1641
+ assistantText = canonical(syntheticVerdict);
1642
+ submissionBytes = new Uint8Array(Buffer.from(assistantText, 'utf8'));
1643
+ }
1644
+ else {
1645
+ const checkStatus = effectiveStatus === 'completed' || effectiveStatus === 'no_change'
1646
+ ? 'passed'
1647
+ : effectiveStatus === 'blocked'
1648
+ ? 'blocked'
1649
+ : 'failed';
1650
+ const checkReason = checkStatus === 'passed' ? null : (effectiveReason ?? 'check_not_satisfied');
1651
+ const synthetic = {
1652
+ version: 1,
1653
+ status: effectiveStatus,
1654
+ checks: context.plan.task.spec.acceptance.checks.map(check => ({
1655
+ checkId: check.id,
1656
+ status: checkStatus,
1657
+ evidenceId: null,
1658
+ reason: checkReason,
1659
+ })),
1660
+ reason: effectiveReason,
1661
+ };
1662
+ assistantText = canonical(synthetic);
1663
+ submissionBytes = new Uint8Array(Buffer.from(assistantText, 'utf8'));
1664
+ }
1665
+ }
1666
+ const payload = {
1667
+ format: 'delegated-capture.v2',
1668
+ version: 2,
1669
+ baseRevision: context.plan.task.spec.target.baseRevision,
1670
+ sourceRevision: context.plan.task.spec.target.sourceRevision,
1671
+ overlay: scanned.overlay,
1672
+ deleted: scanned.deleted,
1673
+ assistantText,
1674
+ status: effectiveStatus,
1675
+ reason: effectiveReason,
1676
+ };
1677
+ try {
1678
+ const bounds = overlayManifestBounds(context.plan.budgets.overlay);
1679
+ const canonicalManifest = identifyManifest(canonicalizeCandidateManifest(scanned.manifest), bounds.options);
1680
+ if (!canonicalManifest.ok || Buffer.byteLength(canonical(canonicalManifest.value.manifest), 'utf8') > bounds.manifestMaxBytes) {
1681
+ refuse('OUTPUT_LIMIT', '', 'execution');
1682
+ }
1683
+ await assertCanonicalMinimalOverlay(canonicalManifest.value.manifest, scanned.files, context.source, 'execution');
1684
+ const subject = bindSubject(context.lock, canonicalManifest.value.manifest, bounds.options);
1685
+ if (!subject.ok)
1686
+ refuse('ARTIFACT_INVALID', '', 'execution');
1687
+ const changed = !same(subject.value.candidateDigest, head.progress.candidate.digest);
1688
+ if (!changed && scanned.overlay.some(entry => (previousModes.get(entry.name) ?? '100644') !== entry.mode)) {
1689
+ refuse('ARTIFACT_INVALID', '', 'execution');
1690
+ }
1691
+ const nextGeneration = head.progress.candidate.generation + (changed ? 1 : 0);
1692
+ if (nextGeneration >= context.plan.capacity.V)
1693
+ refuse('ATTEMPT_LIMIT', '', 'execution');
1694
+ const payloadBytes = Buffer.from(canonical(payload), 'utf8');
1695
+ if (payloadBytes.byteLength > bounds.v2WorkspaceJsonMaxBytes)
1696
+ refuse('OUTPUT_LIMIT', '', 'execution');
1697
+ context.artifacts.vault.assertClean(payloadBytes);
1698
+ if (submissionBytes !== null) {
1699
+ if (submissionBytes.byteLength > 1_048_576)
1700
+ refuse('OUTPUT_LIMIT', '', 'execution');
1701
+ context.artifacts.vault.assertClean(submissionBytes);
1702
+ }
1703
+ }
1704
+ catch (error) {
1705
+ stateValue(context.store.release(context.authority));
1706
+ stateValue(context.store.close());
1707
+ await context.owner.release();
1708
+ throw error;
1709
+ }
1710
+ const cycle = new Cycle(context, head, candidate, false);
1711
+ cycle.submission = submission;
1712
+ let structureFailure;
1713
+ try {
1714
+ const captured = await captureDelegatedRole(context.store, context.authority, context.artifacts, context.lock, role, active, context.source, {
1715
+ candidateManifest: scanned.manifest,
1716
+ candidateFiles: scanned.files,
1717
+ payload,
1718
+ submissionBytes,
1719
+ }, hostProtection);
1720
+ structureFailure = await cycle.completeCapture(active, captured, { ignoreArtifactPath });
1721
+ }
1722
+ catch (error) {
1723
+ await cycle.deadline.dispose().catch(() => { });
1724
+ await cycle.events.suspend().catch(() => { });
1725
+ stateValue(context.store.release(context.authority));
1726
+ stateValue(context.store.close());
1727
+ await context.owner.release();
1728
+ throw error;
1729
+ }
1730
+ await unlink(join(context.directory, 'step-lease.json')).catch(() => { });
1731
+ await rm(join(resolve(input.runRoot), 'workspaces', context.lock.spec.runId, active.id), { recursive: true, force: true }).catch(() => { });
1732
+ await context.artifacts.cleanCasTempFiles().catch(() => { });
1733
+ await cycle.deadline.dispose();
1734
+ await cycle.events.suspend();
1735
+ return await runStepTickWithCycle(context, input.runRoot, meta, {
1736
+ head: cycle.head,
1737
+ candidate: cycle.candidate,
1738
+ submission: cycle.submission,
1739
+ adopt: false,
1740
+ advisoryObservations: cycle.advisoryObservations,
1741
+ }, { postStructureFailure: { nodeId: active.nodeId, code: structureFailure } });
1742
+ }, 'execution');
1743
+ }
1744
+ export function stepCancel(input, ports = {}) {
1745
+ return result(async () => {
1746
+ const fields = Object.keys(input);
1747
+ record(input, fields);
1748
+ if (fields.some(key => !['runRoot', 'runId', 'environment'].includes(key)) ||
1749
+ (input.environment !== undefined && typeof input.environment !== 'function')) {
1750
+ refuse('CONFIG_SCHEMA', '', 'execution');
1751
+ }
1752
+ validateGateUrlOverrides(ports.gateUrlOverrides, 'execution');
1753
+ const reopened = await reopenStepContext({
1754
+ runRoot: input.runRoot,
1755
+ runId: input.runId,
1756
+ ...(input.environment ? { environment: input.environment } : {}),
1757
+ ports,
1758
+ phase: 'execution',
1759
+ forceRecoveryMode: true,
1760
+ });
1761
+ if (reopened.decision === 'terminal') {
1762
+ try {
1763
+ return await retainedPrimary(reopened.context, reopened.head);
1764
+ }
1765
+ finally {
1766
+ stateValue(reopened.context.store.release(reopened.context.authority));
1767
+ stateValue(reopened.context.store.close());
1768
+ await reopened.context.owner.release();
1769
+ }
1770
+ }
1771
+ if (reopened.decision === 'reconcile_required') {
1772
+ return await settleForcedStepRun(reopened.context, reopened.head, reopened.candidate, reopened.submission, input.runRoot, 'reconcile_required');
1773
+ }
1774
+ return await settleForcedStepRun(reopened.context, reopened.head, reopened.candidate, reopened.submission, input.runRoot, 'cancelled');
1775
+ }, 'execution');
1776
+ }