@defrex/autobuild 1.9.0 → 1.10.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 (420) hide show
  1. package/README.md +3 -3
  2. package/SPEC.md +1512 -125
  3. package/bin/ab-dispatch-generation.ts +2 -0
  4. package/docs/agent-runtimes.md +30 -3
  5. package/docs/answering-blocked-builds.md +15 -7
  6. package/docs/architecture.md +282 -39
  7. package/docs/builds.md +5 -0
  8. package/docs/cli.md +7 -1
  9. package/docs/configuration-overview.md +1 -0
  10. package/docs/configuration.md +268 -45
  11. package/docs/dispatcher.md +17 -3
  12. package/docs/forges.md +1 -1
  13. package/docs/getting-started.md +1 -1
  14. package/docs/integration-overview.md +4 -2
  15. package/docs/integration-tree.md +102 -11
  16. package/docs/merge-policy.md +30 -14
  17. package/docs/migration-1.0.md +2 -1
  18. package/docs/operating.md +32 -4
  19. package/docs/operator-api.md +117 -14
  20. package/docs/optimization-nodes.md +1042 -0
  21. package/docs/overview.md +1 -1
  22. package/docs/plugin-authoring.md +46 -12
  23. package/docs/remote-store-protocol.md +46 -7
  24. package/docs/remote-ticket-protocol.md +50 -2
  25. package/docs/restacking.md +99 -11
  26. package/docs/seams.md +2 -2
  27. package/docs/setup.md +13 -2
  28. package/docs/skills.md +4 -2
  29. package/docs/spec-standard.md +2 -1
  30. package/docs/ticket-dependencies.md +5 -0
  31. package/docs/ticket-migration.md +4 -2
  32. package/docs/ticket-sources.md +30 -12
  33. package/docs/tickets.md +15 -6
  34. package/docs/troubleshooting.md +3 -2
  35. package/docs/verification.md +11 -0
  36. package/docs/workspaces.md +3 -1
  37. package/package.json +3 -3
  38. package/packages/core/src/accounts/chatgpt-oauth.ts +7 -5
  39. package/packages/core/src/cli/attempt.ts +103 -0
  40. package/packages/core/src/cli/attention.ts +8 -1
  41. package/packages/core/src/cli/binary-direct.ts +52 -1
  42. package/packages/core/src/cli/binary.ts +5 -3
  43. package/packages/core/src/cli/build-control.ts +328 -66
  44. package/packages/core/src/cli/context.ts +268 -15
  45. package/packages/core/src/cli/dashboard/detail.ts +26 -2
  46. package/packages/core/src/cli/dashboard/facts.ts +40 -3
  47. package/packages/core/src/cli/dashboard/integration-detail.ts +7 -2
  48. package/packages/core/src/cli/dashboard/landing-display.ts +15 -2
  49. package/packages/core/src/cli/dashboard/model.ts +102 -27
  50. package/packages/core/src/cli/dashboard/objective-row.ts +189 -0
  51. package/packages/core/src/cli/dashboard/render.ts +47 -1
  52. package/packages/core/src/cli/dashboard/reopen-display.ts +39 -0
  53. package/packages/core/src/cli/dashboard/tree.ts +12 -1
  54. package/packages/core/src/cli/dispatch-frontend.ts +9 -1
  55. package/packages/core/src/cli/dispatch-launch-stop.ts +55 -0
  56. package/packages/core/src/cli/dispatch-launcher.ts +26 -44
  57. package/packages/core/src/cli/dispatch-repository-feed.ts +1 -1
  58. package/packages/core/src/cli/dispatch.ts +16 -4
  59. package/packages/core/src/cli/env.ts +42 -0
  60. package/packages/core/src/cli/help.ts +208 -11
  61. package/packages/core/src/cli/init-agent.ts +4 -1
  62. package/packages/core/src/cli/init-readiness-remote.ts +3 -2
  63. package/packages/core/src/cli/init-validation.ts +2 -2
  64. package/packages/core/src/cli/init.ts +3 -2
  65. package/packages/core/src/cli/judge-entry.ts +82 -0
  66. package/packages/core/src/cli/judge.ts +233 -0
  67. package/packages/core/src/cli/landings.ts +3 -2
  68. package/packages/core/src/cli/main.ts +412 -143
  69. package/packages/core/src/cli/measurement-text.ts +19 -0
  70. package/packages/core/src/cli/objective.ts +154 -0
  71. package/packages/core/src/cli/publication-settlement.ts +106 -22
  72. package/packages/core/src/cli/repo-lease.ts +1 -0
  73. package/packages/core/src/cli/repository-status.ts +113 -18
  74. package/packages/core/src/cli/status.ts +193 -15
  75. package/packages/core/src/cli/store-opening.ts +4 -0
  76. package/packages/core/src/cli/terminals.ts +205 -8
  77. package/packages/core/src/cli/ticket-start.ts +53 -0
  78. package/packages/core/src/cli/ticket.ts +68 -2
  79. package/packages/core/src/cli/upgrade-agent.ts +12 -8
  80. package/packages/core/src/cli/wait.ts +8 -2
  81. package/packages/core/src/cli/watch.ts +341 -91
  82. package/packages/core/src/config/create-labels.ts +23 -0
  83. package/packages/core/src/config/live.ts +2 -0
  84. package/packages/core/src/config/pipeline-source.ts +1 -3
  85. package/packages/core/src/config/roles.ts +182 -73
  86. package/packages/core/src/config/schema.ts +112 -9
  87. package/packages/core/src/events/catalog.ts +39 -3
  88. package/packages/core/src/events/compatibility.ts +7 -1
  89. package/packages/core/src/events/payloads.ts +588 -1
  90. package/packages/core/src/events/policy.ts +53 -0
  91. package/packages/core/src/events/repository.ts +107 -24
  92. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +1481 -199
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/0ab2a90d0305dc9d.json.gz +0 -0
  94. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/10a4657408d4e121.json.gz +0 -0
  95. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1152a2e97ee81728.json.gz +0 -0
  96. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/13ca84752c5f8b54.json.gz +0 -0
  97. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1411d1cdbdd9911e.json.gz +0 -0
  98. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1444fe1fa7fc802c.json.gz +0 -0
  99. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1491ac0600349391.json.gz +0 -0
  100. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1921f86f752428c9.json.gz +0 -0
  101. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1972c1d66008ef6b.json.gz +0 -0
  102. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/19e8e43e7f3f1a06.json.gz +0 -0
  103. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/20a85c143c3e8164.json.gz +0 -0
  104. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/21ce2c0bf58318e1.json.gz +0 -0
  105. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/293dcb3a94fb3470.json.gz +0 -0
  106. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2ab7436356267118.json.gz +0 -0
  107. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2d084641735caaff.json.gz +0 -0
  108. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3237bcecf68e5db9.json.gz +0 -0
  109. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/33d0cc593610e56f.json.gz +0 -0
  110. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3451ed2136dcc356.json.gz +0 -0
  111. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/358ec8693f2237e6.json.gz +0 -0
  112. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/35cf9ccc4478b2d2.json.gz +0 -0
  113. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3649e7bd1203f154.json.gz +0 -0
  114. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/378da6dece82202a.json.gz +0 -0
  115. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/38c75099d9191471.json.gz +0 -0
  116. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/398952f1f01db1a3.json.gz +0 -0
  117. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3b64d352d56c9121.json.gz +0 -0
  118. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3dc486226c05372d.json.gz +0 -0
  119. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/431c9bb2ee8838e0.json.gz +0 -0
  120. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4400dffca929e2f0.json.gz +0 -0
  121. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/49064fc079964a5c.json.gz +0 -0
  122. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4edded75f17742f4.json.gz +0 -0
  123. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4f00c0f2c8afd159.json.gz +0 -0
  124. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516a5a7aadf97587.json.gz +0 -0
  125. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516dc6ea85d67cd7.json.gz +0 -0
  126. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/584e2ba74608e051.json.gz +0 -0
  127. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/59ffaa6974094c72.json.gz +0 -0
  128. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5bb43afb121674c6.json.gz +0 -0
  129. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5f0ca42af862c4ee.json.gz +0 -0
  130. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6118031132db9bfc.json.gz +0 -0
  131. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63107a8d58776b63.json.gz +0 -0
  132. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63546b08d4d6fa11.json.gz +0 -0
  133. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/643d70429ce03dad.json.gz +0 -0
  134. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/677ea92572c29082.json.gz +0 -0
  135. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6ae5bf60504d6467.json.gz +0 -0
  136. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6efdc8defc75fccb.json.gz +0 -0
  137. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/71c53d33f09d8204.json.gz +0 -0
  138. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7267ca2757cffba7.json.gz +0 -0
  139. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/76b7d4244082b3f9.json.gz +0 -0
  140. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7749f918c6f10968.json.gz +0 -0
  141. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7833e42d16301424.json.gz +0 -0
  142. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7d4edad0614adaf1.json.gz +0 -0
  143. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/837365898d04f45a.json.gz +0 -0
  144. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/85f9f0c921b8b5bb.json.gz +0 -0
  145. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8879f57a24733897.json.gz +0 -0
  146. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/88cb9e71bdec972d.json.gz +0 -0
  147. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8a0cd6dd06cc155e.json.gz +0 -0
  148. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8aa9ca8609dc051d.json.gz +0 -0
  149. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8c8640255bd61658.json.gz +0 -0
  150. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8cc15eb1807c0157.json.gz +0 -0
  151. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8ced97c44bc0af3a.json.gz +0 -0
  152. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8d4144004720b9f8.json.gz +0 -0
  153. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8db633ead1807f8b.json.gz +0 -0
  154. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8e42cdbd0994ab0c.json.gz +0 -0
  155. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9011d0f6ff955ef9.json.gz +0 -0
  156. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/916ebc5433801c41.json.gz +0 -0
  157. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9539b995af5c54a9.json.gz +0 -0
  158. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/95f391bfd7b7dbd7.json.gz +0 -0
  159. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9613e8fa568a9281.json.gz +0 -0
  160. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9a68f8753bd9038d.json.gz +0 -0
  161. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9b25e58227080094.json.gz +0 -0
  162. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9ee3919fbd4f9458.json.gz +0 -0
  163. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a04a34cc2717147b.json.gz +0 -0
  164. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a0b32c12e4e6edb6.json.gz +0 -0
  165. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a55218252707bdd3.json.gz +0 -0
  166. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a732fd08b31522a6.json.gz +0 -0
  167. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a9d206a01f9039e5.json.gz +0 -0
  168. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/abf7fe3c92c82f2d.json.gz +0 -0
  169. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ac928b04842c00db.json.gz +0 -0
  170. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/af953392d81911da.json.gz +0 -0
  171. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0d877c44810ecb0.json.gz +0 -0
  172. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0f7c6ebb2db57fc.json.gz +0 -0
  173. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b905c22ec17eed31.json.gz +0 -0
  174. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/bce0c54e865f4b79.json.gz +0 -0
  175. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c68b7ee2e2610f30.json.gz +0 -0
  176. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c7f7e0378aeea237.json.gz +0 -0
  177. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c98cb1659eb142b6.json.gz +0 -0
  178. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ca830adf06ed55a1.json.gz +0 -0
  179. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cb3a219f33e437ca.json.gz +0 -0
  180. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cf1e0c0d82567e0c.json.gz +0 -0
  181. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d008d86d9ff77b30.json.gz +0 -0
  182. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d1432a819d8e48c5.json.gz +0 -0
  183. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d185ed6aa9192aff.json.gz +0 -0
  184. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d873fad29d6c7e55.json.gz +0 -0
  185. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/db84b12316e2da4a.json.gz +0 -0
  186. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ddf6dc967d898767.json.gz +0 -0
  187. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/dfc64de6e7bfc0a0.json.gz +0 -0
  188. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e2f18fa32fe1f6d0.json.gz +0 -0
  189. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e37393fed29e84c5.json.gz +0 -0
  190. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e6a8585e2a054ff6.json.gz +0 -0
  191. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e7e9e327baca6903.json.gz +0 -0
  192. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e86447af0571672c.json.gz +0 -0
  193. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ea819202d22122e5.json.gz +0 -0
  194. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb4535585f2e84f6.json.gz +0 -0
  195. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb7ddd5319d09e27.json.gz +0 -0
  196. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eca4959b2b87ae15.json.gz +0 -0
  197. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ee10d7959ec4843c.json.gz +0 -0
  198. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ef1b68347966ab26.json.gz +0 -0
  199. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f3e55425cc41f230.json.gz +0 -0
  200. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f40042c1cdb9fd43.json.gz +0 -0
  201. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f48466215c790a3f.json.gz +0 -0
  202. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f5b9ace9b59351e7.json.gz +0 -0
  203. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fa8f1475a55be935.json.gz +0 -0
  204. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fb21116a15d0b1f1.json.gz +0 -0
  205. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fe95444fbeabe592.json.gz +0 -0
  206. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/09bf0a1611d07363.json +984 -0
  207. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/10eac4988d66e161.json +1067 -0
  208. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/1a436b5fb45aee3e.json +1116 -0
  209. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/249db6f7a41f90e2.json +161 -0
  210. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/25dcb2fb6eaa83f4.json +858 -0
  211. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/2e1bdc763924616f.json +4932 -0
  212. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/30e9dabce3c4263d.json +399 -0
  213. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/4898ef339c68fa36.json +83 -0
  214. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/51816c0ffa62af6e.json +417 -0
  215. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/561bf45320062a44.json +83 -0
  216. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5672d0233085d050.json +84 -0
  217. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5e39f42cbdbf35ef.json +163 -0
  218. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/7771a7a2250f9964.json +868 -0
  219. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/881c491321bec99a.json +1074 -0
  220. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/965f25c3af1d2cdc.json +160 -0
  221. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9b76d89da575ca90.json +20 -0
  222. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9eb485320a72a9ff.json +233 -0
  223. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a60448c01016135e.json +18 -0
  224. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6584fb61b6679bd.json +97 -0
  225. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c88365c25b3186d3.json +543 -0
  226. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e8f0481b23f90056.json +711 -0
  227. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ee55782ed40ebbac.json +110 -0
  228. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc5082fac8167f3d.json +98 -0
  229. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fd55c329cfe921cc.json +1069 -0
  230. package/packages/core/src/kernel/attempt-creation-key.ts +20 -0
  231. package/packages/core/src/kernel/attempt-settlement.ts +125 -0
  232. package/packages/core/src/kernel/auto-merge-default.ts +1 -3
  233. package/packages/core/src/kernel/auto-merge.ts +1 -3
  234. package/packages/core/src/kernel/dispatch-capacity.ts +312 -38
  235. package/packages/core/src/kernel/dispatch-placement.ts +1 -1
  236. package/packages/core/src/kernel/dispatch-settings.ts +1 -4
  237. package/packages/core/src/kernel/dispatch-status.ts +3 -5
  238. package/packages/core/src/kernel/dispatch-upgrade.ts +1 -1
  239. package/packages/core/src/kernel/engine.ts +109 -13
  240. package/packages/core/src/kernel/forge-checks.ts +140 -0
  241. package/packages/core/src/kernel/forge-health.ts +2 -2
  242. package/packages/core/src/kernel/generated-files.ts +43 -0
  243. package/packages/core/src/kernel/generated-regeneration.ts +254 -0
  244. package/packages/core/src/kernel/generators/build-log.ts +30 -2
  245. package/packages/core/src/kernel/generators/optimization-log.ts +578 -0
  246. package/packages/core/src/kernel/generators/panel-log.ts +133 -0
  247. package/packages/core/src/kernel/guarded-forge.ts +76 -11
  248. package/packages/core/src/kernel/harvest.ts +1 -4
  249. package/packages/core/src/kernel/head-paths.ts +4 -1
  250. package/packages/core/src/kernel/history-retention.ts +337 -0
  251. package/packages/core/src/kernel/incremental-fixtures.ts +6 -0
  252. package/packages/core/src/kernel/incremental.ts +14 -4
  253. package/packages/core/src/kernel/integration-landing.ts +64 -13
  254. package/packages/core/src/kernel/integration-stack.ts +123 -20
  255. package/packages/core/src/kernel/integration-state.ts +39 -2
  256. package/packages/core/src/kernel/janitor-failure.ts +2 -0
  257. package/packages/core/src/kernel/kernel-git.ts +1 -1
  258. package/packages/core/src/kernel/landing-measurement.ts +275 -0
  259. package/packages/core/src/kernel/landing-readiness.ts +2 -0
  260. package/packages/core/src/kernel/landing-state.ts +20 -1
  261. package/packages/core/src/kernel/leaf-restack-state.ts +17 -1
  262. package/packages/core/src/kernel/log-index-value.ts +2 -0
  263. package/packages/core/src/kernel/log-index.ts +81 -3
  264. package/packages/core/src/kernel/measurement.ts +406 -0
  265. package/packages/core/src/kernel/mixed-version.ts +6 -3
  266. package/packages/core/src/kernel/node-landing.ts +92 -18
  267. package/packages/core/src/kernel/node-restack-state.ts +27 -1
  268. package/packages/core/src/kernel/node-restack-transaction.ts +80 -23
  269. package/packages/core/src/kernel/node-verification-context.ts +14 -4
  270. package/packages/core/src/kernel/open-pr-backpressure-state.ts +24 -0
  271. package/packages/core/src/kernel/open-pr-backpressure.ts +133 -0
  272. package/packages/core/src/kernel/optimization-admission.ts +249 -0
  273. package/packages/core/src/kernel/optimization.ts +774 -0
  274. package/packages/core/src/kernel/panel.ts +225 -0
  275. package/packages/core/src/kernel/phases.ts +42 -6
  276. package/packages/core/src/kernel/pr-attachments.ts +4 -16
  277. package/packages/core/src/kernel/pr-summary.ts +2 -2
  278. package/packages/core/src/kernel/read-deferrals.ts +2 -2
  279. package/packages/core/src/kernel/read-facts.ts +69 -31
  280. package/packages/core/src/kernel/reconcile-restack.ts +352 -103
  281. package/packages/core/src/kernel/reducer-identity.ts +659 -0
  282. package/packages/core/src/kernel/reducer-registry.ts +37 -3
  283. package/packages/core/src/kernel/reducer-revisions.ts +50 -0
  284. package/packages/core/src/kernel/reducer.ts +208 -9
  285. package/packages/core/src/kernel/reopen-state.ts +48 -0
  286. package/packages/core/src/kernel/reopen.ts +143 -0
  287. package/packages/core/src/kernel/replay-retention.ts +208 -39
  288. package/packages/core/src/kernel/repository-attention.ts +1 -1
  289. package/packages/core/src/kernel/service-facts.ts +19 -7
  290. package/packages/core/src/kernel/terminal-guard.ts +13 -5
  291. package/packages/core/src/kernel/ticket-handbacks.ts +1 -1
  292. package/packages/core/src/kernel/ticket-migrations.ts +1 -1
  293. package/packages/core/src/kernel/ticket-preparation.ts +1 -1
  294. package/packages/core/src/kernel/ticket-source-health.ts +1 -1
  295. package/packages/core/src/kernel/ticket-starts.ts +118 -0
  296. package/packages/core/src/kernel/ticket-wait.ts +37 -2
  297. package/packages/core/src/kernel/verify-diff-base.ts +62 -0
  298. package/packages/core/src/kernel/verify-stage-state.ts +1 -0
  299. package/packages/core/src/kernel/verify-stages.ts +41 -1
  300. package/packages/core/src/objective.ts +532 -0
  301. package/packages/core/src/ontology.ts +49 -6
  302. package/packages/core/src/operator/annotations.ts +35 -4
  303. package/packages/core/src/operator/control.ts +2 -1
  304. package/packages/core/src/operator/index.ts +12 -0
  305. package/packages/core/src/operator/optimization.ts +307 -0
  306. package/packages/core/src/operator/protocol.ts +30 -1
  307. package/packages/core/src/operator/query.ts +15 -1
  308. package/packages/core/src/operator/registry.ts +219 -13
  309. package/packages/core/src/operator/requests.ts +25 -2
  310. package/packages/core/src/operator/ticket-start.ts +152 -0
  311. package/packages/core/src/operator/tickets.ts +3 -2
  312. package/packages/core/src/plugin-sdk/index.ts +2 -0
  313. package/packages/core/src/plugins/registry.ts +1 -0
  314. package/packages/core/src/ports/forge/contract.ts +9 -0
  315. package/packages/core/src/ports/forge/fake.ts +23 -2
  316. package/packages/core/src/ports/forge/git-rewrite.ts +6 -4
  317. package/packages/core/src/ports/forge/github-readiness.ts +1 -1
  318. package/packages/core/src/ports/forge/github-transport.ts +156 -1
  319. package/packages/core/src/ports/forge/github.ts +306 -100
  320. package/packages/core/src/ports/forge/readiness.ts +15 -3
  321. package/packages/core/src/ports/forge-failure.ts +22 -0
  322. package/packages/core/src/ports/forge-request-context.ts +23 -1
  323. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  324. package/packages/core/src/ports/runner/antigravity.ts +1071 -0
  325. package/packages/core/src/ports/runner/claude.ts +6 -1
  326. package/packages/core/src/ports/runner/codex.ts +11 -2
  327. package/packages/core/src/ports/runner/contract.ts +25 -1
  328. package/packages/core/src/ports/runner/fake.ts +2 -2
  329. package/packages/core/src/ports/runner/native-cli-fixture.ts +40 -5
  330. package/packages/core/src/ports/runner/native-process-fixture.ts +4 -1
  331. package/packages/core/src/ports/runner/pi.ts +23 -7
  332. package/packages/core/src/ports/runner/production.ts +19 -2
  333. package/packages/core/src/ports/runner/session-env.ts +65 -5
  334. package/packages/core/src/ports/runner/start-prompt.ts +6 -4
  335. package/packages/core/src/ports/tickets/contract.ts +4 -2
  336. package/packages/core/src/ports/tickets/github.ts +20 -5
  337. package/packages/core/src/ports/tickets/hosted-index.ts +6 -1
  338. package/packages/core/src/ports/tickets/labels.ts +21 -0
  339. package/packages/core/src/ports/tickets/linear.ts +33 -0
  340. package/packages/core/src/ports/tickets/migration.ts +2 -0
  341. package/packages/core/src/ports/tickets/priority.ts +11 -0
  342. package/packages/core/src/ports/tickets/remote-protocol.ts +71 -6
  343. package/packages/core/src/ports/tickets/remote.ts +138 -16
  344. package/packages/core/src/ports/tickets/tree.ts +17 -4
  345. package/packages/core/src/ports/types.ts +98 -4
  346. package/packages/core/src/ports/workspace/builtin-capabilities.ts +7 -4
  347. package/packages/core/src/ports/workspace/commit-preservation.ts +182 -64
  348. package/packages/core/src/ports/workspace/create.ts +3 -0
  349. package/packages/core/src/ports/workspace/git-worktree.ts +13 -1
  350. package/packages/core/src/ports/workspace/vercel-sandbox.ts +242 -61
  351. package/packages/core/src/processes/build-execution-state.ts +1 -3
  352. package/packages/core/src/processes/build-runner.ts +1435 -132
  353. package/packages/core/src/processes/dispatch-failure-budget.ts +1 -1
  354. package/packages/core/src/processes/dispatcher-selectors.ts +15 -13
  355. package/packages/core/src/processes/dispatcher.ts +2781 -242
  356. package/packages/core/src/processes/execution-no-progress.ts +36 -1
  357. package/packages/core/src/processes/execution-settlement.ts +2 -6
  358. package/packages/core/src/processes/harvest-execution-state.ts +2 -6
  359. package/packages/core/src/processes/harvest-runner.ts +7 -2
  360. package/packages/core/src/processes/infrastructure-failure-budget.ts +1 -3
  361. package/packages/core/src/processes/judge-launcher.ts +38 -0
  362. package/packages/core/src/processes/measurement-runner.ts +235 -0
  363. package/packages/core/src/processes/optimization-merges.ts +101 -0
  364. package/packages/core/src/processes/optimization-stop.ts +179 -0
  365. package/packages/core/src/processes/panel-runner.ts +756 -0
  366. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  367. package/packages/core/src/processes/publication-state.ts +1 -4
  368. package/packages/core/src/processes/repo-view.ts +77 -5
  369. package/packages/core/src/processes/sandbox-state.ts +1 -4
  370. package/packages/core/src/processes/tick-state.ts +1 -3
  371. package/packages/core/src/processes/workspace-preservation.ts +67 -9
  372. package/packages/core/src/scenarios/harness.ts +19 -8
  373. package/packages/core/src/store/contract.ts +44 -0
  374. package/packages/core/src/store/digest.ts +89 -7
  375. package/packages/core/src/store/judge-authority.ts +161 -0
  376. package/packages/core/src/store/phase-session.ts +226 -4
  377. package/packages/core/src/store/reduced-reads.ts +10 -0
  378. package/packages/core/src/store/reducer-value-shapes.json +17060 -12099
  379. package/packages/core/src/store/remote/client.ts +12 -2
  380. package/packages/core/src/store/remote/credentials.ts +31 -1
  381. package/packages/core/src/store/remote/index.ts +8 -0
  382. package/packages/core/src/store/remote/protocol.ts +38 -0
  383. package/packages/core/src/store/remote/released-clients.json +11 -0
  384. package/packages/core/src/store/remote/released-reducer-values/1.10.0.json +34439 -0
  385. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  386. package/packages/core/src/store/remote/token.ts +13 -4
  387. package/packages/core/src/store/repo-state-events.ts +6 -8
  388. package/packages/core/src/store/session-reducer.ts +1 -4
  389. package/packages/core/src/store/ticket-assets.ts +1 -3
  390. package/packages/core/src/store/types.ts +9 -0
  391. package/packages/core/src/testing/dispatch-read-budget.ts +70 -0
  392. package/packages/core/src/testing/git-config-isolation.ts +25 -0
  393. package/packages/core/src/testing/index.ts +13 -0
  394. package/packages/core/src/testing/reduced-read-budget.ts +3455 -34
  395. package/skills/code-review/SKILL.md +16 -0
  396. package/skills/finalize/SKILL.md +10 -4
  397. package/skills/guide/SKILL.md +383 -77
  398. package/skills/guide/references/integration-tree.md +102 -11
  399. package/skills/guide/references/merge-policy.md +30 -14
  400. package/skills/guide/references/migration-1.0.md +2 -1
  401. package/skills/guide/references/operator-api.md +117 -14
  402. package/skills/guide/references/optimization-nodes.md +1042 -0
  403. package/skills/guide/references/plugin-authoring.md +46 -12
  404. package/skills/guide/references/remote-store-protocol.md +46 -7
  405. package/skills/guide/references/remote-ticket-protocol.md +50 -2
  406. package/skills/guide/references/restacking.md +99 -11
  407. package/skills/guide/references/setup.md +13 -2
  408. package/skills/guide/references/spec-standard.md +2 -1
  409. package/skills/guide/references/ticket-dependencies.md +5 -0
  410. package/skills/guide/references/ticket-migration.md +4 -2
  411. package/skills/implement/SKILL.md +51 -1
  412. package/skills/judge/SKILL.md +43 -0
  413. package/skills/operate/SKILL.md +243 -28
  414. package/skills/plan/SKILL.md +18 -0
  415. package/skills/plan-review/SKILL.md +15 -1
  416. package/skills/propose/SKILL.md +121 -0
  417. package/skills/reconcile/SKILL.md +21 -2
  418. package/skills/spec/SKILL.md +30 -4
  419. package/skills/tickets/SKILL.md +44 -5
  420. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,10 @@
1
1
  import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import {
3
+ recordRetention,
4
+ restoreRetainedHead,
5
+ retainCommit,
6
+ type RetentionOutcome,
7
+ } from '../kernel/history-retention'
2
8
  import {
3
9
  computeHeadPaths,
4
10
  headPathsFor,
@@ -62,7 +68,13 @@ import {
62
68
  MixedVersionDeferral,
63
69
  } from '../kernel/mixed-version'
64
70
  import { guardForge, ForgeCooldown } from '../kernel/guarded-forge'
65
- import { leafLandingDeclineReason } from '../kernel/landing-readiness'
71
+ import {
72
+ CI_FAILURE_PREVIEW,
73
+ ciChecksObservable,
74
+ ciFailureKey,
75
+ failingSetDigest,
76
+ } from '../kernel/forge-checks'
77
+ import { actionableCommands, leafLandingDeclineReason } from '../kernel/landing-readiness'
66
78
  import {
67
79
  escalationsBeyondJanitor,
68
80
  janitorBlocked,
@@ -74,6 +86,13 @@ import {
74
86
  type JanitorOperation,
75
87
  } from '../kernel/janitor-failure'
76
88
  import { KernelGitUnavailable, kernelGitUnavailableDetail } from '../kernel/kernel-git'
89
+ import {
90
+ backpressureExplanation,
91
+ backpressureTransition,
92
+ openPrBackpressure,
93
+ openPrBackpressurePolicy,
94
+ openPrCount,
95
+ } from '../kernel/open-pr-backpressure'
77
96
  import { isForgeFailure, isForgeRejection } from '../ports/forge-failure'
78
97
  import {
79
98
  ForgeRequestDeferred,
@@ -81,15 +100,48 @@ import {
81
100
  forgeRequestContext,
82
101
  } from '../ports/forge-request-context'
83
102
  import {
103
+ forgeRateLimitObservationSchema,
104
+ forgeRateLimitSnapshotSchema,
105
+ type ForgeRateLimitSnapshot,
106
+ } from '../ports/forge-telemetry'
107
+ import {
108
+ buildPriority,
84
109
  dispatchCapacity,
85
110
  epilogueLeaf,
86
111
  intakeCapacity,
87
112
  nodeCapacity,
113
+ occupiesCapacity,
114
+ reservedAhead,
88
115
  settlementDue,
89
116
  settlementKey,
90
117
  slotRequest,
118
+ startCapacity,
119
+ startClaimDemand,
120
+ strandedNodeWorkspace,
121
+ urgentClaimDemand,
91
122
  type CapacityBuild,
123
+ type DispatchCapacity,
92
124
  } from '../kernel/dispatch-capacity'
125
+ import { attemptCreationKey } from '../kernel/attempt-creation-key'
126
+ import {
127
+ exhaustedStopDue,
128
+ optimizationElapsedHours,
129
+ proposalWithdrawalDue,
130
+ proposeAdmissible,
131
+ proposerAdmissible,
132
+ proposerBlocker,
133
+ proposerRoom,
134
+ proposeRunDue,
135
+ proposeStarted,
136
+ signalDue,
137
+ } from '../kernel/optimization'
138
+ import { proposalsDocumentSchema } from '../ontology'
139
+ import {
140
+ decideSampledMeasurement,
141
+ measurementThreshold,
142
+ nodeMeasurementDue,
143
+ sampledMeasurement,
144
+ } from '../kernel/measurement'
93
145
  import {
94
146
  openTicketWait,
95
147
  pendingWaitRequest,
@@ -100,6 +152,8 @@ import {
100
152
  waitUnresolvableQuestion,
101
153
  } from '../kernel/ticket-wait'
102
154
  import { changeBlockers } from '../ports/tickets/operations'
155
+ import { creationAssignees } from '../ports/tickets/assignees'
156
+ import { creationLabels } from '../ports/tickets/labels'
103
157
  import { evaluateLandingPolicy } from '../kernel/landing-policy'
104
158
  import { landingPolicyIdentity } from '../kernel/landing-policy-identity'
105
159
  import {
@@ -124,6 +178,7 @@ import {
124
178
  integrationVerified,
125
179
  integrationHeadVerified,
126
180
  integrationAdmissible,
181
+ nodeLanded,
127
182
  } from '../kernel/integration-state'
128
183
  import {
129
184
  normalizeIdentities,
@@ -144,18 +199,45 @@ import {
144
199
  type PresenceWitness,
145
200
  } from '../kernel/change-presence'
146
201
  import { landIntoNode, settleClosedNode, preflightNodeLanding } from '../kernel/node-landing'
202
+ import {
203
+ landingMeasurementGate,
204
+ harnessEscalationId,
205
+ regressionEscalationId,
206
+ selectTurnHolder,
207
+ mergedAttemptMeasurement,
208
+ settlementMeasurement,
209
+ type AttemptStatus,
210
+ type LandingGateVerdict,
211
+ type TurnCandidate,
212
+ } from '../kernel/landing-measurement'
213
+ import {
214
+ optimizationAttempt,
215
+ optimizationRejection,
216
+ type InFlightAttempt,
217
+ type PendingRejection,
218
+ } from '../kernel/optimization'
219
+ import {
220
+ attemptBranchPublished,
221
+ markUnmeasuredMerge,
222
+ settleAttempt,
223
+ } from '../kernel/attempt-settlement'
224
+ import { candidateHead } from '../kernel/head-paths-state'
225
+ import { compilePathSelectors } from '../config/path-selectors'
226
+ import { moveTicketToRole } from '../ports/tickets/operations'
147
227
  import { mkdtemp, rm } from 'node:fs/promises'
148
228
  import { tmpdir } from 'node:os'
149
229
  import { join } from 'node:path'
150
230
  import { runNodeTransaction } from '../kernel/node-restack-transaction'
151
231
  import { hasBuildTrailer } from '../kernel/build-identity'
152
- import { digestNodeTargets } from '../store/digest'
232
+ import { BuildDigestCapabilityError, digestNodeTargets, digestOptimization } from '../store/digest'
153
233
  import { readBuildDigests, readForgeHealth } from '../store/reduced-reads'
234
+ import { enforceOptimizationStop } from './optimization-stop'
235
+ import { reconcileMergedAttempts } from './optimization-merges'
154
236
  import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
155
237
  import { ensureExecutionProgress } from './execution-no-progress'
156
238
  import { ticketIdentity } from '../ports/tickets/identity'
157
239
  import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
158
- import { urgentFirst } from '../ports/tickets/priority'
240
+ import { ticketPriority, urgentFirst } from '../ports/tickets/priority'
159
241
  import { ensureDispatchBudget } from './dispatch-failure-budget'
160
242
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
161
243
  /**
@@ -202,7 +284,12 @@ import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
202
284
  import { isRemoteWorkspace } from '../events/workspace-remote'
203
285
  import type { AbEvent, EventWrite } from '../events/catalog'
204
286
  import type { AbortDestination, EventPayload, PinnedAsset } from '../events/payloads'
205
- import type { RepositoryEventPayload } from '../events/repository'
287
+ import type {
288
+ RepositoryEventPayload,
289
+ TicketStartOutcome,
290
+ TicketStartPriority,
291
+ } from '../events/repository'
292
+ import { ticketStartKey, type PendingTicketStart, type TicketStarts } from '../kernel/ticket-starts'
206
293
  import { handbackIdentity } from '../kernel/ticket-handbacks'
207
294
  import type { IdSource } from '../ids'
208
295
  import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
@@ -227,8 +314,11 @@ import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution
227
314
  import type {
228
315
  DependencyState,
229
316
  Forge,
317
+ HeadChecks,
230
318
  IssueLink,
319
+ PrState,
231
320
  Ticket,
321
+ TicketPriority,
232
322
  TicketSource,
233
323
  WorkspaceProvider,
234
324
  WorkspaceProvisionResult,
@@ -257,6 +347,13 @@ import { creationBuildSlug } from '../kernel/build-creation'
257
347
  import { preparePinnedAssets } from '../store/ticket-assets'
258
348
  import { resolveRepoOrigin } from '../cli/repo-state'
259
349
  import { specConformance } from '../spec-standard'
350
+ import {
351
+ objectiveBlocks,
352
+ objectiveRefusals,
353
+ objectiveRulerChanged,
354
+ parseObjective,
355
+ type Objective,
356
+ } from '../objective'
260
357
  export { specConformance, type SpecConformance } from '../spec-standard'
261
358
  import { recordInfrastructureFailure as appendInfrastructureFailure } from './infrastructure-failure-budget'
262
359
  import { settleOpenExecution } from './execution-settlement'
@@ -534,6 +631,10 @@ export interface TickReport {
534
631
  * background work this tick. The tick returns without awaiting it; the
535
632
  * continuation completes the remaining boundaries and the launch. */
536
633
  provisioning: number
634
+ /** Builds whose provisioning start was deferred because the bounded
635
+ * invocation's remaining budget was shorter than the provider's
636
+ * provisioning estimate. Nothing is written; a later invocation starts it. */
637
+ provisioningDeferred: number
537
638
  /** Dispatch (§12): builds created and launched. With durable supervision
538
639
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
539
640
  * awaited launches: a dispatch whose remote provisioning continues in the
@@ -597,6 +698,7 @@ export function emptyTickReport(): TickReport {
597
698
  swept: 0,
598
699
  settled: 0,
599
700
  provisioning: 0,
701
+ provisioningDeferred: 0,
600
702
  dispatched: 0,
601
703
  authored: 0,
602
704
  bounced: 0,
@@ -619,6 +721,44 @@ export function emptyTickReport(): TickReport {
619
721
  }
620
722
  }
621
723
 
724
+ /** A settlement `dispatch()` reached for one targeted ticket. */
725
+ type TargetedOutcome = {
726
+ outcome: TicketStartOutcome
727
+ slug?: string
728
+ detail?: string
729
+ }
730
+
731
+ /** One targeted admission pass for operator start requests (AUT-1293). */
732
+ interface TargetedDispatch {
733
+ tickets: Ticket[]
734
+ /** Active ticket identities, matched without source reads. */
735
+ activeIds: Set<string>
736
+ /** The request each ticket answers, keyed by ticket id. */
737
+ requests: Map<string, PendingTicketStart>
738
+ /** Keyed by ticket id. A ticket without an entry stays pending. */
739
+ outcomes: Map<string, TargetedOutcome>
740
+ /** The capacity inputs the stage measured from this tick's served facts. */
741
+ measured: CapacityBuild[]
742
+ /** Slots left for each start tier (`startCapacity`). A claim spends only
743
+ * its own tier's: lower tiers already reserved it as a pending request. */
744
+ budgets: Record<TicketStartPriority, number>
745
+ }
746
+
747
+ /** An active build's ticket ref, normalized through recorded migrations. */
748
+ interface ActiveTicketRef {
749
+ slug: string
750
+ createdAt: string
751
+ ref: TicketRef
752
+ }
753
+
754
+ /** Start requests one pass evaluates, in tier order, oldest first. */
755
+ const START_REQUESTS_PER_TICK = 8
756
+ const START_TIER_ORDER: readonly TicketStartPriority[] = ['manual', 'urgent', 'normal']
757
+ /** Hosted active-build identities one tick resolves; each build once in its life. */
758
+ const IDENTITY_RESOLUTIONS_PER_TICK = 16
759
+ /** Released identity slugs one projection append carries. */
760
+ const IDENTITY_RELEASES_PER_APPEND = 256
761
+
622
762
  // ── Dispatcher ───────────────────────────────────────────────────────────────
623
763
 
624
764
  const DEFAULT_SLUG_NAMING_TIMEOUT_MS = 10_000
@@ -632,6 +772,9 @@ const DISPATCH_COMMENT = /^build ([a-z0-9][a-z0-9-]*) dispatched$/
632
772
  * lease. A dead provisioner is therefore adopted within one lease TTL. */
633
773
  const PROVISION_HEARTBEAT_MS = 15_000
634
774
  const DEFAULT_PROVISION_STALE_MS = 20 * 60 * 1000
775
+ /** Rate-limit readings carried in tick telemetry: resources and age bounds. */
776
+ const FORGE_RATE_LIMIT_RESOURCES = 8
777
+ const FORGE_RATE_LIMIT_RETENTION_MS = 24 * 60 * 60 * 1000
635
778
 
636
779
  /** Outcome of one attempt to complete an interrupted dispatch. `deferred`
637
780
  * means durable progress was made (background provisioning kicked or already
@@ -833,6 +976,19 @@ function baseBranchOf(events: CurrentBuildFacts, config: Config): string {
833
976
  return events.baseBranch ?? config.baseBranch
834
977
  }
835
978
 
979
+ /** An open optimization node whose latest spec revision has not had its
980
+ * objective accepted yet. Read from reduced state alone: zero added reads. */
981
+ export function objectiveAcceptancePending(state: BuildState): boolean {
982
+ return (
983
+ state.kind === 'node' &&
984
+ state.nodeOpened !== undefined &&
985
+ state.optimization !== undefined &&
986
+ state.status !== 'done' &&
987
+ state.status !== 'aborted' &&
988
+ (state.specRev ?? 0) > state.optimization.accepted.specRev
989
+ )
990
+ }
991
+
836
992
  function artifactRefOf(deposited: ArtifactMeta[]): ArtifactRef {
837
993
  const meta = deposited[0]
838
994
  if (!meta) throw new Error('spec deposit produced no artifact meta')
@@ -1111,11 +1267,36 @@ export class Dispatcher {
1111
1267
  /** Per tick, rebuilt from durable state: builds launched so far, which
1112
1268
  * occupy a slot before their runner claims a lease. */
1113
1269
  private tickLaunched: ReadonlySet<string> = new Set()
1114
- /** Per tick: finished leaves the admission gate turned away. Intake reserves their slots. */
1115
- private readonly slotWaiters = new Set<string>()
1270
+ /** Per tick: finished leaves the admission gate turned away or deferred,
1271
+ * with their priority. Intake reserves their slots. */
1272
+ private readonly slotWaiters = new Map<string, TicketPriority>()
1273
+ /** Per tick, in visit order: normal parked admissions that would have taken
1274
+ * a free slot before this tick's dispatch evaluated urgent claims (SPEC §12
1275
+ * "Slot admission order"). Nothing was written for them;
1276
+ * `admitDeferredParked` retries each through its generic path. */
1277
+ private readonly deferredAdmissions = new Map<string, 'leaf' | 'node' | 'proposer'>()
1278
+ /** Per tick: admission may defer normal parked work. Opened by `runTick`
1279
+ * when claims can run, closed once urgent claims were evaluated. */
1280
+ private admissionBoundary = false
1281
+ /** Per tick: this tick's admission scan completed its urgent decision. Only
1282
+ * `dispatch` sets it. */
1283
+ private urgentEvaluated = false
1284
+ /** Per tick: the deferral key this tick's admission scan was forced for. */
1285
+ private forcedDeferralKey: string | undefined
1286
+ /** In memory: the last deferral key whose forced scan completed and whose
1287
+ * retries ran. An unchanged key lists again only when a scan is due on its
1288
+ * own, so idle ticks repeating one blocked state cost no extra listing. */
1289
+ private lastForcedDeferralKey: string | undefined
1290
+ /** Per tick: `opts.acceptNewWork` and the repository pause sampled by `runTick`. */
1291
+ private tickAcceptsNewWork = false
1292
+ private tickPaused = false
1116
1293
  /** Per tick: parked leaves whose sweep decision was `wait awaiting-pr`. A
1117
1294
  * projected wait for one of these is one tick stale and reserves nothing. */
1118
1295
  private readonly parkedSettled = new Set<string>()
1296
+ /** Start requests whose ticket has a target and blockers and that have
1297
+ * had one full pass with no free slot: the pass that may settle them
1298
+ * `blocked`. Later full-capacity ticks wait for a slot without one. */
1299
+ private startBlockersChecked = new Set<number>()
1119
1300
 
1120
1301
  // Batched confirmed landing evidence is shared across nodes for this tick.
1121
1302
  // Only durable availability facts authorize the shortcut after restart. The
@@ -1124,6 +1305,14 @@ export class Dispatcher {
1124
1305
  private availabilityLandings?: ReturnType<typeof confirmedLandings>
1125
1306
  private availabilityLandingKey?: string
1126
1307
  private availabilityEntries?: ReturnType<Dispatcher['repoBuildDigests']>
1308
+ /** While the start pass's targeted dispatch runs: its deferral checks
1309
+ * serve this tick's retained facts (`servedBuildFacts`). */
1310
+ private startPass = false
1311
+ /** Per tick: the janitor's work listing, and the nonterminal children of
1312
+ * each node indexed from it on the first landing turn that needs them. The
1313
+ * landing gate reads its turn candidates here, never from a new listing. */
1314
+ private janitorEntries?: { record: BuildRecord; digest: BuildDigest }[]
1315
+ private nodeChildren?: Map<string, BuildRecord[]>
1127
1316
  /** Set once kernel Git proved unable to run this tick; later node work in
1128
1317
  * the same tick defers on it without spawning again. */
1129
1318
  private kernelGitUnavailable?: KernelGitUnavailable
@@ -1184,10 +1373,72 @@ export class Dispatcher {
1184
1373
  }
1185
1374
 
1186
1375
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
1376
+ /** Latest primary rate-limit reading per resource, carried across ticks so
1377
+ * a cooldown tick with no wire request still reports the last known quota. */
1378
+ private readonly forgeRateLimits = new Map<string, ForgeRateLimitSnapshot>()
1379
+
1380
+ /** Merges the view's retained durable tick sample (newest `observedAt` per
1381
+ * resource wins), then returns the bounded carried list. No store read: the
1382
+ * sample is the record the journal refresh already fetched. */
1383
+ private carriedRateLimits(): ForgeRateLimitSnapshot[] {
1384
+ const sample = this.store.lastTickSample()
1385
+ const durable =
1386
+ sample === undefined
1387
+ ? undefined
1388
+ : sample.outcome === 'completed'
1389
+ ? sample.counters.forgeRequests?.rateLimits
1390
+ : sample.forgeRequests?.rateLimits
1391
+ for (const entry of durable ?? []) {
1392
+ const parsed = forgeRateLimitSnapshotSchema.safeParse(entry)
1393
+ if (!parsed.success) continue
1394
+ const carried = this.forgeRateLimits.get(parsed.data.resource)
1395
+ if (
1396
+ carried === undefined ||
1397
+ Date.parse(parsed.data.observedAt) > Date.parse(carried.observedAt)
1398
+ )
1399
+ this.forgeRateLimits.set(parsed.data.resource, parsed.data)
1400
+ }
1401
+ const cutoff = this.deps.clock().getTime() - FORGE_RATE_LIMIT_RETENTION_MS
1402
+ for (const [resource, entry] of this.forgeRateLimits)
1403
+ if (Date.parse(entry.observedAt) < cutoff) this.forgeRateLimits.delete(resource)
1404
+ this.boundForgeRateLimits()
1405
+ return [...this.forgeRateLimits.values()].sort((a, b) => a.resource.localeCompare(b.resource))
1406
+ }
1407
+
1408
+ private boundForgeRateLimits(): void {
1409
+ while (this.forgeRateLimits.size > FORGE_RATE_LIMIT_RESOURCES) {
1410
+ let oldest: ForgeRateLimitSnapshot | undefined
1411
+ for (const entry of this.forgeRateLimits.values())
1412
+ if (oldest === undefined || Date.parse(entry.observedAt) < Date.parse(oldest.observedAt))
1413
+ oldest = entry
1414
+ if (oldest === undefined) return
1415
+ this.forgeRateLimits.delete(oldest.resource)
1416
+ }
1417
+ }
1418
+
1419
+ /** The forge request telemetry a tick that failed before or inside
1420
+ * {@link tick} persists: the last counts (or an honestly incomplete empty
1421
+ * count) carrying every known rate-limit reading. */
1422
+ failureForgeRequests(): import('../ports/forge-telemetry').ForgeRequestCounts | undefined {
1423
+ const rateLimits = this.carriedRateLimits()
1424
+ const base = this.lastForgeRequests
1425
+ if (base === undefined && rateLimits.length === 0) return undefined
1426
+ const { rateLimits: _previous, ...rest } = base ?? {
1427
+ total: 0,
1428
+ unattributed: 0,
1429
+ builds: [],
1430
+ complete: false,
1431
+ }
1432
+ return { ...rest, ...(rateLimits.length > 0 ? { rateLimits } : {}) }
1433
+ }
1434
+
1187
1435
  async tick(opts: TickOpts = {}): Promise<TickReport> {
1188
1436
  this.kernelGitUnavailable = undefined
1189
1437
  this.tickAbandonments = []
1438
+ this.tickDeadlineAt = opts.deadlineAt
1190
1439
  this.availabilityEntries = undefined
1440
+ this.janitorEntries = undefined
1441
+ this.nodeChildren = undefined
1191
1442
  this.availabilityLandings = undefined
1192
1443
  this.availabilityLandingKey = undefined
1193
1444
  const builds = new Map<string, number>()
@@ -1204,17 +1455,31 @@ export class Dispatcher {
1204
1455
  }
1205
1456
  if (build) builds.set(build, (builds.get(build) ?? 0) + 1)
1206
1457
  else unattributed++
1458
+ if (request.rateLimit) {
1459
+ const observation = forgeRateLimitObservationSchema.safeParse(request.rateLimit)
1460
+ if (observation.success) {
1461
+ this.forgeRateLimits.set(observation.data.resource, {
1462
+ ...observation.data,
1463
+ observedAt: this.deps.clock().toISOString(),
1464
+ })
1465
+ this.boundForgeRateLimits()
1466
+ }
1467
+ }
1207
1468
  })
1208
- const counts = () => ({
1209
- total,
1210
- ...(classified ? categories : {}),
1211
- unattributed,
1212
- builds: [...builds]
1213
- .map(([build, requests]) => ({ build, requests }))
1214
- .sort((a, b) => b.requests - a.requests || a.build.localeCompare(b.build))
1215
- .slice(0, 10),
1216
- complete: true,
1217
- })
1469
+ const counts = () => {
1470
+ const rateLimits = this.carriedRateLimits()
1471
+ return {
1472
+ total,
1473
+ ...(classified ? categories : {}),
1474
+ unattributed,
1475
+ builds: [...builds]
1476
+ .map(([build, requests]) => ({ build, requests }))
1477
+ .sort((a, b) => b.requests - a.requests || a.build.localeCompare(b.build))
1478
+ .slice(0, 10),
1479
+ complete: true,
1480
+ ...(rateLimits.length > 0 ? { rateLimits } : {}),
1481
+ }
1482
+ }
1218
1483
  this.lastForgeRequests = undefined
1219
1484
  try {
1220
1485
  const report = await (this.deps.forge.withReadScope
@@ -1232,6 +1497,10 @@ export class Dispatcher {
1232
1497
  }
1233
1498
  }
1234
1499
 
1500
+ /** The current tick's invocation deadline, consulted by the provisioning
1501
+ * budget gate. Undefined for unbounded (watch/foreground) ticks. */
1502
+ private tickDeadlineAt: number | undefined
1503
+
1235
1504
  /** Ticket preparations durably abandoned during the current tick. Drained
1236
1505
  * once by `tick()` into its report or its rejection, so later ticks never
1237
1506
  * repeat them. At most 8 recoveries plus one inline abandonment per tick. */
@@ -1261,10 +1530,19 @@ export class Dispatcher {
1261
1530
  this.nodePollingTickReads.clear()
1262
1531
  this.slotWaiters.clear()
1263
1532
  this.parkedSettled.clear()
1533
+ this.deferredAdmissions.clear()
1534
+ this.admissionBoundary = false
1535
+ this.urgentEvaluated = false
1536
+ this.forcedDeferralKey = undefined
1264
1537
  // One immutable config for this complete decision pass. A reload racing the
1265
1538
  // tick is observed by the next tick, never half-way through this one.
1266
1539
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1267
1540
  if (opts.viewRefreshed !== true) await this.store.refresh()
1541
+ // A pending start request measures capacity from the facts this tick's
1542
+ // fleet-wide stages read anyway; keep them only then.
1543
+ this.store.retainBuildFacts(
1544
+ Object.keys(this.store.repositoryFacts().ticketStarts.pending).length > 0,
1545
+ )
1268
1546
  const autoMergeUser = undefined
1269
1547
  const report = emptyTickReport()
1270
1548
  this.restoreScan(report)
@@ -1280,6 +1558,11 @@ export class Dispatcher {
1280
1558
  const repoFacts = this.store.repositoryFacts()
1281
1559
  if (this.deps.missingAccounts) await this.reconcileAccountPresence(this.deps.missingAccounts())
1282
1560
  const paused = repoFacts.settings.paused
1561
+ this.tickAcceptsNewWork = opts.acceptNewWork !== false
1562
+ this.tickPaused = paused
1563
+ // Normal parked work never takes a free slot before this tick's dispatch
1564
+ // has evaluated urgent claims, while claims can run at all.
1565
+ this.admissionBoundary = !opts.observationOnly && this.claimsPossible(opts, paused)
1283
1566
  const autoMergeSeedFact = undefined
1284
1567
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
1285
1568
  // provider liveness and settle their completion, lease, and publication.
@@ -1314,13 +1597,27 @@ export class Dispatcher {
1314
1597
  if (this.outOfBudget(opts)) return report
1315
1598
  await this.leaseSweep(report, launched, paused, opts)
1316
1599
  if (this.outOfBudget(opts)) return report
1317
- // Nodes with a durable verification request take freed slots before
1318
- // intake, whether or not idle node polling visited them this tick.
1600
+ // Nodes with a durable verification or propose request take freed slots
1601
+ // before intake, whether or not idle node polling visited them this tick.
1602
+ // The same pass advances optimization nodes' proposers first.
1319
1603
  await this.admitWaitingNodes(report, launched, opts)
1320
1604
  if (this.outOfBudget(opts)) return report
1605
+ // Operator start requests are independent of intake: they claim only the
1606
+ // named tickets, and read nothing when none is pending. Manual and urgent
1607
+ // requests run here, ahead of ordinary claims; normal requests run after
1608
+ // urgent claims and normal parked work (SPEC §12 "Slot admission order").
1609
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, [
1610
+ 'manual',
1611
+ 'urgent',
1612
+ ])
1613
+ if (this.outOfBudget(opts)) return report
1321
1614
  if (opts.acceptNewWork !== false) {
1322
1615
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1323
1616
  }
1617
+ await this.admitDeferredParked(report, launched, paused, opts)
1618
+ // Ordinary normal claims left this pass's reserved slots free.
1619
+ if (!this.outOfBudget(opts))
1620
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, ['normal'])
1324
1621
  // Fire-and-forget by contract: long synthesize/review sessions must not
1325
1622
  // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1326
1623
  // watch ticks. Durable pause and infrastructure-error stops suppress
@@ -1355,14 +1652,21 @@ export class Dispatcher {
1355
1652
  const { repo } = this.deps
1356
1653
  const records = (await store.listBuilds()).filter((record) => record.repo === repo)
1357
1654
  const digests = await readBuildDigests(store, repo)
1655
+ // Including deferred builds needs no deferral check: the tick's stages
1656
+ // that exclude them already checked and recorded it. The check reads
1657
+ // through the view, so a retaining tick keeps the read for capacity, and
1658
+ // the start pass serves it instead of reading the deferred builds again.
1358
1659
  const blocked = new Set<string>()
1359
- for (const record of records) {
1360
- if (
1361
- (digests.get(record.slug)?.compatibility?.decisiveFacts ?? 0) > 0 &&
1362
- (await deferMixedVersion(store, record.slug))
1363
- )
1364
- blocked.add(record.slug)
1365
- }
1660
+ const readFacts = (slug: string) =>
1661
+ this.startPass ? store.servedBuildFacts(slug) : store.buildFacts(slug)
1662
+ if (!includeDeferred)
1663
+ for (const record of records) {
1664
+ if (
1665
+ (digests.get(record.slug)?.compatibility?.decisiveFacts ?? 0) > 0 &&
1666
+ (await deferMixedVersion(store, record.slug, undefined, readFacts))
1667
+ )
1668
+ blocked.add(record.slug)
1669
+ }
1366
1670
  return records
1367
1671
  .filter((record) => includeDeferred || !blocked.has(record.slug))
1368
1672
  .map((record) => {
@@ -1534,6 +1838,296 @@ export class Dispatcher {
1534
1838
  }
1535
1839
  }
1536
1840
 
1841
+ /** Admit pending operator start requests of the given tiers through
1842
+ * `dispatch()`'s gates and settle each one that reaches a decision. Zero
1843
+ * reads while none of those tiers is pending; otherwise one targeted `get`
1844
+ * per request (at most START_REQUESTS_PER_TICK) over the view-cached build
1845
+ * digests. Waiting conditions (pause, no slot in the request's tier,
1846
+ * creation holds, an in-flight preparation, a failed dependency read, a
1847
+ * source error, the tick budget) leave the request pending. */
1848
+ private async honorStartRequests(
1849
+ report: TickReport,
1850
+ launched: Set<string>,
1851
+ autoMergeUser: string | undefined,
1852
+ paused: boolean,
1853
+ opts: TickOpts,
1854
+ tiers: readonly TicketStartPriority[],
1855
+ ): Promise<void> {
1856
+ const starts = this.store.repositoryFacts().ticketStarts
1857
+ const rank = (request: PendingTicketStart) => START_TIER_ORDER.indexOf(request.priority)
1858
+ const pending = Object.values(starts.pending)
1859
+ .filter((request) => tiers.includes(request.priority))
1860
+ .sort((a, b) => rank(a) - rank(b) || a.seq - b.seq)
1861
+ .slice(0, START_REQUESTS_PER_TICK)
1862
+ if (pending.length === 0 || paused) return
1863
+ const { tickets, config } = this.deps
1864
+ const migrations = this.store.repositoryFacts().ticketMigrations
1865
+ // Deferred mixed-version builds are still active: include them, so a
1866
+ // build the tick cannot decide is never mistaken for a free ticket.
1867
+ const active = (await this.repoBuildDigests(true)).filter(
1868
+ ({ digest }) => digest.terminal === undefined,
1869
+ )
1870
+ const refs = active.flatMap(({ record }) => {
1871
+ if (!record.ticket) return []
1872
+ try {
1873
+ const ref = resolveTicketRef(migrations, record.ticket, tickets.name, record.slug)
1874
+ return [{ slug: record.slug, createdAt: record.createdAt, ref }]
1875
+ } catch (error) {
1876
+ // The same policy as activeTicketIdentities: a recorded cutover that
1877
+ // omits a live claim must block admission.
1878
+ if (migrations.migrations.some((m) => m.from === record.ticket!.source && m.from !== m.to))
1879
+ throw error
1880
+ return [{ slug: record.slug, createdAt: record.createdAt, ref: record.ticket }]
1881
+ }
1882
+ })
1883
+ const identified =
1884
+ tickets.name !== 'hosted' || (await this.ensureActiveIdentities(refs, active))
1885
+ if (identified === 'rate-limited') return
1886
+ const identities = this.store.repositoryFacts().ticketStarts.identities
1887
+ const lifecycle = ticketLifecycle(config.tickets)
1888
+ const candidates: { request: PendingTicketStart; ticket: Ticket }[] = []
1889
+ for (const request of pending) {
1890
+ if (this.outOfBudget(opts)) return
1891
+ let ref: TicketRef | undefined
1892
+ try {
1893
+ ref = resolveTicketRef(migrations, request.ticket, tickets.name)
1894
+ } catch {
1895
+ ref = undefined
1896
+ }
1897
+ if (ref === undefined || ref.source !== tickets.name) {
1898
+ await this.settleStartRequest(request, 'missing', {
1899
+ detail: `ticket ${request.ticket.source}:${request.ticket.id} is not in the configured ${tickets.name} ticket source`,
1900
+ })
1901
+ continue
1902
+ }
1903
+ let ticket: Ticket | null
1904
+ try {
1905
+ ticket = await tickets.get(ref.id)
1906
+ } catch (error) {
1907
+ if (error instanceof TicketSourceRateLimitError) {
1908
+ await this.sourceFailure(error, 'dependency-check')
1909
+ return
1910
+ }
1911
+ continue
1912
+ }
1913
+ if (ticket === null) {
1914
+ await this.settleStartRequest(request, 'missing', {
1915
+ detail: `no ticket ${ref.id} in the configured ${tickets.name} ticket source`,
1916
+ })
1917
+ continue
1918
+ }
1919
+ const build = this.targetedActiveBuild(ticket.ref, refs, identities)
1920
+ if (build !== undefined) {
1921
+ // A build created after the request is this request's own claim
1922
+ // whose settlement was lost, or intake's claim in the same window.
1923
+ await this.settleStartRequest(
1924
+ request,
1925
+ Date.parse(build.createdAt) > Date.parse(request.ts) ? 'started' : 'already-building',
1926
+ { slug: build.slug },
1927
+ )
1928
+ continue
1929
+ }
1930
+ // Fail closed: a hosted build whose identity is not yet projected might
1931
+ // embody this ticket under a legacy alias.
1932
+ if (identified !== true) continue
1933
+ // Ingesters propose, humans dispatch: only the ready state starts.
1934
+ if (!holdsState(ticket.state, config.tickets.readyState)) {
1935
+ const terminal =
1936
+ ticket.resolved ||
1937
+ holdsState(ticket.state, this.doneState) ||
1938
+ holdsState(ticket.state, lifecycle.rejected)
1939
+ await this.settleStartRequest(request, terminal ? 'terminal' : 'not-ready', {
1940
+ detail: `ticket ${ticket.ref.id} is in ${ticket.state ?? 'an unreported state'}, not ${config.tickets.readyState}`,
1941
+ })
1942
+ continue
1943
+ }
1944
+ if (this.preparing(ticket.ref.source, ticket.ref.id)) continue
1945
+ candidates.push({ request, ticket })
1946
+ }
1947
+ if (candidates.length === 0 || this.outOfBudget(opts)) return
1948
+ // Capacity is measured from the facts this tick's janitor, recovery and
1949
+ // lease sweep already read (`servedBuildFacts`): a build is read again
1950
+ // only when the tick skipped it or wrote to it since, so neither a wait
1951
+ // nor an admission reads the fleet, on a fresh process or a warm one.
1952
+ // Each tier's budget leaves the slots reserved ahead of it (SPEC §12).
1953
+ // With no free slot in its tier, only a node, or a blocked target not yet
1954
+ // checked, needs the pass.
1955
+ const now = this.deps.clock()
1956
+ const measured = await this.capacityBuilds(launched, true)
1957
+ const projection = dispatchCapacity(measured, config.capacity, now, undefined, {
1958
+ urgentClaims: this.urgentClaims(),
1959
+ startRequests: this.startClaims(),
1960
+ })
1961
+ const adjust = { settled: this.parkedSettled, denied: this.slotWaiters }
1962
+ const budgets = {
1963
+ manual: startCapacity(projection, adjust, 'manual'),
1964
+ urgent: startCapacity(projection, adjust, 'urgent'),
1965
+ normal: startCapacity(projection, adjust, 'normal'),
1966
+ }
1967
+ const open = new Set(Object.values(starts.pending).map(({ seq }) => seq))
1968
+ for (const seq of this.startBlockersChecked)
1969
+ if (!open.has(seq)) this.startBlockersChecked.delete(seq)
1970
+ const free = (request: PendingTicketStart) => budgets[request.priority] > 0
1971
+ const passing = candidates.filter(
1972
+ ({ request, ticket }) =>
1973
+ free(request) ||
1974
+ ticket.kind === 'node' ||
1975
+ (ticket.target !== undefined &&
1976
+ !!ticket.blockedBy?.length &&
1977
+ !this.startBlockersChecked.has(request.seq)),
1978
+ )
1979
+ if (passing.length === 0) return
1980
+ for (const { request, ticket } of passing)
1981
+ if (!free(request) && ticket.kind !== 'node') this.startBlockersChecked.add(request.seq)
1982
+ const key = (ref: TicketRef) => `${ref.source}:${ref.id}`
1983
+ const targeted: TargetedDispatch = {
1984
+ tickets: passing.map(({ ticket }) => ticket),
1985
+ activeIds: new Set(refs.map(({ ref }) => key(ref))),
1986
+ requests: new Map(passing.map(({ request, ticket }) => [ticket.ref.id, request])),
1987
+ outcomes: new Map(),
1988
+ measured,
1989
+ budgets,
1990
+ }
1991
+ const scratch = emptyTickReport()
1992
+ this.startPass = true
1993
+ try {
1994
+ await this.dispatch(scratch, launched, autoMergeUser, paused, opts, undefined, targeted)
1995
+ } finally {
1996
+ this.startPass = false
1997
+ for (const counter of [
1998
+ 'dispatched',
1999
+ 'authored',
2000
+ 'bounced',
2001
+ 'claimRaces',
2002
+ 'dispatchFailed',
2003
+ 'provisioning',
2004
+ 'provisioningDeferred',
2005
+ 'dependencyCheckFailed',
2006
+ ] as const)
2007
+ report[counter] += scratch[counter]
2008
+ for (const { request, ticket } of passing) {
2009
+ const settled = targeted.outcomes.get(ticket.ref.id)
2010
+ if (settled === undefined) continue
2011
+ const { outcome, ...extra } = settled
2012
+ await this.settleStartRequest(request, outcome, extra)
2013
+ }
2014
+ }
2015
+ }
2016
+
2017
+ /** The active build embodying `requested`, matched with no source reads:
2018
+ * by the build's normalized recorded id, or, for hosted, by its projected
2019
+ * canonical identity. Hosted ids compare case-insensitively. */
2020
+ private targetedActiveBuild(
2021
+ requested: TicketRef,
2022
+ refs: readonly ActiveTicketRef[],
2023
+ identities: TicketStarts['identities'],
2024
+ ): ActiveTicketRef | undefined {
2025
+ const hosted = requested.source === 'hosted'
2026
+ const same = (a: string, b: string) => (hosted ? a.toLowerCase() === b.toLowerCase() : a === b)
2027
+ return refs.find(({ slug, ref }) => {
2028
+ if (ref.source !== requested.source) return false
2029
+ if (same(ref.id, requested.id)) return true
2030
+ const identity = identities[slug]
2031
+ return hosted && identity?.recorded === ref.id && same(identity.canonical, requested.id)
2032
+ })
2033
+ }
2034
+
2035
+ /** Project the canonical identity of every active hosted build once in its
2036
+ * life, at most IDENTITY_RESOLUTIONS_PER_TICK per tick, and release builds
2037
+ * no longer active in the same append. True once every active hosted build
2038
+ * has a current entry; false while resolution is incomplete or failed, and
2039
+ * `rate-limited` after a source rate limit. Zero reads and writes once
2040
+ * complete. */
2041
+ private async ensureActiveIdentities(
2042
+ refs: readonly ActiveTicketRef[],
2043
+ active: readonly { record: BuildRecord }[],
2044
+ ): Promise<boolean | 'rate-limited'> {
2045
+ const identities = this.store.repositoryFacts().ticketStarts.identities
2046
+ const missing = refs.filter(
2047
+ ({ slug, ref }) => ref.source === 'hosted' && identities[slug]?.recorded !== ref.id,
2048
+ )
2049
+ const live = new Set(active.map(({ record }) => record.slug))
2050
+ const released = Object.keys(identities)
2051
+ .filter((slug) => !live.has(slug))
2052
+ .slice(0, IDENTITY_RELEASES_PER_APPEND)
2053
+ if (missing.length === 0 && released.length === 0) return true
2054
+ const resolved: { build: string; recorded: string; canonical: string }[] = []
2055
+ let complete = missing.length <= IDENTITY_RESOLUTIONS_PER_TICK
2056
+ for (const { slug, ref } of missing.slice(0, IDENTITY_RESOLUTIONS_PER_TICK)) {
2057
+ try {
2058
+ const ticket = await this.deps.tickets.get(ref.id)
2059
+ resolved.push({
2060
+ build: slug,
2061
+ recorded: ref.id,
2062
+ canonical: ticket?.ref.source === 'hosted' ? ticket.ref.id : ref.id,
2063
+ })
2064
+ } catch (error) {
2065
+ if (error instanceof TicketSourceRateLimitError) {
2066
+ await this.sourceFailure(error, 'dependency-check')
2067
+ return 'rate-limited'
2068
+ }
2069
+ complete = false
2070
+ }
2071
+ }
2072
+ if (resolved.length === 0 && released.length === 0) return false
2073
+ if (this.deps.holdsRepoAuthority?.() === false) return false
2074
+ try {
2075
+ await this.store.ensureRepo(this.deps.repo)
2076
+ await this.store.appendRepo(this.deps.repo, {
2077
+ actor: DISPATCHER,
2078
+ type: 'ticket.identity-recorded',
2079
+ payload: { identities: resolved, ...(released.length > 0 ? { released } : {}) },
2080
+ })
2081
+ await this.store.refreshJournal()
2082
+ } catch (error) {
2083
+ rethrowAuthorityLapse(error)
2084
+ return false
2085
+ }
2086
+ return complete
2087
+ }
2088
+
2089
+ /** Whether the request a targeted ticket answers is still pending at the
2090
+ * priority the pass admitted it under, read after one journal refresh. A
2091
+ * re-request at another priority keeps its `seq` but changes the tier and
2092
+ * build priority, so the claim defers to the next pass, which admits it
2093
+ * from current inputs. */
2094
+ private async startStillPending(targeted: TargetedDispatch, ticket: Ticket): Promise<boolean> {
2095
+ const request = targeted.requests.get(ticket.ref.id)
2096
+ if (request === undefined) return false
2097
+ await this.store.refreshJournal()
2098
+ const current =
2099
+ this.store.repositoryFacts().ticketStarts.pending[ticketStartKey(request.ticket)]
2100
+ return current?.seq === request.seq && current.priority === request.priority
2101
+ }
2102
+
2103
+ /** Settle one start request once. The journal is refreshed first, so a
2104
+ * settlement whose acknowledgement was lost is never appended twice. */
2105
+ private async settleStartRequest(
2106
+ request: PendingTicketStart,
2107
+ outcome: TicketStartOutcome,
2108
+ extra: { slug?: string; detail?: string } = {},
2109
+ ): Promise<void> {
2110
+ if (this.deps.holdsRepoAuthority?.() === false) return
2111
+ await this.store.ensureRepo(this.deps.repo)
2112
+ await this.store.refreshJournal()
2113
+ const current =
2114
+ this.store.repositoryFacts().ticketStarts.pending[ticketStartKey(request.ticket)]
2115
+ if (current?.seq !== request.seq) return
2116
+ const detail = extra.detail?.trim().slice(0, 2000)
2117
+ await this.store.appendRepo(this.deps.repo, {
2118
+ actor: DISPATCHER,
2119
+ type: 'ticket.start-settled',
2120
+ payload: {
2121
+ request: request.seq,
2122
+ ticket: request.ticket,
2123
+ priority: current.priority,
2124
+ outcome,
2125
+ ...(extra.slug !== undefined ? { slug: extra.slug } : {}),
2126
+ ...(detail ? { detail } : {}),
2127
+ },
2128
+ })
2129
+ }
2130
+
1537
2131
  /** Report a preparation attempt's committed hand-back once. */
1538
2132
  private async reportPreparationHandback(
1539
2133
  attempt: TicketPreparation,
@@ -1695,7 +2289,9 @@ export class Dispatcher {
1695
2289
  report[key] = [...previous[key]]
1696
2290
  }
1697
2291
 
1698
- private async scanCheckpoint(mode: 'admission' | 'observation') {
2292
+ /** `force` makes the scan due now, skipping the interval and the journal
2293
+ * deferral: a deferred normal admission waits on this tick's urgent claims. */
2294
+ private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
1699
2295
  const digest = (await this.repoBuildDigests())
1700
2296
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
1701
2297
  .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq] as const)
@@ -1720,6 +2316,7 @@ export class Dispatcher {
1720
2316
  readinessFingerprint,
1721
2317
  criteriaFingerprint,
1722
2318
  }
2319
+ if (force) return { ...checkpoint, allowClockRollback: false, due: true }
1723
2320
  // The journal measurement alone proves deferral, so the cadence row is not read.
1724
2321
  if (ticketScanDeferredByJournal(input))
1725
2322
  return { ...checkpoint, allowClockRollback: false, due: false }
@@ -1730,6 +2327,7 @@ export class Dispatcher {
1730
2327
  private async completeScan(
1731
2328
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
1732
2329
  report: TickReport,
2330
+ urgentWaiting = 0,
1733
2331
  ): Promise<void> {
1734
2332
  const payload = {
1735
2333
  startedAt: checkpoint.startedAt,
@@ -1743,10 +2341,12 @@ export class Dispatcher {
1743
2341
  dependencyDiagnostics: report.dependencyDiagnostics.slice(0, 1000),
1744
2342
  creationWithheld: report.creationWithheld,
1745
2343
  creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
2344
+ ...(urgentWaiting > 0 ? { urgentWaiting } : {}),
1746
2345
  }
1747
2346
  const previous = this.latestScan()
1748
2347
  const unchanged =
1749
2348
  previous !== undefined &&
2349
+ previous.urgentWaiting === payload.urgentWaiting &&
1750
2350
  Object.keys(payload)
1751
2351
  .filter((key) => key !== 'startedAt')
1752
2352
  .every(
@@ -1850,14 +2450,26 @@ export class Dispatcher {
1850
2450
  if (await this.forgeCoolingDown()) return 'already-active'
1851
2451
  if (await deferMixedVersion(this.store, slug)) return 'already-active'
1852
2452
  const launchState = (await this.store.buildFacts(slug)).state
1853
- if (
1854
- launchState.kind === 'node' &&
1855
- !launchState.nodeRestack?.conflict &&
1856
- !integrationCurrent(launchState)
1857
- )
1858
- return 'already-active'
2453
+ // A landed node has nothing left to run; the janitor settles it.
2454
+ if (nodeLanded(launchState)) return 'already-active'
2455
+ if (launchState.kind === 'node' && !launchState.nodeRestack?.conflict) {
2456
+ // The last check before a proposer starts: the open request must still
2457
+ // fit current state, unless its session was already admitted.
2458
+ if (
2459
+ proposeRunDue(launchState.optimization) &&
2460
+ (proposeStarted(launchState) || !nodeMeasurementDue(launchState))
2461
+ ) {
2462
+ if (
2463
+ !proposeStarted(launchState) &&
2464
+ !proposeAdmissible(launchState.optimization, this.deps.clock())
2465
+ )
2466
+ return 'already-active'
2467
+ } else if (!integrationCurrent(launchState) && !nodeMeasurementDue(launchState))
2468
+ return 'already-active'
2469
+ }
1859
2470
  if (launched.has(slug)) return 'already-active'
1860
- if (launchState.kind !== 'node' && !(await this.leafAdmission(slug))) return 'already-active'
2471
+ if (launchState.kind !== 'node' && (await this.leafAdmission(slug)) !== 'admit')
2472
+ return 'already-active'
1861
2473
  launched.add(slug)
1862
2474
  const facts = (await readBuildFacts(this.store, slug)).value
1863
2475
  // Callers reap and reprovision a flagged workspace; an agent never starts
@@ -2227,7 +2839,7 @@ export class Dispatcher {
2227
2839
  autoMergeDefaultSeq?: number
2228
2840
  assets?: PinnedAsset[]
2229
2841
  },
2230
- ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait'> {
2842
+ ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait' | 'budget-wait'> {
2231
2843
  const slug = record.slug
2232
2844
  if (!this.accountsAvailable()) return 'in-flight'
2233
2845
  if (this.continuations.has(slug)) return 'in-flight'
@@ -2248,11 +2860,25 @@ export class Dispatcher {
2248
2860
  }
2249
2861
  // Expired lease, failed attempt, or an old lease-less marker: adopt.
2250
2862
  }
2863
+ // A bounded invocation does not start provisioning it has no realistic
2864
+ // time left to finish; a later invocation starts it with a full budget.
2865
+ // Pure clock arithmetic: nothing is read or written.
2866
+ const estimate = this.deps.workspaces.provisionEstimateMs
2867
+ if (
2868
+ estimate !== undefined &&
2869
+ this.tickDeadlineAt !== undefined &&
2870
+ this.tickDeadlineAt - this.deps.clock().getTime() < estimate
2871
+ )
2872
+ return 'budget-wait'
2251
2873
  // A finished leaf waits for a slot before its continuation reserves one.
2252
2874
  // Nothing is written: the wait costs no attempt and raises no attention.
2253
- if (tail === 'launch' && !(await this.leafAdmission(slug))) return 'slot-wait'
2875
+ if (tail === 'launch' && (await this.leafAdmission(slug)) !== 'admit') return 'slot-wait'
2254
2876
  const branch = record.branch ?? `ab/${slug}`
2255
2877
  const generation = events.workspaceGenerations
2878
+ // The latest attempt at this same generation was cut off by a recorded
2879
+ // dispatcher teardown and its lease is gone (the liveness gate above):
2880
+ // the provider may verify and finish it in place, uncharged.
2881
+ const adoptAbandoned = marker?.abandoned === 'teardown' && marker.generation === generation
2256
2882
  if (this.deps.holdsRepoAuthority?.() === false) return 'in-flight'
2257
2883
  await this.store.append(slug, {
2258
2884
  actor: DISPATCHER,
@@ -2273,6 +2899,7 @@ export class Dispatcher {
2273
2899
  generation,
2274
2900
  seed,
2275
2901
  tail,
2902
+ adoptAbandoned,
2276
2903
  }).catch(() => {
2277
2904
  // Detached work must never reject into the dispatcher process. Failure
2278
2905
  // recording can itself fail on a store outage; durable boundaries and
@@ -2304,6 +2931,7 @@ export class Dispatcher {
2304
2931
  }
2305
2932
  | undefined
2306
2933
  tail: 'dispatch' | 'launch'
2934
+ adoptAbandoned: boolean
2307
2935
  },
2308
2936
  ): Promise<void> {
2309
2937
  const store = this.store
@@ -2340,23 +2968,34 @@ export class Dispatcher {
2340
2968
  return
2341
2969
  }
2342
2970
  const priorGenerations = events.workspaceGenerations
2343
- const handle = await this.provisionWorkspace(slug, {
2344
- // Local providers provision FROM the physical checkout; remote
2345
- // providers ignore the value (their host seams are injected).
2346
- repo: this.deps.checkout ?? this.deps.repo,
2347
- baseBranch:
2348
- events.state.kind === 'node' && events.state.integration?.cycle
2349
- ? input.branch
2350
- : baseBranchOf(events, config),
2351
- branch: input.branch,
2352
- ...(priorGenerations > 0 || input.generation > 0
2353
- ? {
2354
- publication: await this.confirmedWorkspacePublication(events, slug),
2355
- revision: events.state.integration?.cycle?.head ?? this.recoveryCheckpoint(events),
2356
- generation: Math.max(priorGenerations, input.generation),
2357
- }
2358
- : {}),
2359
- })
2971
+ const handle = await this.provisionWorkspace(
2972
+ slug,
2973
+ {
2974
+ // Local providers provision FROM the physical checkout; remote
2975
+ // providers ignore the value (their host seams are injected).
2976
+ repo: this.deps.checkout ?? this.deps.repo,
2977
+ baseBranch:
2978
+ events.state.kind === 'node' &&
2979
+ (events.state.integration?.cycle || proposeRunDue(events.state.optimization))
2980
+ ? input.branch
2981
+ : baseBranchOf(events, config),
2982
+ branch: input.branch,
2983
+ ...(priorGenerations > 0 || input.generation > 0
2984
+ ? {
2985
+ publication: await this.confirmedWorkspacePublication(events, slug),
2986
+ revision:
2987
+ (proposeRunDue(events.state.optimization)
2988
+ ? events.state.optimization?.proposal?.head
2989
+ : undefined) ??
2990
+ events.state.integration?.cycle?.head ??
2991
+ this.recoveryCheckpoint(events),
2992
+ generation: Math.max(priorGenerations, input.generation),
2993
+ }
2994
+ : {}),
2995
+ ...(input.adoptAbandoned ? { adoptAbandoned: true } : {}),
2996
+ },
2997
+ entry.controller.signal,
2998
+ )
2360
2999
  // The provisioned fact is true and welcome even when a teardown signal
2361
3000
  // landed mid-call; the token check below still prevents a superseded
2362
3001
  // supervisor from launching.
@@ -2399,6 +3038,10 @@ export class Dispatcher {
2399
3038
  // A lapsed repository lease started nothing: no failure fact. The
2400
3039
  // finally releases the execution lease; the successor adopts the marker.
2401
3040
  if (isRepositoryAuthorityLapse(error)) return
3041
+ // Teardown aborted this continuation and already recorded the
3042
+ // abandonment; a late provider failure after it is not a new fact, and
3043
+ // recording one would charge an attempt and spoil the adoptable marker.
3044
+ if (entry.controller.signal.aborted) return
2402
3045
  // Dispatch boundaries own their failure facts and exhaustion repair.
2403
3046
  // A failed tail read/write leaves durable unfinished work for the next
2404
3047
  // tick; it is not another provider workspace failure. Replacement
@@ -2406,7 +3049,12 @@ export class Dispatcher {
2406
3049
  if (await this.holdForMissingAccounts(error)) return
2407
3050
  if (boundary === 'read' || boundary === 'dispatch') return
2408
3051
  const events = (await readBuildFacts(store, slug)).value
2409
- if (workspaces.recovery !== undefined) {
3052
+ // Finishing a teardown-abandoned attempt that turns out unfinishable is
3053
+ // uncharged: a teardown abandonment never counts toward
3054
+ // `maxInfrastructureAttempts`. The cleanup-required fact still lets the
3055
+ // sweep reap and replace it.
3056
+ const uncharged = input.adoptAbandoned && error instanceof WorkspaceCleanupRequired
3057
+ if (workspaces.recovery !== undefined && !uncharged) {
2410
3058
  const open = openWorkspace(events)
2411
3059
  const latestRef = events.latestRelease
2412
3060
  await this.recordInfrastructureFailure(slug, events, {
@@ -2483,6 +3131,7 @@ export class Dispatcher {
2483
3131
  attempt,
2484
3132
  error:
2485
3133
  'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3134
+ abandoned: 'teardown',
2486
3135
  },
2487
3136
  })
2488
3137
  }
@@ -2509,9 +3158,13 @@ export class Dispatcher {
2509
3158
  // Only this repo's builds that still have work (§12: another repo's
2510
3159
  // builds are another dispatcher's duty; settled terminal builds cost no
2511
3160
  // event reads).
2512
- const entries = (await this.repoBuildDigests()).filter(
3161
+ // Unfiltered, so optimization stop enforcement sees terminal attempt builds.
3162
+ const builds = await this.repoBuildDigests()
3163
+ const entries = builds.filter(
2513
3164
  ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
2514
3165
  )
3166
+ this.janitorEntries = entries
3167
+ this.nodeChildren = undefined
2515
3168
  // Receipt reporting requires no forge call, capacity or workspace. Recover
2516
3169
  // every episode before the transport-budget and janitor-backoff gates.
2517
3170
  for (const { record, digest } of entries) {
@@ -2544,18 +3197,64 @@ export class Dispatcher {
2544
3197
  const initialFacts = await this.store.buildFacts(record.slug)
2545
3198
  let { state, workspace, log } = initialFacts
2546
3199
  previous = state.janitor
3200
+ // A node's janitor acknowledges every pending control itself, a
3201
+ // cancelling resume included; a leaf's resume that only cancelled a
3202
+ // never-acknowledged pause holds nothing back and waits out backoff.
3203
+ const commands = state.kind === 'node' ? state.pendingCommands : actionableCommands(state)
2547
3204
  const controlDue =
2548
- state.pendingCommands.length > 0 ||
3205
+ commands.length > 0 ||
2549
3206
  state.discardRequest !== undefined ||
3207
+ (state.declined !== undefined && state.status !== 'done') ||
2550
3208
  (state.pr &&
2551
3209
  state.landing?.command &&
2552
3210
  state.landing.command.seq !== state.landing.acknowledgedSeq)
3211
+ // Every tick, independent of janitor backoff and idle node polling: an
3212
+ // hours budget must fire on a node with no other activity.
3213
+ if (state.optimization !== undefined && !mixedVersionDeferred(state)) {
3214
+ const deps = {
3215
+ store: this.store,
3216
+ clock: this.deps.clock,
3217
+ migrations: this.store.repositoryFacts().ticketMigrations,
3218
+ ticketSource: this.deps.tickets.name,
3219
+ }
3220
+ // Merges no settlement or marker recorded first, so a stopped
3221
+ // node's enforcer and completion see them as they are.
3222
+ if (await reconcileMergedAttempts(deps, record, state, builds))
3223
+ state = (await this.store.buildFacts(record.slug)).state
3224
+ if (await enforceOptimizationStop(deps, record, state, builds))
3225
+ state = (await this.store.buildFacts(record.slug)).state
3226
+ }
2553
3227
  // Read the clock only inside an episode, as before episodes could escalate.
2554
3228
  if (!controlDue && previous && !janitorDue(previous, this.deps.clock())) return
2555
3229
  if (mixedVersionDeferred(state)) {
2556
3230
  await deferMixedVersion(this.store, record.slug)
2557
3231
  return
2558
3232
  }
3233
+ // Independent of idle polling: a pending re-acceptance is read from
3234
+ // reduced state, so it survives a crash after `spec.revised`.
3235
+ if (
3236
+ objectiveAcceptancePending(state) &&
3237
+ (await this.acceptRevisedObjective(record, state, report))
3238
+ )
3239
+ state = (await this.store.buildFacts(record.slug)).state
3240
+ // An optimization node's pending rejected-role moves are a
3241
+ // post-terminal duty, like attachment reclaim: they run for open,
3242
+ // aborted and completed nodes alike, ahead of every early return.
3243
+ // Control commands go first, so a tracker refusing the move never
3244
+ // blocks an abort.
3245
+ if (state.kind === 'node' && state.optimization?.rejections.length && !controlDue) {
3246
+ operation = 'attempt rejection'
3247
+ attempted = true
3248
+ if (await this.sweepAttemptRejections(record, state))
3249
+ state = (await this.store.buildFacts(record.slug)).state
3250
+ // A completed node polled only for this duty has nothing else due.
3251
+ if (
3252
+ state.status === 'done' &&
3253
+ digest.reclaimPending !== true &&
3254
+ digest.integrationAuditPending !== true
3255
+ )
3256
+ return
3257
+ }
2559
3258
  const executionLeaseLive = this.hasLiveExecutionLease(record)
2560
3259
  attempted = !executionLeaseLive
2561
3260
  // Raw history, read at most once and only by a branch that acts on it:
@@ -2662,6 +3361,7 @@ export class Dispatcher {
2662
3361
  {
2663
3362
  history,
2664
3363
  workspace,
3364
+ executionOpen: initialFacts.open !== null,
2665
3365
  observed: (pr) => {
2666
3366
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2667
3367
  },
@@ -2757,6 +3457,7 @@ export class Dispatcher {
2757
3457
  {
2758
3458
  history,
2759
3459
  workspace,
3460
+ executionOpen: initialFacts.open !== null,
2760
3461
  observed: (pr) => {
2761
3462
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2762
3463
  },
@@ -2858,6 +3559,11 @@ export class Dispatcher {
2858
3559
  await this.cleanupAborted(record, await history(), report)
2859
3560
  return
2860
3561
  }
3562
+ if (!executionLeaseLive && state.declined !== undefined) {
3563
+ operation = 'decline settlement'
3564
+ await this.settleDeclinedAttempt(record, await history())
3565
+ return
3566
+ }
2861
3567
  operation = 'target observation'
2862
3568
  if (state.kind !== 'node' && state.status !== 'aborted')
2863
3569
  await this.observeTicketTarget(record, state, report)
@@ -2939,6 +3645,7 @@ export class Dispatcher {
2939
3645
  {
2940
3646
  history,
2941
3647
  workspace,
3648
+ executionOpen: initialFacts.open !== null,
2942
3649
  observed: (pr) => {
2943
3650
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2944
3651
  },
@@ -3309,18 +4016,33 @@ export class Dispatcher {
3309
4016
  /** Deferral withholds decisions, but cannot free an existing capacity reservation.
3310
4017
  * A leaf's runner reservation is this process's continuation or a launch
3311
4018
  * this tick; another process's continuation holds a heartbeat lease. */
3312
- private async capacityBuilds(launched?: ReadonlySet<string>): Promise<CapacityBuild[]> {
4019
+ private async capacityBuilds(
4020
+ launched?: ReadonlySet<string>,
4021
+ /** Serve the facts this tick already read (`servedBuildFacts`). */
4022
+ served = false,
4023
+ ): Promise<CapacityBuild[]> {
3313
4024
  const builds: CapacityBuild[] = []
3314
4025
  for (const { record, digest } of await this.repoBuildDigests(true)) {
3315
4026
  if (digest.terminal) continue
3316
- const facts = await this.store.buildFacts(record.slug)
4027
+ // A leaf with a runner provisioning holds its slot and requests none
4028
+ // whatever its state, so any read this tick serves it, launch or not.
4029
+ const allocatedLeaf =
4030
+ digest.kind !== 'node' &&
4031
+ (this.continuations.has(record.slug) || !!launched?.has(record.slug))
4032
+ const facts = served
4033
+ ? ((allocatedLeaf ? this.store.retainedBuildFacts(record.slug) : undefined) ??
4034
+ (await this.store.servedBuildFacts(record.slug)))
4035
+ : await this.store.buildFacts(record.slug)
3317
4036
  builds.push({
3318
4037
  record,
3319
4038
  state: facts.state,
3320
4039
  workspace: facts.workspace !== null,
3321
4040
  provisioning:
3322
4041
  digest.kind === 'node'
3323
- ? (await readBuildFacts(this.store, record.slug)).value.provisionMarker !== undefined
4042
+ ? (served
4043
+ ? facts.provisionMarker
4044
+ : (await readBuildFacts(this.store, record.slug)).value.provisionMarker) !==
4045
+ undefined
3324
4046
  : this.continuations.has(record.slug) || !!launched?.has(record.slug),
3325
4047
  restackDue: landingRestackDue(facts.state, facts.log),
3326
4048
  })
@@ -3328,12 +4050,68 @@ export class Dispatcher {
3328
4050
  return builds
3329
4051
  }
3330
4052
 
4053
+ /** Whether ticket claims can run this tick: the one predicate both
4054
+ * `dispatch` and the urgent admission boundary use. Without the source's
4055
+ * priority capability every claim is normal, so nothing ever defers. */
4056
+ private claimsPossible(opts: Pick<TickOpts, 'acceptNewWork'>, paused: boolean): boolean {
4057
+ return (
4058
+ !!this.deps.tickets.priority &&
4059
+ opts.acceptNewWork !== false &&
4060
+ !paused &&
4061
+ this.claimGateOpen()
4062
+ )
4063
+ }
4064
+
4065
+ /** Accounts are present and the forge is not cooling down: `dispatch`'s own
4066
+ * early returns. */
4067
+ private claimGateOpen(): boolean {
4068
+ if (!this.accountsAvailable()) return false
4069
+ const health = this.store.repositoryFacts().forgeHealth
4070
+ return !(health && Date.parse(health.resetAt) > this.deps.clock().getTime())
4071
+ }
4072
+
4073
+ /** Urgent ticket claims the latest admission scan found waiting for a slot.
4074
+ * In memory: the journal view is refreshed each tick. */
4075
+ private urgentClaims(): number {
4076
+ return this.tickAcceptsNewWork ? urgentClaimDemand(this.store.repositoryFacts()) : 0
4077
+ }
4078
+
4079
+ /** Pending operator start requests by tier; nothing while no claim can
4080
+ * run. In memory, like `urgentClaims`. */
4081
+ private startClaims(): Partial<Record<TicketStartPriority, number>> {
4082
+ return this.claimGateOpen() ? startClaimDemand(this.store.repositoryFacts()) : {}
4083
+ }
4084
+
4085
+ /** A normal waiter must defer: claims can run and this tick's dispatch has
4086
+ * not yet evaluated urgent claims. */
4087
+ private urgentBoundaryOpen(): boolean {
4088
+ return (
4089
+ this.admissionBoundary &&
4090
+ this.claimsPossible({ acceptNewWork: this.tickAcceptsNewWork }, this.tickPaused)
4091
+ )
4092
+ }
4093
+
4094
+ /** One parked waiter's admission into a free slot (SPEC §12 "Slot admission
4095
+ * order"): urgent parked work, urgent claims, normal parked work, normal
4096
+ * claims. `occupied` counts every other build holding a slot. */
4097
+ private slotAdmission(
4098
+ slug: string,
4099
+ priority: TicketPriority,
4100
+ occupied: number,
4101
+ projection: DispatchCapacity,
4102
+ ): 'admit' | 'wait' | 'defer' {
4103
+ if (occupied + reservedAhead(projection, { slug, priority }) >= this.deps.config.capacity)
4104
+ return 'wait'
4105
+ return priority === 'normal' && this.urgentBoundaryOpen() ? 'defer' : 'admit'
4106
+ }
4107
+
3331
4108
  /** Whether a leaf may reserve a runner now. A leaf that has not finished its
3332
4109
  * pipeline already holds its slot, and abort and pause acknowledgements park
3333
4110
  * at once, so only a finished leaf that must run again is gated: it needs
3334
- * a free slot among every other build. A denial is recorded only in memory,
3335
- * for this tick's intake reservation. */
3336
- private async leafAdmission(slug: string): Promise<boolean> {
4111
+ * a free slot among every other build, after urgent work ahead of it. A
4112
+ * denial or deferral is recorded only in memory, for this tick's intake
4113
+ * reservation; a deferral is retried after this tick's dispatch. */
4114
+ private async leafAdmission(slug: string): Promise<'admit' | 'wait' | 'defer'> {
3337
4115
  const { state } = await this.store.buildFacts(slug)
3338
4116
  if (
3339
4117
  !(epilogueLeaf(state) || waitParked(state)) ||
@@ -3341,70 +4119,644 @@ export class Dispatcher {
3341
4119
  (command) => command.command === 'abort' || command.command === 'pause',
3342
4120
  )
3343
4121
  )
3344
- return true
3345
- const others = (await this.capacityBuilds(this.tickLaunched)).filter(
3346
- (build) => build.record.slug !== slug,
3347
- )
4122
+ return 'admit'
4123
+ const builds = await this.capacityBuilds(this.tickLaunched)
4124
+ const others = builds.filter((build) => build.record.slug !== slug)
3348
4125
  const capacity = this.deps.config.capacity
3349
- if (dispatchCapacity(others, capacity, this.deps.clock()).occupied < capacity) {
4126
+ const now = this.deps.clock()
4127
+ const priority = buildPriority(state)
4128
+ const outcome = this.slotAdmission(
4129
+ slug,
4130
+ priority,
4131
+ dispatchCapacity(others, capacity, now).occupied,
4132
+ dispatchCapacity(builds, capacity, now, undefined, {
4133
+ urgentClaims: this.urgentClaims(),
4134
+ startRequests: this.startClaims(),
4135
+ }),
4136
+ )
4137
+ if (outcome === 'admit') {
3350
4138
  this.slotWaiters.delete(slug)
3351
- return true
4139
+ return 'admit'
4140
+ }
4141
+ this.slotWaiters.set(slug, priority)
4142
+ if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
4143
+ this.deferredAdmissions.set(slug, 'leaf')
4144
+ return outcome
4145
+ }
4146
+
4147
+ /**
4148
+ * Retry every admission deferred this tick, once this tick's admission scan
4149
+ * has evaluated urgent claims. Each retry re-enters its generic path with
4150
+ * fresh state: a leaf through the lease sweep's per-build pass, a node
4151
+ * through node admission, a proposer through proposer admission. Without a
4152
+ * completed evaluation nothing launches: the waiters stay reserved in
4153
+ * `slotWaiters` against normal claims and are decided again next tick.
4154
+ */
4155
+ private async admitDeferredParked(
4156
+ report: TickReport,
4157
+ launched: Set<string>,
4158
+ paused: boolean,
4159
+ opts: TickOpts,
4160
+ ): Promise<void> {
4161
+ const deferred = [...this.deferredAdmissions]
4162
+ this.deferredAdmissions.clear()
4163
+ if (deferred.length === 0) {
4164
+ this.lastForcedDeferralKey = undefined
4165
+ return
4166
+ }
4167
+ if (!this.urgentEvaluated) return
4168
+ this.admissionBoundary = false
4169
+ for (const [slug, kind] of deferred) {
4170
+ if (this.outOfBudget(opts)) return
4171
+ if (launched.has(slug)) continue
4172
+ try {
4173
+ const record = await this.store.getBuild(slug)
4174
+ if (record === null) continue
4175
+ if (kind === 'leaf')
4176
+ await this.sweepBuild(record, report, launched, paused, this.deps.clock().getTime())
4177
+ else if (kind === 'node') {
4178
+ const builds = await this.capacityBuilds()
4179
+ const build = builds.find((entry) => entry.record.slug === slug)
4180
+ if (build) await this.admitNode(build, this.deps.clock(), report, launched)
4181
+ } else {
4182
+ const builds = await this.capacityBuilds()
4183
+ await this.admitProposers(builds, this.deps.clock(), 0, report, launched, opts, slug)
4184
+ }
4185
+ } catch (error) {
4186
+ rethrowAuthorityLapse(error)
4187
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4188
+ if (error instanceof ForgeCooldown) throw error
4189
+ const message =
4190
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4191
+ report.janitorDiagnostics.push(`build ${slug}: deferred admission failed — ${message}`)
4192
+ }
3352
4193
  }
3353
- this.slotWaiters.add(slug)
3354
- return false
4194
+ if (this.forcedDeferralKey !== undefined) this.lastForcedDeferralKey = this.forcedDeferralKey
4195
+ }
4196
+
4197
+ /** The deferral key a forced admission scan is bounded by: the deferred
4198
+ * slugs and the occupied count. */
4199
+ private deferralKey(occupied: number): string | undefined {
4200
+ if (this.deferredAdmissions.size === 0) return undefined
4201
+ return JSON.stringify([[...this.deferredAdmissions.keys()].sort(), occupied])
3355
4202
  }
3356
4203
 
3357
4204
  /** Admit every node awaiting verification that has a slot, in slug order,
3358
- * through the janitor's own admission path. Independent of `acceptNewWork`:
3359
- * node admission is existing work, never intake. */
4205
+ * through the janitor's own admission path, then every proposer the free
4206
+ * slots allow. Independent of `acceptNewWork`: node admission is existing
4207
+ * work, never intake. */
3360
4208
  private async admitWaitingNodes(
3361
4209
  report: TickReport,
3362
4210
  launched: Set<string>,
3363
4211
  opts: TickOpts,
4212
+ ): Promise<void> {
4213
+ const entries = await this.repoBuildDigests()
4214
+ if (!entries.some(({ digest }) => digest.kind === 'node' && digest.terminal === undefined))
4215
+ return
4216
+ // An optimization node's proposer: exhausted stops, filings and new
4217
+ // requests, chosen from this pass's digests alone. Proposing is the
4218
+ // node's own work, never intake, so it runs whether or not new work is
4219
+ // accepted. One clock reading serves every stage of the pass.
4220
+ const now = this.deps.clock()
4221
+ await this.advanceOptimizationNodes(report, opts, entries, now)
4222
+ if (this.outOfBudget(opts)) return
4223
+ const builds = (await this.capacityBuilds()).sort((a, b) =>
4224
+ a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0,
4225
+ )
4226
+ await this.releaseStrandedNodeWorkspaces(builds, now, launched, report, opts)
4227
+ if (this.outOfBudget(opts)) return
4228
+ const waiting = builds.filter(
4229
+ (build) =>
4230
+ slotRequest(build, now) === 'verification' ||
4231
+ (nodeMeasurementDue(build.state) &&
4232
+ !proposeStarted(build.state) &&
4233
+ slotRequest({ ...build, workspace: false }, now) === 'verification'),
4234
+ )
4235
+ const before = launched.size
4236
+ for (const build of waiting) {
4237
+ if (this.outOfBudget(opts)) return
4238
+ await this.admitNode(build, now, report, launched)
4239
+ }
4240
+ await this.admitProposers(builds, now, launched.size - before, report, launched, opts)
4241
+ }
4242
+
4243
+ /** One waiting node's admission: a measurement or its integration
4244
+ * verification, through the janitor's own admission path. */
4245
+ private async admitNode(
4246
+ { record, state }: CapacityBuild,
4247
+ now: Date,
4248
+ report: TickReport,
4249
+ launched: Set<string>,
3364
4250
  ): Promise<void> {
3365
4251
  if (
3366
- !(await this.repoBuildDigests()).some(
3367
- ({ digest }) => digest.kind === 'node' && digest.terminal === undefined,
3368
- )
4252
+ launched.has(record.slug) ||
4253
+ this.hasLiveExecutionLease(record) ||
4254
+ !state.nodeOpened ||
4255
+ !janitorDue(state.janitor, now)
3369
4256
  )
3370
4257
  return
3371
- const now = this.deps.clock()
3372
- const waiting = (await this.capacityBuilds())
3373
- .filter((build) => slotRequest(build, now) === 'verification')
3374
- .sort((a, b) => (a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0))
3375
- for (const { record, state } of waiting) {
4258
+ await withForgeRequestContext({ build: record.slug }, async () => {
4259
+ try {
4260
+ if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
4261
+ if (nodeMeasurementDue(state)) await this.prepareNodeMeasurement(record, report, launched)
4262
+ else await this.prepareIntegration(record, state, report, launched)
4263
+ } catch (error) {
4264
+ rethrowAuthorityLapse(error)
4265
+ report.janitorDiagnostics.push(
4266
+ `build ${record.slug}: node admission failed — ${String(error)}`,
4267
+ )
4268
+ }
4269
+ })
4270
+ }
4271
+
4272
+ /**
4273
+ * Release every optimization node workspace that no work owns
4274
+ * (`strandedNodeWorkspace`), over the capacity states this pass already
4275
+ * loaded: no read for a node that holds none. A released entry is updated
4276
+ * in place, so this pass's admission sees the node free.
4277
+ */
4278
+ private async releaseStrandedNodeWorkspaces(
4279
+ builds: CapacityBuild[],
4280
+ now: Date,
4281
+ launched: Set<string>,
4282
+ report: TickReport,
4283
+ opts: TickOpts,
4284
+ ): Promise<void> {
4285
+ for (const build of builds) {
4286
+ if (launched.has(build.record.slug) || !strandedNodeWorkspace(build, now)) continue
3376
4287
  if (this.outOfBudget(opts)) return
3377
- if (
3378
- launched.has(record.slug) ||
3379
- this.hasLiveExecutionLease(record) ||
3380
- !state.nodeOpened ||
3381
- !janitorDue(state.janitor, now)
3382
- )
3383
- continue
4288
+ const { record } = build
3384
4289
  await withForgeRequestContext({ build: record.slug }, async () => {
3385
4290
  try {
3386
- if (!(await this.nodeHasCapacity(record.slug))) return
3387
- await this.prepareIntegration(record, state, report, launched)
4291
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4292
+ if (openWorkspace(facts)) await this.releaseWorkspace(record.slug, facts)
4293
+ const current = await this.store.buildFacts(record.slug)
4294
+ build.workspace = current.workspace !== null
4295
+ build.state = current.state
3388
4296
  } catch (error) {
3389
4297
  rethrowAuthorityLapse(error)
3390
4298
  report.janitorDiagnostics.push(
3391
- `build ${record.slug}: node admission failed — ${String(error)}`,
4299
+ `build ${record.slug}: node workspace release failed — ${String(error)}`,
3392
4300
  )
3393
4301
  }
3394
4302
  })
3395
4303
  }
3396
4304
  }
3397
4305
 
3398
- private async nodeHasCapacity(slug: string): Promise<boolean> {
4306
+ /**
4307
+ * Withdraw stale proposal requests and admit proposers (SPEC §13.1.1), over
4308
+ * the capacity states `admitWaitingNodes` already loaded: one capacity
4309
+ * computation, and no read for a waiter beyond the free slots.
4310
+ *
4311
+ * An undeposited request with no admitted session is withdrawn once it no
4312
+ * longer fits current state (a stop, a spent budget, or a room shrunk below
4313
+ * its allowance); the node requests again at the current room once room
4314
+ * exists. A session that already started keeps its allowance and resumes.
4315
+ * `only` restricts the pass to one deferred proposer's retry.
4316
+ */
4317
+ private async admitProposers(
4318
+ builds: CapacityBuild[],
4319
+ now: Date,
4320
+ admittedThisPass: number,
4321
+ report: TickReport,
4322
+ launched: Set<string>,
4323
+ opts: TickOpts,
4324
+ only?: string,
4325
+ ): Promise<void> {
4326
+ const proposers = builds.filter(
4327
+ (build) =>
4328
+ build.state.kind === 'node' &&
4329
+ proposeRunDue(build.state.optimization) &&
4330
+ (only === undefined || build.record.slug === only),
4331
+ )
4332
+ if (proposers.length === 0) return
4333
+ const projection = dispatchCapacity(builds, this.deps.config.capacity, now, undefined, {
4334
+ urgentClaims: this.urgentClaims(),
4335
+ startRequests: this.startClaims(),
4336
+ })
4337
+ let occupied = projection.occupied + admittedThisPass
4338
+ for (const build of proposers) {
4339
+ if (this.outOfBudget(opts)) return
4340
+ const { record, state } = build
4341
+ if (
4342
+ launched.has(record.slug) ||
4343
+ this.hasLiveExecutionLease(record) ||
4344
+ build.provisioning ||
4345
+ (nodeMeasurementDue(state) && !proposeStarted(state))
4346
+ )
4347
+ continue
4348
+ await withForgeRequestContext({ build: record.slug }, async () => {
4349
+ try {
4350
+ const withdrawal = proposeStarted(state)
4351
+ ? undefined
4352
+ : proposalWithdrawalDue(state.optimization, now)
4353
+ if (withdrawal !== undefined) {
4354
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4355
+ actor: DISPATCHER,
4356
+ type: 'optimization.proposal-withdrawn',
4357
+ payload: { request: state.optimization!.proposal!.id, reason: withdrawal },
4358
+ } satisfies EventWrite<'optimization.proposal-withdrawn'>)
4359
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4360
+ if (strandedNodeWorkspace({ ...build, state: facts.state }, now))
4361
+ await this.releaseWorkspace(record.slug, facts)
4362
+ return
4363
+ }
4364
+ // A workspace already holds this node's slot (a proposer that lost
4365
+ // its runner); otherwise it needs a free one.
4366
+ const holding = build.workspace
4367
+ if (
4368
+ (holding
4369
+ ? state.status === 'paused' || state.status === 'blocked'
4370
+ : slotRequest(build, now) !== 'propose') ||
4371
+ !state.nodeOpened ||
4372
+ !janitorDue(state.janitor, now)
4373
+ )
4374
+ return
4375
+ if (!holding) {
4376
+ if (!this.accountsAvailable()) return
4377
+ const outcome = this.slotAdmission(
4378
+ record.slug,
4379
+ buildPriority(state),
4380
+ occupied,
4381
+ projection,
4382
+ )
4383
+ if (outcome === 'defer') this.deferredAdmissions.set(record.slug, 'proposer')
4384
+ if (outcome !== 'admit') return
4385
+ occupied++
4386
+ }
4387
+ await this.launchProposer(record, report, launched)
4388
+ } catch (error) {
4389
+ rethrowAuthorityLapse(error)
4390
+ report.janitorDiagnostics.push(
4391
+ `build ${record.slug}: proposer admission failed — ${String(error)}`,
4392
+ )
4393
+ }
4394
+ })
4395
+ }
4396
+ }
4397
+
4398
+ /**
4399
+ * The creation keys of attempts a node deposited and has not recorded yet,
4400
+ * from the build digests alone: no per-node read, and one set lookup per
4401
+ * ready ticket. A node digest without the optimization signal (an older
4402
+ * peer) fails closed: every ready ticket with a creation key is withheld.
4403
+ */
4404
+ private async optimizationCreationHolds(): Promise<{
4405
+ holds: Map<string, { node: string; request: string }>
4406
+ failure?: string
4407
+ }> {
4408
+ const holds = new Map<string, { node: string; request: string }>()
4409
+ for (const { record, digest } of await this.repoBuildDigests()) {
4410
+ if (digest.terminal !== undefined) continue
4411
+ let signal: ReturnType<typeof digestOptimization>
4412
+ try {
4413
+ signal = digestOptimization(digest)
4414
+ } catch (error) {
4415
+ if (!(error instanceof BuildDigestCapabilityError)) throw error
4416
+ return { holds, failure: error.message }
4417
+ }
4418
+ const proposal = signal ? signal.proposal : undefined
4419
+ for (const id of proposal?.deposited?.ids ?? [])
4420
+ holds.set(attemptCreationKey(this.deps.repo, record.slug, id), {
4421
+ node: record.slug,
4422
+ request: proposal!.request,
4423
+ })
4424
+ }
4425
+ return { holds }
4426
+ }
4427
+
4428
+ /** Provision a workspace for a starting or progress measurement. */
4429
+ private async prepareNodeMeasurement(
4430
+ record: BuildRecord,
4431
+ report: TickReport,
4432
+ launched: Set<string>,
4433
+ ): Promise<void> {
4434
+ if (!record.branch || !this.accountsAvailable()) return
4435
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4436
+ if (!nodeMeasurementDue(facts.state)) return
4437
+ await this.provisionNodeAndLaunch(record, facts, report, launched)
4438
+ }
4439
+
4440
+ /** Provision the node workspace at its proposal head. */
4441
+ private async launchProposer(
4442
+ record: BuildRecord,
4443
+ report: TickReport,
4444
+ launched: Set<string>,
4445
+ ): Promise<void> {
4446
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4447
+ const proposal = facts.state.optimization?.proposal
4448
+ if (proposal === undefined || !record.branch) return
4449
+ if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
4450
+ const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
4451
+ if (kicked === 'kicked') report.provisioning++
4452
+ return
4453
+ }
4454
+ if (openWorkspace(facts) === null) {
4455
+ let handle: WorkspaceProvisionResult
4456
+ try {
4457
+ handle = await this.provisionWorkspace(record.slug, {
4458
+ repo: this.deps.checkout ?? this.deps.repo,
4459
+ baseBranch: record.branch,
4460
+ branch: record.branch,
4461
+ revision: proposal.head,
4462
+ })
4463
+ } catch (error) {
4464
+ if (await this.holdForMissingAccounts(error)) return
4465
+ throw error
4466
+ }
4467
+ await this.store.append(record.slug, {
4468
+ actor: DISPATCHER,
4469
+ type: 'workspace.provisioned',
4470
+ payload: {
4471
+ provider: handle.provider,
4472
+ ref: handle.ref,
4473
+ path: handle.path,
4474
+ localPath: handle.localPath,
4475
+ remote: false,
4476
+ branch: handle.branch,
4477
+ base: handle.base,
4478
+ ...(handle.restorationSkipped?.length
4479
+ ? { restorationSkipped: handle.restorationSkipped }
4480
+ : {}),
4481
+ },
4482
+ })
4483
+ }
4484
+ await this.launch(record.slug, launched, report)
4485
+ }
4486
+
4487
+ /**
4488
+ * The optimization proposer stage (SPEC §13.1.1). Nodes are selected from
4489
+ * build digests alone: a plain node, a leaf, a stopped or idle optimization
4490
+ * node, and a deferred node with no wake since its deferral cost no read.
4491
+ * Every build read this stage makes precedes a write that changes the
4492
+ * node's digest. An older peer's digest without the optimization signal
4493
+ * fails the stage closed, never falling back to per-node reads.
4494
+ */
4495
+ private async advanceOptimizationNodes(
4496
+ report: TickReport,
4497
+ opts: TickOpts,
4498
+ entries: { record: BuildRecord; digest: BuildDigest }[],
4499
+ now: Date,
4500
+ ): Promise<void> {
4501
+ const due: { record: BuildRecord; kind: 'exhausted' | 'filing' | 'request' }[] = []
4502
+ try {
4503
+ for (const { record, digest } of entries) {
4504
+ if (digest.terminal !== undefined || !digest.nodeOpened) continue
4505
+ const signal = digestOptimization(digest)
4506
+ if (!signal) continue
4507
+ const kind = signalDue(signal, now, (digest.compatibility?.decisiveFacts ?? 0) > 0)
4508
+ // A node whose runner is working requests nothing until it ends.
4509
+ if (
4510
+ kind === 'request' &&
4511
+ (digest.executionOpen === true || this.hasLiveExecutionLease(record))
4512
+ )
4513
+ continue
4514
+ if (kind !== undefined) due.push({ record, kind })
4515
+ }
4516
+ } catch (error) {
4517
+ if (!(error instanceof BuildDigestCapabilityError)) throw error
4518
+ report.janitorDiagnostics.push(`optimization proposing skipped — ${error.message}`)
4519
+ return
4520
+ }
4521
+ for (const { record, kind } of due) {
4522
+ if (this.outOfBudget(opts)) return
4523
+ await withForgeRequestContext({ build: record.slug }, async () => {
4524
+ try {
4525
+ if (kind === 'exhausted') await this.recordExhausted(record.slug)
4526
+ else if (kind === 'filing') await this.fileProposedAttempts(record, now)
4527
+ else await this.requestProposal(record, now)
4528
+ } catch (error) {
4529
+ rethrowAuthorityLapse(error)
4530
+ report.janitorDiagnostics.push(
4531
+ `build ${record.slug}: optimization proposing failed — ${String(error)}`,
4532
+ )
4533
+ }
4534
+ })
4535
+ }
4536
+ }
4537
+
4538
+ /** Record a new proposal request, or a durable deferral naming what
4539
+ * blocks the proposer. */
4540
+ private async requestProposal(record: BuildRecord, now: Date): Promise<void> {
4541
+ const { state } = await this.store.buildFacts(record.slug)
4542
+ const optimization = state.optimization
4543
+ if (optimization === undefined || !record.branch) return
4544
+ if (!proposerAdmissible(state, now)) {
4545
+ const reason = proposerBlocker(state)
4546
+ if (reason !== undefined)
4547
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4548
+ actor: DISPATCHER,
4549
+ type: 'optimization.proposal-deferred',
4550
+ payload: { reason },
4551
+ } satisfies EventWrite<'optimization.proposal-deferred'>)
4552
+ return
4553
+ }
4554
+ const head = await this.baseSha(record.branch)
4555
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4556
+ actor: DISPATCHER,
4557
+ type: 'optimization.proposal-requested',
4558
+ payload: {
4559
+ id: this.deps.ids('proposal'),
4560
+ head,
4561
+ room: proposerRoom(optimization, now),
4562
+ budgetUsed: {
4563
+ attempts: optimization.attempts.filed,
4564
+ hours: optimizationElapsedHours(optimization, now),
4565
+ },
4566
+ },
4567
+ } satisfies EventWrite<'optimization.proposal-requested'>)
4568
+ }
4569
+
4570
+ /** Two consecutive empty proposals stop the node with cause `exhausted`.
4571
+ * Only the cause is recorded here; what a stop does to running attempts
4572
+ * belongs to the stop policy. */
4573
+ private async recordExhausted(slug: string): Promise<void> {
4574
+ const { state } = await this.store.buildFacts(slug)
4575
+ if (!exhaustedStopDue(state.optimization)) return
4576
+ await this.store.appendIfCurrent(slug, state.lastSeq, {
4577
+ actor: DISPATCHER,
4578
+ type: 'optimization.stopped',
4579
+ payload: { cause: 'exhausted', mode: state.optimization!.objective.stop.mode },
4580
+ } satisfies EventWrite<'optimization.stopped'>)
4581
+ }
4582
+
4583
+ /**
4584
+ * File a deposited proposal: one ready ticket per proposal, targeting the
4585
+ * node, each created under a key derived from the node and proposal id so
4586
+ * a retry after a crash adopts what an earlier attempt created. The
4587
+ * deposit is a commitment: every deposited proposal is filed and recorded
4588
+ * in one `attempts-proposed`, whatever revisions or stops landed since.
4589
+ * Until that record lands, intake withholds these keys.
4590
+ */
4591
+ private async fileProposedAttempts(record: BuildRecord, now: Date): Promise<void> {
4592
+ const { state } = await this.store.buildFacts(record.slug)
4593
+ const proposal = state.optimization?.proposal
4594
+ const deposited = proposal?.deposited
4595
+ if (proposal === undefined || deposited === undefined) return
4596
+ const escalate = async (question: string) => {
4597
+ await this.store.append(record.slug, {
4598
+ actor: KERNEL,
4599
+ type: 'escalation.raised',
4600
+ payload: {
4601
+ id: this.deps.ids('esc'),
4602
+ phase: 'propose',
4603
+ round: proposal.round,
4604
+ source: 'agent',
4605
+ question,
4606
+ },
4607
+ } satisfies EventWrite<'escalation.raised'>)
4608
+ }
4609
+ // A filing this node already escalated waits for the answer, durably.
4610
+ if (
4611
+ state.openEscalations.some(
4612
+ (escalation) => escalation.phase === 'propose' && escalation.round === proposal.round,
4613
+ )
4614
+ ) {
4615
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4616
+ actor: DISPATCHER,
4617
+ type: 'optimization.proposal-deferred',
4618
+ payload: { reason: 'blocked' },
4619
+ } satisfies EventWrite<'optimization.proposal-deferred'>)
4620
+ return
4621
+ }
4622
+ const artifact = await this.store.getArtifact(
4623
+ record.slug,
4624
+ deposited.artifact.kind,
4625
+ deposited.artifact.rev,
4626
+ )
4627
+ let document: ReturnType<typeof proposalsDocumentSchema.parse> | undefined
4628
+ try {
4629
+ if (artifact !== null)
4630
+ document = proposalsDocumentSchema.parse(
4631
+ JSON.parse(new TextDecoder().decode(artifact.content)),
4632
+ )
4633
+ } catch {
4634
+ document = undefined
4635
+ }
4636
+ if (
4637
+ document === undefined ||
4638
+ document.proposals.map((entry) => entry.id).join('\u0000') !== deposited.ids.join('\u0000')
4639
+ ) {
4640
+ await escalate(
4641
+ `Cannot file proposal ${proposal.id}: its attempts artifact ` +
4642
+ `${deposited.artifact.kind}@${deposited.artifact.rev} is missing or does not match the deposit.`,
4643
+ )
4644
+ return
4645
+ }
4646
+ const tickets = this.deps.tickets
4647
+ if (document.proposals.length > 0 && !tickets.integrationTree) {
4648
+ await escalate(
4649
+ `Cannot file proposal ${proposal.id}: ticket source ${tickets.name} lacks the ` +
4650
+ 'integrationTree capability, so it cannot create attempts that target this node.',
4651
+ )
4652
+ return
4653
+ }
4654
+ const node = record.ticket
4655
+ ? resolveTicketRef(
4656
+ this.store.repositoryFacts().ticketMigrations,
4657
+ record.ticket,
4658
+ tickets.name,
4659
+ record.slug,
4660
+ )
4661
+ : undefined
4662
+ if (document.proposals.length > 0 && node === undefined) {
4663
+ await escalate(`Cannot file proposal ${proposal.id}: the node build has no ticket to target.`)
4664
+ return
4665
+ }
4666
+ // Attempts are dispatchable at creation: they carry every ready gate, plus
4667
+ // any configured creation labels. The source applies the ready assignee
4668
+ // itself, also to an adopted ticket.
4669
+ const ready = readyCriteria(this.deps.config)
4670
+ const assignees = creationAssignees(this.deps.config.tickets)
4671
+ const labels = creationLabels(this.deps.config.tickets, ready.labels) ?? []
4672
+ const filed: EventPayload<'optimization.attempts-proposed'>['proposals'] = []
4673
+ for (const entry of document.proposals) {
4674
+ const ticket = await tickets.create(
4675
+ {
4676
+ kind: 'work',
4677
+ target: node!.id,
4678
+ title: entry.title,
4679
+ body: entry.body,
4680
+ ...(labels.length > 0 ? { labels } : {}),
4681
+ ...(assignees !== undefined ? { assignees } : {}),
4682
+ },
4683
+ {
4684
+ state: ready.state,
4685
+ idempotencyKey: attemptCreationKey(this.deps.repo, record.slug, entry.id),
4686
+ idempotencyKeyReservedAt: deposited.at,
4687
+ ...(ready.assignee !== undefined ? { readyAssignee: ready.assignee } : {}),
4688
+ },
4689
+ )
4690
+ filed.push({
4691
+ id: entry.id,
4692
+ ticket: ticket.ref,
4693
+ title: entry.title,
4694
+ strategy: entry.strategy,
4695
+ })
4696
+ }
4697
+ const current = (await this.store.buildFacts(record.slug)).state
4698
+ if (current.optimization?.proposal?.id !== proposal.id) return
4699
+ await this.store.appendIfCurrent(record.slug, current.lastSeq, {
4700
+ actor: DISPATCHER,
4701
+ type: 'optimization.attempts-proposed',
4702
+ payload: {
4703
+ request: proposal.id,
4704
+ proposals: filed,
4705
+ ...(document.proposals.length === 0 && document.reason !== undefined
4706
+ ? { reason: document.reason }
4707
+ : {}),
4708
+ },
4709
+ } satisfies EventWrite<'optimization.attempts-proposed'>)
4710
+ // A crash or failure before this release, or a live lease now, leaves the
4711
+ // workspace to `releaseStrandedNodeWorkspaces` on a later pass.
4712
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4713
+ if (
4714
+ strandedNodeWorkspace(
4715
+ {
4716
+ record,
4717
+ state: facts.state,
4718
+ workspace: openWorkspace(facts) !== null,
4719
+ provisioning: this.continuations.has(record.slug),
4720
+ },
4721
+ now,
4722
+ )
4723
+ )
4724
+ await this.releaseWorkspace(record.slug, facts)
4725
+ await this.recordExhausted(record.slug)
4726
+ }
4727
+
4728
+ /** A node's admission into a free slot. A verification or measurement
4729
+ * request (`reserving`) yields to urgent work ahead of it and defers while
4730
+ * urgent claims are unevaluated. A node that already holds its slot — a
4731
+ * restack-conflict reconcile, or runner work that kept its workspace across
4732
+ * a failed launch or expired lease — only needs the node's own room:
4733
+ * priority orders free slots, never one the node owns. */
4734
+ private async nodeHasCapacity(
4735
+ slug: string,
4736
+ reserving = true,
4737
+ ): Promise<'admit' | 'wait' | 'defer'> {
3399
4738
  const builds = await this.capacityBuilds()
3400
- return (
3401
- nodeCapacity(
3402
- builds,
3403
- slug,
3404
- this.deps.clock(),
3405
- migrationIdentity(this.store.repositoryFacts().ticketMigrations, this.deps.tickets.name),
3406
- ).occupied < this.deps.config.capacity
4739
+ const now = this.deps.clock()
4740
+ const identity = migrationIdentity(
4741
+ this.store.repositoryFacts().ticketMigrations,
4742
+ this.deps.tickets.name,
3407
4743
  )
4744
+ const { occupied } = nodeCapacity(builds, slug, now, identity)
4745
+ const node = builds.find((build) => build.record.slug === slug)
4746
+ if (!reserving || (node && occupiesCapacity(node, now)))
4747
+ return occupied < this.deps.config.capacity ? 'admit' : 'wait'
4748
+ const outcome = this.slotAdmission(
4749
+ slug,
4750
+ node ? buildPriority(node.state) : 'normal',
4751
+ occupied,
4752
+ dispatchCapacity(builds, this.deps.config.capacity, now, identity, {
4753
+ urgentClaims: this.urgentClaims(),
4754
+ startRequests: this.startClaims(),
4755
+ }),
4756
+ )
4757
+ if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
4758
+ this.deferredAdmissions.set(slug, 'node')
4759
+ return outcome
3408
4760
  }
3409
4761
 
3410
4762
  private hasLiveExecutionLease(record: BuildRecord): boolean {
@@ -3431,9 +4783,498 @@ export class Dispatcher {
3431
4783
  if (node.nodeIssueLinks?.builds.includes(slug)) return
3432
4784
  await this.store.append(state.target.build, {
3433
4785
  actor: DISPATCHER,
3434
- type: 'node.issue-links-recorded',
3435
- payload: { build: slug, issueLinks },
3436
- } satisfies EventWrite<'node.issue-links-recorded'>)
4786
+ type: 'node.issue-links-recorded',
4787
+ payload: { build: slug, issueLinks },
4788
+ } satisfies EventWrite<'node.issue-links-recorded'>)
4789
+ }
4790
+
4791
+ // ── Optimization attempts (SPEC §15.7, RFC 0005 §6.3–§7.5) ─────────────────
4792
+
4793
+ /** The child's attempt identity on its optimization node, under the
4794
+ * repository's ticket-migration identity: in flight, settled with its
4795
+ * rejected-role move pending, or not an attempt. */
4796
+ private attemptOf(
4797
+ node: Pick<BuildState, 'optimization'>,
4798
+ record: Pick<BuildRecord, 'ticket' | 'slug'>,
4799
+ ): { status: AttemptStatus; attempt?: InFlightAttempt | PendingRejection } {
4800
+ if (node.optimization === undefined || record.ticket === undefined) return { status: 'none' }
4801
+ const key = this.attemptKey()
4802
+ const inFlight = optimizationAttempt(node.optimization, record.ticket, key)
4803
+ if (inFlight) return { status: 'in-flight', attempt: inFlight }
4804
+ const rejection = optimizationRejection(node.optimization, record.ticket, key)
4805
+ if (rejection) return { status: 'settled', attempt: rejection }
4806
+ return { status: 'none' }
4807
+ }
4808
+
4809
+ private attemptKey(): (ref: TicketRef) => string {
4810
+ const identity = migrationIdentity(
4811
+ this.store.repositoryFacts().ticketMigrations,
4812
+ this.deps.tickets.name,
4813
+ )
4814
+ return (ref) => identity(ref)
4815
+ }
4816
+
4817
+ /** The nonterminal children of `nodeSlug` in this tick's janitor listing,
4818
+ * indexed once per tick. Attempts ride in the work set while nonterminal,
4819
+ * and a build created later in the tick has never been overtaken, so it
4820
+ * cannot hold the turn. */
4821
+ private childrenOf(nodeSlug: string): BuildRecord[] {
4822
+ const entries = this.janitorEntries
4823
+ if (entries === undefined)
4824
+ throw new Error('the landing turn reads the janitor listing; run it inside the janitor')
4825
+ if (this.nodeChildren === undefined) {
4826
+ const index = new Map<string, BuildRecord[]>()
4827
+ for (const { record, digest } of entries) {
4828
+ if (digest.terminal !== undefined || record.ticket === undefined) continue
4829
+ for (const target of digestNodeTargets(digest)) {
4830
+ const children = index.get(target)
4831
+ if (children) children.push(record)
4832
+ else index.set(target, [record])
4833
+ }
4834
+ }
4835
+ this.nodeChildren = index
4836
+ }
4837
+ return this.nodeChildren.get(nodeSlug) ?? []
4838
+ }
4839
+
4840
+ /** The gate's verdict for one child of an optimization node, from the
4841
+ * child's and the node's reduced facts. The turn costs at most one reduced
4842
+ * read per other in-flight attempt, and only for a would-be request or
4843
+ * landing; its candidates come from the tick's janitor listing, so it never
4844
+ * lists the repository. */
4845
+ private async landingVerdict(
4846
+ record: BuildRecord,
4847
+ nodeSlug: string,
4848
+ ): Promise<{
4849
+ verdict: LandingGateVerdict
4850
+ state: BuildState
4851
+ node: BuildState
4852
+ status: AttemptStatus
4853
+ attempt?: InFlightAttempt | PendingRejection
4854
+ candidate?: string
4855
+ nodeHead?: string
4856
+ }> {
4857
+ const facts = await this.store.buildFacts(record.slug)
4858
+ const state = facts.state
4859
+ const node = (await this.store.buildFacts(nodeSlug)).state
4860
+ const digest = node.optimization!
4861
+ const { status, attempt } = this.attemptOf(node, record)
4862
+ const candidate = candidateHead(state)
4863
+ // The head the child would land on, once its candidate sits on it: a
4864
+ // measurement against any other base would be stale before it lands.
4865
+ const parent =
4866
+ state.kind === 'node'
4867
+ ? state.integration?.cycle?.parent
4868
+ : (facts.log.restack.completed?.targetBase ?? facts.log.restack.initialBase)
4869
+ const observed =
4870
+ state.kind === 'node' ? state.nodeRestack?.observedParent?.sha : facts.log.restack.target?.sha
4871
+ const nodeHead = observed !== undefined && observed === parent ? observed : undefined
4872
+ const lm = state.landingMeasurement
4873
+ const input = {
4874
+ digest,
4875
+ attempt: status,
4876
+ lm,
4877
+ candidate,
4878
+ nodeHead,
4879
+ self: record.slug,
4880
+ regressionAnswered:
4881
+ lm?.request !== undefined &&
4882
+ state.answeredEscalations.some((e) => e.id === regressionEscalationId(lm.request!.id)),
4883
+ }
4884
+ let verdict = landingMeasurementGate(input)
4885
+ if (verdict === 'land' || verdict === 'request') {
4886
+ const key = this.attemptKey()
4887
+ const self = record.ticket && key(record.ticket)
4888
+ if (digest.inFlight.some((entry) => key(entry.ticket) !== self)) {
4889
+ const wanted = new Set(digest.inFlight.map((entry) => key(entry.ticket)))
4890
+ const candidates: TurnCandidate[] =
4891
+ record.ticket !== undefined ? [{ slug: record.slug, ticket: record.ticket, state }] : []
4892
+ for (const other of this.childrenOf(nodeSlug)) {
4893
+ if (other.slug === record.slug || !wanted.has(key(other.ticket!))) continue
4894
+ const otherState = (await this.store.buildFacts(other.slug)).state
4895
+ if (otherState.target?.build !== nodeSlug) continue
4896
+ candidates.push({ slug: other.slug, ticket: other.ticket!, state: otherState })
4897
+ }
4898
+ verdict = landingMeasurementGate({
4899
+ ...input,
4900
+ turn: selectTurnHolder(digest, candidates, key),
4901
+ })
4902
+ }
4903
+ }
4904
+ return { verdict, state, node, status, attempt, candidate, nodeHead }
4905
+ }
4906
+
4907
+ /** Raise one kernel escalation on a child at landing, deduplicated by id
4908
+ * against open and answered escalations. */
4909
+ private async raiseLandingEscalation(
4910
+ slug: string,
4911
+ state: BuildState,
4912
+ id: string,
4913
+ question: string,
4914
+ ): Promise<void> {
4915
+ if (
4916
+ state.openEscalations.some((e) => e.id === id) ||
4917
+ state.answeredEscalations.some((e) => e.id === id)
4918
+ )
4919
+ return
4920
+ await this.store.append(slug, {
4921
+ actor: KERNEL,
4922
+ type: 'escalation.raised',
4923
+ payload: { id, phase: 'finalize', source: 'agent', question: question.slice(0, 8000) },
4924
+ } satisfies EventWrite<'escalation.raised'>)
4925
+ }
4926
+
4927
+ /**
4928
+ * The measurement landing gate for a ready, authorized child of an
4929
+ * optimization node (SPEC §15.7). Returns the measured pair when the child
4930
+ * may land now; otherwise it did this poll's one action (request a
4931
+ * measurement, escalate, settle and close) or waits, and returns a reason
4932
+ * the caller stops on. The node writer lease is never held here.
4933
+ */
4934
+ private async optimizationLandingGate(
4935
+ record: BuildRecord,
4936
+ nodeSlug: string,
4937
+ workspacePath: string,
4938
+ pr: number,
4939
+ ): Promise<
4940
+ | { kind: 'land'; measured: { candidate: string; baseline: string } }
4941
+ | { kind: 'wait' }
4942
+ | { kind: 'closed'; result: Awaited<ReturnType<NonNullable<Forge['closePr']>>> }
4943
+ > {
4944
+ const gate = await this.landingVerdict(record, nodeSlug)
4945
+ const { verdict, state, node, attempt, candidate, nodeHead } = gate
4946
+ const digest = node.optimization!
4947
+ switch (verdict) {
4948
+ case 'land':
4949
+ return { kind: 'land', measured: { candidate: candidate!, baseline: nodeHead! } }
4950
+ case 'request': {
4951
+ if (gate.status === 'in-flight') {
4952
+ const harnessId = harnessEscalationId(candidate!)
4953
+ // An answered harness escalation still never measures this head.
4954
+ if (
4955
+ state.openEscalations.some((e) => e.id === harnessId) ||
4956
+ state.answeredEscalations.some((e) => e.id === harnessId)
4957
+ )
4958
+ return { kind: 'wait' }
4959
+ const recorded = headPathsFor(state, candidate)
4960
+ // Wait for the head's recorded paths, as `landing.deferred` does.
4961
+ if (!recorded.recorded) return { kind: 'wait' }
4962
+ const paths =
4963
+ recorded.record.total > recorded.record.preview.length
4964
+ ? (await readHeadPaths(this.store, record.slug, recorded.record)).paths
4965
+ : recorded.record.preview
4966
+ const matches = compilePathSelectors(digest.objective.metric.harness)
4967
+ const edited = paths.filter((path) => matches(path))
4968
+ if (edited.length > 0) {
4969
+ await this.raiseLandingEscalation(
4970
+ record.slug,
4971
+ state,
4972
+ harnessId,
4973
+ `Attempt head ${candidate} changes ${edited.length} harness path(s) of optimization node ${nodeSlug}: ${edited.slice(0, 20).join(', ')}${edited.length > 20 ? ', …' : ''}. An attempt may not change how it is measured, so this candidate will not be measured or landed. Revise the attempt without the harness edit, or abort it.`,
4974
+ )
4975
+ return { kind: 'wait' }
4976
+ }
4977
+ }
4978
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4979
+ actor: DISPATCHER,
4980
+ type: 'attempt.measurement-requested',
4981
+ payload: {
4982
+ id: this.deps.ids('measure'),
4983
+ node: nodeSlug,
4984
+ candidate: candidate!,
4985
+ baseline: nodeHead!,
4986
+ harnessPin: digest.accepted.harnessPin,
4987
+ revision: digest.revision,
4988
+ metric: digest.objective.metric,
4989
+ ...(digest.objective.metric.kind === 'panel'
4990
+ ? { purpose: digest.objective.purpose }
4991
+ : {}),
4992
+ },
4993
+ })
4994
+ return { kind: 'wait' }
4995
+ }
4996
+ case 'regressed': {
4997
+ const result = state.landingMeasurement!.result!
4998
+ const medians = result.medians
4999
+ ? `baseline median ${result.medians.baseline}, candidate median ${result.medians.candidate}`
5000
+ : `win rate ${result.winRate}`
5001
+ await this.raiseLandingEscalation(
5002
+ record.slug,
5003
+ state,
5004
+ regressionEscalationId(result.request),
5005
+ `Child ${record.slug} regresses optimization node ${nodeSlug}'s metric beyond epsilon: ${medians}, delta ${result.delta}, epsilon ${measurementThreshold(digest.objective, result)} (measured ${candidate} on ${nodeHead}). It will not land. Answer to measure it again, or abort it.`,
5006
+ )
5007
+ return { kind: 'wait' }
5008
+ }
5009
+ case 'no-improvement': {
5010
+ const result = state.landingMeasurement!.result!
5011
+ await settleAttempt(
5012
+ this.store,
5013
+ nodeSlug,
5014
+ {
5015
+ proposal: attempt!.proposal,
5016
+ ticket: attempt!.ticket,
5017
+ build: record.slug,
5018
+ ...(record.branch !== undefined && attemptBranchPublished(state)
5019
+ ? { branch: record.branch }
5020
+ : {}),
5021
+ },
5022
+ 'no-improvement',
5023
+ { measurement: settlementMeasurement(result) },
5024
+ )
5025
+ return this.closeSettledAttempt(record, workspacePath, pr)
5026
+ }
5027
+ case 'settled':
5028
+ return this.closeSettledAttempt(record, workspacePath, pr)
5029
+ case 'pending':
5030
+ case 'wait-turn':
5031
+ case 'wait-progress':
5032
+ case 'stale':
5033
+ return { kind: 'wait' }
5034
+ }
5035
+ }
5036
+
5037
+ /** Settle a merged attempt `accepted` with the measurement of the head
5038
+ * that landed. Without one (a forge-side human merge bypassed the gate) it
5039
+ * marks the attempt `attempt.merged-unmeasured` on the node, where it keeps
5040
+ * its slot until an operator settles it, and records one followup. */
5041
+ private async settleMergedAttempt(
5042
+ record: BuildRecord,
5043
+ state: BuildState,
5044
+ sha: string,
5045
+ ): Promise<void> {
5046
+ const attempt = await this.terminalAttempt(record, state)
5047
+ if (attempt.status !== 'in-flight') return
5048
+ const identity = {
5049
+ proposal: attempt.attempt!.proposal,
5050
+ ticket: attempt.attempt!.ticket,
5051
+ }
5052
+ const measured = mergedAttemptMeasurement(state.landingMeasurement, attempt.node, sha)
5053
+ if (measured.kind === 'measured') {
5054
+ await settleAttempt(
5055
+ this.store,
5056
+ attempt.node,
5057
+ { ...identity, build: record.slug },
5058
+ 'accepted',
5059
+ { measurement: settlementMeasurement(measured.result), head: sha },
5060
+ )
5061
+ return
5062
+ }
5063
+ const marked = await markUnmeasuredMerge(this.store, attempt.node, identity, {
5064
+ build: record.slug,
5065
+ sha,
5066
+ reason: measured.reason,
5067
+ ...(measured.measuredCandidate !== undefined
5068
+ ? { measuredCandidate: measured.measuredCandidate }
5069
+ : {}),
5070
+ })
5071
+ if (marked)
5072
+ await this.store.append(record.slug, {
5073
+ actor: KERNEL,
5074
+ type: 'observation.recorded',
5075
+ payload: {
5076
+ id: this.deps.ids('obs'),
5077
+ kind: 'followup',
5078
+ summary: `Attempt ${identity.proposal} merged as ${sha} without a landing measurement of that head (${measured.reason}), so it cannot settle as accepted. It keeps its concurrency slot on node ${attempt.node} until an operator runs \`ab objective ${attempt.node} --settle-unmeasured ${identity.proposal} --policy release-unmeasured\`.`,
5079
+ refs: [sha],
5080
+ },
5081
+ })
5082
+ }
5083
+
5084
+ /** Close a settled attempt's PR without merging. The `closed` epilogue
5085
+ * then completes the build; no implement round follows. */
5086
+ private async closeSettledAttempt(
5087
+ record: BuildRecord,
5088
+ workspacePath: string,
5089
+ pr: number,
5090
+ ): Promise<{ kind: 'closed'; result: Awaited<ReturnType<NonNullable<Forge['closePr']>>> }> {
5091
+ const closePr = this.deps.forge.closePr
5092
+ if (closePr === undefined)
5093
+ throw new Error(
5094
+ `selected forge "${this.deps.forge.name}" does not implement closePr; upgrade its plugin`,
5095
+ )
5096
+ const result = await closePr.call(this.deps.forge, workspacePath, pr)
5097
+ if (
5098
+ result.state === 'closed' &&
5099
+ (await this.store.buildFacts(record.slug)).state.prState !== 'closed'
5100
+ )
5101
+ await this.store.append(record.slug, {
5102
+ actor: DISPATCHER,
5103
+ type: 'pr.closed',
5104
+ payload: {},
5105
+ } satisfies EventWrite<'pr.closed'>)
5106
+ return { kind: 'closed', result }
5107
+ }
5108
+
5109
+ /** Whether the pair measured for landing is still the gate's `land` pair:
5110
+ * the publication-time check inside the node writer, separate from the
5111
+ * measurement-independent readiness that admits the gate. */
5112
+ private async measuredPairCurrent(
5113
+ record: BuildRecord,
5114
+ nodeSlug: string,
5115
+ pair: { candidate: string; baseline: string },
5116
+ ): Promise<boolean> {
5117
+ await this.store.refreshBuild(record.slug)
5118
+ await this.store.refreshBuild(nodeSlug)
5119
+ const gate = await this.landingVerdict(record, nodeSlug)
5120
+ return (
5121
+ gate.verdict === 'land' &&
5122
+ gate.candidate === pair.candidate &&
5123
+ gate.nodeHead === pair.baseline
5124
+ )
5125
+ }
5126
+
5127
+ /** The attempt status of a child at one of its terminal paths, from its
5128
+ * node's reduced facts: one read, not recurring. */
5129
+ private async terminalAttempt(
5130
+ record: BuildRecord,
5131
+ state: Pick<BuildState, 'target'>,
5132
+ ): Promise<{
5133
+ node: string
5134
+ status: AttemptStatus
5135
+ attempt?: InFlightAttempt | PendingRejection
5136
+ }> {
5137
+ if (state.target === undefined) return { node: '', status: 'none' }
5138
+ const node = (await this.store.buildFacts(state.target.build)).state
5139
+ return { node: state.target.build, ...this.attemptOf(node, record) }
5140
+ }
5141
+
5142
+ /**
5143
+ * The node-side duties of each settled, non-accepted attempt, once its
5144
+ * build is done: delete a declined or no-improvement attempt's published
5145
+ * build branch (SPEC §15.7), then move its ticket to the rejected role
5146
+ * (SPEC §13), the one owner of that move. An entry waits until its attempt
5147
+ * build is done, so no terminal path can hand the ticket back to triage
5148
+ * afterwards. Zero reads while nothing is pending; otherwise at most one
5149
+ * reduced read per entry with work, which admission bounds by the node's
5150
+ * concurrency. Never lists the repository.
5151
+ */
5152
+ private async sweepAttemptRejections(record: BuildRecord, state: BuildState): Promise<boolean> {
5153
+ const rejectedState = this.deps.config.tickets.rejectedState
5154
+ // Without a rejected role only a branch obligation is work to do.
5155
+ const pending = (state.optimization?.rejections ?? []).filter(
5156
+ (entry) => entry.branch !== undefined || rejectedState !== undefined,
5157
+ )
5158
+ if (pending.length === 0) return false
5159
+ let wrote = false
5160
+ for (const entry of pending) {
5161
+ let attemptRecord: BuildRecord | null = null
5162
+ let attemptState: BuildState | undefined
5163
+ if (entry.build !== undefined) {
5164
+ attemptRecord = await this.store.getBuild(entry.build)
5165
+ if (attemptRecord !== null) {
5166
+ attemptState = (await this.store.buildFacts(entry.build)).state
5167
+ if (attemptState.status !== 'done') continue
5168
+ }
5169
+ }
5170
+ if (entry.branch !== undefined) {
5171
+ const cleanup = await this.cleanupAttemptBranch(
5172
+ record,
5173
+ state,
5174
+ entry,
5175
+ attemptRecord,
5176
+ attemptState,
5177
+ )
5178
+ if (cleanup !== 'unchanged') wrote = true
5179
+ // The ticket moves only once the obligation is met, so the entry
5180
+ // keeps its slot while cleanup is pending.
5181
+ if (cleanup !== 'deleted') continue
5182
+ }
5183
+ if (rejectedState === undefined) continue
5184
+ const id = resolveTicketRef(
5185
+ this.store.repositoryFacts().ticketMigrations,
5186
+ entry.ticket,
5187
+ this.deps.tickets.name,
5188
+ entry.build,
5189
+ ).id
5190
+ const ticket = await moveTicketToRole(
5191
+ this.deps.tickets,
5192
+ this.deps.config.tickets,
5193
+ id,
5194
+ 'rejected',
5195
+ )
5196
+ const rejected = ticket.state ?? rejectedState
5197
+ await this.deps.tickets.comment(
5198
+ id,
5199
+ `attempt ${entry.proposal} settled as ${entry.outcome}; moved to ${rejected}`,
5200
+ )
5201
+ await this.store.append(record.slug, {
5202
+ actor: DISPATCHER,
5203
+ type: 'attempt.ticket-rejected',
5204
+ payload: { proposal: entry.proposal, ticket: entry.ticket, state: rejected },
5205
+ } satisfies EventWrite<'attempt.ticket-rejected'>)
5206
+ wrote = true
5207
+ }
5208
+ return wrote
5209
+ }
5210
+
5211
+ /**
5212
+ * Delete one settled attempt's published build branch and record it, or
5213
+ * record why it could not be deleted. The guards refuse any branch that is
5214
+ * not exactly this done attempt build's own, so cleanup never touches the
5215
+ * node's branch, its base, or another build's contribution. A delete of an
5216
+ * already-absent branch succeeds; a crash before the record repeats it.
5217
+ * A failure is recorded only when its error changed, and the settlement is
5218
+ * never touched, so a retry cannot change the outcome.
5219
+ */
5220
+ private async cleanupAttemptBranch(
5221
+ node: BuildRecord,
5222
+ nodeState: BuildState,
5223
+ entry: PendingRejection,
5224
+ attemptRecord: BuildRecord | null,
5225
+ attemptState: BuildState | undefined,
5226
+ ): Promise<'deleted' | 'failed' | 'unchanged'> {
5227
+ const branch = entry.branch!
5228
+ const refusal =
5229
+ entry.build === undefined
5230
+ ? 'the settlement names no attempt build'
5231
+ : attemptRecord === null || attemptState === undefined
5232
+ ? `attempt build ${entry.build} does not exist`
5233
+ : attemptRecord.branch !== branch
5234
+ ? `branch ${branch} is not attempt build ${entry.build}'s branch`
5235
+ : attemptState.target?.build !== node.slug
5236
+ ? `attempt build ${entry.build} does not target node ${node.slug}`
5237
+ : branch === node.branch ||
5238
+ branch === nodeState.baseBranch ||
5239
+ branch === this.deps.config.baseBranch
5240
+ ? `branch ${branch} is the node's own or base branch`
5241
+ : undefined
5242
+ let error = refusal
5243
+ if (error === undefined) {
5244
+ const forge = this.deps.forge
5245
+ try {
5246
+ if (forge.deleteBranch === undefined)
5247
+ throw new Error(
5248
+ `selected forge "${forge.name}" does not implement deleteBranch; upgrade its plugin`,
5249
+ )
5250
+ // Local forges treat workspacePath as a git cwd: pass the physical
5251
+ // checkout, as abort cleanup does. API forges ignore the argument.
5252
+ await forge.deleteBranch.call(forge, this.deps.checkout ?? this.deps.repo, branch)
5253
+ await this.store.append(node.slug, {
5254
+ actor: DISPATCHER,
5255
+ type: 'attempt.branch-deleted',
5256
+ payload: { proposal: entry.proposal, build: entry.build!, branch },
5257
+ } satisfies EventWrite<'attempt.branch-deleted'>)
5258
+ return 'deleted'
5259
+ } catch (caught) {
5260
+ rethrowAuthorityLapse(caught)
5261
+ if (caught instanceof ForgeCooldown) throw caught
5262
+ error = caught instanceof Error || isForgeFailure(caught) ? caught.message : String(caught)
5263
+ }
5264
+ }
5265
+ const recorded = error.slice(0, 2000) || 'branch deletion failed'
5266
+ if (entry.branchCleanupError === recorded) return 'unchanged'
5267
+ await this.store.append(node.slug, {
5268
+ actor: DISPATCHER,
5269
+ type: 'attempt.branch-cleanup-failed',
5270
+ payload: {
5271
+ proposal: entry.proposal,
5272
+ ...(entry.build !== undefined ? { build: entry.build } : {}),
5273
+ branch,
5274
+ error: recorded,
5275
+ },
5276
+ } satisfies EventWrite<'attempt.branch-cleanup-failed'>)
5277
+ return 'failed'
3437
5278
  }
3438
5279
 
3439
5280
  private async cleanupAborted(
@@ -3626,7 +5467,34 @@ export class Dispatcher {
3626
5467
  }
3627
5468
  }
3628
5469
 
3629
- if (record.ticket !== undefined && !has('abort.ticket-returned')) {
5470
+ // Abort cleanup is the only writer for aborted builds: the first abort
5471
+ // request fixes whether an operator or a node stop caused it. The node moves the ticket
5472
+ // to the rejected role, so none of the triage hand-back below applies.
5473
+ const attempt = await this.terminalAttempt(record, events.state)
5474
+ if (attempt.status === 'in-flight')
5475
+ try {
5476
+ if (events.state.prState === 'merged' && events.state.mergedSha)
5477
+ await this.settleMergedAttempt(record, events.state, events.state.mergedSha)
5478
+ else
5479
+ await settleAttempt(
5480
+ store,
5481
+ attempt.node,
5482
+ {
5483
+ proposal: attempt.attempt!.proposal,
5484
+ ticket: attempt.attempt!.ticket,
5485
+ build: record.slug,
5486
+ },
5487
+ events.latestAbort?.payload.origin?.kind === 'optimization-stop'
5488
+ ? 'stopped'
5489
+ : 'aborted',
5490
+ { note: events.latestAbort?.payload.reason?.trim() || undefined },
5491
+ )
5492
+ } catch (error) {
5493
+ fail('attempt settlement', `build ${record.slug}`, error)
5494
+ }
5495
+ const handback = record.ticket !== undefined && attempt.status === 'none'
5496
+
5497
+ if (handback && record.ticket !== undefined && !has('abort.ticket-returned')) {
3630
5498
  const label = 'autobuild:aborted'
3631
5499
  try {
3632
5500
  const id = await this.currentTicketId(record)
@@ -3678,7 +5546,7 @@ export class Dispatcher {
3678
5546
 
3679
5547
  // Reported from the checkpoint, never a re-read of the ticket, so a
3680
5548
  // retry reports exactly what the committed move did.
3681
- if (record.ticket !== undefined) {
5549
+ if (handback) {
3682
5550
  try {
3683
5551
  const returned = events.latestTicketReturned
3684
5552
  if (returned?.type !== 'abort.ticket-returned')
@@ -3708,11 +5576,54 @@ export class Dispatcher {
3708
5576
  type: 'build.completed',
3709
5577
  payload: { outcome: 'abandoned' },
3710
5578
  })
3711
- if (record.ticket !== undefined) await this.settleBuildHandback(record.slug)
5579
+ if (handback) await this.settleBuildHandback(record.slug)
3712
5580
  await this.reclaimPrAttachments(record.slug, events)
3713
5581
  report.abandoned += 1
3714
5582
  }
3715
5583
 
5584
+ /** Settle an optimization attempt its implementer declined (RFC 0005
5585
+ * §6.2): record `attempt.settled {declined}` on the node, release the
5586
+ * workspace and lease, then complete the build unmerged. The completion is
5587
+ * last, so a crash anywhere earlier retries on the next tick; an attempt no
5588
+ * longer in flight was already settled and is not settled again. The
5589
+ * node rejection sweep moves the ticket after completion. */
5590
+ private async settleDeclinedAttempt(record: BuildRecord, events: CurrentBuildFacts) {
5591
+ const store = this.store
5592
+ const declined = events.state.declined!
5593
+ const target = events.state.target
5594
+ const created = events.created
5595
+ // `ab done` refuses a decline outside an attempt, so a declined build
5596
+ // always targets a node; append nothing if that invariant is broken.
5597
+ if (target === undefined || created?.type !== 'build.created') return
5598
+ const node = (await store.buildFacts(target.build)).state
5599
+ const key = migrationIdentity(store.repositoryFacts().ticketMigrations, this.deps.tickets.name)
5600
+ const attempt = optimizationAttempt(node.optimization, created.payload.ticket, (ref) =>
5601
+ key(ref, record.slug),
5602
+ )
5603
+ if (attempt !== undefined)
5604
+ await settleAttempt(
5605
+ store,
5606
+ target.build,
5607
+ {
5608
+ proposal: attempt.proposal,
5609
+ ticket: attempt.ticket,
5610
+ build: record.slug,
5611
+ ...(record.branch !== undefined && attemptBranchPublished(events.state)
5612
+ ? { branch: record.branch }
5613
+ : {}),
5614
+ },
5615
+ 'declined',
5616
+ { note: declined.reason },
5617
+ )
5618
+ if (record.lease !== undefined) await store.releaseLease(record.slug, record.lease.holder)
5619
+ await this.releaseWorkspace(record.slug, events)
5620
+ await store.append(record.slug, {
5621
+ actor: DISPATCHER,
5622
+ type: 'build.completed',
5623
+ payload: { outcome: 'closed-unmerged' },
5624
+ } satisfies EventWrite<'build.completed'>)
5625
+ }
5626
+
3716
5627
  /** A discard is recovery from dispatcher plumbing, not judgment about the
3717
5628
  * ticket. Return it to the configured Ready state and terminalize last so
3718
5629
  * every partial cleanup is retried after a crash. */
@@ -3778,6 +5689,92 @@ export class Dispatcher {
3778
5689
  }
3779
5690
  }
3780
5691
 
5692
+ /** Forge CI on a finished leaf (§15.7). Compares this poll's observation
5693
+ * with the reduced `ciFailure` in hand and appends only on a transition, so
5694
+ * an unchanged head reads no store rows. A failure recorded for a head the
5695
+ * PR no longer has is cleared first, on the proof of this poll's PR read
5696
+ * alone. Unknown CI (no capability, any read failure, a truncated listing
5697
+ * with no visible failure) records nothing: never green, never red, and
5698
+ * never a janitor failure. */
5699
+ private async observeHeadChecks(
5700
+ record: BuildRecord,
5701
+ state: BuildState,
5702
+ prState: Extract<PrState, { state: 'open' }>,
5703
+ workspacePath: string,
5704
+ ): Promise<void> {
5705
+ if (!ciChecksObservable(state)) return
5706
+ const pr = state.pr!
5707
+ const liveHead = prState.headSha ?? pr.headSha
5708
+ let prior = state.ciFailure
5709
+ const append = async (
5710
+ transition: (current: BuildState) => boolean,
5711
+ event: EventWrite<'pr.checks-failed'> | EventWrite<'pr.checks-cleared'>,
5712
+ ): Promise<void> => {
5713
+ const current = (await this.store.buildFacts(record.slug)).state
5714
+ if (!ciChecksObservable(current) || current.pr?.headSha !== pr.headSha) return
5715
+ if (!transition(current)) return
5716
+ // A lost race is observed again on the next poll.
5717
+ await this.store.appendIfCurrent(record.slug, current.lastSeq, event)
5718
+ }
5719
+ if (prior && (prior.head !== liveHead || prior.buildHead !== pr.headSha)) {
5720
+ const stale = prior
5721
+ await append(
5722
+ (current) =>
5723
+ current.ciFailure !== undefined &&
5724
+ ciFailureKey(current.ciFailure) === ciFailureKey(stale),
5725
+ {
5726
+ actor: DISPATCHER,
5727
+ type: 'pr.checks-cleared',
5728
+ payload: { pr: pr.number, head: stale.head, cause: 'head-changed' },
5729
+ },
5730
+ )
5731
+ prior = undefined
5732
+ }
5733
+ const forge = this.deps.forge
5734
+ if (!forge.inspectHeadChecks) return
5735
+ let checks: HeadChecks
5736
+ try {
5737
+ checks = await forge.inspectHeadChecks(workspacePath, liveHead)
5738
+ } catch (error) {
5739
+ rethrowAuthorityLapse(error)
5740
+ return
5741
+ }
5742
+ if (checks.kind === 'unknown') return
5743
+ if (checks.failing.length > 0) {
5744
+ const payload = {
5745
+ pr: pr.number,
5746
+ head: liveHead,
5747
+ buildHead: pr.headSha,
5748
+ checks: checks.failing.slice(0, CI_FAILURE_PREVIEW),
5749
+ total: checks.failing.length,
5750
+ digest: failingSetDigest(checks.failing),
5751
+ }
5752
+ const key = ciFailureKey(payload)
5753
+ if (prior && ciFailureKey(prior) === key) return
5754
+ await append(
5755
+ (current) => current.ciFailure === undefined || ciFailureKey(current.ciFailure) !== key,
5756
+ { actor: DISPATCHER, type: 'pr.checks-failed', payload },
5757
+ )
5758
+ return
5759
+ }
5760
+ if (!prior) return
5761
+ const cleared = prior
5762
+ await append(
5763
+ (current) =>
5764
+ current.ciFailure !== undefined &&
5765
+ ciFailureKey(current.ciFailure) === ciFailureKey(cleared),
5766
+ {
5767
+ actor: DISPATCHER,
5768
+ type: 'pr.checks-cleared',
5769
+ payload: {
5770
+ pr: pr.number,
5771
+ head: cleared.head,
5772
+ cause: checks.pending ? 'pending' : 'passing',
5773
+ },
5774
+ },
5775
+ )
5776
+ }
5777
+
3781
5778
  /** Post-PR epilogue (§15.7): poll the forge, emit `pr.*` facts (deduped
3782
5779
  * against the reduced `prState`), release/complete, project to the ticket. */
3783
5780
  private async checkPr(
@@ -3787,6 +5784,8 @@ export class Dispatcher {
3787
5784
  source: {
3788
5785
  history: () => Promise<CurrentBuildFacts>
3789
5786
  workspace: OpenBuildWorkspace | null
5787
+ /** An execution is recorded open (started, not yet ended). */
5788
+ executionOpen: boolean
3790
5789
  observed?: (pr: Awaited<ReturnType<Forge['getPrState']>>) => void
3791
5790
  },
3792
5791
  state: BuildState,
@@ -4044,6 +6043,8 @@ export class Dispatcher {
4044
6043
  type: 'landing.command-acknowledged',
4045
6044
  payload: { commandSeq: command.seq },
4046
6045
  })
6046
+ if (!integration && !recoverLanding && prState.state === 'open')
6047
+ await this.observeHeadChecks(record, state, prState, workspacePath)
4047
6048
 
4048
6049
  // A positive conflict re-enters reconcile before any enable attempt. In
4049
6050
  // particular, an ungated fallback can never race ahead of the conflict
@@ -4071,6 +6072,7 @@ export class Dispatcher {
4071
6072
  // never blocks on guest bootstrap.
4072
6073
  const kicked = await this.ensureProvisionContinuation(record, events, 'launch')
4073
6074
  if (kicked === 'kicked') report.provisioning += 1
6075
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
4074
6076
  report.conflicted += 1
4075
6077
  return
4076
6078
  }
@@ -4189,55 +6191,92 @@ export class Dispatcher {
4189
6191
  })
4190
6192
  return
4191
6193
  }
4192
- const preflight = recoverLanding
4193
- ? undefined
4194
- : await preflightNodeLanding(
4195
- this.kernelForge(),
4196
- workspacePath,
6194
+ // A child of an optimization node also needs a fresh, decisive
6195
+ // measurement of its exact pair. Readiness above stays independent of
6196
+ // it, so a newly ready child reaches its first request.
6197
+ let measured: { candidate: string; baseline: string } | undefined
6198
+ let closure: Awaited<ReturnType<NonNullable<Forge['closePr']>>> | undefined
6199
+ const optimized = (await store.buildFacts(target.slug)).state.optimization !== undefined
6200
+ if (!recoverLanding && optimized) {
6201
+ const gate = await this.optimizationLandingGate(
6202
+ record,
6203
+ target.slug,
6204
+ workspacePath,
6205
+ pr.number,
6206
+ )
6207
+ if (gate.kind === 'wait') return
6208
+ if (gate.kind === 'land') measured = gate.measured
6209
+ else closure = gate.result
6210
+ }
6211
+ if (closure === undefined) {
6212
+ // Recovery of a reserved landing still publishes only a pair the
6213
+ // current gate lands: a revised epsilon or ruler since the
6214
+ // reservation makes the writer abandon it rather than publish, and
6215
+ // the next poll measures or settles it. A write that already
6216
+ // happened is recovered by readback before this check runs.
6217
+ const pair =
6218
+ recoverLanding && optimized && reservation
6219
+ ? { candidate: reservation.parent, baseline: reservation.expected }
6220
+ : measured
6221
+ const preflight = recoverLanding
6222
+ ? undefined
6223
+ : await preflightNodeLanding(
6224
+ this.kernelForge(),
6225
+ workspacePath,
6226
+ pr.number,
6227
+ record.branch,
6228
+ target.branch,
6229
+ )
6230
+ const reason =
6231
+ preflight ??
6232
+ (await this.withKernelRepository((kernelPath) =>
6233
+ landIntoNode({
6234
+ store,
6235
+ forge: this.kernelForge(),
6236
+ exec: forge.kernelExec ?? this.deps.exec,
6237
+ workspacePath: kernelPath,
6238
+ slug: record.slug,
6239
+ node: target.slug,
6240
+ branch: record.branch!,
6241
+ destination: target.branch!,
6242
+ pr: pr.number,
6243
+ holder: this.deps.ids('node-writer'),
6244
+ id: this.deps.ids('node-landing').replaceAll('_', '-'),
6245
+ ...(integration
6246
+ ? {
6247
+ stack: {
6248
+ head: state.integration!.cycle!.head,
6249
+ parent: state.integration!.cycle!.parent,
6250
+ cycle: state.integration!.cycle!.id,
6251
+ },
6252
+ }
6253
+ : {}),
6254
+ ...(pair !== undefined ? { measured: pair } : {}),
6255
+ eligible:
6256
+ pair === undefined
6257
+ ? canApply
6258
+ : async () =>
6259
+ (await canApply()) &&
6260
+ (await this.measuredPairCurrent(record, target.slug, pair)),
6261
+ }),
6262
+ ))
6263
+ if (reason && commandSeq !== undefined)
6264
+ await recordAutoMergeDeferralObservation(
6265
+ store,
6266
+ record.slug,
6267
+ reason,
4197
6268
  pr.number,
4198
- record.branch,
4199
- target.branch,
6269
+ commandSeq,
6270
+ this.deps.ids('obs'),
4200
6271
  )
4201
- const reason =
4202
- preflight ??
4203
- (await this.withKernelRepository((kernelPath) =>
4204
- landIntoNode({
4205
- store,
4206
- forge: this.kernelForge(),
4207
- exec: forge.kernelExec ?? this.deps.exec,
4208
- workspacePath: kernelPath,
4209
- slug: record.slug,
4210
- node: target.slug,
4211
- branch: record.branch!,
4212
- destination: target.branch!,
4213
- pr: pr.number,
4214
- holder: this.deps.ids('node-writer'),
4215
- id: this.deps.ids('node-landing').replaceAll('_', '-'),
4216
- ...(integration
4217
- ? {
4218
- stack: {
4219
- head: state.integration!.cycle!.head,
4220
- parent: state.integration!.cycle!.parent,
4221
- cycle: state.integration!.cycle!.id,
4222
- },
4223
- }
4224
- : {}),
4225
- eligible: canApply,
4226
- }),
4227
- ))
4228
- if (reason && commandSeq !== undefined)
4229
- await recordAutoMergeDeferralObservation(
4230
- store,
4231
- record.slug,
4232
- reason,
4233
- pr.number,
4234
- commandSeq,
4235
- this.deps.ids('obs'),
6272
+ if (
6273
+ (await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug
4236
6274
  )
4237
- if ((await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug)
4238
- return
6275
+ return
6276
+ }
4239
6277
  await store.refreshBuild(record.slug)
4240
6278
  state = (await store.buildFacts(record.slug)).state
6279
+ if (closure !== undefined) prState = closure
4241
6280
  if (state.prState === 'merged') {
4242
6281
  if (state.mergedSha) prState = { state: 'merged', sha: state.mergedSha }
4243
6282
  }
@@ -4537,8 +6576,10 @@ export class Dispatcher {
4537
6576
  if (state.prState === 'merged' && state.mergedSha)
4538
6577
  prState = { state: 'merged', sha: state.mergedSha }
4539
6578
  }
6579
+ let landed = integration && state.integration?.landing !== undefined
4540
6580
  if (integration && prState.state === 'merged' && !state.integration?.landing) {
4541
6581
  const head = prState.headSha
6582
+ landed = true
4542
6583
  await store.append(record.slug, {
4543
6584
  actor: DISPATCHER,
4544
6585
  type: 'integration.landed',
@@ -4552,11 +6593,19 @@ export class Dispatcher {
4552
6593
  })
4553
6594
  }
4554
6595
 
6596
+ // A landing ends the node's verification: withdraw the runner's lease so
6597
+ // its next heartbeat stops the work. One write, no reads; it repeats only
6598
+ // while that runner still holds a live lease.
6599
+ if (landed && executionLeaseLive && record.lease !== undefined)
6600
+ await store.releaseLease(record.slug, record.lease.holder)
6601
+ // A withdrawn lease is not an ended execution: settle only once the
6602
+ // landed node's runner has recorded its end.
6603
+ const executionLive = executionLeaseLive || (landed && source.executionOpen)
4555
6604
  if (
4556
6605
  integration &&
4557
6606
  (prState.state === 'merged' || prState.state === 'closed') &&
4558
6607
  record.branch &&
4559
- !executionLeaseLive
6608
+ !executionLive
4560
6609
  ) {
4561
6610
  if (
4562
6611
  !(await this.withKernelRepository((kernelPath) =>
@@ -4575,7 +6624,7 @@ export class Dispatcher {
4575
6624
  }
4576
6625
  switch (prState.state) {
4577
6626
  case 'merged': {
4578
- if (executionLeaseLive) return
6627
+ if (executionLive) return
4579
6628
  const events = await source.history()
4580
6629
  if (!landingAuthorized(state.landing) && !state.landing?.forgeMerge) {
4581
6630
  // Use our durable native-effect evidence, never provider origin.
@@ -4615,6 +6664,9 @@ export class Dispatcher {
4615
6664
  // Before the child can become terminal, so a complete node already
4616
6665
  // folds every landed child's links; the node log dedupes a retry.
4617
6666
  await this.recordNodeIssueLinks(record.slug)
6667
+ // A merged attempt settles `accepted` with the measurement of the
6668
+ // head that landed, before the build can become terminal.
6669
+ if (nodeTarget) await this.settleMergedAttempt(record, state, prState.sha)
4618
6670
  await this.releaseWorkspace(record.slug, events)
4619
6671
  if (record.ticket) {
4620
6672
  await tickets.transition(await this.currentTicketId(record), this.doneState)
@@ -4633,7 +6685,7 @@ export class Dispatcher {
4633
6685
  return
4634
6686
  }
4635
6687
  case 'closed': {
4636
- if (executionLeaseLive) return
6688
+ if (executionLive) return
4637
6689
  const events = await source.history()
4638
6690
  // Closed without merge is a human decision — back to Triage (§15.7).
4639
6691
  if (state.prState !== 'closed') {
@@ -4644,20 +6696,38 @@ export class Dispatcher {
4644
6696
  } satisfies EventWrite<'pr.closed'>)
4645
6697
  }
4646
6698
  await this.releaseWorkspace(record.slug, events)
4647
- await this.returnBuildTicket(
4648
- record,
4649
- events,
4650
- 'pr-closed',
4651
- 'triage',
4652
- (state) =>
4653
- `build ${record.slug} PR closed without merging (${pr.url}) — returned to ${state}`,
4654
- )
6699
+ // A closed attempt goes to the rejected role through its node's
6700
+ // sweep, never back to triage. One a human closed settles `aborted`.
6701
+ const attempt = nodeTarget
6702
+ ? await this.terminalAttempt(record, state)
6703
+ : { node: '', status: 'none' as const }
6704
+ if (attempt.status === 'in-flight')
6705
+ await settleAttempt(
6706
+ store,
6707
+ attempt.node,
6708
+ {
6709
+ proposal: attempt.attempt!.proposal,
6710
+ ticket: attempt.attempt!.ticket,
6711
+ build: record.slug,
6712
+ },
6713
+ 'aborted',
6714
+ { note: `PR ${pr.url} closed without merging` },
6715
+ )
6716
+ if (attempt.status === 'none')
6717
+ await this.returnBuildTicket(
6718
+ record,
6719
+ events,
6720
+ 'pr-closed',
6721
+ 'triage',
6722
+ (state) =>
6723
+ `build ${record.slug} PR closed without merging (${pr.url}) — returned to ${state}`,
6724
+ )
4655
6725
  await store.append(record.slug, {
4656
6726
  actor: DISPATCHER,
4657
6727
  type: 'build.completed',
4658
6728
  payload: { outcome: 'closed-unmerged' },
4659
6729
  } satisfies EventWrite<'build.completed'>)
4660
- if (record.ticket) await this.settleBuildHandback(record.slug)
6730
+ if (record.ticket && attempt.status === 'none') await this.settleBuildHandback(record.slug)
4661
6731
  await this.reclaimPrAttachments(record.slug, events)
4662
6732
  report.closed += 1
4663
6733
  return
@@ -4719,25 +6789,53 @@ export class Dispatcher {
4719
6789
  }
4720
6790
  }
4721
6791
 
6792
+ /** `signal` is a continuation's teardown token: a provider call that
6793
+ * rejects after teardown records no cleanup fact, so the abandoned marker
6794
+ * stays adoptable in the same generation. */
4722
6795
  private async provisionWorkspace(
4723
6796
  slug: string,
4724
6797
  input: Parameters<WorkspaceProvider['provision']>[0],
6798
+ signal?: AbortSignal,
4725
6799
  ) {
4726
6800
  const facts = (await readBuildFacts(this.store, slug)).value
4727
6801
  const { restoration, superseded } = supersedeRestorationHeads(
4728
6802
  facts.workspacePreservation?.payload.heads,
4729
6803
  facts.replacedHeads,
4730
6804
  )
6805
+ const local = this.deps.forge.name === 'local-git'
4731
6806
  try {
4732
6807
  const handle = await this.deps.workspaces.provision({
4733
6808
  ...input,
4734
6809
  restoration,
4735
6810
  ...(facts.replacedHeads.length ? { restorationReplaced: facts.replacedHeads } : {}),
6811
+ // Store reads happen only while provisioning a build whose receipt
6812
+ // keeps some head in the BuildStore.
6813
+ ...(restoration?.some((head) => head.storeBase !== undefined)
6814
+ ? {
6815
+ restoreStored: ({ exec, workspacePath, sha }) =>
6816
+ restoreRetainedHead(
6817
+ {
6818
+ store: this.store,
6819
+ slug,
6820
+ exec,
6821
+ workspacePath,
6822
+ local,
6823
+ branch: input.branch,
6824
+ targetBranch: facts.state.baseBranch ?? input.baseBranch,
6825
+ exclude: sha,
6826
+ archive: async () => {
6827
+ throw new Error('restore only')
6828
+ },
6829
+ },
6830
+ sha,
6831
+ ),
6832
+ }
6833
+ : {}),
4736
6834
  // Same predicate preservation archives under: only local-git keeps
4737
6835
  // archive refs in the local repository.
4738
6836
  ...(restoration?.length
4739
6837
  ? {
4740
- restorationArchives: this.deps.forge.name === 'local-git' ? 'local' : 'remote',
6838
+ restorationArchives: local ? 'local' : 'remote',
4741
6839
  }
4742
6840
  : {}),
4743
6841
  })
@@ -4747,7 +6845,7 @@ export class Dispatcher {
4747
6845
  ]
4748
6846
  return skipped.length ? { ...handle, restorationSkipped: skipped } : handle
4749
6847
  } catch (error) {
4750
- if (error instanceof WorkspaceCleanupRequired) {
6848
+ if (error instanceof WorkspaceCleanupRequired && signal?.aborted !== true) {
4751
6849
  await this.store.append(slug, {
4752
6850
  actor: DISPATCHER,
4753
6851
  type: 'workspace.cleanup-required',
@@ -4816,6 +6914,33 @@ export class Dispatcher {
4816
6914
  return this.deps.retiredWorkspaces?.find((provider) => provider.name === open.provider) ?? null
4817
6915
  }
4818
6916
 
6917
+ /** A workspace a provider flagged `cleanup-required` is fenced, cleaned up
6918
+ * and released before its build's next generation is provisioned (leaf
6919
+ * dispatch retry, node verification and node conflict tails alike).
6920
+ * Returns the facts to continue from, or `undefined` when this tick must
6921
+ * stop: a foreign continuation holds a live lease, or the reap failed,
6922
+ * which is already durable against the build. */
6923
+ private async replaceFlaggedWorkspace(
6924
+ record: BuildRecord,
6925
+ facts: CurrentBuildFacts,
6926
+ launched: Set<string> | undefined,
6927
+ ): Promise<CurrentBuildFacts | undefined> {
6928
+ const flagged = openWorkspace(facts)
6929
+ if (
6930
+ flagged === null ||
6931
+ !cleanupRequiredWorkspace(facts) ||
6932
+ this.workspaceOwner(flagged)?.recovery === undefined
6933
+ )
6934
+ return facts
6935
+ if (this.hasLiveExecutionLease(record)) return undefined
6936
+ if (!(await this.reapStaleWorkspace(record.slug, facts, 'replacement'))) {
6937
+ // Also keeps this tick's sweep from reaping the same build again.
6938
+ launched?.add(record.slug)
6939
+ return undefined
6940
+ }
6941
+ return (await readBuildFacts(this.store, record.slug)).value
6942
+ }
6943
+
4819
6944
  /** Fence and remove a stale remote environment. A replacement is created
4820
6945
  * only after exact-name cleanup is durably acknowledged. */
4821
6946
  private async reapStaleWorkspace(
@@ -5079,6 +7204,7 @@ export class Dispatcher {
5079
7204
  kind?: 'work' | 'node'
5080
7205
  target?: EventPayload<'build.created'>['target']
5081
7206
  baseBranch?: string
7207
+ priority?: 'urgent'
5082
7208
  }
5083
7209
  | undefined,
5084
7210
  ): EventPayload<'build.created'> {
@@ -5104,9 +7230,17 @@ export class Dispatcher {
5104
7230
  }
5105
7231
  : {}),
5106
7232
  ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
7233
+ ...(seed?.priority !== undefined ? { priority: seed.priority } : {}),
5107
7234
  }
5108
7235
  }
5109
7236
 
7237
+ /** The claimed ticket's priority, frozen on `build.created`; normal is omitted. */
7238
+ private claimedPriority(ticket: Ticket): { priority?: 'urgent' } {
7239
+ return this.deps.tickets.priority && ticketPriority(ticket) === 'urgent'
7240
+ ? { priority: 'urgent' }
7241
+ : {}
7242
+ }
7243
+
5110
7244
  /** Every boundary before runner attachment is derived from durable facts.
5111
7245
  * Missing facts are the todo list; successful provider calls are followed
5112
7246
  * immediately by their facts, so an ordinary later tick can continue. */
@@ -5174,6 +7308,7 @@ export class Dispatcher {
5174
7308
  ? { issueLinks: seed.ticket.issueLinks }
5175
7309
  : {}),
5176
7310
  ...(seed !== undefined ? this.selectedProfile(seed.ticket) : {}),
7311
+ ...(seed !== undefined ? this.claimedPriority(seed.ticket) : {}),
5177
7312
  }),
5178
7313
  })
5179
7314
  events = (await readBuildFacts(store, record.slug)).value
@@ -5187,23 +7322,13 @@ export class Dispatcher {
5187
7322
  return this.completeDispatchBoundaries(record, seed, report, launched)
5188
7323
 
5189
7324
  stage = 'workspace'
5190
- const flagged = openWorkspace(events)
5191
- if (
5192
- flagged !== null &&
5193
- cleanupRequiredWorkspace(events) &&
5194
- this.workspaceOwner(flagged)?.recovery !== undefined
5195
- ) {
5196
- // A retry never launches into a flagged environment: release it, then
5197
- // provision the next generation below. A live lease means a foreign
5198
- // continuation still owns the build.
5199
- if (this.hasLiveExecutionLease(record)) return 'parked'
5200
- if (!(await this.reapStaleWorkspace(record.slug, events, 'replacement'))) {
5201
- // The failure is already durable against this build.
5202
- launched.add(record.slug)
5203
- return 'parked'
5204
- }
5205
- events = (await readBuildFacts(store, record.slug)).value
5206
- }
7325
+ // A retry never launches into a flagged environment: release it, then
7326
+ // provision the next generation below. A live lease means a foreign
7327
+ // continuation still owns the build; a failed reap is already durable
7328
+ // against it.
7329
+ const replaced = await this.replaceFlaggedWorkspace(record, events, launched)
7330
+ if (replaced === undefined) return 'parked'
7331
+ events = replaced
5207
7332
  if (openWorkspace(events) === null) {
5208
7333
  if (this.deps.workspaces.recovery !== undefined) {
5209
7334
  // Recovery-capable provider: durable marker + tracked background
@@ -5212,6 +7337,7 @@ export class Dispatcher {
5212
7337
  // and the launch.
5213
7338
  const kicked = await this.ensureProvisionContinuation(record, events, 'dispatch', seed)
5214
7339
  if (kicked === 'kicked') report.provisioning += 1
7340
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
5215
7341
  launched.add(record.slug)
5216
7342
  return 'deferred'
5217
7343
  }
@@ -5326,11 +7452,21 @@ export class Dispatcher {
5326
7452
  }
5327
7453
 
5328
7454
  let body = seed?.body ?? ticket.body
7455
+ const refusals = objectiveRefusals(body, {
7456
+ kind: state.kind ?? 'work',
7457
+ rejectedState: this.rejectedState(),
7458
+ })
7459
+ if (refusals.length > 0)
7460
+ throw new Error(`claimed ticket's spec cannot open as dispatched: ${refusals.join('; ')}`)
5329
7461
  let conformance = specConformance(body)
5330
7462
  let authoredSession = seed?.authoredSession
5331
- if (!conformance.conforms && this.deps.authorSpec !== undefined) {
7463
+ if (
7464
+ !conformance.conforms &&
7465
+ objectiveBlocks(body).length === 0 &&
7466
+ this.deps.authorSpec !== undefined
7467
+ ) {
5332
7468
  const candidate = await this.deps.authorSpec(ticket)
5333
- if (candidate !== null) {
7469
+ if (candidate !== null && objectiveBlocks(candidate).length === 0) {
5334
7470
  conformance = specConformance(candidate)
5335
7471
  if (conformance.conforms) {
5336
7472
  body = candidate
@@ -5664,7 +7800,7 @@ export class Dispatcher {
5664
7800
  /**
5665
7801
  * End open ticket waits whose tickets settled (SPEC §11 "Ticket waits").
5666
7802
  * Every waited ticket completed: `wait.ended {cause: automatic}`, and the
5667
- * build resumes ahead of new claims. Any waited ticket rejected (the
7803
+ * build resumes ahead of normal claims. Any waited ticket rejected (the
5668
7804
  * configured rejected role) or deleted: one `policy/wait-unresolvable`
5669
7805
  * escalation naming it, which the reducer reads as the wait's end. A wait
5670
7806
  * with tickets still pending stays in place.
@@ -5818,6 +7954,56 @@ export class Dispatcher {
5818
7954
  }
5819
7955
  }
5820
7956
 
7957
+ /**
7958
+ * Decide a parked attempt's sampled measurement (SPEC §13.1.1): a
7959
+ * command's medians or a judge panel's win rate. The attempt's runner
7960
+ * holds only its own build, so it records the samples and the dispatcher
7961
+ * records `attempt.measured` against the node's ε and starting spread as
7962
+ * they stand now, or a `policy/measurement-failed`
7963
+ * escalation when the node's ruler or harness pin moved past the request.
7964
+ *
7965
+ * Cost: the sampled-but-undecided check reads the reduced state the sweep
7966
+ * already holds, so a tick with nothing sampled reads nothing more. One
7967
+ * record lookup and one reduced read of the node per sampled request, once:
7968
+ * either append makes the request no longer pending. A lost race is
7969
+ * decided again next tick.
7970
+ */
7971
+ private async recordSampledMeasurement(slug: string, state: BuildState): Promise<void> {
7972
+ const sampled = sampledMeasurement(state)
7973
+ const request = state.attemptMeasurement?.request
7974
+ if (sampled === undefined || request === undefined) return
7975
+ const { seq: _seq, ...requested } = request
7976
+ // A missing node is refused once rather than failing every tick.
7977
+ const decided =
7978
+ (await this.store.getBuild(request.node)) === null
7979
+ ? { refusal: `node ${request.node} does not exist` }
7980
+ : decideSampledMeasurement(
7981
+ (await readBuildFacts(this.store, request.node)).value.state,
7982
+ requested,
7983
+ sampled,
7984
+ )
7985
+ if ('measured' in decided)
7986
+ await this.store.appendIfCurrent(slug, state.lastSeq, {
7987
+ actor: DISPATCHER,
7988
+ type: 'attempt.measured',
7989
+ payload: decided.measured,
7990
+ })
7991
+ else
7992
+ await this.store.appendIfCurrent(slug, state.lastSeq, {
7993
+ actor: DISPATCHER,
7994
+ type: 'escalation.raised',
7995
+ payload: {
7996
+ id: this.deps.ids('esc'),
7997
+ phase: 'measurement',
7998
+ source: 'policy',
7999
+ policyCause: 'measurement-failed',
8000
+ question:
8001
+ `Measurement request ${request.id} was sampled but cannot be decided: ${decided.refusal}. ` +
8002
+ 'No result was recorded; the attempt needs a fresh measurement request under the current ruler.',
8003
+ },
8004
+ })
8005
+ }
8006
+
5821
8007
  /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
5822
8008
  private async sweepBuild(
5823
8009
  record: BuildRecord,
@@ -5881,7 +8067,11 @@ export class Dispatcher {
5881
8067
  // The engine reached the end of the pipeline: record it once per
5882
8068
  // settlement key so capacity stops counting the parked build. A lost
5883
8069
  // race is decided again next tick.
5884
- if (settlementDue(state))
8070
+ // A sampled measurement is decided first: the attempt's landing waits
8071
+ // on it, while settlement only frees capacity and follows next tick.
8072
+ if (sampledMeasurement(state) !== undefined)
8073
+ await this.recordSampledMeasurement(record.slug, state)
8074
+ else if (settlementDue(state))
5885
8075
  await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5886
8076
  actor: DISPATCHER,
5887
8077
  type: 'pipeline.settled',
@@ -5891,7 +8081,7 @@ export class Dispatcher {
5891
8081
  const orphanEligible = (state: BuildState) =>
5892
8082
  !paused &&
5893
8083
  state.status === 'running' &&
5894
- (state.kind !== 'node' || integrationCurrent(state)) &&
8084
+ (state.kind !== 'node' || (integrationCurrent(state) && !nodeLanded(state))) &&
5895
8085
  state.sessions.open.some((session) => session.suspensionCause === undefined)
5896
8086
  const provedEnded =
5897
8087
  facts.open === null &&
@@ -5909,7 +8099,12 @@ export class Dispatcher {
5909
8099
  if (
5910
8100
  state.kind === 'node' &&
5911
8101
  (!integrationCurrent(state) || facts.workspace === null) &&
5912
- decision.kind !== 'wait'
8102
+ decision.kind !== 'wait' &&
8103
+ // An ended or crashed node measurement re-attaches to its workspace.
8104
+ !(
8105
+ (decision.kind === 'measure-baseline' || decision.kind === 'measure-progress') &&
8106
+ facts.workspace !== null
8107
+ )
5913
8108
  )
5914
8109
  return // cascade owns node runner admission
5915
8110
  // Raw history, read at most once and only by a branch that acts on it.
@@ -5984,7 +8179,7 @@ export class Dispatcher {
5984
8179
  const runs = decision.kind !== 'wait' || publicationRecoveryDue || orphanRecoveryDue
5985
8180
  // A finished leaf with work to run waits for a slot before anything is
5986
8181
  // reaped, provisioned or launched for it.
5987
- if (runs && state.kind !== 'node' && !(await this.leafAdmission(record.slug))) return
8182
+ if (runs && state.kind !== 'node' && (await this.leafAdmission(record.slug)) !== 'admit') return
5988
8183
  // A finished parked leaf keeps its workspace until merge or close; a
5989
8184
  // stale environment is reaped only for an admitted replacement.
5990
8185
  // A leaf waiting on tickets, or on the dispatcher's check of its wait,
@@ -6020,7 +8215,7 @@ export class Dispatcher {
6020
8215
  if (kicked === 'kicked') {
6021
8216
  report.provisioning += 1
6022
8217
  report.swept += 1
6023
- }
8218
+ } else if (kicked === 'budget-wait') report.provisioningDeferred += 1
6024
8219
  return
6025
8220
  }
6026
8221
  }
@@ -6043,8 +8238,10 @@ export class Dispatcher {
6043
8238
  report.swept += 1
6044
8239
  return
6045
8240
  }
8241
+ if (kicked === 'budget-wait') report.provisioningDeferred += 1
6046
8242
  // In-flight or foreign-live: whoever owns the marker completes the
6047
- // boundaries and the launch; this tick performs neither.
8243
+ // boundaries and the launch; this tick performs neither. A budget wait
8244
+ // leaves both to a later invocation.
6048
8245
  return
6049
8246
  }
6050
8247
  try {
@@ -6281,48 +8478,113 @@ export class Dispatcher {
6281
8478
  paused: boolean,
6282
8479
  opts: TickOpts = {},
6283
8480
  autoMergeSeedFact: AutoMergeDefaultFact | undefined = undefined,
8481
+ /** Operator start requests: admit exactly these tickets through every
8482
+ * gate below, without the ready listing or the scan checkpoint, and record
8483
+ * each ticket's outcome. The standing report fields are not published. */
8484
+ targeted?: TargetedDispatch,
6284
8485
  ): Promise<void> {
6285
- if (!this.accountsAvailable()) return
6286
- const health = this.store.repositoryFacts().forgeHealth
6287
- if (health && Date.parse(health.resetAt) > this.deps.clock().getTime()) return
8486
+ if (!this.claimGateOpen()) return
6288
8487
  const store = this.store
6289
8488
  const { tickets, config } = this.deps
6290
- const checkpoint = await this.scanCheckpoint('admission')
6291
- if (!checkpoint.due) return
8489
+ // A normal parked admission deferred this tick waits on urgent claims:
8490
+ // list now, once per deferral key; an unchanged key waits for a scan that
8491
+ // is due on its own.
8492
+ let force = false
8493
+ let deferralBuilds: CapacityBuild[] | undefined
8494
+ if (!targeted && this.deferredAdmissions.size > 0) {
8495
+ deferralBuilds = await this.capacityBuilds(launched)
8496
+ const key = this.deferralKey(
8497
+ dispatchCapacity(deferralBuilds, config.capacity, this.deps.clock()).occupied,
8498
+ )
8499
+ if (key !== this.lastForcedDeferralKey) {
8500
+ force = true
8501
+ this.forcedDeferralKey = key
8502
+ }
8503
+ }
8504
+ const checkpoint = targeted ? undefined : await this.scanCheckpoint('admission', { force })
8505
+ if (checkpoint !== undefined && !checkpoint.due) return
8506
+ const settle = (ticket: Ticket, outcome: TargetedOutcome) =>
8507
+ targeted?.outcomes.set(ticket.ref.id, outcome)
6292
8508
  // Clear only standing measurement fields; action counters belong to this tick.
6293
- report.queued = report.invalidTickets = report.dependencyBlocked = report.creationWithheld = 0
6294
- report.ticketDiagnostics = []
6295
- report.dependencyDiagnostics = []
6296
- report.creationDiagnostics = []
8509
+ if (!targeted) {
8510
+ report.queued = report.invalidTickets = report.dependencyBlocked = report.creationWithheld = 0
8511
+ report.ticketDiagnostics = []
8512
+ report.dependencyDiagnostics = []
8513
+ report.creationDiagnostics = []
8514
+ }
6297
8515
  // Capacity counts builds running work. An unfinished build holds its slot
6298
8516
  // even while blocked or paused; a finished build parked for its merge
6299
8517
  // decision holds none. Capacity is per repo (§16.1) — another repo's
6300
8518
  // builds never consume this repo's slots.
6301
- const capacityBuilds = await this.capacityBuilds(launched)
8519
+ // The checkpoint writes nothing, so a deferral capacity read is current.
8520
+ const capacityBuilds =
8521
+ targeted?.measured ?? deferralBuilds ?? (await this.capacityBuilds(launched))
6302
8522
  // A node awaiting verification, or a parked build that must run again,
6303
- // reserves its slot ahead of new claims until it is admitted; this only
6304
- // ever lowers the claim budget.
6305
- const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock())
8523
+ // reserves its slot ahead of claims of its own or a lower priority until
8524
+ // it is admitted; this only ever lowers the claim budgets. Urgent claims
8525
+ // wait only for urgent parked work (SPEC §12 "Slot admission order").
8526
+ // Open-PR backpressure gates new normal-priority claims only: admission,
8527
+ // the janitor, reconciles, landings and urgent claims are untouched, and
8528
+ // capacity accounting is unchanged. Engagement is a durable repository
8529
+ // fact recorded only on transitions, so hysteresis survives restarts.
8530
+ const engagement = this.store.repositoryFacts().openPrBackpressure
8531
+ const engaged = engagement !== undefined
8532
+ const backpressure = openPrBackpressure(
8533
+ capacityBuilds,
8534
+ openPrBackpressurePolicy(config.policy),
8535
+ engaged,
8536
+ )
8537
+ // Pending start requests reserve ahead of the ordinary claims they outrank.
8538
+ const projection = dispatchCapacity(
8539
+ capacityBuilds,
8540
+ config.capacity,
8541
+ this.deps.clock(),
8542
+ undefined,
8543
+ { openPrs: { policy: config.policy, engaged }, startRequests: this.startClaims() },
8544
+ )
8545
+ const transition = backpressureTransition(
8546
+ backpressure,
8547
+ engaged,
8548
+ backpressure?.openPrs ?? openPrCount(capacityBuilds, engagement?.excludeHeld ?? false),
8549
+ )
8550
+ if (!targeted && transition && this.deps.holdsRepoAuthority?.() !== false) {
8551
+ await store.ensureRepo(this.deps.repo)
8552
+ await store.appendRepo(this.deps.repo, { actor: DISPATCHER, ...transition })
8553
+ }
8554
+ const normalPaused = backpressure?.active === true
6306
8555
  const activeRefs: TicketRef[] = capacityBuilds
6307
8556
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
6308
8557
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
6309
- let capacity = intakeCapacity(projection, {
6310
- settled: this.parkedSettled,
6311
- denied: this.slotWaiters,
6312
- })
8558
+ const adjust = { settled: this.parkedSettled, denied: this.slotWaiters }
8559
+ let capacity = intakeCapacity(projection, adjust)
8560
+ let urgentCapacity = tickets.priority ? intakeCapacity(projection, adjust, 'urgent') : capacity
8561
+ let urgentWaiting = 0
8562
+ const urgentClaim = (ticket: Ticket) =>
8563
+ !targeted &&
8564
+ !!tickets.priority &&
8565
+ ticket.kind !== 'node' &&
8566
+ ticketPriority(ticket) === 'urgent'
8567
+ // A targeted ticket's tier is its request's, never its ticket's priority.
8568
+ const startTier = (ticket: Ticket): TicketStartPriority =>
8569
+ targeted?.requests.get(ticket.ref.id)?.priority ?? 'manual'
6313
8570
 
6314
8571
  // The ready scan runs even at full capacity: `queued` is the operator's
6315
8572
  // standing queue-depth report and must stay honest exactly when the
6316
8573
  // dispatcher is saturated. Sources that keep a claimed ticket in the
6317
8574
  // ready state are deduped against the active builds embodying them.
6318
8575
  const journalBeforeReady = this.store.repositoryFacts().harvest
6319
- const listing = await this.listReady()
6320
- const activeTicketIds = await this.activeTicketIdentities(activeRefs, listing.tickets)
8576
+ const listing = targeted
8577
+ ? { tickets: targeted.tickets, diagnostics: [] as string[] }
8578
+ : await this.listReady()
8579
+ // Targeted admission never fans `get` out over unrelated active builds:
8580
+ // its caller matched them without source reads (see honorStartRequests).
8581
+ const activeTicketIds =
8582
+ targeted?.activeIds ?? (await this.activeTicketIdentities(activeRefs, listing.tickets))
6321
8583
  // A provider listing can race reservation and blocker filing. Preserve
6322
8584
  // the before/after union, refreshing once only when admission is possible.
6323
8585
  if (listing.tickets.length > 0) await this.store.refreshJournal()
6324
8586
  const journalAfterReady = this.store.repositoryFacts()
6325
- if (journalAfterReady.health?.cause === 'ready-scan-failed') {
8587
+ if (!targeted && journalAfterReady.health?.cause === 'ready-scan-failed') {
6326
8588
  await this.sourceCondition(undefined, 'ready-scan')
6327
8589
  }
6328
8590
  const creationHolds = new Map(
@@ -6331,6 +8593,7 @@ export class Dispatcher {
6331
8593
  creation,
6332
8594
  ]),
6333
8595
  )
8596
+ const attemptHolds = await this.optimizationCreationHolds()
6334
8597
  const eligible = listing.tickets.filter(
6335
8598
  (ticket) =>
6336
8599
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
@@ -6340,15 +8603,34 @@ export class Dispatcher {
6340
8603
  // unchanged; a source without the priority capability is all normal.
6341
8604
  // A ticket whose labels select two profiles is never claimed (SPEC §9).
6342
8605
  const conflicts = this.profileConflicts(eligible)
8606
+ // Conflicts and their diagnostics are produced in the same order.
8607
+ for (const [index, ticket] of [...conflicts.tickets].entries())
8608
+ settle(ticket, { outcome: 'invalid', detail: conflicts.diagnostics[index]! })
6343
8609
  const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
6344
- const ready = this.deps.tickets.priority ? urgentFirst(claimable) : claimable
8610
+ // A targeted pass keeps its tier-then-request order.
8611
+ const ready = !targeted && this.deps.tickets.priority ? urgentFirst(claimable) : claimable
6345
8612
  report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
6346
8613
  report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
8614
+ if (!targeted && normalPaused)
8615
+ report.ticketDiagnostics.push(backpressureExplanation(backpressure))
6347
8616
  report.queued = ready.length
6348
8617
  const withheld = new Set<string>()
6349
8618
  for (const ticket of ready) {
6350
8619
  if (ticket.creationKey === undefined) continue
6351
- const creation = creationHolds.get(ticket.creationKey.toLowerCase())
8620
+ const key = ticket.creationKey.toLowerCase()
8621
+ const attempt = attemptHolds.failure ?? attemptHolds.holds.get(key)
8622
+ if (attempt !== undefined) {
8623
+ withheld.add(ticket.ref.id)
8624
+ report.creationWithheld += 1
8625
+ report.creationDiagnostics.push(
8626
+ typeof attempt === 'string'
8627
+ ? `ticket ${ticket.ref.id}: creation withheld — ${attempt}`
8628
+ : `ticket ${ticket.ref.id}: creation withheld — optimization node ${attempt.node}, ` +
8629
+ `proposal request ${attempt.request} has not recorded its attempts`,
8630
+ )
8631
+ continue
8632
+ }
8633
+ const creation = creationHolds.get(key)
6352
8634
  if (creation === undefined) continue
6353
8635
  withheld.add(ticket.ref.id)
6354
8636
  report.creationWithheld += 1
@@ -6366,17 +8648,34 @@ export class Dispatcher {
6366
8648
  // still runs either way, so the standing queue-depth report stays honest —
6367
8649
  // this only declines to claim a ticket into a build that would immediately
6368
8650
  // sit held.
8651
+ // Saturated, an urgent ticket still runs the preflight: it claims an
8652
+ // urgent budget, or counts as urgent demand waiting for a slot.
8653
+ const urgentReady = ready.some((ticket) => urgentClaim(ticket) && !withheld.has(ticket.ref.id))
8654
+ const noBudget = targeted
8655
+ ? ready.every((ticket) => targeted.budgets[startTier(ticket)] <= 0)
8656
+ : capacity <= 0 && !urgentReady
6369
8657
  if (
6370
8658
  paused ||
6371
- (capacity <= 0 &&
8659
+ (!targeted &&
8660
+ normalPaused &&
8661
+ !ready.some(
8662
+ (ticket) => ticketPriority(ticket) === 'urgent' && !withheld.has(ticket.ref.id),
8663
+ )) ||
8664
+ (noBudget &&
6372
8665
  !ready.some(
6373
8666
  (ticket) =>
6374
- ticket.kind === 'node' ||
6375
- (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0),
8667
+ (targeted || !normalPaused || ticketPriority(ticket) === 'urgent') &&
8668
+ (ticket.kind === 'node' ||
8669
+ (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0)),
6376
8670
  ))
6377
8671
  ) {
8672
+ if (checkpoint === undefined) return
6378
8673
  await this.sourceCondition(undefined, 'ready-scan')
6379
- if (!this.outOfBudget(opts)) await this.completeScan(checkpoint, report)
8674
+ if (!this.outOfBudget(opts)) {
8675
+ await this.completeScan(checkpoint, report)
8676
+ // No urgent ticket is ready: this scan decided urgent claims.
8677
+ if (!paused) this.urgentEvaluated = true
8678
+ }
6380
8679
  return
6381
8680
  }
6382
8681
  // One dependency-node cache per scan: blockers are commonly shared across
@@ -6460,6 +8759,7 @@ export class Dispatcher {
6460
8759
  targetBlocked.add(ticket.ref.id)
6461
8760
  report.dependencyBlocked += 1
6462
8761
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
8762
+ settle(ticket, { outcome: 'blocked', detail: target })
6463
8763
  continue
6464
8764
  }
6465
8765
  preflightTargets.set(ticket.ref.id, JSON.stringify(target))
@@ -6555,23 +8855,47 @@ export class Dispatcher {
6555
8855
  })
6556
8856
  }
6557
8857
  }
6558
- for (const verdict of verdicts.values()) {
8858
+ for (const [id, verdict] of verdicts) {
6559
8859
  if (verdict.unresolved.length > 0) {
6560
8860
  report.dependencyBlocked += 1
6561
8861
  report.dependencyDiagnostics.push(...verdict.diagnostics)
8862
+ targeted?.outcomes.set(id, {
8863
+ outcome: 'blocked',
8864
+ detail:
8865
+ verdict.diagnostics.join('; ') ||
8866
+ `unresolved blockers: ${verdict.unresolved.join(', ')}`,
8867
+ })
6562
8868
  }
6563
8869
  }
8870
+ let claimLoopCompleted = true
6564
8871
  for (const ticket of ready) {
6565
- if (this.outOfBudget(opts)) break
6566
- if (ticket.kind !== 'node' && capacity <= 0) continue
8872
+ if (this.outOfBudget(opts)) {
8873
+ claimLoopCompleted = false
8874
+ break
8875
+ }
8876
+ if (!targeted && normalPaused && ticketPriority(ticket) !== 'urgent') continue
8877
+ const urgent = urgentClaim(ticket)
8878
+ const budget = targeted
8879
+ ? targeted.budgets[startTier(ticket)]
8880
+ : urgent
8881
+ ? urgentCapacity
8882
+ : capacity
8883
+ if (ticket.kind !== 'node' && budget <= 0 && !urgent) continue
6567
8884
  if (withheld.has(ticket.ref.id)) continue
6568
8885
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
6569
8886
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
8887
+ // An urgent ticket that passed every gate but capacity is demand that
8888
+ // normal parked work yields to until the next admission scan.
8889
+ if (ticket.kind !== 'node' && budget <= 0) {
8890
+ urgentWaiting += 1
8891
+ continue
8892
+ }
6570
8893
 
6571
8894
  const target = await this.resolveNodeTarget(ticket, targetScan)
6572
8895
  if (typeof target === 'string') {
6573
8896
  report.dependencyBlocked += 1
6574
8897
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
8898
+ settle(ticket, { outcome: 'blocked', detail: target })
6575
8899
  continue
6576
8900
  }
6577
8901
  if (hasNodes && preflightTargets.get(ticket.ref.id) !== JSON.stringify(target)) {
@@ -6606,7 +8930,12 @@ export class Dispatcher {
6606
8930
  }
6607
8931
  await store.ensureRepo(this.deps.repo)
6608
8932
  // A lapsed run leaves the ticket Ready for whoever holds the repository.
6609
- if (this.deps.holdsRepoAuthority?.() === false) break
8933
+ if (this.deps.holdsRepoAuthority?.() === false) {
8934
+ claimLoopCompleted = false
8935
+ break
8936
+ }
8937
+ // Cancellation and a priority change are checked again before claiming.
8938
+ if (targeted && !(await this.startStillPending(targeted, ticket))) continue
6610
8939
  await store.appendRepo(this.deps.repo, {
6611
8940
  actor: DISPATCHER,
6612
8941
  type: 'ticket-preparation.intended',
@@ -6626,6 +8955,10 @@ export class Dispatcher {
6626
8955
  try {
6627
8956
  if (!(await tickets.claim(ticket.ref.id))) {
6628
8957
  await this.preparationResolved(attempt, 'lost-claim')
8958
+ settle(ticket, {
8959
+ outcome: 'claim-refused',
8960
+ detail: `the ${tickets.name} ticket source refused the claim of ${ticket.ref.id}`,
8961
+ })
6629
8962
  report.claimRaces += 1
6630
8963
  report.queued -= 1
6631
8964
  continue
@@ -6645,10 +8978,23 @@ export class Dispatcher {
6645
8978
  // Quality gate (§6.3): import a conforming ticket body as the spec;
6646
8979
  // author one for thin-but-groomed tickets; otherwise bounce.
6647
8980
  stage = 'spec'
6648
- let conformance = specConformance(body)
6649
- if (!conformance.conforms && this.deps.authorSpec) {
8981
+ // An objective refusal bounces before any authoring: an authored spec
8982
+ // could strip the block and open a plain node instead (SPEC §13.1).
8983
+ const refusals = objectiveRefusals(body, {
8984
+ kind: ticket.kind ?? 'work',
8985
+ rejectedState: this.rejectedState(),
8986
+ })
8987
+ let conformance =
8988
+ refusals.length > 0 ? { conforms: false, missing: refusals } : specConformance(body)
8989
+ if (
8990
+ !conformance.conforms &&
8991
+ refusals.length === 0 &&
8992
+ objectiveBlocks(body).length === 0 &&
8993
+ this.deps.authorSpec
8994
+ ) {
6650
8995
  const authored = await this.deps.authorSpec(ticket)
6651
- if (authored !== null) {
8996
+ // An authored spec never gains the marker the ticket did not carry.
8997
+ if (authored !== null && objectiveBlocks(authored).length === 0) {
6652
8998
  conformance = specConformance(authored)
6653
8999
  if (conformance.conforms) {
6654
9000
  body = authored
@@ -6671,7 +9017,7 @@ export class Dispatcher {
6671
9017
  },
6672
9018
  })
6673
9019
  stage = 'bounce'
6674
- await this.bounce(ticket, conformance.missing)
9020
+ await this.bounce(ticket, conformance.missing, refusals.length > 0)
6675
9021
  stage = 'handback-report'
6676
9022
  await this.reportPreparationHandback(attempt, {
6677
9023
  ticket: ticket.ref,
@@ -6682,6 +9028,12 @@ export class Dispatcher {
6682
9028
  ...(missing ? { missing } : {}),
6683
9029
  })
6684
9030
  await this.preparationResolved(attempt, 'bounced')
9031
+ settle(ticket, {
9032
+ outcome: 'invalid',
9033
+ detail: `bounced to ${attempt.handback}${
9034
+ conformance.missing.length > 0 ? `; missing: ${conformance.missing.join('; ')}` : ''
9035
+ }`,
9036
+ })
6685
9037
  report.bounced += 1
6686
9038
  report.queued -= 1
6687
9039
  continue
@@ -6715,6 +9067,10 @@ export class Dispatcher {
6715
9067
  ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
6716
9068
  // Fixed at claim from the same sample: relabelling never changes it.
6717
9069
  ...this.selectedProfile(ticket),
9070
+ // `manual` is admission-only; an explicit urgent start is urgent.
9071
+ ...(startTier(ticket) === 'urgent' && targeted
9072
+ ? { priority: 'urgent' as const }
9073
+ : this.claimedPriority(ticket)),
6718
9074
  }
6719
9075
  // `build.created` rides with the record so the pinned assets and the
6720
9076
  // record exist together or not at all.
@@ -6747,6 +9103,7 @@ export class Dispatcher {
6747
9103
  })
6748
9104
  established = true
6749
9105
  await this.preparationResolved(attempt, 'owned')
9106
+ settle(ticket, { outcome: 'started', slug: record.slug })
6750
9107
  } catch (error) {
6751
9108
  // A lapse is not a preparation failure: the successor recovers the
6752
9109
  // intended attempt through `recoverTicketPreparations`.
@@ -6786,7 +9143,11 @@ export class Dispatcher {
6786
9143
  )
6787
9144
  }
6788
9145
  report.queued -= 1
6789
- if (ticket.kind !== 'node') capacity -= 1
9146
+ if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
9147
+ else if (ticket.kind !== 'node') {
9148
+ capacity -= 1
9149
+ urgentCapacity -= 1
9150
+ }
6790
9151
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
6791
9152
  ticket,
6792
9153
  body,
@@ -6797,7 +9158,11 @@ export class Dispatcher {
6797
9158
  // means the remote provisioning continuation owns the rest.
6798
9159
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
6799
9160
  }
6800
- if (scanSuccessful && !this.outOfBudget(opts)) await this.completeScan(checkpoint, report)
9161
+ if (checkpoint !== undefined && scanSuccessful && !this.outOfBudget(opts)) {
9162
+ await this.completeScan(checkpoint, report, urgentWaiting)
9163
+ // The only other place this tick authorizes deferred normal admissions.
9164
+ if (claimLoopCompleted) this.urgentEvaluated = true
9165
+ }
6801
9166
  }
6802
9167
 
6803
9168
  /**
@@ -6865,6 +9230,22 @@ export class Dispatcher {
6865
9230
  return `target node ${ticket.target} is ${state.prState === 'merged' ? 'landed' : 'closed'}`
6866
9231
  if (state.pendingCommands.some((c) => c.command === 'abort'))
6867
9232
  return `target node ${ticket.target} is closing`
9233
+ if (state.optimization?.stopped !== undefined) {
9234
+ const key = (ref: TicketRef) => {
9235
+ try {
9236
+ const resolved = resolveTicketRef(migrations, ref, this.deps.tickets.name)
9237
+ return `${resolved.source}\u0000${resolved.id}`
9238
+ } catch {
9239
+ return `${ref.source}\u0000${ref.id}`
9240
+ }
9241
+ }
9242
+ const wanted = key(ticket.ref)
9243
+ if (
9244
+ optimizationAttempt(state.optimization, ticket.ref, key) !== undefined ||
9245
+ state.optimization.stoppedTickets?.some((ref) => key(ref) === wanted)
9246
+ )
9247
+ return `target optimization node ${ticket.target} has stopped; attempt ${ticket.ref.id} is cancelled`
9248
+ }
6868
9249
  if (state.integration?.intent && !state.integration.landing)
6869
9250
  return `target node ${ticket.target} is merging`
6870
9251
  if (!digest.nodeOpened || !record.branch) return `target node ${ticket.target} is not yet open`
@@ -6899,8 +9280,23 @@ export class Dispatcher {
6899
9280
  }
6900
9281
  const sha = await forge.createNodeBranch(intent.branch, intent.sha)
6901
9282
  await this.store.refreshBuild(record.slug)
6902
- const latest = (await this.store.buildFacts(record.slug)).state
9283
+ let latest = (await this.store.buildFacts(record.slug)).state
6903
9284
  if (latest.status !== 'queued' || latest.pendingCommands.length > 0 || latest.nodeOpened) return
9285
+ // An optimization node's objective is accepted before it opens, so an
9286
+ // opened node without its accepted objective never exists (SPEC §13.1).
9287
+ if (latest.optimization === undefined) {
9288
+ const objective = await this.specObjective(record.slug, latest.specRev)
9289
+ if (objective !== undefined) {
9290
+ const accepted = await this.store.appendIfCurrent(record.slug, latest.lastSeq, {
9291
+ actor: DISPATCHER,
9292
+ type: 'optimization.objective-accepted',
9293
+ payload: { objective, revision: 1, harnessPin: sha, specRev: latest.specRev ?? 0 },
9294
+ })
9295
+ if (!accepted) return
9296
+ await this.store.refreshBuild(record.slug)
9297
+ latest = (await this.store.buildFacts(record.slug)).state
9298
+ }
9299
+ }
6904
9300
  await this.store.appendIfCurrent(record.slug, latest.lastSeq, {
6905
9301
  actor: DISPATCHER,
6906
9302
  type: 'node.opened',
@@ -6908,6 +9304,65 @@ export class Dispatcher {
6908
9304
  })
6909
9305
  }
6910
9306
 
9307
+ /** Re-accept an optimization node's objective after a spec revision
9308
+ * (SPEC §13.1). The harness is pinned again at the node head only when the
9309
+ * revision starts a new ruler. Returns whether a fact was written. */
9310
+ private async acceptRevisedObjective(
9311
+ record: BuildRecord,
9312
+ state: BuildState,
9313
+ report: TickReport,
9314
+ ): Promise<boolean> {
9315
+ const optimization = state.optimization!
9316
+ let objective: Objective | undefined
9317
+ try {
9318
+ objective = await this.specObjective(record.slug, state.specRev)
9319
+ } catch (error) {
9320
+ report.janitorDiagnostics.push(
9321
+ `${record.slug}: ${error instanceof Error ? error.message : String(error)}`,
9322
+ )
9323
+ return false
9324
+ }
9325
+ if (objective === undefined) {
9326
+ report.janitorDiagnostics.push(
9327
+ `${record.slug}: spec revision ${state.specRev} removed the autobuild-objective block`,
9328
+ )
9329
+ return false
9330
+ }
9331
+ const forge = this.deps.forge
9332
+ const harnessPin =
9333
+ objectiveRulerChanged(optimization.accepted.objective, objective) && record.branch
9334
+ ? await forge.remoteBranchSha?.(record.branch)
9335
+ : optimization.accepted.harnessPin
9336
+ if (harnessPin === undefined) return false
9337
+ const written = await this.store.appendIfCurrent(record.slug, state.lastSeq, {
9338
+ actor: DISPATCHER,
9339
+ type: 'optimization.objective-accepted',
9340
+ payload: {
9341
+ objective,
9342
+ revision: optimization.revision + 1,
9343
+ harnessPin,
9344
+ specRev: state.specRev ?? 0,
9345
+ },
9346
+ })
9347
+ return written !== null
9348
+ }
9349
+
9350
+ /** The objective a recorded spec revision declares: undefined for a plain
9351
+ * node or no recorded spec, a thrown refusal for a spec that cannot open as
9352
+ * either kind. One artifact read. */
9353
+ private async specObjective(
9354
+ slug: string,
9355
+ rev: number | undefined,
9356
+ ): Promise<Objective | undefined> {
9357
+ if (rev === undefined) return undefined
9358
+ const artifact = await this.store.getArtifact(slug, 'spec', rev)
9359
+ if (artifact === null) throw new Error(`spec revision ${rev} is unreadable`)
9360
+ const parsed = parseObjective(new TextDecoder().decode(artifact.content))
9361
+ if ('refusal' in parsed)
9362
+ throw new Error(`spec revision ${rev} cannot open as an optimization node: ${parsed.refusal}`)
9363
+ return 'objective' in parsed ? parsed.objective : undefined
9364
+ }
9365
+
6911
9366
  private kernelForge(): Forge {
6912
9367
  const forge = this.deps.forge
6913
9368
  if (!forge.kernelRewrite) return forge
@@ -7243,12 +9698,19 @@ export class Dispatcher {
7243
9698
  }
7244
9699
 
7245
9700
  if (!this.accountsAvailable()) return
7246
- if (!(await this.nodeHasCapacity(record.slug))) return
7247
- if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
7248
- const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
9701
+ if ((await this.nodeHasCapacity(record.slug, false)) !== 'admit') return
9702
+ // `launch()` refuses a flagged workspace and leaves the reap to its
9703
+ // callers; this is the node's caller for conflict work.
9704
+ const current = await this.replaceFlaggedWorkspace(record, facts, launched)
9705
+ if (current === undefined) return
9706
+ if (openWorkspace(current) === null && this.deps.workspaces.recovery) {
9707
+ const kicked = await this.ensureProvisionContinuation(record, current, 'launch')
7249
9708
  if (kicked === 'kicked') report.provisioning += 1
9709
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
9710
+ // After a reap, this tick's sweep leaves the replacement alone.
9711
+ if (kicked === 'kicked' && current !== facts) launched.add(record.slug)
7250
9712
  } else {
7251
- if (openWorkspace(facts) === null) {
9713
+ if (openWorkspace(current) === null) {
7252
9714
  const handle = await this.provisionWorkspace(record.slug, {
7253
9715
  repo: checkout,
7254
9716
  baseBranch: state.baseBranch!,
@@ -7346,6 +9808,7 @@ export class Dispatcher {
7346
9808
  if (
7347
9809
  state.integration?.cycle &&
7348
9810
  !state.nodeRestack?.active &&
9811
+ !proposeRunDue(state.optimization) &&
7349
9812
  (!integrationCurrent(state) || integrationFailed(state))
7350
9813
  ) {
7351
9814
  const stale = (await readBuildFacts(this.store, record.slug)).value
@@ -7354,6 +9817,7 @@ export class Dispatcher {
7354
9817
  }
7355
9818
  if (
7356
9819
  unchangedFailure ||
9820
+ state.integration?.landing ||
7357
9821
  !integrationComplete(state) ||
7358
9822
  state.nodeRestack?.active ||
7359
9823
  state.integration?.intent ||
@@ -7380,6 +9844,9 @@ export class Dispatcher {
7380
9844
  !integrationCurrent(state) ||
7381
9845
  state.integration?.cycle?.config !== integrationConfig(config)
7382
9846
  ) {
9847
+ // An empty owned range (everything already upstream) has nothing to
9848
+ // verify: never prepare a new cycle for it.
9849
+ if (comparison.ahead === 0 || comparison.headSha === comparison.parentSha) return
7383
9850
  await this.observeIntegration(record.slug)
7384
9851
  state = (await this.store.buildFacts(record.slug)).state
7385
9852
  if (!integrationComplete(state)) return
@@ -7396,6 +9863,8 @@ export class Dispatcher {
7396
9863
  return
7397
9864
  const exact = await forge.compareBranches(state.baseBranch!, record.branch!)
7398
9865
  if (exact.parentSha !== comparison.parentSha || exact.headSha !== comparison.headSha) return
9866
+ if (exact.ahead === 0 || exact.headSha === exact.parentSha || current.integration?.landing)
9867
+ return
7399
9868
  const cycle = {
7400
9869
  id: this.deps.ids('integration-cycle'),
7401
9870
  parent: exact.parentSha,
@@ -7403,6 +9872,7 @@ export class Dispatcher {
7403
9872
  }
7404
9873
  let context: string | undefined
7405
9874
  let headPaths: HeadPathsArtifact | undefined
9875
+ let retained: RetentionOutcome | undefined
7406
9876
  await this.withKernelRepository(async (path) => {
7407
9877
  const head = await forge.rewrite!.snapshot({
7408
9878
  workspacePath: path,
@@ -7411,11 +9881,6 @@ export class Dispatcher {
7411
9881
  })
7412
9882
  if (head !== exact.headSha)
7413
9883
  throw new Error('node head moved while preparing verification')
7414
- await forge.rewrite!.archive({
7415
- workspacePath: path,
7416
- ref: `refs/autobuild/archive/${record.slug}/${head}`,
7417
- sha: head,
7418
- })
7419
9884
  const exec = forge.kernelExec ?? this.deps.exec
7420
9885
  // Snapshot fetch brings the complete head ancestry, including merge sides.
7421
9886
  // A parent may have advanced independently and need its own fetch.
@@ -7429,6 +9894,22 @@ export class Dispatcher {
7429
9894
  if (fetched.exitCode !== 0)
7430
9895
  throw new Error(`cannot fetch node verification parent: ${fetched.stderr}`)
7431
9896
  }
9897
+ // Best effort, once the parent a store copy excludes is present: the
9898
+ // head stays reachable from the published node branch.
9899
+ retained = await retainCommit(
9900
+ {
9901
+ store: this.store,
9902
+ slug: record.slug,
9903
+ exec,
9904
+ workspacePath: path,
9905
+ archive: forge.rewrite!.archive,
9906
+ exclude: exact.parentSha,
9907
+ local: forge.name === 'local-git',
9908
+ branch: record.branch!,
9909
+ targetBranch: state.baseBranch!,
9910
+ },
9911
+ head,
9912
+ )
7432
9913
  // The cycle's candidate head is recorded once, with the cycle.
7433
9914
  if (!headPathsFor(current, exact.headSha).recorded)
7434
9915
  headPaths = await computeHeadPaths(exec, path, {
@@ -7450,6 +9931,31 @@ export class Dispatcher {
7450
9931
  })
7451
9932
  if (!(await this.store.renewNodeWriter(record.slug, holder))) return
7452
9933
  let expectedSeq = current.lastSeq
9934
+ if (retained !== undefined && retained.in !== 'forge') {
9935
+ // Recorded under the writer lease, then the guards are re-read so the
9936
+ // compare-and-append below starts from the retention fact.
9937
+ await recordRetention(
9938
+ this.store,
9939
+ record.slug,
9940
+ {
9941
+ event: 'node.history-retained',
9942
+ operation: 'verify',
9943
+ id: cycle.id,
9944
+ base: exact.parentSha,
9945
+ },
9946
+ [retained],
9947
+ )
9948
+ const latest = (await this.store.buildFacts(record.slug)).state
9949
+ if (
9950
+ latest.nodeRestack?.active ||
9951
+ latest.nodeRestack?.parentRequest ||
9952
+ latest.nodeRestack?.parentChange ||
9953
+ latest.pendingCommands.length ||
9954
+ latest.integration?.landing
9955
+ )
9956
+ return
9957
+ expectedSeq = latest.lastSeq
9958
+ }
7453
9959
  if (headPaths !== undefined) {
7454
9960
  const { artifacts, makeEvent } = headPathsWrite(headPaths, 'integration', DISPATCHER)
7455
9961
  const recorded = await this.store.appendWithArtifactsIfCurrent(
@@ -7490,18 +9996,47 @@ export class Dispatcher {
7490
9996
  }
7491
9997
  if (integrationFailed(state) || integrationVerified(state, config)) {
7492
9998
  const facts = (await readBuildFacts(this.store, record.slug)).value
7493
- if (openWorkspace(facts)) await this.releaseWorkspace(record.slug, facts)
9999
+ // The proposer's workspace is released by its filing.
10000
+ if (openWorkspace(facts) && !proposeRunDue(state.optimization))
10001
+ await this.releaseWorkspace(record.slug, facts)
7494
10002
  return
7495
10003
  }
7496
- if (!(await this.nodeHasCapacity(record.slug))) return
10004
+ if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
7497
10005
  await this.observeIntegration(record.slug)
7498
10006
  state = (await this.store.buildFacts(record.slug)).state
7499
10007
  if (!integrationCurrent(state)) return
7500
10008
  if (!this.accountsAvailable()) return
7501
10009
  const facts = (await readBuildFacts(this.store, record.slug)).value
10010
+ await this.provisionNodeAndLaunch(
10011
+ record,
10012
+ facts,
10013
+ report,
10014
+ launched,
10015
+ state.integration!.cycle!.head,
10016
+ )
10017
+ }
10018
+
10019
+ /** Provision a node's workspace when it has none, then launch its runner. A
10020
+ * recovery-capable provider provisions and launches in its background
10021
+ * continuation instead. */
10022
+ private async provisionNodeAndLaunch(
10023
+ record: BuildRecord,
10024
+ read: CurrentBuildFacts,
10025
+ report: TickReport,
10026
+ launched: Set<string>,
10027
+ revision?: string,
10028
+ ): Promise<void> {
10029
+ const branch = record.branch
10030
+ if (!branch) return
10031
+ // Both verification and baseline measurement must recover flagged workspaces.
10032
+ const facts = await this.replaceFlaggedWorkspace(record, read, launched)
10033
+ if (facts === undefined) return
7502
10034
  if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
7503
10035
  const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
7504
10036
  if (kicked === 'kicked') report.provisioning++
10037
+ else if (kicked === 'budget-wait') report.provisioningDeferred++
10038
+ // After a reap, this tick's sweep leaves the replacement alone.
10039
+ if (kicked === 'kicked' && facts !== read) launched.add(record.slug)
7505
10040
  return
7506
10041
  }
7507
10042
  if (openWorkspace(facts) === null) {
@@ -7509,9 +10044,9 @@ export class Dispatcher {
7509
10044
  try {
7510
10045
  handle = await this.provisionWorkspace(record.slug, {
7511
10046
  repo: this.deps.checkout ?? this.deps.repo,
7512
- baseBranch: record.branch,
7513
- branch: record.branch,
7514
- revision: state.integration!.cycle!.head,
10047
+ baseBranch: branch,
10048
+ branch,
10049
+ ...(revision !== undefined ? { revision } : {}),
7515
10050
  })
7516
10051
  } catch (error) {
7517
10052
  if (await this.holdForMissingAccounts(error)) return
@@ -8030,14 +10565,18 @@ export class Dispatcher {
8030
10565
  /** Bounce (§6.3): back to Triage with a comment citing the standard and
8031
10566
  * WHICH parts are missing — failure at the cheapest point, not a build
8032
10567
  * that thrashes and escalates. No build is created. */
8033
- private async bounce(ticket: Ticket, missing: string[]): Promise<void> {
10568
+ private async bounce(ticket: Ticket, missing: string[], refused = false): Promise<void> {
8034
10569
  const triageState = this.triageState()
8035
10570
  await this.deps.tickets.transition(ticket.ref.id, triageState)
8036
10571
  await this.deps.tickets.comment(
8037
10572
  ticket.ref.id,
8038
- `Bounced back to ${triageState}: this ticket does not conform to ` +
8039
- `the spec standard (.agents/skills/ab-guide/references/spec-standard.md) and cannot be dispatched.\n` +
8040
- `Missing: ${missing.join('; ')}.`,
10573
+ refused
10574
+ ? `Bounced back to ${triageState}: this ticket's spec cannot open as dispatched ` +
10575
+ `(.agents/skills/ab-guide/references/optimization-nodes.md).\n` +
10576
+ `Refused: it needs ${missing.join('; ')}.`
10577
+ : `Bounced back to ${triageState}: this ticket does not conform to ` +
10578
+ `the spec standard (.agents/skills/ab-guide/references/spec-standard.md) and cannot be dispatched.\n` +
10579
+ `Missing: ${missing.join('; ')}.`,
8041
10580
  )
8042
10581
  }
8043
10582