@defrex/autobuild 1.9.0 → 1.11.0

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 (537) hide show
  1. package/README.md +3 -3
  2. package/SPEC.md +2232 -175
  3. package/bin/ab-dispatch-generation.ts +5 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/agent-runtimes.md +30 -3
  6. package/docs/answering-blocked-builds.md +35 -7
  7. package/docs/architecture.md +436 -63
  8. package/docs/build-store.md +10 -7
  9. package/docs/builds.md +5 -0
  10. package/docs/cli.md +40 -2
  11. package/docs/configuration-overview.md +5 -1
  12. package/docs/configuration.md +649 -74
  13. package/docs/dispatcher.md +79 -6
  14. package/docs/forges.md +8 -1
  15. package/docs/getting-started.md +1 -1
  16. package/docs/integration-overview.md +4 -2
  17. package/docs/integration-tree.md +102 -11
  18. package/docs/merge-policy.md +30 -14
  19. package/docs/migration-1.0.md +2 -1
  20. package/docs/operating.md +36 -6
  21. package/docs/operator-api.md +251 -20
  22. package/docs/operator-surfaces.md +85 -0
  23. package/docs/optimization-nodes.md +1100 -0
  24. package/docs/overview.md +1 -1
  25. package/docs/plugin-authoring.md +83 -13
  26. package/docs/remote-store-protocol.md +137 -17
  27. package/docs/remote-ticket-protocol.md +90 -2
  28. package/docs/restacking.md +119 -15
  29. package/docs/seams.md +2 -2
  30. package/docs/setup.md +27 -4
  31. package/docs/skills.md +4 -2
  32. package/docs/spec-standard.md +2 -1
  33. package/docs/ticket-dependencies.md +15 -3
  34. package/docs/ticket-migration.md +4 -2
  35. package/docs/ticket-sources.md +54 -14
  36. package/docs/tickets.md +21 -6
  37. package/docs/troubleshooting.md +11 -2
  38. package/docs/verification.md +15 -3
  39. package/docs/workspaces.md +6 -1
  40. package/package.json +9 -5
  41. package/packages/core/src/accounts/chatgpt-oauth.ts +7 -5
  42. package/packages/core/src/cli/accounts.ts +7 -2
  43. package/packages/core/src/cli/attempt.ts +103 -0
  44. package/packages/core/src/cli/attention.ts +11 -2
  45. package/packages/core/src/cli/binary-direct.ts +54 -1
  46. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  47. package/packages/core/src/cli/binary.ts +5 -3
  48. package/packages/core/src/cli/build-control.ts +407 -67
  49. package/packages/core/src/cli/context.ts +272 -15
  50. package/packages/core/src/cli/dashboard/detail.ts +26 -2
  51. package/packages/core/src/cli/dashboard/facts.ts +89 -56
  52. package/packages/core/src/cli/dashboard/header.ts +101 -0
  53. package/packages/core/src/cli/dashboard/integration-detail.ts +7 -2
  54. package/packages/core/src/cli/dashboard/landing-display.ts +15 -2
  55. package/packages/core/src/cli/dashboard/model.ts +133 -66
  56. package/packages/core/src/cli/dashboard/objective-row.ts +221 -0
  57. package/packages/core/src/cli/dashboard/poll.ts +178 -76
  58. package/packages/core/src/cli/dashboard/render.ts +172 -227
  59. package/packages/core/src/cli/dashboard/reopen-display.ts +39 -0
  60. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  61. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  62. package/packages/core/src/cli/dashboard/tree.ts +12 -1
  63. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  64. package/packages/core/src/cli/dispatch-args.ts +44 -1
  65. package/packages/core/src/cli/dispatch-frontend.ts +29 -30
  66. package/packages/core/src/cli/dispatch-launch-stop.ts +73 -0
  67. package/packages/core/src/cli/dispatch-launcher.ts +41 -46
  68. package/packages/core/src/cli/dispatch-repository-feed.ts +1 -1
  69. package/packages/core/src/cli/dispatch-web.ts +155 -0
  70. package/packages/core/src/cli/dispatch.ts +216 -38
  71. package/packages/core/src/cli/env.ts +42 -0
  72. package/packages/core/src/cli/help.ts +293 -12
  73. package/packages/core/src/cli/init-agent.ts +4 -1
  74. package/packages/core/src/cli/init-readiness-remote.ts +3 -2
  75. package/packages/core/src/cli/init-validation.ts +5 -5
  76. package/packages/core/src/cli/init.ts +3 -2
  77. package/packages/core/src/cli/judge-entry.ts +82 -0
  78. package/packages/core/src/cli/judge.ts +233 -0
  79. package/packages/core/src/cli/landings.ts +3 -2
  80. package/packages/core/src/cli/main.ts +481 -148
  81. package/packages/core/src/cli/mcp.ts +35 -3
  82. package/packages/core/src/cli/measurement-text.ts +19 -0
  83. package/packages/core/src/cli/objective.ts +154 -0
  84. package/packages/core/src/cli/operator-preference.ts +57 -0
  85. package/packages/core/src/cli/publication-settlement.ts +106 -22
  86. package/packages/core/src/cli/repo-lease.ts +3 -0
  87. package/packages/core/src/cli/repo-state.ts +56 -6
  88. package/packages/core/src/cli/repository-status.ts +205 -56
  89. package/packages/core/src/cli/status.ts +275 -16
  90. package/packages/core/src/cli/store-opening.ts +4 -0
  91. package/packages/core/src/cli/terminal-restore.ts +32 -7
  92. package/packages/core/src/cli/terminals.ts +205 -8
  93. package/packages/core/src/cli/ticket-start.ts +53 -0
  94. package/packages/core/src/cli/ticket.ts +166 -38
  95. package/packages/core/src/cli/upgrade-agent.ts +12 -8
  96. package/packages/core/src/cli/wait.ts +22 -8
  97. package/packages/core/src/cli/watch.ts +361 -95
  98. package/packages/core/src/cli/web.ts +139 -0
  99. package/packages/core/src/config/create-labels.ts +23 -0
  100. package/packages/core/src/config/live.ts +101 -14
  101. package/packages/core/src/config/load.ts +61 -20
  102. package/packages/core/src/config/local.ts +212 -0
  103. package/packages/core/src/config/pipeline-source.ts +3 -3
  104. package/packages/core/src/config/reference.ts +18 -0
  105. package/packages/core/src/config/roles.ts +182 -73
  106. package/packages/core/src/config/schema.ts +157 -19
  107. package/packages/core/src/events/catalog.ts +43 -3
  108. package/packages/core/src/events/compatibility.ts +7 -1
  109. package/packages/core/src/events/payloads.ts +685 -1
  110. package/packages/core/src/events/policy.ts +63 -0
  111. package/packages/core/src/events/repository.ts +153 -27
  112. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +1797 -199
  113. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  114. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/0ab2a90d0305dc9d.json.gz +0 -0
  115. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/10a4657408d4e121.json.gz +0 -0
  116. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1152a2e97ee81728.json.gz +0 -0
  117. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/13ca84752c5f8b54.json.gz +0 -0
  118. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1411d1cdbdd9911e.json.gz +0 -0
  119. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1444fe1fa7fc802c.json.gz +0 -0
  120. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1491ac0600349391.json.gz +0 -0
  121. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  122. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1921f86f752428c9.json.gz +0 -0
  123. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1972c1d66008ef6b.json.gz +0 -0
  124. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/19e8e43e7f3f1a06.json.gz +0 -0
  125. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/20a85c143c3e8164.json.gz +0 -0
  126. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/21ce2c0bf58318e1.json.gz +0 -0
  127. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/293dcb3a94fb3470.json.gz +0 -0
  128. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2ab7436356267118.json.gz +0 -0
  129. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2d084641735caaff.json.gz +0 -0
  130. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3237bcecf68e5db9.json.gz +0 -0
  131. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/33d0cc593610e56f.json.gz +0 -0
  132. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3451ed2136dcc356.json.gz +0 -0
  133. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/358ec8693f2237e6.json.gz +0 -0
  134. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/35cf9ccc4478b2d2.json.gz +0 -0
  135. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3649e7bd1203f154.json.gz +0 -0
  136. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/378da6dece82202a.json.gz +0 -0
  137. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/38c75099d9191471.json.gz +0 -0
  138. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/398952f1f01db1a3.json.gz +0 -0
  139. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3b64d352d56c9121.json.gz +0 -0
  140. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3dc486226c05372d.json.gz +0 -0
  141. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/431c9bb2ee8838e0.json.gz +0 -0
  142. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4400dffca929e2f0.json.gz +0 -0
  143. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/49064fc079964a5c.json.gz +0 -0
  144. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  145. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4edded75f17742f4.json.gz +0 -0
  146. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4f00c0f2c8afd159.json.gz +0 -0
  147. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516a5a7aadf97587.json.gz +0 -0
  148. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516dc6ea85d67cd7.json.gz +0 -0
  149. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  150. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/584e2ba74608e051.json.gz +0 -0
  151. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/59ffaa6974094c72.json.gz +0 -0
  152. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5bb43afb121674c6.json.gz +0 -0
  153. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5f0ca42af862c4ee.json.gz +0 -0
  154. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6118031132db9bfc.json.gz +0 -0
  155. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63107a8d58776b63.json.gz +0 -0
  156. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63546b08d4d6fa11.json.gz +0 -0
  157. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/643d70429ce03dad.json.gz +0 -0
  158. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/677ea92572c29082.json.gz +0 -0
  159. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6ae5bf60504d6467.json.gz +0 -0
  160. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  161. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6efdc8defc75fccb.json.gz +0 -0
  162. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/71c53d33f09d8204.json.gz +0 -0
  163. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7267ca2757cffba7.json.gz +0 -0
  164. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/76b7d4244082b3f9.json.gz +0 -0
  165. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7749f918c6f10968.json.gz +0 -0
  166. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7833e42d16301424.json.gz +0 -0
  167. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7d4edad0614adaf1.json.gz +0 -0
  168. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/837365898d04f45a.json.gz +0 -0
  169. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/85f9f0c921b8b5bb.json.gz +0 -0
  170. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8879f57a24733897.json.gz +0 -0
  171. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/88cb9e71bdec972d.json.gz +0 -0
  172. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  173. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8a0cd6dd06cc155e.json.gz +0 -0
  174. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8aa9ca8609dc051d.json.gz +0 -0
  175. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8c8640255bd61658.json.gz +0 -0
  176. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8cc15eb1807c0157.json.gz +0 -0
  177. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8ced97c44bc0af3a.json.gz +0 -0
  178. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8d4144004720b9f8.json.gz +0 -0
  179. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8db633ead1807f8b.json.gz +0 -0
  180. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8e42cdbd0994ab0c.json.gz +0 -0
  181. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9011d0f6ff955ef9.json.gz +0 -0
  182. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/916ebc5433801c41.json.gz +0 -0
  183. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9539b995af5c54a9.json.gz +0 -0
  184. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/95f391bfd7b7dbd7.json.gz +0 -0
  185. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9613e8fa568a9281.json.gz +0 -0
  186. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9a68f8753bd9038d.json.gz +0 -0
  187. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9b25e58227080094.json.gz +0 -0
  188. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9ee3919fbd4f9458.json.gz +0 -0
  189. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a04a34cc2717147b.json.gz +0 -0
  190. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a0b32c12e4e6edb6.json.gz +0 -0
  191. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a55218252707bdd3.json.gz +0 -0
  192. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a732fd08b31522a6.json.gz +0 -0
  193. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  194. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a9d206a01f9039e5.json.gz +0 -0
  195. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/abf7fe3c92c82f2d.json.gz +0 -0
  196. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ac928b04842c00db.json.gz +0 -0
  197. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/af953392d81911da.json.gz +0 -0
  198. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0d877c44810ecb0.json.gz +0 -0
  199. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0f7c6ebb2db57fc.json.gz +0 -0
  200. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b905c22ec17eed31.json.gz +0 -0
  201. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/bce0c54e865f4b79.json.gz +0 -0
  202. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c68b7ee2e2610f30.json.gz +0 -0
  203. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c7f7e0378aeea237.json.gz +0 -0
  204. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c98cb1659eb142b6.json.gz +0 -0
  205. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ca830adf06ed55a1.json.gz +0 -0
  206. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cb3a219f33e437ca.json.gz +0 -0
  207. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cf1e0c0d82567e0c.json.gz +0 -0
  208. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d008d86d9ff77b30.json.gz +0 -0
  209. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d1432a819d8e48c5.json.gz +0 -0
  210. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d185ed6aa9192aff.json.gz +0 -0
  211. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  212. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d873fad29d6c7e55.json.gz +0 -0
  213. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/db84b12316e2da4a.json.gz +0 -0
  214. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ddf6dc967d898767.json.gz +0 -0
  215. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/dfc64de6e7bfc0a0.json.gz +0 -0
  216. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e2f18fa32fe1f6d0.json.gz +0 -0
  217. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e37393fed29e84c5.json.gz +0 -0
  218. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e6a8585e2a054ff6.json.gz +0 -0
  219. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e7e9e327baca6903.json.gz +0 -0
  220. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e86447af0571672c.json.gz +0 -0
  221. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ea819202d22122e5.json.gz +0 -0
  222. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb4535585f2e84f6.json.gz +0 -0
  223. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb7ddd5319d09e27.json.gz +0 -0
  224. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eca4959b2b87ae15.json.gz +0 -0
  225. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ee10d7959ec4843c.json.gz +0 -0
  226. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ef1b68347966ab26.json.gz +0 -0
  227. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f3e55425cc41f230.json.gz +0 -0
  228. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f40042c1cdb9fd43.json.gz +0 -0
  229. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f48466215c790a3f.json.gz +0 -0
  230. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f5b9ace9b59351e7.json.gz +0 -0
  231. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  232. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fa8f1475a55be935.json.gz +0 -0
  233. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fb21116a15d0b1f1.json.gz +0 -0
  234. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fe95444fbeabe592.json.gz +0 -0
  235. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/09bf0a1611d07363.json +984 -0
  236. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/10eac4988d66e161.json +1067 -0
  237. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/1a436b5fb45aee3e.json +1116 -0
  238. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/249db6f7a41f90e2.json +161 -0
  239. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/25dcb2fb6eaa83f4.json +858 -0
  240. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/2e1bdc763924616f.json +4932 -0
  241. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/30e9dabce3c4263d.json +399 -0
  242. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  243. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/4898ef339c68fa36.json +83 -0
  244. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/51816c0ffa62af6e.json +417 -0
  245. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/561bf45320062a44.json +83 -0
  246. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5672d0233085d050.json +84 -0
  247. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5e39f42cbdbf35ef.json +163 -0
  248. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/7771a7a2250f9964.json +868 -0
  249. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  250. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  251. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/881c491321bec99a.json +1074 -0
  252. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/965f25c3af1d2cdc.json +160 -0
  253. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9b76d89da575ca90.json +20 -0
  254. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9eb485320a72a9ff.json +233 -0
  255. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  256. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a60448c01016135e.json +18 -0
  257. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6584fb61b6679bd.json +97 -0
  258. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  259. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  260. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  261. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c88365c25b3186d3.json +543 -0
  262. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e8f0481b23f90056.json +711 -0
  263. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ee55782ed40ebbac.json +110 -0
  264. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc5082fac8167f3d.json +98 -0
  265. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  266. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fd55c329cfe921cc.json +1069 -0
  267. package/packages/core/src/kernel/attempt-creation-key.ts +20 -0
  268. package/packages/core/src/kernel/attempt-settlement.ts +125 -0
  269. package/packages/core/src/kernel/auto-merge-default.ts +1 -3
  270. package/packages/core/src/kernel/auto-merge.ts +1 -3
  271. package/packages/core/src/kernel/build-roster.ts +230 -0
  272. package/packages/core/src/kernel/dispatch-capacity.ts +316 -40
  273. package/packages/core/src/kernel/dispatch-placement.ts +1 -1
  274. package/packages/core/src/kernel/dispatch-settings.ts +1 -4
  275. package/packages/core/src/kernel/dispatch-status.ts +3 -5
  276. package/packages/core/src/kernel/dispatch-upgrade.ts +1 -1
  277. package/packages/core/src/kernel/engine.ts +152 -18
  278. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  279. package/packages/core/src/kernel/forge-checks.ts +140 -0
  280. package/packages/core/src/kernel/forge-health.ts +2 -2
  281. package/packages/core/src/kernel/generated-files.ts +43 -0
  282. package/packages/core/src/kernel/generated-regeneration.ts +254 -0
  283. package/packages/core/src/kernel/generators/build-log.ts +30 -2
  284. package/packages/core/src/kernel/generators/optimization-log.ts +679 -0
  285. package/packages/core/src/kernel/generators/panel-log.ts +133 -0
  286. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  287. package/packages/core/src/kernel/guarded-forge.ts +76 -11
  288. package/packages/core/src/kernel/harvest.ts +1 -4
  289. package/packages/core/src/kernel/head-paths.ts +4 -1
  290. package/packages/core/src/kernel/history-retention.ts +337 -0
  291. package/packages/core/src/kernel/incremental-fixtures.ts +6 -0
  292. package/packages/core/src/kernel/incremental.ts +14 -4
  293. package/packages/core/src/kernel/integration-landing.ts +64 -13
  294. package/packages/core/src/kernel/integration-stack.ts +123 -20
  295. package/packages/core/src/kernel/integration-state.ts +39 -2
  296. package/packages/core/src/kernel/janitor-failure.ts +2 -0
  297. package/packages/core/src/kernel/kernel-git.ts +1 -1
  298. package/packages/core/src/kernel/landing-measurement.ts +275 -0
  299. package/packages/core/src/kernel/landing-readiness.ts +2 -0
  300. package/packages/core/src/kernel/landing-state.ts +20 -1
  301. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  302. package/packages/core/src/kernel/leaf-restack-state.ts +99 -4
  303. package/packages/core/src/kernel/log-index-value.ts +2 -0
  304. package/packages/core/src/kernel/log-index.ts +100 -3
  305. package/packages/core/src/kernel/measurement.ts +406 -0
  306. package/packages/core/src/kernel/mixed-version.ts +6 -3
  307. package/packages/core/src/kernel/node-landing.ts +92 -18
  308. package/packages/core/src/kernel/node-restack-state.ts +27 -1
  309. package/packages/core/src/kernel/node-restack-transaction.ts +80 -23
  310. package/packages/core/src/kernel/node-verification-context.ts +14 -4
  311. package/packages/core/src/kernel/open-pr-backpressure-state.ts +24 -0
  312. package/packages/core/src/kernel/open-pr-backpressure.ts +133 -0
  313. package/packages/core/src/kernel/optimization-admission.ts +490 -0
  314. package/packages/core/src/kernel/optimization.ts +953 -0
  315. package/packages/core/src/kernel/panel.ts +225 -0
  316. package/packages/core/src/kernel/phase-failures.ts +121 -0
  317. package/packages/core/src/kernel/phases.ts +42 -6
  318. package/packages/core/src/kernel/pr-attachments.ts +4 -16
  319. package/packages/core/src/kernel/pr-summary.ts +2 -2
  320. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  321. package/packages/core/src/kernel/read-deferrals.ts +2 -2
  322. package/packages/core/src/kernel/read-facts.ts +69 -31
  323. package/packages/core/src/kernel/reconcile-restack.ts +352 -103
  324. package/packages/core/src/kernel/reducer-identity.ts +659 -0
  325. package/packages/core/src/kernel/reducer-registry.ts +62 -9
  326. package/packages/core/src/kernel/reducer-revisions.ts +75 -0
  327. package/packages/core/src/kernel/reducer.ts +269 -11
  328. package/packages/core/src/kernel/reopen-state.ts +48 -0
  329. package/packages/core/src/kernel/reopen.ts +143 -0
  330. package/packages/core/src/kernel/replay-retention.ts +208 -39
  331. package/packages/core/src/kernel/repository-attention.ts +1 -1
  332. package/packages/core/src/kernel/rollup.ts +61 -0
  333. package/packages/core/src/kernel/service-facts.ts +19 -7
  334. package/packages/core/src/kernel/setup-streak.ts +38 -0
  335. package/packages/core/src/kernel/step-durations.ts +257 -0
  336. package/packages/core/src/kernel/target-observation.ts +6 -1
  337. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  338. package/packages/core/src/kernel/terminal-guard.ts +13 -5
  339. package/packages/core/src/kernel/ticket-handbacks.ts +1 -1
  340. package/packages/core/src/kernel/ticket-migrations.ts +1 -1
  341. package/packages/core/src/kernel/ticket-preparation.ts +1 -1
  342. package/packages/core/src/kernel/ticket-source-health.ts +1 -1
  343. package/packages/core/src/kernel/ticket-starts.ts +118 -0
  344. package/packages/core/src/kernel/ticket-wait.ts +37 -2
  345. package/packages/core/src/kernel/verify-diff-base.ts +67 -0
  346. package/packages/core/src/kernel/verify-stage-state.ts +1 -0
  347. package/packages/core/src/kernel/verify-stages.ts +51 -1
  348. package/packages/core/src/objective.ts +532 -0
  349. package/packages/core/src/ontology.ts +54 -6
  350. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  351. package/packages/core/src/operator/annotations.ts +105 -4
  352. package/packages/core/src/operator/attention.ts +470 -0
  353. package/packages/core/src/operator/canonical-skills.ts +35 -0
  354. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  355. package/packages/core/src/operator/context-prompts.ts +61 -0
  356. package/packages/core/src/operator/control.ts +2 -1
  357. package/packages/core/src/operator/index.ts +61 -1
  358. package/packages/core/src/operator/landings.ts +28 -19
  359. package/packages/core/src/operator/optimization.ts +314 -0
  360. package/packages/core/src/operator/protocol.ts +33 -1
  361. package/packages/core/src/operator/query.ts +137 -73
  362. package/packages/core/src/operator/read-view.ts +5 -2
  363. package/packages/core/src/operator/registry.ts +625 -59
  364. package/packages/core/src/operator/requests.ts +45 -20
  365. package/packages/core/src/operator/sandbox-host.ts +107 -11
  366. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  367. package/packages/core/src/operator/sandbox.ts +778 -82
  368. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  369. package/packages/core/src/operator/ticket-assets.ts +167 -0
  370. package/packages/core/src/operator/ticket-start.ts +152 -0
  371. package/packages/core/src/operator/tickets.ts +36 -4
  372. package/packages/core/src/plugin-sdk/index.ts +24 -0
  373. package/packages/core/src/plugins/manifest.ts +1 -1
  374. package/packages/core/src/plugins/registry.ts +1 -0
  375. package/packages/core/src/ports/forge/contract.ts +9 -0
  376. package/packages/core/src/ports/forge/fake.ts +114 -2
  377. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  378. package/packages/core/src/ports/forge/git-rewrite.ts +6 -4
  379. package/packages/core/src/ports/forge/github-readiness.ts +1 -1
  380. package/packages/core/src/ports/forge/github-transport.ts +156 -1
  381. package/packages/core/src/ports/forge/github.ts +388 -100
  382. package/packages/core/src/ports/forge/local-git.ts +61 -1
  383. package/packages/core/src/ports/forge/readiness.ts +15 -3
  384. package/packages/core/src/ports/forge-failure.ts +46 -0
  385. package/packages/core/src/ports/forge-request-context.ts +23 -1
  386. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  387. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  388. package/packages/core/src/ports/runner/antigravity.ts +1071 -0
  389. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  390. package/packages/core/src/ports/runner/claude.ts +6 -1
  391. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  392. package/packages/core/src/ports/runner/codex.ts +11 -2
  393. package/packages/core/src/ports/runner/contract.ts +25 -1
  394. package/packages/core/src/ports/runner/fake.ts +2 -2
  395. package/packages/core/src/ports/runner/native-cli-fixture.ts +40 -5
  396. package/packages/core/src/ports/runner/native-process-fixture.ts +4 -1
  397. package/packages/core/src/ports/runner/pi.ts +23 -7
  398. package/packages/core/src/ports/runner/production.ts +19 -2
  399. package/packages/core/src/ports/runner/session-env.ts +65 -5
  400. package/packages/core/src/ports/runner/start-prompt.ts +6 -4
  401. package/packages/core/src/ports/tickets/contract.ts +75 -2
  402. package/packages/core/src/ports/tickets/fake.ts +11 -0
  403. package/packages/core/src/ports/tickets/file.ts +18 -0
  404. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  405. package/packages/core/src/ports/tickets/github.ts +407 -35
  406. package/packages/core/src/ports/tickets/hosted-index.ts +16 -1
  407. package/packages/core/src/ports/tickets/labels.ts +21 -0
  408. package/packages/core/src/ports/tickets/linear.ts +163 -0
  409. package/packages/core/src/ports/tickets/migration.ts +2 -0
  410. package/packages/core/src/ports/tickets/priority.ts +20 -0
  411. package/packages/core/src/ports/tickets/remote-protocol.ts +105 -6
  412. package/packages/core/src/ports/tickets/remote.ts +203 -17
  413. package/packages/core/src/ports/tickets/search.ts +139 -0
  414. package/packages/core/src/ports/tickets/tree.ts +17 -4
  415. package/packages/core/src/ports/types.ts +202 -6
  416. package/packages/core/src/ports/workspace/builtin-capabilities.ts +16 -4
  417. package/packages/core/src/ports/workspace/commit-preservation.ts +182 -64
  418. package/packages/core/src/ports/workspace/create.ts +18 -1
  419. package/packages/core/src/ports/workspace/fake.ts +340 -12
  420. package/packages/core/src/ports/workspace/git-worktree.ts +846 -43
  421. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  422. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  423. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1539 -221
  424. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  425. package/packages/core/src/processes/agent-context.ts +469 -0
  426. package/packages/core/src/processes/build-execution-state.ts +1 -3
  427. package/packages/core/src/processes/build-runner.ts +1982 -528
  428. package/packages/core/src/processes/dispatch-failure-budget.ts +1 -1
  429. package/packages/core/src/processes/dispatcher-selectors.ts +15 -13
  430. package/packages/core/src/processes/dispatcher.ts +3003 -308
  431. package/packages/core/src/processes/execution-no-progress.ts +40 -1
  432. package/packages/core/src/processes/execution-settlement.ts +2 -6
  433. package/packages/core/src/processes/harvest-execution-state.ts +2 -6
  434. package/packages/core/src/processes/harvest-runner.ts +7 -2
  435. package/packages/core/src/processes/infrastructure-failure-budget.ts +1 -3
  436. package/packages/core/src/processes/judge-launcher.ts +38 -0
  437. package/packages/core/src/processes/measurement-runner.ts +235 -0
  438. package/packages/core/src/processes/optimization-activity.ts +120 -0
  439. package/packages/core/src/processes/optimization-merges.ts +101 -0
  440. package/packages/core/src/processes/optimization-stop.ts +179 -0
  441. package/packages/core/src/processes/panel-runner.ts +756 -0
  442. package/packages/core/src/processes/phase-failure-budget.ts +2 -0
  443. package/packages/core/src/processes/publication-state.ts +1 -4
  444. package/packages/core/src/processes/repo-view.ts +154 -6
  445. package/packages/core/src/processes/sandbox-state.ts +54 -10
  446. package/packages/core/src/processes/tick-publication.ts +2 -0
  447. package/packages/core/src/processes/tick-state.ts +1 -3
  448. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  449. package/packages/core/src/processes/workspace-preservation.ts +67 -9
  450. package/packages/core/src/scenarios/harness.ts +19 -13
  451. package/packages/core/src/store/account-redaction.ts +1 -0
  452. package/packages/core/src/store/adapter.ts +52 -1
  453. package/packages/core/src/store/agent-context.ts +432 -0
  454. package/packages/core/src/store/build-feed.ts +291 -0
  455. package/packages/core/src/store/build-scope.ts +19 -1
  456. package/packages/core/src/store/contract.ts +955 -14
  457. package/packages/core/src/store/digest.ts +104 -9
  458. package/packages/core/src/store/histogram.ts +113 -0
  459. package/packages/core/src/store/judge-authority.ts +161 -0
  460. package/packages/core/src/store/local/schema.ts +62 -0
  461. package/packages/core/src/store/local/store.ts +628 -22
  462. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  463. package/packages/core/src/store/memory.ts +461 -69
  464. package/packages/core/src/store/open-builds.ts +19 -0
  465. package/packages/core/src/store/phase-session.ts +256 -6
  466. package/packages/core/src/store/reduced-reads.ts +24 -4
  467. package/packages/core/src/store/reducer-value-shapes.json +18023 -11824
  468. package/packages/core/src/store/reducer-values.ts +6 -1
  469. package/packages/core/src/store/remote/client.ts +220 -4
  470. package/packages/core/src/store/remote/compatibility.ts +1 -1
  471. package/packages/core/src/store/remote/credentials.ts +31 -1
  472. package/packages/core/src/store/remote/index.ts +41 -0
  473. package/packages/core/src/store/remote/protocol.ts +107 -0
  474. package/packages/core/src/store/remote/released-clients.json +22 -0
  475. package/packages/core/src/store/remote/released-reducer-values/1.10.0.json +34439 -0
  476. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  477. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  478. package/packages/core/src/store/remote/token.ts +13 -4
  479. package/packages/core/src/store/repo-state-events.ts +6 -8
  480. package/packages/core/src/store/retention.ts +23 -1
  481. package/packages/core/src/store/rollups.ts +337 -0
  482. package/packages/core/src/store/session-handle.ts +20 -2
  483. package/packages/core/src/store/session-reducer.ts +1 -4
  484. package/packages/core/src/store/snapshots.ts +10 -0
  485. package/packages/core/src/store/ticket-assets.ts +1 -3
  486. package/packages/core/src/store/types.ts +117 -9
  487. package/packages/core/src/testing/dispatch-read-budget.ts +1162 -2
  488. package/packages/core/src/testing/git-config-isolation.ts +27 -0
  489. package/packages/core/src/testing/index.ts +40 -0
  490. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  491. package/packages/core/src/testing/reduced-read-budget.ts +5349 -153
  492. package/packages/core/src/web/analytics-source.ts +303 -0
  493. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  494. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  495. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  496. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  497. package/packages/core/src/web/assets/app.css +1 -0
  498. package/packages/core/src/web/assets/app.js +9 -0
  499. package/packages/core/src/web/assets/manifest.json +31 -0
  500. package/packages/core/src/web/assets/theme.js +1 -0
  501. package/packages/core/src/web/bounded.ts +31 -0
  502. package/packages/core/src/web/http.ts +315 -0
  503. package/packages/core/src/web/hub.ts +160 -0
  504. package/packages/core/src/web/options.ts +38 -0
  505. package/packages/core/src/web/overview-source.ts +322 -0
  506. package/packages/core/src/web/page.ts +56 -0
  507. package/packages/core/src/web/protocol.ts +151 -0
  508. package/packages/core/src/web/read-only.ts +23 -0
  509. package/packages/core/src/web/repository-source.ts +35 -0
  510. package/packages/core/src/web/server.ts +97 -0
  511. package/skills/code-review/SKILL.md +26 -2
  512. package/skills/finalize/SKILL.md +10 -4
  513. package/skills/guide/SKILL.md +743 -123
  514. package/skills/guide/references/accounts.md +2 -1
  515. package/skills/guide/references/integration-tree.md +102 -11
  516. package/skills/guide/references/merge-policy.md +30 -14
  517. package/skills/guide/references/migration-1.0.md +2 -1
  518. package/skills/guide/references/operator-api.md +251 -20
  519. package/skills/guide/references/optimization-nodes.md +1100 -0
  520. package/skills/guide/references/plugin-authoring.md +83 -13
  521. package/skills/guide/references/remote-store-protocol.md +137 -17
  522. package/skills/guide/references/remote-ticket-protocol.md +90 -2
  523. package/skills/guide/references/restacking.md +119 -15
  524. package/skills/guide/references/setup.md +27 -4
  525. package/skills/guide/references/spec-standard.md +2 -1
  526. package/skills/guide/references/ticket-dependencies.md +15 -3
  527. package/skills/guide/references/ticket-migration.md +4 -2
  528. package/skills/implement/SKILL.md +74 -5
  529. package/skills/judge/SKILL.md +43 -0
  530. package/skills/operate/SKILL.md +374 -57
  531. package/skills/plan/SKILL.md +28 -4
  532. package/skills/plan-review/SKILL.md +24 -3
  533. package/skills/propose/SKILL.md +121 -0
  534. package/skills/reconcile/SKILL.md +21 -2
  535. package/skills/spec/SKILL.md +63 -11
  536. package/skills/tickets/SKILL.md +94 -9
  537. package/templates/hosted-service/package.json +2 -2
@@ -21,6 +21,14 @@ import type { RuntimeIdentity } from '../events/runtime'
21
21
  import { relaunchTarget } from './execution-relaunch'
22
22
  import { runtimeIdentity } from '../runtime-identity'
23
23
  import { publishExact } from '../kernel/publication'
24
+ import { leafVerifiedRestack } from '../kernel/verify-stages'
25
+ import { leafBaseInUse } from '../kernel/leaf-restack-base'
26
+ import {
27
+ classifyAcceptedLocal,
28
+ openPublishingOwner,
29
+ reprovisionResume,
30
+ targetRewriteQuestion,
31
+ } from '../kernel/target-rewrite-recovery'
24
32
  import { waitResumeSupersedes } from '../kernel/ticket-wait'
25
33
  import {
26
34
  deferMixedVersion,
@@ -35,20 +43,39 @@ import type { OpenSession } from '../kernel/reducer'
35
43
  import { nativeSessionHandleSchema } from '../ports/runner/native-session'
36
44
  import type { NativeSessionObserver } from '../ports/types'
37
45
  import { suspendNativeLanding } from '../kernel/landing-publication'
38
- import { integrationCurrent } from '../kernel/integration-state'
39
- import { replayNodeChange } from '../kernel/node-restack'
40
- import { restoreReplay } from '../kernel/reconcile-restack'
46
+ import { integrationCurrent, nodeLanded } from '../kernel/integration-state'
47
+ import { proposeRunDue } from '../kernel/optimization'
48
+ import { replayNodeChange, validateNodeChange } from '../kernel/node-restack'
49
+ import {
50
+ adoptRegeneratedRestack,
51
+ generatedCleanPathspecs,
52
+ regenerateRestackConflict,
53
+ restoreReplay,
54
+ } from '../kernel/reconcile-restack'
55
+ import {
56
+ consentRevocation,
57
+ resolutionPathsFor,
58
+ revocableConsent,
59
+ } from '../kernel/consent-revocation'
60
+ import { classifyGenerated, generatedSelectors } from '../kernel/generated-files'
61
+ import {
62
+ regenerateConflict,
63
+ RegenerationInterrupted,
64
+ regenerationReason,
65
+ } from '../kernel/generated-regeneration'
41
66
  import { completeAutomaticReconcile } from '../kernel/leaf-restack-completion'
42
67
  import { isRemoteWorkspace } from '../events/workspace-remote'
43
68
  import { withBuildTrailer } from '../kernel/build-identity'
44
69
  import {
45
70
  prepareRestack,
46
71
  recoverLostCandidate,
72
+ redoRestack,
73
+ retireCandidate,
47
74
  publishRestack,
48
75
  retainReplay,
49
76
  requireRewrite,
50
77
  } from '../kernel/reconcile-restack'
51
- import { reconcileHead, reconcileRewriteHead } from '../kernel/reconcile-head'
78
+ import { RetainedHistoryUnavailable, restoreRetainedHead } from '../kernel/history-retention'
52
79
  import {
53
80
  readBuildFacts,
54
81
  readBuildSelector,
@@ -109,11 +136,11 @@ import type { EventPayload } from '../events/payloads'
109
136
  import { KERNEL, agentActor, type Actor } from '../events/envelope'
110
137
  import type { IdSource } from '../ids'
111
138
  import { decideNextFromFacts, type Decision } from '../kernel/engine'
112
- import { defineReducer } from '../kernel/incremental'
113
139
  import { continuesVerifyCycle } from '../kernel/pr-summary'
114
- import { PHASE_SPECS } from '../kernel/phases'
140
+ import { isPhaseTerminalEvent, PHASE_SPECS } from '../kernel/phases'
115
141
  import type { BuildState } from '../kernel/reducer'
116
142
  import { evaluateVerifyApplicability } from '../kernel/verify-applicability'
143
+ import { VERIFY_BASE_ENV } from '../kernel/verify-diff-base'
117
144
  import {
118
145
  verifyPhase,
119
146
  verifyReportKind,
@@ -140,12 +167,47 @@ import type {
140
167
  AgentTurnResult,
141
168
  Forge,
142
169
  SessionStreamSink,
170
+ Transcript,
143
171
  } from '../ports/types'
144
172
  import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution'
145
173
  import { phaseScratchRejection, scratchPathsTouchedInRange } from '../ports/workspace/phase-scratch'
146
174
  import type { Exec } from '../ports/workspace/git-worktree'
147
175
  import type { BuildScopedStore, Clock } from '../store/types'
148
- import { resetsPhaseFailureBudget, type PhaseFailureResetEscalation } from './phase-failure-budget'
176
+ import {
177
+ attemptPanelId,
178
+ baselineMeasurementDue,
179
+ baselineSummary,
180
+ effectiveEpsilon,
181
+ median,
182
+ measurementRequestStatus,
183
+ nodeMeasurementDue,
184
+ nodePanelEscalationId,
185
+ nodePanelId,
186
+ noiseExceeded,
187
+ pendingMeasurementRequest,
188
+ progressMeasurementDue,
189
+ } from '../kernel/measurement'
190
+ import { runPairedMeasurement, type MeasurementResult } from './measurement-runner'
191
+ import { preparationStale, type WorkspacePreparation } from './workspace-preparation'
192
+ import { JUDGE_ROLE } from '../config/roles'
193
+ import type { PanelMetric } from '../objective'
194
+ import type { PanelJudgeOutcome, PanelOrder } from '../kernel/panel'
195
+ import { installedSkillName } from '../skills'
196
+ import { distributionRoot } from '../distribution'
197
+ import {
198
+ JUDGE_CONTEXT_DIR,
199
+ JUDGE_PREFERENCE_OUTBOX,
200
+ runPanelJudges,
201
+ type PanelResult,
202
+ type PanelRunInput,
203
+ } from './panel-runner'
204
+ import type { JudgeLaunch } from '../ports/runner/session-env'
205
+ import {
206
+ appendJudgePreference,
207
+ JUDGE_PREFERENCE_OUTBOX_BYTES,
208
+ judgePreferenceOutboxSchema,
209
+ } from '../store/judge-authority'
210
+ import { bundleJudgeLauncher } from './judge-launcher'
149
211
 
150
212
  export { publicationPending } from './publication-state'
151
213
 
@@ -201,6 +263,9 @@ export interface BuildRunnerOpts {
201
263
  leaseTtlMs?: number
202
264
  /** Test seam for phase-session deadlines. Production uses an unref'ed timer. */
203
265
  scheduleSessionBudget?: (expire: () => void, delayMs: number) => () => void
266
+ /** Test seam for the lease keep-alive. Production uses an unref'ed interval;
267
+ * returns a cancel. */
268
+ scheduleHeartbeat?: (beat: () => void, intervalMs: number) => () => void
204
269
  /** Session streams (SPEC §9): open one stream per session bracket for
205
270
  * runtimes that declare the streaming capability. Default true. A failing
206
271
  * stream path never fails a turn; disabling reproduces the event log
@@ -232,6 +297,20 @@ export interface BuildRunnerDeps {
232
297
  slug: string
233
298
  /** Shell seam for deterministic checks and finalize Git guards (§8.2, D7). */
234
299
  exec: Exec
300
+ /** A signal that aborts after `ms`: one measurement command run's timeout.
301
+ * Defaults to `AbortSignal.timeout`. */
302
+ timeoutSignal?: (ms: number) => AbortSignal
303
+ /** The random source a judge panel draws each judge's A/B order from.
304
+ * Defaults to `Math.random`. */
305
+ random?: () => number
306
+ /** The distribution's install form of `ab-judge`, installed into a judge
307
+ * root when the harness pin predates the vendored copy. Defaults to the
308
+ * running distribution's `skills/judge`. */
309
+ judgeSkill?: () => Promise<string>
310
+ /** The self-contained judge-only `ab` launcher's text, written into each
311
+ * panel's scratch launcher directory. Defaults to bundling the running
312
+ * distribution's judge entry. */
313
+ judgeLauncher?: () => Promise<string>
235
314
  /** Remote publication stays behind the kernel-owned Forge port (D7). */
236
315
  forge: Forge
237
316
  ids: IdSource
@@ -257,6 +336,12 @@ type SkipVerifyDecision = Extract<Decision, { kind: 'skip-verify' }>
257
336
  type RunFinalizeStepDecision = Extract<Decision, { kind: 'run-finalize-step' }>
258
337
  type CheckReconcileProgressDecision = Extract<Decision, { kind: 'check-reconcile-progress' }>
259
338
  type RaiseEscalationDecision = Extract<Decision, { kind: 'raise-escalation' }>
339
+ type MeasureBaselineDecision = Extract<Decision, { kind: 'measure-baseline' }>
340
+ type MeasureProgressDecision = Extract<Decision, { kind: 'measure-progress' }>
341
+ type RunMeasurementDecision = Extract<Decision, { kind: 'run-measurement' }>
342
+
343
+ /** The artifact kind holding a measurement's raw per-sample values. */
344
+ const MEASUREMENT_SAMPLES_ARTIFACT = 'measurement-samples'
260
345
 
261
346
  /** Lease acquisition can finish either workspace-backed attachment or one
262
347
  * engine-selected stop acknowledgement that deliberately needs no workspace. */
@@ -369,6 +454,12 @@ function sessionBudgetError(seconds: number): string {
369
454
  return `phase session budget expired after ${seconds} seconds`
370
455
  }
371
456
 
457
+ function defaultHeartbeatScheduler(beat: () => void, intervalMs: number): () => void {
458
+ const timer = setInterval(beat, intervalMs)
459
+ timer.unref?.()
460
+ return () => clearInterval(timer)
461
+ }
462
+
372
463
  function defaultSessionBudgetScheduler(expire: () => void, delayMs: number): () => void {
373
464
  // Node/Bun timers clamp larger delays. Chunk against an absolute deadline so
374
465
  // a valid large positive config value can never become an immediate expiry.
@@ -404,255 +495,26 @@ function providerAttemptSummary(attempts: readonly ProviderAttempt[] | undefined
404
495
  )
405
496
  }
406
497
 
407
- export interface PhaseFailureTally {
408
- count: number
409
- lastError?: string
410
- lastWillRetry?: boolean
411
- lastProviderAttempts?: readonly ProviderAttempt[]
412
- }
413
-
414
- export const PHASE_FAILURES_REDUCER_VERSION = 3
415
-
416
- /**
417
- * phase.failed tally for one phase+round — D5's retry-guard input. A factory
418
- * because phase and round are parameters of the projection.
419
- *
420
- * An answered escalation re-arms this budget only when its semantic class
421
- * acknowledges phase-runner failures (§15.6-B). Runner-failure causes reset
422
- * their matching round, the phase-level verify cause resets all rounds, and
423
- * unrelated policy causes reset nothing. Cause-less historical and
424
- * non-policy raises retain the legacy round-shaped behavior. Failures after
425
- * an applicable answer count again, so a still-failing phase re-escalates on
426
- * new evidence instead of deadlocking before its recovery session starts.
427
- */
428
- export function phaseFailuresReducer(phase: Phase, round: number) {
429
- return defineReducer<
430
- {
431
- /** id → the raise's reset semantics — answers are matched by id (§15.3). */
432
- raised: Record<string, PhaseFailureResetEscalation & { session?: string }>
433
- owners: Record<string, string>
434
- cancelled: Record<string, boolean>
435
- count: number
436
- lastError?: string
437
- lastWillRetry?: boolean
438
- lastProviderAttempts?: readonly ProviderAttempt[]
439
- },
440
- AbEvent,
441
- PhaseFailureTally
442
- >({
443
- version: PHASE_FAILURES_REDUCER_VERSION,
444
- initial: () => ({ raised: {}, owners: {}, cancelled: {}, count: 0 }),
445
- fold(acc, events) {
446
- for (const event of events) {
447
- switch (event.type) {
448
- case 'session.started':
449
- if (event.payload.phase?.startsWith('verify:') && event.payload.round !== undefined)
450
- acc.owners[event.payload.session] = verifyMemberKey(
451
- event.payload.phase.slice(7),
452
- event.payload.round,
453
- )
454
- break
455
- case 'verify.cancelled':
456
- acc.cancelled[verifyMemberKey(event.payload.step, event.payload.attempt)] = true
457
- break
458
- case 'phase.deferral-escalated':
459
- acc.raised[event.payload.id] = {
460
- phase: event.payload.phase,
461
- round: event.payload.round,
462
- source: 'policy',
463
- deferral: 'own-build-read',
464
- }
465
- break
466
- // A ticket wait's escalation (`wait.entered`) is deliberately not
467
- // registered: ending a wait is not a failure retry, so its answer
468
- // re-arms no budget.
469
- case 'escalation.raised':
470
- acc.raised[event.payload.id] = {
471
- phase: event.payload.phase,
472
- source: event.payload.source,
473
- ...(event.actor.kind === 'agent' ? { session: event.actor.session } : {}),
474
- ...(event.payload.policyCause !== undefined
475
- ? { policyCause: event.payload.policyCause }
476
- : {}),
477
- ...(event.payload.round !== undefined ? { round: event.payload.round } : {}),
478
- }
479
- break
480
- case 'escalation.answered': {
481
- const raise = acc.raised[event.payload.id]
482
- if (raise?.session && acc.cancelled[acc.owners[raise.session] ?? '']) break
483
- if (raise !== undefined && resetsPhaseFailureBudget(raise, phase, round)) {
484
- acc.count = 0
485
- delete acc.lastError
486
- delete acc.lastWillRetry
487
- delete acc.lastProviderAttempts
488
- }
489
- break
490
- }
491
- case 'phase.failed':
492
- if (event.payload.phase === phase && event.payload.round === round) {
493
- acc.count += 1
494
- acc.lastError = event.payload.error
495
- acc.lastWillRetry = event.payload.willRetry
496
- acc.lastProviderAttempts = event.payload.providerAttempts
497
- }
498
- break
499
- default:
500
- break
501
- }
502
- }
503
- },
504
- finish: (acc) => ({
505
- count: acc.count,
506
- ...(acc.lastError !== undefined ? { lastError: acc.lastError } : {}),
507
- ...(acc.lastWillRetry !== undefined ? { lastWillRetry: acc.lastWillRetry } : {}),
508
- ...(acc.lastProviderAttempts !== undefined
509
- ? { lastProviderAttempts: acc.lastProviderAttempts }
510
- : {}),
511
- }),
512
- })
513
- }
514
-
515
- export const SETUP_STREAK_REDUCER_VERSION = 1
516
-
517
- /** Consecutive durable setup failures since the latest successful attachment
518
- * or explicit human answer. The accumulator keeps the boundary seq and the
519
- * failure seqs, so it is exact for any array order. */
520
- export const setupStreakReducer = defineReducer<
521
- { escalations: string[]; boundary: number; failures: number[] },
522
- AbEvent,
523
- number
524
- >({
525
- version: SETUP_STREAK_REDUCER_VERSION,
526
- initial: () => ({ escalations: [], boundary: 0, failures: [] }),
527
- fold(acc, events) {
528
- for (const event of events) {
529
- if (event.type === 'runner.attached') acc.boundary = event.seq
530
- else if (
531
- event.type === 'escalation.raised' &&
532
- event.payload.phase === 'setup' &&
533
- event.payload.source === 'policy'
534
- ) {
535
- if (!acc.escalations.includes(event.payload.id)) acc.escalations.push(event.payload.id)
536
- } else if (
537
- event.type === 'escalation.answered' &&
538
- acc.escalations.includes(event.payload.id)
539
- ) {
540
- acc.boundary = event.seq
541
- } else if (event.type === 'runner.setup-failed') {
542
- acc.failures.push(event.seq)
543
- }
544
- }
545
- },
546
- finish: (acc) => acc.failures.filter((seq) => seq > acc.boundary).length,
547
- })
548
-
549
- export const PUBLISHED_BRANCH_HEAD_REDUCER_VERSION = 5
550
-
551
- /** Latest event-checkpointed branch head that kernel plumbing published;
552
- * undefined while the build has none. */
553
- export const publishedBranchHeadReducer = defineReducer<
554
- { head?: string },
555
- AbEvent,
556
- string | undefined
557
- >({
558
- version: PUBLISHED_BRANCH_HEAD_REDUCER_VERSION,
559
- initial: () => ({}),
560
- fold(acc, events) {
561
- for (const event of events) {
562
- if (event.type === 'implement.completed') {
563
- acc.head = event.payload.commits.head
564
- } else if (event.type === 'restack.rewritten' || event.type === 'restack.completed') {
565
- acc.head =
566
- event.type === 'restack.rewritten'
567
- ? (event.payload.observedHead ?? event.payload.headSha)
568
- : event.payload.headSha
569
- } else if (event.type === 'reconcile.rewritten') {
570
- acc.head = reconcileRewriteHead(event.payload)
571
- } else if (event.type === 'reconcile.completed') {
572
- acc.head = reconcileHead(event.payload)
573
- } else if (
574
- event.type === 'wait.requested' &&
575
- event.payload.publication?.settlement === 'published'
576
- ) {
577
- acc.head = event.payload.publication.sha
578
- } else if (event.type === 'wait.published') {
579
- acc.head = event.payload.sha
580
- } else if (
581
- event.type === 'finalize.step-completed' &&
582
- event.payload.ok &&
583
- event.payload.headSha !== undefined
584
- ) {
585
- acc.head = event.payload.headSha
586
- }
587
- }
588
- },
589
- finish: (acc) => acc.head,
590
- })
591
-
592
- /** Latest event-checkpointed branch head that kernel plumbing published. */
593
- export function selectPublishedBranchHead(events: readonly AbEvent[]): string {
594
- const head = publishedBranchHeadReducer.reduce(events)
595
- if (head === undefined) {
596
- throw new Error(
597
- 'finalize publication requires a prior implement.completed, reconcile.completed, ' +
598
- 'or successful finalize publication head, but this build has none',
599
- )
600
- }
601
- return head
602
- }
603
-
604
- export const VERIFY_DIFF_BASE_REDUCER_VERSION = 3
605
-
606
- /**
607
- * The durable tree against which a conditional verifier evaluates the
608
- * branch's current HEAD, or undefined until a `workspace.provisioned` exists.
609
- * The accumulator keeps the first provisioned base and the latest promoted
610
- * reconcile base separately, so the result is exact for any array order (a
611
- * promotion that precedes the provisioned fact in the array still wins).
612
- */
613
- export const verifyDiffBaseReducer = defineReducer<
614
- { provisioned?: string; promoted?: string; pendingReconcileBase?: string },
615
- AbEvent,
616
- string | undefined
617
- >({
618
- version: VERIFY_DIFF_BASE_REDUCER_VERSION,
619
- initial: () => ({}),
620
- fold(acc, events) {
621
- for (const event of events) {
622
- if (event.type === 'workspace.provisioned') {
623
- if (acc.provisioned === undefined) acc.provisioned = event.payload.base.sha
624
- } else if (event.type === 'restack.completed') {
625
- acc.promoted = event.payload.targetBase
626
- } else if (event.type === 'restack.advanced') {
627
- acc.promoted = event.payload.to
628
- } else if (event.type === 'reconcile.superseded') {
629
- // An abandoned occurrence's base never promotes.
630
- delete acc.pendingReconcileBase
631
- } else if (event.type === 'reconcile.started') {
632
- acc.pendingReconcileBase = event.payload.baseSha
633
- } else if (event.type === 'reconcile.completed') {
634
- if (acc.pendingReconcileBase !== undefined) acc.promoted = acc.pendingReconcileBase
635
- delete acc.pendingReconcileBase
636
- }
637
- }
638
- },
639
- finish: (acc) => (acc.provisioned === undefined ? undefined : (acc.promoted ?? acc.provisioned)),
640
- })
498
+ export {
499
+ selectVerifyDiffBase,
500
+ VERIFY_BASE_ENV,
501
+ verifyDiffBaseReducer,
502
+ } from '../kernel/verify-diff-base'
503
+ export { type PhaseFailureTally, phaseFailuresReducer } from '../kernel/phase-failures'
504
+ export {
505
+ publishedBranchHeadReducer,
506
+ selectPublishedBranchHead,
507
+ } from '../kernel/published-branch-head'
508
+ export { setupStreakReducer } from '../kernel/setup-streak'
641
509
 
642
510
  /**
643
- * Select the durable tree against which a conditional verifier evaluates the
644
- * branch's current HEAD. The initial branch-cut SHA is authoritative until a
645
- * successful reconcile; each completed reconcile promotes the latest start's
646
- * refreshed base SHA. A dangling start is intentionally ignored.
511
+ * The commit verification compares against: a node's integration cycle
512
+ * parent, otherwise the leaf's verify diff base. Reads nothing beyond facts.
647
513
  */
648
- export function selectVerifyDiffBase(events: readonly AbEvent[]): string {
649
- const base = verifyDiffBaseReducer.reduce(events)
650
- if (base === undefined) {
651
- throw new Error(
652
- 'conditional verify requires a workspace.provisioned base SHA, but this build has none',
653
- )
654
- }
655
- return base
514
+ function verifyDiffBaseFrom(
515
+ facts: Awaited<ReturnType<typeof readBuildFacts>>['value'],
516
+ ): string | undefined {
517
+ return facts.state.kind === 'node' ? facts.state.integration?.cycle?.parent : facts.verifyDiffBase
656
518
  }
657
519
 
658
520
  export { parseNulChangedPaths }
@@ -743,8 +605,48 @@ function recoveryMatches(decision: Decision, session: OpenSession): boolean {
743
605
  : false
744
606
  }
745
607
 
608
+ /** One judge panel run's inputs (SPEC §13.1.1). */
609
+ export interface PanelRequest {
610
+ /** The panel id; a later call with the same id resumes the run. */
611
+ id: string
612
+ candidate: string
613
+ baseline: string
614
+ harnessPin: string
615
+ purpose: string
616
+ /** The rubric's path, inside the harness. */
617
+ rubric: string
618
+ harness: readonly string[]
619
+ judges: number
620
+ }
621
+
622
+ function samePanelInputs(
623
+ recorded: EventPayload<'panel.started'>,
624
+ requested: EventPayload<'panel.started'>,
625
+ ): boolean {
626
+ return (
627
+ recorded.candidate === requested.candidate &&
628
+ recorded.baseline === requested.baseline &&
629
+ recorded.harnessPin === requested.harnessPin &&
630
+ recorded.purpose === requested.purpose &&
631
+ recorded.rubric === requested.rubric &&
632
+ recorded.judges === requested.judges &&
633
+ recorded.harness.length === requested.harness.length &&
634
+ recorded.harness.every((path, index) => path === requested.harness[index])
635
+ )
636
+ }
637
+
638
+ /** The running distribution's install form of `ab-judge`. */
639
+ async function distributionJudgeSkill(): Promise<string> {
640
+ const { readDistSkills } = await import('../cli/init')
641
+ const skill = (await readDistSkills(distributionRoot())).find((s) => s.name === 'judge')
642
+ if (skill === undefined) throw new Error('this distribution ships no judge skill')
643
+ return skill.content
644
+ }
645
+
746
646
  export class BuildRunner {
747
647
  private verifyWrites = { tail: Promise.resolve() }
648
+ /** Aborts the running node check once a lease lapse reveals a landing. */
649
+ private checkAbort: AbortController | undefined
748
650
  private async withVerifyWrite<T>(write: () => Promise<T>): Promise<T> {
749
651
  const previous = this.verifyWrites.tail
750
652
  let release!: () => void
@@ -936,7 +838,10 @@ export class BuildRunner {
936
838
  private readonly streamSessions: boolean
937
839
  private readonly onDiagnostic: (message: string) => void
938
840
  private attached = false
939
- private heartbeatTimer: ReturnType<typeof setInterval> | undefined
841
+ /** The base this process's own setup run prepared the workspace for;
842
+ * undefined when setup is unconfigured or the runner is unattached. */
843
+ private preparedFor: WorkspacePreparation | undefined
844
+ private cancelHeartbeat: (() => void) | undefined
940
845
  /** Set when a heartbeat reports the lease lapsed (§7.4): the store never
941
846
  * renews an expired lease, so the holder must re-claim before doing any
942
847
  * more work — or stop, because the sweep may already have launched a
@@ -1138,7 +1043,9 @@ export class BuildRunner {
1138
1043
  if (
1139
1044
  attaching.kind === 'node' &&
1140
1045
  !attaching.nodeRestack?.conflict &&
1141
- !integrationCurrent(attaching)
1046
+ !proposeRunDue(attaching.optimization) &&
1047
+ !integrationCurrent(attaching) &&
1048
+ !nodeMeasurementDue(attaching)
1142
1049
  )
1143
1050
  throw new Error('integration runners require a reserved node conflict')
1144
1051
  const config = await this.captureConfig()
@@ -1162,7 +1069,20 @@ export class BuildRunner {
1162
1069
  }
1163
1070
 
1164
1071
  const state = facts.state
1165
- if (state.kind === 'node' && state.integration?.cycle && !state.nodeRestack?.conflict) {
1072
+ const proposal = state.optimization?.proposal
1073
+ if (
1074
+ state.kind === 'node' &&
1075
+ !state.nodeRestack?.conflict &&
1076
+ proposal !== undefined &&
1077
+ proposeRunDue(state.optimization)
1078
+ ) {
1079
+ // The proposer reads the tree its request recorded, never a later tip.
1080
+ const checkout = await this.deps.exec(['git', 'checkout', '--detach', proposal.head], {
1081
+ cwd: this.deps.workspacePath,
1082
+ })
1083
+ if (checkout.exitCode !== 0)
1084
+ throw new Error(`cannot check out the proposal request head: ${checkout.stderr}`)
1085
+ } else if (state.kind === 'node' && state.integration?.cycle && !state.nodeRestack?.conflict) {
1166
1086
  // Local worktree provisioning may create a new branch at its parent;
1167
1087
  // verification consumes the archived cycle commit, never that mutable tip.
1168
1088
  const checkout = await this.deps.exec(
@@ -1197,10 +1117,24 @@ export class BuildRunner {
1197
1117
  // then keep-alive. Setup runs under this heartbeat so a slow install cannot
1198
1118
  // outlive the claimed lease.
1199
1119
  await store.heartbeat(slug, instance)
1200
- this.heartbeatTimer = setInterval(() => {
1120
+ const scheduleHeartbeat = this.deps.opts?.scheduleHeartbeat ?? defaultHeartbeatScheduler
1121
+ this.cancelHeartbeat = scheduleHeartbeat(() => {
1201
1122
  store.heartbeat(slug, instance).then(
1202
1123
  (alive) => {
1203
- if (!alive) this.leaseLost = true
1124
+ if (alive) return
1125
+ this.leaseLost = true
1126
+ // A lapse during a node check may be the dispatcher withdrawing the
1127
+ // lease after a landing; one reduced read tells it from any other lapse.
1128
+ const check = this.checkAbort
1129
+ if (check)
1130
+ void readBuildFacts(store, slug).then(
1131
+ (facts) => {
1132
+ if (nodeLanded(facts.value.state)) check.abort(new Error(`node ${slug} landed`))
1133
+ },
1134
+ () => {
1135
+ // The next lapsed beat retries.
1136
+ },
1137
+ )
1204
1138
  },
1205
1139
  () => {
1206
1140
  // Store unreachable — the next beat retries; the lease TTL is the
@@ -1208,47 +1142,12 @@ export class BuildRunner {
1208
1142
  },
1209
1143
  )
1210
1144
  }, this.heartbeatMs)
1211
- this.heartbeatTimer.unref?.()
1212
1145
 
1213
1146
  const setup = config.commands.setup
1147
+ const preparedBase = verifyDiffBaseFrom(facts)
1214
1148
  if (setup !== undefined) {
1215
- let failure: EventPayload<'runner.setup-failed'> | undefined
1216
- try {
1217
- const result = await this.deps.exec(['sh', '-c', setup], {
1218
- cwd: this.deps.workspacePath,
1219
- })
1220
- if (result.exitCode !== 0) {
1221
- failure = {
1222
- command: setup,
1223
- attempt: streak + 1,
1224
- exitStatus: result.exitCode,
1225
- output: [result.stderr, result.stdout].filter((text) => text !== '').join('\n'),
1226
- }
1227
- }
1228
- } catch (error) {
1229
- failure = {
1230
- command: setup,
1231
- attempt: streak + 1,
1232
- exitStatus: null,
1233
- output: errorMessage(error),
1234
- }
1235
- }
1236
-
1237
- if (failure !== undefined) {
1238
- try {
1239
- await store.append(slug, {
1240
- actor: KERNEL,
1241
- type: 'runner.setup-failed',
1242
- payload: failure,
1243
- } satisfies EventWrite<'runner.setup-failed'>)
1244
- const exhausted = failure.attempt >= config.policy.maxSetupAttempts
1245
- if (exhausted) await this.raiseSetupEscalation(failure)
1246
- throw new SetupFailureError(slug, failure, exhausted)
1247
- } finally {
1248
- this.stopHeartbeat()
1249
- this.attached = false
1250
- }
1251
- }
1149
+ const failure = await this.executeSetup(setup, streak + 1)
1150
+ if (failure !== undefined) await this.failSetup(failure, config)
1252
1151
  }
1253
1152
 
1254
1153
  if (recovering) {
@@ -1258,13 +1157,82 @@ export class BuildRunner {
1258
1157
  } catch (error) {
1259
1158
  this.stopHeartbeat()
1260
1159
  this.attached = false
1160
+ this.preparedFor = undefined
1261
1161
  throw error
1262
1162
  }
1263
1163
  }
1164
+ this.preparedFor = setup === undefined ? undefined : { base: preparedBase }
1264
1165
  this.attached = true
1265
1166
  return { kind: 'workspace-ready' }
1266
1167
  }
1267
1168
 
1169
+ /** Run `[commands].setup` in the workspace; the failure payload, if any. */
1170
+ private async executeSetup(
1171
+ setup: string,
1172
+ attempt: number,
1173
+ ): Promise<EventPayload<'runner.setup-failed'> | undefined> {
1174
+ try {
1175
+ const result = await this.deps.exec(['sh', '-c', setup], {
1176
+ cwd: this.deps.workspacePath,
1177
+ })
1178
+ if (result.exitCode === 0) return undefined
1179
+ return {
1180
+ command: setup,
1181
+ attempt,
1182
+ exitStatus: result.exitCode,
1183
+ output: [result.stderr, result.stdout].filter((text) => text !== '').join('\n'),
1184
+ }
1185
+ } catch (error) {
1186
+ return { command: setup, attempt, exitStatus: null, output: errorMessage(error) }
1187
+ }
1188
+ }
1189
+
1190
+ /**
1191
+ * Record a setup failure durably, raise the policy blocker at the attempt
1192
+ * limit, and leave the runner unattached. Always throws `SetupFailureError`:
1193
+ * only a later successful setup (`runner.attached`) clears the failure.
1194
+ */
1195
+ private async failSetup(
1196
+ failure: EventPayload<'runner.setup-failed'>,
1197
+ config: Config,
1198
+ ): Promise<never> {
1199
+ const { store, slug } = this.deps
1200
+ try {
1201
+ await store.append(slug, {
1202
+ actor: KERNEL,
1203
+ type: 'runner.setup-failed',
1204
+ payload: failure,
1205
+ } satisfies EventWrite<'runner.setup-failed'>)
1206
+ const exhausted = failure.attempt >= config.policy.maxSetupAttempts
1207
+ if (exhausted) await this.raiseSetupEscalation(failure)
1208
+ throw new SetupFailureError(slug, failure, exhausted)
1209
+ } finally {
1210
+ this.stopHeartbeat()
1211
+ this.attached = false
1212
+ this.preparedFor = undefined
1213
+ }
1214
+ }
1215
+
1216
+ /**
1217
+ * Rerun setup before a workspace-using decision when a kernel operation
1218
+ * moved the build onto a new base since this process prepared it
1219
+ * (§15.6-C). Compares against facts `step()` already read; the only store
1220
+ * read is the setup streak, once per base move.
1221
+ */
1222
+ private async refreshPreparation(
1223
+ facts: Awaited<ReturnType<typeof readBuildFacts>>['value'],
1224
+ decision: Decision,
1225
+ config: Config,
1226
+ ): Promise<void> {
1227
+ const setup = config.commands.setup
1228
+ const base = verifyDiffBaseFrom(facts)
1229
+ if (setup === undefined || !preparationStale(this.preparedFor, base, decision)) return
1230
+ const streak = await readBuildSelector(this.deps.store, this.deps.slug, 'setupStreak')
1231
+ const failure = await this.executeSetup(setup, streak + 1)
1232
+ if (failure !== undefined) await this.failSetup(failure, config)
1233
+ this.preparedFor = { base }
1234
+ }
1235
+
1268
1236
  /**
1269
1237
  * One read→decide→execute cycle (§8): the unit-test surface. Returns the
1270
1238
  * decision it executed; `wait` decisions execute nothing.
@@ -1285,6 +1253,11 @@ export class BuildRunner {
1285
1253
  const config = await this.captureConfig()
1286
1254
  const facts = (await readBuildFacts(store, slug)).value
1287
1255
  const decision = decideNextFromFacts(facts.state, facts.log, config)
1256
+ await this.refreshPreparation(facts, decision, config)
1257
+ // A requested measurement runs where the pipeline is otherwise parked.
1258
+ const parked =
1259
+ decision.kind === 'run-measurement' ||
1260
+ (decision.kind === 'wait' && decision.reason === 'awaiting-pr')
1288
1261
  if (
1289
1262
  this.deps.readVerifyPipeline &&
1290
1263
  ([
@@ -1297,8 +1270,7 @@ export class BuildRunner {
1297
1270
  'record-verify-selection-drift',
1298
1271
  ].includes(decision.kind) ||
1299
1272
  (decision.kind === 'run-phase' && decision.phase === 'finalize') ||
1300
- (decision.kind === 'wait' &&
1301
- decision.reason === 'awaiting-pr' &&
1273
+ (parked &&
1302
1274
  (facts.state.verify.configPin !== undefined ||
1303
1275
  (facts.state.kind === 'node' && integrationCurrent(facts.state)))))
1304
1276
  ) {
@@ -1309,10 +1281,7 @@ export class BuildRunner {
1309
1281
  state: facts.state,
1310
1282
  deployment: config,
1311
1283
  read: this.deps.readVerifyPipeline,
1312
- retainCompletedVerification:
1313
- facts.state.kind !== 'node' &&
1314
- decision.kind === 'wait' &&
1315
- decision.reason === 'awaiting-pr',
1284
+ retainCompletedVerification: facts.state.kind !== 'node' && parked,
1316
1285
  exec: this.deps.exec,
1317
1286
  workspacePath: this.deps.workspacePath,
1318
1287
  })
@@ -1378,6 +1347,12 @@ export class BuildRunner {
1378
1347
  case 'restack':
1379
1348
  await this.restack(decision)
1380
1349
  return decision
1350
+ case 'recover-target-rewrite':
1351
+ await this.recoverTargetRewrite()
1352
+ return decision
1353
+ case 'accept-target-rewrite':
1354
+ await this.acceptTargetRewrite(decision)
1355
+ return decision
1381
1356
  case 'capture-reconcile-policy':
1382
1357
  await store.append(slug, {
1383
1358
  actor: KERNEL,
@@ -1433,6 +1408,15 @@ export class BuildRunner {
1433
1408
  case 'check-reconcile-progress':
1434
1409
  await this.checkReconcileProgress(decision)
1435
1410
  return decision
1411
+ case 'measure-baseline':
1412
+ await this.measureBaseline(decision)
1413
+ return decision
1414
+ case 'measure-progress':
1415
+ await this.measureProgress(decision)
1416
+ return decision
1417
+ case 'run-measurement':
1418
+ await this.runMeasurement(decision)
1419
+ return decision
1436
1420
  }
1437
1421
  } catch (error) {
1438
1422
  if (error instanceof ForgeRequestDeferred)
@@ -1486,10 +1470,14 @@ export class BuildRunner {
1486
1470
  if (await deferMixedVersion(this.deps.store, this.deps.slug, KERNEL))
1487
1471
  return (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
1488
1472
  const initial = initialFacts.state
1473
+ // A landed node has nothing left to execute; the janitor settles it.
1474
+ if (nodeLanded(initial)) return initial
1489
1475
  if (
1490
1476
  initial.kind === 'node' &&
1491
1477
  !initial.nodeRestack?.conflict &&
1478
+ !proposeRunDue(initial.optimization) &&
1492
1479
  !integrationCurrent(initial) &&
1480
+ !nodeMeasurementDue(initial) &&
1493
1481
  initialFacts.log.readDeferrals.length === 0
1494
1482
  )
1495
1483
  return initial
@@ -1870,7 +1858,7 @@ export class BuildRunner {
1870
1858
  await readBuildFacts(store, slug)
1871
1859
  ).value.state.verifyStage.failures.find((f) => f.seq === decision.verifyStageFailure),
1872
1860
  }),
1873
- isTerminal: (event) => event.type === spec.terminalEvent && roundMatches(event, round),
1861
+ isTerminal: (event) => isPhaseTerminalEvent(spec, event) && roundMatches(event, round),
1874
1862
  })
1875
1863
  if (phase === 'reconcile') await this.settleLocalReconcile()
1876
1864
  }
@@ -1892,19 +1880,28 @@ export class BuildRunner {
1892
1880
  return
1893
1881
  }
1894
1882
  if (!this.recovery) {
1895
- try {
1896
- for (const sha of [active.expected, active.parent]) {
1897
- const exists = await this.deps.exec(['git', 'cat-file', '-e', `${sha}^{commit}`], {
1898
- cwd: this.deps.workspacePath,
1899
- })
1900
- if (exists.exitCode !== 0) {
1901
- const fetched = await this.deps.exec(
1902
- ['git', 'fetch', '--no-tags', 'origin', `refs/autobuild/archive/${slug}/${sha}`],
1903
- { cwd: this.deps.workspacePath },
1904
- )
1905
- if (fetched.exitCode !== 0) throw new Error(`missing archived node input ${sha}`)
1906
- }
1883
+ // Archived node inputs come back from wherever they are retained: the
1884
+ // forge archive ref, a store copy, or the published branches. The parent
1885
+ // first, since a store copy of `expected` completes only over it.
1886
+ const retention = {
1887
+ store,
1888
+ slug,
1889
+ exec: this.deps.exec,
1890
+ workspacePath: this.deps.workspacePath,
1891
+ local: this.deps.forge.name === 'local-git',
1892
+ exclude: active.parent,
1893
+ branch: this.deps.branch,
1894
+ ...(state.baseBranch === undefined ? {} : { targetBranch: state.baseBranch }),
1895
+ archive: async () => {
1896
+ throw new Error('restore only')
1897
+ },
1898
+ }
1899
+ for (const sha of [active.parent, active.expected])
1900
+ if (!(await restoreRetainedHead(retention, sha))) {
1901
+ await this.abandonUnavailableNodeInputs(active.id, state.lastSeq)
1902
+ return
1907
1903
  }
1904
+ try {
1908
1905
  if (change.build) {
1909
1906
  for (const kind of ['spec', 'plan', 'implement-notes']) {
1910
1907
  if (
@@ -1932,20 +1929,56 @@ export class BuildRunner {
1932
1929
  })
1933
1930
  }
1934
1931
  for (const item of node.items) if (!item.dropped) await restoreReplay(this.deps, item.head)
1935
- await this.deps.exec(['git', 'cherry-pick', '--abort'], { cwd: this.deps.workspacePath })
1936
- const reset = await this.deps.exec(['git', 'checkout', '--detach', conflict.base], {
1937
- cwd: this.deps.workspacePath,
1938
- })
1939
- if (reset.exitCode !== 0) throw new Error(reset.stderr)
1940
- const result = await replayNodeChange(
1941
- this.deps,
1942
- { ...active, oldHead: active.expected },
1943
- conflict.index,
1944
- conflict.base,
1945
- )
1946
- if (result.kind !== 'conflict')
1947
- throw new Error('reserved conflict no longer reproduces from frozen inputs')
1932
+ const declarations = this.boundaryConfig.generated ?? []
1933
+ const regeneration =
1934
+ node.regeneration?.id === active.id &&
1935
+ node.regeneration.index === conflict.index &&
1936
+ node.regeneration.base === conflict.base
1937
+ ? node.regeneration
1938
+ : undefined
1939
+ if (regeneration?.outcome === 'resolved' && regeneration.head !== undefined) {
1940
+ // The resolved head was retained before its fact: finish the receipt.
1941
+ await this.adoptRegeneratedNodeItem(change, conflict, regeneration.head)
1942
+ return
1943
+ }
1944
+ const reproduce = async () => {
1945
+ await this.deps.exec(['git', 'cherry-pick', '--abort'], { cwd: this.deps.workspacePath })
1946
+ if (declarations.length > 0)
1947
+ for (const args of [
1948
+ ['reset', '-q', '--hard'],
1949
+ ['clean', '-q', '-fd', '--', ...generatedCleanPathspecs(declarations)],
1950
+ ]) {
1951
+ const cleaned = await this.deps.exec(['git', ...args], {
1952
+ cwd: this.deps.workspacePath,
1953
+ })
1954
+ if (cleaned.exitCode !== 0) throw new Error(cleaned.stderr)
1955
+ }
1956
+ const reset = await this.deps.exec(['git', 'checkout', '--detach', conflict.base], {
1957
+ cwd: this.deps.workspacePath,
1958
+ })
1959
+ if (reset.exitCode !== 0) throw new Error(reset.stderr)
1960
+ const result = await replayNodeChange(
1961
+ this.deps,
1962
+ { ...active, oldHead: active.expected },
1963
+ conflict.index,
1964
+ conflict.base,
1965
+ )
1966
+ if (result.kind !== 'conflict')
1967
+ throw new Error('reserved conflict no longer reproduces from frozen inputs')
1968
+ }
1969
+ await reproduce()
1970
+ if (
1971
+ declarations.length > 0 &&
1972
+ regeneration === undefined &&
1973
+ state.currentPhase?.phase !== 'reconcile'
1974
+ ) {
1975
+ const outcome = await this.regenerateNodeItem(change, conflict, declarations)
1976
+ if (outcome === 'resolved') return
1977
+ // The agent starts from the recorded conflict, not the failed attempt.
1978
+ if (outcome === 'failed') await reproduce()
1979
+ }
1948
1980
  } catch (error) {
1981
+ if (error instanceof RegenerationInterrupted) return
1949
1982
  if (error instanceof StoreWriteTooLargeError) throw error
1950
1983
  await store.append(slug, {
1951
1984
  actor: KERNEL,
@@ -1977,6 +2010,125 @@ export class BuildRunner {
1977
2010
  })
1978
2011
  }
1979
2012
 
2013
+ /** A reserved node input retained nowhere: abandon the reservation under
2014
+ * the node writer, so the next node transaction reserves again from the
2015
+ * published branches. A contended writer or log retries later. */
2016
+ private async abandonUnavailableNodeInputs(id: string, seq: number): Promise<void> {
2017
+ const { store, slug } = this.deps
2018
+ const holder = this.deps.ids('node-writer')
2019
+ if (!(await store.claimNodeWriter(slug, holder, 60_000))) return
2020
+ try {
2021
+ await store.appendIfCurrent(slug, seq, {
2022
+ actor: KERNEL,
2023
+ type: 'node.writer-settled',
2024
+ payload: { id, outcome: 'abandoned' },
2025
+ })
2026
+ } finally {
2027
+ await store.releaseNodeWriter(slug, holder)
2028
+ }
2029
+ }
2030
+
2031
+ /**
2032
+ * Regenerate one reproduced node item whose conflicts are all declared
2033
+ * `[[generated]]` files. Resolved: validate, retain, record the fact and
2034
+ * the item's receipt, with no reconcile session. Skipped and failed are
2035
+ * recorded too; the item then falls back to an agent.
2036
+ */
2037
+ private async regenerateNodeItem(
2038
+ change: EventPayload<'node.writer-reserved'>['changes'][number],
2039
+ conflict: EventPayload<'node.item-conflicted'>,
2040
+ declarations: NonNullable<Config['generated']>,
2041
+ ): Promise<'resolved' | 'failed' | 'skipped'> {
2042
+ const { store, slug } = this.deps
2043
+ const files = conflict.files ?? []
2044
+ const { groups, other } = classifyGenerated(files, declarations)
2045
+ const commands = groups.map((group) => ({ command: group.command, files: group.files }))
2046
+ const identity = { id: conflict.id, index: conflict.index, base: conflict.base }
2047
+ if (files.length === 0 || other.length > 0) {
2048
+ if (files.length > 0)
2049
+ await store.append(slug, {
2050
+ actor: KERNEL,
2051
+ type: 'node.item-regenerated',
2052
+ payload: {
2053
+ ...identity,
2054
+ files,
2055
+ commands,
2056
+ outcome: 'skipped',
2057
+ reason: regenerationReason(`conflicts outside [[generated]]: ${other.join(', ')}`),
2058
+ },
2059
+ })
2060
+ return 'skipped'
2061
+ }
2062
+ let result = await regenerateConflict(
2063
+ {
2064
+ exec: this.deps.exec,
2065
+ workspacePath: this.deps.workspacePath,
2066
+ ...(this.deps.shutdownSignal ? { signal: this.deps.shutdownSignal } : {}),
2067
+ },
2068
+ { files, groups, selectors: generatedSelectors(declarations), identitySource: change.sha },
2069
+ )
2070
+ if (result.outcome === 'resolved') {
2071
+ try {
2072
+ await validateNodeChange(this.deps, change, conflict.base, result.head)
2073
+ } catch (error) {
2074
+ result = {
2075
+ outcome: 'failed',
2076
+ reason: regenerationReason(`regenerated replay is invalid: ${errorMessage(error)}`),
2077
+ }
2078
+ }
2079
+ }
2080
+ if (result.outcome === 'failed') {
2081
+ await store.append(slug, {
2082
+ actor: KERNEL,
2083
+ type: 'node.item-regenerated',
2084
+ payload: { ...identity, files, commands, ...result },
2085
+ })
2086
+ return 'failed'
2087
+ }
2088
+ await retainReplay(this.deps, result.head, conflict.base)
2089
+ await store.append(slug, {
2090
+ actor: KERNEL,
2091
+ type: 'node.item-regenerated',
2092
+ payload: { ...identity, files, commands, ...result },
2093
+ })
2094
+ await store.append(slug, {
2095
+ actor: KERNEL,
2096
+ type: 'node.item-replayed',
2097
+ payload: { ...identity, head: result.head, dropped: false },
2098
+ })
2099
+ return 'resolved'
2100
+ }
2101
+
2102
+ /** Finish a node item whose regeneration resolved before its receipt landed. */
2103
+ private async adoptRegeneratedNodeItem(
2104
+ change: EventPayload<'node.writer-reserved'>['changes'][number],
2105
+ conflict: EventPayload<'node.item-conflicted'>,
2106
+ head: string,
2107
+ ): Promise<void> {
2108
+ if (!(await restoreReplay(this.deps, head)))
2109
+ throw new Error(`the regenerated node item ${head} was not retained`)
2110
+ await this.deps.exec(['git', 'cherry-pick', '--abort'], { cwd: this.deps.workspacePath })
2111
+ for (const args of [
2112
+ ['reset', '-q', '--hard'],
2113
+ ['checkout', '-q', '--detach', head],
2114
+ ]) {
2115
+ const result = await this.deps.exec(['git', ...args], { cwd: this.deps.workspacePath })
2116
+ if (result.exitCode !== 0) throw new Error(result.stderr)
2117
+ }
2118
+ await validateNodeChange(this.deps, change, conflict.base, head)
2119
+ await this.deps.store.append(this.deps.slug, {
2120
+ actor: KERNEL,
2121
+ type: 'node.item-replayed',
2122
+ payload: {
2123
+ id: conflict.id,
2124
+ index: conflict.index,
2125
+ base: conflict.base,
2126
+ head,
2127
+ dropped: false,
2128
+ },
2129
+ })
2130
+ }
2131
+
1980
2132
  /** Re-read durable ownership and controls at the actual rewrite boundary. */
1981
2133
  private async assertAutomaticRewriteOwnership(allowPublication = false) {
1982
2134
  const { store, slug, instance, clock } = this.deps
@@ -2050,14 +2202,26 @@ export class BuildRunner {
2050
2202
  }
2051
2203
  // A replacement workspace may still be checked out at the old branch tip.
2052
2204
  // Restore the frozen resolved intent before the guarded branch update.
2053
- await prepareRestack(publicationDeps, {
2054
- attempt: intent.payload.attempt,
2055
- branch: intent.payload.branch,
2056
- oldBase: intent.payload.oldBase,
2057
- targetBase: intent.payload.targetBase,
2058
- id: intent.payload.id,
2059
- restackId: intent.payload.restackId,
2060
- })
2205
+ try {
2206
+ await prepareRestack(publicationDeps, {
2207
+ attempt: intent.payload.attempt,
2208
+ branch: intent.payload.branch,
2209
+ oldBase: intent.payload.oldBase,
2210
+ targetBase: intent.payload.targetBase,
2211
+ id: intent.payload.id,
2212
+ restackId: intent.payload.restackId,
2213
+ })
2214
+ } catch (error) {
2215
+ if (!(error instanceof RetainedHistoryUnavailable)) throw error
2216
+ // The resolved candidate is retained nowhere: retire it, and the
2217
+ // reconcile replays from the published branch under its replacement id.
2218
+ const current = await readBuildFacts(store, slug)
2219
+ const latest = current.value.publication.latestUncompletedRequest()
2220
+ if (latest?.seq !== request.seq)
2221
+ throw new Error('publication changed during candidate recovery; retry')
2222
+ await retireCandidate(this.deps, current, latest)
2223
+ return
2224
+ }
2061
2225
  const result = await retryPublicationEffect(
2062
2226
  retryDeps,
2063
2227
  'reconcile',
@@ -2200,7 +2364,41 @@ export class BuildRunner {
2200
2364
  facts = (await readBuildFacts(store, slug)).value
2201
2365
  transaction = facts.log.restack.active
2202
2366
  if (transaction === undefined) throw new Error('missing prepared automatic restack')
2203
- if (facts.log.restack.replay?.conflicted) return
2367
+ if (facts.log.restack.replay?.conflicted) {
2368
+ // Conflicts only in `[[generated]]` files are regenerated, not reconciled.
2369
+ const declarations = this.boundaryConfig.generated ?? []
2370
+ if (
2371
+ declarations.length > 0 &&
2372
+ facts.log.restack.regeneration === undefined &&
2373
+ facts.log.restack.reconcileAttempt === undefined
2374
+ ) {
2375
+ await regenerateRestackConflict(
2376
+ {
2377
+ ...deps,
2378
+ ...(this.deps.shutdownSignal ? { signal: this.deps.shutdownSignal } : {}),
2379
+ },
2380
+ transaction,
2381
+ facts.log.restack.replay.files ?? [],
2382
+ declarations,
2383
+ )
2384
+ facts = (await readBuildFacts(store, slug)).value
2385
+ }
2386
+ const regeneration = facts.log.restack.regeneration
2387
+ if (regeneration?.outcome !== 'resolved' || regeneration.head === undefined) return
2388
+ try {
2389
+ await adoptRegeneratedRestack(deps, transaction, regeneration.head)
2390
+ } catch (error) {
2391
+ if (!(error instanceof RetainedHistoryUnavailable)) throw error
2392
+ // The regenerated head is retained nowhere: replay again from the
2393
+ // published branch; the next step continues the new transaction.
2394
+ await redoRestack(deps, transaction)
2395
+ return
2396
+ }
2397
+ }
2398
+ const regenerated =
2399
+ facts.log.restack.regeneration?.outcome === 'resolved'
2400
+ ? facts.log.restack.regeneration
2401
+ : undefined
2204
2402
  const result = await this.deps.exec(['git', 'rev-parse', 'HEAD'], {
2205
2403
  cwd: this.deps.workspacePath,
2206
2404
  })
@@ -2210,7 +2408,7 @@ export class BuildRunner {
2210
2408
  throw new Error('recovered automatic replay differs from its frozen publication intent')
2211
2409
  await retainReplay(deps, headSha, transaction.targetBase)
2212
2410
  const intent = { ...transaction, headSha }
2213
- await recordHeadPaths(
2411
+ const recorded = await recordHeadPaths(
2214
2412
  {
2215
2413
  store,
2216
2414
  slug,
@@ -2223,8 +2421,37 @@ export class BuildRunner {
2223
2421
  head: headSha,
2224
2422
  destination: transaction.targetBase,
2225
2423
  state: facts.state,
2424
+ // A regenerated replay resolved conflicts, like a reconcile does.
2425
+ ...(regenerated === undefined
2426
+ ? {}
2427
+ : {
2428
+ resolution: [
2429
+ {
2430
+ change: transaction.changeSha,
2431
+ parent: transaction.oldBase,
2432
+ onto: transaction.targetBase,
2433
+ head: headSha,
2434
+ },
2435
+ ],
2436
+ }),
2226
2437
  },
2227
2438
  )
2439
+ const revocation =
2440
+ regenerated !== undefined &&
2441
+ recorded !== null &&
2442
+ revocableConsent(facts.state.landing) &&
2443
+ consentRevocation(facts.state.landing, {
2444
+ source: 'reconcile',
2445
+ previousHead: transaction.oldHead,
2446
+ head: headSha,
2447
+ resolution: await resolutionPathsFor(store, slug, recorded),
2448
+ })
2449
+ if (revocation)
2450
+ await store.append(slug, {
2451
+ actor: KERNEL,
2452
+ type: 'landing.consent-revoked',
2453
+ payload: revocation,
2454
+ })
2228
2455
  if (facts.log.restack.intent === undefined)
2229
2456
  await store.append(slug, {
2230
2457
  actor: KERNEL,
@@ -2279,7 +2506,8 @@ export class BuildRunner {
2279
2506
  error instanceof PublicationRetryPersistenceError
2280
2507
  )
2281
2508
  throw error
2282
- if (error instanceof AutomaticRewriteDeferred) return
2509
+ if (error instanceof AutomaticRewriteDeferred || error instanceof RegenerationInterrupted)
2510
+ return
2283
2511
  await this.failPhase(
2284
2512
  'reconcile',
2285
2513
  round,
@@ -2374,8 +2602,17 @@ export class BuildRunner {
2374
2602
  })
2375
2603
  }
2376
2604
 
2377
- /** Snapshot the frozen target in a build-private ref without tracking-ref updates. */
2605
+ /** Snapshot the frozen target in a build-private ref without tracking-ref
2606
+ * updates, then admit it through target observation. */
2378
2607
  private async refreshReconcileBase(recordAccepted = false): Promise<string> {
2608
+ const { branch, sha } = await this.snapshotTargetBase()
2609
+ await this.admitReconcileBase(branch, sha, recordAccepted)
2610
+ return sha
2611
+ }
2612
+
2613
+ /** Snapshot the frozen target in a build-private ref without tracking-ref
2614
+ * updates or observation: the caller decides what the snapshot means. */
2615
+ private async snapshotTargetBase(): Promise<{ branch: string; sha: string }> {
2379
2616
  const baseBranch = await readBuildSelector(this.deps.store, this.deps.slug, 'baseBranch')
2380
2617
  if (baseBranch === undefined) {
2381
2618
  throw new Error(
@@ -2396,8 +2633,7 @@ export class BuildRunner {
2396
2633
  `${this.deps.forge.name} base snapshot did not return a commit SHA: ${JSON.stringify(sha)}`,
2397
2634
  )
2398
2635
  }
2399
- await this.admitReconcileBase(baseBranch, sha, recordAccepted)
2400
- return sha
2636
+ return { branch: baseBranch, sha }
2401
2637
  }
2402
2638
 
2403
2639
  const fetchArgs = [
@@ -2426,44 +2662,320 @@ export class BuildRunner {
2426
2662
  `${resolved.stderr.trim() || sha || '(no output)'}`,
2427
2663
  )
2428
2664
  }
2429
- await this.admitReconcileBase(baseBranch, sha, recordAccepted)
2430
- return sha
2665
+ return { branch: baseBranch, sha }
2431
2666
  }
2432
2667
 
2433
- private async admitReconcileBase(
2434
- branch: string,
2435
- sha: string,
2436
- recordAccepted: boolean,
2437
- ): Promise<void> {
2438
- const result = await observeTarget({
2439
- store: this.deps.store,
2440
- forge: this.deps.forge,
2441
- slug: this.deps.slug,
2442
- branch,
2443
- sha,
2444
- enforceUsedBaseline: true,
2445
- recordAccepted,
2446
- actor: KERNEL,
2447
- })
2448
- if (result === 'rejected') throw new Error(`upstream target rewrite on ${branch}: ${sha}`)
2668
+ /** One git command in the workspace; throws on failure unless allowed. */
2669
+ private async workspaceGit(args: string[], allowFailure = false) {
2670
+ const result = await this.deps.exec(['git', ...args], { cwd: this.deps.workspacePath })
2671
+ if (result.exitCode !== 0 && !allowFailure)
2672
+ throw new Error(
2673
+ `git ${args.join(' ')} exited ${result.exitCode}: ${result.stderr.trim() || '(no output)'}`,
2674
+ )
2675
+ return result
2449
2676
  }
2450
2677
 
2451
- /**
2452
- * Resolve a conditional verifier against the live branch diff. Exclusion is
2453
- * a canonical kernel-authored skip and launches no command or session.
2454
- * Inclusion delegates to the existing verifier path unchanged.
2455
- */
2456
- private async resolveVerify(
2457
- decision: EvaluateVerifyDecision,
2458
- ): Promise<
2459
- Exclude<import('../kernel/engine').VerifyMemberDecision, { kind: 'evaluate-verify' }>
2460
- > {
2461
- const { exec, workspacePath } = this.deps
2462
- const state = (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
2463
- const baseSha =
2464
- state.kind === 'node'
2465
- ? state.integration?.cycle?.parent
2466
- : await readBuildSelector(this.deps.store, this.deps.slug, 'verifyDiffBase')
2678
+ private async localBranchHead(): Promise<string | undefined> {
2679
+ const result = await this.workspaceGit(
2680
+ ['rev-parse', '-q', '--verify', `refs/heads/${this.deps.branch}^{commit}`],
2681
+ true,
2682
+ )
2683
+ return result.exitCode === 0 ? result.stdout.trim() : undefined
2684
+ }
2685
+
2686
+ private async trackedTreeClean(): Promise<boolean> {
2687
+ return (
2688
+ (await this.workspaceGit(['status', '--porcelain', '--untracked-files=no'])).stdout.trim() ===
2689
+ ''
2690
+ )
2691
+ }
2692
+
2693
+ /** `sha subject` of each commit in `from..to`, oldest first. */
2694
+ private async commitsBetween(from: string, to: string) {
2695
+ const out = (await this.workspaceGit(['log', '--reverse', '--format=%H %s', `${from}..${to}`]))
2696
+ .stdout
2697
+ return out
2698
+ .split('\n')
2699
+ .filter((line) => line.trim() !== '')
2700
+ .map((line) => {
2701
+ const space = line.indexOf(' ')
2702
+ return space < 0
2703
+ ? { sha: line, subject: '' }
2704
+ : { sha: line.slice(0, space), subject: line.slice(space + 1) }
2705
+ })
2706
+ }
2707
+
2708
+ private async isAncestor(ancestor: string, descendant: string): Promise<boolean> {
2709
+ const result = await this.workspaceGit(
2710
+ ['merge-base', '--is-ancestor', ancestor, descendant],
2711
+ true,
2712
+ )
2713
+ if (result.exitCode === 0) return true
2714
+ if (result.exitCode === 1) return false
2715
+ throw new Error(
2716
+ `git merge-base --is-ancestor exited ${result.exitCode}: ${result.stderr.trim()}`,
2717
+ )
2718
+ }
2719
+
2720
+ /**
2721
+ * Leave the `target-rewritten` wait (SPEC §7.4). An open no-work reset is
2722
+ * completed forward first. Otherwise a leaf with no work of its own (no
2723
+ * published head, no PR, no commits beyond its base in use, a clean tracked
2724
+ * tree) is reprovisioned from the current target through a durable
2725
+ * prepare → reset → recovered transaction; a leaf with work raises the
2726
+ * episode's one `policy/target-rewritten` escalation.
2727
+ */
2728
+ private async recoverTargetRewrite(): Promise<void> {
2729
+ const { store, slug } = this.deps
2730
+ await this.closeProducerSessions()
2731
+ try {
2732
+ for (;;) {
2733
+ const current = await readBuildFacts(store, slug)
2734
+ const facts = current.value
2735
+ const prepared = facts.log.restack.reprovision
2736
+ if (prepared !== undefined) {
2737
+ await this.resumeReprovision(prepared)
2738
+ return
2739
+ }
2740
+ const rewrite = facts.log.restack.targetRewrite
2741
+ if (rewrite === undefined) return
2742
+ const base = facts.verifyDiffBase
2743
+ if (base === undefined) throw new Error('missing contribution base')
2744
+ const published = await readBuildSelector(store, slug, 'publishedBranchHead')
2745
+ const local = await this.localBranchHead()
2746
+ if (local === undefined) throw new Error(`missing local branch ${this.deps.branch}`)
2747
+ const commits = await this.commitsBetween(base, local)
2748
+ const clean = await this.trackedTreeClean()
2749
+ if (
2750
+ published !== undefined ||
2751
+ facts.state.pr !== undefined ||
2752
+ commits.length > 0 ||
2753
+ !clean
2754
+ ) {
2755
+ await this.raiseTargetRewrite({
2756
+ previousSha: rewrite.previousSha,
2757
+ branch: rewrite.branch,
2758
+ sha: rewrite.sha,
2759
+ commits,
2760
+ ...(published === undefined ? {} : { published }),
2761
+ ...(facts.state.pr === undefined ? {} : { pr: facts.state.pr.number }),
2762
+ })
2763
+ return
2764
+ }
2765
+ const { sha } = await this.snapshotTargetBase()
2766
+ const written = await store.appendIfCurrent(slug, current.cursor, {
2767
+ actor: KERNEL,
2768
+ type: 'target.rewrite-reprovision-prepared',
2769
+ payload: {
2770
+ branch: rewrite.branch,
2771
+ previousSha: rewrite.previousSha,
2772
+ base,
2773
+ from: local,
2774
+ sha,
2775
+ },
2776
+ })
2777
+ // A concurrent observation or control: classify again from the log.
2778
+ if (!written) continue
2779
+ await this.assertAutomaticRewriteOwnership()
2780
+ await this.workspaceGit(['checkout', '-q', '-B', this.deps.branch, sha])
2781
+ await this.completeReprovision()
2782
+ return
2783
+ }
2784
+ } catch (error) {
2785
+ if (error instanceof AutomaticRewriteDeferred) return
2786
+ throw error
2787
+ }
2788
+ }
2789
+
2790
+ /** Complete an open reprovision preparation forward, never re-classifying. */
2791
+ private async resumeReprovision(
2792
+ prepared: EventPayload<'target.rewrite-reprovision-prepared'>,
2793
+ ): Promise<void> {
2794
+ const local = await this.localBranchHead()
2795
+ const clean = await this.trackedTreeClean()
2796
+ switch (reprovisionResume(prepared, local, clean)) {
2797
+ case 'complete':
2798
+ await this.completeReprovision()
2799
+ return
2800
+ case 'redo': {
2801
+ await this.assertAutomaticRewriteOwnership()
2802
+ let sha = prepared.sha
2803
+ const exists = async (oid: string) =>
2804
+ (await this.workspaceGit(['cat-file', '-e', `${oid}^{commit}`], true)).exitCode === 0
2805
+ if (!(await exists(sha))) {
2806
+ // A fresh guest may lack the prepared commit: refresh the snapshot,
2807
+ // else re-prepare from it with the same proven head.
2808
+ const fresh = await this.snapshotTargetBase()
2809
+ if (!(await exists(sha))) {
2810
+ sha = fresh.sha
2811
+ await this.deps.store.append(this.deps.slug, {
2812
+ actor: KERNEL,
2813
+ type: 'target.rewrite-reprovision-prepared',
2814
+ // The reduced preparation also carries its seq: name each
2815
+ // payload field so the strict schema sees only the fact.
2816
+ payload: {
2817
+ branch: prepared.branch,
2818
+ previousSha: prepared.previousSha,
2819
+ base: prepared.base,
2820
+ from: prepared.from,
2821
+ sha,
2822
+ },
2823
+ })
2824
+ }
2825
+ }
2826
+ await this.workspaceGit(['checkout', '-q', '-B', this.deps.branch, sha])
2827
+ await this.completeReprovision()
2828
+ return
2829
+ }
2830
+ case 'unknown':
2831
+ await this.raiseTargetRewrite({
2832
+ previousSha: prepared.previousSha,
2833
+ branch: prepared.branch,
2834
+ sha: prepared.sha,
2835
+ commits: local === undefined ? [] : await this.commitsBetween(prepared.from, local),
2836
+ })
2837
+ return
2838
+ }
2839
+ }
2840
+
2841
+ /** Append the reset's completion from the open preparation, idempotently. */
2842
+ private async completeReprovision(): Promise<void> {
2843
+ const { store, slug } = this.deps
2844
+ for (;;) {
2845
+ const current = await readBuildFacts(store, slug)
2846
+ const prepared = current.value.log.restack.reprovision
2847
+ if (prepared === undefined) return
2848
+ const { seq: _seq, from: _from, ...payload } = prepared
2849
+ if (
2850
+ await store.appendIfCurrent(slug, current.cursor, {
2851
+ actor: KERNEL,
2852
+ type: 'target.rewrite-recovered',
2853
+ payload: { ...payload, recovery: 'reprovisioned' },
2854
+ })
2855
+ )
2856
+ return
2857
+ }
2858
+ }
2859
+
2860
+ /** Raise the episode's one operator question (or a refused accept's). */
2861
+ private async raiseTargetRewrite(
2862
+ input: Omit<Parameters<typeof targetRewriteQuestion>[0], 'slug'>,
2863
+ ): Promise<void> {
2864
+ const { store, slug, ids } = this.deps
2865
+ const facts = (await readBuildFacts(store, slug)).value
2866
+ await store.append(slug, {
2867
+ actor: KERNEL,
2868
+ type: 'escalation.raised',
2869
+ payload: {
2870
+ id: ids('esc'),
2871
+ phase: facts.state.currentPhase?.phase ?? facts.state.lastCompletedPhase?.phase ?? 'setup',
2872
+ source: 'policy',
2873
+ policyCause: 'target-rewritten',
2874
+ question: targetRewriteQuestion({ slug, ...input }),
2875
+ },
2876
+ } satisfies EventWrite<'escalation.raised'>)
2877
+ }
2878
+
2879
+ /**
2880
+ * Record an operator's accept-target: waive the rejected base in use and
2881
+ * accept the current target. The engine restacks the build's published
2882
+ * commits at the new replay boundary. Unpublished local commits inside an
2883
+ * open publishing occurrence are named as `pendingLocal`, withholding the
2884
+ * boundary until that occurrence publishes them; local commits nothing owns
2885
+ * refuse the accept with a fresh escalation.
2886
+ */
2887
+ private async acceptTargetRewrite(
2888
+ decision: Extract<Decision, { kind: 'accept-target-rewrite' }>,
2889
+ ): Promise<void> {
2890
+ const { store, slug } = this.deps
2891
+ await this.closeProducerSessions()
2892
+ for (;;) {
2893
+ const current = await readBuildFacts(store, slug)
2894
+ const facts = current.value
2895
+ const rewrite = facts.log.restack.targetRewrite
2896
+ const prepared = facts.log.restack.reprovision
2897
+ if (rewrite === undefined && prepared === undefined) return
2898
+ const previousSha = rewrite?.previousSha ?? prepared!.previousSha
2899
+ const branch = rewrite?.branch ?? prepared!.branch
2900
+ const base = leafBaseInUse(facts.log)
2901
+ if (base === undefined) throw new Error('missing contribution base')
2902
+ const { sha } = await this.snapshotTargetBase()
2903
+ const published = await readBuildSelector(store, slug, 'publishedBranchHead')
2904
+ const local = await this.localBranchHead()
2905
+ if (local === undefined) throw new Error(`missing local branch ${this.deps.branch}`)
2906
+ const verdict = classifyAcceptedLocal({
2907
+ local,
2908
+ published,
2909
+ base,
2910
+ localInPublished: published !== undefined && (await this.isAncestor(local, published)),
2911
+ localDescends: await this.isAncestor(published ?? base, local),
2912
+ owner: openPublishingOwner(facts.state, facts.log),
2913
+ })
2914
+ if (verdict.kind === 'refuse') {
2915
+ const from = (await this.isAncestor(verdict.from, local))
2916
+ ? verdict.from
2917
+ : (await this.workspaceGit(['merge-base', verdict.from, local], true)).stdout.trim() ||
2918
+ verdict.from
2919
+ await this.raiseTargetRewrite({
2920
+ previousSha,
2921
+ branch,
2922
+ sha,
2923
+ commits: await this.commitsBetween(from, local),
2924
+ ...(published === undefined ? {} : { published }),
2925
+ ...(facts.state.pr === undefined ? {} : { pr: facts.state.pr.number }),
2926
+ unowned: true,
2927
+ })
2928
+ return
2929
+ }
2930
+ const written = await store.appendIfCurrent(slug, current.cursor, {
2931
+ actor: KERNEL,
2932
+ type: 'target.rewrite-recovered',
2933
+ payload: {
2934
+ branch,
2935
+ previousSha,
2936
+ sha,
2937
+ base,
2938
+ recovery: 'accepted',
2939
+ escalation: decision.escalation,
2940
+ ...(verdict.kind === 'pending' ? { pendingLocal: verdict.pendingLocal } : {}),
2941
+ },
2942
+ })
2943
+ if (written) return
2944
+ }
2945
+ }
2946
+
2947
+ private async admitReconcileBase(
2948
+ branch: string,
2949
+ sha: string,
2950
+ recordAccepted: boolean,
2951
+ ): Promise<void> {
2952
+ const result = await observeTarget({
2953
+ store: this.deps.store,
2954
+ forge: this.deps.forge,
2955
+ slug: this.deps.slug,
2956
+ branch,
2957
+ sha,
2958
+ enforceUsedBaseline: true,
2959
+ recordAccepted,
2960
+ actor: KERNEL,
2961
+ })
2962
+ if (result === 'rejected') throw new Error(`upstream target rewrite on ${branch}: ${sha}`)
2963
+ }
2964
+
2965
+ /**
2966
+ * Resolve a conditional verifier against the live branch diff. Exclusion is
2967
+ * a canonical kernel-authored skip and launches no command or session.
2968
+ * Inclusion delegates to the existing verifier path unchanged.
2969
+ */
2970
+ private async resolveVerify(
2971
+ decision: EvaluateVerifyDecision,
2972
+ ): Promise<
2973
+ Exclude<import('../kernel/engine').VerifyMemberDecision, { kind: 'evaluate-verify' }>
2974
+ > {
2975
+ const { exec, workspacePath } = this.deps
2976
+ const baseSha = verifyDiffBaseFrom(
2977
+ (await readBuildFacts(this.deps.store, this.deps.slug)).value,
2978
+ )
2467
2979
  if (baseSha === undefined)
2468
2980
  throw new Error(
2469
2981
  'conditional verify requires a workspace.provisioned base SHA, but this build has none',
@@ -2585,166 +3097,1073 @@ export class BuildRunner {
2585
3097
  wake?.()
2586
3098
  },
2587
3099
  )
2588
- let decision: Decision = initial
2589
- let drain = false
2590
- let terminalDrain = false
3100
+ let decision: Decision = initial
3101
+ let drain = false
3102
+ let terminalDrain = false
3103
+ let landed = false
3104
+ try {
3105
+ for (;;) {
3106
+ const observed = revision
3107
+ if (this.deps.shutdownSignal?.aborted) return
3108
+ if (decision.kind !== 'run-verify-stage') {
3109
+ if (decision.kind === 'cancel-verify-stage') {
3110
+ await this.cancelVerifyStage(decision)
3111
+ await this.endCancelledVerifySessions(decision)
3112
+ } else {
3113
+ drain = terminalDrain
3114
+ }
3115
+ return
3116
+ }
3117
+ if (
3118
+ decision.members.some(
3119
+ (member) => !initial.members.some((first) => first.step === member.step),
3120
+ )
3121
+ ) {
3122
+ drain = terminalDrain
3123
+ return
3124
+ }
3125
+ const members = await Promise.all(
3126
+ decision.members.map((member) =>
3127
+ member.kind === 'evaluate-verify' ? this.resolveVerify(member) : member,
3128
+ ),
3129
+ )
3130
+ for (const member of members) {
3131
+ const key = verifyMemberKey(member.step, member.attempt)
3132
+ const active = inFlight.get(key)
3133
+ if (active && !active.done) continue
3134
+ if (active?.error) throw active.error
3135
+ const child = new BuildRunner({
3136
+ ...this.deps,
3137
+ config: this.boundaryConfig,
3138
+ shutdownSignal: this.deps.shutdownSignal
3139
+ ? AbortSignal.any([this.deps.shutdownSignal, interrupted.signal])
3140
+ : interrupted.signal,
3141
+ })
3142
+ child.verifyWrites = this.verifyWrites
3143
+ const recovery = this.stageRecoveries.get(key)
3144
+ child.recovery = recovery?.session
3145
+ child.recoveryBoundaryMs = this.recoveryBoundaryMs
3146
+ child.recoveryCause = recovery?.cause ?? 'runner-loss'
3147
+ this.stageRecoveries.delete(key)
3148
+ const entry: MemberExecution = {
3149
+ runner: child,
3150
+ done: false,
3151
+ agent: member.kind === 'run-agent-verify',
3152
+ }
3153
+ inFlight.set(key, entry)
3154
+ const work =
3155
+ member.kind === 'run-check'
3156
+ ? child.runCheck(member)
3157
+ : member.kind === 'run-agent-verify'
3158
+ ? child.runAgentVerify(member)
3159
+ : member.kind === 'skip-verify'
3160
+ ? child.skipVerify(member)
3161
+ : Promise.resolve()
3162
+ entry.pending = work.then(
3163
+ () => {
3164
+ entry.done = true
3165
+ revision += 1
3166
+ wake?.()
3167
+ },
3168
+ (error) => {
3169
+ entry.done = true
3170
+ entry.error = error
3171
+ revision += 1
3172
+ wake?.()
3173
+ },
3174
+ )
3175
+ }
3176
+ if (revision === observed)
3177
+ await new Promise<void>((resolve) => {
3178
+ wake = resolve
3179
+ if (revision !== observed) resolve()
3180
+ })
3181
+ wake = undefined
3182
+ const facts = (await readBuildFacts(store, slug)).value
3183
+ decision = decideNextFromFacts(facts.state, facts.log, await this.captureConfig())
3184
+ // A landing cancels open agent members as operator stops; let them end, not suspend.
3185
+ landed = nodeLanded(facts.state)
3186
+ terminalDrain =
3187
+ landed ||
3188
+ (facts.state.status === 'running' &&
3189
+ facts.state.pendingCommands.length === 0 &&
3190
+ [...inFlight.keys()].every(
3191
+ (key) => facts.state.verifyStage.outcomes[key] !== undefined,
3192
+ ))
3193
+
3194
+ for (const entry of inFlight.values()) if (entry.error) throw entry.error
3195
+ }
3196
+ } finally {
3197
+ unsubscribe()
3198
+ this.deps.shutdownSignal?.removeEventListener('abort', onShutdown)
3199
+ // A terminal can precede the adapter return. Let normal agent settlement
3200
+ // close its bracket before stage-local shutdown can suspend it remotely.
3201
+ // Parent shutdown and session budgets remain active throughout this drain.
3202
+ if (drain) for (const entry of inFlight.values()) if (entry.agent) await entry.pending
3203
+ interrupted.abort()
3204
+ for (const entry of inFlight.values()) {
3205
+ // Fail-fast must reach whole-execution teardown even when an adapter
3206
+ // ignores abort. Its cancelled brackets are already durably ended;
3207
+ // the supervisor, rather than a per-member reaper, owns descendants.
3208
+ // A landing releases the workspace once execution ends, so every
3209
+ // aborted member, checks included, finishes before the stage returns.
3210
+ if (landed || (entry.agent && decision.kind !== 'cancel-verify-stage')) await entry.pending
3211
+ for (const stream of entry.runner.bracketStreams.values())
3212
+ entry.runner.closeBracketStream(stream, 'aborted')
3213
+ await entry.runner.closeProducerSessions()
3214
+ }
3215
+ }
3216
+ }
3217
+
3218
+ /** Shared writer for every deterministic exclusion mechanism. A skip is a
3219
+ * queryable two-fact phase occurrence and launches no command or session. */
3220
+ private async verifyEvidence() {
3221
+ const facts = (await readBuildFacts(this.deps.store, this.deps.slug)).value
3222
+ if (facts.state.kind === 'node') {
3223
+ const cycle = facts.state.integration?.cycle
3224
+ if (!cycle) throw new Error('missing prepared integration verification')
3225
+ const head = await this.deps.exec(['git', 'rev-parse', 'HEAD'], {
3226
+ cwd: this.deps.workspacePath,
3227
+ })
3228
+ if (head.exitCode !== 0 || head.stdout.trim() !== cycle.head)
3229
+ throw new Error('integration checkout differs from prepared head')
3230
+ return { baseSha: cycle.parent, headSha: cycle.head, restackId: cycle.id }
3231
+ }
3232
+ const gate = leafVerifiedRestack(facts.log)
3233
+ if (gate !== undefined)
3234
+ return { baseSha: gate.targetBase, headSha: gate.headSha, restackId: gate.id }
3235
+ return {}
3236
+ }
3237
+
3238
+ private async skipVerify(decision: SkipVerifyDecision): Promise<void> {
3239
+ const { store, slug } = this.deps
3240
+ await this.withVerifyWrite(async () => {
3241
+ const { state } = (await readBuildFacts(store, slug)).value
3242
+ const key = verifyMemberKey(decision.step, decision.attempt)
3243
+ if (state.verifyStage.cancellations[key] || state.verifyStage.outcomes[key]) return
3244
+ const evidence = await this.verifyEvidence()
3245
+ await store.append(slug, {
3246
+ actor: KERNEL,
3247
+ type: 'verify.started',
3248
+ payload: { ...evidence, step: decision.step, attempt: decision.attempt },
3249
+ } satisfies EventWrite<'verify.started'>)
3250
+ await store.append(slug, {
3251
+ actor: KERNEL,
3252
+ type: 'verify.completed',
3253
+ payload: {
3254
+ step: decision.step,
3255
+ attempt: decision.attempt,
3256
+ ...evidence,
3257
+ outcome: 'skipped',
3258
+ reason: decision.reason,
3259
+ ...(decision.skipCause !== undefined ? { skipCause: decision.skipCause } : {}),
3260
+ },
3261
+ } satisfies EventWrite<'verify.completed'>)
3262
+ })
3263
+ }
3264
+
3265
+ // ── Optimization measurement (SPEC §13.1.1) ────────────────────────────────
3266
+
3267
+ private pairedMeasurement(input: {
3268
+ id: string
3269
+ candidate: string
3270
+ baseline: string
3271
+ harnessPin: string
3272
+ metric: Parameters<typeof runPairedMeasurement>[1]['metric']
3273
+ config: Config
3274
+ }): Promise<MeasurementResult> {
3275
+ const { exec, workspacePath, shutdownSignal } = this.deps
3276
+ return runPairedMeasurement(
3277
+ {
3278
+ exec,
3279
+ timeoutSignal: this.deps.timeoutSignal ?? ((ms) => AbortSignal.timeout(ms)),
3280
+ ...(shutdownSignal !== undefined ? { shutdownSignal } : {}),
3281
+ },
3282
+ {
3283
+ workspacePath,
3284
+ build: this.deps.slug,
3285
+ id: input.id,
3286
+ candidate: input.candidate,
3287
+ baseline: input.baseline,
3288
+ harnessPin: input.harnessPin,
3289
+ metric: input.metric,
3290
+ ...(input.config.commands.setup !== undefined
3291
+ ? { setupCommand: input.config.commands.setup }
3292
+ : {}),
3293
+ },
3294
+ )
3295
+ }
3296
+
3297
+ /** A measurement that cannot record a decision blocks the build until an
3298
+ * operator answers; the answer re-arms the same measurement. A node panel
3299
+ * passes its deterministic id, so a crash never raises it twice. */
3300
+ private async raiseMeasurementEscalation(question: string, id?: string): Promise<void> {
3301
+ if (id !== undefined) {
3302
+ const state = (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
3303
+ if (
3304
+ state.openEscalations.some((escalation) => escalation.id === id) ||
3305
+ state.answeredEscalations.some((escalation) => escalation.id === id)
3306
+ )
3307
+ return
3308
+ }
3309
+ await this.deps.store.append(this.deps.slug, {
3310
+ actor: KERNEL,
3311
+ type: 'escalation.raised',
3312
+ payload: {
3313
+ id: id ?? this.deps.ids('esc'),
3314
+ phase: 'measurement',
3315
+ source: 'policy',
3316
+ policyCause: 'measurement-failed',
3317
+ question,
3318
+ },
3319
+ } satisfies EventWrite<'escalation.raised'>)
3320
+ }
3321
+
3322
+ private failedMeasurementQuestion(
3323
+ what: string,
3324
+ failure: Extract<MeasurementResult, { kind: 'failed' }>,
3325
+ ): string {
3326
+ return (
3327
+ `${what} failed: ${failure.reason}. ` +
3328
+ `Output: ${failure.outputTail || '(no output)'}. ` +
3329
+ 'Fix the metric command, harness or setup, then answer to measure again.'
3330
+ )
3331
+ }
3332
+
3333
+ /** The node's starting value: its harness pin measured against itself. */
3334
+ private async measureBaseline(decision: MeasureBaselineDecision): Promise<void> {
3335
+ const { store, slug } = this.deps
3336
+ const before = (await readBuildFacts(store, slug)).value.state
3337
+ const ruler = before.optimization?.rulerRevision
3338
+ if (
3339
+ !baselineMeasurementDue(before) ||
3340
+ before.optimization!.accepted.harnessPin !== decision.harnessPin
3341
+ )
3342
+ return
3343
+ const metric = before.optimization!.objective.metric
3344
+ if (metric.kind === 'panel') return this.measurePanelBaseline(decision, before)
3345
+ const pin = decision.harnessPin
3346
+ const result = await this.pairedMeasurement({
3347
+ id: `baseline-${decision.revision}-${pin}`,
3348
+ candidate: pin,
3349
+ baseline: pin,
3350
+ harnessPin: pin,
3351
+ metric,
3352
+ config: await this.captureConfig(),
3353
+ })
3354
+ if (result.kind === 'interrupted') return
3355
+ // A newer ruler, or a measurement another runner recorded, supersedes
3356
+ // these samples; the engine decides again from the fresh state.
3357
+ const after = (await readBuildFacts(store, slug)).value.state
3358
+ const optimization = after.optimization
3359
+ if (
3360
+ !baselineMeasurementDue(after) ||
3361
+ optimization === undefined ||
3362
+ optimization.rulerRevision !== ruler ||
3363
+ optimization.accepted.harnessPin !== pin
3364
+ )
3365
+ return
3366
+ if (result.kind === 'failed') {
3367
+ await this.raiseMeasurementEscalation(
3368
+ this.failedMeasurementQuestion(`The starting measurement of harness pin ${pin}`, result),
3369
+ )
3370
+ return
3371
+ }
3372
+ const summary = baselineSummary(result.baseline, result.candidate)
3373
+ const epsilon = optimization.objective.target.epsilon
3374
+ const effective = effectiveEpsilon(epsilon, summary.median)
3375
+ // Attention first: a crash before the starting value re-measures and
3376
+ // raises it again, never loses it.
3377
+ if (noiseExceeded(effective, summary.spread))
3378
+ await store.append(slug, {
3379
+ actor: KERNEL,
3380
+ type: 'optimization.noise-exceeded',
3381
+ payload: {
3382
+ revision: optimization.revision,
3383
+ head: pin,
3384
+ harnessPin: pin,
3385
+ median: summary.median,
3386
+ spread: summary.spread,
3387
+ epsilon: { ...epsilon },
3388
+ effectiveEpsilon: effective,
3389
+ },
3390
+ } satisfies EventWrite<'optimization.noise-exceeded'>)
3391
+ await store.appendWithArtifacts(
3392
+ slug,
3393
+ [{ kind: MEASUREMENT_SAMPLES_ARTIFACT, content: JSON.stringify(result, null, 2) }],
3394
+ (deposited) => ({
3395
+ actor: KERNEL,
3396
+ type: 'optimization.baseline-measured',
3397
+ payload: {
3398
+ revision: optimization.revision,
3399
+ head: pin,
3400
+ harnessPin: pin,
3401
+ samples: metric.samples,
3402
+ median: summary.median,
3403
+ spread: summary.spread,
3404
+ report: { kind: MEASUREMENT_SAMPLES_ARTIFACT, rev: deposited[0]!.revision },
3405
+ },
3406
+ }),
3407
+ )
3408
+ }
3409
+
3410
+ /** A panel node's starting measurement: one panel of its harness pin
3411
+ * against itself. The starting value is 0.5 by definition; the spread is
3412
+ * the self-comparison win rate's distance from 0.5. */
3413
+ private async measurePanelBaseline(
3414
+ decision: MeasureBaselineDecision,
3415
+ before: BuildState,
3416
+ ): Promise<void> {
3417
+ const { store, slug } = this.deps
3418
+ const ruler = before.optimization!.rulerRevision
3419
+ const { objective } = before.optimization!
3420
+ if (objective.metric.kind !== 'panel') return
3421
+ const metric = objective.metric
3422
+ const pin = decision.harnessPin
3423
+ // Keyed on the ruler, not the revision: a quick revision mid-run resumes
3424
+ // the same panel.
3425
+ const panel = nodePanelId(before, `baseline-${ruler}-${pin}`)
3426
+ const result = await this.runPanel({
3427
+ id: panel,
3428
+ candidate: pin,
3429
+ baseline: pin,
3430
+ harnessPin: pin,
3431
+ purpose: objective.purpose,
3432
+ rubric: metric.rubric,
3433
+ harness: metric.harness,
3434
+ judges: metric.judges,
3435
+ })
3436
+ if (result.kind === 'interrupted') return
3437
+ const after = (await readBuildFacts(store, slug)).value.state
3438
+ const optimization = after.optimization
3439
+ if (
3440
+ !baselineMeasurementDue(after) ||
3441
+ optimization === undefined ||
3442
+ optimization.rulerRevision !== ruler ||
3443
+ optimization.accepted.harnessPin !== pin
3444
+ )
3445
+ return
3446
+ if (result.kind === 'failed') {
3447
+ await this.raiseMeasurementEscalation(
3448
+ this.failedPanelQuestion(`The starting panel of harness pin ${pin}`, result),
3449
+ nodePanelEscalationId(panel),
3450
+ )
3451
+ return
3452
+ }
3453
+ const spread = Math.abs(result.winRate - 0.5)
3454
+ const epsilon = optimization.objective.target.epsilon
3455
+ const effective = effectiveEpsilon(epsilon, result.winRate)
3456
+ // Attention first, as for a command: a crash before the starting value
3457
+ // resumes the panel and raises it again, never loses it.
3458
+ if (noiseExceeded(effective, spread))
3459
+ await store.append(slug, {
3460
+ actor: KERNEL,
3461
+ type: 'optimization.noise-exceeded',
3462
+ payload: {
3463
+ revision: optimization.revision,
3464
+ head: pin,
3465
+ harnessPin: pin,
3466
+ median: result.winRate,
3467
+ spread,
3468
+ epsilon: { ...epsilon },
3469
+ effectiveEpsilon: effective,
3470
+ },
3471
+ } satisfies EventWrite<'optimization.noise-exceeded'>)
3472
+ // The judgments are on this log as `panel.judged`; no report is deposited.
3473
+ await store.append(slug, {
3474
+ actor: KERNEL,
3475
+ type: 'optimization.baseline-measured',
3476
+ payload: {
3477
+ revision: optimization.revision,
3478
+ head: pin,
3479
+ harnessPin: pin,
3480
+ samples: metric.judges,
3481
+ median: result.winRate,
3482
+ spread,
3483
+ },
3484
+ } satisfies EventWrite<'optimization.baseline-measured'>)
3485
+ }
3486
+
3487
+ /** A panel node's progress: one panel of the oldest landed head without a
3488
+ * recorded progress against the starting head (SPEC §13.1.1). */
3489
+ private async measureProgress(decision: MeasureProgressDecision): Promise<void> {
3490
+ const { store, slug } = this.deps
3491
+ const before = (await readBuildFacts(store, slug)).value.state
3492
+ const due = progressMeasurementDue(before)
3493
+ if (
3494
+ due === undefined ||
3495
+ due.head !== decision.head ||
3496
+ due.start !== decision.start ||
3497
+ due.harnessPin !== decision.harnessPin
3498
+ )
3499
+ return
3500
+ const { objective, rulerRevision: ruler } = before.optimization!
3501
+ if (objective.metric.kind !== 'panel') return
3502
+ const metric = objective.metric
3503
+ const { head, start, harnessPin } = due
3504
+ const panel = nodePanelId(before, `progress-${ruler}-${head}`)
3505
+ const result = await this.runPanel({
3506
+ id: panel,
3507
+ candidate: head,
3508
+ baseline: start,
3509
+ harnessPin,
3510
+ purpose: objective.purpose,
3511
+ rubric: metric.rubric,
3512
+ harness: metric.harness,
3513
+ judges: metric.judges,
3514
+ })
3515
+ if (result.kind === 'interrupted') return
3516
+ // A newer ruler or starting head makes this win rate history. Heads
3517
+ // accepted during the run stay queued behind this one.
3518
+ const after = (await readBuildFacts(store, slug)).value.state
3519
+ const optimization = after.optimization
3520
+ if (
3521
+ optimization === undefined ||
3522
+ optimization.rulerRevision !== ruler ||
3523
+ optimization.starting?.head !== start ||
3524
+ !optimization.progressQueue?.includes(head)
3525
+ )
3526
+ return
3527
+ if (result.kind === 'failed') {
3528
+ await this.raiseMeasurementEscalation(
3529
+ this.failedPanelQuestion(
3530
+ `The progress panel of head ${head} against starting head ${start}`,
3531
+ result,
3532
+ ),
3533
+ nodePanelEscalationId(panel),
3534
+ )
3535
+ return
3536
+ }
3537
+ await store.append(slug, {
3538
+ actor: KERNEL,
3539
+ type: 'optimization.progress-measured',
3540
+ payload: {
3541
+ revision: optimization.revision,
3542
+ head,
3543
+ start,
3544
+ winRate: result.winRate,
3545
+ judges: metric.judges,
3546
+ },
3547
+ } satisfies EventWrite<'optimization.progress-measured'>)
3548
+ }
3549
+
3550
+ private failedPanelQuestion(
3551
+ what: string,
3552
+ failure: Extract<PanelResult, { kind: 'failed' }>,
3553
+ ): string {
3554
+ return (
3555
+ `${what} failed: ${failure.reason}. ` +
3556
+ `Output: ${failure.outputTail || '(no output)'}. ` +
3557
+ 'Fix the rubric, harness or judge configuration, then answer to run the panel again with fresh judges.'
3558
+ )
3559
+ }
3560
+
3561
+ /** A requested measurement of this attempt: sample both sides, a
3562
+ * command's paired runs or a judge panel, and record the samples. The
3563
+ * runner holds only this build's store, so the decision against the node's
3564
+ * ε and spread is the dispatcher's, recorded as `attempt.measured` after
3565
+ * sampling (SPEC §13.1.1). */
3566
+ private async runMeasurement(decision: RunMeasurementDecision): Promise<void> {
3567
+ const { store, slug } = this.deps
3568
+ const { request } = decision
3569
+ const state = async () => (await readBuildFacts(store, slug)).value.state
3570
+ // A request whose baseline the child already saw superseded is never
3571
+ // started: the landing gate requests a current one after the restack.
3572
+ if (pendingMeasurementRequest(await state())?.id !== request.id) return
3573
+ const metric = request.metric
3574
+ if (metric === undefined) {
3575
+ await this.raiseMeasurementEscalation(
3576
+ `Measurement request ${request.id} names no metric, so it cannot be sampled. Answer once a fresh request names the node's metric, or abort the attempt.`,
3577
+ )
3578
+ return
3579
+ }
3580
+ if (metric.kind === 'panel') {
3581
+ await this.runPanelMeasurement(request, metric)
3582
+ return
3583
+ }
3584
+ const result = await this.pairedMeasurement({
3585
+ id: `attempt-${request.id}`,
3586
+ candidate: request.candidate,
3587
+ baseline: request.baseline,
3588
+ harnessPin: request.harnessPin,
3589
+ metric,
3590
+ config: await this.captureConfig(),
3591
+ })
3592
+ if (result.kind === 'interrupted') return
3593
+ // A newer request supersedes these samples; the engine decides again. A
3594
+ // node head that moved during sampling does not: the samples are recorded
3595
+ // and the landing gate's freshness check rejects them as stale.
3596
+ if (measurementRequestStatus(await state())?.request.id !== request.id) return
3597
+ if (result.kind === 'failed') {
3598
+ await this.raiseMeasurementEscalation(
3599
+ this.failedMeasurementQuestion(`Measurement request ${request.id}`, result),
3600
+ )
3601
+ return
3602
+ }
3603
+ await store.appendWithArtifacts(
3604
+ slug,
3605
+ [{ kind: MEASUREMENT_SAMPLES_ARTIFACT, content: JSON.stringify(result, null, 2) }],
3606
+ (deposited) => ({
3607
+ actor: KERNEL,
3608
+ type: 'attempt.sampled',
3609
+ payload: {
3610
+ request: request.id,
3611
+ candidate: request.candidate,
3612
+ baseline: request.baseline,
3613
+ harnessPin: request.harnessPin,
3614
+ revision: request.revision,
3615
+ samples: metric.samples,
3616
+ medians: { baseline: median(result.baseline), candidate: median(result.candidate) },
3617
+ report: { kind: MEASUREMENT_SAMPLES_ARTIFACT, rev: deposited[0]!.revision },
3618
+ },
3619
+ }),
3620
+ )
3621
+ }
3622
+
3623
+ /** A requested panel measurement of this attempt: one judge panel of the
3624
+ * attempt's head against the node head, recorded as `attempt.sampled`
3625
+ * with the win rate. The panel id survives a crash and changes after an
3626
+ * answered measurement escalation, so an answer judges afresh. */
3627
+ private async runPanelMeasurement(
3628
+ request: RunMeasurementDecision['request'],
3629
+ metric: PanelMetric,
3630
+ ): Promise<void> {
3631
+ const { store, slug } = this.deps
3632
+ const purpose = request.purpose
3633
+ if (purpose === undefined) {
3634
+ await this.raiseMeasurementEscalation(
3635
+ `Measurement request ${request.id} names a judge panel without the objective purpose, so it cannot be judged. Answer once a fresh request names the purpose, or abort the attempt.`,
3636
+ )
3637
+ return
3638
+ }
3639
+ const state = (await readBuildFacts(store, slug)).value.state
3640
+ const recorded = state.attemptMeasurement?.request
3641
+ if (recorded?.id !== request.id) return
3642
+ const id = attemptPanelId(state, recorded)
3643
+ const result = await this.runPanel({
3644
+ id,
3645
+ candidate: request.candidate,
3646
+ baseline: request.baseline,
3647
+ harnessPin: request.harnessPin,
3648
+ purpose,
3649
+ rubric: metric.rubric,
3650
+ harness: metric.harness,
3651
+ judges: metric.judges,
3652
+ })
3653
+ if (result.kind === 'interrupted') return
3654
+ // A newer request supersedes this panel; the engine decides again.
3655
+ const after = pendingMeasurementRequest((await readBuildFacts(store, slug)).value.state)
3656
+ if (after?.id !== request.id) return
3657
+ if (result.kind === 'failed') {
3658
+ await this.raiseMeasurementEscalation(
3659
+ `Judge panel ${id} for measurement request ${request.id} failed: ${result.reason}. ` +
3660
+ `Output: ${result.outputTail || '(no output)'}. ` +
3661
+ 'Fix the judge runtime, rubric or harness, then answer to judge again.',
3662
+ )
3663
+ return
3664
+ }
3665
+ const report = {
3666
+ kind: 'panel',
3667
+ panel: id,
3668
+ winRate: result.winRate,
3669
+ judgments: result.judgments,
3670
+ }
3671
+ await store.appendWithArtifacts(
3672
+ slug,
3673
+ [{ kind: MEASUREMENT_SAMPLES_ARTIFACT, content: JSON.stringify(report, null, 2) }],
3674
+ (deposited) => ({
3675
+ actor: KERNEL,
3676
+ type: 'attempt.sampled',
3677
+ payload: {
3678
+ request: request.id,
3679
+ candidate: request.candidate,
3680
+ baseline: request.baseline,
3681
+ harnessPin: request.harnessPin,
3682
+ revision: request.revision,
3683
+ samples: metric.judges,
3684
+ winRate: result.winRate,
3685
+ report: { kind: MEASUREMENT_SAMPLES_ARTIFACT, rev: deposited[0]!.revision },
3686
+ },
3687
+ }),
3688
+ )
3689
+ }
3690
+
3691
+ // ── Judge panels (SPEC §13.1.1) ────────────────────────────────────────────
3692
+
3693
+ /**
3694
+ * Run one judge panel over two harness-pinned variants and return the
3695
+ * candidate's win rate, ties counted as half. A run with the same id
3696
+ * resumes: recorded judgments are kept, a saved preference is completed
3697
+ * without a session, and only judges with no preference run again.
3698
+ */
3699
+ async runPanel(input: PanelRequest): Promise<PanelResult> {
3700
+ const { store, slug } = this.deps
3701
+ const started: EventPayload<'panel.started'> = {
3702
+ panel: input.id,
3703
+ candidate: input.candidate,
3704
+ baseline: input.baseline,
3705
+ harnessPin: input.harnessPin,
3706
+ purpose: input.purpose,
3707
+ rubric: input.rubric,
3708
+ harness: [...input.harness],
3709
+ judges: input.judges,
3710
+ }
3711
+ const recorded = (await readBuildFacts(store, slug)).value.state.panel
3712
+ if (recorded?.started.panel === input.id) {
3713
+ if (!samePanelInputs(recorded.started, started))
3714
+ throw new Error(`panel ${input.id} was started with different inputs`)
3715
+ } else
3716
+ await store.append(slug, {
3717
+ actor: KERNEL,
3718
+ type: 'panel.started',
3719
+ payload: started,
3720
+ } satisfies EventWrite<'panel.started'>)
3721
+ await this.captureConfig()
3722
+ const read = async () => {
3723
+ const run = (await readBuildFacts(store, slug)).value.state.panel
3724
+ if (run?.started.panel !== input.id)
3725
+ throw new Error(`panel ${input.id} was superseded by another run`)
3726
+ return run
3727
+ }
3728
+ const runtime = this.boundaryResolver.resolve(JUDGE_ROLE).runner
3729
+ const localStore = this.judgeLocalStore()
3730
+ const run: PanelRunInput = {
3731
+ workspacePath: this.deps.workspacePath,
3732
+ ...(localStore !== undefined ? { localStore } : {}),
3733
+ ...(runtime.executable !== undefined ? { runtimeExecutable: runtime.executable } : {}),
3734
+ build: slug,
3735
+ panel: input.id,
3736
+ candidate: input.candidate,
3737
+ baseline: input.baseline,
3738
+ harnessPin: input.harnessPin,
3739
+ harness: input.harness,
3740
+ purpose: input.purpose,
3741
+ rubric: input.rubric,
3742
+ judges: input.judges,
3743
+ }
3744
+ return runPanelJudges(
3745
+ {
3746
+ exec: this.deps.exec,
3747
+ distributionSkill: this.deps.judgeSkill ?? distributionJudgeSkill,
3748
+ judgeLauncher: this.deps.judgeLauncher ?? bundleJudgeLauncher,
3749
+ distributionRoot: distributionRoot(),
3750
+ },
3751
+ run,
3752
+ {
3753
+ read,
3754
+ complete: async (judged) => {
3755
+ await store.append(slug, {
3756
+ actor: KERNEL,
3757
+ type: 'panel.judged',
3758
+ payload: judged,
3759
+ } satisfies EventWrite<'panel.judged'>)
3760
+ },
3761
+ reclaim: async (judge, session, root, stream) => {
3762
+ // A preference the crashed session saved is committed while its
3763
+ // session is still open, then completed like any saved preference.
3764
+ // Its stream closes after that settlement and before its end.
3765
+ if (!this.judgeStoreIsRemote())
3766
+ await this.commitJudgeOutbox(input.id, judge, session, root, { onlyOwn: true })
3767
+ if (stream !== undefined)
3768
+ try {
3769
+ await store.closeStream(stream, 'aborted')
3770
+ } catch {
3771
+ // Best-effort: the reclaimed end is still recorded.
3772
+ }
3773
+ await store.append(slug, {
3774
+ actor: KERNEL,
3775
+ type: 'panel.judge-ended',
3776
+ payload: { panel: input.id, judge, session, outcome: 'reclaimed' },
3777
+ } satisfies EventWrite<'panel.judge-ended'>)
3778
+ },
3779
+ launch: (judge, order, root, judgeLaunch, preflight) =>
3780
+ this.runJudge(input.id, judge, order, root, judgeLaunch, preflight),
3781
+ random: this.deps.random ?? Math.random,
3782
+ ...(this.deps.shutdownSignal !== undefined
3783
+ ? { shutdownSignal: this.deps.shutdownSignal }
3784
+ : {}),
3785
+ },
3786
+ )
3787
+ }
3788
+
3789
+ /** One judge's sessions in its sealed root, primary first, then each of
3790
+ * the judge role's provider alternates while the previous session's
3791
+ * failure is alternate-eligible (SPEC §13.1.1). Every target is its own
3792
+ * session in the same root and order: its order is durable in
3793
+ * `panel.judge-started` before it starts, it gets its own credential and
3794
+ * stream, and afterwards one reduced read finds its preference, recorded
3795
+ * with the order as `panel.judged`. A fallback follows only once the
3796
+ * failed session's preference is settled and its end recorded, and never
3797
+ * after any preference or saved outbox. Failures inside a session become
3798
+ * its outcome; store errors propagate. */
3799
+ private async runJudge(
3800
+ panel: string,
3801
+ judge: number,
3802
+ order: PanelOrder,
3803
+ root: string,
3804
+ judgeLaunch: JudgeLaunch,
3805
+ preflight: (executable: string) => Promise<string | undefined>,
3806
+ ): Promise<PanelJudgeOutcome> {
3807
+ const { store, slug } = this.deps
3808
+ const resolved = this.boundaryResolver.resolve(JUDGE_ROLE)
3809
+ const targets: readonly ResolvedRuntime[] = [resolved, ...resolved.alternates]
3810
+ let substitution: ProviderAttempt | undefined
3811
+ for (let index = 0; ; index += 1) {
3812
+ const step = await this.runJudgeSession(
3813
+ panel,
3814
+ judge,
3815
+ order,
3816
+ root,
3817
+ judgeLaunch,
3818
+ resolved.sessionBudgetSeconds,
3819
+ targets,
3820
+ index,
3821
+ substitution,
3822
+ preflight,
3823
+ )
3824
+ if (step.kind === 'ended') return step.outcome
3825
+ // The failed session has ended, so its credential can no longer
3826
+ // record. A preference that raced that end stops the chain: the next
3827
+ // wave completes it, and no fallback session ever coexists with it.
3828
+ const state = (await readBuildFacts(store, slug)).value.state.panel
3829
+ const recorded = state?.started.panel === panel ? state.judges[String(judge)] : undefined
3830
+ if (recorded?.preferred !== undefined) return 'failed'
3831
+ substitution = step.substituted
3832
+ }
3833
+ }
3834
+
3835
+ /** One judge session against `targets[index]`. Resolves `fallback` with
3836
+ * the failed attempt when the next target should run, after this
3837
+ * session's `panel.judge-ended` is recorded. */
3838
+ private async runJudgeSession(
3839
+ panel: string,
3840
+ judge: number,
3841
+ order: PanelOrder,
3842
+ root: string,
3843
+ judgeLaunch: JudgeLaunch,
3844
+ sessionBudgetSeconds: number,
3845
+ targets: readonly ResolvedRuntime[],
3846
+ index: number,
3847
+ substitution: ProviderAttempt | undefined,
3848
+ preflight: (executable: string) => Promise<string | undefined>,
3849
+ ): Promise<
3850
+ | { kind: 'ended'; outcome: PanelJudgeOutcome }
3851
+ | { kind: 'fallback'; substituted: ProviderAttempt }
3852
+ > {
3853
+ const { store, slug, ids, shutdownSignal } = this.deps
3854
+ const target = targets[index]!
3855
+ const { runner, runtime, model, args, account } = target
3856
+ const session = ids('s')
3857
+ // The stream's identity names the judge, never its order, root or side.
3858
+ const streamBracket = await this.openSessionStream(target, {
3859
+ session,
3860
+ role: JUDGE_ROLE,
3861
+ runner: runtime,
3862
+ ...(model !== undefined ? { model } : {}),
3863
+ phase: `judge:${panel}:${judge}`,
3864
+ })
2591
3865
  try {
2592
- for (;;) {
2593
- const observed = revision
2594
- if (this.deps.shutdownSignal?.aborted) return
2595
- if (decision.kind !== 'run-verify-stage') {
2596
- if (decision.kind === 'cancel-verify-stage') {
2597
- await this.cancelVerifyStage(decision)
2598
- await this.endCancelledVerifySessions(decision)
2599
- } else {
2600
- drain = terminalDrain
3866
+ await store.append(slug, {
3867
+ actor: KERNEL,
3868
+ type: 'panel.judge-started',
3869
+ payload: {
3870
+ panel,
3871
+ judge,
3872
+ session,
3873
+ order,
3874
+ runner: runtime,
3875
+ ...(model !== undefined ? { model } : {}),
3876
+ ...(account !== undefined ? { account } : {}),
3877
+ ...(streamBracket !== undefined ? { stream: streamBracket.streamId } : {}),
3878
+ ...(substitution !== undefined
3879
+ ? { substitution: { failed: substitution, selectedIndex: index } }
3880
+ : {}),
3881
+ },
3882
+ } satisfies EventWrite<'panel.judge-started'>)
3883
+
3884
+ const budget = (this.deps.timeoutSignal ?? ((ms) => AbortSignal.timeout(ms)))(
3885
+ sessionBudgetSeconds * 1000,
3886
+ )
3887
+ const signal = shutdownSignal ? AbortSignal.any([budget, shutdownSignal]) : budget
3888
+ let outcome: PanelJudgeOutcome = 'completed'
3889
+ let error: string | undefined
3890
+ let handle: AgentSessionHandle | undefined
3891
+ // The provider failure an alternate may follow. A delegation failure is
3892
+ // a store failure, not a provider failure, so it leaves this undefined.
3893
+ let failure: AgentTurnFailure | undefined
3894
+ let env: Record<string, string> | undefined
3895
+ try {
3896
+ env = await this.judgeSessionEnv(panel, judge, session)
3897
+ } catch (caught) {
3898
+ outcome = 'failed'
3899
+ error = errorMessage(caught)
3900
+ }
3901
+ if (env !== undefined)
3902
+ try {
3903
+ const turn = await runner.start({
3904
+ skill: installedSkillName('judge'),
3905
+ invocation: panel,
3906
+ workspacePath: root,
3907
+ ...(model !== undefined ? { model } : {}),
3908
+ ...(args.length > 0 ? { args } : {}),
3909
+ ...(account !== undefined ? { account } : {}),
3910
+ env,
3911
+ judgeLaunch,
3912
+ signal,
3913
+ ...(streamBracket !== undefined ? { stream: streamBracket.sink } : {}),
3914
+ })
3915
+ handle = turn.session
3916
+ if (turn.result.kind === 'failed') {
3917
+ outcome = 'failed'
3918
+ error = turn.result.failure.message
3919
+ if (isAlternateEligible(turn.result.failure)) failure = turn.result.failure
2601
3920
  }
2602
- return
3921
+ } catch (caught) {
3922
+ // A thrown start, including an adapter's launch-argument refusal,
3923
+ // is eligible as in every build phase; the alternate gets its own
3924
+ // preflight and the same launch context.
3925
+ outcome = 'failed'
3926
+ error = errorMessage(caught)
3927
+ failure = { message: error, permanent: false, cause: 'availability' }
2603
3928
  }
2604
- if (
2605
- decision.members.some(
2606
- (member) => !initial.members.some((first) => first.step === member.step),
2607
- )
2608
- ) {
2609
- drain = terminalDrain
2610
- return
3929
+ if (shutdownSignal?.aborted) outcome = 'interrupted'
3930
+ else if (budget.aborted) {
3931
+ outcome = 'expired'
3932
+ error = sessionBudgetError(sessionBudgetSeconds)
3933
+ }
3934
+ let transcript: Transcript | undefined
3935
+ if (handle !== undefined)
3936
+ try {
3937
+ transcript = await runner.end(handle)
3938
+ } catch {
3939
+ // Best-effort: the judge's outcome below is still recorded.
2611
3940
  }
2612
- const members = await Promise.all(
2613
- decision.members.map((member) =>
2614
- member.kind === 'evaluate-verify' ? this.resolveVerify(member) : member,
2615
- ),
2616
- )
2617
- for (const member of members) {
2618
- const key = verifyMemberKey(member.step, member.attempt)
2619
- const active = inFlight.get(key)
2620
- if (active && !active.done) continue
2621
- if (active?.error) throw active.error
2622
- const child = new BuildRunner({
2623
- ...this.deps,
2624
- config: this.boundaryConfig,
2625
- shutdownSignal: this.deps.shutdownSignal
2626
- ? AbortSignal.any([this.deps.shutdownSignal, interrupted.signal])
2627
- : interrupted.signal,
2628
- })
2629
- child.verifyWrites = this.verifyWrites
2630
- const recovery = this.stageRecoveries.get(key)
2631
- child.recovery = recovery?.session
2632
- child.recoveryBoundaryMs = this.recoveryBoundaryMs
2633
- child.recoveryCause = recovery?.cause ?? 'runner-loss'
2634
- this.stageRecoveries.delete(key)
2635
- const entry: MemberExecution = {
2636
- runner: child,
2637
- done: false,
2638
- agent: member.kind === 'run-agent-verify',
2639
- }
2640
- inFlight.set(key, entry)
2641
- const work =
2642
- member.kind === 'run-check'
2643
- ? child.runCheck(member)
2644
- : member.kind === 'run-agent-verify'
2645
- ? child.runAgentVerify(member)
2646
- : member.kind === 'skip-verify'
2647
- ? child.skipVerify(member)
2648
- : Promise.resolve()
2649
- entry.pending = work.then(
2650
- () => {
2651
- entry.done = true
2652
- revision += 1
2653
- wake?.()
2654
- },
2655
- (error) => {
2656
- entry.done = true
2657
- entry.error = error
2658
- revision += 1
2659
- wake?.()
3941
+ // A local judge saved its preference in its root; commit it while the
3942
+ // session is still open, before the reduced read below finds it.
3943
+ const outboxError = this.judgeStoreIsRemote()
3944
+ ? undefined
3945
+ : await this.commitJudgeOutbox(panel, judge, session, root)
3946
+
3947
+ const state = (await readBuildFacts(store, slug)).value.state.panel
3948
+ const recorded = state?.started.panel === panel ? state.judges[String(judge)] : undefined
3949
+ const preferred = recorded?.preferred?.session === session ? recorded.preferred : undefined
3950
+ if (preferred !== undefined) {
3951
+ if (recorded?.judged === undefined)
3952
+ await store.append(slug, {
3953
+ actor: KERNEL,
3954
+ type: 'panel.judged',
3955
+ payload: {
3956
+ panel,
3957
+ judge,
3958
+ session,
3959
+ order,
3960
+ preference: preferred.preference,
3961
+ reason: preferred.reason,
2660
3962
  },
2661
- )
2662
- }
2663
- if (revision === observed)
2664
- await new Promise<void>((resolve) => {
2665
- wake = resolve
2666
- if (revision !== observed) resolve()
2667
- })
2668
- wake = undefined
2669
- const facts = (await readBuildFacts(store, slug)).value
2670
- decision = decideNextFromFacts(facts.state, facts.log, await this.captureConfig())
2671
- terminalDrain =
2672
- facts.state.status === 'running' &&
2673
- facts.state.pendingCommands.length === 0 &&
2674
- [...inFlight.keys()].every((key) => facts.state.verifyStage.outcomes[key] !== undefined)
3963
+ } satisfies EventWrite<'panel.judged'>)
3964
+ outcome = 'completed'
3965
+ error = undefined
3966
+ } else {
3967
+ if (outcome === 'completed') outcome = 'no-terminal'
3968
+ if (outboxError !== undefined) error = error ?? outboxError
3969
+ }
2675
3970
 
2676
- for (const entry of inFlight.values()) if (entry.error) throw entry.error
3971
+ // A recorded terminal wins over a failure: any preference or saved
3972
+ // outbox ends the chain, so an alternate never meets a stale outbox.
3973
+ let substituted: ProviderAttempt | undefined
3974
+ const next = targets[index + 1]
3975
+ if (
3976
+ outcome === 'failed' &&
3977
+ failure !== undefined &&
3978
+ next !== undefined &&
3979
+ recorded?.preferred === undefined &&
3980
+ outboxError === undefined
3981
+ ) {
3982
+ const refusal =
3983
+ next.runner.executable !== undefined ? await preflight(next.runner.executable) : undefined
3984
+ if (refusal !== undefined)
3985
+ error = `${error}; alternate ${index + 1} (${next.runtime}) refused: ${refusal}`
3986
+ else
3987
+ substituted = {
3988
+ index,
3989
+ session,
3990
+ runner: runtime,
3991
+ ...(account !== undefined ? { account } : {}),
3992
+ ...(model !== undefined ? { model } : {}),
3993
+ error: failure.message,
3994
+ ...(failure.cause !== undefined ? { cause: failure.cause } : {}),
3995
+ }
2677
3996
  }
3997
+
3998
+ if (streamBracket !== undefined)
3999
+ try {
4000
+ await streamBracket.sink.close(preferred !== undefined ? 'completed' : 'aborted')
4001
+ } catch {
4002
+ // Best-effort: the session's end is still recorded.
4003
+ }
4004
+ const ended = (artifact?: {
4005
+ kind: string
4006
+ rev: number
4007
+ }): EventWrite<'panel.judge-ended'> => ({
4008
+ actor: KERNEL,
4009
+ type: 'panel.judge-ended',
4010
+ payload: {
4011
+ panel,
4012
+ judge,
4013
+ session,
4014
+ outcome,
4015
+ ...(error !== undefined ? { error } : {}),
4016
+ ...(artifact !== undefined ? { transcript: artifact } : {}),
4017
+ },
4018
+ })
4019
+ if (transcript === undefined) await store.append(slug, ended())
4020
+ else
4021
+ await store.appendWithArtifacts(
4022
+ slug,
4023
+ [
4024
+ {
4025
+ kind: 'transcript',
4026
+ content: transcript.content,
4027
+ metadata: {
4028
+ panel,
4029
+ judge,
4030
+ session,
4031
+ role: JUDGE_ROLE,
4032
+ runner: runtime,
4033
+ ...((transcript.metadata.model ?? model)
4034
+ ? { model: transcript.metadata.model ?? model }
4035
+ : {}),
4036
+ usage: transcript.metadata.usage,
4037
+ },
4038
+ },
4039
+ ],
4040
+ (deposited) => ended({ kind: deposited[0]!.kind, rev: deposited[0]!.revision }),
4041
+ )
4042
+ return substituted !== undefined
4043
+ ? { kind: 'fallback', substituted }
4044
+ : { kind: 'ended', outcome }
2678
4045
  } finally {
2679
- unsubscribe()
2680
- this.deps.shutdownSignal?.removeEventListener('abort', onShutdown)
2681
- // A terminal can precede the adapter return. Let normal agent settlement
2682
- // close its bracket before stage-local shutdown can suspend it remotely.
2683
- // Parent shutdown and session budgets remain active throughout this drain.
2684
- if (drain) for (const entry of inFlight.values()) if (entry.agent) await entry.pending
2685
- interrupted.abort()
2686
- for (const entry of inFlight.values()) {
2687
- // Fail-fast must reach whole-execution teardown even when an adapter
2688
- // ignores abort. Its cancelled brackets are already durably ended;
2689
- // the supervisor, rather than a per-member reaper, owns descendants.
2690
- if (entry.agent && decision.kind !== 'cancel-verify-stage') await entry.pending
2691
- for (const stream of entry.runner.bracketStreams.values())
2692
- entry.runner.closeBracketStream(stream, 'aborted')
2693
- await entry.runner.closeProducerSessions()
2694
- }
4046
+ this.closeBracketStream(streamBracket, 'aborted')
4047
+ this.bracketStreams.delete(session)
2695
4048
  }
2696
4049
  }
2697
4050
 
2698
- /** Shared writer for every deterministic exclusion mechanism. A skip is a
2699
- * queryable two-fact phase occurrence and launches no command or session. */
2700
- private async verifyEvidence() {
2701
- const facts = (await readBuildFacts(this.deps.store, this.deps.slug)).value
2702
- if (facts.state.kind === 'node') {
2703
- const cycle = facts.state.integration?.cycle
2704
- if (!cycle) throw new Error('missing prepared integration verification')
2705
- const head = await this.deps.exec(['git', 'rev-parse', 'HEAD'], {
2706
- cwd: this.deps.workspacePath,
2707
- })
2708
- if (head.exitCode !== 0 || head.stdout.trim() !== cycle.head)
2709
- throw new Error('integration checkout differs from prepared head')
2710
- return { baseSha: cycle.parent, headSha: cycle.head, restackId: cycle.id }
4051
+ /** Whether judges reach a remote store (a write-only grant) rather than
4052
+ * the local store (a preference outbox the runner commits). */
4053
+ private judgeStoreIsRemote(): boolean {
4054
+ const store = this.deps.sessionEnv?.AB_STORE
4055
+ return store !== undefined && /^https?:/i.test(store)
4056
+ }
4057
+
4058
+ /** The local store's path, which no judge may learn. */
4059
+ private judgeLocalStore(): string | undefined {
4060
+ const store = this.deps.sessionEnv?.AB_STORE
4061
+ return store !== undefined && store !== '' && store !== 'local' && !this.judgeStoreIsRemote()
4062
+ ? store
4063
+ : undefined
4064
+ }
4065
+
4066
+ /**
4067
+ * A judge session's scoped environment: the judge identity and, for a
4068
+ * remote store, its URL and a write-only credential. A local judge gets no
4069
+ * store at all: its preference goes to an outbox in its root. There is no
4070
+ * `AB_BUILD` and no `AB_PHASE`, and the runner's own token never passes
4071
+ * through. A delegation failure throws, so the judge never launches with a
4072
+ * weaker environment.
4073
+ */
4074
+ private async judgeSessionEnv(
4075
+ panel: string,
4076
+ judge: number,
4077
+ session: string,
4078
+ ): Promise<Record<string, string>> {
4079
+ const parent = this.deps.sessionEnv ?? {}
4080
+ const remote = this.judgeStoreIsRemote()
4081
+ const token = remote
4082
+ ? await (this.deps.delegateCredential ?? delegateCredential)(
4083
+ parent.AB_STORE!,
4084
+ parent.AB_TOKEN,
4085
+ { kind: 'build-judge', id: this.deps.slug, session, panel, judge },
4086
+ )
4087
+ : undefined
4088
+ const env: Record<string, string> = {
4089
+ AB_ACCOUNT_CREDENTIAL_ENVS: JSON.stringify(
4090
+ Object.values(this.boundaryConfig.accounts).map((account) => account.credentialEnv),
4091
+ ),
4092
+ ...parent,
4093
+ }
4094
+ delete env.AB_TOKEN
4095
+ delete env.AB_BUILD
4096
+ delete env.AB_PHASE
4097
+ delete env.AB_REPO
4098
+ delete env.AB_HARVEST
4099
+ if (!remote) delete env.AB_STORE
4100
+ return {
4101
+ ...env,
4102
+ ...(token !== undefined ? { AB_TOKEN: token } : {}),
4103
+ AB_JUDGE: `${this.deps.slug}:${panel}:${judge}`,
4104
+ AB_SESSION: session,
4105
+ AB_CONTEXT_DIR: JUDGE_CONTEXT_DIR,
2711
4106
  }
2712
- const cycle = Math.max(facts.log.code.latestApproveSeq, facts.log.lastReconcileCompletedSeq)
2713
- const gate = facts.log.restack.gates[String(cycle)]
2714
- if (gate !== undefined)
2715
- return { baseSha: gate.targetBase, headSha: gate.headSha, restackId: gate.id }
2716
- return {}
2717
4107
  }
2718
4108
 
2719
- private async skipVerify(decision: SkipVerifyDecision): Promise<void> {
2720
- const { store, slug } = this.deps
2721
- await this.withVerifyWrite(async () => {
2722
- const { state } = (await readBuildFacts(store, slug)).value
2723
- const key = verifyMemberKey(decision.step, decision.attempt)
2724
- if (state.verifyStage.cancellations[key] || state.verifyStage.outcomes[key]) return
2725
- const evidence = await this.verifyEvidence()
2726
- await store.append(slug, {
2727
- actor: KERNEL,
2728
- type: 'verify.started',
2729
- payload: { ...evidence, step: decision.step, attempt: decision.attempt },
2730
- } satisfies EventWrite<'verify.started'>)
2731
- await store.append(slug, {
2732
- actor: KERNEL,
2733
- type: 'verify.completed',
2734
- payload: {
2735
- step: decision.step,
2736
- attempt: decision.attempt,
2737
- ...evidence,
2738
- outcome: 'skipped',
2739
- reason: decision.reason,
2740
- ...(decision.skipCause !== undefined ? { skipCause: decision.skipCause } : {}),
2741
- },
2742
- } satisfies EventWrite<'verify.completed'>)
2743
- })
4109
+ /**
4110
+ * Commit a local judge's saved preference (SPEC §13.1.1): read its outbox
4111
+ * from the judge's root, validate it, and append it atomically as the
4112
+ * judge session. A missing outbox does nothing; a preference this session
4113
+ * already recorded is success. Returns the reason a present, or unreadable,
4114
+ * outbox was not committed. With `onlyOwn`, an outbox naming another session is left for
4115
+ * that session's own reclaim.
4116
+ */
4117
+ private async commitJudgeOutbox(
4118
+ panel: string,
4119
+ judge: number,
4120
+ session: string,
4121
+ root: string,
4122
+ opts: { onlyOwn?: boolean } = {},
4123
+ ): Promise<string | undefined> {
4124
+ const read = await this.deps.exec(
4125
+ [
4126
+ 'sh',
4127
+ '-c',
4128
+ 'if [ -f "$1" ]; then printf 1; head -c "$2" "$1"; else printf 0; fi',
4129
+ 'judge-outbox',
4130
+ `${root}/${JUDGE_PREFERENCE_OUTBOX}`,
4131
+ String(JUDGE_PREFERENCE_OUTBOX_BYTES + 1),
4132
+ ],
4133
+ {},
4134
+ )
4135
+ // Only a clean read of `0` proves absence. A failed read may hide a saved
4136
+ // preference, so it is reported, which keeps an alternate out of the root.
4137
+ if (read.exitCode !== 0)
4138
+ return `the saved judge preference could not be read: ${read.stderr.trim() || `exit ${read.exitCode}`}`
4139
+ if (read.stdout.startsWith('0')) return undefined
4140
+ const text = read.stdout.slice(1)
4141
+ if (text.length > JUDGE_PREFERENCE_OUTBOX_BYTES)
4142
+ return 'the saved judge preference is larger than 64 KiB'
4143
+ let saved: ReturnType<typeof judgePreferenceOutboxSchema.parse>
4144
+ try {
4145
+ saved = judgePreferenceOutboxSchema.parse(JSON.parse(text))
4146
+ } catch {
4147
+ return 'the saved judge preference is malformed'
4148
+ }
4149
+ if (opts.onlyOwn && saved.session !== session) return undefined
4150
+ const result = await appendJudgePreference(
4151
+ this.deps.store,
4152
+ { build: this.deps.slug, panel, judge, session },
4153
+ {
4154
+ actor: agentActor('judge', session),
4155
+ type: 'panel.preferred',
4156
+ payload: saved,
4157
+ },
4158
+ )
4159
+ if (result.kind === 'recorded') return undefined
4160
+ if (result.reason === 'this judge already recorded its preference') return undefined
4161
+ return `the saved judge preference was refused: ${result.reason}`
2744
4162
  }
2745
4163
 
2746
4164
  /** Deterministic check (§8.2): NO session, NO CLI — the kernel runs the
2747
- * command directly; a failure deposits the output tail as the report. */
4165
+ * command directly with `AB_VERIFY_BASE` set to the verify diff base, or
4166
+ * unset when none exists; a failure deposits the output tail as the report. */
2748
4167
  private async runCheck(decision: RunCheckDecision): Promise<void> {
2749
4168
  await this.withKernelPhaseFailure(verifyPhase(decision.step), decision.attempt, () =>
2750
4169
  this.runCheckOperation(decision),
@@ -2754,7 +4173,8 @@ export class BuildRunner {
2754
4173
  private async runCheckOperation(decision: RunCheckDecision): Promise<void> {
2755
4174
  const { store, slug, exec, workspacePath } = this.deps
2756
4175
  const { step, command, attempt } = decision
2757
- const current = (await readBuildFacts(store, slug)).value.state
4176
+ const facts = (await readBuildFacts(store, slug)).value
4177
+ const current = facts.state
2758
4178
  const memberKey = verifyMemberKey(step, attempt)
2759
4179
  if (current.verifyStage.outcomes[memberKey] || current.verifyStage.cancellations[memberKey])
2760
4180
  return
@@ -2775,15 +4195,29 @@ export class BuildRunner {
2775
4195
  payload: { ...evidence, step, attempt },
2776
4196
  } satisfies EventWrite<'verify.started'>)
2777
4197
 
2778
- const result = await exec(['sh', '-c', command], {
2779
- cwd: workspacePath,
2780
- ...(this.deps.shutdownSignal ? { signal: this.deps.shutdownSignal } : {}),
2781
- })
2782
- if (this.deps.shutdownSignal?.aborted) return
4198
+ // A node's landing withdraws its lease; the heartbeat then aborts the check.
4199
+ const landing = current.kind === 'node' ? new AbortController() : undefined
4200
+ this.checkAbort = landing
4201
+ const signals = [this.deps.shutdownSignal, landing?.signal].filter(
4202
+ (signal): signal is AbortSignal => signal !== undefined,
4203
+ )
4204
+ let result: Awaited<ReturnType<typeof exec>>
4205
+ try {
4206
+ result = await exec(['sh', '-c', command], {
4207
+ cwd: workspacePath,
4208
+ // An undefined value clears any inherited base rather than leaking it.
4209
+ env: { [VERIFY_BASE_ENV]: verifyDiffBaseFrom(facts) },
4210
+ ...(signals.length ? { signal: AbortSignal.any(signals) } : {}),
4211
+ })
4212
+ } finally {
4213
+ if (this.checkAbort === landing) this.checkAbort = undefined
4214
+ }
4215
+ if (this.deps.shutdownSignal?.aborted || landing?.signal.aborted) return
2783
4216
  await this.withVerifyWrite(async () => {
2784
4217
  const state = (await readBuildFacts(store, slug)).value.state
2785
4218
  const key = verifyMemberKey(step, attempt)
2786
4219
  if (state.verifyStage.cancellations[key] || state.verifyStage.outcomes[key]) return
4220
+ if (nodeLanded(state)) return
2787
4221
  if (result.exitCode === 0) {
2788
4222
  await store.append(slug, {
2789
4223
  actor: KERNEL,
@@ -3506,6 +4940,12 @@ export class BuildRunner {
3506
4940
  void readBuildFacts(store, slug)
3507
4941
  .then((facts) => {
3508
4942
  if (closed || controller.signal.aborted) return
4943
+ // A landing recorded before this bracket armed ends the turn as an operator stop.
4944
+ if (nodeLanded(facts.value.state)) {
4945
+ abortCause = 'operator'
4946
+ controller.abort(new Error(`node ${slug} landed`))
4947
+ return
4948
+ }
3509
4949
  const next = decideNextFromFacts(facts.value.state, facts.value.log, this.boundaryConfig)
3510
4950
  if (next.kind !== 'acknowledge' || next.command !== 'pause') return
3511
4951
  pauseInterrupted = true
@@ -3528,6 +4968,11 @@ export class BuildRunner {
3528
4968
  abortCause = 'operator'
3529
4969
  controller.abort(new Error(`build ${slug} aborted by operator`))
3530
4970
  }
4971
+ // Only node builds record a landing; it ends open verification like an operator stop.
4972
+ if (event.type === 'integration.landed') {
4973
+ abortCause = 'operator'
4974
+ controller.abort(new Error(`node ${slug} landed`))
4975
+ }
3531
4976
  })
3532
4977
  // A pause may have landed after phase selection but before this bracket.
3533
4978
  // Arm future delivery first, then check the current durable command too.
@@ -4868,13 +6313,22 @@ export class BuildRunner {
4868
6313
  payload: { attempt: reconcile.attempt, baseSha: reconcileBaseSha },
4869
6314
  } satisfies EventWrite<'reconcile.started'>
4870
6315
  }
6316
+ case 'propose': {
6317
+ if (decision.propose === undefined)
6318
+ throw new Error('run-phase propose start requires its open request')
6319
+ return {
6320
+ actor: KERNEL,
6321
+ type: 'propose.started',
6322
+ payload: { round, request: decision.propose.request },
6323
+ } satisfies EventWrite<'propose.started'>
6324
+ }
4871
6325
  }
4872
6326
  }
4873
6327
 
4874
6328
  private stopHeartbeat(): void {
4875
- if (this.heartbeatTimer !== undefined) {
4876
- clearInterval(this.heartbeatTimer)
4877
- this.heartbeatTimer = undefined
6329
+ if (this.cancelHeartbeat !== undefined) {
6330
+ this.cancelHeartbeat()
6331
+ this.cancelHeartbeat = undefined
4878
6332
  }
4879
6333
  }
4880
6334