@gpustack/loopwright 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (477) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +356 -2
  3. package/bin/loopwright.js +3 -0
  4. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
  5. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
  6. package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
  7. package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
  8. package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
  9. package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
  10. package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
  11. package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
  12. package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
  13. package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
  14. package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
  15. package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
  16. package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
  17. package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
  18. package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
  19. package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
  20. package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
  21. package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
  22. package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
  23. package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
  24. package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
  25. package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
  26. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
  27. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
  28. package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
  29. package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
  30. package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
  31. package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
  32. package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
  33. package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
  34. package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
  35. package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
  36. package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
  37. package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
  38. package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
  39. package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
  40. package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
  41. package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
  42. package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
  43. package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
  44. package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
  45. package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
  46. package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
  47. package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
  48. package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
  49. package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
  50. package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
  51. package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
  52. package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
  53. package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
  54. package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
  55. package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
  56. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
  57. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
  58. package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
  59. package/node_modules/@loopwright/agent-pi/dist/host-session.js +2083 -0
  60. package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
  61. package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
  62. package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
  63. package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
  64. package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
  65. package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
  66. package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
  67. package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
  68. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
  69. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
  70. package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
  71. package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
  72. package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
  73. package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
  74. package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
  75. package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
  76. package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
  77. package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
  78. package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
  79. package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
  80. package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
  81. package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
  82. package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
  83. package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
  84. package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
  85. package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
  86. package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
  87. package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
  88. package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
  89. package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
  90. package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
  91. package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
  92. package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
  93. package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
  94. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
  95. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
  96. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
  97. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
  98. package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
  99. package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
  100. package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
  101. package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
  102. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
  103. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
  104. package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
  105. package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
  106. package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
  107. package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
  108. package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
  109. package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
  110. package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
  111. package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
  112. package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
  113. package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
  114. package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
  115. package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
  116. package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
  117. package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
  118. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
  119. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
  120. package/node_modules/@loopwright/agent-pi/package.json +24 -0
  121. package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
  122. package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
  123. package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
  124. package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
  125. package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
  126. package/node_modules/@loopwright/cli/dist/closure.js +230 -0
  127. package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
  128. package/node_modules/@loopwright/cli/dist/draft.js +106 -0
  129. package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
  130. package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
  131. package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
  132. package/node_modules/@loopwright/cli/dist/index.js +5 -0
  133. package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
  134. package/node_modules/@loopwright/cli/dist/main.js +1855 -0
  135. package/node_modules/@loopwright/cli/package.json +16 -0
  136. package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
  137. package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
  138. package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
  139. package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
  140. package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
  141. package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
  142. package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
  143. package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
  144. package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
  145. package/node_modules/@loopwright/controller/dist/capture.js +587 -0
  146. package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
  147. package/node_modules/@loopwright/controller/dist/compile.js +402 -0
  148. package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
  149. package/node_modules/@loopwright/controller/dist/config.js +255 -0
  150. package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
  151. package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
  152. package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
  153. package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
  154. package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
  155. package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
  156. package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
  157. package/node_modules/@loopwright/controller/dist/errors.js +41 -0
  158. package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
  159. package/node_modules/@loopwright/controller/dist/events.js +228 -0
  160. package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
  161. package/node_modules/@loopwright/controller/dist/files.js +386 -0
  162. package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
  163. package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
  164. package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
  165. package/node_modules/@loopwright/controller/dist/gate.js +640 -0
  166. package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
  167. package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
  168. package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
  169. package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
  170. package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
  171. package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
  172. package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
  173. package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
  174. package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
  175. package/node_modules/@loopwright/controller/dist/index.js +21 -0
  176. package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
  177. package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
  178. package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
  179. package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
  180. package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
  181. package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
  182. package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
  183. package/node_modules/@loopwright/controller/dist/parser.js +200 -0
  184. package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
  185. package/node_modules/@loopwright/controller/dist/progress.js +904 -0
  186. package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
  187. package/node_modules/@loopwright/controller/dist/publication.js +329 -0
  188. package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
  189. package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
  190. package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
  191. package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
  192. package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
  193. package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
  194. package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
  195. package/node_modules/@loopwright/controller/dist/registry.js +374 -0
  196. package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
  197. package/node_modules/@loopwright/controller/dist/repair.js +102 -0
  198. package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
  199. package/node_modules/@loopwright/controller/dist/report.js +596 -0
  200. package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
  201. package/node_modules/@loopwright/controller/dist/retained.js +193 -0
  202. package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
  203. package/node_modules/@loopwright/controller/dist/rules.js +110 -0
  204. package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
  205. package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
  206. package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
  207. package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
  208. package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
  209. package/node_modules/@loopwright/controller/dist/schema.js +78 -0
  210. package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
  211. package/node_modules/@loopwright/controller/dist/source.js +872 -0
  212. package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
  213. package/node_modules/@loopwright/controller/dist/step.js +1776 -0
  214. package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
  215. package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
  216. package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
  217. package/node_modules/@loopwright/controller/dist/submission.js +292 -0
  218. package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
  219. package/node_modules/@loopwright/controller/dist/types.js +9 -0
  220. package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
  221. package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
  222. package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
  223. package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
  224. package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
  225. package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
  226. package/node_modules/@loopwright/controller/package.json +12 -0
  227. package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
  228. package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
  229. package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
  230. package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
  231. package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
  232. package/node_modules/@loopwright/core/dist/boundary.js +484 -0
  233. package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
  234. package/node_modules/@loopwright/core/dist/contracts.js +694 -0
  235. package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
  236. package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
  237. package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
  238. package/node_modules/@loopwright/core/dist/evidence.js +85 -0
  239. package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
  240. package/node_modules/@loopwright/core/dist/graph.js +44 -0
  241. package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
  242. package/node_modules/@loopwright/core/dist/identity.js +80 -0
  243. package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
  244. package/node_modules/@loopwright/core/dist/index.js +39 -0
  245. package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
  246. package/node_modules/@loopwright/core/dist/limits.js +59 -0
  247. package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
  248. package/node_modules/@loopwright/core/dist/results.js +98 -0
  249. package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
  250. package/node_modules/@loopwright/core/dist/scope.js +154 -0
  251. package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
  252. package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
  253. package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
  254. package/node_modules/@loopwright/core/dist/usage.js +56 -0
  255. package/node_modules/@loopwright/core/package.json +12 -0
  256. package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
  257. package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
  258. package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
  259. package/node_modules/@loopwright/decisions/dist/client.js +292 -0
  260. package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
  261. package/node_modules/@loopwright/decisions/dist/index.js +8 -0
  262. package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
  263. package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
  264. package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
  265. package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
  266. package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
  267. package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
  268. package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
  269. package/node_modules/@loopwright/decisions/dist/router.js +248 -0
  270. package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
  271. package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
  272. package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
  273. package/node_modules/@loopwright/decisions/dist/types.js +80 -0
  274. package/node_modules/@loopwright/decisions/package.json +12 -0
  275. package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
  276. package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
  277. package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
  278. package/node_modules/@loopwright/github-app/dist/config.js +297 -0
  279. package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
  280. package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
  281. package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
  282. package/node_modules/@loopwright/github-app/dist/index.js +13 -0
  283. package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
  284. package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
  285. package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
  286. package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
  287. package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
  288. package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
  289. package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
  290. package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
  291. package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
  292. package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
  293. package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
  294. package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
  295. package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
  296. package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
  297. package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
  298. package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
  299. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
  300. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
  301. package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
  302. package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
  303. package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
  304. package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
  305. package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
  306. package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
  307. package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
  308. package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
  309. package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
  310. package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
  311. package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
  312. package/node_modules/@loopwright/github-app/dist/types.js +14 -0
  313. package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
  314. package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
  315. package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
  316. package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
  317. package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
  318. package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
  319. package/node_modules/@loopwright/github-app/package.json +12 -0
  320. package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
  321. package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
  322. package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
  323. package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
  324. package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
  325. package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
  326. package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
  327. package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
  328. package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
  329. package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
  330. package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
  331. package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
  332. package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
  333. package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
  334. package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
  335. package/node_modules/@loopwright/hardware-runner/dist/worker.js +1646 -0
  336. package/node_modules/@loopwright/hardware-runner/package.json +12 -0
  337. package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
  338. package/node_modules/@loopwright/memory/dist/cas.js +510 -0
  339. package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
  340. package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
  341. package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
  342. package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
  343. package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
  344. package/node_modules/@loopwright/memory/dist/index.js +8 -0
  345. package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
  346. package/node_modules/@loopwright/memory/dist/schema.js +510 -0
  347. package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
  348. package/node_modules/@loopwright/memory/dist/selector.js +157 -0
  349. package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
  350. package/node_modules/@loopwright/memory/dist/store.js +554 -0
  351. package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
  352. package/node_modules/@loopwright/memory/dist/types.js +8 -0
  353. package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
  354. package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
  355. package/node_modules/@loopwright/memory/package.json +12 -0
  356. package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
  357. package/node_modules/@loopwright/state/dist/admission.js +199 -0
  358. package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
  359. package/node_modules/@loopwright/state/dist/boundary.js +194 -0
  360. package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
  361. package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
  362. package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
  363. package/node_modules/@loopwright/state/dist/clock.js +27 -0
  364. package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
  365. package/node_modules/@loopwright/state/dist/connection.js +391 -0
  366. package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
  367. package/node_modules/@loopwright/state/dist/errors.js +34 -0
  368. package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
  369. package/node_modules/@loopwright/state/dist/index.js +1 -0
  370. package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
  371. package/node_modules/@loopwright/state/dist/journal.js +72 -0
  372. package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
  373. package/node_modules/@loopwright/state/dist/model.js +58 -0
  374. package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
  375. package/node_modules/@loopwright/state/dist/ownership.js +45 -0
  376. package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
  377. package/node_modules/@loopwright/state/dist/pages.js +41 -0
  378. package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
  379. package/node_modules/@loopwright/state/dist/receipts.js +97 -0
  380. package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
  381. package/node_modules/@loopwright/state/dist/schema.js +41 -0
  382. package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
  383. package/node_modules/@loopwright/state/dist/settlement.js +129 -0
  384. package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
  385. package/node_modules/@loopwright/state/dist/store.js +100 -0
  386. package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
  387. package/node_modules/@loopwright/state/dist/types.js +1 -0
  388. package/node_modules/@loopwright/state/package.json +12 -0
  389. package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
  390. package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
  391. package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
  392. package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
  393. package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
  394. package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
  395. package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
  396. package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
  397. package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
  398. package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
  399. package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
  400. package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
  401. package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
  402. package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
  403. package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
  404. package/node_modules/@loopwright/taskpack/dist/sandbox.js +2605 -0
  405. package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
  406. package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
  407. package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
  408. package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
  409. package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
  410. package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
  411. package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
  412. package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
  413. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
  414. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
  415. package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
  416. package/node_modules/@loopwright/taskpack/dist/turnkey.js +7313 -0
  417. package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
  418. package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
  419. package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
  420. package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
  421. package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
  422. package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
  423. package/node_modules/@loopwright/taskpack/package.json +12 -0
  424. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
  425. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
  426. package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
  427. package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
  428. package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
  429. package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
  430. package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
  431. package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
  432. package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
  433. package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
  434. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
  435. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
  436. package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
  437. package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
  438. package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
  439. package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
  440. package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
  441. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
  442. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
  443. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
  444. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
  445. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
  446. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
  447. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
  448. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
  449. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
  450. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
  451. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
  452. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
  453. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
  454. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
  455. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
  456. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
  457. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
  458. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
  459. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
  460. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
  461. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
  462. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
  463. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
  464. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
  465. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
  466. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
  467. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
  468. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
  469. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
  470. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
  471. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
  472. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
  473. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
  474. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
  475. package/node_modules/package-lock.json +3021 -0
  476. package/package-lock.json +3021 -0
  477. package/package.json +52 -4
@@ -0,0 +1,2135 @@
1
+ import { mkdir, open, rm } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { openPiAdapterV2 } from '@loopwright/agent-pi';
6
+ import { LIMITS, admitTask, bindSubject, identifyManifest, validateRelativePath } from '@loopwright/core';
7
+ import { createLocalRun } from '@loopwright/state';
8
+ import { approvedState, selectRoleResources } from './config.js';
9
+ import { compilePlan } from './compile.js';
10
+ import { ControllerFailure, refuse, result, safeDiagnostic } from './errors.js';
11
+ import { privateDirectory, ArtifactStore, checkedRef, stateValue, streamVerifiedCasBlob } from './storage.js';
12
+ import { ControllerOwner, bootIdentity } from './ownership.js';
13
+ import { effectiveRunHostPolicy, hostProtectionFromPolicy, resolveStoreLeaseMs, validatePortPolicyFields } from './retained.js';
14
+ export { resolveStoreLeaseMs };
15
+ import { compareUtf16, freezeSource, gitObjectOid, materializeBaseline, overlayManifestBounds, verifySource } from './source.js';
16
+ import { ProgressStore, stableId, journal } from './progress.js';
17
+ import { captureRole, adoptRoleCapture, decodeCandidateCapture, nativeSessionId } from './capture.js';
18
+ import { appendHandoffPromptBlock, evaluateStepHandoffSelectors, materializeContextFilesDir, persistHandoffExtractsToCas, } from './handoff.js';
19
+ import { evaluateResourceActivationRules } from './rules.js';
20
+ import { boundFindingsForObservations, hydrateStepVerdicts, isVerdictStep, normalizeSubmission, parseStepVerdict, readSubmissionCandidateBytes, retainStepOutput, summarizeStepVerdictPreview, } from './submission.js';
21
+ import { prepareVerification, preflightVerification, Verifier, authenticatedCheck } from './verification.js';
22
+ import { prepareGate, Gate, GATE_OUTPUT_BYTES, authenticatedGate, validateGateUrlOverrides } from './gate.js';
23
+ import { prepareBenchmarkGate, BenchmarkGate, BENCHMARK_OUTPUT_BYTES, authenticatedBenchmarkGate, collectPriorGenerationVerifierBudget, createRateLimitedProgress, sealBenchmarkBaseTreeBundle, } from './benchmark-gate.js';
24
+ import { preparePublication, Publication, headRevision } from './publication.js';
25
+ import { evaluateControllerAcceptance, verifyControllerVerifierCasDescriptors, } from './acceptance.js';
26
+ import { nextNode, descendants, compactionTarget, resetSubgraphNodes, reworkSubgraph } from './scheduler.js';
27
+ import { failureSignature, rememberFailure, repairDisposition, formatPolicy, formatPrompt, reworkPrompt, verdictFormatPrompt } from './repair.js';
28
+ import { WorkDeadline } from './deadlines.js';
29
+ import { countDelegatedBudgets, observeParentExhaustion, schedulingSnapshot, isBudgetRefusal, isNoEffectBudgetRefusal, storeFactsCertain, refuseFromRoleOutcome } from './budget-observations.js';
30
+ import { ControllerEvents } from './events.js';
31
+ import { Finalizer, incident } from './finalize.js';
32
+ import { canonical, freeze, hash, id, isRecord, list, record, same, text } from './schema.js';
33
+ import { parsePrivateJson } from './parser.js';
34
+ import { CONTROLLER_LIMITS, } from './types.js';
35
+ const VALID_ADVISORY_SOURCES = new Set([
36
+ 'jev',
37
+ 'deterministic_fallback',
38
+ 'deterministic_heuristic',
39
+ 'user_override',
40
+ ]);
41
+ const VALID_ALIGNMENT_ROUTES = new Set(['continue', 'revise', 'needs_review', 'blocked']);
42
+ const VALID_CAPABILITY_TIERS = new Set(['fast', 'balanced', 'strongest']);
43
+ const VALID_SOFT_COMPACTION_DECISIONS = new Set(['compact', 'defer']);
44
+ export function isHaltedByVerdict(progress) {
45
+ const verdicts = progress?.stepVerdicts;
46
+ if (!verdicts || verdicts.length === 0)
47
+ return null;
48
+ const epoch = progress?.reworkEpoch ?? 0;
49
+ for (let i = verdicts.length - 1; i >= 0; i -= 1) {
50
+ const entry = verdicts[i];
51
+ if (entry.reworkEpoch !== epoch)
52
+ continue;
53
+ if (entry.verdict === 'fail')
54
+ return 'failed';
55
+ if (entry.verdict === 'human' || entry.verdict === 'rework')
56
+ return 'blocked';
57
+ }
58
+ return null;
59
+ }
60
+ export function normalizeWatchedPaths(raw, phase = 'admission') {
61
+ if (raw === undefined)
62
+ return undefined;
63
+ const items = list(raw, '/watchedPaths', LIMITS.patterns).map((entry, idx) => {
64
+ const str = text(entry, `/watchedPaths/${idx}`, LIMITS.path);
65
+ const checked = validateRelativePath(str);
66
+ if (!checked.ok)
67
+ refuse('CONFIG_SCHEMA', `/watchedPaths/${idx}`, phase);
68
+ return checked.value;
69
+ });
70
+ return freeze([...new Set(items)]);
71
+ }
72
+ function pruneRecordKeys(current, resetIds) {
73
+ if (!current)
74
+ return undefined;
75
+ const out = {};
76
+ let count = 0;
77
+ for (const [key, val] of Object.entries(current)) {
78
+ if (resetIds.has(key))
79
+ continue;
80
+ out[key] = val;
81
+ count += 1;
82
+ }
83
+ return count > 0 ? freeze(out) : undefined;
84
+ }
85
+ function cycleHostProtection(context) {
86
+ const persisted = effectiveRunHostPolicy(context.descriptor);
87
+ return hostProtectionFromPolicy({
88
+ policyProfile: context.ports.policyProfile ?? persisted.policyProfile,
89
+ allowWorkflowWrites: context.ports.allowWorkflowWrites ?? persisted.allowWorkflowWrites,
90
+ });
91
+ }
92
+ export function roleResourcesFor(loaded, plan, roleId) {
93
+ const all = approvedState(loaded).resources;
94
+ const declared = plan.task.spec.roles.find(item => item.id === roleId);
95
+ return selectRoleResources(all, declared?.resourceIds, 'execution');
96
+ }
97
+ function omitDraftNodeSnapshots(draft) {
98
+ const copy = { ...draft };
99
+ delete copy.nodeSubmissions;
100
+ delete copy.nodeCandidates;
101
+ return copy;
102
+ }
103
+ function isArtifactHandoffSourceStep(plan, stepId) {
104
+ return plan.orderedDAG.some(node => node.handoffs?.some(h => h.fromStep === stepId && h.source.kind === 'artifact') === true);
105
+ }
106
+ async function exclusiveJson(path, value) {
107
+ const bytes = Buffer.from(canonical(value));
108
+ if (bytes.length > 1048576)
109
+ refuse('OUTPUT_LIMIT', '', 'admission');
110
+ const file = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
111
+ try {
112
+ await file.writeFile(bytes);
113
+ await file.sync();
114
+ }
115
+ finally {
116
+ await file.close();
117
+ }
118
+ const parent = await open(resolve(path, '..'), constants.O_RDONLY | constants.O_NOFOLLOW);
119
+ try {
120
+ await parent.sync();
121
+ }
122
+ finally {
123
+ await parent.close();
124
+ }
125
+ }
126
+ export async function createCycle(input, ports) {
127
+ const state = approvedState(input.configuration), compiled = await compilePlan(input.configuration);
128
+ if (!compiled.ok)
129
+ throw new ControllerFailure(compiled.error);
130
+ const plan = compiled.value;
131
+ validatePortPolicyFields(ports, 'admission');
132
+ const normalizedWatchedPaths = normalizeWatchedPaths(ports.watchedPaths, 'admission');
133
+ validateGateUrlOverrides(ports.gateUrlOverrides, 'admission', input.configuration.registry.spec.gateEndpoints);
134
+ const hostPolicy = freeze({
135
+ policyProfile: ports.policyProfile ?? 'local',
136
+ allowWorkflowWrites: ports.allowWorkflowWrites === true,
137
+ });
138
+ const effectivePorts = {
139
+ ...ports,
140
+ policyProfile: hostPolicy.policyProfile,
141
+ allowWorkflowWrites: hostPolicy.allowWorkflowWrites,
142
+ ...(normalizedWatchedPaths !== undefined ? { watchedPaths: normalizedWatchedPaths } : {}),
143
+ };
144
+ const runId = id(input.runId), root = resolve(text(input.runRoot)), repository = resolve(text(input.repository)), directory = join(root, runId);
145
+ const excluded = [repository, process.cwd(), ...state.input.untrustedRoots];
146
+ await privateDirectory(root, excluded);
147
+ try {
148
+ await mkdir(directory, { mode: 0o700 });
149
+ }
150
+ catch (error) {
151
+ if (error.code === 'EEXIST')
152
+ refuse('OWNER_BUSY', '', 'admission');
153
+ throw error;
154
+ }
155
+ let owner = null, store = null;
156
+ try {
157
+ owner = await ControllerOwner.acquire(directory, runId, plan.planDigest);
158
+ const artifactDirectory = join(directory, 'artifacts');
159
+ await privateDirectory(artifactDirectory);
160
+ const artifacts = new ArtifactStore(artifactDirectory, owner, state.vault);
161
+ const jsonPaths = 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));
162
+ const source = await freezeSource(repository, plan.task, owner, artifacts, jsonPaths);
163
+ const overlayBounds = overlayManifestBounds(plan.budgets.overlay);
164
+ const admitted = admitTask(plan.task, { admissionId: 'admission.' + hash('loopwright.dev/controller/admission/v1\0' + runId + '\0' + plan.planDigest.hex).hex.slice(0, 40), runId });
165
+ if (!admitted.ok)
166
+ refuse('CONFIG_SCHEMA', '/spec/task', 'admission');
167
+ const lock = admitted.value, manifest = await artifacts.json('manifest', source.manifest, overlayBounds.manifestMaxBytes);
168
+ const initial = { manifest: source.manifest, ref: manifest, files: source.artifacts, baselineProofs: source.baselineProofs };
169
+ // Core identity is pure; complete byte preflight still precedes S02 create/claim and every initial dispatch.
170
+ for (const slot of plan.verifierSlots) {
171
+ if (slot.handler.implementation === 'gate.v1')
172
+ continue;
173
+ if (slot.handler.implementation === 'benchmark-gate.v1') {
174
+ prepareBenchmarkGate(plan, lock, slot.id, initial, 0, randomBytes(16).toString('hex'), input.configuration.registry.spec.gateEndpoints);
175
+ continue;
176
+ }
177
+ prepareVerification(plan, lock, slot.id, initial, initial, 0, randomBytes(16).toString('hex'));
178
+ }
179
+ const planRef = await artifacts.json('plan', plan, 4194304), lockRef = await artifacts.json('task-lock', lock, 4194304);
180
+ const adapters = [...new Set(plan.task.spec.roles.map(role => role.adapter))].sort().map(id => ({ id, version: '0.0.0' }));
181
+ const identity = { directory: join(directory, 'state'), storeId: 'store.' + hash('loopwright.dev/controller/store/v1\0' + runId).hex.slice(0, 40), lock,
182
+ policy: { version: 1, leaseMs: resolveStoreLeaseMs(input.configuration, plan), cost: 'observe_only' }, binding: { coreApiVersion: 'loopwright.dev/v1alpha1', hostVersion: 's04-controller-v1', adapters,
183
+ resourceVersion: plan.task.spec.trustedContext.revision, clockEpoch: 'boot.' + hash(await bootIdentity()).hex.slice(0, 40) } };
184
+ const descriptor = { version: 1, identity, plan: planRef, source: source.inventory, sourceWorkspace: source.workspace,
185
+ configuration: { configPath: state.input.configPath, registryPath: state.input.registryPath, registrySha256: state.input.registrySha256, ...(state.input.roleModelOverrides !== undefined ? { roleModelOverrides: state.input.roleModelOverrides } : {}) }, repository, hostPolicy };
186
+ state.vault.assertClean(descriptor);
187
+ await exclusiveJson(join(directory, 'run.json'), descriptor);
188
+ store = stateValue(createLocalRun(identity));
189
+ const current = stateValue(store.inspect()), authority = stateValue(store.claim({ ownerId: 'controller.' + owner.nonce, expectedGeneration: current.owner.generation, expectedRevision: current.revision, mode: 'active' })).authority;
190
+ const progress = new ProgressStore(store, authority, artifacts, plan, lock, planRef, source.inventory);
191
+ // lockRef is private provenance; source/plan remain the four-ref checkpoint roots.
192
+ await artifacts.json('admission', { version: 1, lock: lockRef, source: source.inventory, plan: planRef }, 65536);
193
+ return { loaded: input.configuration, plan, lock, directory, source, store, authority, owner, artifacts, progress, descriptor, signal: input.signal ?? new AbortController().signal, onEvent: input.onEvent, ports: effectivePorts };
194
+ }
195
+ catch (error) {
196
+ if (store)
197
+ stateValue(store.close());
198
+ if (owner)
199
+ await owner.release();
200
+ throw error;
201
+ }
202
+ }
203
+ function extractGateVerdictDetail(checked, isBenchmark) {
204
+ const trusted = isBenchmark ? authenticatedBenchmarkGate(checked) : authenticatedGate(checked);
205
+ const outCap = isBenchmark ? BENCHMARK_OUTPUT_BYTES : GATE_OUTPUT_BYTES;
206
+ try {
207
+ const parsed = parsePrivateJson(Buffer.from(trusted.outputBytes), outCap);
208
+ const verdict = isRecord(parsed) && isRecord(parsed.verdict) ? parsed.verdict : null;
209
+ if (!verdict)
210
+ return undefined;
211
+ let rawDetail;
212
+ if (isBenchmark && typeof verdict.detail === 'string' && verdict.detail.length > 0) {
213
+ rawDetail = verdict.detail;
214
+ }
215
+ else if (typeof verdict.reason === 'string' && verdict.reason.length > 0) {
216
+ rawDetail = verdict.reason;
217
+ }
218
+ return rawDetail !== undefined ? Array.from(rawDetail).slice(0, 256).join('') : undefined;
219
+ }
220
+ catch {
221
+ return undefined;
222
+ }
223
+ }
224
+ export class Cycle {
225
+ context;
226
+ resumeAdoption;
227
+ head;
228
+ candidate;
229
+ submission = null;
230
+ checks = new Map();
231
+ refusals = new Map();
232
+ deadline;
233
+ events;
234
+ verifier;
235
+ gate;
236
+ benchmarkGate;
237
+ publisher;
238
+ advisoryObservations = [];
239
+ #activeAdapter = null;
240
+ #candidateKnown = true;
241
+ #cleanup = 'complete';
242
+ #baseTreeBundles = new Map();
243
+ #publicationObservation = { status: 'not_run', reason: 'disabled', receipt: null };
244
+ constructor(context, head = null, candidate, resumeAdoption) {
245
+ this.context = context;
246
+ this.resumeAdoption = resumeAdoption;
247
+ this.head = head;
248
+ this.candidate = candidate ?? { manifest: context.source.manifest, ref: { name: '', digest: hash(''), byteLength: 0 }, files: context.source.artifacts, baselineProofs: context.source.baselineProofs };
249
+ this.deadline = new WorkDeadline(context.store, context.authority, context.plan.controls.drainReserveMs, context.signal);
250
+ this.events = new ControllerEvents(context.store, context.artifacts, context.onEvent, () => this.deadline.stop('OUTPUT_LIMIT'), head?.progress.eventSequence ?? 0);
251
+ if (head)
252
+ this.events.setDelegatedBudget(countDelegatedBudgets(context.plan, head.progress.attempts));
253
+ const overlayOpts = overlayManifestBounds(context.plan.budgets.overlay).options;
254
+ this.verifier = new Verifier(context.store, context.authority, context.artifacts, context.plan, context.lock, () => { const bound = bindSubject(context.lock, this.candidate.manifest, overlayOpts); if (!bound.ok)
255
+ refuse('ARTIFACT_INVALID', '', 'verification'); return bound.value; });
256
+ this.gate = new Gate(context.store, context.authority, context.artifacts, context.plan, context.lock, ref => approvedState(context.loaded).vault.resolveNetworkCredential(ref), () => { const bound = bindSubject(context.lock, this.candidate.manifest, overlayOpts); if (!bound.ok)
257
+ refuse('ARTIFACT_INVALID', '', 'verification'); return bound.value; }, detail => this.events.push('gate_waiting', null, null, null, [], detail), context.ports.gateUrlOverrides);
258
+ this.benchmarkGate = new BenchmarkGate(context.store, context.authority, context.artifacts, context.plan, context.lock, ref => approvedState(context.loaded).vault.resolveNetworkCredential(ref), () => { const bound = bindSubject(context.lock, this.candidate.manifest, overlayOpts); if (!bound.ok)
259
+ refuse('ARTIFACT_INVALID', '', 'verification'); return bound.value; }, detail => this.events.push('gate_waiting', null, null, null, [], detail), context.ports.gateUrlOverrides, (gen, excludeSlotId) => collectPriorGenerationVerifierBudget(context.plan, context.artifacts, gen, excludeSlotId, this.checks, this.head?.progress.verifierReceipts));
260
+ this.publisher = new Publication(context.store, context.authority, context.artifacts, context.plan, context.lock, ref => approvedState(context.loaded).vault.resolveNetworkCredential(ref), () => { const bound = bindSubject(context.lock, this.candidate.manifest, overlayOpts); if (!bound.ok)
261
+ refuse('ARTIFACT_INVALID', '', 'verification'); return bound.value; }, context.descriptor.repository);
262
+ if (head && head.progress.publication.status !== 'idle') {
263
+ const prior = head.progress.publication;
264
+ this.#publicationObservation = prior.status === 'confirmed' ? { status: 'confirmed', reason: null, receipt: prior.receipt }
265
+ : prior.status === 'failed' ? { status: 'failed', reason: 'not_executed', receipt: prior.receipt } : { status: 'unresolved', reason: 'unresolved', receipt: null };
266
+ }
267
+ }
268
+ get generation() { return this.head?.progress.candidate.generation ?? 0; }
269
+ get reworkEpoch() { return this.head?.progress.reworkEpoch ?? 0; }
270
+ get candidateKnown() { return this.#candidateKnown; }
271
+ markCandidateUnknown() { this.#candidateKnown = false; }
272
+ #overlayBounds() { return overlayManifestBounds(this.context.plan.budgets.overlay); }
273
+ #contextUtilization() {
274
+ const view = stateValue(this.context.store.inspect());
275
+ const charged = Number(view.ledger.chargedTokens.safeValue ?? 0);
276
+ const total = this.context.lock.spec.contract.spec.budgets.totalTokens;
277
+ return total > 0 ? Math.min(1, Math.max(0, charged / total)) : 0;
278
+ }
279
+ #failedVerificationLoops() {
280
+ return (this.head?.progress.attempts.filter(a => a.repair === 'implementation').length ?? 0) + this.reworkEpoch;
281
+ }
282
+ haltedVerdictStatus() {
283
+ return isHaltedByVerdict(this.head?.progress);
284
+ }
285
+ async activeReworkForNode(nodeId) {
286
+ const epoch = this.reworkEpoch;
287
+ if (epoch === 0)
288
+ return null;
289
+ const verdicts = this.head?.progress.stepVerdicts ?? [];
290
+ const triggering = [...verdicts].reverse().find(item => item.reworkEpoch === epoch - 1 && item.verdict === 'rework');
291
+ if (!triggering)
292
+ return null;
293
+ const fromNode = this.context.plan.orderedDAG.find(item => item.id === triggering.stepId);
294
+ if (!fromNode?.onRework)
295
+ return null;
296
+ const targetNode = this.context.plan.orderedDAG.find(item => item.id === nodeId);
297
+ if (!targetNode || targetNode.kind !== 'agent' || targetNode.handler.implementation === 'pi.compact.v1' || targetNode.handler.parameters.purpose === 'review') {
298
+ return null;
299
+ }
300
+ if (!reworkSubgraph(this.context.plan, fromNode.onRework.rejectTo).includes(nodeId))
301
+ return null;
302
+ let hydrated;
303
+ try {
304
+ hydrated = parseStepVerdict(await this.context.artifacts.read(triggering.raw, 1_048_576));
305
+ }
306
+ catch {
307
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
308
+ }
309
+ return freeze({
310
+ epoch,
311
+ count: this.head?.progress.reworkCounts?.[fromNode.id] ?? 1,
312
+ maxReworks: fromNode.onRework.maxReworks,
313
+ fromStepId: fromNode.id,
314
+ summary: hydrated.summary,
315
+ findings: hydrated.findings,
316
+ });
317
+ }
318
+ async adviseCapabilityRouting(nodeId, role, purpose, roleResources) {
319
+ const hook = this.context.ports.decisions?.routeCapabilityTier;
320
+ if (!hook)
321
+ return;
322
+ const candidateSkills = roleResources.filter(item => item.kind === 'skill').map(item => item.id);
323
+ try {
324
+ const routed = await hook({
325
+ runId: this.context.lock.spec.runId,
326
+ stepId: nodeId,
327
+ roleId: role.roleId,
328
+ taskKind: purpose,
329
+ estimatedFilesCount: this.candidate.files.length,
330
+ hasFailingTests: this.currentChecks().some(c => c.status === 'failed'),
331
+ requiresArchitectureChange: false,
332
+ candidateSkills,
333
+ pinnedModel: { provider: role.policy.selection.provider, model: role.policy.selection.model, thinking: role.policy.selection.thinking },
334
+ });
335
+ if (routed === null || routed === undefined)
336
+ return;
337
+ if (!isRecord(routed) ||
338
+ typeof routed.tier !== 'string' ||
339
+ !VALID_CAPABILITY_TIERS.has(routed.tier) ||
340
+ typeof routed.source !== 'string' ||
341
+ !VALID_ADVISORY_SOURCES.has(routed.source)) {
342
+ throw new Error('invalid_capability_routing_output');
343
+ }
344
+ this.advisoryObservations.push({
345
+ intent: 'route_capability_tier',
346
+ stepId: nodeId,
347
+ tier: routed.tier,
348
+ pinnedModelPreserved: true,
349
+ source: routed.source,
350
+ });
351
+ }
352
+ catch {
353
+ this.advisoryObservations.push({
354
+ intent: 'route_capability_tier',
355
+ stepId: nodeId,
356
+ pinnedModelPreserved: true,
357
+ source: 'deterministic_fallback',
358
+ });
359
+ }
360
+ }
361
+ async evaluateAlignment(trigger, targetStepId, candidateDigest) {
362
+ const hook = this.context.ports.decisions?.evaluateCycleAlignment;
363
+ if (!hook)
364
+ return true;
365
+ try {
366
+ const output = await hook({
367
+ runId: this.context.lock.spec.runId,
368
+ trigger,
369
+ targetStepId,
370
+ contractHash: this.context.lock.spec.contractHash,
371
+ baseRevision: this.context.lock.spec.contract.spec.target.baseRevision,
372
+ candidateDigest,
373
+ reworkEpoch: this.reworkEpoch,
374
+ remainingAttempts: Math.max(0, this.context.plan.capacity.A - (this.head?.progress.attempts.length ?? 0)),
375
+ contextUtilization: this.#contextUtilization(),
376
+ failedVerificationLoops: this.#failedVerificationLoops(),
377
+ });
378
+ if (output === null || output === undefined)
379
+ return true;
380
+ if (!isRecord(output) ||
381
+ typeof output.route !== 'string' ||
382
+ !VALID_ALIGNMENT_ROUTES.has(output.route) ||
383
+ typeof output.precheckPassed !== 'boolean' ||
384
+ typeof output.source !== 'string' ||
385
+ !VALID_ADVISORY_SOURCES.has(output.source)) {
386
+ throw new Error('invalid_alignment_output');
387
+ }
388
+ this.advisoryObservations.push({
389
+ intent: 'evaluate_cycle_alignment',
390
+ trigger,
391
+ targetStepId,
392
+ route: output.route,
393
+ precheckPassed: output.precheckPassed,
394
+ source: output.source,
395
+ });
396
+ return output.route !== 'blocked' && output.route !== 'needs_review';
397
+ }
398
+ catch {
399
+ this.advisoryObservations.push({
400
+ intent: 'evaluate_cycle_alignment',
401
+ trigger,
402
+ targetStepId,
403
+ route: 'continue',
404
+ precheckPassed: true,
405
+ source: 'deterministic_fallback',
406
+ });
407
+ return true;
408
+ }
409
+ }
410
+ async triageCandidateDiffAdvisory(stepId, attemptId, candidateDigest, files, deleted) {
411
+ const hook = this.context.ports.decisions?.triageCandidateDiff;
412
+ if (!hook)
413
+ return;
414
+ let modifiedFiles = files;
415
+ const effectiveDeleted = [...deleted];
416
+ if (this.context.source.version === 1) {
417
+ const baseByPath = new Map(this.context.source.artifacts.map(item => [item.name, item.bytes]));
418
+ const present = new Set(files.map(item => item.name));
419
+ modifiedFiles = files.filter(file => {
420
+ const baseBytes = baseByPath.get(file.name);
421
+ if (baseBytes === undefined)
422
+ return true;
423
+ if ('bytes' in file)
424
+ return !Buffer.from(baseBytes).equals(Buffer.from(file.bytes));
425
+ return baseBytes.byteLength !== file.byteLength || hash(baseBytes).hex !== file.digest.hex;
426
+ });
427
+ for (const base of this.context.source.artifacts) {
428
+ if (!present.has(base.name))
429
+ effectiveDeleted.push(base.name);
430
+ }
431
+ }
432
+ const changedFiles = [...new Set([...modifiedFiles.map(f => f.name), ...effectiveDeleted])].sort();
433
+ const touchedPackages = [
434
+ ...new Set(changedFiles
435
+ .map(path => (/^packages\/([^/]+)\//.exec(path)?.[1] ?? null))
436
+ .filter((pkg) => pkg !== null)),
437
+ ].sort();
438
+ let addedLines = 0;
439
+ for (const file of modifiedFiles) {
440
+ if ('bytes' in file) {
441
+ if (file.bytes.byteLength === 0)
442
+ continue;
443
+ if (file.bytes.byteLength > 262_144) {
444
+ addedLines += 1;
445
+ continue;
446
+ }
447
+ let count = 0;
448
+ for (let i = 0; i < file.bytes.byteLength; i++)
449
+ if (file.bytes[i] === 10)
450
+ count++;
451
+ addedLines += Math.max(1, count);
452
+ }
453
+ else {
454
+ if (file.byteLength === 0)
455
+ continue;
456
+ if (file.byteLength > 262_144) {
457
+ addedLines += 1;
458
+ continue;
459
+ }
460
+ let count = 0;
461
+ try {
462
+ await streamVerifiedCasBlob(this.context.artifacts.directory, {
463
+ name: file.name,
464
+ sha256: file.digest.hex,
465
+ byteLength: file.byteLength,
466
+ uri: 'cas://sha256/' + file.digest.hex,
467
+ path: file.blobPath,
468
+ }, chunk => {
469
+ for (let i = 0; i < chunk.byteLength; i++)
470
+ if (chunk[i] === 10)
471
+ count++;
472
+ }, 'execution');
473
+ addedLines += Math.max(1, count);
474
+ }
475
+ catch (error) {
476
+ if (error instanceof ControllerFailure)
477
+ throw error;
478
+ addedLines += 1;
479
+ }
480
+ }
481
+ }
482
+ const summary = freeze({
483
+ changedFiles,
484
+ addedLines,
485
+ deletedLines: effectiveDeleted.length,
486
+ touchedPackages,
487
+ redactedHunkSummaries: changedFiles.slice(0, 16).map(f => 'modified ' + f),
488
+ });
489
+ try {
490
+ const output = await hook({
491
+ runId: this.context.lock.spec.runId,
492
+ stepId,
493
+ attemptId,
494
+ candidateDigest,
495
+ summary,
496
+ });
497
+ if (output === null || output === undefined)
498
+ return;
499
+ if (!isRecord(output) ||
500
+ !Array.isArray(output.escalated) ||
501
+ typeof output.source !== 'string' ||
502
+ !VALID_ADVISORY_SOURCES.has(output.source)) {
503
+ throw new Error('invalid_triage_output');
504
+ }
505
+ // Non-delegable authority invariant: triage escalations are strictly advisory; verificationCertified is forced false.
506
+ this.advisoryObservations.push({
507
+ intent: 'triage_candidate_diff',
508
+ stepId,
509
+ attemptId,
510
+ escalatedCount: output.escalated.length,
511
+ verificationCertified: false,
512
+ source: output.source,
513
+ });
514
+ }
515
+ catch {
516
+ this.advisoryObservations.push({
517
+ intent: 'triage_candidate_diff',
518
+ stepId,
519
+ attemptId,
520
+ escalatedCount: 0,
521
+ verificationCertified: false,
522
+ source: 'deterministic_fallback',
523
+ });
524
+ }
525
+ }
526
+ get draft() {
527
+ if (!this.head)
528
+ refuse('RECOVERY_REQUIRED', '', 'execution');
529
+ return { ...this.head.progress, eventSequence: this.events.sequence };
530
+ }
531
+ async publish(draft, phase) {
532
+ this.head = await this.context.progress.publish({ ...draft, eventSequence: this.events.sequence }, phase);
533
+ this.events.setDelegatedBudget(countDelegatedBudgets(this.context.plan, this.head.progress.attempts));
534
+ await this.context.ports.afterCheckpoint?.(phase, this.head);
535
+ }
536
+ async bootstrap() {
537
+ const { plan, lock, source, artifacts } = this.context, bounds = this.#overlayBounds();
538
+ const manifest = await artifacts.json('manifest', source.manifest, bounds.manifestMaxBytes);
539
+ this.candidate = { manifest: source.manifest, ref: manifest, files: source.artifacts, baselineProofs: source.baselineProofs };
540
+ const bound = bindSubject(lock, source.manifest, bounds.options);
541
+ if (!bound.ok)
542
+ refuse('ARTIFACT_INVALID', '', 'admission');
543
+ await this.events.push('admission', null);
544
+ await this.publish({ version: 2, runId: lock.spec.runId, lockHash: lock.spec.lockHash, stage: { kind: 'bootstrap', phase: 'bootstrap', capacity: plan.capacity },
545
+ nodes: plan.orderedDAG.map(node => ({ id: node.id, state: 'pending' })), attempts: [], nativeCheckpoints: [], submission: null, publication: { status: 'idle', operationId: null, receipt: null },
546
+ candidate: { manifest, digest: bound.value.candidateDigest, generation: 0, workspace: source.workspace, privateSession: null }, failures: [], verifierReceipts: [], verifierRefusals: [], eventSequence: this.events.sequence, terminalIntent: null }, 'bootstrap');
547
+ }
548
+ async guard() { this.deadline.assert(); await this.context.owner.assertCurrent(); await verifySource(this.context.source, this.context.plan.task, this.context.owner); this.deadline.assert(); }
549
+ async #finalizeVerifierPost(slotId, checked, ordinal, phase) {
550
+ const { plan, artifacts } = this.context;
551
+ const slot = plan.verifierSlots[ordinal];
552
+ const impl = slot.handler.implementation;
553
+ const gateSlot = impl === 'gate.v1';
554
+ const benchmarkSlot = impl === 'benchmark-gate.v1';
555
+ const isPreemptedBenchmark = benchmarkSlot && (checked.reason === 'BENCHMARK_PREEMPTED' || authenticatedBenchmarkGate(checked).retryablePreemption);
556
+ let draft = {
557
+ ...this.draft,
558
+ stage: { ...this.draft.stage, kind: 'verifier_post' },
559
+ verifierReceipts: this.draft.verifierReceipts.map(item => item.slot === slotId && item.generation === this.generation ? { ...item, output: checked.output, receipt: checked.receipt } : item),
560
+ };
561
+ if (checked.status === 'failed' && !isPreemptedBenchmark) {
562
+ const trusted = gateSlot
563
+ ? authenticatedGate(checked)
564
+ : benchmarkSlot
565
+ ? authenticatedBenchmarkGate(checked)
566
+ : authenticatedCheck(checked);
567
+ const stable = hash(canonical({
568
+ slot: slot.id,
569
+ handler: slot.handler.digest,
570
+ reason: checked.reason,
571
+ method: trusted.evidence.spec.method,
572
+ parameters: slot.handler.parameters,
573
+ }));
574
+ const signature = failureSignature({
575
+ category: 'implementation',
576
+ codes: [checked.reason],
577
+ handler: slot.handler.implementation,
578
+ handlerVersion: 1,
579
+ target: typeof slot.handler.parameters.path === 'string' ? slot.handler.parameters.path : slot.id,
580
+ candidate: trusted.subject.candidateDigest,
581
+ evidence: [stable],
582
+ });
583
+ draft = { ...draft, failures: rememberFailure(draft.failures, signature, this.generation, checked.output) };
584
+ }
585
+ const reworkCheckNode = checked.status === 'failed' && !isPreemptedBenchmark
586
+ ? plan.orderedDAG.find(node => {
587
+ if (node.kind !== 'check' || !node.onRework || node.handler.id !== slot.handler.id)
588
+ return false;
589
+ if (!same(node.handler.parameters, slot.handler.parameters))
590
+ return false;
591
+ const state = draft.nodes.find(item => item.id === node.id)?.state;
592
+ if (state !== 'pending' && state !== 'running')
593
+ return false;
594
+ return node.dependsOn.every(parent => draft.nodes.find(item => item.id === parent)?.state === 'completed');
595
+ })
596
+ : undefined;
597
+ if (reworkCheckNode?.onRework) {
598
+ const detail = (gateSlot || benchmarkSlot)
599
+ ? extractGateVerdictDetail(checked, benchmarkSlot)
600
+ : undefined;
601
+ const reasonText = checked.reason ?? 'check_failed';
602
+ const summary = detail
603
+ ? `Check ${reworkCheckNode.id} (${checked.checkId}) failed: ${reasonText} — ${detail}`
604
+ : `Check ${reworkCheckNode.id} (${checked.checkId}) failed: ${reasonText}`;
605
+ const findingPath = typeof slot.handler.parameters.path === 'string' ? slot.handler.parameters.path : undefined;
606
+ const finding = freeze({
607
+ title: Array.from(`Check ${checked.checkId} failed (${reasonText})`).slice(0, 256).join(''),
608
+ severity: 'high',
609
+ ...(findingPath !== undefined ? { path: findingPath } : {}),
610
+ evidence: detail ? `${reasonText}: ${detail}` : reasonText,
611
+ });
612
+ const verdictPayload = freeze({
613
+ verdict: 'rework',
614
+ summary,
615
+ findings: freeze([finding]),
616
+ });
617
+ const raw = await artifacts.put('step-verdict', Buffer.from(canonical(verdictPayload), 'utf8'), 1_048_576);
618
+ const currentEpoch = draft.reworkEpoch ?? 0;
619
+ const usedReworks = draft.reworkCounts?.[reworkCheckNode.id] ?? 0;
620
+ const canRework = usedReworks < reworkCheckNode.onRework.maxReworks && this.generation + 1 < plan.capacity.V;
621
+ const alignmentOk = canRework ? await this.evaluateAlignment('rework', reworkCheckNode.onRework.rejectTo, draft.candidate.digest) : false;
622
+ const reworked = canRework && alignmentOk;
623
+ const nextGen = this.generation + (reworked ? 1 : 0);
624
+ const storedVerdict = freeze({
625
+ attemptId: null,
626
+ stepId: reworkCheckNode.id,
627
+ roleId: null,
628
+ reworkEpoch: currentEpoch,
629
+ generation: nextGen,
630
+ raw,
631
+ verdict: 'rework',
632
+ summaryPreview: summarizeStepVerdictPreview(verdictPayload.summary),
633
+ findingCount: verdictPayload.findings.length,
634
+ });
635
+ const nextStepVerdicts = freeze([...(draft.stepVerdicts ?? []), storedVerdict]);
636
+ if (reworked) {
637
+ const resetSet = new Set(reworkSubgraph(plan, reworkCheckNode.onRework.rejectTo));
638
+ const prunedSubs = pruneRecordKeys(draft.nodeSubmissions, resetSet);
639
+ const prunedCands = pruneRecordKeys(draft.nodeCandidates, resetSet);
640
+ const restDraft = omitDraftNodeSnapshots(draft);
641
+ const markedDone = restDraft.nodes.map(item => (item.id === reworkCheckNode.id ? { ...item, state: 'completed' } : item));
642
+ draft = {
643
+ ...restDraft,
644
+ candidate: { ...restDraft.candidate, generation: nextGen },
645
+ nodes: [...resetSubgraphNodes(plan, markedDone, reworkCheckNode.onRework.rejectTo)],
646
+ reworkEpoch: currentEpoch + 1,
647
+ reworkCounts: freeze({ ...(restDraft.reworkCounts ?? {}), [reworkCheckNode.id]: usedReworks + 1 }),
648
+ ...(prunedSubs !== undefined ? { nodeSubmissions: prunedSubs } : {}),
649
+ ...(prunedCands !== undefined ? { nodeCandidates: prunedCands } : {}),
650
+ stepVerdicts: nextStepVerdicts,
651
+ };
652
+ }
653
+ else {
654
+ draft = {
655
+ ...draft,
656
+ nodes: draft.nodes.map(item => item.id === reworkCheckNode.id ? { ...item, state: 'blocked' } : item.state === 'pending' ? { ...item, state: 'not_run' } : item),
657
+ stepVerdicts: nextStepVerdicts,
658
+ };
659
+ }
660
+ }
661
+ else {
662
+ draft = { ...draft, nodes: this.nodeDispositions(draft.nodes, this.generation) };
663
+ }
664
+ await this.publish(draft, phase + '.post');
665
+ }
666
+ async #ensureBenchmarkBaseTreeBundle() {
667
+ if (this.context.source.version !== 2 || this.candidate.manifest.spec.baseTree === undefined)
668
+ return undefined;
669
+ const key = String(this.generation) + ':' + hash(canonical(this.candidate.manifest)).hex;
670
+ if (this.#baseTreeBundles.has(key)) {
671
+ return this.#baseTreeBundles.get(key) ?? undefined;
672
+ }
673
+ const bundleProgress = createRateLimitedProgress(() => {
674
+ this.deadline.assert(true);
675
+ }, 1_000);
676
+ const sealed = await sealBenchmarkBaseTreeBundle(this.context.source, this.candidate.manifest, this.context.artifacts, this.context.owner, this.deadline.abort.signal, bundleProgress);
677
+ this.#baseTreeBundles.set(key, sealed ?? null);
678
+ return sealed;
679
+ }
680
+ async runVerifier(slotId) {
681
+ const { plan, lock, artifacts } = this.context, bounds = this.#overlayBounds();
682
+ const existing = this.head.progress.verifierReceipts.find(item => item.slot === slotId && item.generation === this.generation);
683
+ const negative = this.head.progress.verifierRefusals.find(item => item.slot === slotId && item.generation === this.generation);
684
+ if (negative) {
685
+ const known = this.refusals.get(slotId + ':' + this.generation);
686
+ if (known)
687
+ return known;
688
+ const source = { manifest: this.context.source.manifest, ref: await artifacts.json('manifest', this.context.source.manifest, bounds.manifestMaxBytes), files: this.context.source.artifacts, baselineProofs: this.context.source.baselineProofs };
689
+ const prepared = preflightVerification(plan, lock, slotId, source, this.candidate, this.generation, negative.producerNonce);
690
+ if (prepared.kind !== 'refused')
691
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
692
+ await this.verifier.validateStoredRefusal(prepared.prepared, negative);
693
+ const ordinal = plan.verifierSlots.findIndex(slot => slot.id === slotId), phase = 'verify.' + this.generation + '.' + ordinal;
694
+ if (!this.head.progress.stage.consumed.includes(phase + '.post')) {
695
+ if (this.draft.stage.phase !== phase + '.pre')
696
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
697
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'verifier_post' }, nodes: this.nodeDispositions(this.draft.nodes, this.generation, { slotId, status: 'blocked' }) }, phase + '.post');
698
+ }
699
+ const restored = await this.verifier.restoreRefusal(prepared.prepared, negative);
700
+ this.refusals.set(slotId + ':' + this.generation, restored);
701
+ return restored;
702
+ }
703
+ if (existing) {
704
+ const key = slotId + ':' + this.generation, known = this.checks.get(key);
705
+ if (known)
706
+ return known;
707
+ const impl = plan.verifierSlots.find(item => item.id === slotId).handler.implementation;
708
+ const gateSlot = impl === 'gate.v1';
709
+ const benchmarkSlot = impl === 'benchmark-gate.v1';
710
+ const baseTreeBundle = benchmarkSlot ? await this.#ensureBenchmarkBaseTreeBundle() : undefined;
711
+ const job = gateSlot
712
+ ? prepareGate(plan, lock, slotId, this.candidate, this.generation, existing.producerNonce, this.context.loaded.registry.spec.gateEndpoints)
713
+ : benchmarkSlot
714
+ ? prepareBenchmarkGate(plan, lock, slotId, this.candidate, this.generation, existing.producerNonce, this.context.loaded.registry.spec.gateEndpoints, baseTreeBundle)
715
+ : prepareVerification(plan, lock, slotId, { manifest: this.context.source.manifest, ref: await artifacts.json('manifest', this.context.source.manifest, bounds.manifestMaxBytes), files: this.context.source.artifacts, baselineProofs: this.context.source.baselineProofs }, this.candidate, this.generation, existing.producerNonce);
716
+ const operation = this.context.store.getOperation(job.operationId);
717
+ const isFresh = !operation.ok && operation.error.code === 'RECORD_NOT_FOUND' && existing.receipt === null;
718
+ const restored = isFresh
719
+ ? await (gateSlot
720
+ ? this.gate.run(job, this.deadline.abort.signal)
721
+ : benchmarkSlot
722
+ ? this.benchmarkGate.run(job, this.deadline.abort.signal)
723
+ : this.verifier.run(job, this.deadline.abort.signal))
724
+ : await (gateSlot
725
+ ? this.gate.restore(job)
726
+ : benchmarkSlot
727
+ ? this.benchmarkGate.restore(job, this.deadline.abort.signal)
728
+ : this.verifier.restore(job));
729
+ if (existing.receipt !== null && (!same(existing.receipt, restored.receipt) || !same(existing.output, restored.output)))
730
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
731
+ this.checks.set(key, restored);
732
+ const ordinal = plan.verifierSlots.findIndex(slot => slot.id === slotId), phase = 'verify.' + this.generation + '.' + ordinal;
733
+ if (!this.head.progress.stage.consumed.includes(phase + '.post')) {
734
+ if (this.draft.stage.phase !== phase + '.pre')
735
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
736
+ await this.#finalizeVerifierPost(slotId, restored, ordinal, phase);
737
+ }
738
+ return restored;
739
+ }
740
+ if (this.draft.failures.length >= 16)
741
+ refuse('OUTPUT_LIMIT', '', 'verification');
742
+ await this.guard();
743
+ const ordinal = plan.verifierSlots.findIndex(slot => slot.id === slotId);
744
+ if (ordinal < 0)
745
+ refuse('EVIDENCE_UNAVAILABLE', '', 'verification');
746
+ const nonce = randomBytes(16).toString('hex'), source = { manifest: this.context.source.manifest, ref: await artifacts.json('manifest', this.context.source.manifest, bounds.manifestMaxBytes), files: this.context.source.artifacts, baselineProofs: this.context.source.baselineProofs };
747
+ const impl = plan.verifierSlots[ordinal].handler.implementation;
748
+ const gateSlot = impl === 'gate.v1';
749
+ const benchmarkSlot = impl === 'benchmark-gate.v1';
750
+ const sized = gateSlot || benchmarkSlot ? null : preflightVerification(plan, lock, slotId, source, this.candidate, this.generation, nonce), phase = 'verify.' + this.generation + '.' + ordinal;
751
+ if (sized && sized.kind === 'refused') {
752
+ const row = await this.verifier.storeRefusal(sized.prepared);
753
+ await this.events.push('verification', 'OUTPUT_LIMIT');
754
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'verifier_pre' }, verifierRefusals: [...this.draft.verifierRefusals, row] }, phase + '.pre');
755
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'verifier_post' }, nodes: this.nodeDispositions(this.draft.nodes, this.generation, { slotId, status: 'blocked' }) }, phase + '.post');
756
+ const checked = await this.verifier.restoreRefusal(sized.prepared, row);
757
+ this.refusals.set(slotId + ':' + this.generation, checked);
758
+ return checked;
759
+ }
760
+ const baseTreeBundle = benchmarkSlot ? await this.#ensureBenchmarkBaseTreeBundle() : undefined;
761
+ const job = gateSlot
762
+ ? prepareGate(plan, lock, slotId, this.candidate, this.generation, nonce, this.context.loaded.registry.spec.gateEndpoints)
763
+ : benchmarkSlot
764
+ ? prepareBenchmarkGate(plan, lock, slotId, this.candidate, this.generation, nonce, this.context.loaded.registry.spec.gateEndpoints, baseTreeBundle)
765
+ : sized.job;
766
+ await this.events.push('verification', null);
767
+ const epochTag = this.reworkEpoch > 0 ? { reworkEpoch: this.reworkEpoch } : {};
768
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'verifier_pre' }, verifierReceipts: [...this.draft.verifierReceipts, { slot: slotId, generation: this.generation, operationId: job.operationId, producerNonce: nonce, output: null, receipt: null, ...epochTag }] }, phase + '.pre');
769
+ this.deadline.assert();
770
+ const checked = await (gateSlot
771
+ ? this.gate.run(job, this.deadline.abort.signal)
772
+ : benchmarkSlot
773
+ ? this.benchmarkGate.run(job, this.deadline.abort.signal)
774
+ : this.verifier.run(job, this.deadline.abort.signal));
775
+ this.checks.set(slotId + ':' + this.generation, checked);
776
+ await this.#finalizeVerifierPost(slotId, checked, ordinal, phase);
777
+ return checked;
778
+ }
779
+ nodeDispositions(input, generation, pendingRefusal) {
780
+ const nodes = input.map(item => ({ ...item })), { plan } = this.context;
781
+ for (const node of plan.orderedDAG) {
782
+ const state = nodes.find(item => item.id === node.id);
783
+ if (node.kind !== 'check' || state.state === 'not_run' || !node.dependsOn.every(parent => nodes.find(item => item.id === parent)?.state === 'completed'))
784
+ continue;
785
+ const slot = plan.verifierSlots.find(slot => slot.handler.id === node.handler.id), checked = slot ? this.checks.get(slot.id + ':' + generation) ?? this.refusals.get(slot.id + ':' + generation) ?? (pendingRefusal?.slotId === slot.id ? pendingRefusal : undefined) : undefined;
786
+ if (!checked)
787
+ continue;
788
+ state.state = checked.status === 'passed' ? 'completed' : checked.status;
789
+ if (checked.status !== 'passed')
790
+ for (const id of descendants(plan, node.id)) {
791
+ const child = nodes.find(item => item.id === id);
792
+ if (child.state === 'pending')
793
+ child.state = 'not_run';
794
+ }
795
+ }
796
+ return nodes;
797
+ }
798
+ async captureStepOutput(captured, repair, originalInvalidRaw, ignoreArtifactPath, previousFiles, expectedKind) {
799
+ const { artifacts, plan } = this.context;
800
+ if (repair === 'format') {
801
+ if (!captured.submission || !originalInvalidRaw)
802
+ refuse('RECOVERY_REQUIRED', '', 'execution');
803
+ const rawBytes = await artifacts.read(captured.submission, 1048576);
804
+ if (expectedKind === 'verdict') {
805
+ const value = parseStepVerdict(rawBytes);
806
+ const raw = await artifacts.put('step-verdict', rawBytes, 1048576);
807
+ await artifacts.json('format-lineage', { version: 1, original: originalInvalidRaw, repaired: raw, candidate: captured.digest, attemptId: this.draft.attempts.at(-1).id }, 65536);
808
+ return { kind: 'verdict', retained: freeze({ version: 1, origin: 'assistant', raw, value }) };
809
+ }
810
+ const value = normalizeSubmission(rawBytes, plan.task);
811
+ const raw = await artifacts.put('submission', rawBytes, 1048576);
812
+ await artifacts.json('format-lineage', { version: 1, original: originalInvalidRaw, repaired: raw, candidate: captured.digest, attemptId: this.draft.attempts.at(-1).id }, 65536);
813
+ return { kind: 'submission', retained: freeze({ version: 1, origin: 'assistant', raw, value }) };
814
+ }
815
+ return retainStepOutput(captured, plan.controls.submission, plan.task, artifacts, { ignoreArtifactPath, previousFiles, expectedKind });
816
+ }
817
+ async completeCapture(attempt, captured, options) {
818
+ const { plan, store, artifacts } = this.context, { nodeId, repair, purpose, ordinal, id: commandId } = attempt;
819
+ const dagNode = plan.orderedDAG.find(item => item.id === nodeId);
820
+ const role = plan.roles.find(item => item.roleId === dagNode.roleId);
821
+ const expectedKind = isVerdictStep(dagNode) ? 'verdict' : 'submission';
822
+ const disallowMutations = repair === 'format' || !role.policy.tools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash');
823
+ const ignoreArtifactPath = options?.ignoreArtifactPath === true || disallowMutations;
824
+ const previousFiles = this.candidate.files;
825
+ const oldDigest = this.draft.candidate.digest;
826
+ const originalInvalidRaw = this.draft.failures.at(-1)?.evidence ?? this.draft.submission;
827
+ const manifest = await this.context.progress.manifest(captured.manifest), changed = !same(captured.digest, oldDigest);
828
+ if (changed && this.generation + 1 >= plan.capacity.V)
829
+ refuse('ATTEMPT_LIMIT', '', 'execution');
830
+ this.candidate = { manifest, ref: captured.manifest, files: captured.artifacts, baselineProofs: this.context.source.baselineProofs };
831
+ this.#candidateKnown = true;
832
+ if (changed) {
833
+ await this.triageCandidateDiffAdvisory(nodeId, commandId, captured.digest, captured.artifacts, manifest.spec.deleted ?? []);
834
+ }
835
+ let stepOutput = null, failure = null, failedRaw = null;
836
+ try {
837
+ if (purpose !== 'compaction') {
838
+ stepOutput = await this.captureStepOutput(captured, repair, originalInvalidRaw, ignoreArtifactPath, previousFiles, expectedKind);
839
+ }
840
+ }
841
+ catch (error) {
842
+ if (error instanceof ControllerFailure && ['SUBMISSION_INVALID', 'SUBMISSION_AMBIGUOUS'].includes(error.diagnostic.code))
843
+ failure = error.diagnostic.code;
844
+ else
845
+ throw error;
846
+ }
847
+ if (failure) {
848
+ const selectedFile = ignoreArtifactPath || plan.controls.submission.path === null
849
+ ? undefined
850
+ : captured.artifacts.find(file => file.name === plan.controls.submission.path);
851
+ let selectedBytes;
852
+ if (selectedFile !== undefined) {
853
+ try {
854
+ selectedBytes = await readSubmissionCandidateBytes(selectedFile, artifacts, 'verification');
855
+ }
856
+ catch {
857
+ selectedBytes = undefined;
858
+ }
859
+ }
860
+ failedRaw = repair === 'format' || selectedBytes === undefined ? captured.submission : await artifacts.put('submission', selectedBytes, 1048576);
861
+ }
862
+ const currentEpoch = this.draft.reworkEpoch ?? 0;
863
+ let nextReworkEpoch = currentEpoch;
864
+ let nextReworkCounts = this.draft.reworkCounts;
865
+ let nextNodeSubmissions = this.draft.nodeSubmissions;
866
+ let nextNodeCandidates = this.draft.nodeCandidates;
867
+ let nextStepVerdicts = this.draft.stepVerdicts;
868
+ let reworked = false;
869
+ let verdictHalted = false;
870
+ let nextSubmissionRef = this.draft.submission;
871
+ let nextNodes = this.draft.nodes.map(item => ({ ...item }));
872
+ if (failure) {
873
+ if (this.submission === null)
874
+ nextSubmissionRef = failedRaw;
875
+ nextNodes = nextNodes.map(item => (item.id === nodeId ? { ...item, state: 'failed' } : item));
876
+ }
877
+ else if (stepOutput?.kind === 'verdict') {
878
+ const verdictVal = stepOutput.retained.value;
879
+ if (verdictVal.verdict === 'rework') {
880
+ const usedReworks = this.draft.reworkCounts?.[nodeId] ?? 0;
881
+ const canRework = dagNode.onRework !== undefined && usedReworks < dagNode.onRework.maxReworks && this.generation + 1 < plan.capacity.V;
882
+ const alignmentOk = canRework ? await this.evaluateAlignment('rework', dagNode.onRework.rejectTo, captured.digest) : false;
883
+ if (canRework && alignmentOk) {
884
+ reworked = true;
885
+ nextReworkEpoch = currentEpoch + 1;
886
+ nextReworkCounts = freeze({ ...(this.draft.reworkCounts ?? {}), [nodeId]: usedReworks + 1 });
887
+ }
888
+ else {
889
+ verdictHalted = true;
890
+ }
891
+ }
892
+ else if (verdictVal.verdict === 'human' || verdictVal.verdict === 'fail') {
893
+ verdictHalted = true;
894
+ }
895
+ nextSubmissionRef = this.submission?.raw ?? null;
896
+ const nextGenForVerdict = this.generation + (changed || reworked ? 1 : 0);
897
+ const storedVerdict = freeze({
898
+ attemptId: commandId,
899
+ stepId: nodeId,
900
+ roleId: role.roleId,
901
+ reworkEpoch: currentEpoch,
902
+ generation: nextGenForVerdict,
903
+ raw: stepOutput.retained.raw,
904
+ verdict: verdictVal.verdict,
905
+ summaryPreview: summarizeStepVerdictPreview(verdictVal.summary),
906
+ findingCount: verdictVal.findings.length,
907
+ });
908
+ nextStepVerdicts = freeze([...(this.draft.stepVerdicts ?? []), storedVerdict]);
909
+ if (verdictVal.verdict === 'pass') {
910
+ if (isArtifactHandoffSourceStep(plan, nodeId)) {
911
+ nextNodeCandidates = freeze({
912
+ ...(this.draft.nodeCandidates ?? {}),
913
+ [nodeId]: freeze({
914
+ attemptId: commandId,
915
+ reworkEpoch: currentEpoch,
916
+ manifest: captured.manifest,
917
+ digest: captured.digest,
918
+ workspace: captured.workspace,
919
+ }),
920
+ });
921
+ }
922
+ nextNodes = nextNodes.map(item => (item.id === nodeId ? { ...item, state: 'completed' } : item));
923
+ }
924
+ else if (reworked) {
925
+ const resetSet = new Set(reworkSubgraph(plan, dagNode.onRework.rejectTo));
926
+ nextNodeSubmissions = pruneRecordKeys(nextNodeSubmissions, resetSet);
927
+ nextNodeCandidates = pruneRecordKeys(nextNodeCandidates, resetSet);
928
+ const markedDone = nextNodes.map(item => (item.id === nodeId ? { ...item, state: 'completed' } : item));
929
+ const resetNodes = resetSubgraphNodes(plan, markedDone, dagNode.onRework.rejectTo);
930
+ nextNodes = resetNodes.map(item => {
931
+ if (item.state !== 'completed')
932
+ return item;
933
+ const itemDagNode = plan.orderedDAG.find(node => node.id === item.id);
934
+ return itemDagNode?.kind === 'check' ? { ...item, state: 'pending' } : item;
935
+ });
936
+ }
937
+ else if (verdictVal.verdict === 'fail') {
938
+ nextNodes = nextNodes.map(item => item.id === nodeId ? { ...item, state: 'failed' } : item.state === 'pending' ? { ...item, state: 'not_run' } : item);
939
+ }
940
+ else {
941
+ nextNodes = nextNodes.map(item => item.id === nodeId ? { ...item, state: 'blocked' } : item.state === 'pending' ? { ...item, state: 'not_run' } : item);
942
+ }
943
+ }
944
+ else {
945
+ if (stepOutput?.kind === 'submission') {
946
+ const retained = stepOutput.retained;
947
+ const priorNodeSub = this.draft.nodeSubmissions?.[nodeId];
948
+ nextNodeSubmissions = freeze({ ...(this.draft.nodeSubmissions ?? {}), [nodeId]: retained.raw });
949
+ const keepPriorRicherAuthorClaims = this.submission !== null &&
950
+ !(priorNodeSub !== undefined && same(priorNodeSub, this.submission.raw)) &&
951
+ this.submission.value.status === 'completed' &&
952
+ this.submission.value.checks.length > 0 &&
953
+ retained.value.status === 'completed' &&
954
+ retained.value.checks.length === 0;
955
+ if (!keepPriorRicherAuthorClaims) {
956
+ this.submission = retained;
957
+ }
958
+ nextSubmissionRef = this.submission.raw;
959
+ }
960
+ if (purpose !== 'compaction' && isArtifactHandoffSourceStep(plan, nodeId)) {
961
+ nextNodeCandidates = freeze({
962
+ ...(this.draft.nodeCandidates ?? {}),
963
+ [nodeId]: freeze({
964
+ attemptId: commandId,
965
+ reworkEpoch: currentEpoch,
966
+ manifest: captured.manifest,
967
+ digest: captured.digest,
968
+ workspace: captured.workspace,
969
+ }),
970
+ });
971
+ }
972
+ nextNodes = nextNodes.map(item => (item.id === nodeId ? { ...item, state: 'completed' } : item));
973
+ }
974
+ const generation = this.generation + (changed || reworked ? 1 : 0);
975
+ if (generation >= plan.capacity.V)
976
+ refuse('ATTEMPT_LIMIT', '', 'execution');
977
+ const after = stateValue(store.inspect()).counts;
978
+ const baseDraft = omitDraftNodeSnapshots(this.draft);
979
+ let draft = {
980
+ ...baseDraft,
981
+ stage: { ...baseDraft.stage, kind: 'role_post' },
982
+ attempts: baseDraft.attempts.map(item => item.id === commandId ? { ...item, finished: { after: { requests: after.requests, operations: after.operations }, outcome: captured.outcome, nativeCheckpointId: captured.checkpointId } } : item),
983
+ nativeCheckpoints: [...baseDraft.nativeCheckpoints, { attemptId: commandId, checkpointId: captured.checkpointId, outcome: captured.outcome }],
984
+ submission: nextSubmissionRef,
985
+ candidate: { manifest: captured.manifest, digest: captured.digest, generation, workspace: captured.workspace, privateSession: captured.session },
986
+ nodes: nextNodes,
987
+ ...(nextReworkEpoch > 0 ? { reworkEpoch: nextReworkEpoch } : {}),
988
+ ...(nextReworkCounts !== undefined && Object.keys(nextReworkCounts).length > 0 ? { reworkCounts: nextReworkCounts } : {}),
989
+ ...(nextNodeSubmissions !== undefined && Object.keys(nextNodeSubmissions).length > 0 ? { nodeSubmissions: nextNodeSubmissions } : {}),
990
+ ...(nextNodeCandidates !== undefined && Object.keys(nextNodeCandidates).length > 0 ? { nodeCandidates: nextNodeCandidates } : {}),
991
+ ...(nextStepVerdicts !== undefined && nextStepVerdicts.length > 0 ? { stepVerdicts: nextStepVerdicts } : {}),
992
+ };
993
+ if (failure) {
994
+ const signature = failureSignature({ category: 'format', codes: [failure], handler: expectedKind === 'verdict' ? 'step-verdict.v1' : 'submission.v1', handlerVersion: 1, target: nodeId, candidate: captured.digest, evidence: [failedRaw?.digest ?? hash('missing_submission')] });
995
+ draft = { ...draft, failures: rememberFailure(draft.failures, signature, generation, failedRaw) };
996
+ }
997
+ if (repair === 'implementation' && !changed) {
998
+ const requiredOutputs = this.currentChecks().filter(check => check.status === 'failed' && plan.task.spec.acceptance.required.includes(check.checkId)).map(check => check.output);
999
+ draft = { ...draft, failures: draft.failures.map(item => item.evidence && requiredOutputs.some(output => same(item.evidence, output)) ? { ...item, count: Math.min(2, item.count + 1) } : item) };
1000
+ }
1001
+ if (changed && !reworked && !verdictHalted) {
1002
+ const downstreamSet = repair === 'implementation' ? new Set(descendants(plan, nodeId)) : null;
1003
+ draft = {
1004
+ ...draft,
1005
+ nodes: draft.nodes.map(item => {
1006
+ const itemDagNode = plan.orderedDAG.find(node => node.id === item.id);
1007
+ if (itemDagNode.kind === 'check' && (repair === 'implementation' || item.state !== 'not_run'))
1008
+ return { ...item, state: 'pending' };
1009
+ if (downstreamSet && downstreamSet.has(item.id) && itemDagNode.kind === 'agent' && itemDagNode.handler.parameters.purpose === 'review')
1010
+ return { ...item, state: 'pending' };
1011
+ return item;
1012
+ }),
1013
+ };
1014
+ }
1015
+ draft = { ...draft, nodes: this.nodeDispositions(draft.nodes, generation) };
1016
+ await this.publish(draft, 'role.' + ordinal + '.post');
1017
+ return failure;
1018
+ }
1019
+ computeCandidateChangedPaths() {
1020
+ if (this.context.source.version === 2) {
1021
+ const changed = [
1022
+ ...this.candidate.manifest.spec.entries.map(entry => entry.name),
1023
+ ...(this.candidate.manifest.spec.deleted ?? []),
1024
+ ];
1025
+ return freeze([...new Set(changed)].sort(compareUtf16));
1026
+ }
1027
+ const baseByPath = new Map(this.context.source.manifest.spec.entries.map(entry => [entry.name, entry]));
1028
+ const present = new Set(this.candidate.manifest.spec.entries.map(entry => entry.name));
1029
+ const changed = [];
1030
+ for (const entry of this.candidate.manifest.spec.entries) {
1031
+ const baseEntry = baseByPath.get(entry.name);
1032
+ if (baseEntry === undefined || !same(baseEntry.digest, entry.digest)) {
1033
+ changed.push(entry.name);
1034
+ }
1035
+ }
1036
+ for (const baseEntry of this.context.source.manifest.spec.entries) {
1037
+ if (!present.has(baseEntry.name))
1038
+ changed.push(baseEntry.name);
1039
+ }
1040
+ return freeze([...new Set(changed)].sort(compareUtf16));
1041
+ }
1042
+ async computeFailedCheckSignals() {
1043
+ const failedChecks = new Set();
1044
+ const failureCodes = new Set();
1045
+ const { plan, artifacts } = this.context;
1046
+ for (const check of this.currentChecks()) {
1047
+ if (check.status === 'passed')
1048
+ continue;
1049
+ failedChecks.add(check.checkId);
1050
+ if (check.reason !== null && check.reason.length > 0)
1051
+ failureCodes.add(check.reason);
1052
+ const slot = plan.verifierSlots.find(s => s.id === check.slotId);
1053
+ if (slot?.handler.implementation === 'gate.v1') {
1054
+ const trusted = authenticatedGate(check);
1055
+ let parsed = null;
1056
+ try {
1057
+ parsed = parsePrivateJson(Buffer.from(trusted.outputBytes), CONTROLLER_LIMITS.verifierSignalJsonBytes);
1058
+ }
1059
+ catch (error) {
1060
+ if (!(error instanceof ControllerFailure) || error.diagnostic.code !== 'ARTIFACT_INVALID') {
1061
+ throw error;
1062
+ }
1063
+ }
1064
+ const verdict = isRecord(parsed) && isRecord(parsed.verdict) ? parsed.verdict : null;
1065
+ if (verdict && typeof verdict.reason === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(verdict.reason)) {
1066
+ failureCodes.add(verdict.reason);
1067
+ }
1068
+ }
1069
+ }
1070
+ for (const refusal of this.currentRefusals()) {
1071
+ failedChecks.add(refusal.checkId);
1072
+ if (refusal.reason.length > 0)
1073
+ failureCodes.add(refusal.reason);
1074
+ }
1075
+ if (failedChecks.size === 0 && this.reworkEpoch > 0 && this.generation > 0 && this.head) {
1076
+ for (const row of this.head.progress.verifierReceipts) {
1077
+ if (row.generation !== this.generation - 1 || row.output === null)
1078
+ continue;
1079
+ const slot = plan.verifierSlots.find(s => s.id === row.slot);
1080
+ if (!slot || row.output.byteLength > CONTROLLER_LIMITS.verifierSignalJsonBytes)
1081
+ continue;
1082
+ const rawBytes = await artifacts.read(row.output, CONTROLLER_LIMITS.verifierSignalJsonBytes);
1083
+ let parsed = null;
1084
+ try {
1085
+ parsed = parsePrivateJson(rawBytes, CONTROLLER_LIMITS.verifierSignalJsonBytes);
1086
+ }
1087
+ catch (error) {
1088
+ if (!(error instanceof ControllerFailure) || error.diagnostic.code !== 'ARTIFACT_INVALID') {
1089
+ throw error;
1090
+ }
1091
+ }
1092
+ if (!isRecord(parsed))
1093
+ continue;
1094
+ const payload = slot.handler.implementation === 'gate.v1' ? parsed.disposition : parsed.response;
1095
+ if (isRecord(payload) && typeof payload.status === 'string' && payload.status !== 'passed') {
1096
+ failedChecks.add(slot.checkId);
1097
+ if (typeof payload.reason === 'string' && payload.reason.length > 0) {
1098
+ failureCodes.add(payload.reason);
1099
+ }
1100
+ }
1101
+ }
1102
+ }
1103
+ return freeze({
1104
+ failedChecks: freeze([...failedChecks].sort(compareUtf16)),
1105
+ failureCodes: freeze([...failureCodes].sort(compareUtf16)),
1106
+ });
1107
+ }
1108
+ resolveRetainedActiveResources(roleId, retained) {
1109
+ const allRoleResources = roleResourcesFor(this.context.loaded, this.context.plan, roleId);
1110
+ if (retained.activatedResourceIds === undefined) {
1111
+ if (retained.repair === 'format' || retained.purpose === 'compaction') {
1112
+ const whenById = new Map(this.context.plan.task.spec.trustedContext.resources.map(r => [r.id, r.when]));
1113
+ return allRoleResources.filter(r => whenById.get(r.id) === undefined);
1114
+ }
1115
+ return allRoleResources;
1116
+ }
1117
+ const activeSet = new Set(retained.activatedResourceIds);
1118
+ return allRoleResources.filter(r => activeSet.has(r.id));
1119
+ }
1120
+ async #readSnapshotArtifactBytes(snap, relPath, diagPath, memo) {
1121
+ const { artifacts, source, owner, store, lock, plan } = this.context;
1122
+ const manifestKey = snap.manifest.digest.hex;
1123
+ let manifestPromise = memo?.manifests.get(manifestKey);
1124
+ if (manifestPromise === undefined) {
1125
+ manifestPromise = this.context.progress.manifest(snap.manifest);
1126
+ memo?.manifests.set(manifestKey, manifestPromise);
1127
+ }
1128
+ const manifest = await manifestPromise;
1129
+ const readCasOrWorkspaceFile = async (entry) => {
1130
+ if (entry.byteLength > LIMITS.handoffSourceBytes)
1131
+ refuse('OUTPUT_LIMIT', diagPath, 'execution');
1132
+ const casReused = await artifacts.tryReuseCasBlob(relPath, entry.digest.hex, entry.byteLength);
1133
+ if (casReused !== null) {
1134
+ const chunks = [];
1135
+ await streamVerifiedCasBlob(artifacts.directory, {
1136
+ name: relPath,
1137
+ sha256: casReused.sha256,
1138
+ byteLength: casReused.byteLength,
1139
+ uri: casReused.blobRef.uri,
1140
+ path: casReused.path,
1141
+ blobRef: casReused.blobRef,
1142
+ }, chunk => {
1143
+ chunks.push(new Uint8Array(chunk));
1144
+ }, 'execution');
1145
+ const bytes = new Uint8Array(Buffer.concat(chunks));
1146
+ if (bytes.byteLength !== entry.byteLength || hash(bytes).hex !== entry.digest.hex) {
1147
+ refuse('ARTIFACT_INVALID', diagPath, 'execution');
1148
+ }
1149
+ return bytes;
1150
+ }
1151
+ if (source.version === 1 && same(snap.workspace, source.workspace)) {
1152
+ const baseFile = source.artifacts.find(f => f.name === relPath);
1153
+ if (!baseFile || baseFile.bytes.byteLength !== entry.byteLength || hash(baseFile.bytes).hex !== entry.digest.hex) {
1154
+ refuse('ARTIFACT_INVALID', diagPath, 'execution');
1155
+ }
1156
+ return new Uint8Array(baseFile.bytes);
1157
+ }
1158
+ const attempt = (this.head?.progress.attempts ?? []).find(a => a.id === snap.attemptId);
1159
+ if (!attempt?.finished?.nativeCheckpointId)
1160
+ refuse('RECOVERY_REQUIRED', diagPath, 'execution');
1161
+ const loadDecodedCapture = () => {
1162
+ const cached = memo?.captures.get(snap.attemptId);
1163
+ if (cached !== undefined)
1164
+ return cached;
1165
+ const checkpoint = stateValue(store.getCheckpoint(attempt.finished.nativeCheckpointId));
1166
+ const interval = journal(store).requests.filter(row => row.sequence > attempt.before.requests && row.sequence <= attempt.finished.after.requests);
1167
+ const promise = decodeCandidateCapture({
1168
+ artifacts,
1169
+ artifactsDirectory: artifacts.directory,
1170
+ lock,
1171
+ plan,
1172
+ checkpoint,
1173
+ attempt,
1174
+ expectedManifest: manifest,
1175
+ requestIds: interval.map(row => row.admission.requestId),
1176
+ phase: 'execution',
1177
+ });
1178
+ memo?.captures.set(snap.attemptId, promise);
1179
+ return promise;
1180
+ };
1181
+ const decoded = await loadDecodedCapture();
1182
+ const matched = decoded.artifacts.find(f => f.name === relPath);
1183
+ if (!matched)
1184
+ refuse('ARTIFACT_INVALID', diagPath, 'execution');
1185
+ if ('bytes' in matched) {
1186
+ if (matched.bytes.byteLength !== entry.byteLength || hash(matched.bytes).hex !== entry.digest.hex) {
1187
+ refuse('ARTIFACT_INVALID', diagPath, 'execution');
1188
+ }
1189
+ return new Uint8Array(matched.bytes);
1190
+ }
1191
+ const chunks = [];
1192
+ await streamVerifiedCasBlob(artifacts.directory, {
1193
+ name: matched.name,
1194
+ sha256: matched.digest.hex,
1195
+ byteLength: matched.byteLength,
1196
+ uri: 'cas://sha256/' + matched.digest.hex,
1197
+ path: matched.blobPath,
1198
+ }, chunk => {
1199
+ chunks.push(new Uint8Array(chunk));
1200
+ }, 'execution');
1201
+ const bytes = new Uint8Array(Buffer.concat(chunks));
1202
+ if (bytes.byteLength !== entry.byteLength || hash(bytes).hex !== entry.digest.hex) {
1203
+ refuse('ARTIFACT_INVALID', diagPath, 'execution');
1204
+ }
1205
+ return bytes;
1206
+ };
1207
+ if (source.version === 2) {
1208
+ if ((manifest.spec.deleted ?? []).includes(relPath))
1209
+ return null;
1210
+ const overlayEntry = manifest.spec.entries.find(e => e.name === relPath);
1211
+ if (overlayEntry !== undefined) {
1212
+ return readCasOrWorkspaceFile(overlayEntry);
1213
+ }
1214
+ const baseEntry = (source.baselineEntries ?? []).find(b => b.name === relPath);
1215
+ if (!baseEntry)
1216
+ return null;
1217
+ if (baseEntry.byteLength > LIMITS.handoffSourceBytes)
1218
+ refuse('OUTPUT_LIMIT', diagPath, 'execution');
1219
+ const rawBlob = await owner.git(source.directory, ['cat-file', 'blob', baseEntry.oid], LIMITS.handoffSourceBytes + 1);
1220
+ const blobBytes = new Uint8Array(rawBlob);
1221
+ if (blobBytes.byteLength !== baseEntry.byteLength
1222
+ || gitObjectOid(manifest.spec.baseTree.objectFormat, 'blob', blobBytes) !== baseEntry.oid) {
1223
+ refuse('ARTIFACT_INVALID', diagPath, 'execution');
1224
+ }
1225
+ return blobBytes;
1226
+ }
1227
+ const entry = manifest.spec.entries.find(e => e.name === relPath);
1228
+ if (!entry)
1229
+ return null;
1230
+ return readCasOrWorkspaceFile(entry);
1231
+ }
1232
+ async readUpstreamHandoffSource(selector, diagPath, memo) {
1233
+ const progress = this.head?.progress;
1234
+ const attempts = progress?.attempts ?? [];
1235
+ const lastFromAttempt = [...attempts]
1236
+ .reverse()
1237
+ .find(a => a.nodeId === selector.fromStep && a.purpose !== 'compaction' && Boolean(a.finished?.nativeCheckpointId));
1238
+ const fromNodeCompleted = progress?.nodes.find(n => n.id === selector.fromStep)?.state === 'completed';
1239
+ if (selector.source.kind === 'artifact') {
1240
+ const snap = progress?.nodeCandidates?.[selector.fromStep];
1241
+ if (!snap || !fromNodeCompleted) {
1242
+ return {
1243
+ found: false,
1244
+ bytes: null,
1245
+ fromAttemptId: lastFromAttempt?.id ?? null,
1246
+ reworkEpoch: lastFromAttempt?.reworkEpoch ?? this.reworkEpoch,
1247
+ };
1248
+ }
1249
+ const bytes = await this.#readSnapshotArtifactBytes(snap, selector.source.path, `${diagPath}/source/path`, memo);
1250
+ return {
1251
+ found: bytes !== null,
1252
+ bytes,
1253
+ fromAttemptId: snap.attemptId,
1254
+ reworkEpoch: snap.reworkEpoch,
1255
+ };
1256
+ }
1257
+ if (selector.source.kind === 'submission') {
1258
+ const subRef = fromNodeCompleted ? progress?.nodeSubmissions?.[selector.fromStep] : undefined;
1259
+ if (!subRef) {
1260
+ return {
1261
+ found: false,
1262
+ bytes: null,
1263
+ fromAttemptId: lastFromAttempt?.id ?? null,
1264
+ reworkEpoch: lastFromAttempt?.reworkEpoch ?? this.reworkEpoch,
1265
+ };
1266
+ }
1267
+ if (subRef.byteLength > LIMITS.handoffSourceBytes)
1268
+ refuse('OUTPUT_LIMIT', `${diagPath}/source`, 'execution');
1269
+ const bytes = await this.context.artifacts.read(subRef, LIMITS.handoffSourceBytes);
1270
+ return {
1271
+ found: true,
1272
+ bytes,
1273
+ fromAttemptId: lastFromAttempt?.id ?? null,
1274
+ reworkEpoch: lastFromAttempt?.reworkEpoch ?? this.reworkEpoch,
1275
+ };
1276
+ }
1277
+ if (!fromNodeCompleted) {
1278
+ return {
1279
+ found: false,
1280
+ bytes: null,
1281
+ fromAttemptId: null,
1282
+ reworkEpoch: this.reworkEpoch,
1283
+ };
1284
+ }
1285
+ const fromNode = this.context.plan.orderedDAG.find(n => n.id === selector.fromStep);
1286
+ const verdicts = progress?.stepVerdicts ?? [];
1287
+ const verdictRow = fromNode?.kind === 'agent'
1288
+ ? (lastFromAttempt ? [...verdicts].reverse().find(v => v.attemptId === lastFromAttempt.id) : undefined)
1289
+ : [...verdicts].reverse().find(v => v.stepId === selector.fromStep && v.reworkEpoch === this.reworkEpoch);
1290
+ if (verdictRow) {
1291
+ if (verdictRow.raw.byteLength > LIMITS.handoffSourceBytes)
1292
+ refuse('OUTPUT_LIMIT', `${diagPath}/source`, 'execution');
1293
+ const bytes = await this.context.artifacts.read(verdictRow.raw, LIMITS.handoffSourceBytes);
1294
+ return {
1295
+ found: true,
1296
+ bytes,
1297
+ fromAttemptId: verdictRow.attemptId,
1298
+ reworkEpoch: verdictRow.reworkEpoch,
1299
+ };
1300
+ }
1301
+ if (fromNode?.kind === 'check') {
1302
+ const compiledSlot = this.context.plan.verifierSlots.find(s => s.handler.id === fromNode.handler.id)?.id;
1303
+ const receipt = [...(progress?.verifierReceipts ?? [])]
1304
+ .reverse()
1305
+ .find(r => (r.slot === compiledSlot || r.slot === 'node:' + selector.fromStep)
1306
+ && r.generation === this.generation
1307
+ && r.output !== null);
1308
+ if (receipt?.output) {
1309
+ if (receipt.output.byteLength > LIMITS.handoffSourceBytes)
1310
+ refuse('OUTPUT_LIMIT', `${diagPath}/source`, 'execution');
1311
+ const bytes = await this.context.artifacts.read(receipt.output, LIMITS.handoffSourceBytes);
1312
+ return {
1313
+ found: true,
1314
+ bytes,
1315
+ fromAttemptId: null,
1316
+ reworkEpoch: this.reworkEpoch,
1317
+ };
1318
+ }
1319
+ }
1320
+ return {
1321
+ found: false,
1322
+ bytes: null,
1323
+ fromAttemptId: lastFromAttempt?.id ?? null,
1324
+ reworkEpoch: this.reworkEpoch,
1325
+ };
1326
+ }
1327
+ async prepareAttemptContext(nodeId, role, repair, purpose, attemptEpoch, watchedPaths) {
1328
+ const { loaded, plan, artifacts, ports } = this.context;
1329
+ const allRoleResources = roleResourcesFor(loaded, plan, role.roleId);
1330
+ if (purpose === 'compaction') {
1331
+ const whenById = new Map(plan.task.spec.trustedContext.resources.map(r => [r.id, r.when]));
1332
+ const unconditionalOnly = allRoleResources.filter(r => whenById.get(r.id) === undefined);
1333
+ return {
1334
+ activeResources: unconditionalOnly,
1335
+ activatedResourceIds: freeze(unconditionalOnly.map(r => r.id)),
1336
+ resolvedHandoffs: [],
1337
+ handoffExtracts: undefined,
1338
+ };
1339
+ }
1340
+ const whenById = new Map(plan.task.spec.trustedContext.resources.map(r => [r.id, r.when]));
1341
+ const evaluable = allRoleResources.map(res => {
1342
+ const when = whenById.get(res.id);
1343
+ return when !== undefined ? { ...res, when } : { ...res };
1344
+ });
1345
+ const changedPaths = this.computeCandidateChangedPaths();
1346
+ const { failedChecks, failureCodes } = await this.computeFailedCheckSignals();
1347
+ const effectiveWatched = watchedPaths ?? ports.watchedPaths;
1348
+ const filtered = evaluateResourceActivationRules(evaluable, {
1349
+ repair,
1350
+ reworkEpoch: attemptEpoch,
1351
+ purpose,
1352
+ isReviewer: purpose === 'reviewer',
1353
+ changedPaths,
1354
+ ...(effectiveWatched !== undefined ? { watchedPaths: effectiveWatched } : {}),
1355
+ failedChecks,
1356
+ failureCodes,
1357
+ });
1358
+ const activeIdSet = new Set(filtered.map(item => item.id));
1359
+ const activeResources = allRoleResources.filter(item => activeIdSet.has(item.id));
1360
+ const activatedResourceIds = freeze(activeResources.map(item => item.id));
1361
+ if (activeResources.length > CONTROLLER_LIMITS.maxStepContextFiles) {
1362
+ refuse('OUTPUT_LIMIT', '/spec/task/spec/trustedContext/resources', 'execution');
1363
+ }
1364
+ const node = plan.orderedDAG.find(n => n.id === nodeId);
1365
+ if (repair === 'format' || !node?.handoffs || node.handoffs.length === 0) {
1366
+ return {
1367
+ activeResources,
1368
+ activatedResourceIds,
1369
+ resolvedHandoffs: [],
1370
+ handoffExtracts: undefined,
1371
+ };
1372
+ }
1373
+ const stepIndex = plan.task.spec.steps.findIndex(s => s.id === nodeId);
1374
+ const stepDiagBase = stepIndex >= 0 ? `/spec/task/spec/steps/${stepIndex}/handoffs` : '/handoffs';
1375
+ const snapshotMemo = {
1376
+ manifests: new Map(),
1377
+ captures: new Map(),
1378
+ };
1379
+ const lookups = [];
1380
+ for (let i = 0; i < node.handoffs.length; i += 1) {
1381
+ lookups.push(await this.readUpstreamHandoffSource(node.handoffs[i], `${stepDiagBase}/${i}`, snapshotMemo));
1382
+ }
1383
+ const resolvedHandoffs = evaluateStepHandoffSelectors(node.handoffs, (_, idx) => lookups[idx], {
1384
+ ...(stepIndex >= 0 ? { stepIndex } : {}),
1385
+ reworkEpoch: attemptEpoch,
1386
+ });
1387
+ const extractedCount = resolvedHandoffs.filter(item => item.provenance.status === 'extracted').length;
1388
+ if (activeResources.length + extractedCount > CONTROLLER_LIMITS.maxStepContextFiles) {
1389
+ refuse('OUTPUT_LIMIT', stepDiagBase, 'execution');
1390
+ }
1391
+ const handoffExtracts = await persistHandoffExtractsToCas(resolvedHandoffs, artifacts);
1392
+ return {
1393
+ activeResources,
1394
+ activatedResourceIds,
1395
+ resolvedHandoffs,
1396
+ handoffExtracts,
1397
+ };
1398
+ }
1399
+ async role(nodeId, repair = 'none', prompt, retained) {
1400
+ await this.guard();
1401
+ const { plan, lock, store, artifacts, authority, loaded, directory } = this.context, bounds = this.#overlayBounds();
1402
+ const delegatedCounts = countDelegatedBudgets(plan, this.draft.attempts);
1403
+ observeParentExhaustion(this.deadline.assert(), lock, delegatedCounts.modelCalls);
1404
+ const node = plan.orderedDAG.find(node => node.id === nodeId);
1405
+ if (!node || node.kind !== 'agent')
1406
+ refuse('CAPABILITY_UNSUPPORTED', '', 'execution');
1407
+ if (!retained && this.draft.attempts.length >= plan.capacity.A)
1408
+ refuse('ATTEMPT_LIMIT', '', 'execution');
1409
+ const originalRole = plan.roles.find(role => role.roleId === node.roleId);
1410
+ if (originalRole.adapter === 'delegated')
1411
+ refuse('CAPABILITY_UNSUPPORTED', '/spec/profiles/roles', 'execution');
1412
+ const role = repair === 'format' ? { ...originalRole, policy: formatPolicy(originalRole.policy) } : originalRole;
1413
+ const purpose = node.handler.implementation === 'pi.compact.v1' ? 'compaction' : node.handler.parameters.purpose === 'review' ? 'reviewer' : 'task';
1414
+ if (!retained && purpose === 'compaction' && this.context.ports.decisions?.adviseSoftCompaction) {
1415
+ const contextUtilization = this.#contextUtilization();
1416
+ const failedVerificationLoops = this.#failedVerificationLoops();
1417
+ const hardTrigger = contextUtilization >= 0.8 || failedVerificationLoops >= 2;
1418
+ try {
1419
+ const advisory = await this.context.ports.decisions.adviseSoftCompaction({
1420
+ runId: lock.spec.runId,
1421
+ stepId: nodeId,
1422
+ roleId: role.roleId,
1423
+ contextUtilization,
1424
+ failedVerificationLoops,
1425
+ });
1426
+ if (advisory !== null && advisory !== undefined) {
1427
+ if (!isRecord(advisory) ||
1428
+ (advisory.advisoryDecision !== null &&
1429
+ (typeof advisory.advisoryDecision !== 'string' || !VALID_SOFT_COMPACTION_DECISIONS.has(advisory.advisoryDecision))) ||
1430
+ typeof advisory.source !== 'string' ||
1431
+ !VALID_ADVISORY_SOURCES.has(advisory.source)) {
1432
+ throw new Error('invalid_soft_compaction_output');
1433
+ }
1434
+ }
1435
+ const vetoAttempted = hardTrigger && advisory?.advisoryDecision === 'defer';
1436
+ this.advisoryObservations.push({
1437
+ intent: 'advise_soft_compaction',
1438
+ stepId: nodeId,
1439
+ advisoryDecision: hardTrigger ? 'compact' : (advisory?.advisoryDecision ?? 'compact'),
1440
+ hardTriggerActive: hardTrigger,
1441
+ hardTriggerVetoRefused: vetoAttempted,
1442
+ source: advisory?.source ?? 'deterministic_heuristic',
1443
+ });
1444
+ }
1445
+ catch {
1446
+ this.advisoryObservations.push({
1447
+ intent: 'advise_soft_compaction',
1448
+ stepId: nodeId,
1449
+ advisoryDecision: 'compact',
1450
+ hardTriggerActive: hardTrigger,
1451
+ hardTriggerVetoRefused: false,
1452
+ source: 'deterministic_fallback',
1453
+ });
1454
+ }
1455
+ }
1456
+ const attemptEpoch = retained ? (retained.reworkEpoch ?? 0) : this.reworkEpoch;
1457
+ const nativeStepId = purpose === 'compaction' ? compactionTarget(plan, nodeId) : nodeId, ordinal = retained?.ordinal ?? this.draft.attempts.length + 1;
1458
+ const commandId = stableId(lock.spec.runId, nodeId, purpose, repair, ordinal), sessionId = nativeSessionId(lock.spec.runId, role.roleId, nativeStepId, role.policy, attemptEpoch);
1459
+ const configured = purpose === 'compaction' ? '' : text(loaded.registry.spec.handlers.find(handler => handler.id === node.handler.id)?.parameters.prompt);
1460
+ // Verify base handler prompt digest FIRST before evaluating or appending any runtime handoff block.
1461
+ if (purpose !== 'compaction' && node.handler.parameters.prompt !== '[private command sha256:' + hash(configured).hex + ']')
1462
+ refuse('RECOVERY_REQUIRED', '', 'execution');
1463
+ const preparedCtx = retained ? null : await this.prepareAttemptContext(nodeId, role, repair, purpose, attemptEpoch);
1464
+ const activeResources = retained ? this.resolveRetainedActiveResources(role.roleId, retained) : preparedCtx.activeResources;
1465
+ if (!retained && purpose !== 'compaction') {
1466
+ await this.adviseCapabilityRouting(nodeId, role, purpose, activeResources);
1467
+ }
1468
+ const maxPromptBytes = Math.min(LIMITS.inputBytes, role.policy.limits.promptBytes);
1469
+ const reworkCtx = repair === 'none' && prompt === undefined ? await this.activeReworkForNode(nodeId) : null;
1470
+ const defaultPrompt = reworkCtx ? reworkPrompt(configured, reworkCtx, Math.min(CONTROLLER_LIMITS.reworkPromptMaxBytes, role.policy.limits.promptBytes)) : configured;
1471
+ const baseCommandText = prompt ?? defaultPrompt;
1472
+ const commandText = retained
1473
+ ? new TextDecoder('utf-8', { fatal: true }).decode(await artifacts.read(retained.command, LIMITS.inputBytes))
1474
+ : repair !== 'format' && purpose !== 'compaction' && preparedCtx !== null && preparedCtx.resolvedHandoffs.length > 0
1475
+ ? appendHandoffPromptBlock(baseCommandText, preparedCtx.resolvedHandoffs, maxPromptBytes, 'execution')
1476
+ : baseCommandText;
1477
+ const command = await artifacts.put('command', Buffer.from(commandText), maxPromptBytes);
1478
+ const originalSubmission = this.draft.failures.at(-1)?.evidence ?? this.draft.submission, before = journal(store).view.counts, oldDigest = this.draft.candidate.digest;
1479
+ const originalState = await schedulingSnapshot(store, authority, lock, artifacts, this.candidate, this.draft.candidate);
1480
+ observeParentExhaustion(this.deadline.assert(), lock, delegatedCounts.modelCalls);
1481
+ // Native Pi adapter materializes files using baseline-derived modes in tree_overlay (v2) and 0o444 (100644)
1482
+ // for every file in classic (v1); fail closed with zero effect before launching a native role whenever a
1483
+ // candidate overlay/mutation carries an effective mode that Pi cannot faithfully materialize.
1484
+ const baselineByPath = new Map(this.context.source.version === 2
1485
+ ? (this.context.source.baselineEntries ?? []).map(entry => [
1486
+ entry.name,
1487
+ { mode: entry.mode, bytes: null, sha256: null },
1488
+ ])
1489
+ : this.context.source.artifacts.map(entry => [
1490
+ entry.name,
1491
+ { mode: entry.mode ?? '100644', bytes: entry.bytes, sha256: hash(entry.bytes).hex },
1492
+ ]));
1493
+ for (const file of this.candidate.files) {
1494
+ const base = baselineByPath.get(file.name);
1495
+ const baselineMode = base?.mode ?? '100644';
1496
+ const effectiveMode = file.mode ?? baselineMode;
1497
+ const piMaterializedMode = this.context.source.version === 2 ? baselineMode : '100644';
1498
+ if (this.context.source.version === 1 && base !== undefined) {
1499
+ const bytesUnchanged = 'bytes' in file
1500
+ ? Buffer.from(file.bytes).equals(Buffer.from(base.bytes))
1501
+ : file.byteLength === base.bytes.byteLength && file.digest.hex === base.sha256;
1502
+ if (bytesUnchanged && effectiveMode === baselineMode) {
1503
+ continue;
1504
+ }
1505
+ }
1506
+ if (effectiveMode !== piMaterializedMode) {
1507
+ refuse('CAPABILITY_UNSUPPORTED', '', 'execution', { effect: 'none' });
1508
+ }
1509
+ }
1510
+ const attempt = retained ?? {
1511
+ ordinal, id: commandId, nodeId, nativeStepId, sessionId, purpose, repair, command,
1512
+ before: { requests: before.requests, operations: before.operations }, finished: null,
1513
+ ...(attemptEpoch > 0 ? { reworkEpoch: attemptEpoch } : {}),
1514
+ ...(purpose !== 'compaction' && preparedCtx !== null ? { activatedResourceIds: preparedCtx.activatedResourceIds } : {}),
1515
+ ...(purpose !== 'compaction' && preparedCtx?.handoffExtracts !== undefined ? { handoffExtracts: preparedCtx.handoffExtracts } : {}),
1516
+ };
1517
+ if (retained) {
1518
+ if (!same(retained, { ...attempt, command, id: commandId, sessionId, nativeStepId, nodeId, purpose, repair, ...(attemptEpoch > 0 ? { reworkEpoch: attemptEpoch } : {}) }) || !same(this.draft.attempts.at(-1), retained) || retained.finished !== null)
1519
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1520
+ }
1521
+ else {
1522
+ if (repair === 'format')
1523
+ await artifacts.json('format-intent', { version: 1, attemptId: commandId, original: originalSubmission, schema: isVerdictStep(node) ? 'step-verdict.v1' : 'submission.v1', candidate: oldDigest, output: 'new_assistant_representation' }, 65536);
1524
+ await this.events.push(repair === 'none' ? 'role' : 'repair', null, nodeId, commandId);
1525
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'role_pre' }, attempts: [...this.draft.attempts, attempt], nodes: this.draft.nodes.map(item => item.id === nodeId ? { ...item, state: 'running' } : item) }, 'role.' + ordinal + '.pre');
1526
+ }
1527
+ let restore = null, nativeManifest = this.candidate.manifest;
1528
+ if (purpose === 'compaction' || repair === 'implementation') {
1529
+ const prior = this.draft.attempts.slice(0, -1).filter(item => item.nativeStepId === nativeStepId && item.sessionId === sessionId && item.finished?.nativeCheckpointId).at(-1);
1530
+ if (prior) {
1531
+ const wrapper = parsePrivateJson(await artifacts.read(prior.finished.outcome, 4194304), 4194304, 16384);
1532
+ const checkpoint = stateValue(store.getCheckpoint(prior.finished.nativeCheckpointId));
1533
+ if (same(checkpoint.subject.candidateDigest, this.draft.candidate.digest)) {
1534
+ const identified = identifyManifest(parsePrivateJson(await artifacts.read(checkedRef(wrapper.originalManifest), bounds.manifestMaxBytes), bounds.manifestMaxBytes, bounds.collectionLimit), bounds.options);
1535
+ if (!identified.ok)
1536
+ refuse('RECOVERY_REQUIRED', '', 'recovery');
1537
+ nativeManifest = identified.value.manifest;
1538
+ restore = { checkpointId: checkpoint.checkpointId, workspace: { ref: checkpoint.workspace, bytes: await artifacts.read(checkpoint.workspace, Math.max(8_388_608, bounds.v2WorkspaceJsonMaxBytes, bounds.workspaceMaxBytes)) }, session: { ref: checkpoint.privateSession, bytes: await artifacts.read(checkpoint.privateSession, 67108864) } };
1539
+ }
1540
+ }
1541
+ if (purpose === 'compaction' && restore === null)
1542
+ refuse('CAPABILITY_UNSUPPORTED', '', 'execution');
1543
+ }
1544
+ const hostDirectory = join(directory, 'runtime', commandId);
1545
+ await privateDirectory(hostDirectory);
1546
+ if (purpose !== 'compaction') {
1547
+ const contextDirectory = join(hostDirectory, 'context');
1548
+ await rm(contextDirectory, { recursive: true, force: true });
1549
+ await privateDirectory(contextDirectory);
1550
+ await materializeContextFilesDir(contextDirectory, activeResources, attempt.handoffExtracts ?? [], artifacts.directory, retained ? 'recovery' : 'execution');
1551
+ }
1552
+ let baseline;
1553
+ if (this.context.source.version === 2) {
1554
+ const baselineDirectory = join(hostDirectory, 'baseline');
1555
+ await materializeBaseline(this.context.source, baselineDirectory, this.context.owner, this.deadline);
1556
+ baseline = { directory: baselineDirectory, entries: this.context.source.baselineEntries ?? [] };
1557
+ }
1558
+ const host = { store, authority, directory: hostDirectory, artifactsDirectory: artifacts.directory, dockerExecutable: role.runtime.dockerExecutable, dockerSocket: role.runtime.dockerSocket, runtime: role.runtime.identity,
1559
+ createCandidateStreamChecker: () => approvedState(loaded).vault.createStreamChecker(),
1560
+ ...approvedState(loaded).vault.bind({ runId: lock.spec.runId, roleId: role.roleId, stepId: nativeStepId, providerCredentialRef: role.providerCredentialRef, selection: role.policy.selection, mcp: role.policy.mcp }) };
1561
+ const piCandidateArtifacts = this.candidate.files.map(file => 'bytes' in file
1562
+ ? { name: file.name, bytes: file.bytes }
1563
+ : { name: file.name, byteLength: file.byteLength, digest: file.digest, blobPath: file.blobPath });
1564
+ const input = { version: 2, lock, roleId: role.roleId, stepId: nativeStepId, sessionId, policy: role.policy, candidate: { manifest: nativeManifest, baseRevision: plan.task.spec.target.baseRevision, sourceRevision: plan.task.spec.target.sourceRevision, artifacts: piCandidateArtifacts, ...(baseline ? { baseline } : {}) }, resources: activeResources, restore };
1565
+ const release = await this.context.owner.holdLocalActivity();
1566
+ let noEffectMcpAuth = false;
1567
+ let cleanupKnown = false, reader = null, nativeOutcome = null;
1568
+ let structureFailure;
1569
+ let noEffectBudget = false;
1570
+ let midSessionBudget = null;
1571
+ const closeLocal = async () => {
1572
+ this.deadline.onStop(null);
1573
+ if (this.#activeAdapter) {
1574
+ const active = this.#activeAdapter;
1575
+ this.#activeAdapter = null;
1576
+ const closed = await active.close();
1577
+ cleanupKnown = closed.ok;
1578
+ if (!closed.ok)
1579
+ this.#cleanup = 'failed';
1580
+ }
1581
+ if (reader) {
1582
+ const draining = reader;
1583
+ reader = null;
1584
+ try {
1585
+ await draining;
1586
+ }
1587
+ catch {
1588
+ cleanupKnown = false;
1589
+ this.#cleanup = 'failed';
1590
+ this.deadline.stop('OUTPUT_LIMIT');
1591
+ }
1592
+ }
1593
+ };
1594
+ try {
1595
+ this.deadline.assert();
1596
+ const opened = await (this.context.ports.openAdapter ?? openPiAdapterV2)(host, input);
1597
+ if (!opened.ok) {
1598
+ cleanupKnown = opened.error.code !== 'CLEANUP_FAILED';
1599
+ noEffectBudget = isNoEffectBudgetRefusal(opened.error);
1600
+ if (opened.error.effect !== 'none' || !cleanupKnown)
1601
+ this.#candidateKnown = false;
1602
+ refuse(opened.error.code === 'MCP_AUTHENTICATION_REQUIRED' ? 'MCP_AUTHENTICATION_REQUIRED' : 'CAPABILITY_UNSUPPORTED', '', 'execution', { piCode: opened.error.code, stateCode: opened.error.stateErrorCode, effect: opened.error.effect });
1603
+ }
1604
+ const adapter = opened.value;
1605
+ this.#activeAdapter = adapter;
1606
+ this.deadline.onStop(async (reason) => { const stopped = await adapter.cancel({ reason: reason === 'DEADLINE' ? 'deadline' : reason === 'CANCELLED' ? 'operator' : 'consumer_disconnected' }); if (!stopped.ok || stopped.value.localCleanup !== 'complete')
1607
+ refuse('CLEANUP_FAILED', '', 'finalization'); });
1608
+ reader = (async () => { for await (const event of adapter.events()) {
1609
+ await this.events.push('role', null, nodeId, commandId);
1610
+ if (event.kind === 'request_uncertain')
1611
+ this.deadline.stop('AUTHORITY_REFUSED');
1612
+ } })().catch(() => { this.deadline.stop('OUTPUT_LIMIT'); });
1613
+ // Opening/management is bounded, then the original work cutoff is checked again before the only command call.
1614
+ this.deadline.assert();
1615
+ this.#candidateKnown = false;
1616
+ const executed = purpose === 'compaction' ? await adapter.compact({ commandId }) : await adapter.execute({ commandId, text: commandText, purpose, repair });
1617
+ if (!executed.ok) {
1618
+ noEffectBudget = isNoEffectBudgetRefusal(executed.error);
1619
+ if (executed.error.code === 'MCP_AUTHENTICATION_REQUIRED' && executed.error.effect === 'none')
1620
+ noEffectMcpAuth = true;
1621
+ if (!noEffectBudget && isBudgetRefusal(executed.error) && executed.error.effect === 'confirmed') {
1622
+ midSessionBudget = { piCode: executed.error.code, stateCode: executed.error.stateErrorCode };
1623
+ }
1624
+ refuse('RECOVERY_REQUIRED', '', 'execution', { piCode: executed.error.code, stateCode: executed.error.stateErrorCode, effect: executed.error.effect });
1625
+ }
1626
+ const outcome = executed.value;
1627
+ nativeOutcome = await artifacts.json('native-outcome', { version: 1, attemptId: commandId, outcome }, 524288);
1628
+ noEffectBudget = outcome.error !== null && isNoEffectBudgetRefusal(outcome.error) && outcome.requestIds.length === 0 && outcome.operationIds.length === 0
1629
+ && outcome.providerTermination === 'none' && outcome.usage === 'none' && outcome.localCleanup === 'complete' && outcome.cleanupError === null;
1630
+ noEffectMcpAuth = outcome.error?.code === 'MCP_AUTHENTICATION_REQUIRED' && outcome.error?.effect === 'none' && outcome.requestIds.length === 0 && outcome.operationIds.length === 0
1631
+ && outcome.providerTermination === 'none' && outcome.usage === 'none' && outcome.localCleanup === 'complete' && outcome.cleanupError === null;
1632
+ if (outcome.status === 'blocked' && outcome.error?.code === 'MCP_AUTHENTICATION_REQUIRED' && outcome.providerTermination === 'confirmed' && outcome.usage === 'complete' && outcome.localCleanup === 'complete' && outcome.cleanupError === null) {
1633
+ this.deadline.assert();
1634
+ const captured = await captureRole(adapter, store, artifacts, lock, role, attempt, outcome, this.context.source, cycleHostProtection(this.context));
1635
+ structureFailure = await this.completeCapture(attempt, captured);
1636
+ refuse('MCP_AUTHENTICATION_REQUIRED', '', 'execution', { piCode: 'MCP_AUTHENTICATION_REQUIRED', effect: outcome.error.effect });
1637
+ }
1638
+ if (!noEffectBudget && outcome.status === 'failed' && outcome.error !== null && isBudgetRefusal(outcome.error) && outcome.error.effect === 'confirmed' && outcome.providerTermination === 'confirmed' && outcome.usage === 'complete' && outcome.localCleanup === 'complete' && outcome.cleanupError === null) {
1639
+ midSessionBudget = { piCode: outcome.error.code, stateCode: outcome.error.stateErrorCode };
1640
+ }
1641
+ if (outcome.status !== 'execution_settled' || outcome.providerTermination !== 'confirmed' || outcome.usage !== 'complete')
1642
+ refuse('RECOVERY_REQUIRED', '', 'execution', { piCode: outcome.error?.code ?? null, effect: outcome.error?.effect ?? 'possible' });
1643
+ this.deadline.assert();
1644
+ const captured = await captureRole(adapter, store, artifacts, lock, role, attempt, outcome, this.context.source, cycleHostProtection(this.context));
1645
+ if ((repair === 'format' || purpose === 'compaction') && !same(captured.digest, oldDigest))
1646
+ refuse('CAPABILITY_UNSUPPORTED', '', 'execution', { effect: 'confirmed' });
1647
+ structureFailure = await this.completeCapture(attempt, captured);
1648
+ if (stateValue(store.inspect()).ledger.admittedCalls + delegatedCounts.modelCalls > lock.spec.contract.spec.budgets.maxModelCalls) {
1649
+ cleanupKnown = true;
1650
+ this.#candidateKnown = true;
1651
+ refuse('BUDGET_EXHAUSTED', '', 'execution', { stateCode: 'BUDGET_EXHAUSTED', effect: 'none' });
1652
+ }
1653
+ }
1654
+ catch (error) {
1655
+ let failure = error;
1656
+ if (noEffectBudget || noEffectMcpAuth) {
1657
+ this.#candidateKnown = false;
1658
+ await closeLocal();
1659
+ if (cleanupKnown && this.deadline.reason === null) {
1660
+ const afterState = await schedulingSnapshot(store, authority, lock, artifacts, this.candidate, this.draft.candidate);
1661
+ if (same(originalState, afterState)) {
1662
+ this.#candidateKnown = true;
1663
+ failure = new ControllerFailure({ ...safeDiagnostic(failure, 'execution'), code: noEffectMcpAuth ? 'MCP_AUTHENTICATION_REQUIRED' : 'BUDGET_EXHAUSTED', stateCode: noEffectMcpAuth ? null : 'BUDGET_EXHAUSTED', piCode: noEffectMcpAuth ? 'MCP_AUTHENTICATION_REQUIRED' : null, effect: 'none' });
1664
+ }
1665
+ else
1666
+ this.#candidateKnown = false;
1667
+ }
1668
+ else
1669
+ this.#candidateKnown = false;
1670
+ }
1671
+ else if (midSessionBudget) {
1672
+ this.#candidateKnown = false;
1673
+ await closeLocal();
1674
+ const facts = store.inspect();
1675
+ if (cleanupKnown && this.deadline.reason === null && facts.ok && storeFactsCertain(facts.value)) {
1676
+ failure = new ControllerFailure({
1677
+ ...safeDiagnostic(failure, 'execution'),
1678
+ code: 'BUDGET_EXHAUSTED',
1679
+ stateCode: midSessionBudget.stateCode,
1680
+ piCode: midSessionBudget.piCode,
1681
+ effect: 'confirmed',
1682
+ });
1683
+ }
1684
+ }
1685
+ if (this.head?.progress.attempts.at(-1)?.id === commandId && this.head.progress.attempts.at(-1).finished === null) {
1686
+ const diagnostic = safeDiagnostic(failure, 'execution'), after = stateValue(store.inspect()).counts;
1687
+ const outcome = await artifacts.json('role-refusal', { version: 1, attemptId: commandId, command, diagnostic, nativeOutcome, currentCandidate: this.#candidateKnown ? this.draft.candidate.manifest : null, unavailable: this.#candidateKnown ? [] : ['current_candidate', 'submission'], localCleanup: cleanupKnown ? 'complete' : 'pending' }, 65536);
1688
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'role_post' }, attempts: this.draft.attempts.map(item => item.id === commandId ? { ...item, finished: { after: { requests: after.requests, operations: after.operations }, outcome, nativeCheckpointId: null } } : item), nodes: this.draft.nodes.map(item => item.id === nodeId ? { ...item, state: 'failed' } : descendants(plan, nodeId).includes(item.id) && item.state === 'pending' ? { ...item, state: 'not_run' } : item) }, 'role.' + ordinal + '.post');
1689
+ }
1690
+ throw failure;
1691
+ }
1692
+ finally {
1693
+ await closeLocal();
1694
+ if (cleanupKnown)
1695
+ release();
1696
+ else if (this.#cleanup === 'complete')
1697
+ this.#cleanup = 'pending';
1698
+ }
1699
+ if (structureFailure === 'SUBMISSION_AMBIGUOUS')
1700
+ refuse(structureFailure, '', 'verification');
1701
+ if (structureFailure === 'SUBMISSION_INVALID')
1702
+ await this.repairFormat(nodeId);
1703
+ }
1704
+ async resumeAttempt(adopt) {
1705
+ const attempt = this.draft.attempts.at(-1);
1706
+ if (!attempt || attempt.finished !== null)
1707
+ return;
1708
+ if (!adopt) {
1709
+ await this.role(attempt.nodeId, attempt.repair, undefined, attempt);
1710
+ return;
1711
+ }
1712
+ const original = this.context.plan.roles.find(role => role.roleId === this.context.plan.orderedDAG.find(node => node.id === attempt.nodeId).roleId);
1713
+ const role = attempt.repair === 'format' ? { ...original, policy: formatPolicy(original.policy) } : original;
1714
+ const captured = await adoptRoleCapture(this.context.store, this.context.artifacts, this.context.lock, role, attempt, undefined, this.context.source, cycleHostProtection(this.context));
1715
+ const failure = await this.completeCapture(attempt, captured);
1716
+ if (failure === 'SUBMISSION_AMBIGUOUS')
1717
+ refuse(failure, '', 'verification');
1718
+ if (failure === 'SUBMISSION_INVALID')
1719
+ await this.repairFormat(attempt.nodeId);
1720
+ }
1721
+ repairBound(kind, actionable, repeats) {
1722
+ const view = this.deadline.assert(), { plan } = this.context, delegated = countDelegatedBudgets(plan, this.draft.attempts);
1723
+ const latest = this.draft.failures.at(-1), refusal = repairDisposition(kind, { attempts: this.draft.attempts.length, maxAttempts: plan.capacity.A,
1724
+ formatRepairs: view.ledger.formatRepairs + delegated.formatRepairs, implementationRepairs: view.ledger.implementationRepairs + delegated.implementationRepairs, maxFormatRepairs: plan.budgets.maxFormatRepairs, maxImplementationRepairs: plan.budgets.maxImplementationRepairs,
1725
+ repeats: repeats ?? latest?.count ?? 0, actionable, uncertain: !storeFactsCertain(view) });
1726
+ if (refusal)
1727
+ refuse(refusal, '', 'execution');
1728
+ }
1729
+ async formatRepairPrompt(nodeId) {
1730
+ const raw = this.draft.failures.at(-1)?.evidence ?? this.draft.submission;
1731
+ this.repairBound('format', raw !== null);
1732
+ if (!raw)
1733
+ refuse('EVIDENCE_UNAVAILABLE', '', 'verification');
1734
+ const node = this.context.plan.orderedDAG.find(item => item.id === nodeId);
1735
+ const role = this.context.plan.roles.find(item => item.roleId === node?.roleId);
1736
+ const maxPromptBytes = role ? Math.min(16384, role.policy.limits.promptBytes) : 16384;
1737
+ const bytes = await this.context.artifacts.read(raw, 1048576);
1738
+ if (isVerdictStep(node)) {
1739
+ return verdictFormatPrompt(bytes, maxPromptBytes);
1740
+ }
1741
+ const allowedCheckIds = this.context.plan.task.spec.acceptance.checks.map(item => item.id);
1742
+ return formatPrompt(bytes, allowedCheckIds, maxPromptBytes);
1743
+ }
1744
+ async repairFormat(nodeId) {
1745
+ const prompt = await this.formatRepairPrompt(nodeId);
1746
+ await this.role(nodeId, 'format', prompt);
1747
+ }
1748
+ currentChecks() { return [...this.checks.values()].filter(check => check.generation === this.generation); }
1749
+ currentRefusals() { return [...this.refusals.values()].filter(item => item.generation === this.generation); }
1750
+ async verifyEligible() {
1751
+ for (const slot of this.context.plan.verifierSlots) {
1752
+ const nodes = this.context.plan.orderedDAG.filter(node => node.kind === 'check' && node.handler.id === slot.handler.id);
1753
+ if (nodes.some(node => this.draft.nodes.find(item => item.id === node.id)?.state !== 'completed'))
1754
+ continue;
1755
+ await this.runVerifier(slot.id);
1756
+ }
1757
+ }
1758
+ async graph() {
1759
+ const { plan } = this.context;
1760
+ for (;;) {
1761
+ const node = nextNode(plan, this.draft.nodes);
1762
+ if (!node)
1763
+ break;
1764
+ if (node.kind === 'agent')
1765
+ await this.role(node.id);
1766
+ else {
1767
+ const slot = plan.verifierSlots.find(slot => slot.handler.id === node.handler.id);
1768
+ if (!slot)
1769
+ refuse('CAPABILITY_UNSUPPORTED', '', 'verification');
1770
+ const epochBefore = this.reworkEpoch;
1771
+ const checked = await this.runVerifier(slot.id), state = checked.status === 'passed' ? 'completed' : checked.status;
1772
+ const actualState = this.draft.nodes.find(item => item.id === node.id).state;
1773
+ const validCheckRework = node.onRework !== undefined &&
1774
+ checked.status === 'failed' &&
1775
+ ((this.reworkEpoch === epochBefore + 1 && actualState === 'pending') ||
1776
+ (this.haltedVerdictStatus() === 'blocked' && actualState === 'blocked'));
1777
+ // Node disposition is part of the same predefined post-job boundary, never an extra checkpoint.
1778
+ if (actualState !== state && !validCheckRework)
1779
+ refuse('RECOVERY_REQUIRED', '', 'execution');
1780
+ }
1781
+ }
1782
+ await this.verifyEligible();
1783
+ }
1784
+ async prepareImplementationRepair() {
1785
+ const { plan } = this.context;
1786
+ if (plan.budgets.maxImplementationRepairs === 0)
1787
+ return null;
1788
+ const checks = this.currentChecks(), required = plan.verifierSlots.filter(slot => slot.implicit === null && plan.task.spec.acceptance.required.includes(slot.checkId));
1789
+ const failed = checks.filter(check => {
1790
+ if (check.status !== 'failed')
1791
+ return false;
1792
+ const slot = required.find(item => item.id === check.slotId);
1793
+ if (!slot)
1794
+ return false;
1795
+ if (slot.handler.implementation === 'benchmark-gate.v1'
1796
+ && (check.reason === 'BENCHMARK_PREEMPTED' || authenticatedBenchmarkGate(check).retryablePreemption)) {
1797
+ return false;
1798
+ }
1799
+ return true;
1800
+ });
1801
+ if (!failed.length || this.submission?.value.status === 'no_change' && !plan.noChangeEligibility.available)
1802
+ return null;
1803
+ const allAvailable = required.every(slot => checks.some(check => check.slotId === slot.id && check.status !== 'blocked'));
1804
+ if (!allAvailable || checks.some(check => plan.verifierSlots.find(slot => slot.id === check.slotId).implicit === 'scope' && check.status !== 'passed'))
1805
+ return null;
1806
+ const isMutating = (role) => role.policy.tools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash');
1807
+ const mutatingTasks = this.draft.attempts.filter(attempt => attempt.purpose === 'task' && attempt.repair !== 'format' && attempt.finished?.nativeCheckpointId && isMutating(plan.roles.find(role => role.roleId === plan.orderedDAG.find(node => node.id === attempt.nodeId).roleId)));
1808
+ const prior = mutatingTasks.filter(attempt => (attempt.reworkEpoch ?? 0) === this.reworkEpoch).at(-1) ?? mutatingTasks.at(-1);
1809
+ const target = prior?.nodeId, node = plan.orderedDAG.find(node => node.id === target), role = plan.roles.find(role => role.roleId === node?.roleId);
1810
+ if (!node || !role || !isMutating(role))
1811
+ return null;
1812
+ this.repairBound('implementation', true, Math.max(0, ...this.draft.failures.filter(item => failed.some(check => same(check.output, item.evidence))).map(item => item.count)));
1813
+ const candidateDigest = this.draft.candidate.digest;
1814
+ if (!(await this.evaluateAlignment('implementation_repair', target, candidateDigest)))
1815
+ return null;
1816
+ const findings = failed.map(check => {
1817
+ const slot = plan.verifierSlots.find(slot => slot.id === check.slotId);
1818
+ const detail = (slot.handler.implementation === 'gate.v1' || slot.handler.implementation === 'benchmark-gate.v1')
1819
+ ? extractGateVerdictDetail(check, slot.handler.implementation === 'benchmark-gate.v1')
1820
+ : undefined;
1821
+ return {
1822
+ checkId: check.checkId,
1823
+ handler: slot.handler.implementation,
1824
+ code: check.reason,
1825
+ ...(detail !== undefined ? { detail } : {}),
1826
+ parameters: slot.handler.parameters,
1827
+ candidate: candidateDigest,
1828
+ };
1829
+ });
1830
+ const maxPromptBytes = Math.min(16384, role.policy.limits.promptBytes);
1831
+ const prefix = 'Repair only writable candidate files for these findings; submit status "blocked" if caused by protected scripts or host environment. Return the complete structured submission. Findings:\n';
1832
+ let prompt = prefix + canonical(findings);
1833
+ if (Buffer.byteLength(prompt, 'utf8') > maxPromptBytes) {
1834
+ for (let index = findings.length - 1; index >= 0 && Buffer.byteLength(prompt, 'utf8') > maxPromptBytes; index--) {
1835
+ if (findings[index].detail !== undefined) {
1836
+ delete findings[index].detail;
1837
+ prompt = prefix + canonical(findings);
1838
+ }
1839
+ }
1840
+ while (findings.length > 1 && Buffer.byteLength(prompt, 'utf8') > maxPromptBytes) {
1841
+ findings.pop();
1842
+ prompt = prefix + canonical(findings);
1843
+ }
1844
+ }
1845
+ return { targetNodeId: target, role, prompt };
1846
+ }
1847
+ async implementationRepair() {
1848
+ const spec = await this.prepareImplementationRepair();
1849
+ if (!spec)
1850
+ return false;
1851
+ await this.role(spec.targetNodeId, 'implementation', spec.prompt);
1852
+ return true;
1853
+ }
1854
+ async ensureSubmissionForAcceptance() {
1855
+ if (this.submission)
1856
+ return;
1857
+ if ((this.draft.stepVerdicts?.length ?? 0) > 0) {
1858
+ const forced = this.haltedVerdictStatus();
1859
+ const status = forced === 'failed' ? 'failed' : forced === 'blocked' ? 'blocked' : 'completed';
1860
+ const value = { version: 1, status, checks: [], reason: status === 'completed' ? null : 'step_verdict_' + status };
1861
+ const raw = await this.context.artifacts.json('submission', value, 1048576);
1862
+ this.submission = { version: 1, origin: 'controller', raw, value };
1863
+ return;
1864
+ }
1865
+ if (this.context.plan.orderedDAG.some(node => node.kind === 'agent'))
1866
+ refuse('EVIDENCE_UNAVAILABLE', '', 'verification');
1867
+ const value = { version: 1, status: 'completed', checks: [], reason: null };
1868
+ const raw = await this.context.artifacts.json('submission', value, 1048576);
1869
+ this.submission = { version: 1, origin: 'controller', raw, value };
1870
+ }
1871
+ async execute() {
1872
+ if (!this.head)
1873
+ await this.bootstrap();
1874
+ else {
1875
+ if (this.head.progress.attempts.at(-1)?.finished === null)
1876
+ await this.resumeAttempt(this.resumeAdoption === true);
1877
+ const retained = [...this.head.progress.verifierReceipts, ...this.head.progress.verifierRefusals].filter(row => row.generation === this.generation);
1878
+ for (const row of retained)
1879
+ await this.runVerifier(row.slot);
1880
+ const attempt = this.draft.attempts.at(-1);
1881
+ if (attempt?.finished?.nativeCheckpointId === null) {
1882
+ await refuseFromRoleOutcome(this.context.artifacts, attempt.finished.outcome, this.draft.candidate.manifest, () => { this.#candidateKnown = false; });
1883
+ }
1884
+ if (attempt?.finished?.nativeCheckpointId && attempt.purpose !== 'compaction' && !this.haltedVerdictStatus() && this.draft.nodes.find(node => node.id === attempt.nodeId)?.state === 'failed') {
1885
+ await this.repairFormat(attempt.nodeId);
1886
+ }
1887
+ }
1888
+ await this.graph();
1889
+ for (;;) {
1890
+ await this.ensureSubmissionForAcceptance();
1891
+ const checks = this.currentChecks();
1892
+ const preverified = await verifyControllerVerifierCasDescriptors(this.context.plan, checks, {
1893
+ signal: this.deadline.abort.signal,
1894
+ checkAuthority: async () => {
1895
+ this.deadline.assert(true);
1896
+ await this.context.owner.assertCurrent();
1897
+ },
1898
+ });
1899
+ const verdictHalt = this.haltedVerdictStatus();
1900
+ const acceptance = evaluateControllerAcceptance(this.context.plan, this.context.lock, this.candidate.manifest, this.candidate.files, this.generation, checks, this.submission.value, this.context.store, verdictHalt, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), null, preverified);
1901
+ if (verdictHalt === null && acceptance.result.spec.status === 'failed' && await this.implementationRepair()) {
1902
+ await this.graph();
1903
+ continue;
1904
+ }
1905
+ return acceptance.result.spec.status === 'completed' ? await this.publishBoundary(acceptance) : acceptance;
1906
+ }
1907
+ }
1908
+ async publishBoundary(acceptance) {
1909
+ const { plan, lock, store, loaded } = this.context, publication = plan.publication, overlayOpts = this.#overlayBounds().options;
1910
+ if (publication.mode !== 'pull_request' || ['confirmed', 'failed', 'unresolved'].includes(this.draft.publication.status))
1911
+ return acceptance;
1912
+ const view = stateValue(store.inspect()), endpoint = loaded.registry.spec.publicationEndpoints.find(item => item.id === publication.endpointRef);
1913
+ if (!endpoint)
1914
+ refuse('CONFIG_REFERENCE', '/spec/publication', 'execution');
1915
+ const subject = (() => { const bound = bindSubject(lock, this.candidate.manifest, overlayOpts); if (!bound.ok)
1916
+ refuse('ARTIFACT_INVALID', '', 'execution'); return bound.value; })();
1917
+ const scope = acceptance.verifierMatrix.find(row => row.implicit === 'scope');
1918
+ const head = headRevision(this.context.descriptor.repository);
1919
+ if (![plan.task.spec.target.baseRevision, plan.task.spec.target.sourceRevision].includes(head))
1920
+ refuse('TARGET_MISMATCH', '', 'execution');
1921
+ if (this.draft.publication.status !== 'pending') {
1922
+ const eligible = this.draft.nodes.every(node => node.state === 'completed') && scope?.status === 'passed'
1923
+ && storeFactsCertain(view)
1924
+ && this.submission !== null && this.submission.value.status === 'completed'
1925
+ && same(this.draft.candidate.digest, subject.candidateDigest);
1926
+ if (!eligible) {
1927
+ this.#publicationObservation = { status: 'not_run', reason: 'ineligible', receipt: null };
1928
+ return acceptance;
1929
+ }
1930
+ }
1931
+ const prepared = preparePublication(plan, lock, view.storeId, endpoint, subject);
1932
+ const operation = store.getOperation(prepared.operationId);
1933
+ await this.events.push('publication', null);
1934
+ if (!this.head?.progress.stage.consumed.includes('publication.pre'))
1935
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'publication_pre' }, publication: { status: 'pending', operationId: prepared.operationId, receipt: null } }, 'publication.pre');
1936
+ this.deadline.assert();
1937
+ const result = !operation.ok && operation.error.code === 'RECORD_NOT_FOUND'
1938
+ ? await this.publisher.run(prepared, endpoint, this.deadline.abort.signal)
1939
+ : await this.publisher.restore(prepared, endpoint);
1940
+ if (result.kind === 'settled') {
1941
+ this.#publicationObservation = result.outcome === 'succeeded'
1942
+ ? { status: 'confirmed', reason: null, receipt: result.receiptRef }
1943
+ : { status: 'failed', reason: 'not_executed', receipt: result.receiptRef };
1944
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'publication_post' }, publication: { status: result.outcome === 'succeeded' ? 'confirmed' : 'failed', operationId: prepared.operationId, receipt: result.receiptRef } }, 'publication.post');
1945
+ }
1946
+ else {
1947
+ this.#publicationObservation = { status: 'unresolved', reason: result.reason, receipt: null };
1948
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'publication_post' }, publication: { status: 'unresolved', operationId: prepared.operationId, receipt: null } }, 'publication.post');
1949
+ }
1950
+ const checks = this.currentChecks();
1951
+ const preverified = await verifyControllerVerifierCasDescriptors(plan, checks, {
1952
+ signal: this.deadline.abort.signal,
1953
+ checkAuthority: async () => {
1954
+ this.deadline.assert(true);
1955
+ await this.context.owner.assertCurrent();
1956
+ },
1957
+ });
1958
+ return evaluateControllerAcceptance(plan, lock, this.candidate.manifest, this.candidate.files, this.generation, checks, this.submission.value, store, null, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), null, preverified);
1959
+ }
1960
+ async terminal(primary, drainWindowMs = 0) {
1961
+ const { store, artifacts, lock } = this.context, secondary = [];
1962
+ const accepted = 'result' in primary, status = accepted ? primary.result.spec.status : primary.code;
1963
+ let observations = null, primaryRef = null, admitted = false;
1964
+ const current = stateValue(store.inspect()), finalizer = new Finalizer(artifacts, Math.max(current.clock.remainingTaskMs.safeValue ?? 0, drainWindowMs));
1965
+ const checkpoint = async (kind, phase) => {
1966
+ // Worst-case logical progress, receipt index and checkpoint framing; no extra allowance is granted.
1967
+ finalizer.reserve(65536 + 65536 + 40960);
1968
+ const stopped = accepted && ['exhausted', 'expired', 'cancelled'].includes(primary.result.spec.status);
1969
+ await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind }, nodes: this.draft.nodes.map(node => stopped && node.state === 'pending' ? { ...node, state: 'not_run' } : node), terminalIntent: { primary: status, result: primaryRef, observations } }, phase);
1970
+ finalizer.check();
1971
+ };
1972
+ try {
1973
+ primaryRef = await finalizer.put(accepted ? 'result' : 'incident', accepted ? primary.result : primary);
1974
+ await checkpoint('terminal_intent', 'terminal.intent');
1975
+ admitted = true;
1976
+ await this.events.push('terminal', accepted ? null : primary.code);
1977
+ await checkpoint('terminal_result', 'terminal.result');
1978
+ // Event bytes were already synced during work. Sealing is no-overwrite metadata, not a final body rewrite.
1979
+ const eventsRef = await this.events.close();
1980
+ finalizer.check();
1981
+ const storedVerdicts = this.head?.progress.stepVerdicts ?? [];
1982
+ const hydratedVerdicts = await hydrateStepVerdicts(artifacts, storedVerdicts);
1983
+ const boundedFindings = boundFindingsForObservations(hydratedVerdicts.flatMap(item => item.verdict.findings));
1984
+ observations = await finalizer.put('observations', {
1985
+ version: 1,
1986
+ primary: primaryRef,
1987
+ requestedStatus: accepted ? primary.requestedStatus : null,
1988
+ diagnostic: accepted ? primary.diagnostic : primary.code,
1989
+ requestedStatusSource: this.submission === null ? 'unavailable' : this.submission.origin === 'controller' ? 'controller_check_only' : 'captured_submission',
1990
+ selectedNoChangeCheck: accepted ? primary.selectedNoChangeCheck : this.context.plan.noChangeEligibility.checkId,
1991
+ contradictions: accepted ? primary.contradictions : [],
1992
+ verifierMatrix: accepted ? primary.verifierMatrix : null,
1993
+ verification: accepted ? primary.verification : null,
1994
+ preflightRefusals: accepted ? primary.preflightRefusals : null,
1995
+ events: eventsRef,
1996
+ cleanup: this.#cleanup,
1997
+ memory: { status: 'not_requested', reason: null },
1998
+ publication: this.#publicationObservation,
1999
+ ...(storedVerdicts.length > 0 ? { stepVerdicts: storedVerdicts } : {}),
2000
+ ...(boundedFindings.findings.length > 0 ? { findings: boundedFindings.findings } : {}),
2001
+ ...(boundedFindings.findingsTruncated ? { findingsTruncated: true, totalFindingsCount: boundedFindings.totalFindingsCount } : {}),
2002
+ ...(this.advisoryObservations.length > 0 ? { advisoryDecisions: this.advisoryObservations } : {}),
2003
+ });
2004
+ await checkpoint('terminal_observations', 'terminal.observations');
2005
+ }
2006
+ catch (error) {
2007
+ secondary.push(safeDiagnostic(error, 'finalization').code);
2008
+ }
2009
+ finally {
2010
+ try {
2011
+ await this.events.close();
2012
+ }
2013
+ catch {
2014
+ secondary.push('CLEANUP_FAILED');
2015
+ this.#cleanup = 'pending';
2016
+ }
2017
+ }
2018
+ const finalVerdicts = await hydrateStepVerdicts(artifacts, this.head?.progress.stepVerdicts).catch(() => []);
2019
+ const finalFindings = finalVerdicts.flatMap(item => item.verdict.findings);
2020
+ if (!admitted)
2021
+ return freeze({ kind: 'incident', version: 1, incident: incident({ version: 1, code: 'RECOVERY_REQUIRED', phase: 'finalization', path: '', stateCode: null, piCode: null, effect: 'possible', retryable: false }, lock.spec.runId, lock.spec.lockHash, [this.context.descriptor.plan, this.context.source.inventory, ...(primaryRef ? [primaryRef] : [])], ['terminal_admission'], this.#cleanup) });
2022
+ if (accepted) {
2023
+ return freeze({
2024
+ kind: 'result',
2025
+ version: 1,
2026
+ runId: lock.spec.runId,
2027
+ result: primary.result,
2028
+ observations,
2029
+ secondary,
2030
+ ...(finalFindings.length > 0 ? { findings: freeze(finalFindings) } : {}),
2031
+ ...(finalVerdicts.length > 0 ? { stepVerdicts: freeze([...finalVerdicts]) } : {}),
2032
+ });
2033
+ }
2034
+ return freeze({ kind: 'incident', version: 1, incident: primary });
2035
+ }
2036
+ async finish() {
2037
+ let primary;
2038
+ try {
2039
+ primary = await this.execute();
2040
+ }
2041
+ catch (error) {
2042
+ const diagnostic = safeDiagnostic(error, 'execution');
2043
+ if (diagnostic.code === 'CAPABILITY_UNSUPPORTED' && diagnostic.path === '/spec/profiles/roles') {
2044
+ try {
2045
+ await this.deadline.dispose();
2046
+ }
2047
+ catch { /* ignore */ }
2048
+ throw error;
2049
+ }
2050
+ const facts = this.context.store.inspect();
2051
+ const certain = facts.ok && facts.value.clockStatus === 'trusted' && !facts.value.counts.dispatchedRequests && !facts.value.counts.unresolvedRequests && !facts.value.counts.unresolvedOperations && !facts.value.ledger.violations.length;
2052
+ if (this.#candidateKnown && facts.ok && (['DEADLINE', 'CANCELLED', 'BUDGET_EXHAUSTED', 'ATTEMPT_LIMIT', 'REPEAT_FAILURE'].includes(diagnostic.code) || (certain && ['CAPABILITY_UNSUPPORTED', 'MCP_AUTHENTICATION_REQUIRED', 'EVIDENCE_UNAVAILABLE', 'SUBMISSION_AMBIGUOUS', 'SUBMISSION_INVALID'].includes(diagnostic.code)))) {
2053
+ const forced = diagnostic.code === 'DEADLINE' ? 'expired' : diagnostic.code === 'CANCELLED' ? 'cancelled' : ['SUBMISSION_AMBIGUOUS', 'SUBMISSION_INVALID'].includes(diagnostic.code) ? 'failed' : ['CAPABILITY_UNSUPPORTED', 'MCP_AUTHENTICATION_REQUIRED', 'EVIDENCE_UNAVAILABLE'].includes(diagnostic.code) ? 'blocked' : 'exhausted';
2054
+ const forcedDiagnostic = ['CAPABILITY_UNSUPPORTED', 'MCP_AUTHENTICATION_REQUIRED', 'EVIDENCE_UNAVAILABLE', 'SUBMISSION_AMBIGUOUS', 'SUBMISSION_INVALID'].includes(diagnostic.code) ? diagnostic.code : null;
2055
+ try {
2056
+ const checks = this.currentChecks();
2057
+ const preverified = await verifyControllerVerifierCasDescriptors(this.context.plan, checks, {
2058
+ checkAuthority: () => this.context.owner.assertCurrent(),
2059
+ });
2060
+ primary = evaluateControllerAcceptance(this.context.plan, this.context.lock, this.candidate.manifest, this.candidate.files, this.generation, checks, this.submission?.value ?? null, this.context.store, forced, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), forcedDiagnostic, preverified);
2061
+ }
2062
+ catch {
2063
+ primary = incident(diagnostic, this.context.lock.spec.runId, this.context.lock.spec.lockHash, [this.context.descriptor.plan, this.context.source.inventory], ['authoritative_result'], this.#cleanup);
2064
+ }
2065
+ }
2066
+ else
2067
+ primary = incident(diagnostic, this.context.lock.spec.runId, this.context.lock.spec.lockHash, [this.context.descriptor.plan, this.context.source.inventory], this.#candidateKnown ? ['authoritative_result'] : ['current_candidate', 'submission', 'authoritative_result'], this.#cleanup);
2068
+ }
2069
+ try {
2070
+ await this.deadline.dispose();
2071
+ }
2072
+ catch {
2073
+ this.#cleanup = 'failed';
2074
+ }
2075
+ if (this.#cleanup !== 'complete' && 'result' in primary)
2076
+ primary = incident({ version: 1, code: 'CLEANUP_FAILED', phase: 'finalization', path: '', stateCode: null, piCode: null, effect: 'possible', retryable: false }, this.context.lock.spec.runId, this.context.lock.spec.lockHash, [this.context.descriptor.plan, this.context.source.inventory], ['local_cleanup'], this.#cleanup);
2077
+ return this.terminal(primary);
2078
+ }
2079
+ }
2080
+ export async function executeCycleContext(context, restored) {
2081
+ let execution;
2082
+ let delegatedUnsupported = null;
2083
+ try {
2084
+ const cycle = new Cycle(context, restored?.head, restored?.candidate, restored?.adopt);
2085
+ cycle.submission = restored?.submission ?? null;
2086
+ execution = await cycle.finish();
2087
+ }
2088
+ catch (error) {
2089
+ if (error instanceof ControllerFailure && error.diagnostic.code === 'CAPABILITY_UNSUPPORTED' && error.diagnostic.path === '/spec/profiles/roles') {
2090
+ delegatedUnsupported = error;
2091
+ }
2092
+ else {
2093
+ execution = { kind: 'incident', version: 1, incident: incident(safeDiagnostic(error, 'execution'), context.lock.spec.runId, context.lock.spec.lockHash, [context.descriptor.plan, context.source.inventory], ['authoritative_result'], 'pending') };
2094
+ }
2095
+ }
2096
+ let cleanup;
2097
+ try {
2098
+ const released = context.store.release(context.authority);
2099
+ const closed = context.store.close();
2100
+ cleanup = released.ok && closed.ok;
2101
+ if (cleanup)
2102
+ await context.owner.release();
2103
+ }
2104
+ catch {
2105
+ cleanup = false;
2106
+ }
2107
+ if (!cleanup)
2108
+ return { kind: 'incident', version: 1, 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') };
2109
+ if (delegatedUnsupported)
2110
+ throw delegatedUnsupported;
2111
+ return execution;
2112
+ }
2113
+ export function runCycle(input) { return runCycleWithPorts(input); }
2114
+ export function runCycleWithPorts(input, ports = {}) {
2115
+ return result(async () => {
2116
+ const fields = Object.keys(input);
2117
+ record(input, fields);
2118
+ if (fields.some(key => !['configuration', 'repository', 'runRoot', 'runId', 'signal', 'onEvent'].includes(key)))
2119
+ refuse('CONFIG_SCHEMA', '', 'admission');
2120
+ if (input.onEvent !== undefined && typeof input.onEvent !== 'function' || input.signal !== undefined && !(input.signal instanceof AbortSignal))
2121
+ refuse('CONFIG_SCHEMA', '', 'admission');
2122
+ validateGateUrlOverrides(ports.gateUrlOverrides, 'admission');
2123
+ validatePortPolicyFields(ports, 'admission');
2124
+ if (input.signal?.aborted)
2125
+ refuse('CANCELLED', '', 'admission');
2126
+ const compiled = await compilePlan(input.configuration);
2127
+ if (!compiled.ok)
2128
+ throw new ControllerFailure(compiled.error);
2129
+ validateGateUrlOverrides(ports.gateUrlOverrides, 'admission', input.configuration.registry.spec.gateEndpoints);
2130
+ if (compiled.value.orderedDAG.some(node => node.kind === 'agent' && compiled.value.roles.find(role => role.roleId === node.roleId)?.adapter === 'delegated'))
2131
+ refuse('CAPABILITY_UNSUPPORTED', '/spec/profiles/roles', 'admission');
2132
+ const context = await createCycle(input, ports);
2133
+ return executeCycleContext(context);
2134
+ }, 'admission');
2135
+ }