@defrex/autobuild 1.8.1 → 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 (429) hide show
  1. package/README.md +3 -3
  2. package/SPEC.md +1602 -134
  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 +320 -53
  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 +515 -49
  11. package/docs/dispatcher-hosting.md +4 -0
  12. package/docs/dispatcher.md +17 -3
  13. package/docs/forges.md +1 -1
  14. package/docs/getting-started.md +1 -1
  15. package/docs/integration-overview.md +4 -2
  16. package/docs/integration-tree.md +102 -11
  17. package/docs/merge-policy.md +70 -14
  18. package/docs/migration-1.0.md +2 -1
  19. package/docs/operating.md +53 -4
  20. package/docs/operator-api.md +128 -16
  21. package/docs/optimization-nodes.md +1042 -0
  22. package/docs/overview.md +1 -1
  23. package/docs/plugin-authoring.md +50 -13
  24. package/docs/remote-store-protocol.md +46 -7
  25. package/docs/remote-ticket-protocol.md +50 -2
  26. package/docs/restacking.md +102 -10
  27. package/docs/seams.md +2 -2
  28. package/docs/setup.md +16 -3
  29. package/docs/skills.md +4 -2
  30. package/docs/spec-standard.md +2 -1
  31. package/docs/ticket-dependencies.md +5 -0
  32. package/docs/ticket-migration.md +4 -2
  33. package/docs/ticket-sources.md +30 -12
  34. package/docs/tickets.md +15 -6
  35. package/docs/troubleshooting.md +3 -2
  36. package/docs/verification.md +18 -6
  37. package/docs/workspaces.md +3 -1
  38. package/package.json +4 -3
  39. package/packages/core/src/accounts/chatgpt-oauth.ts +7 -5
  40. package/packages/core/src/cli/attempt.ts +103 -0
  41. package/packages/core/src/cli/attention.ts +11 -1
  42. package/packages/core/src/cli/binary-direct.ts +52 -1
  43. package/packages/core/src/cli/binary.ts +5 -3
  44. package/packages/core/src/cli/build-control.ts +328 -66
  45. package/packages/core/src/cli/context.ts +268 -15
  46. package/packages/core/src/cli/dashboard/detail.ts +26 -2
  47. package/packages/core/src/cli/dashboard/facts.ts +40 -3
  48. package/packages/core/src/cli/dashboard/integration-detail.ts +7 -2
  49. package/packages/core/src/cli/dashboard/landing-display.ts +24 -3
  50. package/packages/core/src/cli/dashboard/model.ts +127 -33
  51. package/packages/core/src/cli/dashboard/objective-row.ts +189 -0
  52. package/packages/core/src/cli/dashboard/render.ts +49 -3
  53. package/packages/core/src/cli/dashboard/reopen-display.ts +39 -0
  54. package/packages/core/src/cli/dashboard/tree.ts +12 -1
  55. package/packages/core/src/cli/dispatch-frontend.ts +9 -1
  56. package/packages/core/src/cli/dispatch-launch-stop.ts +55 -0
  57. package/packages/core/src/cli/dispatch-launcher.ts +26 -44
  58. package/packages/core/src/cli/dispatch-repository-feed.ts +1 -1
  59. package/packages/core/src/cli/dispatch.ts +136 -5
  60. package/packages/core/src/cli/env.ts +42 -0
  61. package/packages/core/src/cli/help.ts +212 -11
  62. package/packages/core/src/cli/init-agent.ts +4 -1
  63. package/packages/core/src/cli/init-readiness-remote.ts +3 -2
  64. package/packages/core/src/cli/init-validation.ts +2 -2
  65. package/packages/core/src/cli/init.ts +3 -2
  66. package/packages/core/src/cli/judge-entry.ts +82 -0
  67. package/packages/core/src/cli/judge.ts +233 -0
  68. package/packages/core/src/cli/landings.ts +3 -2
  69. package/packages/core/src/cli/main.ts +412 -143
  70. package/packages/core/src/cli/measurement-text.ts +19 -0
  71. package/packages/core/src/cli/objective.ts +154 -0
  72. package/packages/core/src/cli/publication-settlement.ts +106 -22
  73. package/packages/core/src/cli/repo-lease.ts +1 -0
  74. package/packages/core/src/cli/repository-status.ts +179 -19
  75. package/packages/core/src/cli/status.ts +195 -17
  76. package/packages/core/src/cli/store-opening.ts +4 -0
  77. package/packages/core/src/cli/terminals.ts +205 -8
  78. package/packages/core/src/cli/ticket-start.ts +53 -0
  79. package/packages/core/src/cli/ticket.ts +68 -2
  80. package/packages/core/src/cli/upgrade-agent.ts +12 -8
  81. package/packages/core/src/cli/wait.ts +8 -2
  82. package/packages/core/src/cli/watch.ts +1325 -628
  83. package/packages/core/src/config/create-labels.ts +23 -0
  84. package/packages/core/src/config/live.ts +3 -0
  85. package/packages/core/src/config/load.ts +19 -0
  86. package/packages/core/src/config/pipeline-source.ts +1 -3
  87. package/packages/core/src/config/roles.ts +182 -73
  88. package/packages/core/src/config/schema.ts +226 -9
  89. package/packages/core/src/events/catalog.ts +41 -3
  90. package/packages/core/src/events/compatibility.ts +7 -1
  91. package/packages/core/src/events/payloads.ts +610 -1
  92. package/packages/core/src/events/policy.ts +62 -0
  93. package/packages/core/src/events/repository.ts +147 -21
  94. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +1512 -199
  95. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/0ab2a90d0305dc9d.json.gz +0 -0
  96. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/10a4657408d4e121.json.gz +0 -0
  97. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1152a2e97ee81728.json.gz +0 -0
  98. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/13ca84752c5f8b54.json.gz +0 -0
  99. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1411d1cdbdd9911e.json.gz +0 -0
  100. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1444fe1fa7fc802c.json.gz +0 -0
  101. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1491ac0600349391.json.gz +0 -0
  102. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1921f86f752428c9.json.gz +0 -0
  103. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1972c1d66008ef6b.json.gz +0 -0
  104. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/19e8e43e7f3f1a06.json.gz +0 -0
  105. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/20a85c143c3e8164.json.gz +0 -0
  106. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/21ce2c0bf58318e1.json.gz +0 -0
  107. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/293dcb3a94fb3470.json.gz +0 -0
  108. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2ab7436356267118.json.gz +0 -0
  109. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2d084641735caaff.json.gz +0 -0
  110. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3237bcecf68e5db9.json.gz +0 -0
  111. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/33d0cc593610e56f.json.gz +0 -0
  112. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3451ed2136dcc356.json.gz +0 -0
  113. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/358ec8693f2237e6.json.gz +0 -0
  114. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/35cf9ccc4478b2d2.json.gz +0 -0
  115. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3649e7bd1203f154.json.gz +0 -0
  116. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/378da6dece82202a.json.gz +0 -0
  117. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/38c75099d9191471.json.gz +0 -0
  118. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/398952f1f01db1a3.json.gz +0 -0
  119. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3b64d352d56c9121.json.gz +0 -0
  120. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3dc486226c05372d.json.gz +0 -0
  121. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/431c9bb2ee8838e0.json.gz +0 -0
  122. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4400dffca929e2f0.json.gz +0 -0
  123. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/49064fc079964a5c.json.gz +0 -0
  124. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4edded75f17742f4.json.gz +0 -0
  125. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4f00c0f2c8afd159.json.gz +0 -0
  126. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516a5a7aadf97587.json.gz +0 -0
  127. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516dc6ea85d67cd7.json.gz +0 -0
  128. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/584e2ba74608e051.json.gz +0 -0
  129. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/59ffaa6974094c72.json.gz +0 -0
  130. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5bb43afb121674c6.json.gz +0 -0
  131. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5f0ca42af862c4ee.json.gz +0 -0
  132. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6118031132db9bfc.json.gz +0 -0
  133. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63107a8d58776b63.json.gz +0 -0
  134. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63546b08d4d6fa11.json.gz +0 -0
  135. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/643d70429ce03dad.json.gz +0 -0
  136. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/677ea92572c29082.json.gz +0 -0
  137. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6ae5bf60504d6467.json.gz +0 -0
  138. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6efdc8defc75fccb.json.gz +0 -0
  139. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/71c53d33f09d8204.json.gz +0 -0
  140. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7267ca2757cffba7.json.gz +0 -0
  141. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/76b7d4244082b3f9.json.gz +0 -0
  142. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7749f918c6f10968.json.gz +0 -0
  143. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7833e42d16301424.json.gz +0 -0
  144. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7d4edad0614adaf1.json.gz +0 -0
  145. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/837365898d04f45a.json.gz +0 -0
  146. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/85f9f0c921b8b5bb.json.gz +0 -0
  147. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8879f57a24733897.json.gz +0 -0
  148. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/88cb9e71bdec972d.json.gz +0 -0
  149. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8a0cd6dd06cc155e.json.gz +0 -0
  150. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8aa9ca8609dc051d.json.gz +0 -0
  151. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8c8640255bd61658.json.gz +0 -0
  152. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8cc15eb1807c0157.json.gz +0 -0
  153. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8ced97c44bc0af3a.json.gz +0 -0
  154. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8d4144004720b9f8.json.gz +0 -0
  155. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8db633ead1807f8b.json.gz +0 -0
  156. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8e42cdbd0994ab0c.json.gz +0 -0
  157. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9011d0f6ff955ef9.json.gz +0 -0
  158. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/916ebc5433801c41.json.gz +0 -0
  159. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9539b995af5c54a9.json.gz +0 -0
  160. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/95f391bfd7b7dbd7.json.gz +0 -0
  161. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9613e8fa568a9281.json.gz +0 -0
  162. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9a68f8753bd9038d.json.gz +0 -0
  163. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9b25e58227080094.json.gz +0 -0
  164. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9ee3919fbd4f9458.json.gz +0 -0
  165. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a04a34cc2717147b.json.gz +0 -0
  166. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a0b32c12e4e6edb6.json.gz +0 -0
  167. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a55218252707bdd3.json.gz +0 -0
  168. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a732fd08b31522a6.json.gz +0 -0
  169. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a9d206a01f9039e5.json.gz +0 -0
  170. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/abf7fe3c92c82f2d.json.gz +0 -0
  171. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ac928b04842c00db.json.gz +0 -0
  172. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/af953392d81911da.json.gz +0 -0
  173. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0d877c44810ecb0.json.gz +0 -0
  174. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0f7c6ebb2db57fc.json.gz +0 -0
  175. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b905c22ec17eed31.json.gz +0 -0
  176. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/bce0c54e865f4b79.json.gz +0 -0
  177. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c68b7ee2e2610f30.json.gz +0 -0
  178. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c7f7e0378aeea237.json.gz +0 -0
  179. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c98cb1659eb142b6.json.gz +0 -0
  180. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ca830adf06ed55a1.json.gz +0 -0
  181. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cb3a219f33e437ca.json.gz +0 -0
  182. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cf1e0c0d82567e0c.json.gz +0 -0
  183. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d008d86d9ff77b30.json.gz +0 -0
  184. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d1432a819d8e48c5.json.gz +0 -0
  185. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d185ed6aa9192aff.json.gz +0 -0
  186. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d873fad29d6c7e55.json.gz +0 -0
  187. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/db84b12316e2da4a.json.gz +0 -0
  188. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ddf6dc967d898767.json.gz +0 -0
  189. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/dfc64de6e7bfc0a0.json.gz +0 -0
  190. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e2f18fa32fe1f6d0.json.gz +0 -0
  191. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e37393fed29e84c5.json.gz +0 -0
  192. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e6a8585e2a054ff6.json.gz +0 -0
  193. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e7e9e327baca6903.json.gz +0 -0
  194. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e86447af0571672c.json.gz +0 -0
  195. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ea819202d22122e5.json.gz +0 -0
  196. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb4535585f2e84f6.json.gz +0 -0
  197. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb7ddd5319d09e27.json.gz +0 -0
  198. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eca4959b2b87ae15.json.gz +0 -0
  199. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ee10d7959ec4843c.json.gz +0 -0
  200. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ef1b68347966ab26.json.gz +0 -0
  201. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f3e55425cc41f230.json.gz +0 -0
  202. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f40042c1cdb9fd43.json.gz +0 -0
  203. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f48466215c790a3f.json.gz +0 -0
  204. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f5b9ace9b59351e7.json.gz +0 -0
  205. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fa8f1475a55be935.json.gz +0 -0
  206. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fb21116a15d0b1f1.json.gz +0 -0
  207. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fe95444fbeabe592.json.gz +0 -0
  208. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/09bf0a1611d07363.json +984 -0
  209. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/10eac4988d66e161.json +1067 -0
  210. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/1a436b5fb45aee3e.json +1116 -0
  211. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/249db6f7a41f90e2.json +161 -0
  212. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/25dcb2fb6eaa83f4.json +858 -0
  213. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/2e1bdc763924616f.json +4932 -0
  214. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/30e9dabce3c4263d.json +399 -0
  215. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/4898ef339c68fa36.json +83 -0
  216. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/51816c0ffa62af6e.json +417 -0
  217. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/561bf45320062a44.json +83 -0
  218. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5672d0233085d050.json +84 -0
  219. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5e39f42cbdbf35ef.json +163 -0
  220. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/7771a7a2250f9964.json +868 -0
  221. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/881c491321bec99a.json +1074 -0
  222. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/965f25c3af1d2cdc.json +160 -0
  223. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9b76d89da575ca90.json +20 -0
  224. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9eb485320a72a9ff.json +233 -0
  225. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a60448c01016135e.json +18 -0
  226. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6584fb61b6679bd.json +97 -0
  227. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c88365c25b3186d3.json +543 -0
  228. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e8f0481b23f90056.json +711 -0
  229. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ee55782ed40ebbac.json +110 -0
  230. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc5082fac8167f3d.json +98 -0
  231. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fd55c329cfe921cc.json +1069 -0
  232. package/packages/core/src/kernel/attempt-creation-key.ts +20 -0
  233. package/packages/core/src/kernel/attempt-settlement.ts +125 -0
  234. package/packages/core/src/kernel/auto-merge-default.ts +1 -3
  235. package/packages/core/src/kernel/auto-merge.ts +34 -3
  236. package/packages/core/src/kernel/dispatch-capacity.ts +312 -38
  237. package/packages/core/src/kernel/dispatch-placement.ts +1 -1
  238. package/packages/core/src/kernel/dispatch-settings.ts +1 -4
  239. package/packages/core/src/kernel/dispatch-status.ts +3 -5
  240. package/packages/core/src/kernel/dispatch-upgrade.ts +1 -1
  241. package/packages/core/src/kernel/engine.ts +109 -13
  242. package/packages/core/src/kernel/forge-checks.ts +140 -0
  243. package/packages/core/src/kernel/forge-health.ts +2 -2
  244. package/packages/core/src/kernel/generated-files.ts +43 -0
  245. package/packages/core/src/kernel/generated-regeneration.ts +254 -0
  246. package/packages/core/src/kernel/generators/build-log.ts +30 -2
  247. package/packages/core/src/kernel/generators/optimization-log.ts +578 -0
  248. package/packages/core/src/kernel/generators/panel-log.ts +133 -0
  249. package/packages/core/src/kernel/generators/repository-journals.ts +18 -0
  250. package/packages/core/src/kernel/guarded-forge.ts +76 -11
  251. package/packages/core/src/kernel/harvest.ts +1 -4
  252. package/packages/core/src/kernel/head-paths.ts +4 -1
  253. package/packages/core/src/kernel/history-retention.ts +337 -0
  254. package/packages/core/src/kernel/incremental-fixtures.ts +6 -0
  255. package/packages/core/src/kernel/incremental.ts +14 -4
  256. package/packages/core/src/kernel/integration-landing.ts +64 -13
  257. package/packages/core/src/kernel/integration-stack.ts +123 -20
  258. package/packages/core/src/kernel/integration-state.ts +39 -2
  259. package/packages/core/src/kernel/janitor-failure.ts +2 -0
  260. package/packages/core/src/kernel/kernel-git.ts +1 -1
  261. package/packages/core/src/kernel/landing-measurement.ts +275 -0
  262. package/packages/core/src/kernel/landing-readiness.ts +2 -0
  263. package/packages/core/src/kernel/landing-state.ts +76 -1
  264. package/packages/core/src/kernel/leaf-restack-state.ts +17 -1
  265. package/packages/core/src/kernel/log-index-value.ts +2 -0
  266. package/packages/core/src/kernel/log-index.ts +81 -3
  267. package/packages/core/src/kernel/measurement.ts +406 -0
  268. package/packages/core/src/kernel/mixed-version.ts +6 -3
  269. package/packages/core/src/kernel/node-landing.ts +92 -18
  270. package/packages/core/src/kernel/node-restack-state.ts +27 -1
  271. package/packages/core/src/kernel/node-restack-transaction.ts +80 -23
  272. package/packages/core/src/kernel/node-verification-context.ts +14 -4
  273. package/packages/core/src/kernel/open-pr-backpressure-state.ts +24 -0
  274. package/packages/core/src/kernel/open-pr-backpressure.ts +133 -0
  275. package/packages/core/src/kernel/optimization-admission.ts +249 -0
  276. package/packages/core/src/kernel/optimization.ts +774 -0
  277. package/packages/core/src/kernel/panel.ts +225 -0
  278. package/packages/core/src/kernel/phases.ts +42 -6
  279. package/packages/core/src/kernel/pr-attachments.ts +4 -16
  280. package/packages/core/src/kernel/pr-summary.ts +2 -2
  281. package/packages/core/src/kernel/read-deferrals.ts +2 -2
  282. package/packages/core/src/kernel/read-facts.ts +69 -31
  283. package/packages/core/src/kernel/reconcile-restack.ts +352 -103
  284. package/packages/core/src/kernel/reducer-identity.ts +659 -0
  285. package/packages/core/src/kernel/reducer-registry.ts +37 -3
  286. package/packages/core/src/kernel/reducer-revisions.ts +50 -0
  287. package/packages/core/src/kernel/reducer.ts +208 -9
  288. package/packages/core/src/kernel/reopen-state.ts +48 -0
  289. package/packages/core/src/kernel/reopen.ts +143 -0
  290. package/packages/core/src/kernel/replay-retention.ts +208 -39
  291. package/packages/core/src/kernel/repository-attention.ts +1 -1
  292. package/packages/core/src/kernel/service-facts.ts +19 -7
  293. package/packages/core/src/kernel/terminal-guard.ts +13 -5
  294. package/packages/core/src/kernel/ticket-handbacks.ts +1 -1
  295. package/packages/core/src/kernel/ticket-migrations.ts +1 -1
  296. package/packages/core/src/kernel/ticket-preparation.ts +1 -1
  297. package/packages/core/src/kernel/ticket-source-health.ts +1 -1
  298. package/packages/core/src/kernel/ticket-starts.ts +118 -0
  299. package/packages/core/src/kernel/ticket-wait.ts +37 -2
  300. package/packages/core/src/kernel/verify-diff-base.ts +62 -0
  301. package/packages/core/src/kernel/verify-stage-state.ts +1 -0
  302. package/packages/core/src/kernel/verify-stages.ts +41 -1
  303. package/packages/core/src/objective.ts +532 -0
  304. package/packages/core/src/ontology.ts +49 -6
  305. package/packages/core/src/operator/annotations.ts +35 -4
  306. package/packages/core/src/operator/control.ts +2 -1
  307. package/packages/core/src/operator/index.ts +12 -0
  308. package/packages/core/src/operator/optimization.ts +307 -0
  309. package/packages/core/src/operator/protocol.ts +30 -1
  310. package/packages/core/src/operator/query.ts +15 -1
  311. package/packages/core/src/operator/registry.ts +219 -13
  312. package/packages/core/src/operator/requests.ts +25 -2
  313. package/packages/core/src/operator/ticket-start.ts +152 -0
  314. package/packages/core/src/operator/tickets.ts +3 -2
  315. package/packages/core/src/plugin-sdk/index.ts +9 -1
  316. package/packages/core/src/plugins/registry.ts +1 -0
  317. package/packages/core/src/ports/forge/contract.ts +9 -0
  318. package/packages/core/src/ports/forge/fake.ts +151 -10
  319. package/packages/core/src/ports/forge/git-rewrite.ts +38 -5
  320. package/packages/core/src/ports/forge/github-readiness.ts +1 -1
  321. package/packages/core/src/ports/forge/github-squash-message.ts +89 -0
  322. package/packages/core/src/ports/forge/github-transport.ts +186 -1
  323. package/packages/core/src/ports/forge/github.ts +846 -239
  324. package/packages/core/src/ports/forge/readiness.ts +15 -3
  325. package/packages/core/src/ports/forge-failure.ts +22 -0
  326. package/packages/core/src/ports/forge-request-context.ts +23 -1
  327. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  328. package/packages/core/src/ports/runner/antigravity.ts +1071 -0
  329. package/packages/core/src/ports/runner/claude.ts +6 -1
  330. package/packages/core/src/ports/runner/codex.ts +11 -2
  331. package/packages/core/src/ports/runner/contract.ts +25 -1
  332. package/packages/core/src/ports/runner/fake.ts +2 -2
  333. package/packages/core/src/ports/runner/native-cli-fixture.ts +40 -5
  334. package/packages/core/src/ports/runner/native-process-fixture.ts +4 -1
  335. package/packages/core/src/ports/runner/pi.ts +23 -7
  336. package/packages/core/src/ports/runner/production.ts +19 -2
  337. package/packages/core/src/ports/runner/session-env.ts +65 -5
  338. package/packages/core/src/ports/runner/start-prompt.ts +6 -4
  339. package/packages/core/src/ports/tickets/contract.ts +4 -2
  340. package/packages/core/src/ports/tickets/github.ts +20 -5
  341. package/packages/core/src/ports/tickets/hosted-index.ts +6 -1
  342. package/packages/core/src/ports/tickets/labels.ts +21 -0
  343. package/packages/core/src/ports/tickets/linear.ts +33 -0
  344. package/packages/core/src/ports/tickets/migration.ts +2 -0
  345. package/packages/core/src/ports/tickets/priority.ts +11 -0
  346. package/packages/core/src/ports/tickets/remote-protocol.ts +71 -6
  347. package/packages/core/src/ports/tickets/remote.ts +138 -16
  348. package/packages/core/src/ports/tickets/tree.ts +17 -4
  349. package/packages/core/src/ports/types.ts +145 -7
  350. package/packages/core/src/ports/workspace/builtin-capabilities.ts +7 -4
  351. package/packages/core/src/ports/workspace/commit-preservation.ts +182 -64
  352. package/packages/core/src/ports/workspace/create.ts +3 -0
  353. package/packages/core/src/ports/workspace/git-worktree.ts +13 -1
  354. package/packages/core/src/ports/workspace/vercel-sandbox.ts +242 -61
  355. package/packages/core/src/processes/build-execution-state.ts +5 -6
  356. package/packages/core/src/processes/build-runner.ts +1435 -132
  357. package/packages/core/src/processes/dispatch-failure-budget.ts +1 -1
  358. package/packages/core/src/processes/dispatcher-selectors.ts +15 -13
  359. package/packages/core/src/processes/dispatcher.ts +2874 -266
  360. package/packages/core/src/processes/execution-no-progress.ts +38 -1
  361. package/packages/core/src/processes/execution-settlement.ts +2 -6
  362. package/packages/core/src/processes/harvest-execution-state.ts +2 -6
  363. package/packages/core/src/processes/harvest-runner.ts +7 -2
  364. package/packages/core/src/processes/hook-command.ts +125 -0
  365. package/packages/core/src/processes/hook-webhook.ts +144 -0
  366. package/packages/core/src/processes/hooks.ts +740 -0
  367. package/packages/core/src/processes/infrastructure-failure-budget.ts +1 -3
  368. package/packages/core/src/processes/judge-launcher.ts +38 -0
  369. package/packages/core/src/processes/measurement-runner.ts +235 -0
  370. package/packages/core/src/processes/optimization-merges.ts +101 -0
  371. package/packages/core/src/processes/optimization-stop.ts +179 -0
  372. package/packages/core/src/processes/panel-runner.ts +756 -0
  373. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  374. package/packages/core/src/processes/publication-state.ts +1 -4
  375. package/packages/core/src/processes/repo-view.ts +77 -5
  376. package/packages/core/src/processes/sandbox-state.ts +1 -4
  377. package/packages/core/src/processes/tick-state.ts +1 -3
  378. package/packages/core/src/processes/workspace-preservation.ts +67 -9
  379. package/packages/core/src/scenarios/harness.ts +19 -8
  380. package/packages/core/src/store/contract.ts +72 -0
  381. package/packages/core/src/store/digest.ts +89 -7
  382. package/packages/core/src/store/judge-authority.ts +161 -0
  383. package/packages/core/src/store/phase-session.ts +226 -4
  384. package/packages/core/src/store/reduced-reads.ts +10 -0
  385. package/packages/core/src/store/reducer-value-shapes.json +17254 -11861
  386. package/packages/core/src/store/remote/client.ts +12 -2
  387. package/packages/core/src/store/remote/credentials.ts +31 -1
  388. package/packages/core/src/store/remote/index.ts +8 -0
  389. package/packages/core/src/store/remote/protocol.ts +38 -0
  390. package/packages/core/src/store/remote/released-clients.json +22 -0
  391. package/packages/core/src/store/remote/released-reducer-values/1.10.0.json +34439 -0
  392. package/packages/core/src/store/remote/released-reducer-values/1.9.0.json +29475 -0
  393. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -14
  394. package/packages/core/src/store/remote/token.ts +13 -4
  395. package/packages/core/src/store/repo-state-events.ts +9 -8
  396. package/packages/core/src/store/retention.ts +16 -2
  397. package/packages/core/src/store/session-reducer.ts +1 -4
  398. package/packages/core/src/store/ticket-assets.ts +1 -3
  399. package/packages/core/src/store/types.ts +9 -0
  400. package/packages/core/src/testing/dispatch-read-budget.ts +70 -0
  401. package/packages/core/src/testing/git-config-isolation.ts +25 -0
  402. package/packages/core/src/testing/index.ts +14 -0
  403. package/packages/core/src/testing/reduced-read-budget.ts +3950 -54
  404. package/skills/code-review/SKILL.md +16 -0
  405. package/skills/finalize/SKILL.md +10 -4
  406. package/skills/guide/SKILL.md +464 -83
  407. package/skills/guide/references/integration-tree.md +102 -11
  408. package/skills/guide/references/merge-policy.md +70 -14
  409. package/skills/guide/references/migration-1.0.md +2 -1
  410. package/skills/guide/references/operator-api.md +128 -16
  411. package/skills/guide/references/optimization-nodes.md +1042 -0
  412. package/skills/guide/references/plugin-authoring.md +50 -13
  413. package/skills/guide/references/remote-store-protocol.md +46 -7
  414. package/skills/guide/references/remote-ticket-protocol.md +50 -2
  415. package/skills/guide/references/restacking.md +102 -10
  416. package/skills/guide/references/setup.md +16 -3
  417. package/skills/guide/references/spec-standard.md +2 -1
  418. package/skills/guide/references/ticket-dependencies.md +5 -0
  419. package/skills/guide/references/ticket-migration.md +4 -2
  420. package/skills/implement/SKILL.md +51 -1
  421. package/skills/judge/SKILL.md +43 -0
  422. package/skills/operate/SKILL.md +267 -32
  423. package/skills/plan/SKILL.md +18 -0
  424. package/skills/plan-review/SKILL.md +15 -1
  425. package/skills/propose/SKILL.md +121 -0
  426. package/skills/reconcile/SKILL.md +21 -2
  427. package/skills/spec/SKILL.md +30 -4
  428. package/skills/tickets/SKILL.md +44 -5
  429. 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,22 +86,62 @@ import {
74
86
  type JanitorOperation,
75
87
  } from '../kernel/janitor-failure'
76
88
  import { KernelGitUnavailable, kernelGitUnavailableDetail } from '../kernel/kernel-git'
77
- import { isForgeFailure } from '../ports/forge-failure'
89
+ import {
90
+ backpressureExplanation,
91
+ backpressureTransition,
92
+ openPrBackpressure,
93
+ openPrBackpressurePolicy,
94
+ openPrCount,
95
+ } from '../kernel/open-pr-backpressure'
96
+ import { isForgeFailure, isForgeRejection } from '../ports/forge-failure'
78
97
  import {
79
98
  ForgeRequestDeferred,
80
99
  withForgeRequestContext,
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,9 +152,12 @@ 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 {
160
+ currentLandingFallback,
106
161
  landingAuthorized,
107
162
  nativeLandingApplied,
108
163
  sameLandingCandidate,
@@ -123,6 +178,7 @@ import {
123
178
  integrationVerified,
124
179
  integrationHeadVerified,
125
180
  integrationAdmissible,
181
+ nodeLanded,
126
182
  } from '../kernel/integration-state'
127
183
  import {
128
184
  normalizeIdentities,
@@ -143,18 +199,45 @@ import {
143
199
  type PresenceWitness,
144
200
  } from '../kernel/change-presence'
145
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'
146
227
  import { mkdtemp, rm } from 'node:fs/promises'
147
228
  import { tmpdir } from 'node:os'
148
229
  import { join } from 'node:path'
149
230
  import { runNodeTransaction } from '../kernel/node-restack-transaction'
150
231
  import { hasBuildTrailer } from '../kernel/build-identity'
151
- import { digestNodeTargets } from '../store/digest'
232
+ import { BuildDigestCapabilityError, digestNodeTargets, digestOptimization } from '../store/digest'
152
233
  import { readBuildDigests, readForgeHealth } from '../store/reduced-reads'
234
+ import { enforceOptimizationStop } from './optimization-stop'
235
+ import { reconcileMergedAttempts } from './optimization-merges'
153
236
  import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
154
237
  import { ensureExecutionProgress } from './execution-no-progress'
155
238
  import { ticketIdentity } from '../ports/tickets/identity'
156
239
  import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
157
- import { urgentFirst } from '../ports/tickets/priority'
240
+ import { ticketPriority, urgentFirst } from '../ports/tickets/priority'
158
241
  import { ensureDispatchBudget } from './dispatch-failure-budget'
159
242
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
160
243
  /**
@@ -201,7 +284,12 @@ import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
201
284
  import { isRemoteWorkspace } from '../events/workspace-remote'
202
285
  import type { AbEvent, EventWrite } from '../events/catalog'
203
286
  import type { AbortDestination, EventPayload, PinnedAsset } from '../events/payloads'
204
- 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'
205
293
  import { handbackIdentity } from '../kernel/ticket-handbacks'
206
294
  import type { IdSource } from '../ids'
207
295
  import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
@@ -226,13 +314,20 @@ import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution
226
314
  import type {
227
315
  DependencyState,
228
316
  Forge,
317
+ HeadChecks,
229
318
  IssueLink,
319
+ PrState,
230
320
  Ticket,
321
+ TicketPriority,
231
322
  TicketSource,
232
323
  WorkspaceProvider,
233
324
  WorkspaceProvisionResult,
234
325
  } from '../ports/types'
235
- import { NoCommitsBetweenBranchesError, TicketSourceRateLimitError } from '../ports/types'
326
+ import {
327
+ isForgeMergeQueueRejection,
328
+ NoCommitsBetweenBranchesError,
329
+ TicketSourceRateLimitError,
330
+ } from '../ports/types'
236
331
  import { issueLinksForForge } from '../kernel/issue-keywords'
237
332
  import {
238
333
  contributedIssueLinks,
@@ -252,6 +347,13 @@ import { creationBuildSlug } from '../kernel/build-creation'
252
347
  import { preparePinnedAssets } from '../store/ticket-assets'
253
348
  import { resolveRepoOrigin } from '../cli/repo-state'
254
349
  import { specConformance } from '../spec-standard'
350
+ import {
351
+ objectiveBlocks,
352
+ objectiveRefusals,
353
+ objectiveRulerChanged,
354
+ parseObjective,
355
+ type Objective,
356
+ } from '../objective'
255
357
  export { specConformance, type SpecConformance } from '../spec-standard'
256
358
  import { recordInfrastructureFailure as appendInfrastructureFailure } from './infrastructure-failure-budget'
257
359
  import { settleOpenExecution } from './execution-settlement'
@@ -529,6 +631,10 @@ export interface TickReport {
529
631
  * background work this tick. The tick returns without awaiting it; the
530
632
  * continuation completes the remaining boundaries and the launch. */
531
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
532
638
  /** Dispatch (§12): builds created and launched. With durable supervision
533
639
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
534
640
  * awaited launches: a dispatch whose remote provisioning continues in the
@@ -592,6 +698,7 @@ export function emptyTickReport(): TickReport {
592
698
  swept: 0,
593
699
  settled: 0,
594
700
  provisioning: 0,
701
+ provisioningDeferred: 0,
595
702
  dispatched: 0,
596
703
  authored: 0,
597
704
  bounced: 0,
@@ -614,6 +721,44 @@ export function emptyTickReport(): TickReport {
614
721
  }
615
722
  }
616
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
+
617
762
  // ── Dispatcher ───────────────────────────────────────────────────────────────
618
763
 
619
764
  const DEFAULT_SLUG_NAMING_TIMEOUT_MS = 10_000
@@ -627,6 +772,9 @@ const DISPATCH_COMMENT = /^build ([a-z0-9][a-z0-9-]*) dispatched$/
627
772
  * lease. A dead provisioner is therefore adopted within one lease TTL. */
628
773
  const PROVISION_HEARTBEAT_MS = 15_000
629
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
630
778
 
631
779
  /** Outcome of one attempt to complete an interrupted dispatch. `deferred`
632
780
  * means durable progress was made (background provisioning kicked or already
@@ -828,6 +976,19 @@ function baseBranchOf(events: CurrentBuildFacts, config: Config): string {
828
976
  return events.baseBranch ?? config.baseBranch
829
977
  }
830
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
+
831
992
  function artifactRefOf(deposited: ArtifactMeta[]): ArtifactRef {
832
993
  const meta = deposited[0]
833
994
  if (!meta) throw new Error('spec deposit produced no artifact meta')
@@ -1106,11 +1267,36 @@ export class Dispatcher {
1106
1267
  /** Per tick, rebuilt from durable state: builds launched so far, which
1107
1268
  * occupy a slot before their runner claims a lease. */
1108
1269
  private tickLaunched: ReadonlySet<string> = new Set()
1109
- /** Per tick: finished leaves the admission gate turned away. Intake reserves their slots. */
1110
- 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
1111
1293
  /** Per tick: parked leaves whose sweep decision was `wait awaiting-pr`. A
1112
1294
  * projected wait for one of these is one tick stale and reserves nothing. */
1113
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>()
1114
1300
 
1115
1301
  // Batched confirmed landing evidence is shared across nodes for this tick.
1116
1302
  // Only durable availability facts authorize the shortcut after restart. The
@@ -1119,6 +1305,14 @@ export class Dispatcher {
1119
1305
  private availabilityLandings?: ReturnType<typeof confirmedLandings>
1120
1306
  private availabilityLandingKey?: string
1121
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[]>
1122
1316
  /** Set once kernel Git proved unable to run this tick; later node work in
1123
1317
  * the same tick defers on it without spawning again. */
1124
1318
  private kernelGitUnavailable?: KernelGitUnavailable
@@ -1179,10 +1373,72 @@ export class Dispatcher {
1179
1373
  }
1180
1374
 
1181
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
+
1182
1435
  async tick(opts: TickOpts = {}): Promise<TickReport> {
1183
1436
  this.kernelGitUnavailable = undefined
1184
1437
  this.tickAbandonments = []
1438
+ this.tickDeadlineAt = opts.deadlineAt
1185
1439
  this.availabilityEntries = undefined
1440
+ this.janitorEntries = undefined
1441
+ this.nodeChildren = undefined
1186
1442
  this.availabilityLandings = undefined
1187
1443
  this.availabilityLandingKey = undefined
1188
1444
  const builds = new Map<string, number>()
@@ -1199,17 +1455,31 @@ export class Dispatcher {
1199
1455
  }
1200
1456
  if (build) builds.set(build, (builds.get(build) ?? 0) + 1)
1201
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
+ }
1202
1468
  })
1203
- const counts = () => ({
1204
- total,
1205
- ...(classified ? categories : {}),
1206
- unattributed,
1207
- builds: [...builds]
1208
- .map(([build, requests]) => ({ build, requests }))
1209
- .sort((a, b) => b.requests - a.requests || a.build.localeCompare(b.build))
1210
- .slice(0, 10),
1211
- complete: true,
1212
- })
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
+ }
1213
1483
  this.lastForgeRequests = undefined
1214
1484
  try {
1215
1485
  const report = await (this.deps.forge.withReadScope
@@ -1227,6 +1497,10 @@ export class Dispatcher {
1227
1497
  }
1228
1498
  }
1229
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
+
1230
1504
  /** Ticket preparations durably abandoned during the current tick. Drained
1231
1505
  * once by `tick()` into its report or its rejection, so later ticks never
1232
1506
  * repeat them. At most 8 recoveries plus one inline abandonment per tick. */
@@ -1256,10 +1530,19 @@ export class Dispatcher {
1256
1530
  this.nodePollingTickReads.clear()
1257
1531
  this.slotWaiters.clear()
1258
1532
  this.parkedSettled.clear()
1533
+ this.deferredAdmissions.clear()
1534
+ this.admissionBoundary = false
1535
+ this.urgentEvaluated = false
1536
+ this.forcedDeferralKey = undefined
1259
1537
  // One immutable config for this complete decision pass. A reload racing the
1260
1538
  // tick is observed by the next tick, never half-way through this one.
1261
1539
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1262
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
+ )
1263
1546
  const autoMergeUser = undefined
1264
1547
  const report = emptyTickReport()
1265
1548
  this.restoreScan(report)
@@ -1275,6 +1558,11 @@ export class Dispatcher {
1275
1558
  const repoFacts = this.store.repositoryFacts()
1276
1559
  if (this.deps.missingAccounts) await this.reconcileAccountPresence(this.deps.missingAccounts())
1277
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)
1278
1566
  const autoMergeSeedFact = undefined
1279
1567
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
1280
1568
  // provider liveness and settle their completion, lease, and publication.
@@ -1309,13 +1597,27 @@ export class Dispatcher {
1309
1597
  if (this.outOfBudget(opts)) return report
1310
1598
  await this.leaseSweep(report, launched, paused, opts)
1311
1599
  if (this.outOfBudget(opts)) return report
1312
- // Nodes with a durable verification request take freed slots before
1313
- // 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.
1314
1603
  await this.admitWaitingNodes(report, launched, opts)
1315
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
1316
1614
  if (opts.acceptNewWork !== false) {
1317
1615
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1318
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'])
1319
1621
  // Fire-and-forget by contract: long synthesize/review sessions must not
1320
1622
  // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1321
1623
  // watch ticks. Durable pause and infrastructure-error stops suppress
@@ -1350,14 +1652,21 @@ export class Dispatcher {
1350
1652
  const { repo } = this.deps
1351
1653
  const records = (await store.listBuilds()).filter((record) => record.repo === repo)
1352
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.
1353
1659
  const blocked = new Set<string>()
1354
- for (const record of records) {
1355
- if (
1356
- (digests.get(record.slug)?.compatibility?.decisiveFacts ?? 0) > 0 &&
1357
- (await deferMixedVersion(store, record.slug))
1358
- )
1359
- blocked.add(record.slug)
1360
- }
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
+ }
1361
1670
  return records
1362
1671
  .filter((record) => includeDeferred || !blocked.has(record.slug))
1363
1672
  .map((record) => {
@@ -1529,6 +1838,296 @@ export class Dispatcher {
1529
1838
  }
1530
1839
  }
1531
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
+
1532
2131
  /** Report a preparation attempt's committed hand-back once. */
1533
2132
  private async reportPreparationHandback(
1534
2133
  attempt: TicketPreparation,
@@ -1690,7 +2289,9 @@ export class Dispatcher {
1690
2289
  report[key] = [...previous[key]]
1691
2290
  }
1692
2291
 
1693
- 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 } = {}) {
1694
2295
  const digest = (await this.repoBuildDigests())
1695
2296
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
1696
2297
  .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq] as const)
@@ -1715,6 +2316,7 @@ export class Dispatcher {
1715
2316
  readinessFingerprint,
1716
2317
  criteriaFingerprint,
1717
2318
  }
2319
+ if (force) return { ...checkpoint, allowClockRollback: false, due: true }
1718
2320
  // The journal measurement alone proves deferral, so the cadence row is not read.
1719
2321
  if (ticketScanDeferredByJournal(input))
1720
2322
  return { ...checkpoint, allowClockRollback: false, due: false }
@@ -1725,6 +2327,7 @@ export class Dispatcher {
1725
2327
  private async completeScan(
1726
2328
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
1727
2329
  report: TickReport,
2330
+ urgentWaiting = 0,
1728
2331
  ): Promise<void> {
1729
2332
  const payload = {
1730
2333
  startedAt: checkpoint.startedAt,
@@ -1738,10 +2341,12 @@ export class Dispatcher {
1738
2341
  dependencyDiagnostics: report.dependencyDiagnostics.slice(0, 1000),
1739
2342
  creationWithheld: report.creationWithheld,
1740
2343
  creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
2344
+ ...(urgentWaiting > 0 ? { urgentWaiting } : {}),
1741
2345
  }
1742
2346
  const previous = this.latestScan()
1743
2347
  const unchanged =
1744
2348
  previous !== undefined &&
2349
+ previous.urgentWaiting === payload.urgentWaiting &&
1745
2350
  Object.keys(payload)
1746
2351
  .filter((key) => key !== 'startedAt')
1747
2352
  .every(
@@ -1845,14 +2450,26 @@ export class Dispatcher {
1845
2450
  if (await this.forgeCoolingDown()) return 'already-active'
1846
2451
  if (await deferMixedVersion(this.store, slug)) return 'already-active'
1847
2452
  const launchState = (await this.store.buildFacts(slug)).state
1848
- if (
1849
- launchState.kind === 'node' &&
1850
- !launchState.nodeRestack?.conflict &&
1851
- !integrationCurrent(launchState)
1852
- )
1853
- 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
+ }
1854
2470
  if (launched.has(slug)) return 'already-active'
1855
- 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'
1856
2473
  launched.add(slug)
1857
2474
  const facts = (await readBuildFacts(this.store, slug)).value
1858
2475
  // Callers reap and reprovision a flagged workspace; an agent never starts
@@ -2222,7 +2839,7 @@ export class Dispatcher {
2222
2839
  autoMergeDefaultSeq?: number
2223
2840
  assets?: PinnedAsset[]
2224
2841
  },
2225
- ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait'> {
2842
+ ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait' | 'budget-wait'> {
2226
2843
  const slug = record.slug
2227
2844
  if (!this.accountsAvailable()) return 'in-flight'
2228
2845
  if (this.continuations.has(slug)) return 'in-flight'
@@ -2243,11 +2860,25 @@ export class Dispatcher {
2243
2860
  }
2244
2861
  // Expired lease, failed attempt, or an old lease-less marker: adopt.
2245
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'
2246
2873
  // A finished leaf waits for a slot before its continuation reserves one.
2247
2874
  // Nothing is written: the wait costs no attempt and raises no attention.
2248
- if (tail === 'launch' && !(await this.leafAdmission(slug))) return 'slot-wait'
2875
+ if (tail === 'launch' && (await this.leafAdmission(slug)) !== 'admit') return 'slot-wait'
2249
2876
  const branch = record.branch ?? `ab/${slug}`
2250
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
2251
2882
  if (this.deps.holdsRepoAuthority?.() === false) return 'in-flight'
2252
2883
  await this.store.append(slug, {
2253
2884
  actor: DISPATCHER,
@@ -2268,6 +2899,7 @@ export class Dispatcher {
2268
2899
  generation,
2269
2900
  seed,
2270
2901
  tail,
2902
+ adoptAbandoned,
2271
2903
  }).catch(() => {
2272
2904
  // Detached work must never reject into the dispatcher process. Failure
2273
2905
  // recording can itself fail on a store outage; durable boundaries and
@@ -2299,6 +2931,7 @@ export class Dispatcher {
2299
2931
  }
2300
2932
  | undefined
2301
2933
  tail: 'dispatch' | 'launch'
2934
+ adoptAbandoned: boolean
2302
2935
  },
2303
2936
  ): Promise<void> {
2304
2937
  const store = this.store
@@ -2335,23 +2968,34 @@ export class Dispatcher {
2335
2968
  return
2336
2969
  }
2337
2970
  const priorGenerations = events.workspaceGenerations
2338
- const handle = await this.provisionWorkspace(slug, {
2339
- // Local providers provision FROM the physical checkout; remote
2340
- // providers ignore the value (their host seams are injected).
2341
- repo: this.deps.checkout ?? this.deps.repo,
2342
- baseBranch:
2343
- events.state.kind === 'node' && events.state.integration?.cycle
2344
- ? input.branch
2345
- : baseBranchOf(events, config),
2346
- branch: input.branch,
2347
- ...(priorGenerations > 0 || input.generation > 0
2348
- ? {
2349
- publication: await this.confirmedWorkspacePublication(events, slug),
2350
- revision: events.state.integration?.cycle?.head ?? this.recoveryCheckpoint(events),
2351
- generation: Math.max(priorGenerations, input.generation),
2352
- }
2353
- : {}),
2354
- })
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
+ )
2355
2999
  // The provisioned fact is true and welcome even when a teardown signal
2356
3000
  // landed mid-call; the token check below still prevents a superseded
2357
3001
  // supervisor from launching.
@@ -2394,6 +3038,10 @@ export class Dispatcher {
2394
3038
  // A lapsed repository lease started nothing: no failure fact. The
2395
3039
  // finally releases the execution lease; the successor adopts the marker.
2396
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
2397
3045
  // Dispatch boundaries own their failure facts and exhaustion repair.
2398
3046
  // A failed tail read/write leaves durable unfinished work for the next
2399
3047
  // tick; it is not another provider workspace failure. Replacement
@@ -2401,7 +3049,12 @@ export class Dispatcher {
2401
3049
  if (await this.holdForMissingAccounts(error)) return
2402
3050
  if (boundary === 'read' || boundary === 'dispatch') return
2403
3051
  const events = (await readBuildFacts(store, slug)).value
2404
- 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) {
2405
3058
  const open = openWorkspace(events)
2406
3059
  const latestRef = events.latestRelease
2407
3060
  await this.recordInfrastructureFailure(slug, events, {
@@ -2478,6 +3131,7 @@ export class Dispatcher {
2478
3131
  attempt,
2479
3132
  error:
2480
3133
  'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3134
+ abandoned: 'teardown',
2481
3135
  },
2482
3136
  })
2483
3137
  }
@@ -2504,9 +3158,13 @@ export class Dispatcher {
2504
3158
  // Only this repo's builds that still have work (§12: another repo's
2505
3159
  // builds are another dispatcher's duty; settled terminal builds cost no
2506
3160
  // event reads).
2507
- 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(
2508
3164
  ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
2509
3165
  )
3166
+ this.janitorEntries = entries
3167
+ this.nodeChildren = undefined
2510
3168
  // Receipt reporting requires no forge call, capacity or workspace. Recover
2511
3169
  // every episode before the transport-budget and janitor-backoff gates.
2512
3170
  for (const { record, digest } of entries) {
@@ -2539,18 +3197,64 @@ export class Dispatcher {
2539
3197
  const initialFacts = await this.store.buildFacts(record.slug)
2540
3198
  let { state, workspace, log } = initialFacts
2541
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)
2542
3204
  const controlDue =
2543
- state.pendingCommands.length > 0 ||
3205
+ commands.length > 0 ||
2544
3206
  state.discardRequest !== undefined ||
3207
+ (state.declined !== undefined && state.status !== 'done') ||
2545
3208
  (state.pr &&
2546
3209
  state.landing?.command &&
2547
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
+ }
2548
3227
  // Read the clock only inside an episode, as before episodes could escalate.
2549
3228
  if (!controlDue && previous && !janitorDue(previous, this.deps.clock())) return
2550
3229
  if (mixedVersionDeferred(state)) {
2551
3230
  await deferMixedVersion(this.store, record.slug)
2552
3231
  return
2553
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
+ }
2554
3258
  const executionLeaseLive = this.hasLiveExecutionLease(record)
2555
3259
  attempted = !executionLeaseLive
2556
3260
  // Raw history, read at most once and only by a branch that acts on it:
@@ -2657,6 +3361,7 @@ export class Dispatcher {
2657
3361
  {
2658
3362
  history,
2659
3363
  workspace,
3364
+ executionOpen: initialFacts.open !== null,
2660
3365
  observed: (pr) => {
2661
3366
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2662
3367
  },
@@ -2752,6 +3457,7 @@ export class Dispatcher {
2752
3457
  {
2753
3458
  history,
2754
3459
  workspace,
3460
+ executionOpen: initialFacts.open !== null,
2755
3461
  observed: (pr) => {
2756
3462
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2757
3463
  },
@@ -2853,6 +3559,11 @@ export class Dispatcher {
2853
3559
  await this.cleanupAborted(record, await history(), report)
2854
3560
  return
2855
3561
  }
3562
+ if (!executionLeaseLive && state.declined !== undefined) {
3563
+ operation = 'decline settlement'
3564
+ await this.settleDeclinedAttempt(record, await history())
3565
+ return
3566
+ }
2856
3567
  operation = 'target observation'
2857
3568
  if (state.kind !== 'node' && state.status !== 'aborted')
2858
3569
  await this.observeTicketTarget(record, state, report)
@@ -2934,6 +3645,7 @@ export class Dispatcher {
2934
3645
  {
2935
3646
  history,
2936
3647
  workspace,
3648
+ executionOpen: initialFacts.open !== null,
2937
3649
  observed: (pr) => {
2938
3650
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2939
3651
  },
@@ -3304,18 +4016,33 @@ export class Dispatcher {
3304
4016
  /** Deferral withholds decisions, but cannot free an existing capacity reservation.
3305
4017
  * A leaf's runner reservation is this process's continuation or a launch
3306
4018
  * this tick; another process's continuation holds a heartbeat lease. */
3307
- 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[]> {
3308
4024
  const builds: CapacityBuild[] = []
3309
4025
  for (const { record, digest } of await this.repoBuildDigests(true)) {
3310
4026
  if (digest.terminal) continue
3311
- 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)
3312
4036
  builds.push({
3313
4037
  record,
3314
4038
  state: facts.state,
3315
4039
  workspace: facts.workspace !== null,
3316
4040
  provisioning:
3317
4041
  digest.kind === 'node'
3318
- ? (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
3319
4046
  : this.continuations.has(record.slug) || !!launched?.has(record.slug),
3320
4047
  restackDue: landingRestackDue(facts.state, facts.log),
3321
4048
  })
@@ -3323,12 +4050,68 @@ export class Dispatcher {
3323
4050
  return builds
3324
4051
  }
3325
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
+
3326
4108
  /** Whether a leaf may reserve a runner now. A leaf that has not finished its
3327
4109
  * pipeline already holds its slot, and abort and pause acknowledgements park
3328
4110
  * at once, so only a finished leaf that must run again is gated: it needs
3329
- * a free slot among every other build. A denial is recorded only in memory,
3330
- * for this tick's intake reservation. */
3331
- 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'> {
3332
4115
  const { state } = await this.store.buildFacts(slug)
3333
4116
  if (
3334
4117
  !(epilogueLeaf(state) || waitParked(state)) ||
@@ -3336,85 +4119,659 @@ export class Dispatcher {
3336
4119
  (command) => command.command === 'abort' || command.command === 'pause',
3337
4120
  )
3338
4121
  )
3339
- return true
3340
- const others = (await this.capacityBuilds(this.tickLaunched)).filter(
3341
- (build) => build.record.slug !== slug,
3342
- )
4122
+ return 'admit'
4123
+ const builds = await this.capacityBuilds(this.tickLaunched)
4124
+ const others = builds.filter((build) => build.record.slug !== slug)
3343
4125
  const capacity = this.deps.config.capacity
3344
- 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') {
3345
4138
  this.slotWaiters.delete(slug)
3346
- return true
4139
+ return 'admit'
3347
4140
  }
3348
- this.slotWaiters.add(slug)
3349
- return false
4141
+ this.slotWaiters.set(slug, priority)
4142
+ if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
4143
+ this.deferredAdmissions.set(slug, 'leaf')
4144
+ return outcome
3350
4145
  }
3351
4146
 
3352
- /** Admit every node awaiting verification that has a slot, in slug order,
3353
- * through the janitor's own admission path. Independent of `acceptNewWork`:
3354
- * node admission is existing work, never intake. */
3355
- private async admitWaitingNodes(
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(
3356
4156
  report: TickReport,
3357
4157
  launched: Set<string>,
4158
+ paused: boolean,
3358
4159
  opts: TickOpts,
3359
4160
  ): Promise<void> {
3360
- if (
3361
- !(await this.repoBuildDigests()).some(
3362
- ({ digest }) => digest.kind === 'node' && digest.terminal === undefined,
3363
- )
3364
- )
4161
+ const deferred = [...this.deferredAdmissions]
4162
+ this.deferredAdmissions.clear()
4163
+ if (deferred.length === 0) {
4164
+ this.lastForcedDeferralKey = undefined
3365
4165
  return
3366
- const now = this.deps.clock()
3367
- const waiting = (await this.capacityBuilds())
3368
- .filter((build) => slotRequest(build, now) === 'verification')
3369
- .sort((a, b) => (a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0))
3370
- for (const { record, state } of waiting) {
4166
+ }
4167
+ if (!this.urgentEvaluated) return
4168
+ this.admissionBoundary = false
4169
+ for (const [slug, kind] of deferred) {
3371
4170
  if (this.outOfBudget(opts)) return
3372
- if (
3373
- launched.has(record.slug) ||
3374
- this.hasLiveExecutionLease(record) ||
3375
- !state.nodeOpened ||
3376
- !janitorDue(state.janitor, now)
3377
- )
3378
- continue
3379
- await withForgeRequestContext({ build: record.slug }, async () => {
3380
- try {
3381
- if (!(await this.nodeHasCapacity(record.slug))) return
3382
- await this.prepareIntegration(record, state, report, launched)
3383
- } catch (error) {
3384
- rethrowAuthorityLapse(error)
3385
- report.janitorDiagnostics.push(
3386
- `build ${record.slug}: node admission failed — ${String(error)}`,
3387
- )
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)
3388
4184
  }
3389
- })
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
+ }
3390
4193
  }
4194
+ if (this.forcedDeferralKey !== undefined) this.lastForcedDeferralKey = this.forcedDeferralKey
3391
4195
  }
3392
4196
 
3393
- private async nodeHasCapacity(slug: string): Promise<boolean> {
3394
- const builds = await this.capacityBuilds()
3395
- return (
3396
- nodeCapacity(
3397
- builds,
3398
- slug,
3399
- this.deps.clock(),
3400
- migrationIdentity(this.store.repositoryFacts().ticketMigrations, this.deps.tickets.name),
3401
- ).occupied < this.deps.config.capacity
3402
- )
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])
3403
4202
  }
3404
4203
 
3405
- private hasLiveExecutionLease(record: BuildRecord): boolean {
3406
- return (
3407
- record.lease !== undefined &&
3408
- new Date(record.lease.expiresAt).getTime() > this.deps.clock().getTime()
4204
+ /** Admit every node awaiting verification that has a slot, in slug order,
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. */
4208
+ private async admitWaitingNodes(
4209
+ report: TickReport,
4210
+ launched: Set<string>,
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'),
3409
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)
3410
4241
  }
3411
4242
 
3412
- /** Complete abort cleanup as an ordered checkpointed saga. External effects
3413
- * are idempotent; a fact after each one prevents already-settled work from
3414
- * repeating on later ticks. `build.completed` is deliberately last. */
3415
- /** Record a landed child's effective issue links on its target node, once
3416
- * per child (SPEC "Forge issue links"). Reduced reads only: the child's
3417
- * refreshed state and the node's union, never any child history. */
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>,
4250
+ ): Promise<void> {
4251
+ if (
4252
+ launched.has(record.slug) ||
4253
+ this.hasLiveExecutionLease(record) ||
4254
+ !state.nodeOpened ||
4255
+ !janitorDue(state.janitor, now)
4256
+ )
4257
+ return
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
4287
+ if (this.outOfBudget(opts)) return
4288
+ const { record } = build
4289
+ await withForgeRequestContext({ build: record.slug }, async () => {
4290
+ try {
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
4296
+ } catch (error) {
4297
+ rethrowAuthorityLapse(error)
4298
+ report.janitorDiagnostics.push(
4299
+ `build ${record.slug}: node workspace release failed — ${String(error)}`,
4300
+ )
4301
+ }
4302
+ })
4303
+ }
4304
+ }
4305
+
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'> {
4738
+ const builds = await this.capacityBuilds()
4739
+ const now = this.deps.clock()
4740
+ const identity = migrationIdentity(
4741
+ this.store.repositoryFacts().ticketMigrations,
4742
+ this.deps.tickets.name,
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
4760
+ }
4761
+
4762
+ private hasLiveExecutionLease(record: BuildRecord): boolean {
4763
+ return (
4764
+ record.lease !== undefined &&
4765
+ new Date(record.lease.expiresAt).getTime() > this.deps.clock().getTime()
4766
+ )
4767
+ }
4768
+
4769
+ /** Complete abort cleanup as an ordered checkpointed saga. External effects
4770
+ * are idempotent; a fact after each one prevents already-settled work from
4771
+ * repeating on later ticks. `build.completed` is deliberately last. */
4772
+ /** Record a landed child's effective issue links on its target node, once
4773
+ * per child (SPEC "Forge issue links"). Reduced reads only: the child's
4774
+ * refreshed state and the node's union, never any child history. */
3418
4775
  private async recordNodeIssueLinks(slug: string): Promise<void> {
3419
4776
  const state = (await this.store.buildFacts(slug)).state
3420
4777
  if (state.target === undefined) return
@@ -3431,6 +4788,495 @@ export class Dispatcher {
3431
4788
  } satisfies EventWrite<'node.issue-links-recorded'>)
3432
4789
  }
3433
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'
5278
+ }
5279
+
3434
5280
  private async cleanupAborted(
3435
5281
  record: BuildRecord,
3436
5282
  events: CurrentBuildFacts,
@@ -3621,7 +5467,34 @@ export class Dispatcher {
3621
5467
  }
3622
5468
  }
3623
5469
 
3624
- 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')) {
3625
5498
  const label = 'autobuild:aborted'
3626
5499
  try {
3627
5500
  const id = await this.currentTicketId(record)
@@ -3673,7 +5546,7 @@ export class Dispatcher {
3673
5546
 
3674
5547
  // Reported from the checkpoint, never a re-read of the ticket, so a
3675
5548
  // retry reports exactly what the committed move did.
3676
- if (record.ticket !== undefined) {
5549
+ if (handback) {
3677
5550
  try {
3678
5551
  const returned = events.latestTicketReturned
3679
5552
  if (returned?.type !== 'abort.ticket-returned')
@@ -3703,11 +5576,54 @@ export class Dispatcher {
3703
5576
  type: 'build.completed',
3704
5577
  payload: { outcome: 'abandoned' },
3705
5578
  })
3706
- if (record.ticket !== undefined) await this.settleBuildHandback(record.slug)
5579
+ if (handback) await this.settleBuildHandback(record.slug)
3707
5580
  await this.reclaimPrAttachments(record.slug, events)
3708
5581
  report.abandoned += 1
3709
5582
  }
3710
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
+
3711
5627
  /** A discard is recovery from dispatcher plumbing, not judgment about the
3712
5628
  * ticket. Return it to the configured Ready state and terminalize last so
3713
5629
  * every partial cleanup is retried after a crash. */
@@ -3773,6 +5689,92 @@ export class Dispatcher {
3773
5689
  }
3774
5690
  }
3775
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
+
3776
5778
  /** Post-PR epilogue (§15.7): poll the forge, emit `pr.*` facts (deduped
3777
5779
  * against the reduced `prState`), release/complete, project to the ticket. */
3778
5780
  private async checkPr(
@@ -3782,6 +5784,8 @@ export class Dispatcher {
3782
5784
  source: {
3783
5785
  history: () => Promise<CurrentBuildFacts>
3784
5786
  workspace: OpenBuildWorkspace | null
5787
+ /** An execution is recorded open (started, not yet ended). */
5788
+ executionOpen: boolean
3785
5789
  observed?: (pr: Awaited<ReturnType<Forge['getPrState']>>) => void
3786
5790
  },
3787
5791
  state: BuildState,
@@ -4039,6 +6043,8 @@ export class Dispatcher {
4039
6043
  type: 'landing.command-acknowledged',
4040
6044
  payload: { commandSeq: command.seq },
4041
6045
  })
6046
+ if (!integration && !recoverLanding && prState.state === 'open')
6047
+ await this.observeHeadChecks(record, state, prState, workspacePath)
4042
6048
 
4043
6049
  // A positive conflict re-enters reconcile before any enable attempt. In
4044
6050
  // particular, an ungated fallback can never race ahead of the conflict
@@ -4066,6 +6072,7 @@ export class Dispatcher {
4066
6072
  // never blocks on guest bootstrap.
4067
6073
  const kicked = await this.ensureProvisionContinuation(record, events, 'launch')
4068
6074
  if (kicked === 'kicked') report.provisioning += 1
6075
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
4069
6076
  report.conflicted += 1
4070
6077
  return
4071
6078
  }
@@ -4184,55 +6191,92 @@ export class Dispatcher {
4184
6191
  })
4185
6192
  return
4186
6193
  }
4187
- const preflight = recoverLanding
4188
- ? undefined
4189
- : await preflightNodeLanding(
4190
- this.kernelForge(),
4191
- 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,
4192
6268
  pr.number,
4193
- record.branch,
4194
- target.branch,
6269
+ commandSeq,
6270
+ this.deps.ids('obs'),
4195
6271
  )
4196
- const reason =
4197
- preflight ??
4198
- (await this.withKernelRepository((kernelPath) =>
4199
- landIntoNode({
4200
- store,
4201
- forge: this.kernelForge(),
4202
- exec: forge.kernelExec ?? this.deps.exec,
4203
- workspacePath: kernelPath,
4204
- slug: record.slug,
4205
- node: target.slug,
4206
- branch: record.branch!,
4207
- destination: target.branch!,
4208
- pr: pr.number,
4209
- holder: this.deps.ids('node-writer'),
4210
- id: this.deps.ids('node-landing').replaceAll('_', '-'),
4211
- ...(integration
4212
- ? {
4213
- stack: {
4214
- head: state.integration!.cycle!.head,
4215
- parent: state.integration!.cycle!.parent,
4216
- cycle: state.integration!.cycle!.id,
4217
- },
4218
- }
4219
- : {}),
4220
- eligible: canApply,
4221
- }),
4222
- ))
4223
- if (reason && commandSeq !== undefined)
4224
- await recordAutoMergeDeferralObservation(
4225
- store,
4226
- record.slug,
4227
- reason,
4228
- pr.number,
4229
- commandSeq,
4230
- this.deps.ids('obs'),
6272
+ if (
6273
+ (await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug
4231
6274
  )
4232
- if ((await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug)
4233
- return
6275
+ return
6276
+ }
4234
6277
  await store.refreshBuild(record.slug)
4235
6278
  state = (await store.buildFacts(record.slug)).state
6279
+ if (closure !== undefined) prState = closure
4236
6280
  if (state.prState === 'merged') {
4237
6281
  if (state.mergedSha) prState = { state: 'merged', sha: state.mergedSha }
4238
6282
  }
@@ -4277,15 +6321,27 @@ export class Dispatcher {
4277
6321
  prState.nativeAutoMerge === true &&
4278
6322
  !nativeCancelled &&
4279
6323
  isReady
6324
+ // A landing that cannot be armed natively lands by polling; a quiet
6325
+ // polling tick needs no consent read, because the forge answers from the
6326
+ // poll's PR read and consent is rechecked before any merge. A landing
6327
+ // settled as awaiting a human merge makes no landing call at all; the PR
6328
+ // read above still records the human's merge.
6329
+ const fallback = currentLandingFallback(state.landing)
6330
+ const polling =
6331
+ fallback?.mode === 'polling' &&
6332
+ prState.state === 'open' &&
6333
+ prState.nativeAutoMerge !== true &&
6334
+ isReady
4280
6335
  if (
4281
6336
  !integration &&
4282
6337
  !nodeTarget &&
4283
6338
  prState.state === 'open' &&
4284
6339
  landingAuthorized(state.landing) &&
6340
+ fallback?.mode !== 'human-merge' &&
4285
6341
  (prState.nativeAutoMerge === false || !acknowledged || maintain) &&
4286
6342
  (!retry || Date.parse(retry.after) <= this.deps.clock().getTime()) &&
4287
6343
  commandSeq !== undefined &&
4288
- (maintain || (await canApply()))
6344
+ (maintain || polling || (await canApply()))
4289
6345
  ) {
4290
6346
  const decision = state.landing!.decision!
4291
6347
  // The provider checks eligibility immediately before mutating. Inspection
@@ -4323,6 +6379,7 @@ export class Dispatcher {
4323
6379
  buildSlug: record.slug,
4324
6380
  baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
4325
6381
  ...issueLinksForForge(state, forge),
6382
+ ...(polling ? { polling: true } : {}),
4326
6383
  canApply: async () => {
4327
6384
  if (!(await canApply())) return false
4328
6385
  if (enableSeq === undefined)
@@ -4363,7 +6420,58 @@ export class Dispatcher {
4363
6420
  await settleFailedEnable()
4364
6421
  throw error
4365
6422
  })
4366
- if (maintain && enableSeq === undefined) {
6423
+ const fallbackFact = {
6424
+ candidate: decision.candidate,
6425
+ decisionSeq: decision.seq,
6426
+ ...(state.landing?.command ? { commandSeq: state.landing.command.seq } : {}),
6427
+ }
6428
+ const requireHumanMerge = (
6429
+ cause: EventPayload<'landing.human-merge-required'>['cause'],
6430
+ detail: string,
6431
+ ) =>
6432
+ store.append(record.slug, {
6433
+ actor: DISPATCHER,
6434
+ type: 'landing.human-merge-required',
6435
+ payload: { ...fallbackFact, cause, detail },
6436
+ })
6437
+ if (result.kind === 'human-merge') {
6438
+ // Settled once: later ticks make no landing call for this candidate.
6439
+ await requireHumanMerge(result.cause, result.detail)
6440
+ } else if (result.kind === 'polling') {
6441
+ // The forge never called the consent guard, so nothing was mutated.
6442
+ if (fallback?.mode !== 'polling')
6443
+ await store.append(record.slug, {
6444
+ actor: DISPATCHER,
6445
+ type: 'landing.polling-selected',
6446
+ payload: { ...fallbackFact, detail: result.detail },
6447
+ })
6448
+ if (
6449
+ result.clear &&
6450
+ prState.mergeable === true &&
6451
+ result.headSha === decision.candidate.head &&
6452
+ (await canApply())
6453
+ ) {
6454
+ try {
6455
+ // Re-reads the PR clear at the candidate head and rechecks
6456
+ // consent immediately before the merge request.
6457
+ await forge.squashMerge(workspacePath, pr.number, decision.candidate.head, {
6458
+ buildSlug: record.slug,
6459
+ baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
6460
+ ...issueLinksForForge(state, forge),
6461
+ requireClearState: true,
6462
+ canApply,
6463
+ })
6464
+ } catch (error) {
6465
+ // Only the forge refusing a merge it reported clear settles;
6466
+ // pre-merge checks throw ordinary errors and poll again.
6467
+ if (!isForgeRejection(error)) throw error
6468
+ await requireHumanMerge(
6469
+ isForgeMergeQueueRejection(error) ? 'merge-queue-activity' : 'merge-refused',
6470
+ error.forgeMessage,
6471
+ )
6472
+ }
6473
+ }
6474
+ } else if (maintain && enableSeq === undefined) {
4367
6475
  // Quiet maintenance: no consent check passed, so nothing was mutated.
4368
6476
  // A vanished request is reconciled by the next poll's PR read.
4369
6477
  if (result.kind === 'deferred' && result.reason)
@@ -4468,8 +6576,10 @@ export class Dispatcher {
4468
6576
  if (state.prState === 'merged' && state.mergedSha)
4469
6577
  prState = { state: 'merged', sha: state.mergedSha }
4470
6578
  }
6579
+ let landed = integration && state.integration?.landing !== undefined
4471
6580
  if (integration && prState.state === 'merged' && !state.integration?.landing) {
4472
6581
  const head = prState.headSha
6582
+ landed = true
4473
6583
  await store.append(record.slug, {
4474
6584
  actor: DISPATCHER,
4475
6585
  type: 'integration.landed',
@@ -4483,11 +6593,19 @@ export class Dispatcher {
4483
6593
  })
4484
6594
  }
4485
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)
4486
6604
  if (
4487
6605
  integration &&
4488
6606
  (prState.state === 'merged' || prState.state === 'closed') &&
4489
6607
  record.branch &&
4490
- !executionLeaseLive
6608
+ !executionLive
4491
6609
  ) {
4492
6610
  if (
4493
6611
  !(await this.withKernelRepository((kernelPath) =>
@@ -4506,7 +6624,7 @@ export class Dispatcher {
4506
6624
  }
4507
6625
  switch (prState.state) {
4508
6626
  case 'merged': {
4509
- if (executionLeaseLive) return
6627
+ if (executionLive) return
4510
6628
  const events = await source.history()
4511
6629
  if (!landingAuthorized(state.landing) && !state.landing?.forgeMerge) {
4512
6630
  // Use our durable native-effect evidence, never provider origin.
@@ -4546,6 +6664,9 @@ export class Dispatcher {
4546
6664
  // Before the child can become terminal, so a complete node already
4547
6665
  // folds every landed child's links; the node log dedupes a retry.
4548
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)
4549
6670
  await this.releaseWorkspace(record.slug, events)
4550
6671
  if (record.ticket) {
4551
6672
  await tickets.transition(await this.currentTicketId(record), this.doneState)
@@ -4564,7 +6685,7 @@ export class Dispatcher {
4564
6685
  return
4565
6686
  }
4566
6687
  case 'closed': {
4567
- if (executionLeaseLive) return
6688
+ if (executionLive) return
4568
6689
  const events = await source.history()
4569
6690
  // Closed without merge is a human decision — back to Triage (§15.7).
4570
6691
  if (state.prState !== 'closed') {
@@ -4575,20 +6696,38 @@ export class Dispatcher {
4575
6696
  } satisfies EventWrite<'pr.closed'>)
4576
6697
  }
4577
6698
  await this.releaseWorkspace(record.slug, events)
4578
- await this.returnBuildTicket(
4579
- record,
4580
- events,
4581
- 'pr-closed',
4582
- 'triage',
4583
- (state) =>
4584
- `build ${record.slug} PR closed without merging (${pr.url}) — returned to ${state}`,
4585
- )
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
+ )
4586
6725
  await store.append(record.slug, {
4587
6726
  actor: DISPATCHER,
4588
6727
  type: 'build.completed',
4589
6728
  payload: { outcome: 'closed-unmerged' },
4590
6729
  } satisfies EventWrite<'build.completed'>)
4591
- if (record.ticket) await this.settleBuildHandback(record.slug)
6730
+ if (record.ticket && attempt.status === 'none') await this.settleBuildHandback(record.slug)
4592
6731
  await this.reclaimPrAttachments(record.slug, events)
4593
6732
  report.closed += 1
4594
6733
  return
@@ -4650,25 +6789,53 @@ export class Dispatcher {
4650
6789
  }
4651
6790
  }
4652
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. */
4653
6795
  private async provisionWorkspace(
4654
6796
  slug: string,
4655
6797
  input: Parameters<WorkspaceProvider['provision']>[0],
6798
+ signal?: AbortSignal,
4656
6799
  ) {
4657
6800
  const facts = (await readBuildFacts(this.store, slug)).value
4658
6801
  const { restoration, superseded } = supersedeRestorationHeads(
4659
6802
  facts.workspacePreservation?.payload.heads,
4660
6803
  facts.replacedHeads,
4661
6804
  )
6805
+ const local = this.deps.forge.name === 'local-git'
4662
6806
  try {
4663
6807
  const handle = await this.deps.workspaces.provision({
4664
6808
  ...input,
4665
6809
  restoration,
4666
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
+ : {}),
4667
6834
  // Same predicate preservation archives under: only local-git keeps
4668
6835
  // archive refs in the local repository.
4669
6836
  ...(restoration?.length
4670
6837
  ? {
4671
- restorationArchives: this.deps.forge.name === 'local-git' ? 'local' : 'remote',
6838
+ restorationArchives: local ? 'local' : 'remote',
4672
6839
  }
4673
6840
  : {}),
4674
6841
  })
@@ -4678,7 +6845,7 @@ export class Dispatcher {
4678
6845
  ]
4679
6846
  return skipped.length ? { ...handle, restorationSkipped: skipped } : handle
4680
6847
  } catch (error) {
4681
- if (error instanceof WorkspaceCleanupRequired) {
6848
+ if (error instanceof WorkspaceCleanupRequired && signal?.aborted !== true) {
4682
6849
  await this.store.append(slug, {
4683
6850
  actor: DISPATCHER,
4684
6851
  type: 'workspace.cleanup-required',
@@ -4747,6 +6914,33 @@ export class Dispatcher {
4747
6914
  return this.deps.retiredWorkspaces?.find((provider) => provider.name === open.provider) ?? null
4748
6915
  }
4749
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
+
4750
6944
  /** Fence and remove a stale remote environment. A replacement is created
4751
6945
  * only after exact-name cleanup is durably acknowledged. */
4752
6946
  private async reapStaleWorkspace(
@@ -5010,6 +7204,7 @@ export class Dispatcher {
5010
7204
  kind?: 'work' | 'node'
5011
7205
  target?: EventPayload<'build.created'>['target']
5012
7206
  baseBranch?: string
7207
+ priority?: 'urgent'
5013
7208
  }
5014
7209
  | undefined,
5015
7210
  ): EventPayload<'build.created'> {
@@ -5035,9 +7230,17 @@ export class Dispatcher {
5035
7230
  }
5036
7231
  : {}),
5037
7232
  ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
7233
+ ...(seed?.priority !== undefined ? { priority: seed.priority } : {}),
5038
7234
  }
5039
7235
  }
5040
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
+
5041
7244
  /** Every boundary before runner attachment is derived from durable facts.
5042
7245
  * Missing facts are the todo list; successful provider calls are followed
5043
7246
  * immediately by their facts, so an ordinary later tick can continue. */
@@ -5105,6 +7308,7 @@ export class Dispatcher {
5105
7308
  ? { issueLinks: seed.ticket.issueLinks }
5106
7309
  : {}),
5107
7310
  ...(seed !== undefined ? this.selectedProfile(seed.ticket) : {}),
7311
+ ...(seed !== undefined ? this.claimedPriority(seed.ticket) : {}),
5108
7312
  }),
5109
7313
  })
5110
7314
  events = (await readBuildFacts(store, record.slug)).value
@@ -5118,23 +7322,13 @@ export class Dispatcher {
5118
7322
  return this.completeDispatchBoundaries(record, seed, report, launched)
5119
7323
 
5120
7324
  stage = 'workspace'
5121
- const flagged = openWorkspace(events)
5122
- if (
5123
- flagged !== null &&
5124
- cleanupRequiredWorkspace(events) &&
5125
- this.workspaceOwner(flagged)?.recovery !== undefined
5126
- ) {
5127
- // A retry never launches into a flagged environment: release it, then
5128
- // provision the next generation below. A live lease means a foreign
5129
- // continuation still owns the build.
5130
- if (this.hasLiveExecutionLease(record)) return 'parked'
5131
- if (!(await this.reapStaleWorkspace(record.slug, events, 'replacement'))) {
5132
- // The failure is already durable against this build.
5133
- launched.add(record.slug)
5134
- return 'parked'
5135
- }
5136
- events = (await readBuildFacts(store, record.slug)).value
5137
- }
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
5138
7332
  if (openWorkspace(events) === null) {
5139
7333
  if (this.deps.workspaces.recovery !== undefined) {
5140
7334
  // Recovery-capable provider: durable marker + tracked background
@@ -5143,6 +7337,7 @@ export class Dispatcher {
5143
7337
  // and the launch.
5144
7338
  const kicked = await this.ensureProvisionContinuation(record, events, 'dispatch', seed)
5145
7339
  if (kicked === 'kicked') report.provisioning += 1
7340
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
5146
7341
  launched.add(record.slug)
5147
7342
  return 'deferred'
5148
7343
  }
@@ -5257,11 +7452,21 @@ export class Dispatcher {
5257
7452
  }
5258
7453
 
5259
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('; ')}`)
5260
7461
  let conformance = specConformance(body)
5261
7462
  let authoredSession = seed?.authoredSession
5262
- if (!conformance.conforms && this.deps.authorSpec !== undefined) {
7463
+ if (
7464
+ !conformance.conforms &&
7465
+ objectiveBlocks(body).length === 0 &&
7466
+ this.deps.authorSpec !== undefined
7467
+ ) {
5263
7468
  const candidate = await this.deps.authorSpec(ticket)
5264
- if (candidate !== null) {
7469
+ if (candidate !== null && objectiveBlocks(candidate).length === 0) {
5265
7470
  conformance = specConformance(candidate)
5266
7471
  if (conformance.conforms) {
5267
7472
  body = candidate
@@ -5595,7 +7800,7 @@ export class Dispatcher {
5595
7800
  /**
5596
7801
  * End open ticket waits whose tickets settled (SPEC §11 "Ticket waits").
5597
7802
  * Every waited ticket completed: `wait.ended {cause: automatic}`, and the
5598
- * build resumes ahead of new claims. Any waited ticket rejected (the
7803
+ * build resumes ahead of normal claims. Any waited ticket rejected (the
5599
7804
  * configured rejected role) or deleted: one `policy/wait-unresolvable`
5600
7805
  * escalation naming it, which the reducer reads as the wait's end. A wait
5601
7806
  * with tickets still pending stays in place.
@@ -5749,6 +7954,56 @@ export class Dispatcher {
5749
7954
  }
5750
7955
  }
5751
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
+
5752
8007
  /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
5753
8008
  private async sweepBuild(
5754
8009
  record: BuildRecord,
@@ -5812,7 +8067,11 @@ export class Dispatcher {
5812
8067
  // The engine reached the end of the pipeline: record it once per
5813
8068
  // settlement key so capacity stops counting the parked build. A lost
5814
8069
  // race is decided again next tick.
5815
- 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))
5816
8075
  await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5817
8076
  actor: DISPATCHER,
5818
8077
  type: 'pipeline.settled',
@@ -5822,7 +8081,7 @@ export class Dispatcher {
5822
8081
  const orphanEligible = (state: BuildState) =>
5823
8082
  !paused &&
5824
8083
  state.status === 'running' &&
5825
- (state.kind !== 'node' || integrationCurrent(state)) &&
8084
+ (state.kind !== 'node' || (integrationCurrent(state) && !nodeLanded(state))) &&
5826
8085
  state.sessions.open.some((session) => session.suspensionCause === undefined)
5827
8086
  const provedEnded =
5828
8087
  facts.open === null &&
@@ -5840,7 +8099,12 @@ export class Dispatcher {
5840
8099
  if (
5841
8100
  state.kind === 'node' &&
5842
8101
  (!integrationCurrent(state) || facts.workspace === null) &&
5843
- 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
+ )
5844
8108
  )
5845
8109
  return // cascade owns node runner admission
5846
8110
  // Raw history, read at most once and only by a branch that acts on it.
@@ -5915,7 +8179,7 @@ export class Dispatcher {
5915
8179
  const runs = decision.kind !== 'wait' || publicationRecoveryDue || orphanRecoveryDue
5916
8180
  // A finished leaf with work to run waits for a slot before anything is
5917
8181
  // reaped, provisioned or launched for it.
5918
- if (runs && state.kind !== 'node' && !(await this.leafAdmission(record.slug))) return
8182
+ if (runs && state.kind !== 'node' && (await this.leafAdmission(record.slug)) !== 'admit') return
5919
8183
  // A finished parked leaf keeps its workspace until merge or close; a
5920
8184
  // stale environment is reaped only for an admitted replacement.
5921
8185
  // A leaf waiting on tickets, or on the dispatcher's check of its wait,
@@ -5951,7 +8215,7 @@ export class Dispatcher {
5951
8215
  if (kicked === 'kicked') {
5952
8216
  report.provisioning += 1
5953
8217
  report.swept += 1
5954
- }
8218
+ } else if (kicked === 'budget-wait') report.provisioningDeferred += 1
5955
8219
  return
5956
8220
  }
5957
8221
  }
@@ -5974,8 +8238,10 @@ export class Dispatcher {
5974
8238
  report.swept += 1
5975
8239
  return
5976
8240
  }
8241
+ if (kicked === 'budget-wait') report.provisioningDeferred += 1
5977
8242
  // In-flight or foreign-live: whoever owns the marker completes the
5978
- // 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.
5979
8245
  return
5980
8246
  }
5981
8247
  try {
@@ -6212,48 +8478,113 @@ export class Dispatcher {
6212
8478
  paused: boolean,
6213
8479
  opts: TickOpts = {},
6214
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,
6215
8485
  ): Promise<void> {
6216
- if (!this.accountsAvailable()) return
6217
- const health = this.store.repositoryFacts().forgeHealth
6218
- if (health && Date.parse(health.resetAt) > this.deps.clock().getTime()) return
8486
+ if (!this.claimGateOpen()) return
6219
8487
  const store = this.store
6220
8488
  const { tickets, config } = this.deps
6221
- const checkpoint = await this.scanCheckpoint('admission')
6222
- 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)
6223
8508
  // Clear only standing measurement fields; action counters belong to this tick.
6224
- report.queued = report.invalidTickets = report.dependencyBlocked = report.creationWithheld = 0
6225
- report.ticketDiagnostics = []
6226
- report.dependencyDiagnostics = []
6227
- 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
+ }
6228
8515
  // Capacity counts builds running work. An unfinished build holds its slot
6229
8516
  // even while blocked or paused; a finished build parked for its merge
6230
8517
  // decision holds none. Capacity is per repo (§16.1) — another repo's
6231
8518
  // builds never consume this repo's slots.
6232
- 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))
6233
8522
  // A node awaiting verification, or a parked build that must run again,
6234
- // reserves its slot ahead of new claims until it is admitted; this only
6235
- // ever lowers the claim budget.
6236
- 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
6237
8555
  const activeRefs: TicketRef[] = capacityBuilds
6238
8556
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
6239
8557
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
6240
- let capacity = intakeCapacity(projection, {
6241
- settled: this.parkedSettled,
6242
- denied: this.slotWaiters,
6243
- })
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'
6244
8570
 
6245
8571
  // The ready scan runs even at full capacity: `queued` is the operator's
6246
8572
  // standing queue-depth report and must stay honest exactly when the
6247
8573
  // dispatcher is saturated. Sources that keep a claimed ticket in the
6248
8574
  // ready state are deduped against the active builds embodying them.
6249
8575
  const journalBeforeReady = this.store.repositoryFacts().harvest
6250
- const listing = await this.listReady()
6251
- 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))
6252
8583
  // A provider listing can race reservation and blocker filing. Preserve
6253
8584
  // the before/after union, refreshing once only when admission is possible.
6254
8585
  if (listing.tickets.length > 0) await this.store.refreshJournal()
6255
8586
  const journalAfterReady = this.store.repositoryFacts()
6256
- if (journalAfterReady.health?.cause === 'ready-scan-failed') {
8587
+ if (!targeted && journalAfterReady.health?.cause === 'ready-scan-failed') {
6257
8588
  await this.sourceCondition(undefined, 'ready-scan')
6258
8589
  }
6259
8590
  const creationHolds = new Map(
@@ -6262,6 +8593,7 @@ export class Dispatcher {
6262
8593
  creation,
6263
8594
  ]),
6264
8595
  )
8596
+ const attemptHolds = await this.optimizationCreationHolds()
6265
8597
  const eligible = listing.tickets.filter(
6266
8598
  (ticket) =>
6267
8599
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
@@ -6271,15 +8603,34 @@ export class Dispatcher {
6271
8603
  // unchanged; a source without the priority capability is all normal.
6272
8604
  // A ticket whose labels select two profiles is never claimed (SPEC §9).
6273
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]! })
6274
8609
  const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
6275
- 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
6276
8612
  report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
6277
8613
  report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
8614
+ if (!targeted && normalPaused)
8615
+ report.ticketDiagnostics.push(backpressureExplanation(backpressure))
6278
8616
  report.queued = ready.length
6279
8617
  const withheld = new Set<string>()
6280
8618
  for (const ticket of ready) {
6281
8619
  if (ticket.creationKey === undefined) continue
6282
- 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)
6283
8634
  if (creation === undefined) continue
6284
8635
  withheld.add(ticket.ref.id)
6285
8636
  report.creationWithheld += 1
@@ -6297,17 +8648,34 @@ export class Dispatcher {
6297
8648
  // still runs either way, so the standing queue-depth report stays honest —
6298
8649
  // this only declines to claim a ticket into a build that would immediately
6299
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
6300
8657
  if (
6301
8658
  paused ||
6302
- (capacity <= 0 &&
8659
+ (!targeted &&
8660
+ normalPaused &&
8661
+ !ready.some(
8662
+ (ticket) => ticketPriority(ticket) === 'urgent' && !withheld.has(ticket.ref.id),
8663
+ )) ||
8664
+ (noBudget &&
6303
8665
  !ready.some(
6304
8666
  (ticket) =>
6305
- ticket.kind === 'node' ||
6306
- (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)),
6307
8670
  ))
6308
8671
  ) {
8672
+ if (checkpoint === undefined) return
6309
8673
  await this.sourceCondition(undefined, 'ready-scan')
6310
- 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
+ }
6311
8679
  return
6312
8680
  }
6313
8681
  // One dependency-node cache per scan: blockers are commonly shared across
@@ -6391,6 +8759,7 @@ export class Dispatcher {
6391
8759
  targetBlocked.add(ticket.ref.id)
6392
8760
  report.dependencyBlocked += 1
6393
8761
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
8762
+ settle(ticket, { outcome: 'blocked', detail: target })
6394
8763
  continue
6395
8764
  }
6396
8765
  preflightTargets.set(ticket.ref.id, JSON.stringify(target))
@@ -6486,23 +8855,47 @@ export class Dispatcher {
6486
8855
  })
6487
8856
  }
6488
8857
  }
6489
- for (const verdict of verdicts.values()) {
8858
+ for (const [id, verdict] of verdicts) {
6490
8859
  if (verdict.unresolved.length > 0) {
6491
8860
  report.dependencyBlocked += 1
6492
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
+ })
6493
8868
  }
6494
8869
  }
8870
+ let claimLoopCompleted = true
6495
8871
  for (const ticket of ready) {
6496
- if (this.outOfBudget(opts)) break
6497
- 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
6498
8884
  if (withheld.has(ticket.ref.id)) continue
6499
8885
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
6500
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
+ }
6501
8893
 
6502
8894
  const target = await this.resolveNodeTarget(ticket, targetScan)
6503
8895
  if (typeof target === 'string') {
6504
8896
  report.dependencyBlocked += 1
6505
8897
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
8898
+ settle(ticket, { outcome: 'blocked', detail: target })
6506
8899
  continue
6507
8900
  }
6508
8901
  if (hasNodes && preflightTargets.get(ticket.ref.id) !== JSON.stringify(target)) {
@@ -6537,7 +8930,12 @@ export class Dispatcher {
6537
8930
  }
6538
8931
  await store.ensureRepo(this.deps.repo)
6539
8932
  // A lapsed run leaves the ticket Ready for whoever holds the repository.
6540
- 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
6541
8939
  await store.appendRepo(this.deps.repo, {
6542
8940
  actor: DISPATCHER,
6543
8941
  type: 'ticket-preparation.intended',
@@ -6557,6 +8955,10 @@ export class Dispatcher {
6557
8955
  try {
6558
8956
  if (!(await tickets.claim(ticket.ref.id))) {
6559
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
+ })
6560
8962
  report.claimRaces += 1
6561
8963
  report.queued -= 1
6562
8964
  continue
@@ -6576,10 +8978,23 @@ export class Dispatcher {
6576
8978
  // Quality gate (§6.3): import a conforming ticket body as the spec;
6577
8979
  // author one for thin-but-groomed tickets; otherwise bounce.
6578
8980
  stage = 'spec'
6579
- let conformance = specConformance(body)
6580
- 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
+ ) {
6581
8995
  const authored = await this.deps.authorSpec(ticket)
6582
- if (authored !== null) {
8996
+ // An authored spec never gains the marker the ticket did not carry.
8997
+ if (authored !== null && objectiveBlocks(authored).length === 0) {
6583
8998
  conformance = specConformance(authored)
6584
8999
  if (conformance.conforms) {
6585
9000
  body = authored
@@ -6602,7 +9017,7 @@ export class Dispatcher {
6602
9017
  },
6603
9018
  })
6604
9019
  stage = 'bounce'
6605
- await this.bounce(ticket, conformance.missing)
9020
+ await this.bounce(ticket, conformance.missing, refusals.length > 0)
6606
9021
  stage = 'handback-report'
6607
9022
  await this.reportPreparationHandback(attempt, {
6608
9023
  ticket: ticket.ref,
@@ -6613,6 +9028,12 @@ export class Dispatcher {
6613
9028
  ...(missing ? { missing } : {}),
6614
9029
  })
6615
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
+ })
6616
9037
  report.bounced += 1
6617
9038
  report.queued -= 1
6618
9039
  continue
@@ -6646,6 +9067,10 @@ export class Dispatcher {
6646
9067
  ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
6647
9068
  // Fixed at claim from the same sample: relabelling never changes it.
6648
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)),
6649
9074
  }
6650
9075
  // `build.created` rides with the record so the pinned assets and the
6651
9076
  // record exist together or not at all.
@@ -6678,6 +9103,7 @@ export class Dispatcher {
6678
9103
  })
6679
9104
  established = true
6680
9105
  await this.preparationResolved(attempt, 'owned')
9106
+ settle(ticket, { outcome: 'started', slug: record.slug })
6681
9107
  } catch (error) {
6682
9108
  // A lapse is not a preparation failure: the successor recovers the
6683
9109
  // intended attempt through `recoverTicketPreparations`.
@@ -6717,7 +9143,11 @@ export class Dispatcher {
6717
9143
  )
6718
9144
  }
6719
9145
  report.queued -= 1
6720
- 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
+ }
6721
9151
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
6722
9152
  ticket,
6723
9153
  body,
@@ -6728,7 +9158,11 @@ export class Dispatcher {
6728
9158
  // means the remote provisioning continuation owns the rest.
6729
9159
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
6730
9160
  }
6731
- 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
+ }
6732
9166
  }
6733
9167
 
6734
9168
  /**
@@ -6796,6 +9230,22 @@ export class Dispatcher {
6796
9230
  return `target node ${ticket.target} is ${state.prState === 'merged' ? 'landed' : 'closed'}`
6797
9231
  if (state.pendingCommands.some((c) => c.command === 'abort'))
6798
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
+ }
6799
9249
  if (state.integration?.intent && !state.integration.landing)
6800
9250
  return `target node ${ticket.target} is merging`
6801
9251
  if (!digest.nodeOpened || !record.branch) return `target node ${ticket.target} is not yet open`
@@ -6830,8 +9280,23 @@ export class Dispatcher {
6830
9280
  }
6831
9281
  const sha = await forge.createNodeBranch(intent.branch, intent.sha)
6832
9282
  await this.store.refreshBuild(record.slug)
6833
- const latest = (await this.store.buildFacts(record.slug)).state
9283
+ let latest = (await this.store.buildFacts(record.slug)).state
6834
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
+ }
6835
9300
  await this.store.appendIfCurrent(record.slug, latest.lastSeq, {
6836
9301
  actor: DISPATCHER,
6837
9302
  type: 'node.opened',
@@ -6839,6 +9304,65 @@ export class Dispatcher {
6839
9304
  })
6840
9305
  }
6841
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
+
6842
9366
  private kernelForge(): Forge {
6843
9367
  const forge = this.deps.forge
6844
9368
  if (!forge.kernelRewrite) return forge
@@ -7174,12 +9698,19 @@ export class Dispatcher {
7174
9698
  }
7175
9699
 
7176
9700
  if (!this.accountsAvailable()) return
7177
- if (!(await this.nodeHasCapacity(record.slug))) return
7178
- if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
7179
- 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')
7180
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)
7181
9712
  } else {
7182
- if (openWorkspace(facts) === null) {
9713
+ if (openWorkspace(current) === null) {
7183
9714
  const handle = await this.provisionWorkspace(record.slug, {
7184
9715
  repo: checkout,
7185
9716
  baseBranch: state.baseBranch!,
@@ -7277,6 +9808,7 @@ export class Dispatcher {
7277
9808
  if (
7278
9809
  state.integration?.cycle &&
7279
9810
  !state.nodeRestack?.active &&
9811
+ !proposeRunDue(state.optimization) &&
7280
9812
  (!integrationCurrent(state) || integrationFailed(state))
7281
9813
  ) {
7282
9814
  const stale = (await readBuildFacts(this.store, record.slug)).value
@@ -7285,6 +9817,7 @@ export class Dispatcher {
7285
9817
  }
7286
9818
  if (
7287
9819
  unchangedFailure ||
9820
+ state.integration?.landing ||
7288
9821
  !integrationComplete(state) ||
7289
9822
  state.nodeRestack?.active ||
7290
9823
  state.integration?.intent ||
@@ -7311,6 +9844,9 @@ export class Dispatcher {
7311
9844
  !integrationCurrent(state) ||
7312
9845
  state.integration?.cycle?.config !== integrationConfig(config)
7313
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
7314
9850
  await this.observeIntegration(record.slug)
7315
9851
  state = (await this.store.buildFacts(record.slug)).state
7316
9852
  if (!integrationComplete(state)) return
@@ -7327,6 +9863,8 @@ export class Dispatcher {
7327
9863
  return
7328
9864
  const exact = await forge.compareBranches(state.baseBranch!, record.branch!)
7329
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
7330
9868
  const cycle = {
7331
9869
  id: this.deps.ids('integration-cycle'),
7332
9870
  parent: exact.parentSha,
@@ -7334,6 +9872,7 @@ export class Dispatcher {
7334
9872
  }
7335
9873
  let context: string | undefined
7336
9874
  let headPaths: HeadPathsArtifact | undefined
9875
+ let retained: RetentionOutcome | undefined
7337
9876
  await this.withKernelRepository(async (path) => {
7338
9877
  const head = await forge.rewrite!.snapshot({
7339
9878
  workspacePath: path,
@@ -7342,11 +9881,6 @@ export class Dispatcher {
7342
9881
  })
7343
9882
  if (head !== exact.headSha)
7344
9883
  throw new Error('node head moved while preparing verification')
7345
- await forge.rewrite!.archive({
7346
- workspacePath: path,
7347
- ref: `refs/autobuild/archive/${record.slug}/${head}`,
7348
- sha: head,
7349
- })
7350
9884
  const exec = forge.kernelExec ?? this.deps.exec
7351
9885
  // Snapshot fetch brings the complete head ancestry, including merge sides.
7352
9886
  // A parent may have advanced independently and need its own fetch.
@@ -7360,6 +9894,22 @@ export class Dispatcher {
7360
9894
  if (fetched.exitCode !== 0)
7361
9895
  throw new Error(`cannot fetch node verification parent: ${fetched.stderr}`)
7362
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
+ )
7363
9913
  // The cycle's candidate head is recorded once, with the cycle.
7364
9914
  if (!headPathsFor(current, exact.headSha).recorded)
7365
9915
  headPaths = await computeHeadPaths(exec, path, {
@@ -7381,6 +9931,31 @@ export class Dispatcher {
7381
9931
  })
7382
9932
  if (!(await this.store.renewNodeWriter(record.slug, holder))) return
7383
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
+ }
7384
9959
  if (headPaths !== undefined) {
7385
9960
  const { artifacts, makeEvent } = headPathsWrite(headPaths, 'integration', DISPATCHER)
7386
9961
  const recorded = await this.store.appendWithArtifactsIfCurrent(
@@ -7421,18 +9996,47 @@ export class Dispatcher {
7421
9996
  }
7422
9997
  if (integrationFailed(state) || integrationVerified(state, config)) {
7423
9998
  const facts = (await readBuildFacts(this.store, record.slug)).value
7424
- 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)
7425
10002
  return
7426
10003
  }
7427
- if (!(await this.nodeHasCapacity(record.slug))) return
10004
+ if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
7428
10005
  await this.observeIntegration(record.slug)
7429
10006
  state = (await this.store.buildFacts(record.slug)).state
7430
10007
  if (!integrationCurrent(state)) return
7431
10008
  if (!this.accountsAvailable()) return
7432
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
7433
10034
  if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
7434
10035
  const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
7435
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)
7436
10040
  return
7437
10041
  }
7438
10042
  if (openWorkspace(facts) === null) {
@@ -7440,9 +10044,9 @@ export class Dispatcher {
7440
10044
  try {
7441
10045
  handle = await this.provisionWorkspace(record.slug, {
7442
10046
  repo: this.deps.checkout ?? this.deps.repo,
7443
- baseBranch: record.branch,
7444
- branch: record.branch,
7445
- revision: state.integration!.cycle!.head,
10047
+ baseBranch: branch,
10048
+ branch,
10049
+ ...(revision !== undefined ? { revision } : {}),
7446
10050
  })
7447
10051
  } catch (error) {
7448
10052
  if (await this.holdForMissingAccounts(error)) return
@@ -7961,14 +10565,18 @@ export class Dispatcher {
7961
10565
  /** Bounce (§6.3): back to Triage with a comment citing the standard and
7962
10566
  * WHICH parts are missing — failure at the cheapest point, not a build
7963
10567
  * that thrashes and escalates. No build is created. */
7964
- private async bounce(ticket: Ticket, missing: string[]): Promise<void> {
10568
+ private async bounce(ticket: Ticket, missing: string[], refused = false): Promise<void> {
7965
10569
  const triageState = this.triageState()
7966
10570
  await this.deps.tickets.transition(ticket.ref.id, triageState)
7967
10571
  await this.deps.tickets.comment(
7968
10572
  ticket.ref.id,
7969
- `Bounced back to ${triageState}: this ticket does not conform to ` +
7970
- `the spec standard (.agents/skills/ab-guide/references/spec-standard.md) and cannot be dispatched.\n` +
7971
- `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('; ')}.`,
7972
10580
  )
7973
10581
  }
7974
10582