@defrex/autobuild 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (537) hide show
  1. package/README.md +3 -3
  2. package/SPEC.md +2232 -175
  3. package/bin/ab-dispatch-generation.ts +5 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/agent-runtimes.md +30 -3
  6. package/docs/answering-blocked-builds.md +35 -7
  7. package/docs/architecture.md +436 -63
  8. package/docs/build-store.md +10 -7
  9. package/docs/builds.md +5 -0
  10. package/docs/cli.md +40 -2
  11. package/docs/configuration-overview.md +5 -1
  12. package/docs/configuration.md +649 -74
  13. package/docs/dispatcher.md +79 -6
  14. package/docs/forges.md +8 -1
  15. package/docs/getting-started.md +1 -1
  16. package/docs/integration-overview.md +4 -2
  17. package/docs/integration-tree.md +102 -11
  18. package/docs/merge-policy.md +30 -14
  19. package/docs/migration-1.0.md +2 -1
  20. package/docs/operating.md +36 -6
  21. package/docs/operator-api.md +251 -20
  22. package/docs/operator-surfaces.md +85 -0
  23. package/docs/optimization-nodes.md +1100 -0
  24. package/docs/overview.md +1 -1
  25. package/docs/plugin-authoring.md +83 -13
  26. package/docs/remote-store-protocol.md +137 -17
  27. package/docs/remote-ticket-protocol.md +90 -2
  28. package/docs/restacking.md +119 -15
  29. package/docs/seams.md +2 -2
  30. package/docs/setup.md +27 -4
  31. package/docs/skills.md +4 -2
  32. package/docs/spec-standard.md +2 -1
  33. package/docs/ticket-dependencies.md +15 -3
  34. package/docs/ticket-migration.md +4 -2
  35. package/docs/ticket-sources.md +54 -14
  36. package/docs/tickets.md +21 -6
  37. package/docs/troubleshooting.md +11 -2
  38. package/docs/verification.md +15 -3
  39. package/docs/workspaces.md +6 -1
  40. package/package.json +9 -5
  41. package/packages/core/src/accounts/chatgpt-oauth.ts +7 -5
  42. package/packages/core/src/cli/accounts.ts +7 -2
  43. package/packages/core/src/cli/attempt.ts +103 -0
  44. package/packages/core/src/cli/attention.ts +11 -2
  45. package/packages/core/src/cli/binary-direct.ts +54 -1
  46. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  47. package/packages/core/src/cli/binary.ts +5 -3
  48. package/packages/core/src/cli/build-control.ts +407 -67
  49. package/packages/core/src/cli/context.ts +272 -15
  50. package/packages/core/src/cli/dashboard/detail.ts +26 -2
  51. package/packages/core/src/cli/dashboard/facts.ts +89 -56
  52. package/packages/core/src/cli/dashboard/header.ts +101 -0
  53. package/packages/core/src/cli/dashboard/integration-detail.ts +7 -2
  54. package/packages/core/src/cli/dashboard/landing-display.ts +15 -2
  55. package/packages/core/src/cli/dashboard/model.ts +133 -66
  56. package/packages/core/src/cli/dashboard/objective-row.ts +221 -0
  57. package/packages/core/src/cli/dashboard/poll.ts +178 -76
  58. package/packages/core/src/cli/dashboard/render.ts +172 -227
  59. package/packages/core/src/cli/dashboard/reopen-display.ts +39 -0
  60. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  61. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  62. package/packages/core/src/cli/dashboard/tree.ts +12 -1
  63. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  64. package/packages/core/src/cli/dispatch-args.ts +44 -1
  65. package/packages/core/src/cli/dispatch-frontend.ts +29 -30
  66. package/packages/core/src/cli/dispatch-launch-stop.ts +73 -0
  67. package/packages/core/src/cli/dispatch-launcher.ts +41 -46
  68. package/packages/core/src/cli/dispatch-repository-feed.ts +1 -1
  69. package/packages/core/src/cli/dispatch-web.ts +155 -0
  70. package/packages/core/src/cli/dispatch.ts +216 -38
  71. package/packages/core/src/cli/env.ts +42 -0
  72. package/packages/core/src/cli/help.ts +293 -12
  73. package/packages/core/src/cli/init-agent.ts +4 -1
  74. package/packages/core/src/cli/init-readiness-remote.ts +3 -2
  75. package/packages/core/src/cli/init-validation.ts +5 -5
  76. package/packages/core/src/cli/init.ts +3 -2
  77. package/packages/core/src/cli/judge-entry.ts +82 -0
  78. package/packages/core/src/cli/judge.ts +233 -0
  79. package/packages/core/src/cli/landings.ts +3 -2
  80. package/packages/core/src/cli/main.ts +481 -148
  81. package/packages/core/src/cli/mcp.ts +35 -3
  82. package/packages/core/src/cli/measurement-text.ts +19 -0
  83. package/packages/core/src/cli/objective.ts +154 -0
  84. package/packages/core/src/cli/operator-preference.ts +57 -0
  85. package/packages/core/src/cli/publication-settlement.ts +106 -22
  86. package/packages/core/src/cli/repo-lease.ts +3 -0
  87. package/packages/core/src/cli/repo-state.ts +56 -6
  88. package/packages/core/src/cli/repository-status.ts +205 -56
  89. package/packages/core/src/cli/status.ts +275 -16
  90. package/packages/core/src/cli/store-opening.ts +4 -0
  91. package/packages/core/src/cli/terminal-restore.ts +32 -7
  92. package/packages/core/src/cli/terminals.ts +205 -8
  93. package/packages/core/src/cli/ticket-start.ts +53 -0
  94. package/packages/core/src/cli/ticket.ts +166 -38
  95. package/packages/core/src/cli/upgrade-agent.ts +12 -8
  96. package/packages/core/src/cli/wait.ts +22 -8
  97. package/packages/core/src/cli/watch.ts +361 -95
  98. package/packages/core/src/cli/web.ts +139 -0
  99. package/packages/core/src/config/create-labels.ts +23 -0
  100. package/packages/core/src/config/live.ts +101 -14
  101. package/packages/core/src/config/load.ts +61 -20
  102. package/packages/core/src/config/local.ts +212 -0
  103. package/packages/core/src/config/pipeline-source.ts +3 -3
  104. package/packages/core/src/config/reference.ts +18 -0
  105. package/packages/core/src/config/roles.ts +182 -73
  106. package/packages/core/src/config/schema.ts +157 -19
  107. package/packages/core/src/events/catalog.ts +43 -3
  108. package/packages/core/src/events/compatibility.ts +7 -1
  109. package/packages/core/src/events/payloads.ts +685 -1
  110. package/packages/core/src/events/policy.ts +63 -0
  111. package/packages/core/src/events/repository.ts +153 -27
  112. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +1797 -199
  113. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  114. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/0ab2a90d0305dc9d.json.gz +0 -0
  115. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/10a4657408d4e121.json.gz +0 -0
  116. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1152a2e97ee81728.json.gz +0 -0
  117. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/13ca84752c5f8b54.json.gz +0 -0
  118. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1411d1cdbdd9911e.json.gz +0 -0
  119. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1444fe1fa7fc802c.json.gz +0 -0
  120. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1491ac0600349391.json.gz +0 -0
  121. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  122. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1921f86f752428c9.json.gz +0 -0
  123. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/1972c1d66008ef6b.json.gz +0 -0
  124. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/19e8e43e7f3f1a06.json.gz +0 -0
  125. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/20a85c143c3e8164.json.gz +0 -0
  126. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/21ce2c0bf58318e1.json.gz +0 -0
  127. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/293dcb3a94fb3470.json.gz +0 -0
  128. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2ab7436356267118.json.gz +0 -0
  129. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/2d084641735caaff.json.gz +0 -0
  130. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3237bcecf68e5db9.json.gz +0 -0
  131. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/33d0cc593610e56f.json.gz +0 -0
  132. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3451ed2136dcc356.json.gz +0 -0
  133. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/358ec8693f2237e6.json.gz +0 -0
  134. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/35cf9ccc4478b2d2.json.gz +0 -0
  135. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3649e7bd1203f154.json.gz +0 -0
  136. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/378da6dece82202a.json.gz +0 -0
  137. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/38c75099d9191471.json.gz +0 -0
  138. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/398952f1f01db1a3.json.gz +0 -0
  139. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3b64d352d56c9121.json.gz +0 -0
  140. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/3dc486226c05372d.json.gz +0 -0
  141. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/431c9bb2ee8838e0.json.gz +0 -0
  142. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4400dffca929e2f0.json.gz +0 -0
  143. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/49064fc079964a5c.json.gz +0 -0
  144. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  145. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4edded75f17742f4.json.gz +0 -0
  146. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4f00c0f2c8afd159.json.gz +0 -0
  147. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516a5a7aadf97587.json.gz +0 -0
  148. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/516dc6ea85d67cd7.json.gz +0 -0
  149. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  150. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/584e2ba74608e051.json.gz +0 -0
  151. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/59ffaa6974094c72.json.gz +0 -0
  152. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5bb43afb121674c6.json.gz +0 -0
  153. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/5f0ca42af862c4ee.json.gz +0 -0
  154. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6118031132db9bfc.json.gz +0 -0
  155. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63107a8d58776b63.json.gz +0 -0
  156. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/63546b08d4d6fa11.json.gz +0 -0
  157. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/643d70429ce03dad.json.gz +0 -0
  158. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/677ea92572c29082.json.gz +0 -0
  159. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6ae5bf60504d6467.json.gz +0 -0
  160. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  161. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6efdc8defc75fccb.json.gz +0 -0
  162. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/71c53d33f09d8204.json.gz +0 -0
  163. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7267ca2757cffba7.json.gz +0 -0
  164. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/76b7d4244082b3f9.json.gz +0 -0
  165. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7749f918c6f10968.json.gz +0 -0
  166. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7833e42d16301424.json.gz +0 -0
  167. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/7d4edad0614adaf1.json.gz +0 -0
  168. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/837365898d04f45a.json.gz +0 -0
  169. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/85f9f0c921b8b5bb.json.gz +0 -0
  170. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8879f57a24733897.json.gz +0 -0
  171. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/88cb9e71bdec972d.json.gz +0 -0
  172. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  173. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8a0cd6dd06cc155e.json.gz +0 -0
  174. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8aa9ca8609dc051d.json.gz +0 -0
  175. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8c8640255bd61658.json.gz +0 -0
  176. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8cc15eb1807c0157.json.gz +0 -0
  177. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8ced97c44bc0af3a.json.gz +0 -0
  178. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8d4144004720b9f8.json.gz +0 -0
  179. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8db633ead1807f8b.json.gz +0 -0
  180. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/8e42cdbd0994ab0c.json.gz +0 -0
  181. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9011d0f6ff955ef9.json.gz +0 -0
  182. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/916ebc5433801c41.json.gz +0 -0
  183. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9539b995af5c54a9.json.gz +0 -0
  184. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/95f391bfd7b7dbd7.json.gz +0 -0
  185. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9613e8fa568a9281.json.gz +0 -0
  186. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9a68f8753bd9038d.json.gz +0 -0
  187. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9b25e58227080094.json.gz +0 -0
  188. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/9ee3919fbd4f9458.json.gz +0 -0
  189. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a04a34cc2717147b.json.gz +0 -0
  190. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a0b32c12e4e6edb6.json.gz +0 -0
  191. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a55218252707bdd3.json.gz +0 -0
  192. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a732fd08b31522a6.json.gz +0 -0
  193. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  194. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a9d206a01f9039e5.json.gz +0 -0
  195. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/abf7fe3c92c82f2d.json.gz +0 -0
  196. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ac928b04842c00db.json.gz +0 -0
  197. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/af953392d81911da.json.gz +0 -0
  198. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0d877c44810ecb0.json.gz +0 -0
  199. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b0f7c6ebb2db57fc.json.gz +0 -0
  200. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/b905c22ec17eed31.json.gz +0 -0
  201. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/bce0c54e865f4b79.json.gz +0 -0
  202. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c68b7ee2e2610f30.json.gz +0 -0
  203. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c7f7e0378aeea237.json.gz +0 -0
  204. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/c98cb1659eb142b6.json.gz +0 -0
  205. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ca830adf06ed55a1.json.gz +0 -0
  206. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cb3a219f33e437ca.json.gz +0 -0
  207. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/cf1e0c0d82567e0c.json.gz +0 -0
  208. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d008d86d9ff77b30.json.gz +0 -0
  209. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d1432a819d8e48c5.json.gz +0 -0
  210. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d185ed6aa9192aff.json.gz +0 -0
  211. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  212. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d873fad29d6c7e55.json.gz +0 -0
  213. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/db84b12316e2da4a.json.gz +0 -0
  214. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ddf6dc967d898767.json.gz +0 -0
  215. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/dfc64de6e7bfc0a0.json.gz +0 -0
  216. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e2f18fa32fe1f6d0.json.gz +0 -0
  217. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e37393fed29e84c5.json.gz +0 -0
  218. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e6a8585e2a054ff6.json.gz +0 -0
  219. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e7e9e327baca6903.json.gz +0 -0
  220. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/e86447af0571672c.json.gz +0 -0
  221. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ea819202d22122e5.json.gz +0 -0
  222. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb4535585f2e84f6.json.gz +0 -0
  223. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eb7ddd5319d09e27.json.gz +0 -0
  224. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/eca4959b2b87ae15.json.gz +0 -0
  225. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ee10d7959ec4843c.json.gz +0 -0
  226. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/ef1b68347966ab26.json.gz +0 -0
  227. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f3e55425cc41f230.json.gz +0 -0
  228. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f40042c1cdb9fd43.json.gz +0 -0
  229. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f48466215c790a3f.json.gz +0 -0
  230. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f5b9ace9b59351e7.json.gz +0 -0
  231. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  232. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fa8f1475a55be935.json.gz +0 -0
  233. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fb21116a15d0b1f1.json.gz +0 -0
  234. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/fe95444fbeabe592.json.gz +0 -0
  235. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/09bf0a1611d07363.json +984 -0
  236. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/10eac4988d66e161.json +1067 -0
  237. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/1a436b5fb45aee3e.json +1116 -0
  238. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/249db6f7a41f90e2.json +161 -0
  239. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/25dcb2fb6eaa83f4.json +858 -0
  240. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/2e1bdc763924616f.json +4932 -0
  241. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/30e9dabce3c4263d.json +399 -0
  242. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  243. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/4898ef339c68fa36.json +83 -0
  244. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/51816c0ffa62af6e.json +417 -0
  245. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/561bf45320062a44.json +83 -0
  246. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5672d0233085d050.json +84 -0
  247. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/5e39f42cbdbf35ef.json +163 -0
  248. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/7771a7a2250f9964.json +868 -0
  249. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  250. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  251. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/881c491321bec99a.json +1074 -0
  252. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/965f25c3af1d2cdc.json +160 -0
  253. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9b76d89da575ca90.json +20 -0
  254. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9eb485320a72a9ff.json +233 -0
  255. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  256. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a60448c01016135e.json +18 -0
  257. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6584fb61b6679bd.json +97 -0
  258. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  259. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  260. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  261. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c88365c25b3186d3.json +543 -0
  262. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e8f0481b23f90056.json +711 -0
  263. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ee55782ed40ebbac.json +110 -0
  264. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc5082fac8167f3d.json +98 -0
  265. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  266. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fd55c329cfe921cc.json +1069 -0
  267. package/packages/core/src/kernel/attempt-creation-key.ts +20 -0
  268. package/packages/core/src/kernel/attempt-settlement.ts +125 -0
  269. package/packages/core/src/kernel/auto-merge-default.ts +1 -3
  270. package/packages/core/src/kernel/auto-merge.ts +1 -3
  271. package/packages/core/src/kernel/build-roster.ts +230 -0
  272. package/packages/core/src/kernel/dispatch-capacity.ts +316 -40
  273. package/packages/core/src/kernel/dispatch-placement.ts +1 -1
  274. package/packages/core/src/kernel/dispatch-settings.ts +1 -4
  275. package/packages/core/src/kernel/dispatch-status.ts +3 -5
  276. package/packages/core/src/kernel/dispatch-upgrade.ts +1 -1
  277. package/packages/core/src/kernel/engine.ts +152 -18
  278. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  279. package/packages/core/src/kernel/forge-checks.ts +140 -0
  280. package/packages/core/src/kernel/forge-health.ts +2 -2
  281. package/packages/core/src/kernel/generated-files.ts +43 -0
  282. package/packages/core/src/kernel/generated-regeneration.ts +254 -0
  283. package/packages/core/src/kernel/generators/build-log.ts +30 -2
  284. package/packages/core/src/kernel/generators/optimization-log.ts +679 -0
  285. package/packages/core/src/kernel/generators/panel-log.ts +133 -0
  286. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  287. package/packages/core/src/kernel/guarded-forge.ts +76 -11
  288. package/packages/core/src/kernel/harvest.ts +1 -4
  289. package/packages/core/src/kernel/head-paths.ts +4 -1
  290. package/packages/core/src/kernel/history-retention.ts +337 -0
  291. package/packages/core/src/kernel/incremental-fixtures.ts +6 -0
  292. package/packages/core/src/kernel/incremental.ts +14 -4
  293. package/packages/core/src/kernel/integration-landing.ts +64 -13
  294. package/packages/core/src/kernel/integration-stack.ts +123 -20
  295. package/packages/core/src/kernel/integration-state.ts +39 -2
  296. package/packages/core/src/kernel/janitor-failure.ts +2 -0
  297. package/packages/core/src/kernel/kernel-git.ts +1 -1
  298. package/packages/core/src/kernel/landing-measurement.ts +275 -0
  299. package/packages/core/src/kernel/landing-readiness.ts +2 -0
  300. package/packages/core/src/kernel/landing-state.ts +20 -1
  301. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  302. package/packages/core/src/kernel/leaf-restack-state.ts +99 -4
  303. package/packages/core/src/kernel/log-index-value.ts +2 -0
  304. package/packages/core/src/kernel/log-index.ts +100 -3
  305. package/packages/core/src/kernel/measurement.ts +406 -0
  306. package/packages/core/src/kernel/mixed-version.ts +6 -3
  307. package/packages/core/src/kernel/node-landing.ts +92 -18
  308. package/packages/core/src/kernel/node-restack-state.ts +27 -1
  309. package/packages/core/src/kernel/node-restack-transaction.ts +80 -23
  310. package/packages/core/src/kernel/node-verification-context.ts +14 -4
  311. package/packages/core/src/kernel/open-pr-backpressure-state.ts +24 -0
  312. package/packages/core/src/kernel/open-pr-backpressure.ts +133 -0
  313. package/packages/core/src/kernel/optimization-admission.ts +490 -0
  314. package/packages/core/src/kernel/optimization.ts +953 -0
  315. package/packages/core/src/kernel/panel.ts +225 -0
  316. package/packages/core/src/kernel/phase-failures.ts +121 -0
  317. package/packages/core/src/kernel/phases.ts +42 -6
  318. package/packages/core/src/kernel/pr-attachments.ts +4 -16
  319. package/packages/core/src/kernel/pr-summary.ts +2 -2
  320. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  321. package/packages/core/src/kernel/read-deferrals.ts +2 -2
  322. package/packages/core/src/kernel/read-facts.ts +69 -31
  323. package/packages/core/src/kernel/reconcile-restack.ts +352 -103
  324. package/packages/core/src/kernel/reducer-identity.ts +659 -0
  325. package/packages/core/src/kernel/reducer-registry.ts +62 -9
  326. package/packages/core/src/kernel/reducer-revisions.ts +75 -0
  327. package/packages/core/src/kernel/reducer.ts +269 -11
  328. package/packages/core/src/kernel/reopen-state.ts +48 -0
  329. package/packages/core/src/kernel/reopen.ts +143 -0
  330. package/packages/core/src/kernel/replay-retention.ts +208 -39
  331. package/packages/core/src/kernel/repository-attention.ts +1 -1
  332. package/packages/core/src/kernel/rollup.ts +61 -0
  333. package/packages/core/src/kernel/service-facts.ts +19 -7
  334. package/packages/core/src/kernel/setup-streak.ts +38 -0
  335. package/packages/core/src/kernel/step-durations.ts +257 -0
  336. package/packages/core/src/kernel/target-observation.ts +6 -1
  337. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  338. package/packages/core/src/kernel/terminal-guard.ts +13 -5
  339. package/packages/core/src/kernel/ticket-handbacks.ts +1 -1
  340. package/packages/core/src/kernel/ticket-migrations.ts +1 -1
  341. package/packages/core/src/kernel/ticket-preparation.ts +1 -1
  342. package/packages/core/src/kernel/ticket-source-health.ts +1 -1
  343. package/packages/core/src/kernel/ticket-starts.ts +118 -0
  344. package/packages/core/src/kernel/ticket-wait.ts +37 -2
  345. package/packages/core/src/kernel/verify-diff-base.ts +67 -0
  346. package/packages/core/src/kernel/verify-stage-state.ts +1 -0
  347. package/packages/core/src/kernel/verify-stages.ts +51 -1
  348. package/packages/core/src/objective.ts +532 -0
  349. package/packages/core/src/ontology.ts +54 -6
  350. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  351. package/packages/core/src/operator/annotations.ts +105 -4
  352. package/packages/core/src/operator/attention.ts +470 -0
  353. package/packages/core/src/operator/canonical-skills.ts +35 -0
  354. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  355. package/packages/core/src/operator/context-prompts.ts +61 -0
  356. package/packages/core/src/operator/control.ts +2 -1
  357. package/packages/core/src/operator/index.ts +61 -1
  358. package/packages/core/src/operator/landings.ts +28 -19
  359. package/packages/core/src/operator/optimization.ts +314 -0
  360. package/packages/core/src/operator/protocol.ts +33 -1
  361. package/packages/core/src/operator/query.ts +137 -73
  362. package/packages/core/src/operator/read-view.ts +5 -2
  363. package/packages/core/src/operator/registry.ts +625 -59
  364. package/packages/core/src/operator/requests.ts +45 -20
  365. package/packages/core/src/operator/sandbox-host.ts +107 -11
  366. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  367. package/packages/core/src/operator/sandbox.ts +778 -82
  368. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  369. package/packages/core/src/operator/ticket-assets.ts +167 -0
  370. package/packages/core/src/operator/ticket-start.ts +152 -0
  371. package/packages/core/src/operator/tickets.ts +36 -4
  372. package/packages/core/src/plugin-sdk/index.ts +24 -0
  373. package/packages/core/src/plugins/manifest.ts +1 -1
  374. package/packages/core/src/plugins/registry.ts +1 -0
  375. package/packages/core/src/ports/forge/contract.ts +9 -0
  376. package/packages/core/src/ports/forge/fake.ts +114 -2
  377. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  378. package/packages/core/src/ports/forge/git-rewrite.ts +6 -4
  379. package/packages/core/src/ports/forge/github-readiness.ts +1 -1
  380. package/packages/core/src/ports/forge/github-transport.ts +156 -1
  381. package/packages/core/src/ports/forge/github.ts +388 -100
  382. package/packages/core/src/ports/forge/local-git.ts +61 -1
  383. package/packages/core/src/ports/forge/readiness.ts +15 -3
  384. package/packages/core/src/ports/forge-failure.ts +46 -0
  385. package/packages/core/src/ports/forge-request-context.ts +23 -1
  386. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  387. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  388. package/packages/core/src/ports/runner/antigravity.ts +1071 -0
  389. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  390. package/packages/core/src/ports/runner/claude.ts +6 -1
  391. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  392. package/packages/core/src/ports/runner/codex.ts +11 -2
  393. package/packages/core/src/ports/runner/contract.ts +25 -1
  394. package/packages/core/src/ports/runner/fake.ts +2 -2
  395. package/packages/core/src/ports/runner/native-cli-fixture.ts +40 -5
  396. package/packages/core/src/ports/runner/native-process-fixture.ts +4 -1
  397. package/packages/core/src/ports/runner/pi.ts +23 -7
  398. package/packages/core/src/ports/runner/production.ts +19 -2
  399. package/packages/core/src/ports/runner/session-env.ts +65 -5
  400. package/packages/core/src/ports/runner/start-prompt.ts +6 -4
  401. package/packages/core/src/ports/tickets/contract.ts +75 -2
  402. package/packages/core/src/ports/tickets/fake.ts +11 -0
  403. package/packages/core/src/ports/tickets/file.ts +18 -0
  404. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  405. package/packages/core/src/ports/tickets/github.ts +407 -35
  406. package/packages/core/src/ports/tickets/hosted-index.ts +16 -1
  407. package/packages/core/src/ports/tickets/labels.ts +21 -0
  408. package/packages/core/src/ports/tickets/linear.ts +163 -0
  409. package/packages/core/src/ports/tickets/migration.ts +2 -0
  410. package/packages/core/src/ports/tickets/priority.ts +20 -0
  411. package/packages/core/src/ports/tickets/remote-protocol.ts +105 -6
  412. package/packages/core/src/ports/tickets/remote.ts +203 -17
  413. package/packages/core/src/ports/tickets/search.ts +139 -0
  414. package/packages/core/src/ports/tickets/tree.ts +17 -4
  415. package/packages/core/src/ports/types.ts +202 -6
  416. package/packages/core/src/ports/workspace/builtin-capabilities.ts +16 -4
  417. package/packages/core/src/ports/workspace/commit-preservation.ts +182 -64
  418. package/packages/core/src/ports/workspace/create.ts +18 -1
  419. package/packages/core/src/ports/workspace/fake.ts +340 -12
  420. package/packages/core/src/ports/workspace/git-worktree.ts +846 -43
  421. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  422. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  423. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1539 -221
  424. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  425. package/packages/core/src/processes/agent-context.ts +469 -0
  426. package/packages/core/src/processes/build-execution-state.ts +1 -3
  427. package/packages/core/src/processes/build-runner.ts +1982 -528
  428. package/packages/core/src/processes/dispatch-failure-budget.ts +1 -1
  429. package/packages/core/src/processes/dispatcher-selectors.ts +15 -13
  430. package/packages/core/src/processes/dispatcher.ts +3003 -308
  431. package/packages/core/src/processes/execution-no-progress.ts +40 -1
  432. package/packages/core/src/processes/execution-settlement.ts +2 -6
  433. package/packages/core/src/processes/harvest-execution-state.ts +2 -6
  434. package/packages/core/src/processes/harvest-runner.ts +7 -2
  435. package/packages/core/src/processes/infrastructure-failure-budget.ts +1 -3
  436. package/packages/core/src/processes/judge-launcher.ts +38 -0
  437. package/packages/core/src/processes/measurement-runner.ts +235 -0
  438. package/packages/core/src/processes/optimization-activity.ts +120 -0
  439. package/packages/core/src/processes/optimization-merges.ts +101 -0
  440. package/packages/core/src/processes/optimization-stop.ts +179 -0
  441. package/packages/core/src/processes/panel-runner.ts +756 -0
  442. package/packages/core/src/processes/phase-failure-budget.ts +2 -0
  443. package/packages/core/src/processes/publication-state.ts +1 -4
  444. package/packages/core/src/processes/repo-view.ts +154 -6
  445. package/packages/core/src/processes/sandbox-state.ts +54 -10
  446. package/packages/core/src/processes/tick-publication.ts +2 -0
  447. package/packages/core/src/processes/tick-state.ts +1 -3
  448. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  449. package/packages/core/src/processes/workspace-preservation.ts +67 -9
  450. package/packages/core/src/scenarios/harness.ts +19 -13
  451. package/packages/core/src/store/account-redaction.ts +1 -0
  452. package/packages/core/src/store/adapter.ts +52 -1
  453. package/packages/core/src/store/agent-context.ts +432 -0
  454. package/packages/core/src/store/build-feed.ts +291 -0
  455. package/packages/core/src/store/build-scope.ts +19 -1
  456. package/packages/core/src/store/contract.ts +955 -14
  457. package/packages/core/src/store/digest.ts +104 -9
  458. package/packages/core/src/store/histogram.ts +113 -0
  459. package/packages/core/src/store/judge-authority.ts +161 -0
  460. package/packages/core/src/store/local/schema.ts +62 -0
  461. package/packages/core/src/store/local/store.ts +628 -22
  462. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  463. package/packages/core/src/store/memory.ts +461 -69
  464. package/packages/core/src/store/open-builds.ts +19 -0
  465. package/packages/core/src/store/phase-session.ts +256 -6
  466. package/packages/core/src/store/reduced-reads.ts +24 -4
  467. package/packages/core/src/store/reducer-value-shapes.json +18023 -11824
  468. package/packages/core/src/store/reducer-values.ts +6 -1
  469. package/packages/core/src/store/remote/client.ts +220 -4
  470. package/packages/core/src/store/remote/compatibility.ts +1 -1
  471. package/packages/core/src/store/remote/credentials.ts +31 -1
  472. package/packages/core/src/store/remote/index.ts +41 -0
  473. package/packages/core/src/store/remote/protocol.ts +107 -0
  474. package/packages/core/src/store/remote/released-clients.json +22 -0
  475. package/packages/core/src/store/remote/released-reducer-values/1.10.0.json +34439 -0
  476. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  477. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  478. package/packages/core/src/store/remote/token.ts +13 -4
  479. package/packages/core/src/store/repo-state-events.ts +6 -8
  480. package/packages/core/src/store/retention.ts +23 -1
  481. package/packages/core/src/store/rollups.ts +337 -0
  482. package/packages/core/src/store/session-handle.ts +20 -2
  483. package/packages/core/src/store/session-reducer.ts +1 -4
  484. package/packages/core/src/store/snapshots.ts +10 -0
  485. package/packages/core/src/store/ticket-assets.ts +1 -3
  486. package/packages/core/src/store/types.ts +117 -9
  487. package/packages/core/src/testing/dispatch-read-budget.ts +1162 -2
  488. package/packages/core/src/testing/git-config-isolation.ts +27 -0
  489. package/packages/core/src/testing/index.ts +40 -0
  490. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  491. package/packages/core/src/testing/reduced-read-budget.ts +5349 -153
  492. package/packages/core/src/web/analytics-source.ts +303 -0
  493. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  494. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  495. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  496. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  497. package/packages/core/src/web/assets/app.css +1 -0
  498. package/packages/core/src/web/assets/app.js +9 -0
  499. package/packages/core/src/web/assets/manifest.json +31 -0
  500. package/packages/core/src/web/assets/theme.js +1 -0
  501. package/packages/core/src/web/bounded.ts +31 -0
  502. package/packages/core/src/web/http.ts +315 -0
  503. package/packages/core/src/web/hub.ts +160 -0
  504. package/packages/core/src/web/options.ts +38 -0
  505. package/packages/core/src/web/overview-source.ts +322 -0
  506. package/packages/core/src/web/page.ts +56 -0
  507. package/packages/core/src/web/protocol.ts +151 -0
  508. package/packages/core/src/web/read-only.ts +23 -0
  509. package/packages/core/src/web/repository-source.ts +35 -0
  510. package/packages/core/src/web/server.ts +97 -0
  511. package/skills/code-review/SKILL.md +26 -2
  512. package/skills/finalize/SKILL.md +10 -4
  513. package/skills/guide/SKILL.md +743 -123
  514. package/skills/guide/references/accounts.md +2 -1
  515. package/skills/guide/references/integration-tree.md +102 -11
  516. package/skills/guide/references/merge-policy.md +30 -14
  517. package/skills/guide/references/migration-1.0.md +2 -1
  518. package/skills/guide/references/operator-api.md +251 -20
  519. package/skills/guide/references/optimization-nodes.md +1100 -0
  520. package/skills/guide/references/plugin-authoring.md +83 -13
  521. package/skills/guide/references/remote-store-protocol.md +137 -17
  522. package/skills/guide/references/remote-ticket-protocol.md +90 -2
  523. package/skills/guide/references/restacking.md +119 -15
  524. package/skills/guide/references/setup.md +27 -4
  525. package/skills/guide/references/spec-standard.md +2 -1
  526. package/skills/guide/references/ticket-dependencies.md +15 -3
  527. package/skills/guide/references/ticket-migration.md +4 -2
  528. package/skills/implement/SKILL.md +74 -5
  529. package/skills/judge/SKILL.md +43 -0
  530. package/skills/operate/SKILL.md +374 -57
  531. package/skills/plan/SKILL.md +28 -4
  532. package/skills/plan-review/SKILL.md +24 -3
  533. package/skills/propose/SKILL.md +121 -0
  534. package/skills/reconcile/SKILL.md +21 -2
  535. package/skills/spec/SKILL.md +63 -11
  536. package/skills/tickets/SKILL.md +94 -9
  537. package/templates/hosted-service/package.json +2 -2
@@ -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,
@@ -21,6 +27,8 @@ import {
21
27
 
22
28
  import { preserveWorkspaceBeforeRelease, supersedeRestorationHeads } from './workspace-preservation'
23
29
  import { WorkspaceCleanupRequired } from '../ports/types'
30
+ import type { AgentContextCapture } from './agent-context'
31
+ import type { AgentContextDiagnostic } from '../store/agent-context'
24
32
  import type { OpenHarvestExecution } from './harvest-execution-state'
25
33
  import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
26
34
  import {
@@ -62,7 +70,13 @@ import {
62
70
  MixedVersionDeferral,
63
71
  } from '../kernel/mixed-version'
64
72
  import { guardForge, ForgeCooldown } from '../kernel/guarded-forge'
65
- import { leafLandingDeclineReason } from '../kernel/landing-readiness'
73
+ import {
74
+ CI_FAILURE_PREVIEW,
75
+ ciChecksObservable,
76
+ ciFailureKey,
77
+ failingSetDigest,
78
+ } from '../kernel/forge-checks'
79
+ import { actionableCommands, leafLandingDeclineReason } from '../kernel/landing-readiness'
66
80
  import {
67
81
  escalationsBeyondJanitor,
68
82
  janitorBlocked,
@@ -74,6 +88,13 @@ import {
74
88
  type JanitorOperation,
75
89
  } from '../kernel/janitor-failure'
76
90
  import { KernelGitUnavailable, kernelGitUnavailableDetail } from '../kernel/kernel-git'
91
+ import {
92
+ backpressureExplanation,
93
+ backpressureTransition,
94
+ openPrBackpressure,
95
+ openPrBackpressurePolicy,
96
+ openPrCount,
97
+ } from '../kernel/open-pr-backpressure'
77
98
  import { isForgeFailure, isForgeRejection } from '../ports/forge-failure'
78
99
  import {
79
100
  ForgeRequestDeferred,
@@ -81,15 +102,49 @@ import {
81
102
  forgeRequestContext,
82
103
  } from '../ports/forge-request-context'
83
104
  import {
105
+ forgeRateLimitObservationSchema,
106
+ forgeRateLimitSnapshotSchema,
107
+ type ForgeRateLimitSnapshot,
108
+ } from '../ports/forge-telemetry'
109
+ import {
110
+ buildPriority,
84
111
  dispatchCapacity,
85
112
  epilogueLeaf,
86
113
  intakeCapacity,
87
114
  nodeCapacity,
115
+ occupiesCapacity,
116
+ reservedAhead,
88
117
  settlementDue,
89
118
  settlementKey,
90
119
  slotRequest,
120
+ startCapacity,
121
+ startClaimDemand,
122
+ strandedNodeWorkspace,
123
+ urgentClaimDemand,
91
124
  type CapacityBuild,
125
+ type DispatchCapacity,
92
126
  } from '../kernel/dispatch-capacity'
127
+ import { attemptCreationKey } from '../kernel/attempt-creation-key'
128
+ import {
129
+ ExecutionFactsMissingError,
130
+ exhaustedStopDue,
131
+ optimizationElapsedHours,
132
+ proposalWithdrawalDue,
133
+ proposeAdmissible,
134
+ proposerAdmissible,
135
+ proposerBlocker,
136
+ proposerRoom,
137
+ proposeRunDue,
138
+ proposeStarted,
139
+ signalDue,
140
+ } from '../kernel/optimization'
141
+ import { proposalsDocumentSchema } from '../ontology'
142
+ import {
143
+ decideSampledMeasurement,
144
+ measurementThreshold,
145
+ nodeMeasurementDue,
146
+ sampledMeasurement,
147
+ } from '../kernel/measurement'
93
148
  import {
94
149
  openTicketWait,
95
150
  pendingWaitRequest,
@@ -100,6 +155,8 @@ import {
100
155
  waitUnresolvableQuestion,
101
156
  } from '../kernel/ticket-wait'
102
157
  import { changeBlockers } from '../ports/tickets/operations'
158
+ import { creationAssignees } from '../ports/tickets/assignees'
159
+ import { creationLabels } from '../ports/tickets/labels'
103
160
  import { evaluateLandingPolicy } from '../kernel/landing-policy'
104
161
  import { landingPolicyIdentity } from '../kernel/landing-policy-identity'
105
162
  import {
@@ -124,6 +181,7 @@ import {
124
181
  integrationVerified,
125
182
  integrationHeadVerified,
126
183
  integrationAdmissible,
184
+ nodeLanded,
127
185
  } from '../kernel/integration-state'
128
186
  import {
129
187
  normalizeIdentities,
@@ -144,18 +202,46 @@ import {
144
202
  type PresenceWitness,
145
203
  } from '../kernel/change-presence'
146
204
  import { landIntoNode, settleClosedNode, preflightNodeLanding } from '../kernel/node-landing'
205
+ import {
206
+ landingMeasurementGate,
207
+ harnessEscalationId,
208
+ regressionEscalationId,
209
+ selectTurnHolder,
210
+ mergedAttemptMeasurement,
211
+ settlementMeasurement,
212
+ type AttemptStatus,
213
+ type LandingGateVerdict,
214
+ type TurnCandidate,
215
+ } from '../kernel/landing-measurement'
216
+ import {
217
+ optimizationAttempt,
218
+ optimizationRejection,
219
+ type InFlightAttempt,
220
+ type PendingRejection,
221
+ } from '../kernel/optimization'
222
+ import {
223
+ attemptBranchPublished,
224
+ markUnmeasuredMerge,
225
+ settleAttempt,
226
+ } from '../kernel/attempt-settlement'
227
+ import { candidateHead } from '../kernel/head-paths-state'
228
+ import { compilePathSelectors } from '../config/path-selectors'
229
+ import { moveTicketToRole } from '../ports/tickets/operations'
147
230
  import { mkdtemp, rm } from 'node:fs/promises'
148
231
  import { tmpdir } from 'node:os'
149
232
  import { join } from 'node:path'
150
233
  import { runNodeTransaction } from '../kernel/node-restack-transaction'
151
234
  import { hasBuildTrailer } from '../kernel/build-identity'
152
- import { digestNodeTargets } from '../store/digest'
235
+ import { BuildDigestCapabilityError, digestNodeTargets, digestOptimization } from '../store/digest'
153
236
  import { readBuildDigests, readForgeHealth } from '../store/reduced-reads'
237
+ import { enforceOptimizationStop } from './optimization-stop'
238
+ import { recordOptimizationActivity } from './optimization-activity'
239
+ import { reconcileMergedAttempts } from './optimization-merges'
154
240
  import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
155
241
  import { ensureExecutionProgress } from './execution-no-progress'
156
242
  import { ticketIdentity } from '../ports/tickets/identity'
157
243
  import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
158
- import { urgentFirst } from '../ports/tickets/priority'
244
+ import { ticketPriority, urgentFirstBy } from '../ports/tickets/priority'
159
245
  import { ensureDispatchBudget } from './dispatch-failure-budget'
160
246
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
161
247
  /**
@@ -197,12 +283,17 @@ import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
197
283
  * execution lease before launch; the child renews that same-holder lease.
198
284
  */
199
285
  import { createHash } from 'node:crypto'
200
- import type { Config } from '../config/schema'
286
+ import { orchestratorEnabled, type Config, type OrchestratorHost } from '../config/schema'
201
287
  import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
202
288
  import { isRemoteWorkspace } from '../events/workspace-remote'
203
289
  import type { AbEvent, EventWrite } from '../events/catalog'
204
290
  import type { AbortDestination, EventPayload, PinnedAsset } from '../events/payloads'
205
- import type { RepositoryEventPayload } from '../events/repository'
291
+ import type {
292
+ RepositoryEventPayload,
293
+ TicketStartOutcome,
294
+ TicketStartPriority,
295
+ } from '../events/repository'
296
+ import { ticketStartKey, type PendingTicketStart, type TicketStarts } from '../kernel/ticket-starts'
206
297
  import { handbackIdentity } from '../kernel/ticket-handbacks'
207
298
  import type { IdSource } from '../ids'
208
299
  import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
@@ -227,8 +318,11 @@ import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution
227
318
  import type {
228
319
  DependencyState,
229
320
  Forge,
321
+ HeadChecks,
230
322
  IssueLink,
323
+ PrState,
231
324
  Ticket,
325
+ TicketPriority,
232
326
  TicketSource,
233
327
  WorkspaceProvider,
234
328
  WorkspaceProvisionResult,
@@ -236,6 +330,7 @@ import type {
236
330
  import {
237
331
  isForgeMergeQueueRejection,
238
332
  NoCommitsBetweenBranchesError,
333
+ TicketClaimBlockedError,
239
334
  TicketSourceRateLimitError,
240
335
  } from '../ports/types'
241
336
  import { issueLinksForForge } from '../kernel/issue-keywords'
@@ -257,6 +352,13 @@ import { creationBuildSlug } from '../kernel/build-creation'
257
352
  import { preparePinnedAssets } from '../store/ticket-assets'
258
353
  import { resolveRepoOrigin } from '../cli/repo-state'
259
354
  import { specConformance } from '../spec-standard'
355
+ import {
356
+ objectiveBlocks,
357
+ objectiveRefusals,
358
+ objectiveRulerChanged,
359
+ parseObjective,
360
+ type Objective,
361
+ } from '../objective'
260
362
  export { specConformance, type SpecConformance } from '../spec-standard'
261
363
  import { recordInfrastructureFailure as appendInfrastructureFailure } from './infrastructure-failure-budget'
262
364
  import { settleOpenExecution } from './execution-settlement'
@@ -534,6 +636,10 @@ export interface TickReport {
534
636
  * background work this tick. The tick returns without awaiting it; the
535
637
  * continuation completes the remaining boundaries and the launch. */
536
638
  provisioning: number
639
+ /** Builds whose provisioning start was deferred because the bounded
640
+ * invocation's remaining budget was shorter than the provider's
641
+ * provisioning estimate. Nothing is written; a later invocation starts it. */
642
+ provisioningDeferred: number
537
643
  /** Dispatch (§12): builds created and launched. With durable supervision
538
644
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
539
645
  * awaited launches: a dispatch whose remote provisioning continues in the
@@ -579,6 +685,9 @@ export interface TickReport {
579
685
  sandboxIdleStops: number
580
686
  /** Contained idle-settlement failures this tick; retried next tick. */
581
687
  sandboxSettleFailures: number
688
+ /** Agent-context stage (`processes/agent-context.ts`): typed problems this
689
+ * tick found capturing the base branch's skills and agent instructions. */
690
+ agentContextDiagnostics: AgentContextDiagnostic[]
582
691
  }
583
692
 
584
693
  export function emptyTickReport(): TickReport {
@@ -597,6 +706,7 @@ export function emptyTickReport(): TickReport {
597
706
  swept: 0,
598
707
  settled: 0,
599
708
  provisioning: 0,
709
+ provisioningDeferred: 0,
600
710
  dispatched: 0,
601
711
  authored: 0,
602
712
  bounced: 0,
@@ -616,9 +726,48 @@ export function emptyTickReport(): TickReport {
616
726
  harvestFailed: 0,
617
727
  sandboxIdleStops: 0,
618
728
  sandboxSettleFailures: 0,
729
+ agentContextDiagnostics: [],
619
730
  }
620
731
  }
621
732
 
733
+ /** A settlement `dispatch()` reached for one targeted ticket. */
734
+ type TargetedOutcome = {
735
+ outcome: TicketStartOutcome
736
+ slug?: string
737
+ detail?: string
738
+ }
739
+
740
+ /** One targeted admission pass for operator start requests (AUT-1293). */
741
+ interface TargetedDispatch {
742
+ tickets: Ticket[]
743
+ /** Active ticket identities, matched without source reads. */
744
+ activeIds: Set<string>
745
+ /** The request each ticket answers, keyed by ticket id. */
746
+ requests: Map<string, PendingTicketStart>
747
+ /** Keyed by ticket id. A ticket without an entry stays pending. */
748
+ outcomes: Map<string, TargetedOutcome>
749
+ /** The capacity inputs the stage measured from this tick's served facts. */
750
+ measured: CapacityBuild[]
751
+ /** Slots left for each start tier (`startCapacity`). A claim spends only
752
+ * its own tier's: lower tiers already reserved it as a pending request. */
753
+ budgets: Record<TicketStartPriority, number>
754
+ }
755
+
756
+ /** An active build's ticket ref, normalized through recorded migrations. */
757
+ interface ActiveTicketRef {
758
+ slug: string
759
+ createdAt: string
760
+ ref: TicketRef
761
+ }
762
+
763
+ /** Start requests one pass evaluates, in tier order, oldest first. */
764
+ const START_REQUESTS_PER_TICK = 8
765
+ const START_TIER_ORDER: readonly TicketStartPriority[] = ['manual', 'urgent', 'normal']
766
+ /** Hosted active-build identities one tick resolves; each build once in its life. */
767
+ const IDENTITY_RESOLUTIONS_PER_TICK = 16
768
+ /** Released identity slugs one projection append carries. */
769
+ const IDENTITY_RELEASES_PER_APPEND = 256
770
+
622
771
  // ── Dispatcher ───────────────────────────────────────────────────────────────
623
772
 
624
773
  const DEFAULT_SLUG_NAMING_TIMEOUT_MS = 10_000
@@ -632,6 +781,9 @@ const DISPATCH_COMMENT = /^build ([a-z0-9][a-z0-9-]*) dispatched$/
632
781
  * lease. A dead provisioner is therefore adopted within one lease TTL. */
633
782
  const PROVISION_HEARTBEAT_MS = 15_000
634
783
  const DEFAULT_PROVISION_STALE_MS = 20 * 60 * 1000
784
+ /** Rate-limit readings carried in tick telemetry: resources and age bounds. */
785
+ const FORGE_RATE_LIMIT_RESOURCES = 8
786
+ const FORGE_RATE_LIMIT_RETENTION_MS = 24 * 60 * 60 * 1000
635
787
 
636
788
  /** Outcome of one attempt to complete an interrupted dispatch. `deferred`
637
789
  * means durable progress was made (background provisioning kicked or already
@@ -737,6 +889,9 @@ export interface TickOpts {
737
889
  export type LaunchRunnerResult = 'scheduled' | 'already-active'
738
890
 
739
891
  export interface DispatcherDeps {
892
+ /** Where `[orchestrator].enabled` is resolved for idle settlement
893
+ * (`orchestratorEnabled`). Default `local`. */
894
+ orchestratorHost?: OrchestratorHost
740
895
  /** Whether this process currently holds repository authority (SPEC §12).
741
896
  * Synchronous and without I/O. Absent means always true. When false, the
742
897
  * tick starts no further unit of work, and its durable new-work writes are
@@ -809,6 +964,9 @@ export interface DispatcherDeps {
809
964
  * harvest settlement stage skips them: their completion chain owns the
810
965
  * durable facts. */
811
966
  activeHarvestExecutions?: () => ReadonlySet<string>
967
+ /** The agent-context stage, run last on every tick that still has budget
968
+ * and repository authority. Absent: the tick captures nothing. */
969
+ agentContext?: Pick<AgentContextCapture, 'run'>
812
970
  ids: IdSource
813
971
  clock: Clock
814
972
  opts?: DispatcherOpts
@@ -833,6 +991,19 @@ function baseBranchOf(events: CurrentBuildFacts, config: Config): string {
833
991
  return events.baseBranch ?? config.baseBranch
834
992
  }
835
993
 
994
+ /** An open optimization node whose latest spec revision has not had its
995
+ * objective accepted yet. Read from reduced state alone: zero added reads. */
996
+ export function objectiveAcceptancePending(state: BuildState): boolean {
997
+ return (
998
+ state.kind === 'node' &&
999
+ state.nodeOpened !== undefined &&
1000
+ state.optimization !== undefined &&
1001
+ state.status !== 'done' &&
1002
+ state.status !== 'aborted' &&
1003
+ (state.specRev ?? 0) > state.optimization.accepted.specRev
1004
+ )
1005
+ }
1006
+
836
1007
  function artifactRefOf(deposited: ArtifactMeta[]): ArtifactRef {
837
1008
  const meta = deposited[0]
838
1009
  if (!meta) throw new Error('spec deposit produced no artifact meta')
@@ -1111,11 +1282,36 @@ export class Dispatcher {
1111
1282
  /** Per tick, rebuilt from durable state: builds launched so far, which
1112
1283
  * occupy a slot before their runner claims a lease. */
1113
1284
  private tickLaunched: ReadonlySet<string> = new Set()
1114
- /** Per tick: finished leaves the admission gate turned away. Intake reserves their slots. */
1115
- private readonly slotWaiters = new Set<string>()
1285
+ /** Per tick: finished leaves the admission gate turned away or deferred,
1286
+ * with their priority. Intake reserves their slots. */
1287
+ private readonly slotWaiters = new Map<string, TicketPriority>()
1288
+ /** Per tick, in visit order: normal parked admissions that would have taken
1289
+ * a free slot before this tick's dispatch evaluated urgent claims (SPEC §12
1290
+ * "Slot admission order"). Nothing was written for them;
1291
+ * `admitDeferredParked` retries each through its generic path. */
1292
+ private readonly deferredAdmissions = new Map<string, 'leaf' | 'node' | 'proposer'>()
1293
+ /** Per tick: admission may defer normal parked work. Opened by `runTick`
1294
+ * when claims can run, closed once urgent claims were evaluated. */
1295
+ private admissionBoundary = false
1296
+ /** Per tick: this tick's admission scan completed its urgent decision. Only
1297
+ * `dispatch` sets it. */
1298
+ private urgentEvaluated = false
1299
+ /** Per tick: the deferral key this tick's admission scan was forced for. */
1300
+ private forcedDeferralKey: string | undefined
1301
+ /** In memory: the last deferral key whose forced scan completed and whose
1302
+ * retries ran. An unchanged key lists again only when a scan is due on its
1303
+ * own, so idle ticks repeating one blocked state cost no extra listing. */
1304
+ private lastForcedDeferralKey: string | undefined
1305
+ /** Per tick: `opts.acceptNewWork` and the repository pause sampled by `runTick`. */
1306
+ private tickAcceptsNewWork = false
1307
+ private tickPaused = false
1116
1308
  /** Per tick: parked leaves whose sweep decision was `wait awaiting-pr`. A
1117
1309
  * projected wait for one of these is one tick stale and reserves nothing. */
1118
1310
  private readonly parkedSettled = new Set<string>()
1311
+ /** Start requests whose ticket has a target and blockers and that have
1312
+ * had one full pass with no free slot: the pass that may settle them
1313
+ * `blocked`. Later full-capacity ticks wait for a slot without one. */
1314
+ private startBlockersChecked = new Set<number>()
1119
1315
 
1120
1316
  // Batched confirmed landing evidence is shared across nodes for this tick.
1121
1317
  // Only durable availability facts authorize the shortcut after restart. The
@@ -1124,6 +1320,14 @@ export class Dispatcher {
1124
1320
  private availabilityLandings?: ReturnType<typeof confirmedLandings>
1125
1321
  private availabilityLandingKey?: string
1126
1322
  private availabilityEntries?: ReturnType<Dispatcher['repoBuildDigests']>
1323
+ /** While the start pass's targeted dispatch runs: its deferral checks
1324
+ * serve this tick's retained facts (`servedBuildFacts`). */
1325
+ private startPass = false
1326
+ /** Per tick: the janitor's work listing, and the nonterminal children of
1327
+ * each node indexed from it on the first landing turn that needs them. The
1328
+ * landing gate reads its turn candidates here, never from a new listing. */
1329
+ private janitorEntries?: { record: BuildRecord; digest: BuildDigest }[]
1330
+ private nodeChildren?: Map<string, BuildRecord[]>
1127
1331
  /** Set once kernel Git proved unable to run this tick; later node work in
1128
1332
  * the same tick defers on it without spawning again. */
1129
1333
  private kernelGitUnavailable?: KernelGitUnavailable
@@ -1184,10 +1388,72 @@ export class Dispatcher {
1184
1388
  }
1185
1389
 
1186
1390
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
1391
+ /** Latest primary rate-limit reading per resource, carried across ticks so
1392
+ * a cooldown tick with no wire request still reports the last known quota. */
1393
+ private readonly forgeRateLimits = new Map<string, ForgeRateLimitSnapshot>()
1394
+
1395
+ /** Merges the view's retained durable tick sample (newest `observedAt` per
1396
+ * resource wins), then returns the bounded carried list. No store read: the
1397
+ * sample is the record the journal refresh already fetched. */
1398
+ private carriedRateLimits(): ForgeRateLimitSnapshot[] {
1399
+ const sample = this.store.lastTickSample()
1400
+ const durable =
1401
+ sample === undefined
1402
+ ? undefined
1403
+ : sample.outcome === 'completed'
1404
+ ? sample.counters.forgeRequests?.rateLimits
1405
+ : sample.forgeRequests?.rateLimits
1406
+ for (const entry of durable ?? []) {
1407
+ const parsed = forgeRateLimitSnapshotSchema.safeParse(entry)
1408
+ if (!parsed.success) continue
1409
+ const carried = this.forgeRateLimits.get(parsed.data.resource)
1410
+ if (
1411
+ carried === undefined ||
1412
+ Date.parse(parsed.data.observedAt) > Date.parse(carried.observedAt)
1413
+ )
1414
+ this.forgeRateLimits.set(parsed.data.resource, parsed.data)
1415
+ }
1416
+ const cutoff = this.deps.clock().getTime() - FORGE_RATE_LIMIT_RETENTION_MS
1417
+ for (const [resource, entry] of this.forgeRateLimits)
1418
+ if (Date.parse(entry.observedAt) < cutoff) this.forgeRateLimits.delete(resource)
1419
+ this.boundForgeRateLimits()
1420
+ return [...this.forgeRateLimits.values()].sort((a, b) => a.resource.localeCompare(b.resource))
1421
+ }
1422
+
1423
+ private boundForgeRateLimits(): void {
1424
+ while (this.forgeRateLimits.size > FORGE_RATE_LIMIT_RESOURCES) {
1425
+ let oldest: ForgeRateLimitSnapshot | undefined
1426
+ for (const entry of this.forgeRateLimits.values())
1427
+ if (oldest === undefined || Date.parse(entry.observedAt) < Date.parse(oldest.observedAt))
1428
+ oldest = entry
1429
+ if (oldest === undefined) return
1430
+ this.forgeRateLimits.delete(oldest.resource)
1431
+ }
1432
+ }
1433
+
1434
+ /** The forge request telemetry a tick that failed before or inside
1435
+ * {@link tick} persists: the last counts (or an honestly incomplete empty
1436
+ * count) carrying every known rate-limit reading. */
1437
+ failureForgeRequests(): import('../ports/forge-telemetry').ForgeRequestCounts | undefined {
1438
+ const rateLimits = this.carriedRateLimits()
1439
+ const base = this.lastForgeRequests
1440
+ if (base === undefined && rateLimits.length === 0) return undefined
1441
+ const { rateLimits: _previous, ...rest } = base ?? {
1442
+ total: 0,
1443
+ unattributed: 0,
1444
+ builds: [],
1445
+ complete: false,
1446
+ }
1447
+ return { ...rest, ...(rateLimits.length > 0 ? { rateLimits } : {}) }
1448
+ }
1449
+
1187
1450
  async tick(opts: TickOpts = {}): Promise<TickReport> {
1188
1451
  this.kernelGitUnavailable = undefined
1189
1452
  this.tickAbandonments = []
1453
+ this.tickDeadlineAt = opts.deadlineAt
1190
1454
  this.availabilityEntries = undefined
1455
+ this.janitorEntries = undefined
1456
+ this.nodeChildren = undefined
1191
1457
  this.availabilityLandings = undefined
1192
1458
  this.availabilityLandingKey = undefined
1193
1459
  const builds = new Map<string, number>()
@@ -1204,17 +1470,31 @@ export class Dispatcher {
1204
1470
  }
1205
1471
  if (build) builds.set(build, (builds.get(build) ?? 0) + 1)
1206
1472
  else unattributed++
1473
+ if (request.rateLimit) {
1474
+ const observation = forgeRateLimitObservationSchema.safeParse(request.rateLimit)
1475
+ if (observation.success) {
1476
+ this.forgeRateLimits.set(observation.data.resource, {
1477
+ ...observation.data,
1478
+ observedAt: this.deps.clock().toISOString(),
1479
+ })
1480
+ this.boundForgeRateLimits()
1481
+ }
1482
+ }
1207
1483
  })
1208
- const counts = () => ({
1209
- total,
1210
- ...(classified ? categories : {}),
1211
- unattributed,
1212
- builds: [...builds]
1213
- .map(([build, requests]) => ({ build, requests }))
1214
- .sort((a, b) => b.requests - a.requests || a.build.localeCompare(b.build))
1215
- .slice(0, 10),
1216
- complete: true,
1217
- })
1484
+ const counts = () => {
1485
+ const rateLimits = this.carriedRateLimits()
1486
+ return {
1487
+ total,
1488
+ ...(classified ? categories : {}),
1489
+ unattributed,
1490
+ builds: [...builds]
1491
+ .map(([build, requests]) => ({ build, requests }))
1492
+ .sort((a, b) => b.requests - a.requests || a.build.localeCompare(b.build))
1493
+ .slice(0, 10),
1494
+ complete: true,
1495
+ ...(rateLimits.length > 0 ? { rateLimits } : {}),
1496
+ }
1497
+ }
1218
1498
  this.lastForgeRequests = undefined
1219
1499
  try {
1220
1500
  const report = await (this.deps.forge.withReadScope
@@ -1232,6 +1512,10 @@ export class Dispatcher {
1232
1512
  }
1233
1513
  }
1234
1514
 
1515
+ /** The current tick's invocation deadline, consulted by the provisioning
1516
+ * budget gate. Undefined for unbounded (watch/foreground) ticks. */
1517
+ private tickDeadlineAt: number | undefined
1518
+
1235
1519
  /** Ticket preparations durably abandoned during the current tick. Drained
1236
1520
  * once by `tick()` into its report or its rejection, so later ticks never
1237
1521
  * repeat them. At most 8 recoveries plus one inline abandonment per tick. */
@@ -1261,10 +1545,19 @@ export class Dispatcher {
1261
1545
  this.nodePollingTickReads.clear()
1262
1546
  this.slotWaiters.clear()
1263
1547
  this.parkedSettled.clear()
1548
+ this.deferredAdmissions.clear()
1549
+ this.admissionBoundary = false
1550
+ this.urgentEvaluated = false
1551
+ this.forcedDeferralKey = undefined
1264
1552
  // One immutable config for this complete decision pass. A reload racing the
1265
1553
  // tick is observed by the next tick, never half-way through this one.
1266
1554
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1267
1555
  if (opts.viewRefreshed !== true) await this.store.refresh()
1556
+ // A pending start request measures capacity from the facts this tick's
1557
+ // fleet-wide stages read anyway; keep them only then.
1558
+ this.store.retainBuildFacts(
1559
+ Object.keys(this.store.repositoryFacts().ticketStarts.pending).length > 0,
1560
+ )
1268
1561
  const autoMergeUser = undefined
1269
1562
  const report = emptyTickReport()
1270
1563
  this.restoreScan(report)
@@ -1280,6 +1573,11 @@ export class Dispatcher {
1280
1573
  const repoFacts = this.store.repositoryFacts()
1281
1574
  if (this.deps.missingAccounts) await this.reconcileAccountPresence(this.deps.missingAccounts())
1282
1575
  const paused = repoFacts.settings.paused
1576
+ this.tickAcceptsNewWork = opts.acceptNewWork !== false
1577
+ this.tickPaused = paused
1578
+ // Normal parked work never takes a free slot before this tick's dispatch
1579
+ // has evaluated urgent claims, while claims can run at all.
1580
+ this.admissionBoundary = !opts.observationOnly && this.claimsPossible(opts, paused)
1283
1581
  const autoMergeSeedFact = undefined
1284
1582
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
1285
1583
  // provider liveness and settle their completion, lease, and publication.
@@ -1314,22 +1612,59 @@ export class Dispatcher {
1314
1612
  if (this.outOfBudget(opts)) return report
1315
1613
  await this.leaseSweep(report, launched, paused, opts)
1316
1614
  if (this.outOfBudget(opts)) return report
1317
- // Nodes with a durable verification request take freed slots before
1318
- // intake, whether or not idle node polling visited them this tick.
1615
+ // Nodes with a durable verification or propose request take freed slots
1616
+ // before intake, whether or not idle node polling visited them this tick.
1617
+ // The same pass advances optimization nodes' proposers first.
1319
1618
  await this.admitWaitingNodes(report, launched, opts)
1320
1619
  if (this.outOfBudget(opts)) return report
1620
+ // Operator start requests are independent of intake: they claim only the
1621
+ // named tickets, and read nothing when none is pending. Manual and urgent
1622
+ // requests run here, ahead of ordinary claims; normal requests run after
1623
+ // urgent claims and normal parked work (SPEC §12 "Slot admission order").
1624
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, [
1625
+ 'manual',
1626
+ 'urgent',
1627
+ ])
1628
+ if (this.outOfBudget(opts)) return report
1321
1629
  if (opts.acceptNewWork !== false) {
1322
1630
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1323
1631
  }
1632
+ await this.admitDeferredParked(report, launched, paused, opts)
1633
+ // Ordinary normal claims left this pass's reserved slots free.
1634
+ if (!this.outOfBudget(opts))
1635
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, ['normal'])
1324
1636
  // Fire-and-forget by contract: long synthesize/review sessions must not
1325
1637
  // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1326
1638
  // watch ticks. Durable pause and infrastructure-error stops suppress
1327
1639
  // launch. Pending control commands still launch the runner so the kernel
1328
1640
  // can settle them under the repository lease.
1329
1641
  await this.triggerHarvest()
1642
+ await this.captureAgentContext(report, opts)
1330
1643
  return report
1331
1644
  }
1332
1645
 
1646
+ /** Agent-context stage: contained, so a capture failure never fails the
1647
+ * tick; only an authority lapse escapes. */
1648
+ private async captureAgentContext(report: TickReport, opts: TickOpts): Promise<void> {
1649
+ const stage = this.deps.agentContext
1650
+ if (stage === undefined || this.outOfBudget(opts)) return
1651
+ try {
1652
+ report.agentContextDiagnostics.push(
1653
+ ...(await stage.run({
1654
+ baseBranch: this.deps.config.baseBranch,
1655
+ ...(opts.deadlineAt !== undefined ? { deadlineAt: opts.deadlineAt } : {}),
1656
+ holdsAuthority: () => this.deps.holdsRepoAuthority?.() !== false,
1657
+ })),
1658
+ )
1659
+ } catch (error) {
1660
+ rethrowAuthorityLapse(error)
1661
+ report.agentContextDiagnostics.push({
1662
+ kind: 'capture-failed',
1663
+ message: error instanceof Error ? error.message : String(error),
1664
+ })
1665
+ }
1666
+ }
1667
+
1333
1668
  /** The repository-wide quiescence flag, from durable state. Guarded like
1334
1669
  * `triggerHarvest`: `getRepoEvents` throws for a repository row no tick has
1335
1670
  * created yet, and an unpaused repository is the correct reading of one that
@@ -1355,14 +1690,21 @@ export class Dispatcher {
1355
1690
  const { repo } = this.deps
1356
1691
  const records = (await store.listBuilds()).filter((record) => record.repo === repo)
1357
1692
  const digests = await readBuildDigests(store, repo)
1693
+ // Including deferred builds needs no deferral check: the tick's stages
1694
+ // that exclude them already checked and recorded it. The check reads
1695
+ // through the view, so a retaining tick keeps the read for capacity, and
1696
+ // the start pass serves it instead of reading the deferred builds again.
1358
1697
  const blocked = new Set<string>()
1359
- for (const record of records) {
1360
- if (
1361
- (digests.get(record.slug)?.compatibility?.decisiveFacts ?? 0) > 0 &&
1362
- (await deferMixedVersion(store, record.slug))
1363
- )
1364
- blocked.add(record.slug)
1365
- }
1698
+ const readFacts = (slug: string) =>
1699
+ this.startPass ? store.servedBuildFacts(slug) : store.buildFacts(slug)
1700
+ if (!includeDeferred)
1701
+ for (const record of records) {
1702
+ if (
1703
+ (digests.get(record.slug)?.compatibility?.decisiveFacts ?? 0) > 0 &&
1704
+ (await deferMixedVersion(store, record.slug, undefined, readFacts))
1705
+ )
1706
+ blocked.add(record.slug)
1707
+ }
1366
1708
  return records
1367
1709
  .filter((record) => includeDeferred || !blocked.has(record.slug))
1368
1710
  .map((record) => {
@@ -1534,6 +1876,296 @@ export class Dispatcher {
1534
1876
  }
1535
1877
  }
1536
1878
 
1879
+ /** Admit pending operator start requests of the given tiers through
1880
+ * `dispatch()`'s gates and settle each one that reaches a decision. Zero
1881
+ * reads while none of those tiers is pending; otherwise one targeted `get`
1882
+ * per request (at most START_REQUESTS_PER_TICK) over the view-cached build
1883
+ * digests. Waiting conditions (pause, no slot in the request's tier,
1884
+ * creation holds, an in-flight preparation, a failed dependency read, a
1885
+ * source error, the tick budget) leave the request pending. */
1886
+ private async honorStartRequests(
1887
+ report: TickReport,
1888
+ launched: Set<string>,
1889
+ autoMergeUser: string | undefined,
1890
+ paused: boolean,
1891
+ opts: TickOpts,
1892
+ tiers: readonly TicketStartPriority[],
1893
+ ): Promise<void> {
1894
+ const starts = this.store.repositoryFacts().ticketStarts
1895
+ const rank = (request: PendingTicketStart) => START_TIER_ORDER.indexOf(request.priority)
1896
+ const pending = Object.values(starts.pending)
1897
+ .filter((request) => tiers.includes(request.priority))
1898
+ .sort((a, b) => rank(a) - rank(b) || a.seq - b.seq)
1899
+ .slice(0, START_REQUESTS_PER_TICK)
1900
+ if (pending.length === 0 || paused) return
1901
+ const { tickets, config } = this.deps
1902
+ const migrations = this.store.repositoryFacts().ticketMigrations
1903
+ // Deferred mixed-version builds are still active: include them, so a
1904
+ // build the tick cannot decide is never mistaken for a free ticket.
1905
+ const active = (await this.repoBuildDigests(true)).filter(
1906
+ ({ digest }) => digest.terminal === undefined,
1907
+ )
1908
+ const refs = active.flatMap(({ record }) => {
1909
+ if (!record.ticket) return []
1910
+ try {
1911
+ const ref = resolveTicketRef(migrations, record.ticket, tickets.name, record.slug)
1912
+ return [{ slug: record.slug, createdAt: record.createdAt, ref }]
1913
+ } catch (error) {
1914
+ // The same policy as activeTicketIdentities: a recorded cutover that
1915
+ // omits a live claim must block admission.
1916
+ if (migrations.migrations.some((m) => m.from === record.ticket!.source && m.from !== m.to))
1917
+ throw error
1918
+ return [{ slug: record.slug, createdAt: record.createdAt, ref: record.ticket }]
1919
+ }
1920
+ })
1921
+ const identified =
1922
+ tickets.name !== 'hosted' || (await this.ensureActiveIdentities(refs, active))
1923
+ if (identified === 'rate-limited') return
1924
+ const identities = this.store.repositoryFacts().ticketStarts.identities
1925
+ const lifecycle = ticketLifecycle(config.tickets)
1926
+ const candidates: { request: PendingTicketStart; ticket: Ticket }[] = []
1927
+ for (const request of pending) {
1928
+ if (this.outOfBudget(opts)) return
1929
+ let ref: TicketRef | undefined
1930
+ try {
1931
+ ref = resolveTicketRef(migrations, request.ticket, tickets.name)
1932
+ } catch {
1933
+ ref = undefined
1934
+ }
1935
+ if (ref === undefined || ref.source !== tickets.name) {
1936
+ await this.settleStartRequest(request, 'missing', {
1937
+ detail: `ticket ${request.ticket.source}:${request.ticket.id} is not in the configured ${tickets.name} ticket source`,
1938
+ })
1939
+ continue
1940
+ }
1941
+ let ticket: Ticket | null
1942
+ try {
1943
+ ticket = await tickets.get(ref.id)
1944
+ } catch (error) {
1945
+ if (error instanceof TicketSourceRateLimitError) {
1946
+ await this.sourceFailure(error, 'dependency-check')
1947
+ return
1948
+ }
1949
+ continue
1950
+ }
1951
+ if (ticket === null) {
1952
+ await this.settleStartRequest(request, 'missing', {
1953
+ detail: `no ticket ${ref.id} in the configured ${tickets.name} ticket source`,
1954
+ })
1955
+ continue
1956
+ }
1957
+ const build = this.targetedActiveBuild(ticket.ref, refs, identities)
1958
+ if (build !== undefined) {
1959
+ // A build created after the request is this request's own claim
1960
+ // whose settlement was lost, or intake's claim in the same window.
1961
+ await this.settleStartRequest(
1962
+ request,
1963
+ Date.parse(build.createdAt) > Date.parse(request.ts) ? 'started' : 'already-building',
1964
+ { slug: build.slug },
1965
+ )
1966
+ continue
1967
+ }
1968
+ // Fail closed: a hosted build whose identity is not yet projected might
1969
+ // embody this ticket under a legacy alias.
1970
+ if (identified !== true) continue
1971
+ // Ingesters propose, humans dispatch: only the ready state starts.
1972
+ if (!holdsState(ticket.state, config.tickets.readyState)) {
1973
+ const terminal =
1974
+ ticket.resolved ||
1975
+ holdsState(ticket.state, this.doneState) ||
1976
+ holdsState(ticket.state, lifecycle.rejected)
1977
+ await this.settleStartRequest(request, terminal ? 'terminal' : 'not-ready', {
1978
+ detail: `ticket ${ticket.ref.id} is in ${ticket.state ?? 'an unreported state'}, not ${config.tickets.readyState}`,
1979
+ })
1980
+ continue
1981
+ }
1982
+ if (this.preparing(ticket.ref.source, ticket.ref.id)) continue
1983
+ candidates.push({ request, ticket })
1984
+ }
1985
+ if (candidates.length === 0 || this.outOfBudget(opts)) return
1986
+ // Capacity is measured from the facts this tick's janitor, recovery and
1987
+ // lease sweep already read (`servedBuildFacts`): a build is read again
1988
+ // only when the tick skipped it or wrote to it since, so neither a wait
1989
+ // nor an admission reads the fleet, on a fresh process or a warm one.
1990
+ // Each tier's budget leaves the slots reserved ahead of it (SPEC §12).
1991
+ // With no free slot in its tier, only a node, or a blocked target not yet
1992
+ // checked, needs the pass.
1993
+ const now = this.deps.clock()
1994
+ const measured = await this.capacityBuilds(launched, true)
1995
+ const projection = dispatchCapacity(measured, config.capacity, now, undefined, {
1996
+ urgentClaims: this.urgentClaims(),
1997
+ startRequests: this.startClaims(),
1998
+ })
1999
+ const adjust = { settled: this.parkedSettled, denied: this.slotWaiters }
2000
+ const budgets = {
2001
+ manual: startCapacity(projection, adjust, 'manual'),
2002
+ urgent: startCapacity(projection, adjust, 'urgent'),
2003
+ normal: startCapacity(projection, adjust, 'normal'),
2004
+ }
2005
+ const open = new Set(Object.values(starts.pending).map(({ seq }) => seq))
2006
+ for (const seq of this.startBlockersChecked)
2007
+ if (!open.has(seq)) this.startBlockersChecked.delete(seq)
2008
+ const free = (request: PendingTicketStart) => budgets[request.priority] > 0
2009
+ const passing = candidates.filter(
2010
+ ({ request, ticket }) =>
2011
+ free(request) ||
2012
+ ticket.kind === 'node' ||
2013
+ (ticket.target !== undefined &&
2014
+ !!ticket.blockedBy?.length &&
2015
+ !this.startBlockersChecked.has(request.seq)),
2016
+ )
2017
+ if (passing.length === 0) return
2018
+ for (const { request, ticket } of passing)
2019
+ if (!free(request) && ticket.kind !== 'node') this.startBlockersChecked.add(request.seq)
2020
+ const key = (ref: TicketRef) => `${ref.source}:${ref.id}`
2021
+ const targeted: TargetedDispatch = {
2022
+ tickets: passing.map(({ ticket }) => ticket),
2023
+ activeIds: new Set(refs.map(({ ref }) => key(ref))),
2024
+ requests: new Map(passing.map(({ request, ticket }) => [ticket.ref.id, request])),
2025
+ outcomes: new Map(),
2026
+ measured,
2027
+ budgets,
2028
+ }
2029
+ const scratch = emptyTickReport()
2030
+ this.startPass = true
2031
+ try {
2032
+ await this.dispatch(scratch, launched, autoMergeUser, paused, opts, undefined, targeted)
2033
+ } finally {
2034
+ this.startPass = false
2035
+ for (const counter of [
2036
+ 'dispatched',
2037
+ 'authored',
2038
+ 'bounced',
2039
+ 'claimRaces',
2040
+ 'dispatchFailed',
2041
+ 'provisioning',
2042
+ 'provisioningDeferred',
2043
+ 'dependencyCheckFailed',
2044
+ ] as const)
2045
+ report[counter] += scratch[counter]
2046
+ for (const { request, ticket } of passing) {
2047
+ const settled = targeted.outcomes.get(ticket.ref.id)
2048
+ if (settled === undefined) continue
2049
+ const { outcome, ...extra } = settled
2050
+ await this.settleStartRequest(request, outcome, extra)
2051
+ }
2052
+ }
2053
+ }
2054
+
2055
+ /** The active build embodying `requested`, matched with no source reads:
2056
+ * by the build's normalized recorded id, or, for hosted, by its projected
2057
+ * canonical identity. Hosted ids compare case-insensitively. */
2058
+ private targetedActiveBuild(
2059
+ requested: TicketRef,
2060
+ refs: readonly ActiveTicketRef[],
2061
+ identities: TicketStarts['identities'],
2062
+ ): ActiveTicketRef | undefined {
2063
+ const hosted = requested.source === 'hosted'
2064
+ const same = (a: string, b: string) => (hosted ? a.toLowerCase() === b.toLowerCase() : a === b)
2065
+ return refs.find(({ slug, ref }) => {
2066
+ if (ref.source !== requested.source) return false
2067
+ if (same(ref.id, requested.id)) return true
2068
+ const identity = identities[slug]
2069
+ return hosted && identity?.recorded === ref.id && same(identity.canonical, requested.id)
2070
+ })
2071
+ }
2072
+
2073
+ /** Project the canonical identity of every active hosted build once in its
2074
+ * life, at most IDENTITY_RESOLUTIONS_PER_TICK per tick, and release builds
2075
+ * no longer active in the same append. True once every active hosted build
2076
+ * has a current entry; false while resolution is incomplete or failed, and
2077
+ * `rate-limited` after a source rate limit. Zero reads and writes once
2078
+ * complete. */
2079
+ private async ensureActiveIdentities(
2080
+ refs: readonly ActiveTicketRef[],
2081
+ active: readonly { record: BuildRecord }[],
2082
+ ): Promise<boolean | 'rate-limited'> {
2083
+ const identities = this.store.repositoryFacts().ticketStarts.identities
2084
+ const missing = refs.filter(
2085
+ ({ slug, ref }) => ref.source === 'hosted' && identities[slug]?.recorded !== ref.id,
2086
+ )
2087
+ const live = new Set(active.map(({ record }) => record.slug))
2088
+ const released = Object.keys(identities)
2089
+ .filter((slug) => !live.has(slug))
2090
+ .slice(0, IDENTITY_RELEASES_PER_APPEND)
2091
+ if (missing.length === 0 && released.length === 0) return true
2092
+ const resolved: { build: string; recorded: string; canonical: string }[] = []
2093
+ let complete = missing.length <= IDENTITY_RESOLUTIONS_PER_TICK
2094
+ for (const { slug, ref } of missing.slice(0, IDENTITY_RESOLUTIONS_PER_TICK)) {
2095
+ try {
2096
+ const ticket = await this.deps.tickets.get(ref.id)
2097
+ resolved.push({
2098
+ build: slug,
2099
+ recorded: ref.id,
2100
+ canonical: ticket?.ref.source === 'hosted' ? ticket.ref.id : ref.id,
2101
+ })
2102
+ } catch (error) {
2103
+ if (error instanceof TicketSourceRateLimitError) {
2104
+ await this.sourceFailure(error, 'dependency-check')
2105
+ return 'rate-limited'
2106
+ }
2107
+ complete = false
2108
+ }
2109
+ }
2110
+ if (resolved.length === 0 && released.length === 0) return false
2111
+ if (this.deps.holdsRepoAuthority?.() === false) return false
2112
+ try {
2113
+ await this.store.ensureRepo(this.deps.repo)
2114
+ await this.store.appendRepo(this.deps.repo, {
2115
+ actor: DISPATCHER,
2116
+ type: 'ticket.identity-recorded',
2117
+ payload: { identities: resolved, ...(released.length > 0 ? { released } : {}) },
2118
+ })
2119
+ await this.store.refreshJournal()
2120
+ } catch (error) {
2121
+ rethrowAuthorityLapse(error)
2122
+ return false
2123
+ }
2124
+ return complete
2125
+ }
2126
+
2127
+ /** Whether the request a targeted ticket answers is still pending at the
2128
+ * priority the pass admitted it under, read after one journal refresh. A
2129
+ * re-request at another priority keeps its `seq` but changes the tier and
2130
+ * build priority, so the claim defers to the next pass, which admits it
2131
+ * from current inputs. */
2132
+ private async startStillPending(targeted: TargetedDispatch, ticket: Ticket): Promise<boolean> {
2133
+ const request = targeted.requests.get(ticket.ref.id)
2134
+ if (request === undefined) return false
2135
+ await this.store.refreshJournal()
2136
+ const current =
2137
+ this.store.repositoryFacts().ticketStarts.pending[ticketStartKey(request.ticket)]
2138
+ return current?.seq === request.seq && current.priority === request.priority
2139
+ }
2140
+
2141
+ /** Settle one start request once. The journal is refreshed first, so a
2142
+ * settlement whose acknowledgement was lost is never appended twice. */
2143
+ private async settleStartRequest(
2144
+ request: PendingTicketStart,
2145
+ outcome: TicketStartOutcome,
2146
+ extra: { slug?: string; detail?: string } = {},
2147
+ ): Promise<void> {
2148
+ if (this.deps.holdsRepoAuthority?.() === false) return
2149
+ await this.store.ensureRepo(this.deps.repo)
2150
+ await this.store.refreshJournal()
2151
+ const current =
2152
+ this.store.repositoryFacts().ticketStarts.pending[ticketStartKey(request.ticket)]
2153
+ if (current?.seq !== request.seq) return
2154
+ const detail = extra.detail?.trim().slice(0, 2000)
2155
+ await this.store.appendRepo(this.deps.repo, {
2156
+ actor: DISPATCHER,
2157
+ type: 'ticket.start-settled',
2158
+ payload: {
2159
+ request: request.seq,
2160
+ ticket: request.ticket,
2161
+ priority: current.priority,
2162
+ outcome,
2163
+ ...(extra.slug !== undefined ? { slug: extra.slug } : {}),
2164
+ ...(detail ? { detail } : {}),
2165
+ },
2166
+ })
2167
+ }
2168
+
1537
2169
  /** Report a preparation attempt's committed hand-back once. */
1538
2170
  private async reportPreparationHandback(
1539
2171
  attempt: TicketPreparation,
@@ -1695,7 +2327,9 @@ export class Dispatcher {
1695
2327
  report[key] = [...previous[key]]
1696
2328
  }
1697
2329
 
1698
- private async scanCheckpoint(mode: 'admission' | 'observation') {
2330
+ /** `force` makes the scan due now, skipping the interval and the journal
2331
+ * deferral: a deferred normal admission waits on this tick's urgent claims. */
2332
+ private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
1699
2333
  const digest = (await this.repoBuildDigests())
1700
2334
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
1701
2335
  .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq] as const)
@@ -1720,6 +2354,7 @@ export class Dispatcher {
1720
2354
  readinessFingerprint,
1721
2355
  criteriaFingerprint,
1722
2356
  }
2357
+ if (force) return { ...checkpoint, allowClockRollback: false, due: true }
1723
2358
  // The journal measurement alone proves deferral, so the cadence row is not read.
1724
2359
  if (ticketScanDeferredByJournal(input))
1725
2360
  return { ...checkpoint, allowClockRollback: false, due: false }
@@ -1730,6 +2365,7 @@ export class Dispatcher {
1730
2365
  private async completeScan(
1731
2366
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
1732
2367
  report: TickReport,
2368
+ urgentWaiting = 0,
1733
2369
  ): Promise<void> {
1734
2370
  const payload = {
1735
2371
  startedAt: checkpoint.startedAt,
@@ -1743,10 +2379,12 @@ export class Dispatcher {
1743
2379
  dependencyDiagnostics: report.dependencyDiagnostics.slice(0, 1000),
1744
2380
  creationWithheld: report.creationWithheld,
1745
2381
  creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
2382
+ ...(urgentWaiting > 0 ? { urgentWaiting } : {}),
1746
2383
  }
1747
2384
  const previous = this.latestScan()
1748
2385
  const unchanged =
1749
2386
  previous !== undefined &&
2387
+ previous.urgentWaiting === payload.urgentWaiting &&
1750
2388
  Object.keys(payload)
1751
2389
  .filter((key) => key !== 'startedAt')
1752
2390
  .every(
@@ -1850,14 +2488,26 @@ export class Dispatcher {
1850
2488
  if (await this.forgeCoolingDown()) return 'already-active'
1851
2489
  if (await deferMixedVersion(this.store, slug)) return 'already-active'
1852
2490
  const launchState = (await this.store.buildFacts(slug)).state
1853
- if (
1854
- launchState.kind === 'node' &&
1855
- !launchState.nodeRestack?.conflict &&
1856
- !integrationCurrent(launchState)
1857
- )
1858
- return 'already-active'
2491
+ // A landed node has nothing left to run; the janitor settles it.
2492
+ if (nodeLanded(launchState)) return 'already-active'
2493
+ if (launchState.kind === 'node' && !launchState.nodeRestack?.conflict) {
2494
+ // The last check before a proposer starts: the open request must still
2495
+ // fit current state, unless its session was already admitted.
2496
+ if (
2497
+ proposeRunDue(launchState.optimization) &&
2498
+ (proposeStarted(launchState) || !nodeMeasurementDue(launchState))
2499
+ ) {
2500
+ if (
2501
+ !proposeStarted(launchState) &&
2502
+ !proposeAdmissible(launchState.optimization, this.deps.clock())
2503
+ )
2504
+ return 'already-active'
2505
+ } else if (!integrationCurrent(launchState) && !nodeMeasurementDue(launchState))
2506
+ return 'already-active'
2507
+ }
1859
2508
  if (launched.has(slug)) return 'already-active'
1860
- if (launchState.kind !== 'node' && !(await this.leafAdmission(slug))) return 'already-active'
2509
+ if (launchState.kind !== 'node' && (await this.leafAdmission(slug)) !== 'admit')
2510
+ return 'already-active'
1861
2511
  launched.add(slug)
1862
2512
  const facts = (await readBuildFacts(this.store, slug)).value
1863
2513
  // Callers reap and reprovision a flagged workspace; an agent never starts
@@ -2077,17 +2727,21 @@ export class Dispatcher {
2077
2727
  * provider no longer matches the wired provider is likewise dispositioned
2078
2728
  * once idle: its trail is closed with an unconfirmed release fact (AUT-377)
2079
2729
  * — never a stop, since this dispatcher cannot reach a provider it is not
2080
- * wired to — and if the old provider returns, the next operator ensure()
2730
+ * wired to — and if the old provider returns, the next sandbox.open
2081
2731
  * re-provisions and re-brackets the environment, so the disposition is
2082
- * reachable again. The stage is a no-op unless `[orchestrator]` is
2083
- * enabled and the wired provider hosts the capability; `unsupported`
2732
+ * reachable again. The stage is a no-op unless `[orchestrator]` resolves
2733
+ * enabled for this dispatcher's host (`orchestratorEnabled` with
2734
+ * `orchestratorHost`) and the wired provider hosts the capability; `unsupported`
2084
2735
  * providers (local worktrees) are skipped silently. */
2085
2736
  private async settleOrchestratorSandboxes(
2086
2737
  report: TickReport,
2087
2738
  opts: TickOpts = {},
2088
2739
  ): Promise<void> {
2089
2740
  const config = this.deps.config
2090
- if (config.orchestrator?.enabled !== true) return
2741
+ // Test configs may omit the table entirely; production configs always
2742
+ // carry it after parsing.
2743
+ if (config.orchestrator === undefined) return
2744
+ if (!orchestratorEnabled(config, this.deps.orchestratorHost ?? 'local')) return
2091
2745
  const capability = this.deps.workspaces.orchestratorSandbox
2092
2746
  if (capability === undefined) return
2093
2747
  const providerName = this.deps.workspaces.name
@@ -2129,7 +2783,7 @@ export class Dispatcher {
2129
2783
  // every tick forever. Close the trail with an unconfirmed release —
2130
2784
  // never a stop: nothing was stopped through a provider this
2131
2785
  // dispatcher no longer owns. If the provider returns, the next
2132
- // operator ensure() re-provisions and re-brackets the environment.
2786
+ // sandbox.open re-provisions and re-brackets the environment.
2133
2787
  await this.store.appendRepo(this.deps.repo, {
2134
2788
  actor: DISPATCHER,
2135
2789
  type: 'orchestrator.sandbox.released',
@@ -2227,7 +2881,7 @@ export class Dispatcher {
2227
2881
  autoMergeDefaultSeq?: number
2228
2882
  assets?: PinnedAsset[]
2229
2883
  },
2230
- ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait'> {
2884
+ ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait' | 'budget-wait'> {
2231
2885
  const slug = record.slug
2232
2886
  if (!this.accountsAvailable()) return 'in-flight'
2233
2887
  if (this.continuations.has(slug)) return 'in-flight'
@@ -2248,11 +2902,25 @@ export class Dispatcher {
2248
2902
  }
2249
2903
  // Expired lease, failed attempt, or an old lease-less marker: adopt.
2250
2904
  }
2905
+ // A bounded invocation does not start provisioning it has no realistic
2906
+ // time left to finish; a later invocation starts it with a full budget.
2907
+ // Pure clock arithmetic: nothing is read or written.
2908
+ const estimate = this.deps.workspaces.provisionEstimateMs
2909
+ if (
2910
+ estimate !== undefined &&
2911
+ this.tickDeadlineAt !== undefined &&
2912
+ this.tickDeadlineAt - this.deps.clock().getTime() < estimate
2913
+ )
2914
+ return 'budget-wait'
2251
2915
  // A finished leaf waits for a slot before its continuation reserves one.
2252
2916
  // Nothing is written: the wait costs no attempt and raises no attention.
2253
- if (tail === 'launch' && !(await this.leafAdmission(slug))) return 'slot-wait'
2917
+ if (tail === 'launch' && (await this.leafAdmission(slug)) !== 'admit') return 'slot-wait'
2254
2918
  const branch = record.branch ?? `ab/${slug}`
2255
2919
  const generation = events.workspaceGenerations
2920
+ // The latest attempt at this same generation was cut off by a recorded
2921
+ // dispatcher teardown and its lease is gone (the liveness gate above):
2922
+ // the provider may verify and finish it in place, uncharged.
2923
+ const adoptAbandoned = marker?.abandoned === 'teardown' && marker.generation === generation
2256
2924
  if (this.deps.holdsRepoAuthority?.() === false) return 'in-flight'
2257
2925
  await this.store.append(slug, {
2258
2926
  actor: DISPATCHER,
@@ -2273,6 +2941,7 @@ export class Dispatcher {
2273
2941
  generation,
2274
2942
  seed,
2275
2943
  tail,
2944
+ adoptAbandoned,
2276
2945
  }).catch(() => {
2277
2946
  // Detached work must never reject into the dispatcher process. Failure
2278
2947
  // recording can itself fail on a store outage; durable boundaries and
@@ -2304,6 +2973,7 @@ export class Dispatcher {
2304
2973
  }
2305
2974
  | undefined
2306
2975
  tail: 'dispatch' | 'launch'
2976
+ adoptAbandoned: boolean
2307
2977
  },
2308
2978
  ): Promise<void> {
2309
2979
  const store = this.store
@@ -2340,23 +3010,34 @@ export class Dispatcher {
2340
3010
  return
2341
3011
  }
2342
3012
  const priorGenerations = events.workspaceGenerations
2343
- const handle = await this.provisionWorkspace(slug, {
2344
- // Local providers provision FROM the physical checkout; remote
2345
- // providers ignore the value (their host seams are injected).
2346
- repo: this.deps.checkout ?? this.deps.repo,
2347
- baseBranch:
2348
- events.state.kind === 'node' && events.state.integration?.cycle
2349
- ? input.branch
2350
- : baseBranchOf(events, config),
2351
- branch: input.branch,
2352
- ...(priorGenerations > 0 || input.generation > 0
2353
- ? {
2354
- publication: await this.confirmedWorkspacePublication(events, slug),
2355
- revision: events.state.integration?.cycle?.head ?? this.recoveryCheckpoint(events),
2356
- generation: Math.max(priorGenerations, input.generation),
2357
- }
2358
- : {}),
2359
- })
3013
+ const handle = await this.provisionWorkspace(
3014
+ slug,
3015
+ {
3016
+ // Local providers provision FROM the physical checkout; remote
3017
+ // providers ignore the value (their host seams are injected).
3018
+ repo: this.deps.checkout ?? this.deps.repo,
3019
+ baseBranch:
3020
+ events.state.kind === 'node' &&
3021
+ (events.state.integration?.cycle || proposeRunDue(events.state.optimization))
3022
+ ? input.branch
3023
+ : baseBranchOf(events, config),
3024
+ branch: input.branch,
3025
+ ...(priorGenerations > 0 || input.generation > 0
3026
+ ? {
3027
+ publication: await this.confirmedWorkspacePublication(events, slug),
3028
+ revision:
3029
+ (proposeRunDue(events.state.optimization)
3030
+ ? events.state.optimization?.proposal?.head
3031
+ : undefined) ??
3032
+ events.state.integration?.cycle?.head ??
3033
+ this.recoveryCheckpoint(events),
3034
+ generation: Math.max(priorGenerations, input.generation),
3035
+ }
3036
+ : {}),
3037
+ ...(input.adoptAbandoned ? { adoptAbandoned: true } : {}),
3038
+ },
3039
+ entry.controller.signal,
3040
+ )
2360
3041
  // The provisioned fact is true and welcome even when a teardown signal
2361
3042
  // landed mid-call; the token check below still prevents a superseded
2362
3043
  // supervisor from launching.
@@ -2399,6 +3080,10 @@ export class Dispatcher {
2399
3080
  // A lapsed repository lease started nothing: no failure fact. The
2400
3081
  // finally releases the execution lease; the successor adopts the marker.
2401
3082
  if (isRepositoryAuthorityLapse(error)) return
3083
+ // Teardown aborted this continuation and already recorded the
3084
+ // abandonment; a late provider failure after it is not a new fact, and
3085
+ // recording one would charge an attempt and spoil the adoptable marker.
3086
+ if (entry.controller.signal.aborted) return
2402
3087
  // Dispatch boundaries own their failure facts and exhaustion repair.
2403
3088
  // A failed tail read/write leaves durable unfinished work for the next
2404
3089
  // tick; it is not another provider workspace failure. Replacement
@@ -2406,7 +3091,12 @@ export class Dispatcher {
2406
3091
  if (await this.holdForMissingAccounts(error)) return
2407
3092
  if (boundary === 'read' || boundary === 'dispatch') return
2408
3093
  const events = (await readBuildFacts(store, slug)).value
2409
- if (workspaces.recovery !== undefined) {
3094
+ // Finishing a teardown-abandoned attempt that turns out unfinishable is
3095
+ // uncharged: a teardown abandonment never counts toward
3096
+ // `maxInfrastructureAttempts`. The cleanup-required fact still lets the
3097
+ // sweep reap and replace it.
3098
+ const uncharged = input.adoptAbandoned && error instanceof WorkspaceCleanupRequired
3099
+ if (workspaces.recovery !== undefined && !uncharged) {
2410
3100
  const open = openWorkspace(events)
2411
3101
  const latestRef = events.latestRelease
2412
3102
  await this.recordInfrastructureFailure(slug, events, {
@@ -2483,6 +3173,7 @@ export class Dispatcher {
2483
3173
  attempt,
2484
3174
  error:
2485
3175
  'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3176
+ abandoned: 'teardown',
2486
3177
  },
2487
3178
  })
2488
3179
  }
@@ -2509,9 +3200,13 @@ export class Dispatcher {
2509
3200
  // Only this repo's builds that still have work (§12: another repo's
2510
3201
  // builds are another dispatcher's duty; settled terminal builds cost no
2511
3202
  // event reads).
2512
- const entries = (await this.repoBuildDigests()).filter(
3203
+ // Unfiltered, so optimization stop enforcement sees terminal attempt builds.
3204
+ const builds = await this.repoBuildDigests()
3205
+ const entries = builds.filter(
2513
3206
  ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
2514
3207
  )
3208
+ this.janitorEntries = entries
3209
+ this.nodeChildren = undefined
2515
3210
  // Receipt reporting requires no forge call, capacity or workspace. Recover
2516
3211
  // every episode before the transport-budget and janitor-backoff gates.
2517
3212
  for (const { record, digest } of entries) {
@@ -2544,18 +3239,79 @@ export class Dispatcher {
2544
3239
  const initialFacts = await this.store.buildFacts(record.slug)
2545
3240
  let { state, workspace, log } = initialFacts
2546
3241
  previous = state.janitor
3242
+ // A node's janitor acknowledges every pending control itself, a
3243
+ // cancelling resume included; a leaf's resume that only cancelled a
3244
+ // never-acknowledged pause holds nothing back and waits out backoff.
3245
+ const commands = state.kind === 'node' ? state.pendingCommands : actionableCommands(state)
2547
3246
  const controlDue =
2548
- state.pendingCommands.length > 0 ||
3247
+ commands.length > 0 ||
2549
3248
  state.discardRequest !== undefined ||
3249
+ (state.declined !== undefined && state.status !== 'done') ||
2550
3250
  (state.pr &&
2551
3251
  state.landing?.command &&
2552
3252
  state.landing.command.seq !== state.landing.acknowledgedSeq)
3253
+ // Every tick, independent of janitor backoff and idle node polling: an
3254
+ // hours budget must fire on a node with no other activity.
3255
+ if (state.optimization !== undefined && !mixedVersionDeferred(state)) {
3256
+ const deps = {
3257
+ store: this.store,
3258
+ clock: this.deps.clock,
3259
+ migrations: this.store.repositoryFacts().ticketMigrations,
3260
+ ticketSource: this.deps.tickets.name,
3261
+ }
3262
+ // Merges no settlement or marker recorded first, so a stopped
3263
+ // node's enforcer and completion see them as they are.
3264
+ if (await reconcileMergedAttempts(deps, record, state, builds))
3265
+ state = (await this.store.buildFacts(record.slug)).state
3266
+ // The active-hours clock: attempt runs since the last pass, and a
3267
+ // stopped node's one settlement, ahead of every early return.
3268
+ try {
3269
+ if (await recordOptimizationActivity(deps, record, state, builds))
3270
+ state = (await this.store.buildFacts(record.slug)).state
3271
+ } catch (error) {
3272
+ if (
3273
+ !(error instanceof BuildDigestCapabilityError) &&
3274
+ !(error instanceof ExecutionFactsMissingError)
3275
+ )
3276
+ throw error
3277
+ report.janitorDiagnostics.push(
3278
+ `build ${record.slug}: optimization activity not recorded — ${error.message}`,
3279
+ )
3280
+ }
3281
+ if (await enforceOptimizationStop(deps, record, state, builds))
3282
+ state = (await this.store.buildFacts(record.slug)).state
3283
+ }
2553
3284
  // Read the clock only inside an episode, as before episodes could escalate.
2554
3285
  if (!controlDue && previous && !janitorDue(previous, this.deps.clock())) return
2555
3286
  if (mixedVersionDeferred(state)) {
2556
3287
  await deferMixedVersion(this.store, record.slug)
2557
3288
  return
2558
3289
  }
3290
+ // Independent of idle polling: a pending re-acceptance is read from
3291
+ // reduced state, so it survives a crash after `spec.revised`.
3292
+ if (
3293
+ objectiveAcceptancePending(state) &&
3294
+ (await this.acceptRevisedObjective(record, state, report))
3295
+ )
3296
+ state = (await this.store.buildFacts(record.slug)).state
3297
+ // An optimization node's pending rejected-role moves are a
3298
+ // post-terminal duty, like attachment reclaim: they run for open,
3299
+ // aborted and completed nodes alike, ahead of every early return.
3300
+ // Control commands go first, so a tracker refusing the move never
3301
+ // blocks an abort.
3302
+ if (state.kind === 'node' && state.optimization?.rejections.length && !controlDue) {
3303
+ operation = 'attempt rejection'
3304
+ attempted = true
3305
+ if (await this.sweepAttemptRejections(record, state))
3306
+ state = (await this.store.buildFacts(record.slug)).state
3307
+ // A completed node polled only for this duty has nothing else due.
3308
+ if (
3309
+ state.status === 'done' &&
3310
+ digest.reclaimPending !== true &&
3311
+ digest.integrationAuditPending !== true
3312
+ )
3313
+ return
3314
+ }
2559
3315
  const executionLeaseLive = this.hasLiveExecutionLease(record)
2560
3316
  attempted = !executionLeaseLive
2561
3317
  // Raw history, read at most once and only by a branch that acts on it:
@@ -2662,6 +3418,7 @@ export class Dispatcher {
2662
3418
  {
2663
3419
  history,
2664
3420
  workspace,
3421
+ executionOpen: initialFacts.open !== null,
2665
3422
  observed: (pr) => {
2666
3423
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2667
3424
  },
@@ -2757,6 +3514,7 @@ export class Dispatcher {
2757
3514
  {
2758
3515
  history,
2759
3516
  workspace,
3517
+ executionOpen: initialFacts.open !== null,
2760
3518
  observed: (pr) => {
2761
3519
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2762
3520
  },
@@ -2858,6 +3616,11 @@ export class Dispatcher {
2858
3616
  await this.cleanupAborted(record, await history(), report)
2859
3617
  return
2860
3618
  }
3619
+ if (!executionLeaseLive && state.declined !== undefined) {
3620
+ operation = 'decline settlement'
3621
+ await this.settleDeclinedAttempt(record, await history())
3622
+ return
3623
+ }
2861
3624
  operation = 'target observation'
2862
3625
  if (state.kind !== 'node' && state.status !== 'aborted')
2863
3626
  await this.observeTicketTarget(record, state, report)
@@ -2939,6 +3702,7 @@ export class Dispatcher {
2939
3702
  {
2940
3703
  history,
2941
3704
  workspace,
3705
+ executionOpen: initialFacts.open !== null,
2942
3706
  observed: (pr) => {
2943
3707
  incompleteObservation ||= pr.state === 'open' && pr.mergeable === null
2944
3708
  },
@@ -3309,18 +4073,33 @@ export class Dispatcher {
3309
4073
  /** Deferral withholds decisions, but cannot free an existing capacity reservation.
3310
4074
  * A leaf's runner reservation is this process's continuation or a launch
3311
4075
  * this tick; another process's continuation holds a heartbeat lease. */
3312
- private async capacityBuilds(launched?: ReadonlySet<string>): Promise<CapacityBuild[]> {
4076
+ private async capacityBuilds(
4077
+ launched?: ReadonlySet<string>,
4078
+ /** Serve the facts this tick already read (`servedBuildFacts`). */
4079
+ served = false,
4080
+ ): Promise<CapacityBuild[]> {
3313
4081
  const builds: CapacityBuild[] = []
3314
4082
  for (const { record, digest } of await this.repoBuildDigests(true)) {
3315
4083
  if (digest.terminal) continue
3316
- const facts = await this.store.buildFacts(record.slug)
4084
+ // A leaf with a runner provisioning holds its slot and requests none
4085
+ // whatever its state, so any read this tick serves it, launch or not.
4086
+ const allocatedLeaf =
4087
+ digest.kind !== 'node' &&
4088
+ (this.continuations.has(record.slug) || !!launched?.has(record.slug))
4089
+ const facts = served
4090
+ ? ((allocatedLeaf ? this.store.retainedBuildFacts(record.slug) : undefined) ??
4091
+ (await this.store.servedBuildFacts(record.slug)))
4092
+ : await this.store.buildFacts(record.slug)
3317
4093
  builds.push({
3318
4094
  record,
3319
4095
  state: facts.state,
3320
4096
  workspace: facts.workspace !== null,
3321
4097
  provisioning:
3322
4098
  digest.kind === 'node'
3323
- ? (await readBuildFacts(this.store, record.slug)).value.provisionMarker !== undefined
4099
+ ? (served
4100
+ ? facts.provisionMarker
4101
+ : (await readBuildFacts(this.store, record.slug)).value.provisionMarker) !==
4102
+ undefined
3324
4103
  : this.continuations.has(record.slug) || !!launched?.has(record.slug),
3325
4104
  restackDue: landingRestackDue(facts.state, facts.log),
3326
4105
  })
@@ -3328,12 +4107,68 @@ export class Dispatcher {
3328
4107
  return builds
3329
4108
  }
3330
4109
 
4110
+ /** Whether ticket claims can run this tick: the one predicate both
4111
+ * `dispatch` and the urgent admission boundary use. Without the source's
4112
+ * priority capability every claim is normal, so nothing ever defers. */
4113
+ private claimsPossible(opts: Pick<TickOpts, 'acceptNewWork'>, paused: boolean): boolean {
4114
+ return (
4115
+ !!this.deps.tickets.priority &&
4116
+ opts.acceptNewWork !== false &&
4117
+ !paused &&
4118
+ this.claimGateOpen()
4119
+ )
4120
+ }
4121
+
4122
+ /** Accounts are present and the forge is not cooling down: `dispatch`'s own
4123
+ * early returns. */
4124
+ private claimGateOpen(): boolean {
4125
+ if (!this.accountsAvailable()) return false
4126
+ const health = this.store.repositoryFacts().forgeHealth
4127
+ return !(health && Date.parse(health.resetAt) > this.deps.clock().getTime())
4128
+ }
4129
+
4130
+ /** Urgent ticket claims the latest admission scan found waiting for a slot.
4131
+ * In memory: the journal view is refreshed each tick. */
4132
+ private urgentClaims(): number {
4133
+ return this.tickAcceptsNewWork ? urgentClaimDemand(this.store.repositoryFacts()) : 0
4134
+ }
4135
+
4136
+ /** Pending operator start requests by tier; nothing while no claim can
4137
+ * run. In memory, like `urgentClaims`. */
4138
+ private startClaims(): Partial<Record<TicketStartPriority, number>> {
4139
+ return this.claimGateOpen() ? startClaimDemand(this.store.repositoryFacts()) : {}
4140
+ }
4141
+
4142
+ /** A normal waiter must defer: claims can run and this tick's dispatch has
4143
+ * not yet evaluated urgent claims. */
4144
+ private urgentBoundaryOpen(): boolean {
4145
+ return (
4146
+ this.admissionBoundary &&
4147
+ this.claimsPossible({ acceptNewWork: this.tickAcceptsNewWork }, this.tickPaused)
4148
+ )
4149
+ }
4150
+
4151
+ /** One parked waiter's admission into a free slot (SPEC §12 "Slot admission
4152
+ * order"): urgent parked work, urgent claims, normal parked work, normal
4153
+ * claims. `occupied` counts every other build holding a slot. */
4154
+ private slotAdmission(
4155
+ slug: string,
4156
+ priority: TicketPriority,
4157
+ occupied: number,
4158
+ projection: DispatchCapacity,
4159
+ ): 'admit' | 'wait' | 'defer' {
4160
+ if (occupied + reservedAhead(projection, { slug, priority }) >= this.deps.config.capacity)
4161
+ return 'wait'
4162
+ return priority === 'normal' && this.urgentBoundaryOpen() ? 'defer' : 'admit'
4163
+ }
4164
+
3331
4165
  /** Whether a leaf may reserve a runner now. A leaf that has not finished its
3332
4166
  * pipeline already holds its slot, and abort and pause acknowledgements park
3333
4167
  * at once, so only a finished leaf that must run again is gated: it needs
3334
- * a free slot among every other build. A denial is recorded only in memory,
3335
- * for this tick's intake reservation. */
3336
- private async leafAdmission(slug: string): Promise<boolean> {
4168
+ * a free slot among every other build, after urgent work ahead of it. A
4169
+ * denial or deferral is recorded only in memory, for this tick's intake
4170
+ * reservation; a deferral is retried after this tick's dispatch. */
4171
+ private async leafAdmission(slug: string): Promise<'admit' | 'wait' | 'defer'> {
3337
4172
  const { state } = await this.store.buildFacts(slug)
3338
4173
  if (
3339
4174
  !(epilogueLeaf(state) || waitParked(state)) ||
@@ -3341,84 +4176,658 @@ export class Dispatcher {
3341
4176
  (command) => command.command === 'abort' || command.command === 'pause',
3342
4177
  )
3343
4178
  )
3344
- return true
3345
- const others = (await this.capacityBuilds(this.tickLaunched)).filter(
3346
- (build) => build.record.slug !== slug,
3347
- )
4179
+ return 'admit'
4180
+ const builds = await this.capacityBuilds(this.tickLaunched)
4181
+ const others = builds.filter((build) => build.record.slug !== slug)
3348
4182
  const capacity = this.deps.config.capacity
3349
- if (dispatchCapacity(others, capacity, this.deps.clock()).occupied < capacity) {
4183
+ const now = this.deps.clock()
4184
+ const priority = buildPriority(state)
4185
+ const outcome = this.slotAdmission(
4186
+ slug,
4187
+ priority,
4188
+ dispatchCapacity(others, capacity, now).occupied,
4189
+ dispatchCapacity(builds, capacity, now, undefined, {
4190
+ urgentClaims: this.urgentClaims(),
4191
+ startRequests: this.startClaims(),
4192
+ }),
4193
+ )
4194
+ if (outcome === 'admit') {
3350
4195
  this.slotWaiters.delete(slug)
3351
- return true
4196
+ return 'admit'
3352
4197
  }
3353
- this.slotWaiters.add(slug)
3354
- return false
4198
+ this.slotWaiters.set(slug, priority)
4199
+ if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
4200
+ this.deferredAdmissions.set(slug, 'leaf')
4201
+ return outcome
3355
4202
  }
3356
4203
 
3357
- /** Admit every node awaiting verification that has a slot, in slug order,
3358
- * through the janitor's own admission path. Independent of `acceptNewWork`:
3359
- * node admission is existing work, never intake. */
3360
- private async admitWaitingNodes(
4204
+ /**
4205
+ * Retry every admission deferred this tick, once this tick's admission scan
4206
+ * has evaluated urgent claims. Each retry re-enters its generic path with
4207
+ * fresh state: a leaf through the lease sweep's per-build pass, a node
4208
+ * through node admission, a proposer through proposer admission. Without a
4209
+ * completed evaluation nothing launches: the waiters stay reserved in
4210
+ * `slotWaiters` against normal claims and are decided again next tick.
4211
+ */
4212
+ private async admitDeferredParked(
3361
4213
  report: TickReport,
3362
4214
  launched: Set<string>,
4215
+ paused: boolean,
3363
4216
  opts: TickOpts,
3364
4217
  ): Promise<void> {
3365
- if (
3366
- !(await this.repoBuildDigests()).some(
3367
- ({ digest }) => digest.kind === 'node' && digest.terminal === undefined,
3368
- )
3369
- )
4218
+ const deferred = [...this.deferredAdmissions]
4219
+ this.deferredAdmissions.clear()
4220
+ if (deferred.length === 0) {
4221
+ this.lastForcedDeferralKey = undefined
3370
4222
  return
3371
- const now = this.deps.clock()
3372
- const waiting = (await this.capacityBuilds())
3373
- .filter((build) => slotRequest(build, now) === 'verification')
3374
- .sort((a, b) => (a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0))
3375
- for (const { record, state } of waiting) {
4223
+ }
4224
+ if (!this.urgentEvaluated) return
4225
+ this.admissionBoundary = false
4226
+ for (const [slug, kind] of deferred) {
3376
4227
  if (this.outOfBudget(opts)) return
3377
- if (
3378
- launched.has(record.slug) ||
3379
- this.hasLiveExecutionLease(record) ||
3380
- !state.nodeOpened ||
3381
- !janitorDue(state.janitor, now)
3382
- )
3383
- continue
3384
- await withForgeRequestContext({ build: record.slug }, async () => {
3385
- try {
3386
- if (!(await this.nodeHasCapacity(record.slug))) return
3387
- await this.prepareIntegration(record, state, report, launched)
3388
- } catch (error) {
3389
- rethrowAuthorityLapse(error)
3390
- report.janitorDiagnostics.push(
3391
- `build ${record.slug}: node admission failed — ${String(error)}`,
3392
- )
4228
+ if (launched.has(slug)) continue
4229
+ try {
4230
+ const record = await this.store.getBuild(slug)
4231
+ if (record === null) continue
4232
+ if (kind === 'leaf')
4233
+ await this.sweepBuild(record, report, launched, paused, this.deps.clock().getTime())
4234
+ else if (kind === 'node') {
4235
+ const builds = await this.capacityBuilds()
4236
+ const build = builds.find((entry) => entry.record.slug === slug)
4237
+ if (build) await this.admitNode(build, this.deps.clock(), report, launched)
4238
+ } else {
4239
+ const builds = await this.capacityBuilds()
4240
+ await this.admitProposers(builds, this.deps.clock(), 0, report, launched, opts, slug)
3393
4241
  }
3394
- })
4242
+ } catch (error) {
4243
+ rethrowAuthorityLapse(error)
4244
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4245
+ if (error instanceof ForgeCooldown) throw error
4246
+ const message =
4247
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4248
+ report.janitorDiagnostics.push(`build ${slug}: deferred admission failed — ${message}`)
4249
+ }
3395
4250
  }
4251
+ if (this.forcedDeferralKey !== undefined) this.lastForcedDeferralKey = this.forcedDeferralKey
3396
4252
  }
3397
4253
 
3398
- private async nodeHasCapacity(slug: string): Promise<boolean> {
3399
- const builds = await this.capacityBuilds()
3400
- return (
3401
- nodeCapacity(
3402
- builds,
3403
- slug,
3404
- this.deps.clock(),
3405
- migrationIdentity(this.store.repositoryFacts().ticketMigrations, this.deps.tickets.name),
3406
- ).occupied < this.deps.config.capacity
3407
- )
3408
- }
3409
-
3410
- private hasLiveExecutionLease(record: BuildRecord): boolean {
3411
- return (
3412
- record.lease !== undefined &&
3413
- new Date(record.lease.expiresAt).getTime() > this.deps.clock().getTime()
3414
- )
4254
+ /** The deferral key a forced admission scan is bounded by: the deferred
4255
+ * slugs and the occupied count. */
4256
+ private deferralKey(occupied: number): string | undefined {
4257
+ if (this.deferredAdmissions.size === 0) return undefined
4258
+ return JSON.stringify([[...this.deferredAdmissions.keys()].sort(), occupied])
3415
4259
  }
3416
4260
 
3417
- /** Complete abort cleanup as an ordered checkpointed saga. External effects
3418
- * are idempotent; a fact after each one prevents already-settled work from
3419
- * repeating on later ticks. `build.completed` is deliberately last. */
3420
- /** Record a landed child's effective issue links on its target node, once
3421
- * per child (SPEC "Forge issue links"). Reduced reads only: the child's
4261
+ /** Admit every node awaiting verification that has a slot, in slug order,
4262
+ * through the janitor's own admission path, then every proposer the free
4263
+ * slots allow. Independent of `acceptNewWork`: node admission is existing
4264
+ * work, never intake. */
4265
+ private async admitWaitingNodes(
4266
+ report: TickReport,
4267
+ launched: Set<string>,
4268
+ opts: TickOpts,
4269
+ ): Promise<void> {
4270
+ const entries = await this.repoBuildDigests()
4271
+ if (!entries.some(({ digest }) => digest.kind === 'node' && digest.terminal === undefined))
4272
+ return
4273
+ // An optimization node's proposer: exhausted stops, filings and new
4274
+ // requests, chosen from this pass's digests alone. Proposing is the
4275
+ // node's own work, never intake, so it runs whether or not new work is
4276
+ // accepted. One clock reading serves every stage of the pass.
4277
+ const now = this.deps.clock()
4278
+ await this.advanceOptimizationNodes(report, opts, entries, now)
4279
+ if (this.outOfBudget(opts)) return
4280
+ const builds = (await this.capacityBuilds()).sort((a, b) =>
4281
+ a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0,
4282
+ )
4283
+ await this.releaseStrandedNodeWorkspaces(builds, now, launched, report, opts)
4284
+ if (this.outOfBudget(opts)) return
4285
+ const waiting = builds.filter(
4286
+ (build) =>
4287
+ slotRequest(build, now) === 'verification' ||
4288
+ (nodeMeasurementDue(build.state) &&
4289
+ !proposeStarted(build.state) &&
4290
+ slotRequest({ ...build, workspace: false }, now) === 'verification'),
4291
+ )
4292
+ const before = launched.size
4293
+ for (const build of waiting) {
4294
+ if (this.outOfBudget(opts)) return
4295
+ await this.admitNode(build, now, report, launched)
4296
+ }
4297
+ await this.admitProposers(builds, now, launched.size - before, report, launched, opts)
4298
+ }
4299
+
4300
+ /** One waiting node's admission: a measurement or its integration
4301
+ * verification, through the janitor's own admission path. */
4302
+ private async admitNode(
4303
+ { record, state }: CapacityBuild,
4304
+ now: Date,
4305
+ report: TickReport,
4306
+ launched: Set<string>,
4307
+ ): Promise<void> {
4308
+ if (
4309
+ launched.has(record.slug) ||
4310
+ this.hasLiveExecutionLease(record) ||
4311
+ !state.nodeOpened ||
4312
+ !janitorDue(state.janitor, now)
4313
+ )
4314
+ return
4315
+ await withForgeRequestContext({ build: record.slug }, async () => {
4316
+ try {
4317
+ if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
4318
+ if (nodeMeasurementDue(state)) await this.prepareNodeMeasurement(record, report, launched)
4319
+ else await this.prepareIntegration(record, state, report, launched)
4320
+ } catch (error) {
4321
+ rethrowAuthorityLapse(error)
4322
+ report.janitorDiagnostics.push(
4323
+ `build ${record.slug}: node admission failed — ${String(error)}`,
4324
+ )
4325
+ }
4326
+ })
4327
+ }
4328
+
4329
+ /**
4330
+ * Release every optimization node workspace that no work owns
4331
+ * (`strandedNodeWorkspace`), over the capacity states this pass already
4332
+ * loaded: no read for a node that holds none. A released entry is updated
4333
+ * in place, so this pass's admission sees the node free.
4334
+ */
4335
+ private async releaseStrandedNodeWorkspaces(
4336
+ builds: CapacityBuild[],
4337
+ now: Date,
4338
+ launched: Set<string>,
4339
+ report: TickReport,
4340
+ opts: TickOpts,
4341
+ ): Promise<void> {
4342
+ for (const build of builds) {
4343
+ if (launched.has(build.record.slug) || !strandedNodeWorkspace(build, now)) continue
4344
+ if (this.outOfBudget(opts)) return
4345
+ const { record } = build
4346
+ await withForgeRequestContext({ build: record.slug }, async () => {
4347
+ try {
4348
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4349
+ if (openWorkspace(facts)) await this.releaseWorkspace(record.slug, facts)
4350
+ const current = await this.store.buildFacts(record.slug)
4351
+ build.workspace = current.workspace !== null
4352
+ build.state = current.state
4353
+ } catch (error) {
4354
+ rethrowAuthorityLapse(error)
4355
+ report.janitorDiagnostics.push(
4356
+ `build ${record.slug}: node workspace release failed — ${String(error)}`,
4357
+ )
4358
+ }
4359
+ })
4360
+ }
4361
+ }
4362
+
4363
+ /**
4364
+ * Withdraw stale proposal requests and admit proposers (SPEC §13.1.1), over
4365
+ * the capacity states `admitWaitingNodes` already loaded: one capacity
4366
+ * computation, and no read for a waiter beyond the free slots.
4367
+ *
4368
+ * An undeposited request with no admitted session is withdrawn once it no
4369
+ * longer fits current state (a stop, a spent budget, or a room shrunk below
4370
+ * its allowance); the node requests again at the current room once room
4371
+ * exists. A session that already started keeps its allowance and resumes.
4372
+ * `only` restricts the pass to one deferred proposer's retry.
4373
+ */
4374
+ private async admitProposers(
4375
+ builds: CapacityBuild[],
4376
+ now: Date,
4377
+ admittedThisPass: number,
4378
+ report: TickReport,
4379
+ launched: Set<string>,
4380
+ opts: TickOpts,
4381
+ only?: string,
4382
+ ): Promise<void> {
4383
+ const proposers = builds.filter(
4384
+ (build) =>
4385
+ build.state.kind === 'node' &&
4386
+ proposeRunDue(build.state.optimization) &&
4387
+ (only === undefined || build.record.slug === only),
4388
+ )
4389
+ if (proposers.length === 0) return
4390
+ const projection = dispatchCapacity(builds, this.deps.config.capacity, now, undefined, {
4391
+ urgentClaims: this.urgentClaims(),
4392
+ startRequests: this.startClaims(),
4393
+ })
4394
+ let occupied = projection.occupied + admittedThisPass
4395
+ for (const build of proposers) {
4396
+ if (this.outOfBudget(opts)) return
4397
+ const { record, state } = build
4398
+ if (
4399
+ launched.has(record.slug) ||
4400
+ this.hasLiveExecutionLease(record) ||
4401
+ build.provisioning ||
4402
+ (nodeMeasurementDue(state) && !proposeStarted(state))
4403
+ )
4404
+ continue
4405
+ await withForgeRequestContext({ build: record.slug }, async () => {
4406
+ try {
4407
+ const withdrawal = proposeStarted(state)
4408
+ ? undefined
4409
+ : proposalWithdrawalDue(state.optimization, now)
4410
+ if (withdrawal !== undefined) {
4411
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4412
+ actor: DISPATCHER,
4413
+ type: 'optimization.proposal-withdrawn',
4414
+ payload: { request: state.optimization!.proposal!.id, reason: withdrawal },
4415
+ } satisfies EventWrite<'optimization.proposal-withdrawn'>)
4416
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4417
+ if (strandedNodeWorkspace({ ...build, state: facts.state }, now))
4418
+ await this.releaseWorkspace(record.slug, facts)
4419
+ return
4420
+ }
4421
+ // A workspace already holds this node's slot (a proposer that lost
4422
+ // its runner); otherwise it needs a free one.
4423
+ const holding = build.workspace
4424
+ if (
4425
+ (holding
4426
+ ? state.status === 'paused' || state.status === 'blocked'
4427
+ : slotRequest(build, now) !== 'propose') ||
4428
+ !state.nodeOpened ||
4429
+ !janitorDue(state.janitor, now)
4430
+ )
4431
+ return
4432
+ if (!holding) {
4433
+ if (!this.accountsAvailable()) return
4434
+ const outcome = this.slotAdmission(
4435
+ record.slug,
4436
+ buildPriority(state),
4437
+ occupied,
4438
+ projection,
4439
+ )
4440
+ if (outcome === 'defer') this.deferredAdmissions.set(record.slug, 'proposer')
4441
+ if (outcome !== 'admit') return
4442
+ occupied++
4443
+ }
4444
+ await this.launchProposer(record, report, launched)
4445
+ } catch (error) {
4446
+ rethrowAuthorityLapse(error)
4447
+ report.janitorDiagnostics.push(
4448
+ `build ${record.slug}: proposer admission failed — ${String(error)}`,
4449
+ )
4450
+ }
4451
+ })
4452
+ }
4453
+ }
4454
+
4455
+ /**
4456
+ * The creation keys of attempts a node deposited and has not recorded yet,
4457
+ * from the build digests alone: no per-node read, and one set lookup per
4458
+ * ready ticket. A node digest without the optimization signal (an older
4459
+ * peer) fails closed: every ready ticket with a creation key is withheld.
4460
+ */
4461
+ private async optimizationCreationHolds(): Promise<{
4462
+ holds: Map<string, { node: string; request: string }>
4463
+ failure?: string
4464
+ }> {
4465
+ const holds = new Map<string, { node: string; request: string }>()
4466
+ for (const { record, digest } of await this.repoBuildDigests()) {
4467
+ if (digest.terminal !== undefined) continue
4468
+ let signal: ReturnType<typeof digestOptimization>
4469
+ try {
4470
+ signal = digestOptimization(digest)
4471
+ } catch (error) {
4472
+ if (!(error instanceof BuildDigestCapabilityError)) throw error
4473
+ return { holds, failure: error.message }
4474
+ }
4475
+ const proposal = signal ? signal.proposal : undefined
4476
+ for (const id of proposal?.deposited?.ids ?? [])
4477
+ holds.set(attemptCreationKey(this.deps.repo, record.slug, id), {
4478
+ node: record.slug,
4479
+ request: proposal!.request,
4480
+ })
4481
+ }
4482
+ return { holds }
4483
+ }
4484
+
4485
+ /** Provision a workspace for a starting or progress measurement. */
4486
+ private async prepareNodeMeasurement(
4487
+ record: BuildRecord,
4488
+ report: TickReport,
4489
+ launched: Set<string>,
4490
+ ): Promise<void> {
4491
+ if (!record.branch || !this.accountsAvailable()) return
4492
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4493
+ if (!nodeMeasurementDue(facts.state)) return
4494
+ await this.provisionNodeAndLaunch(record, facts, report, launched)
4495
+ }
4496
+
4497
+ /** Provision the node workspace at its proposal head. */
4498
+ private async launchProposer(
4499
+ record: BuildRecord,
4500
+ report: TickReport,
4501
+ launched: Set<string>,
4502
+ ): Promise<void> {
4503
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4504
+ const proposal = facts.state.optimization?.proposal
4505
+ if (proposal === undefined || !record.branch) return
4506
+ if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
4507
+ const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
4508
+ if (kicked === 'kicked') report.provisioning++
4509
+ return
4510
+ }
4511
+ if (openWorkspace(facts) === null) {
4512
+ let handle: WorkspaceProvisionResult
4513
+ try {
4514
+ handle = await this.provisionWorkspace(record.slug, {
4515
+ repo: this.deps.checkout ?? this.deps.repo,
4516
+ baseBranch: record.branch,
4517
+ branch: record.branch,
4518
+ revision: proposal.head,
4519
+ })
4520
+ } catch (error) {
4521
+ if (await this.holdForMissingAccounts(error)) return
4522
+ throw error
4523
+ }
4524
+ await this.store.append(record.slug, {
4525
+ actor: DISPATCHER,
4526
+ type: 'workspace.provisioned',
4527
+ payload: {
4528
+ provider: handle.provider,
4529
+ ref: handle.ref,
4530
+ path: handle.path,
4531
+ localPath: handle.localPath,
4532
+ remote: false,
4533
+ branch: handle.branch,
4534
+ base: handle.base,
4535
+ ...(handle.restorationSkipped?.length
4536
+ ? { restorationSkipped: handle.restorationSkipped }
4537
+ : {}),
4538
+ },
4539
+ })
4540
+ }
4541
+ await this.launch(record.slug, launched, report)
4542
+ }
4543
+
4544
+ /**
4545
+ * The optimization proposer stage (SPEC §13.1.1). Nodes are selected from
4546
+ * build digests alone: a plain node, a leaf, a stopped or idle optimization
4547
+ * node, and a deferred node with no wake since its deferral cost no read.
4548
+ * Every build read this stage makes precedes a write that changes the
4549
+ * node's digest. An older peer's digest without the optimization signal
4550
+ * fails the stage closed, never falling back to per-node reads.
4551
+ */
4552
+ private async advanceOptimizationNodes(
4553
+ report: TickReport,
4554
+ opts: TickOpts,
4555
+ entries: { record: BuildRecord; digest: BuildDigest }[],
4556
+ now: Date,
4557
+ ): Promise<void> {
4558
+ const due: { record: BuildRecord; kind: 'exhausted' | 'filing' | 'request' }[] = []
4559
+ try {
4560
+ for (const { record, digest } of entries) {
4561
+ if (digest.terminal !== undefined || !digest.nodeOpened) continue
4562
+ const signal = digestOptimization(digest)
4563
+ if (!signal) continue
4564
+ const kind = signalDue(signal, now, (digest.compatibility?.decisiveFacts ?? 0) > 0)
4565
+ // A node whose runner is working requests nothing until it ends.
4566
+ if (
4567
+ kind === 'request' &&
4568
+ (digest.executionOpen === true || this.hasLiveExecutionLease(record))
4569
+ )
4570
+ continue
4571
+ if (kind !== undefined) due.push({ record, kind })
4572
+ }
4573
+ } catch (error) {
4574
+ if (!(error instanceof BuildDigestCapabilityError)) throw error
4575
+ report.janitorDiagnostics.push(`optimization proposing skipped — ${error.message}`)
4576
+ return
4577
+ }
4578
+ for (const { record, kind } of due) {
4579
+ if (this.outOfBudget(opts)) return
4580
+ await withForgeRequestContext({ build: record.slug }, async () => {
4581
+ try {
4582
+ if (kind === 'exhausted') await this.recordExhausted(record.slug)
4583
+ else if (kind === 'filing') await this.fileProposedAttempts(record, now)
4584
+ else await this.requestProposal(record, now)
4585
+ } catch (error) {
4586
+ rethrowAuthorityLapse(error)
4587
+ report.janitorDiagnostics.push(
4588
+ `build ${record.slug}: optimization proposing failed — ${String(error)}`,
4589
+ )
4590
+ }
4591
+ })
4592
+ }
4593
+ }
4594
+
4595
+ /** Record a new proposal request, or a durable deferral naming what
4596
+ * blocks the proposer. */
4597
+ private async requestProposal(record: BuildRecord, now: Date): Promise<void> {
4598
+ const { state } = await this.store.buildFacts(record.slug)
4599
+ const optimization = state.optimization
4600
+ if (optimization === undefined || !record.branch) return
4601
+ if (!proposerAdmissible(state, now)) {
4602
+ const reason = proposerBlocker(state)
4603
+ if (reason !== undefined)
4604
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4605
+ actor: DISPATCHER,
4606
+ type: 'optimization.proposal-deferred',
4607
+ payload: { reason },
4608
+ } satisfies EventWrite<'optimization.proposal-deferred'>)
4609
+ return
4610
+ }
4611
+ const head = await this.baseSha(record.branch)
4612
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4613
+ actor: DISPATCHER,
4614
+ type: 'optimization.proposal-requested',
4615
+ payload: {
4616
+ id: this.deps.ids('proposal'),
4617
+ head,
4618
+ room: proposerRoom(optimization, now),
4619
+ budgetUsed: {
4620
+ attempts: optimization.attempts.filed,
4621
+ hours: optimizationElapsedHours(optimization, now),
4622
+ },
4623
+ },
4624
+ } satisfies EventWrite<'optimization.proposal-requested'>)
4625
+ }
4626
+
4627
+ /** Two consecutive empty proposals stop the node with cause `exhausted`.
4628
+ * Only the cause is recorded here; what a stop does to running attempts
4629
+ * belongs to the stop policy. */
4630
+ private async recordExhausted(slug: string): Promise<void> {
4631
+ const { state } = await this.store.buildFacts(slug)
4632
+ if (!exhaustedStopDue(state.optimization)) return
4633
+ await this.store.appendIfCurrent(slug, state.lastSeq, {
4634
+ actor: DISPATCHER,
4635
+ type: 'optimization.stopped',
4636
+ payload: { cause: 'exhausted', mode: state.optimization!.objective.stop.mode },
4637
+ } satisfies EventWrite<'optimization.stopped'>)
4638
+ }
4639
+
4640
+ /**
4641
+ * File a deposited proposal: one ready ticket per proposal, targeting the
4642
+ * node, each created under a key derived from the node and proposal id so
4643
+ * a retry after a crash adopts what an earlier attempt created. The
4644
+ * deposit is a commitment: every deposited proposal is filed and recorded
4645
+ * in one `attempts-proposed`, whatever revisions or stops landed since.
4646
+ * Until that record lands, intake withholds these keys.
4647
+ */
4648
+ private async fileProposedAttempts(record: BuildRecord, now: Date): Promise<void> {
4649
+ const { state } = await this.store.buildFacts(record.slug)
4650
+ const proposal = state.optimization?.proposal
4651
+ const deposited = proposal?.deposited
4652
+ if (proposal === undefined || deposited === undefined) return
4653
+ const escalate = async (question: string) => {
4654
+ await this.store.append(record.slug, {
4655
+ actor: KERNEL,
4656
+ type: 'escalation.raised',
4657
+ payload: {
4658
+ id: this.deps.ids('esc'),
4659
+ phase: 'propose',
4660
+ round: proposal.round,
4661
+ source: 'agent',
4662
+ question,
4663
+ },
4664
+ } satisfies EventWrite<'escalation.raised'>)
4665
+ }
4666
+ // A filing this node already escalated waits for the answer, durably.
4667
+ if (
4668
+ state.openEscalations.some(
4669
+ (escalation) => escalation.phase === 'propose' && escalation.round === proposal.round,
4670
+ )
4671
+ ) {
4672
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4673
+ actor: DISPATCHER,
4674
+ type: 'optimization.proposal-deferred',
4675
+ payload: { reason: 'blocked' },
4676
+ } satisfies EventWrite<'optimization.proposal-deferred'>)
4677
+ return
4678
+ }
4679
+ const artifact = await this.store.getArtifact(
4680
+ record.slug,
4681
+ deposited.artifact.kind,
4682
+ deposited.artifact.rev,
4683
+ )
4684
+ let document: ReturnType<typeof proposalsDocumentSchema.parse> | undefined
4685
+ try {
4686
+ if (artifact !== null)
4687
+ document = proposalsDocumentSchema.parse(
4688
+ JSON.parse(new TextDecoder().decode(artifact.content)),
4689
+ )
4690
+ } catch {
4691
+ document = undefined
4692
+ }
4693
+ if (
4694
+ document === undefined ||
4695
+ document.proposals.map((entry) => entry.id).join('\u0000') !== deposited.ids.join('\u0000')
4696
+ ) {
4697
+ await escalate(
4698
+ `Cannot file proposal ${proposal.id}: its attempts artifact ` +
4699
+ `${deposited.artifact.kind}@${deposited.artifact.rev} is missing or does not match the deposit.`,
4700
+ )
4701
+ return
4702
+ }
4703
+ const tickets = this.deps.tickets
4704
+ if (document.proposals.length > 0 && !tickets.integrationTree) {
4705
+ await escalate(
4706
+ `Cannot file proposal ${proposal.id}: ticket source ${tickets.name} lacks the ` +
4707
+ 'integrationTree capability, so it cannot create attempts that target this node.',
4708
+ )
4709
+ return
4710
+ }
4711
+ const node = record.ticket
4712
+ ? resolveTicketRef(
4713
+ this.store.repositoryFacts().ticketMigrations,
4714
+ record.ticket,
4715
+ tickets.name,
4716
+ record.slug,
4717
+ )
4718
+ : undefined
4719
+ if (document.proposals.length > 0 && node === undefined) {
4720
+ await escalate(`Cannot file proposal ${proposal.id}: the node build has no ticket to target.`)
4721
+ return
4722
+ }
4723
+ // Attempts are dispatchable at creation: they carry every ready gate, plus
4724
+ // any configured creation labels. The source applies the ready assignee
4725
+ // itself, also to an adopted ticket.
4726
+ const ready = readyCriteria(this.deps.config)
4727
+ const assignees = creationAssignees(this.deps.config.tickets)
4728
+ const labels = creationLabels(this.deps.config.tickets, ready.labels) ?? []
4729
+ const filed: EventPayload<'optimization.attempts-proposed'>['proposals'] = []
4730
+ for (const entry of document.proposals) {
4731
+ const ticket = await tickets.create(
4732
+ {
4733
+ kind: 'work',
4734
+ target: node!.id,
4735
+ title: entry.title,
4736
+ body: entry.body,
4737
+ ...(labels.length > 0 ? { labels } : {}),
4738
+ ...(assignees !== undefined ? { assignees } : {}),
4739
+ },
4740
+ {
4741
+ state: ready.state,
4742
+ idempotencyKey: attemptCreationKey(this.deps.repo, record.slug, entry.id),
4743
+ idempotencyKeyReservedAt: deposited.at,
4744
+ ...(ready.assignee !== undefined ? { readyAssignee: ready.assignee } : {}),
4745
+ },
4746
+ )
4747
+ filed.push({
4748
+ id: entry.id,
4749
+ ticket: ticket.ref,
4750
+ title: entry.title,
4751
+ strategy: entry.strategy,
4752
+ })
4753
+ }
4754
+ const current = (await this.store.buildFacts(record.slug)).state
4755
+ if (current.optimization?.proposal?.id !== proposal.id) return
4756
+ await this.store.appendIfCurrent(record.slug, current.lastSeq, {
4757
+ actor: DISPATCHER,
4758
+ type: 'optimization.attempts-proposed',
4759
+ payload: {
4760
+ request: proposal.id,
4761
+ proposals: filed,
4762
+ ...(document.proposals.length === 0 && document.reason !== undefined
4763
+ ? { reason: document.reason }
4764
+ : {}),
4765
+ },
4766
+ } satisfies EventWrite<'optimization.attempts-proposed'>)
4767
+ // A crash or failure before this release, or a live lease now, leaves the
4768
+ // workspace to `releaseStrandedNodeWorkspaces` on a later pass.
4769
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4770
+ if (
4771
+ strandedNodeWorkspace(
4772
+ {
4773
+ record,
4774
+ state: facts.state,
4775
+ workspace: openWorkspace(facts) !== null,
4776
+ provisioning: this.continuations.has(record.slug),
4777
+ },
4778
+ now,
4779
+ )
4780
+ )
4781
+ await this.releaseWorkspace(record.slug, facts)
4782
+ await this.recordExhausted(record.slug)
4783
+ }
4784
+
4785
+ /** A node's admission into a free slot. A verification or measurement
4786
+ * request (`reserving`) yields to urgent work ahead of it and defers while
4787
+ * urgent claims are unevaluated. A node that already holds its slot — a
4788
+ * restack-conflict reconcile, or runner work that kept its workspace across
4789
+ * a failed launch or expired lease — only needs the node's own room:
4790
+ * priority orders free slots, never one the node owns. */
4791
+ private async nodeHasCapacity(
4792
+ slug: string,
4793
+ reserving = true,
4794
+ ): Promise<'admit' | 'wait' | 'defer'> {
4795
+ const builds = await this.capacityBuilds()
4796
+ const now = this.deps.clock()
4797
+ const identity = migrationIdentity(
4798
+ this.store.repositoryFacts().ticketMigrations,
4799
+ this.deps.tickets.name,
4800
+ )
4801
+ const { occupied } = nodeCapacity(builds, slug, now, identity)
4802
+ const node = builds.find((build) => build.record.slug === slug)
4803
+ if (!reserving || (node && occupiesCapacity(node, now)))
4804
+ return occupied < this.deps.config.capacity ? 'admit' : 'wait'
4805
+ const outcome = this.slotAdmission(
4806
+ slug,
4807
+ node ? buildPriority(node.state) : 'normal',
4808
+ occupied,
4809
+ dispatchCapacity(builds, this.deps.config.capacity, now, identity, {
4810
+ urgentClaims: this.urgentClaims(),
4811
+ startRequests: this.startClaims(),
4812
+ }),
4813
+ )
4814
+ if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
4815
+ this.deferredAdmissions.set(slug, 'node')
4816
+ return outcome
4817
+ }
4818
+
4819
+ private hasLiveExecutionLease(record: BuildRecord): boolean {
4820
+ return (
4821
+ record.lease !== undefined &&
4822
+ new Date(record.lease.expiresAt).getTime() > this.deps.clock().getTime()
4823
+ )
4824
+ }
4825
+
4826
+ /** Complete abort cleanup as an ordered checkpointed saga. External effects
4827
+ * are idempotent; a fact after each one prevents already-settled work from
4828
+ * repeating on later ticks. `build.completed` is deliberately last. */
4829
+ /** Record a landed child's effective issue links on its target node, once
4830
+ * per child (SPEC "Forge issue links"). Reduced reads only: the child's
3422
4831
  * refreshed state and the node's union, never any child history. */
3423
4832
  private async recordNodeIssueLinks(slug: string): Promise<void> {
3424
4833
  const state = (await this.store.buildFacts(slug)).state
@@ -3436,6 +4845,495 @@ export class Dispatcher {
3436
4845
  } satisfies EventWrite<'node.issue-links-recorded'>)
3437
4846
  }
3438
4847
 
4848
+ // ── Optimization attempts (SPEC §15.7, RFC 0005 §6.3–§7.5) ─────────────────
4849
+
4850
+ /** The child's attempt identity on its optimization node, under the
4851
+ * repository's ticket-migration identity: in flight, settled with its
4852
+ * rejected-role move pending, or not an attempt. */
4853
+ private attemptOf(
4854
+ node: Pick<BuildState, 'optimization'>,
4855
+ record: Pick<BuildRecord, 'ticket' | 'slug'>,
4856
+ ): { status: AttemptStatus; attempt?: InFlightAttempt | PendingRejection } {
4857
+ if (node.optimization === undefined || record.ticket === undefined) return { status: 'none' }
4858
+ const key = this.attemptKey()
4859
+ const inFlight = optimizationAttempt(node.optimization, record.ticket, key)
4860
+ if (inFlight) return { status: 'in-flight', attempt: inFlight }
4861
+ const rejection = optimizationRejection(node.optimization, record.ticket, key)
4862
+ if (rejection) return { status: 'settled', attempt: rejection }
4863
+ return { status: 'none' }
4864
+ }
4865
+
4866
+ private attemptKey(): (ref: TicketRef) => string {
4867
+ const identity = migrationIdentity(
4868
+ this.store.repositoryFacts().ticketMigrations,
4869
+ this.deps.tickets.name,
4870
+ )
4871
+ return (ref) => identity(ref)
4872
+ }
4873
+
4874
+ /** The nonterminal children of `nodeSlug` in this tick's janitor listing,
4875
+ * indexed once per tick. Attempts ride in the work set while nonterminal,
4876
+ * and a build created later in the tick has never been overtaken, so it
4877
+ * cannot hold the turn. */
4878
+ private childrenOf(nodeSlug: string): BuildRecord[] {
4879
+ const entries = this.janitorEntries
4880
+ if (entries === undefined)
4881
+ throw new Error('the landing turn reads the janitor listing; run it inside the janitor')
4882
+ if (this.nodeChildren === undefined) {
4883
+ const index = new Map<string, BuildRecord[]>()
4884
+ for (const { record, digest } of entries) {
4885
+ if (digest.terminal !== undefined || record.ticket === undefined) continue
4886
+ for (const target of digestNodeTargets(digest)) {
4887
+ const children = index.get(target)
4888
+ if (children) children.push(record)
4889
+ else index.set(target, [record])
4890
+ }
4891
+ }
4892
+ this.nodeChildren = index
4893
+ }
4894
+ return this.nodeChildren.get(nodeSlug) ?? []
4895
+ }
4896
+
4897
+ /** The gate's verdict for one child of an optimization node, from the
4898
+ * child's and the node's reduced facts. The turn costs at most one reduced
4899
+ * read per other in-flight attempt, and only for a would-be request or
4900
+ * landing; its candidates come from the tick's janitor listing, so it never
4901
+ * lists the repository. */
4902
+ private async landingVerdict(
4903
+ record: BuildRecord,
4904
+ nodeSlug: string,
4905
+ ): Promise<{
4906
+ verdict: LandingGateVerdict
4907
+ state: BuildState
4908
+ node: BuildState
4909
+ status: AttemptStatus
4910
+ attempt?: InFlightAttempt | PendingRejection
4911
+ candidate?: string
4912
+ nodeHead?: string
4913
+ }> {
4914
+ const facts = await this.store.buildFacts(record.slug)
4915
+ const state = facts.state
4916
+ const node = (await this.store.buildFacts(nodeSlug)).state
4917
+ const digest = node.optimization!
4918
+ const { status, attempt } = this.attemptOf(node, record)
4919
+ const candidate = candidateHead(state)
4920
+ // The head the child would land on, once its candidate sits on it: a
4921
+ // measurement against any other base would be stale before it lands.
4922
+ const parent =
4923
+ state.kind === 'node'
4924
+ ? state.integration?.cycle?.parent
4925
+ : (facts.log.restack.completed?.targetBase ?? facts.log.restack.initialBase)
4926
+ const observed =
4927
+ state.kind === 'node' ? state.nodeRestack?.observedParent?.sha : facts.log.restack.target?.sha
4928
+ const nodeHead = observed !== undefined && observed === parent ? observed : undefined
4929
+ const lm = state.landingMeasurement
4930
+ const input = {
4931
+ digest,
4932
+ attempt: status,
4933
+ lm,
4934
+ candidate,
4935
+ nodeHead,
4936
+ self: record.slug,
4937
+ regressionAnswered:
4938
+ lm?.request !== undefined &&
4939
+ state.answeredEscalations.some((e) => e.id === regressionEscalationId(lm.request!.id)),
4940
+ }
4941
+ let verdict = landingMeasurementGate(input)
4942
+ if (verdict === 'land' || verdict === 'request') {
4943
+ const key = this.attemptKey()
4944
+ const self = record.ticket && key(record.ticket)
4945
+ if (digest.inFlight.some((entry) => key(entry.ticket) !== self)) {
4946
+ const wanted = new Set(digest.inFlight.map((entry) => key(entry.ticket)))
4947
+ const candidates: TurnCandidate[] =
4948
+ record.ticket !== undefined ? [{ slug: record.slug, ticket: record.ticket, state }] : []
4949
+ for (const other of this.childrenOf(nodeSlug)) {
4950
+ if (other.slug === record.slug || !wanted.has(key(other.ticket!))) continue
4951
+ const otherState = (await this.store.buildFacts(other.slug)).state
4952
+ if (otherState.target?.build !== nodeSlug) continue
4953
+ candidates.push({ slug: other.slug, ticket: other.ticket!, state: otherState })
4954
+ }
4955
+ verdict = landingMeasurementGate({
4956
+ ...input,
4957
+ turn: selectTurnHolder(digest, candidates, key),
4958
+ })
4959
+ }
4960
+ }
4961
+ return { verdict, state, node, status, attempt, candidate, nodeHead }
4962
+ }
4963
+
4964
+ /** Raise one kernel escalation on a child at landing, deduplicated by id
4965
+ * against open and answered escalations. */
4966
+ private async raiseLandingEscalation(
4967
+ slug: string,
4968
+ state: BuildState,
4969
+ id: string,
4970
+ question: string,
4971
+ ): Promise<void> {
4972
+ if (
4973
+ state.openEscalations.some((e) => e.id === id) ||
4974
+ state.answeredEscalations.some((e) => e.id === id)
4975
+ )
4976
+ return
4977
+ await this.store.append(slug, {
4978
+ actor: KERNEL,
4979
+ type: 'escalation.raised',
4980
+ payload: { id, phase: 'finalize', source: 'agent', question: question.slice(0, 8000) },
4981
+ } satisfies EventWrite<'escalation.raised'>)
4982
+ }
4983
+
4984
+ /**
4985
+ * The measurement landing gate for a ready, authorized child of an
4986
+ * optimization node (SPEC §15.7). Returns the measured pair when the child
4987
+ * may land now; otherwise it did this poll's one action (request a
4988
+ * measurement, escalate, settle and close) or waits, and returns a reason
4989
+ * the caller stops on. The node writer lease is never held here.
4990
+ */
4991
+ private async optimizationLandingGate(
4992
+ record: BuildRecord,
4993
+ nodeSlug: string,
4994
+ workspacePath: string,
4995
+ pr: number,
4996
+ ): Promise<
4997
+ | { kind: 'land'; measured: { candidate: string; baseline: string } }
4998
+ | { kind: 'wait' }
4999
+ | { kind: 'closed'; result: Awaited<ReturnType<NonNullable<Forge['closePr']>>> }
5000
+ > {
5001
+ const gate = await this.landingVerdict(record, nodeSlug)
5002
+ const { verdict, state, node, attempt, candidate, nodeHead } = gate
5003
+ const digest = node.optimization!
5004
+ switch (verdict) {
5005
+ case 'land':
5006
+ return { kind: 'land', measured: { candidate: candidate!, baseline: nodeHead! } }
5007
+ case 'request': {
5008
+ if (gate.status === 'in-flight') {
5009
+ const harnessId = harnessEscalationId(candidate!)
5010
+ // An answered harness escalation still never measures this head.
5011
+ if (
5012
+ state.openEscalations.some((e) => e.id === harnessId) ||
5013
+ state.answeredEscalations.some((e) => e.id === harnessId)
5014
+ )
5015
+ return { kind: 'wait' }
5016
+ const recorded = headPathsFor(state, candidate)
5017
+ // Wait for the head's recorded paths, as `landing.deferred` does.
5018
+ if (!recorded.recorded) return { kind: 'wait' }
5019
+ const paths =
5020
+ recorded.record.total > recorded.record.preview.length
5021
+ ? (await readHeadPaths(this.store, record.slug, recorded.record)).paths
5022
+ : recorded.record.preview
5023
+ const matches = compilePathSelectors(digest.objective.metric.harness)
5024
+ const edited = paths.filter((path) => matches(path))
5025
+ if (edited.length > 0) {
5026
+ await this.raiseLandingEscalation(
5027
+ record.slug,
5028
+ state,
5029
+ harnessId,
5030
+ `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.`,
5031
+ )
5032
+ return { kind: 'wait' }
5033
+ }
5034
+ }
5035
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5036
+ actor: DISPATCHER,
5037
+ type: 'attempt.measurement-requested',
5038
+ payload: {
5039
+ id: this.deps.ids('measure'),
5040
+ node: nodeSlug,
5041
+ candidate: candidate!,
5042
+ baseline: nodeHead!,
5043
+ harnessPin: digest.accepted.harnessPin,
5044
+ revision: digest.revision,
5045
+ metric: digest.objective.metric,
5046
+ ...(digest.objective.metric.kind === 'panel'
5047
+ ? { purpose: digest.objective.purpose }
5048
+ : {}),
5049
+ },
5050
+ })
5051
+ return { kind: 'wait' }
5052
+ }
5053
+ case 'regressed': {
5054
+ const result = state.landingMeasurement!.result!
5055
+ const medians = result.medians
5056
+ ? `baseline median ${result.medians.baseline}, candidate median ${result.medians.candidate}`
5057
+ : `win rate ${result.winRate}`
5058
+ await this.raiseLandingEscalation(
5059
+ record.slug,
5060
+ state,
5061
+ regressionEscalationId(result.request),
5062
+ `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.`,
5063
+ )
5064
+ return { kind: 'wait' }
5065
+ }
5066
+ case 'no-improvement': {
5067
+ const result = state.landingMeasurement!.result!
5068
+ await settleAttempt(
5069
+ this.store,
5070
+ nodeSlug,
5071
+ {
5072
+ proposal: attempt!.proposal,
5073
+ ticket: attempt!.ticket,
5074
+ build: record.slug,
5075
+ ...(record.branch !== undefined && attemptBranchPublished(state)
5076
+ ? { branch: record.branch }
5077
+ : {}),
5078
+ },
5079
+ 'no-improvement',
5080
+ { measurement: settlementMeasurement(result) },
5081
+ )
5082
+ return this.closeSettledAttempt(record, workspacePath, pr)
5083
+ }
5084
+ case 'settled':
5085
+ return this.closeSettledAttempt(record, workspacePath, pr)
5086
+ case 'pending':
5087
+ case 'wait-turn':
5088
+ case 'wait-progress':
5089
+ case 'stale':
5090
+ return { kind: 'wait' }
5091
+ }
5092
+ }
5093
+
5094
+ /** Settle a merged attempt `accepted` with the measurement of the head
5095
+ * that landed. Without one (a forge-side human merge bypassed the gate) it
5096
+ * marks the attempt `attempt.merged-unmeasured` on the node, where it keeps
5097
+ * its slot until an operator settles it, and records one followup. */
5098
+ private async settleMergedAttempt(
5099
+ record: BuildRecord,
5100
+ state: BuildState,
5101
+ sha: string,
5102
+ ): Promise<void> {
5103
+ const attempt = await this.terminalAttempt(record, state)
5104
+ if (attempt.status !== 'in-flight') return
5105
+ const identity = {
5106
+ proposal: attempt.attempt!.proposal,
5107
+ ticket: attempt.attempt!.ticket,
5108
+ }
5109
+ const measured = mergedAttemptMeasurement(state.landingMeasurement, attempt.node, sha)
5110
+ if (measured.kind === 'measured') {
5111
+ await settleAttempt(
5112
+ this.store,
5113
+ attempt.node,
5114
+ { ...identity, build: record.slug },
5115
+ 'accepted',
5116
+ { measurement: settlementMeasurement(measured.result), head: sha },
5117
+ )
5118
+ return
5119
+ }
5120
+ const marked = await markUnmeasuredMerge(this.store, attempt.node, identity, {
5121
+ build: record.slug,
5122
+ sha,
5123
+ reason: measured.reason,
5124
+ ...(measured.measuredCandidate !== undefined
5125
+ ? { measuredCandidate: measured.measuredCandidate }
5126
+ : {}),
5127
+ })
5128
+ if (marked)
5129
+ await this.store.append(record.slug, {
5130
+ actor: KERNEL,
5131
+ type: 'observation.recorded',
5132
+ payload: {
5133
+ id: this.deps.ids('obs'),
5134
+ kind: 'followup',
5135
+ 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\`.`,
5136
+ refs: [sha],
5137
+ },
5138
+ })
5139
+ }
5140
+
5141
+ /** Close a settled attempt's PR without merging. The `closed` epilogue
5142
+ * then completes the build; no implement round follows. */
5143
+ private async closeSettledAttempt(
5144
+ record: BuildRecord,
5145
+ workspacePath: string,
5146
+ pr: number,
5147
+ ): Promise<{ kind: 'closed'; result: Awaited<ReturnType<NonNullable<Forge['closePr']>>> }> {
5148
+ const closePr = this.deps.forge.closePr
5149
+ if (closePr === undefined)
5150
+ throw new Error(
5151
+ `selected forge "${this.deps.forge.name}" does not implement closePr; upgrade its plugin`,
5152
+ )
5153
+ const result = await closePr.call(this.deps.forge, workspacePath, pr)
5154
+ if (
5155
+ result.state === 'closed' &&
5156
+ (await this.store.buildFacts(record.slug)).state.prState !== 'closed'
5157
+ )
5158
+ await this.store.append(record.slug, {
5159
+ actor: DISPATCHER,
5160
+ type: 'pr.closed',
5161
+ payload: {},
5162
+ } satisfies EventWrite<'pr.closed'>)
5163
+ return { kind: 'closed', result }
5164
+ }
5165
+
5166
+ /** Whether the pair measured for landing is still the gate's `land` pair:
5167
+ * the publication-time check inside the node writer, separate from the
5168
+ * measurement-independent readiness that admits the gate. */
5169
+ private async measuredPairCurrent(
5170
+ record: BuildRecord,
5171
+ nodeSlug: string,
5172
+ pair: { candidate: string; baseline: string },
5173
+ ): Promise<boolean> {
5174
+ await this.store.refreshBuild(record.slug)
5175
+ await this.store.refreshBuild(nodeSlug)
5176
+ const gate = await this.landingVerdict(record, nodeSlug)
5177
+ return (
5178
+ gate.verdict === 'land' &&
5179
+ gate.candidate === pair.candidate &&
5180
+ gate.nodeHead === pair.baseline
5181
+ )
5182
+ }
5183
+
5184
+ /** The attempt status of a child at one of its terminal paths, from its
5185
+ * node's reduced facts: one read, not recurring. */
5186
+ private async terminalAttempt(
5187
+ record: BuildRecord,
5188
+ state: Pick<BuildState, 'target'>,
5189
+ ): Promise<{
5190
+ node: string
5191
+ status: AttemptStatus
5192
+ attempt?: InFlightAttempt | PendingRejection
5193
+ }> {
5194
+ if (state.target === undefined) return { node: '', status: 'none' }
5195
+ const node = (await this.store.buildFacts(state.target.build)).state
5196
+ return { node: state.target.build, ...this.attemptOf(node, record) }
5197
+ }
5198
+
5199
+ /**
5200
+ * The node-side duties of each settled, non-accepted attempt, once its
5201
+ * build is done: delete a declined or no-improvement attempt's published
5202
+ * build branch (SPEC §15.7), then move its ticket to the rejected role
5203
+ * (SPEC §13), the one owner of that move. An entry waits until its attempt
5204
+ * build is done, so no terminal path can hand the ticket back to triage
5205
+ * afterwards. Zero reads while nothing is pending; otherwise at most one
5206
+ * reduced read per entry with work, which admission bounds by the node's
5207
+ * concurrency. Never lists the repository.
5208
+ */
5209
+ private async sweepAttemptRejections(record: BuildRecord, state: BuildState): Promise<boolean> {
5210
+ const rejectedState = this.deps.config.tickets.rejectedState
5211
+ // Without a rejected role only a branch obligation is work to do.
5212
+ const pending = (state.optimization?.rejections ?? []).filter(
5213
+ (entry) => entry.branch !== undefined || rejectedState !== undefined,
5214
+ )
5215
+ if (pending.length === 0) return false
5216
+ let wrote = false
5217
+ for (const entry of pending) {
5218
+ let attemptRecord: BuildRecord | null = null
5219
+ let attemptState: BuildState | undefined
5220
+ if (entry.build !== undefined) {
5221
+ attemptRecord = await this.store.getBuild(entry.build)
5222
+ if (attemptRecord !== null) {
5223
+ attemptState = (await this.store.buildFacts(entry.build)).state
5224
+ if (attemptState.status !== 'done') continue
5225
+ }
5226
+ }
5227
+ if (entry.branch !== undefined) {
5228
+ const cleanup = await this.cleanupAttemptBranch(
5229
+ record,
5230
+ state,
5231
+ entry,
5232
+ attemptRecord,
5233
+ attemptState,
5234
+ )
5235
+ if (cleanup !== 'unchanged') wrote = true
5236
+ // The ticket moves only once the obligation is met, so the entry
5237
+ // keeps its slot while cleanup is pending.
5238
+ if (cleanup !== 'deleted') continue
5239
+ }
5240
+ if (rejectedState === undefined) continue
5241
+ const id = resolveTicketRef(
5242
+ this.store.repositoryFacts().ticketMigrations,
5243
+ entry.ticket,
5244
+ this.deps.tickets.name,
5245
+ entry.build,
5246
+ ).id
5247
+ const ticket = await moveTicketToRole(
5248
+ this.deps.tickets,
5249
+ this.deps.config.tickets,
5250
+ id,
5251
+ 'rejected',
5252
+ )
5253
+ const rejected = ticket.state ?? rejectedState
5254
+ await this.deps.tickets.comment(
5255
+ id,
5256
+ `attempt ${entry.proposal} settled as ${entry.outcome}; moved to ${rejected}`,
5257
+ )
5258
+ await this.store.append(record.slug, {
5259
+ actor: DISPATCHER,
5260
+ type: 'attempt.ticket-rejected',
5261
+ payload: { proposal: entry.proposal, ticket: entry.ticket, state: rejected },
5262
+ } satisfies EventWrite<'attempt.ticket-rejected'>)
5263
+ wrote = true
5264
+ }
5265
+ return wrote
5266
+ }
5267
+
5268
+ /**
5269
+ * Delete one settled attempt's published build branch and record it, or
5270
+ * record why it could not be deleted. The guards refuse any branch that is
5271
+ * not exactly this done attempt build's own, so cleanup never touches the
5272
+ * node's branch, its base, or another build's contribution. A delete of an
5273
+ * already-absent branch succeeds; a crash before the record repeats it.
5274
+ * A failure is recorded only when its error changed, and the settlement is
5275
+ * never touched, so a retry cannot change the outcome.
5276
+ */
5277
+ private async cleanupAttemptBranch(
5278
+ node: BuildRecord,
5279
+ nodeState: BuildState,
5280
+ entry: PendingRejection,
5281
+ attemptRecord: BuildRecord | null,
5282
+ attemptState: BuildState | undefined,
5283
+ ): Promise<'deleted' | 'failed' | 'unchanged'> {
5284
+ const branch = entry.branch!
5285
+ const refusal =
5286
+ entry.build === undefined
5287
+ ? 'the settlement names no attempt build'
5288
+ : attemptRecord === null || attemptState === undefined
5289
+ ? `attempt build ${entry.build} does not exist`
5290
+ : attemptRecord.branch !== branch
5291
+ ? `branch ${branch} is not attempt build ${entry.build}'s branch`
5292
+ : attemptState.target?.build !== node.slug
5293
+ ? `attempt build ${entry.build} does not target node ${node.slug}`
5294
+ : branch === node.branch ||
5295
+ branch === nodeState.baseBranch ||
5296
+ branch === this.deps.config.baseBranch
5297
+ ? `branch ${branch} is the node's own or base branch`
5298
+ : undefined
5299
+ let error = refusal
5300
+ if (error === undefined) {
5301
+ const forge = this.deps.forge
5302
+ try {
5303
+ if (forge.deleteBranch === undefined)
5304
+ throw new Error(
5305
+ `selected forge "${forge.name}" does not implement deleteBranch; upgrade its plugin`,
5306
+ )
5307
+ // Local forges treat workspacePath as a git cwd: pass the physical
5308
+ // checkout, as abort cleanup does. API forges ignore the argument.
5309
+ await forge.deleteBranch.call(forge, this.deps.checkout ?? this.deps.repo, branch)
5310
+ await this.store.append(node.slug, {
5311
+ actor: DISPATCHER,
5312
+ type: 'attempt.branch-deleted',
5313
+ payload: { proposal: entry.proposal, build: entry.build!, branch },
5314
+ } satisfies EventWrite<'attempt.branch-deleted'>)
5315
+ return 'deleted'
5316
+ } catch (caught) {
5317
+ rethrowAuthorityLapse(caught)
5318
+ if (caught instanceof ForgeCooldown) throw caught
5319
+ error = caught instanceof Error || isForgeFailure(caught) ? caught.message : String(caught)
5320
+ }
5321
+ }
5322
+ const recorded = error.slice(0, 2000) || 'branch deletion failed'
5323
+ if (entry.branchCleanupError === recorded) return 'unchanged'
5324
+ await this.store.append(node.slug, {
5325
+ actor: DISPATCHER,
5326
+ type: 'attempt.branch-cleanup-failed',
5327
+ payload: {
5328
+ proposal: entry.proposal,
5329
+ ...(entry.build !== undefined ? { build: entry.build } : {}),
5330
+ branch,
5331
+ error: recorded,
5332
+ },
5333
+ } satisfies EventWrite<'attempt.branch-cleanup-failed'>)
5334
+ return 'failed'
5335
+ }
5336
+
3439
5337
  private async cleanupAborted(
3440
5338
  record: BuildRecord,
3441
5339
  events: CurrentBuildFacts,
@@ -3626,7 +5524,34 @@ export class Dispatcher {
3626
5524
  }
3627
5525
  }
3628
5526
 
3629
- if (record.ticket !== undefined && !has('abort.ticket-returned')) {
5527
+ // Abort cleanup is the only writer for aborted builds: the first abort
5528
+ // request fixes whether an operator or a node stop caused it. The node moves the ticket
5529
+ // to the rejected role, so none of the triage hand-back below applies.
5530
+ const attempt = await this.terminalAttempt(record, events.state)
5531
+ if (attempt.status === 'in-flight')
5532
+ try {
5533
+ if (events.state.prState === 'merged' && events.state.mergedSha)
5534
+ await this.settleMergedAttempt(record, events.state, events.state.mergedSha)
5535
+ else
5536
+ await settleAttempt(
5537
+ store,
5538
+ attempt.node,
5539
+ {
5540
+ proposal: attempt.attempt!.proposal,
5541
+ ticket: attempt.attempt!.ticket,
5542
+ build: record.slug,
5543
+ },
5544
+ events.latestAbort?.payload.origin?.kind === 'optimization-stop'
5545
+ ? 'stopped'
5546
+ : 'aborted',
5547
+ { note: events.latestAbort?.payload.reason?.trim() || undefined },
5548
+ )
5549
+ } catch (error) {
5550
+ fail('attempt settlement', `build ${record.slug}`, error)
5551
+ }
5552
+ const handback = record.ticket !== undefined && attempt.status === 'none'
5553
+
5554
+ if (handback && record.ticket !== undefined && !has('abort.ticket-returned')) {
3630
5555
  const label = 'autobuild:aborted'
3631
5556
  try {
3632
5557
  const id = await this.currentTicketId(record)
@@ -3678,7 +5603,7 @@ export class Dispatcher {
3678
5603
 
3679
5604
  // Reported from the checkpoint, never a re-read of the ticket, so a
3680
5605
  // retry reports exactly what the committed move did.
3681
- if (record.ticket !== undefined) {
5606
+ if (handback) {
3682
5607
  try {
3683
5608
  const returned = events.latestTicketReturned
3684
5609
  if (returned?.type !== 'abort.ticket-returned')
@@ -3708,11 +5633,54 @@ export class Dispatcher {
3708
5633
  type: 'build.completed',
3709
5634
  payload: { outcome: 'abandoned' },
3710
5635
  })
3711
- if (record.ticket !== undefined) await this.settleBuildHandback(record.slug)
5636
+ if (handback) await this.settleBuildHandback(record.slug)
3712
5637
  await this.reclaimPrAttachments(record.slug, events)
3713
5638
  report.abandoned += 1
3714
5639
  }
3715
5640
 
5641
+ /** Settle an optimization attempt its implementer declined (RFC 0005
5642
+ * §6.2): record `attempt.settled {declined}` on the node, release the
5643
+ * workspace and lease, then complete the build unmerged. The completion is
5644
+ * last, so a crash anywhere earlier retries on the next tick; an attempt no
5645
+ * longer in flight was already settled and is not settled again. The
5646
+ * node rejection sweep moves the ticket after completion. */
5647
+ private async settleDeclinedAttempt(record: BuildRecord, events: CurrentBuildFacts) {
5648
+ const store = this.store
5649
+ const declined = events.state.declined!
5650
+ const target = events.state.target
5651
+ const created = events.created
5652
+ // `ab done` refuses a decline outside an attempt, so a declined build
5653
+ // always targets a node; append nothing if that invariant is broken.
5654
+ if (target === undefined || created?.type !== 'build.created') return
5655
+ const node = (await store.buildFacts(target.build)).state
5656
+ const key = migrationIdentity(store.repositoryFacts().ticketMigrations, this.deps.tickets.name)
5657
+ const attempt = optimizationAttempt(node.optimization, created.payload.ticket, (ref) =>
5658
+ key(ref, record.slug),
5659
+ )
5660
+ if (attempt !== undefined)
5661
+ await settleAttempt(
5662
+ store,
5663
+ target.build,
5664
+ {
5665
+ proposal: attempt.proposal,
5666
+ ticket: attempt.ticket,
5667
+ build: record.slug,
5668
+ ...(record.branch !== undefined && attemptBranchPublished(events.state)
5669
+ ? { branch: record.branch }
5670
+ : {}),
5671
+ },
5672
+ 'declined',
5673
+ { note: declined.reason },
5674
+ )
5675
+ if (record.lease !== undefined) await store.releaseLease(record.slug, record.lease.holder)
5676
+ await this.releaseWorkspace(record.slug, events)
5677
+ await store.append(record.slug, {
5678
+ actor: DISPATCHER,
5679
+ type: 'build.completed',
5680
+ payload: { outcome: 'closed-unmerged' },
5681
+ } satisfies EventWrite<'build.completed'>)
5682
+ }
5683
+
3716
5684
  /** A discard is recovery from dispatcher plumbing, not judgment about the
3717
5685
  * ticket. Return it to the configured Ready state and terminalize last so
3718
5686
  * every partial cleanup is retried after a crash. */
@@ -3764,18 +5732,104 @@ export class Dispatcher {
3764
5732
  }
3765
5733
  } catch (error) {
3766
5734
  rethrowAuthorityLapse(error)
3767
- await this.store.append(record.slug, {
3768
- actor: KERNEL,
3769
- type: 'observation.recorded',
5735
+ await this.store.append(record.slug, {
5736
+ actor: KERNEL,
5737
+ type: 'observation.recorded',
5738
+ payload: {
5739
+ id: this.deps.ids('obs'),
5740
+ kind: 'followup',
5741
+ summary: `Merged commit ${sha} identity inspection failed; inspect its Autobuild-Build trailer manually: ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
5742
+ refs: [sha],
5743
+ },
5744
+ })
5745
+ return { sha }
5746
+ }
5747
+ }
5748
+
5749
+ /** Forge CI on a finished leaf (§15.7). Compares this poll's observation
5750
+ * with the reduced `ciFailure` in hand and appends only on a transition, so
5751
+ * an unchanged head reads no store rows. A failure recorded for a head the
5752
+ * PR no longer has is cleared first, on the proof of this poll's PR read
5753
+ * alone. Unknown CI (no capability, any read failure, a truncated listing
5754
+ * with no visible failure) records nothing: never green, never red, and
5755
+ * never a janitor failure. */
5756
+ private async observeHeadChecks(
5757
+ record: BuildRecord,
5758
+ state: BuildState,
5759
+ prState: Extract<PrState, { state: 'open' }>,
5760
+ workspacePath: string,
5761
+ ): Promise<void> {
5762
+ if (!ciChecksObservable(state)) return
5763
+ const pr = state.pr!
5764
+ const liveHead = prState.headSha ?? pr.headSha
5765
+ let prior = state.ciFailure
5766
+ const append = async (
5767
+ transition: (current: BuildState) => boolean,
5768
+ event: EventWrite<'pr.checks-failed'> | EventWrite<'pr.checks-cleared'>,
5769
+ ): Promise<void> => {
5770
+ const current = (await this.store.buildFacts(record.slug)).state
5771
+ if (!ciChecksObservable(current) || current.pr?.headSha !== pr.headSha) return
5772
+ if (!transition(current)) return
5773
+ // A lost race is observed again on the next poll.
5774
+ await this.store.appendIfCurrent(record.slug, current.lastSeq, event)
5775
+ }
5776
+ if (prior && (prior.head !== liveHead || prior.buildHead !== pr.headSha)) {
5777
+ const stale = prior
5778
+ await append(
5779
+ (current) =>
5780
+ current.ciFailure !== undefined &&
5781
+ ciFailureKey(current.ciFailure) === ciFailureKey(stale),
5782
+ {
5783
+ actor: DISPATCHER,
5784
+ type: 'pr.checks-cleared',
5785
+ payload: { pr: pr.number, head: stale.head, cause: 'head-changed' },
5786
+ },
5787
+ )
5788
+ prior = undefined
5789
+ }
5790
+ const forge = this.deps.forge
5791
+ if (!forge.inspectHeadChecks) return
5792
+ let checks: HeadChecks
5793
+ try {
5794
+ checks = await forge.inspectHeadChecks(workspacePath, liveHead)
5795
+ } catch (error) {
5796
+ rethrowAuthorityLapse(error)
5797
+ return
5798
+ }
5799
+ if (checks.kind === 'unknown') return
5800
+ if (checks.failing.length > 0) {
5801
+ const payload = {
5802
+ pr: pr.number,
5803
+ head: liveHead,
5804
+ buildHead: pr.headSha,
5805
+ checks: checks.failing.slice(0, CI_FAILURE_PREVIEW),
5806
+ total: checks.failing.length,
5807
+ digest: failingSetDigest(checks.failing),
5808
+ }
5809
+ const key = ciFailureKey(payload)
5810
+ if (prior && ciFailureKey(prior) === key) return
5811
+ await append(
5812
+ (current) => current.ciFailure === undefined || ciFailureKey(current.ciFailure) !== key,
5813
+ { actor: DISPATCHER, type: 'pr.checks-failed', payload },
5814
+ )
5815
+ return
5816
+ }
5817
+ if (!prior) return
5818
+ const cleared = prior
5819
+ await append(
5820
+ (current) =>
5821
+ current.ciFailure !== undefined &&
5822
+ ciFailureKey(current.ciFailure) === ciFailureKey(cleared),
5823
+ {
5824
+ actor: DISPATCHER,
5825
+ type: 'pr.checks-cleared',
3770
5826
  payload: {
3771
- id: this.deps.ids('obs'),
3772
- kind: 'followup',
3773
- summary: `Merged commit ${sha} identity inspection failed; inspect its Autobuild-Build trailer manually: ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
3774
- refs: [sha],
5827
+ pr: pr.number,
5828
+ head: cleared.head,
5829
+ cause: checks.pending ? 'pending' : 'passing',
3775
5830
  },
3776
- })
3777
- return { sha }
3778
- }
5831
+ },
5832
+ )
3779
5833
  }
3780
5834
 
3781
5835
  /** Post-PR epilogue (§15.7): poll the forge, emit `pr.*` facts (deduped
@@ -3787,6 +5841,8 @@ export class Dispatcher {
3787
5841
  source: {
3788
5842
  history: () => Promise<CurrentBuildFacts>
3789
5843
  workspace: OpenBuildWorkspace | null
5844
+ /** An execution is recorded open (started, not yet ended). */
5845
+ executionOpen: boolean
3790
5846
  observed?: (pr: Awaited<ReturnType<Forge['getPrState']>>) => void
3791
5847
  },
3792
5848
  state: BuildState,
@@ -4044,6 +6100,8 @@ export class Dispatcher {
4044
6100
  type: 'landing.command-acknowledged',
4045
6101
  payload: { commandSeq: command.seq },
4046
6102
  })
6103
+ if (!integration && !recoverLanding && prState.state === 'open')
6104
+ await this.observeHeadChecks(record, state, prState, workspacePath)
4047
6105
 
4048
6106
  // A positive conflict re-enters reconcile before any enable attempt. In
4049
6107
  // particular, an ungated fallback can never race ahead of the conflict
@@ -4071,6 +6129,7 @@ export class Dispatcher {
4071
6129
  // never blocks on guest bootstrap.
4072
6130
  const kicked = await this.ensureProvisionContinuation(record, events, 'launch')
4073
6131
  if (kicked === 'kicked') report.provisioning += 1
6132
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
4074
6133
  report.conflicted += 1
4075
6134
  return
4076
6135
  }
@@ -4189,55 +6248,92 @@ export class Dispatcher {
4189
6248
  })
4190
6249
  return
4191
6250
  }
4192
- const preflight = recoverLanding
4193
- ? undefined
4194
- : await preflightNodeLanding(
4195
- this.kernelForge(),
4196
- workspacePath,
6251
+ // A child of an optimization node also needs a fresh, decisive
6252
+ // measurement of its exact pair. Readiness above stays independent of
6253
+ // it, so a newly ready child reaches its first request.
6254
+ let measured: { candidate: string; baseline: string } | undefined
6255
+ let closure: Awaited<ReturnType<NonNullable<Forge['closePr']>>> | undefined
6256
+ const optimized = (await store.buildFacts(target.slug)).state.optimization !== undefined
6257
+ if (!recoverLanding && optimized) {
6258
+ const gate = await this.optimizationLandingGate(
6259
+ record,
6260
+ target.slug,
6261
+ workspacePath,
6262
+ pr.number,
6263
+ )
6264
+ if (gate.kind === 'wait') return
6265
+ if (gate.kind === 'land') measured = gate.measured
6266
+ else closure = gate.result
6267
+ }
6268
+ if (closure === undefined) {
6269
+ // Recovery of a reserved landing still publishes only a pair the
6270
+ // current gate lands: a revised epsilon or ruler since the
6271
+ // reservation makes the writer abandon it rather than publish, and
6272
+ // the next poll measures or settles it. A write that already
6273
+ // happened is recovered by readback before this check runs.
6274
+ const pair =
6275
+ recoverLanding && optimized && reservation
6276
+ ? { candidate: reservation.parent, baseline: reservation.expected }
6277
+ : measured
6278
+ const preflight = recoverLanding
6279
+ ? undefined
6280
+ : await preflightNodeLanding(
6281
+ this.kernelForge(),
6282
+ workspacePath,
6283
+ pr.number,
6284
+ record.branch,
6285
+ target.branch,
6286
+ )
6287
+ const reason =
6288
+ preflight ??
6289
+ (await this.withKernelRepository((kernelPath) =>
6290
+ landIntoNode({
6291
+ store,
6292
+ forge: this.kernelForge(),
6293
+ exec: forge.kernelExec ?? this.deps.exec,
6294
+ workspacePath: kernelPath,
6295
+ slug: record.slug,
6296
+ node: target.slug,
6297
+ branch: record.branch!,
6298
+ destination: target.branch!,
6299
+ pr: pr.number,
6300
+ holder: this.deps.ids('node-writer'),
6301
+ id: this.deps.ids('node-landing').replaceAll('_', '-'),
6302
+ ...(integration
6303
+ ? {
6304
+ stack: {
6305
+ head: state.integration!.cycle!.head,
6306
+ parent: state.integration!.cycle!.parent,
6307
+ cycle: state.integration!.cycle!.id,
6308
+ },
6309
+ }
6310
+ : {}),
6311
+ ...(pair !== undefined ? { measured: pair } : {}),
6312
+ eligible:
6313
+ pair === undefined
6314
+ ? canApply
6315
+ : async () =>
6316
+ (await canApply()) &&
6317
+ (await this.measuredPairCurrent(record, target.slug, pair)),
6318
+ }),
6319
+ ))
6320
+ if (reason && commandSeq !== undefined)
6321
+ await recordAutoMergeDeferralObservation(
6322
+ store,
6323
+ record.slug,
6324
+ reason,
4197
6325
  pr.number,
4198
- record.branch,
4199
- target.branch,
6326
+ commandSeq,
6327
+ this.deps.ids('obs'),
4200
6328
  )
4201
- const reason =
4202
- preflight ??
4203
- (await this.withKernelRepository((kernelPath) =>
4204
- landIntoNode({
4205
- store,
4206
- forge: this.kernelForge(),
4207
- exec: forge.kernelExec ?? this.deps.exec,
4208
- workspacePath: kernelPath,
4209
- slug: record.slug,
4210
- node: target.slug,
4211
- branch: record.branch!,
4212
- destination: target.branch!,
4213
- pr: pr.number,
4214
- holder: this.deps.ids('node-writer'),
4215
- id: this.deps.ids('node-landing').replaceAll('_', '-'),
4216
- ...(integration
4217
- ? {
4218
- stack: {
4219
- head: state.integration!.cycle!.head,
4220
- parent: state.integration!.cycle!.parent,
4221
- cycle: state.integration!.cycle!.id,
4222
- },
4223
- }
4224
- : {}),
4225
- eligible: canApply,
4226
- }),
4227
- ))
4228
- if (reason && commandSeq !== undefined)
4229
- await recordAutoMergeDeferralObservation(
4230
- store,
4231
- record.slug,
4232
- reason,
4233
- pr.number,
4234
- commandSeq,
4235
- this.deps.ids('obs'),
6329
+ if (
6330
+ (await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug
4236
6331
  )
4237
- if ((await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug)
4238
- return
6332
+ return
6333
+ }
4239
6334
  await store.refreshBuild(record.slug)
4240
6335
  state = (await store.buildFacts(record.slug)).state
6336
+ if (closure !== undefined) prState = closure
4241
6337
  if (state.prState === 'merged') {
4242
6338
  if (state.mergedSha) prState = { state: 'merged', sha: state.mergedSha }
4243
6339
  }
@@ -4537,8 +6633,10 @@ export class Dispatcher {
4537
6633
  if (state.prState === 'merged' && state.mergedSha)
4538
6634
  prState = { state: 'merged', sha: state.mergedSha }
4539
6635
  }
6636
+ let landed = integration && state.integration?.landing !== undefined
4540
6637
  if (integration && prState.state === 'merged' && !state.integration?.landing) {
4541
6638
  const head = prState.headSha
6639
+ landed = true
4542
6640
  await store.append(record.slug, {
4543
6641
  actor: DISPATCHER,
4544
6642
  type: 'integration.landed',
@@ -4552,11 +6650,19 @@ export class Dispatcher {
4552
6650
  })
4553
6651
  }
4554
6652
 
6653
+ // A landing ends the node's verification: withdraw the runner's lease so
6654
+ // its next heartbeat stops the work. One write, no reads; it repeats only
6655
+ // while that runner still holds a live lease.
6656
+ if (landed && executionLeaseLive && record.lease !== undefined)
6657
+ await store.releaseLease(record.slug, record.lease.holder)
6658
+ // A withdrawn lease is not an ended execution: settle only once the
6659
+ // landed node's runner has recorded its end.
6660
+ const executionLive = executionLeaseLive || (landed && source.executionOpen)
4555
6661
  if (
4556
6662
  integration &&
4557
6663
  (prState.state === 'merged' || prState.state === 'closed') &&
4558
6664
  record.branch &&
4559
- !executionLeaseLive
6665
+ !executionLive
4560
6666
  ) {
4561
6667
  if (
4562
6668
  !(await this.withKernelRepository((kernelPath) =>
@@ -4575,7 +6681,7 @@ export class Dispatcher {
4575
6681
  }
4576
6682
  switch (prState.state) {
4577
6683
  case 'merged': {
4578
- if (executionLeaseLive) return
6684
+ if (executionLive) return
4579
6685
  const events = await source.history()
4580
6686
  if (!landingAuthorized(state.landing) && !state.landing?.forgeMerge) {
4581
6687
  // Use our durable native-effect evidence, never provider origin.
@@ -4615,6 +6721,9 @@ export class Dispatcher {
4615
6721
  // Before the child can become terminal, so a complete node already
4616
6722
  // folds every landed child's links; the node log dedupes a retry.
4617
6723
  await this.recordNodeIssueLinks(record.slug)
6724
+ // A merged attempt settles `accepted` with the measurement of the
6725
+ // head that landed, before the build can become terminal.
6726
+ if (nodeTarget) await this.settleMergedAttempt(record, state, prState.sha)
4618
6727
  await this.releaseWorkspace(record.slug, events)
4619
6728
  if (record.ticket) {
4620
6729
  await tickets.transition(await this.currentTicketId(record), this.doneState)
@@ -4633,7 +6742,7 @@ export class Dispatcher {
4633
6742
  return
4634
6743
  }
4635
6744
  case 'closed': {
4636
- if (executionLeaseLive) return
6745
+ if (executionLive) return
4637
6746
  const events = await source.history()
4638
6747
  // Closed without merge is a human decision — back to Triage (§15.7).
4639
6748
  if (state.prState !== 'closed') {
@@ -4644,20 +6753,38 @@ export class Dispatcher {
4644
6753
  } satisfies EventWrite<'pr.closed'>)
4645
6754
  }
4646
6755
  await this.releaseWorkspace(record.slug, events)
4647
- await this.returnBuildTicket(
4648
- record,
4649
- events,
4650
- 'pr-closed',
4651
- 'triage',
4652
- (state) =>
4653
- `build ${record.slug} PR closed without merging (${pr.url}) — returned to ${state}`,
4654
- )
6756
+ // A closed attempt goes to the rejected role through its node's
6757
+ // sweep, never back to triage. One a human closed settles `aborted`.
6758
+ const attempt = nodeTarget
6759
+ ? await this.terminalAttempt(record, state)
6760
+ : { node: '', status: 'none' as const }
6761
+ if (attempt.status === 'in-flight')
6762
+ await settleAttempt(
6763
+ store,
6764
+ attempt.node,
6765
+ {
6766
+ proposal: attempt.attempt!.proposal,
6767
+ ticket: attempt.attempt!.ticket,
6768
+ build: record.slug,
6769
+ },
6770
+ 'aborted',
6771
+ { note: `PR ${pr.url} closed without merging` },
6772
+ )
6773
+ if (attempt.status === 'none')
6774
+ await this.returnBuildTicket(
6775
+ record,
6776
+ events,
6777
+ 'pr-closed',
6778
+ 'triage',
6779
+ (state) =>
6780
+ `build ${record.slug} PR closed without merging (${pr.url}) — returned to ${state}`,
6781
+ )
4655
6782
  await store.append(record.slug, {
4656
6783
  actor: DISPATCHER,
4657
6784
  type: 'build.completed',
4658
6785
  payload: { outcome: 'closed-unmerged' },
4659
6786
  } satisfies EventWrite<'build.completed'>)
4660
- if (record.ticket) await this.settleBuildHandback(record.slug)
6787
+ if (record.ticket && attempt.status === 'none') await this.settleBuildHandback(record.slug)
4661
6788
  await this.reclaimPrAttachments(record.slug, events)
4662
6789
  report.closed += 1
4663
6790
  return
@@ -4719,25 +6846,73 @@ export class Dispatcher {
4719
6846
  }
4720
6847
  }
4721
6848
 
6849
+ /** `signal` is a continuation's teardown token: a provider call that
6850
+ * rejects after teardown records no cleanup fact, so the abandoned marker
6851
+ * stays adoptable in the same generation. */
4722
6852
  private async provisionWorkspace(
4723
6853
  slug: string,
4724
6854
  input: Parameters<WorkspaceProvider['provision']>[0],
6855
+ signal?: AbortSignal,
4725
6856
  ) {
4726
6857
  const facts = (await readBuildFacts(this.store, slug)).value
4727
6858
  const { restoration, superseded } = supersedeRestorationHeads(
4728
6859
  facts.workspacePreservation?.payload.heads,
4729
6860
  facts.replacedHeads,
4730
6861
  )
6862
+ const local = this.deps.forge.name === 'local-git'
6863
+ // A leaf's first provision never adopts a pre-existing branch (#1261).
6864
+ // A node is exempt: the kernel opens its branch before any provision and
6865
+ // children merge into it, so that branch is the node's own work.
6866
+ // `owner` is unique to this build (an earlier same-slug build in another
6867
+ // store has another creation time) and stable across its retries.
6868
+ const fresh =
6869
+ facts.state.kind !== 'node' &&
6870
+ facts.workspaceGenerations === 0 &&
6871
+ input.revision === undefined &&
6872
+ input.generation === undefined &&
6873
+ input.baseBranch !== input.branch &&
6874
+ facts.created !== undefined
6875
+ ? {
6876
+ owner: createHash('sha256')
6877
+ .update(`${slug}\0${facts.created.ts}`)
6878
+ .digest('hex')
6879
+ .slice(0, 32),
6880
+ }
6881
+ : undefined
4731
6882
  try {
4732
6883
  const handle = await this.deps.workspaces.provision({
4733
6884
  ...input,
6885
+ ...(fresh !== undefined ? { fresh } : {}),
4734
6886
  restoration,
4735
6887
  ...(facts.replacedHeads.length ? { restorationReplaced: facts.replacedHeads } : {}),
6888
+ // Store reads happen only while provisioning a build whose receipt
6889
+ // keeps some head in the BuildStore.
6890
+ ...(restoration?.some((head) => head.storeBase !== undefined)
6891
+ ? {
6892
+ restoreStored: ({ exec, workspacePath, sha }) =>
6893
+ restoreRetainedHead(
6894
+ {
6895
+ store: this.store,
6896
+ slug,
6897
+ exec,
6898
+ workspacePath,
6899
+ local,
6900
+ branch: input.branch,
6901
+ targetBranch: facts.state.baseBranch ?? input.baseBranch,
6902
+ exclude: sha,
6903
+ archive: async () => {
6904
+ throw new Error('restore only')
6905
+ },
6906
+ },
6907
+ sha,
6908
+ ),
6909
+ }
6910
+ : {}),
4736
6911
  // Same predicate preservation archives under: only local-git keeps
4737
6912
  // archive refs in the local repository.
4738
6913
  ...(restoration?.length
4739
6914
  ? {
4740
- restorationArchives: this.deps.forge.name === 'local-git' ? 'local' : 'remote',
6915
+ restorationArchives: local ? 'local' : 'remote',
4741
6916
  }
4742
6917
  : {}),
4743
6918
  })
@@ -4747,7 +6922,7 @@ export class Dispatcher {
4747
6922
  ]
4748
6923
  return skipped.length ? { ...handle, restorationSkipped: skipped } : handle
4749
6924
  } catch (error) {
4750
- if (error instanceof WorkspaceCleanupRequired) {
6925
+ if (error instanceof WorkspaceCleanupRequired && signal?.aborted !== true) {
4751
6926
  await this.store.append(slug, {
4752
6927
  actor: DISPATCHER,
4753
6928
  type: 'workspace.cleanup-required',
@@ -4816,6 +6991,33 @@ export class Dispatcher {
4816
6991
  return this.deps.retiredWorkspaces?.find((provider) => provider.name === open.provider) ?? null
4817
6992
  }
4818
6993
 
6994
+ /** A workspace a provider flagged `cleanup-required` is fenced, cleaned up
6995
+ * and released before its build's next generation is provisioned (leaf
6996
+ * dispatch retry, node verification and node conflict tails alike).
6997
+ * Returns the facts to continue from, or `undefined` when this tick must
6998
+ * stop: a foreign continuation holds a live lease, or the reap failed,
6999
+ * which is already durable against the build. */
7000
+ private async replaceFlaggedWorkspace(
7001
+ record: BuildRecord,
7002
+ facts: CurrentBuildFacts,
7003
+ launched: Set<string> | undefined,
7004
+ ): Promise<CurrentBuildFacts | undefined> {
7005
+ const flagged = openWorkspace(facts)
7006
+ if (
7007
+ flagged === null ||
7008
+ !cleanupRequiredWorkspace(facts) ||
7009
+ this.workspaceOwner(flagged)?.recovery === undefined
7010
+ )
7011
+ return facts
7012
+ if (this.hasLiveExecutionLease(record)) return undefined
7013
+ if (!(await this.reapStaleWorkspace(record.slug, facts, 'replacement'))) {
7014
+ // Also keeps this tick's sweep from reaping the same build again.
7015
+ launched?.add(record.slug)
7016
+ return undefined
7017
+ }
7018
+ return (await readBuildFacts(this.store, record.slug)).value
7019
+ }
7020
+
4819
7021
  /** Fence and remove a stale remote environment. A replacement is created
4820
7022
  * only after exact-name cleanup is durably acknowledged. */
4821
7023
  private async reapStaleWorkspace(
@@ -5079,6 +7281,7 @@ export class Dispatcher {
5079
7281
  kind?: 'work' | 'node'
5080
7282
  target?: EventPayload<'build.created'>['target']
5081
7283
  baseBranch?: string
7284
+ priority?: 'urgent'
5082
7285
  }
5083
7286
  | undefined,
5084
7287
  ): EventPayload<'build.created'> {
@@ -5104,9 +7307,17 @@ export class Dispatcher {
5104
7307
  }
5105
7308
  : {}),
5106
7309
  ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
7310
+ ...(seed?.priority !== undefined ? { priority: seed.priority } : {}),
5107
7311
  }
5108
7312
  }
5109
7313
 
7314
+ /** The claimed ticket's priority, frozen on `build.created`; normal is omitted. */
7315
+ private claimedPriority(ticket: Ticket): { priority?: 'urgent' } {
7316
+ return this.deps.tickets.priority && ticketPriority(ticket) === 'urgent'
7317
+ ? { priority: 'urgent' }
7318
+ : {}
7319
+ }
7320
+
5110
7321
  /** Every boundary before runner attachment is derived from durable facts.
5111
7322
  * Missing facts are the todo list; successful provider calls are followed
5112
7323
  * immediately by their facts, so an ordinary later tick can continue. */
@@ -5174,6 +7385,7 @@ export class Dispatcher {
5174
7385
  ? { issueLinks: seed.ticket.issueLinks }
5175
7386
  : {}),
5176
7387
  ...(seed !== undefined ? this.selectedProfile(seed.ticket) : {}),
7388
+ ...(seed !== undefined ? this.claimedPriority(seed.ticket) : {}),
5177
7389
  }),
5178
7390
  })
5179
7391
  events = (await readBuildFacts(store, record.slug)).value
@@ -5187,23 +7399,13 @@ export class Dispatcher {
5187
7399
  return this.completeDispatchBoundaries(record, seed, report, launched)
5188
7400
 
5189
7401
  stage = 'workspace'
5190
- const flagged = openWorkspace(events)
5191
- if (
5192
- flagged !== null &&
5193
- cleanupRequiredWorkspace(events) &&
5194
- this.workspaceOwner(flagged)?.recovery !== undefined
5195
- ) {
5196
- // A retry never launches into a flagged environment: release it, then
5197
- // provision the next generation below. A live lease means a foreign
5198
- // continuation still owns the build.
5199
- if (this.hasLiveExecutionLease(record)) return 'parked'
5200
- if (!(await this.reapStaleWorkspace(record.slug, events, 'replacement'))) {
5201
- // The failure is already durable against this build.
5202
- launched.add(record.slug)
5203
- return 'parked'
5204
- }
5205
- events = (await readBuildFacts(store, record.slug)).value
5206
- }
7402
+ // A retry never launches into a flagged environment: release it, then
7403
+ // provision the next generation below. A live lease means a foreign
7404
+ // continuation still owns the build; a failed reap is already durable
7405
+ // against it.
7406
+ const replaced = await this.replaceFlaggedWorkspace(record, events, launched)
7407
+ if (replaced === undefined) return 'parked'
7408
+ events = replaced
5207
7409
  if (openWorkspace(events) === null) {
5208
7410
  if (this.deps.workspaces.recovery !== undefined) {
5209
7411
  // Recovery-capable provider: durable marker + tracked background
@@ -5212,6 +7414,7 @@ export class Dispatcher {
5212
7414
  // and the launch.
5213
7415
  const kicked = await this.ensureProvisionContinuation(record, events, 'dispatch', seed)
5214
7416
  if (kicked === 'kicked') report.provisioning += 1
7417
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
5215
7418
  launched.add(record.slug)
5216
7419
  return 'deferred'
5217
7420
  }
@@ -5326,11 +7529,21 @@ export class Dispatcher {
5326
7529
  }
5327
7530
 
5328
7531
  let body = seed?.body ?? ticket.body
7532
+ const refusals = objectiveRefusals(body, {
7533
+ kind: state.kind ?? 'work',
7534
+ rejectedState: this.rejectedState(),
7535
+ })
7536
+ if (refusals.length > 0)
7537
+ throw new Error(`claimed ticket's spec cannot open as dispatched: ${refusals.join('; ')}`)
5329
7538
  let conformance = specConformance(body)
5330
7539
  let authoredSession = seed?.authoredSession
5331
- if (!conformance.conforms && this.deps.authorSpec !== undefined) {
7540
+ if (
7541
+ !conformance.conforms &&
7542
+ objectiveBlocks(body).length === 0 &&
7543
+ this.deps.authorSpec !== undefined
7544
+ ) {
5332
7545
  const candidate = await this.deps.authorSpec(ticket)
5333
- if (candidate !== null) {
7546
+ if (candidate !== null && objectiveBlocks(candidate).length === 0) {
5334
7547
  conformance = specConformance(candidate)
5335
7548
  if (conformance.conforms) {
5336
7549
  body = candidate
@@ -5664,7 +7877,7 @@ export class Dispatcher {
5664
7877
  /**
5665
7878
  * End open ticket waits whose tickets settled (SPEC §11 "Ticket waits").
5666
7879
  * Every waited ticket completed: `wait.ended {cause: automatic}`, and the
5667
- * build resumes ahead of new claims. Any waited ticket rejected (the
7880
+ * build resumes ahead of normal claims. Any waited ticket rejected (the
5668
7881
  * configured rejected role) or deleted: one `policy/wait-unresolvable`
5669
7882
  * escalation naming it, which the reducer reads as the wait's end. A wait
5670
7883
  * with tickets still pending stays in place.
@@ -5818,6 +8031,56 @@ export class Dispatcher {
5818
8031
  }
5819
8032
  }
5820
8033
 
8034
+ /**
8035
+ * Decide a parked attempt's sampled measurement (SPEC §13.1.1): a
8036
+ * command's medians or a judge panel's win rate. The attempt's runner
8037
+ * holds only its own build, so it records the samples and the dispatcher
8038
+ * records `attempt.measured` against the node's ε and starting spread as
8039
+ * they stand now, or a `policy/measurement-failed`
8040
+ * escalation when the node's ruler or harness pin moved past the request.
8041
+ *
8042
+ * Cost: the sampled-but-undecided check reads the reduced state the sweep
8043
+ * already holds, so a tick with nothing sampled reads nothing more. One
8044
+ * record lookup and one reduced read of the node per sampled request, once:
8045
+ * either append makes the request no longer pending. A lost race is
8046
+ * decided again next tick.
8047
+ */
8048
+ private async recordSampledMeasurement(slug: string, state: BuildState): Promise<void> {
8049
+ const sampled = sampledMeasurement(state)
8050
+ const request = state.attemptMeasurement?.request
8051
+ if (sampled === undefined || request === undefined) return
8052
+ const { seq: _seq, ...requested } = request
8053
+ // A missing node is refused once rather than failing every tick.
8054
+ const decided =
8055
+ (await this.store.getBuild(request.node)) === null
8056
+ ? { refusal: `node ${request.node} does not exist` }
8057
+ : decideSampledMeasurement(
8058
+ (await readBuildFacts(this.store, request.node)).value.state,
8059
+ requested,
8060
+ sampled,
8061
+ )
8062
+ if ('measured' in decided)
8063
+ await this.store.appendIfCurrent(slug, state.lastSeq, {
8064
+ actor: DISPATCHER,
8065
+ type: 'attempt.measured',
8066
+ payload: decided.measured,
8067
+ })
8068
+ else
8069
+ await this.store.appendIfCurrent(slug, state.lastSeq, {
8070
+ actor: DISPATCHER,
8071
+ type: 'escalation.raised',
8072
+ payload: {
8073
+ id: this.deps.ids('esc'),
8074
+ phase: 'measurement',
8075
+ source: 'policy',
8076
+ policyCause: 'measurement-failed',
8077
+ question:
8078
+ `Measurement request ${request.id} was sampled but cannot be decided: ${decided.refusal}. ` +
8079
+ 'No result was recorded; the attempt needs a fresh measurement request under the current ruler.',
8080
+ },
8081
+ })
8082
+ }
8083
+
5821
8084
  /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
5822
8085
  private async sweepBuild(
5823
8086
  record: BuildRecord,
@@ -5881,7 +8144,11 @@ export class Dispatcher {
5881
8144
  // The engine reached the end of the pipeline: record it once per
5882
8145
  // settlement key so capacity stops counting the parked build. A lost
5883
8146
  // race is decided again next tick.
5884
- if (settlementDue(state))
8147
+ // A sampled measurement is decided first: the attempt's landing waits
8148
+ // on it, while settlement only frees capacity and follows next tick.
8149
+ if (sampledMeasurement(state) !== undefined)
8150
+ await this.recordSampledMeasurement(record.slug, state)
8151
+ else if (settlementDue(state))
5885
8152
  await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5886
8153
  actor: DISPATCHER,
5887
8154
  type: 'pipeline.settled',
@@ -5891,7 +8158,7 @@ export class Dispatcher {
5891
8158
  const orphanEligible = (state: BuildState) =>
5892
8159
  !paused &&
5893
8160
  state.status === 'running' &&
5894
- (state.kind !== 'node' || integrationCurrent(state)) &&
8161
+ (state.kind !== 'node' || (integrationCurrent(state) && !nodeLanded(state))) &&
5895
8162
  state.sessions.open.some((session) => session.suspensionCause === undefined)
5896
8163
  const provedEnded =
5897
8164
  facts.open === null &&
@@ -5909,7 +8176,12 @@ export class Dispatcher {
5909
8176
  if (
5910
8177
  state.kind === 'node' &&
5911
8178
  (!integrationCurrent(state) || facts.workspace === null) &&
5912
- decision.kind !== 'wait'
8179
+ decision.kind !== 'wait' &&
8180
+ // An ended or crashed node measurement re-attaches to its workspace.
8181
+ !(
8182
+ (decision.kind === 'measure-baseline' || decision.kind === 'measure-progress') &&
8183
+ facts.workspace !== null
8184
+ )
5913
8185
  )
5914
8186
  return // cascade owns node runner admission
5915
8187
  // Raw history, read at most once and only by a branch that acts on it.
@@ -5984,7 +8256,7 @@ export class Dispatcher {
5984
8256
  const runs = decision.kind !== 'wait' || publicationRecoveryDue || orphanRecoveryDue
5985
8257
  // A finished leaf with work to run waits for a slot before anything is
5986
8258
  // reaped, provisioned or launched for it.
5987
- if (runs && state.kind !== 'node' && !(await this.leafAdmission(record.slug))) return
8259
+ if (runs && state.kind !== 'node' && (await this.leafAdmission(record.slug)) !== 'admit') return
5988
8260
  // A finished parked leaf keeps its workspace until merge or close; a
5989
8261
  // stale environment is reaped only for an admitted replacement.
5990
8262
  // A leaf waiting on tickets, or on the dispatcher's check of its wait,
@@ -6020,7 +8292,7 @@ export class Dispatcher {
6020
8292
  if (kicked === 'kicked') {
6021
8293
  report.provisioning += 1
6022
8294
  report.swept += 1
6023
- }
8295
+ } else if (kicked === 'budget-wait') report.provisioningDeferred += 1
6024
8296
  return
6025
8297
  }
6026
8298
  }
@@ -6043,8 +8315,10 @@ export class Dispatcher {
6043
8315
  report.swept += 1
6044
8316
  return
6045
8317
  }
8318
+ if (kicked === 'budget-wait') report.provisioningDeferred += 1
6046
8319
  // In-flight or foreign-live: whoever owns the marker completes the
6047
- // boundaries and the launch; this tick performs neither.
8320
+ // boundaries and the launch; this tick performs neither. A budget wait
8321
+ // leaves both to a later invocation.
6048
8322
  return
6049
8323
  }
6050
8324
  try {
@@ -6281,48 +8555,116 @@ export class Dispatcher {
6281
8555
  paused: boolean,
6282
8556
  opts: TickOpts = {},
6283
8557
  autoMergeSeedFact: AutoMergeDefaultFact | undefined = undefined,
8558
+ /** Operator start requests: admit exactly these tickets through every
8559
+ * gate below, without the ready listing or the scan checkpoint, and record
8560
+ * each ticket's outcome. The standing report fields are not published. */
8561
+ targeted?: TargetedDispatch,
6284
8562
  ): Promise<void> {
6285
- if (!this.accountsAvailable()) return
6286
- const health = this.store.repositoryFacts().forgeHealth
6287
- if (health && Date.parse(health.resetAt) > this.deps.clock().getTime()) return
8563
+ if (!this.claimGateOpen()) return
6288
8564
  const store = this.store
6289
8565
  const { tickets, config } = this.deps
6290
- const checkpoint = await this.scanCheckpoint('admission')
6291
- if (!checkpoint.due) return
8566
+ // A normal parked admission deferred this tick waits on urgent claims:
8567
+ // list now, once per deferral key; an unchanged key waits for a scan that
8568
+ // is due on its own.
8569
+ let force = false
8570
+ let deferralBuilds: CapacityBuild[] | undefined
8571
+ if (!targeted && this.deferredAdmissions.size > 0) {
8572
+ deferralBuilds = await this.capacityBuilds(launched)
8573
+ const key = this.deferralKey(
8574
+ dispatchCapacity(deferralBuilds, config.capacity, this.deps.clock()).occupied,
8575
+ )
8576
+ if (key !== this.lastForcedDeferralKey) {
8577
+ force = true
8578
+ this.forcedDeferralKey = key
8579
+ }
8580
+ }
8581
+ const checkpoint = targeted ? undefined : await this.scanCheckpoint('admission', { force })
8582
+ if (checkpoint !== undefined && !checkpoint.due) return
8583
+ const settle = (ticket: Ticket, outcome: TargetedOutcome) =>
8584
+ targeted?.outcomes.set(ticket.ref.id, outcome)
6292
8585
  // Clear only standing measurement fields; action counters belong to this tick.
6293
- report.queued = report.invalidTickets = report.dependencyBlocked = report.creationWithheld = 0
6294
- report.ticketDiagnostics = []
6295
- report.dependencyDiagnostics = []
6296
- report.creationDiagnostics = []
8586
+ if (!targeted) {
8587
+ report.queued = report.invalidTickets = report.dependencyBlocked = report.creationWithheld = 0
8588
+ report.ticketDiagnostics = []
8589
+ report.dependencyDiagnostics = []
8590
+ report.creationDiagnostics = []
8591
+ }
6297
8592
  // Capacity counts builds running work. An unfinished build holds its slot
6298
8593
  // even while blocked or paused; a finished build parked for its merge
6299
8594
  // decision holds none. Capacity is per repo (§16.1) — another repo's
6300
8595
  // builds never consume this repo's slots.
6301
- const capacityBuilds = await this.capacityBuilds(launched)
8596
+ // The checkpoint writes nothing, so a deferral capacity read is current.
8597
+ const capacityBuilds =
8598
+ targeted?.measured ?? deferralBuilds ?? (await this.capacityBuilds(launched))
6302
8599
  // A node awaiting verification, or a parked build that must run again,
6303
- // reserves its slot ahead of new claims until it is admitted; this only
6304
- // ever lowers the claim budget.
6305
- const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock())
8600
+ // reserves its slot ahead of claims of its own or a lower priority until
8601
+ // it is admitted; this only ever lowers the claim budgets. Urgent claims
8602
+ // wait only for urgent parked work (SPEC §12 "Slot admission order").
8603
+ // Open-PR backpressure gates new normal-priority claims only: admission,
8604
+ // the janitor, reconciles, landings and urgent claims are untouched, and
8605
+ // capacity accounting is unchanged. Engagement is a durable repository
8606
+ // fact recorded only on transitions, so hysteresis survives restarts.
8607
+ const engagement = this.store.repositoryFacts().openPrBackpressure
8608
+ const engaged = engagement !== undefined
8609
+ const backpressure = openPrBackpressure(
8610
+ capacityBuilds,
8611
+ openPrBackpressurePolicy(config.policy),
8612
+ engaged,
8613
+ )
8614
+ // Pending start requests reserve ahead of the ordinary claims they outrank.
8615
+ const projection = dispatchCapacity(
8616
+ capacityBuilds,
8617
+ config.capacity,
8618
+ this.deps.clock(),
8619
+ undefined,
8620
+ { openPrs: { policy: config.policy, engaged }, startRequests: this.startClaims() },
8621
+ )
8622
+ const transition = backpressureTransition(
8623
+ backpressure,
8624
+ engaged,
8625
+ backpressure?.openPrs ?? openPrCount(capacityBuilds, engagement?.excludeHeld ?? false),
8626
+ )
8627
+ if (!targeted && transition && this.deps.holdsRepoAuthority?.() !== false) {
8628
+ await store.ensureRepo(this.deps.repo)
8629
+ await store.appendRepo(this.deps.repo, { actor: DISPATCHER, ...transition })
8630
+ }
8631
+ const normalPaused = backpressure?.active === true
6306
8632
  const activeRefs: TicketRef[] = capacityBuilds
6307
8633
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
6308
8634
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
6309
- let capacity = intakeCapacity(projection, {
6310
- settled: this.parkedSettled,
6311
- denied: this.slotWaiters,
6312
- })
8635
+ const adjust = { settled: this.parkedSettled, denied: this.slotWaiters }
8636
+ let capacity = intakeCapacity(projection, adjust)
8637
+ let urgentCapacity = intakeCapacity(projection, adjust, 'urgent')
8638
+ let urgentWaiting = 0
8639
+ // Each ready ticket's claim tier: an optimization attempt claims at its
8640
+ // node's current build priority, any other ticket at its own priority
8641
+ // when the source stores one. Filled once the claimable set is known.
8642
+ let attemptTiers = new Map<string, TicketPriority>()
8643
+ const tierOf = (ticket: Ticket): TicketPriority =>
8644
+ attemptTiers.get(ticket.ref.id) ?? (tickets.priority ? ticketPriority(ticket) : 'normal')
8645
+ const urgentClaim = (ticket: Ticket) =>
8646
+ !targeted && ticket.kind !== 'node' && tierOf(ticket) === 'urgent'
8647
+ // A targeted ticket's tier is its request's, never its ticket's priority.
8648
+ const startTier = (ticket: Ticket): TicketStartPriority =>
8649
+ targeted?.requests.get(ticket.ref.id)?.priority ?? 'manual'
6313
8650
 
6314
8651
  // The ready scan runs even at full capacity: `queued` is the operator's
6315
8652
  // standing queue-depth report and must stay honest exactly when the
6316
8653
  // dispatcher is saturated. Sources that keep a claimed ticket in the
6317
8654
  // ready state are deduped against the active builds embodying them.
6318
8655
  const journalBeforeReady = this.store.repositoryFacts().harvest
6319
- const listing = await this.listReady()
6320
- const activeTicketIds = await this.activeTicketIdentities(activeRefs, listing.tickets)
8656
+ const listing = targeted
8657
+ ? { tickets: targeted.tickets, diagnostics: [] as string[] }
8658
+ : await this.listReady()
8659
+ // Targeted admission never fans `get` out over unrelated active builds:
8660
+ // its caller matched them without source reads (see honorStartRequests).
8661
+ const activeTicketIds =
8662
+ targeted?.activeIds ?? (await this.activeTicketIdentities(activeRefs, listing.tickets))
6321
8663
  // A provider listing can race reservation and blocker filing. Preserve
6322
8664
  // the before/after union, refreshing once only when admission is possible.
6323
8665
  if (listing.tickets.length > 0) await this.store.refreshJournal()
6324
8666
  const journalAfterReady = this.store.repositoryFacts()
6325
- if (journalAfterReady.health?.cause === 'ready-scan-failed') {
8667
+ if (!targeted && journalAfterReady.health?.cause === 'ready-scan-failed') {
6326
8668
  await this.sourceCondition(undefined, 'ready-scan')
6327
8669
  }
6328
8670
  const creationHolds = new Map(
@@ -6331,6 +8673,7 @@ export class Dispatcher {
6331
8673
  creation,
6332
8674
  ]),
6333
8675
  )
8676
+ const attemptHolds = await this.optimizationCreationHolds()
6334
8677
  const eligible = listing.tickets.filter(
6335
8678
  (ticket) =>
6336
8679
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
@@ -6340,15 +8683,35 @@ export class Dispatcher {
6340
8683
  // unchanged; a source without the priority capability is all normal.
6341
8684
  // A ticket whose labels select two profiles is never claimed (SPEC §9).
6342
8685
  const conflicts = this.profileConflicts(eligible)
8686
+ // Conflicts and their diagnostics are produced in the same order.
8687
+ for (const [index, ticket] of [...conflicts.tickets].entries())
8688
+ settle(ticket, { outcome: 'invalid', detail: conflicts.diagnostics[index]! })
6343
8689
  const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
6344
- const ready = this.deps.tickets.priority ? urgentFirst(claimable) : claimable
8690
+ if (!targeted) attemptTiers = await this.attemptClaimTiers(claimable)
8691
+ // A targeted pass keeps its tier-then-request order.
8692
+ const ready = targeted ? claimable : urgentFirstBy(claimable, tierOf)
6345
8693
  report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
6346
8694
  report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
8695
+ if (!targeted && normalPaused)
8696
+ report.ticketDiagnostics.push(backpressureExplanation(backpressure))
6347
8697
  report.queued = ready.length
6348
8698
  const withheld = new Set<string>()
6349
8699
  for (const ticket of ready) {
6350
8700
  if (ticket.creationKey === undefined) continue
6351
- const creation = creationHolds.get(ticket.creationKey.toLowerCase())
8701
+ const key = ticket.creationKey.toLowerCase()
8702
+ const attempt = attemptHolds.failure ?? attemptHolds.holds.get(key)
8703
+ if (attempt !== undefined) {
8704
+ withheld.add(ticket.ref.id)
8705
+ report.creationWithheld += 1
8706
+ report.creationDiagnostics.push(
8707
+ typeof attempt === 'string'
8708
+ ? `ticket ${ticket.ref.id}: creation withheld — ${attempt}`
8709
+ : `ticket ${ticket.ref.id}: creation withheld — optimization node ${attempt.node}, ` +
8710
+ `proposal request ${attempt.request} has not recorded its attempts`,
8711
+ )
8712
+ continue
8713
+ }
8714
+ const creation = creationHolds.get(key)
6352
8715
  if (creation === undefined) continue
6353
8716
  withheld.add(ticket.ref.id)
6354
8717
  report.creationWithheld += 1
@@ -6366,17 +8729,32 @@ export class Dispatcher {
6366
8729
  // still runs either way, so the standing queue-depth report stays honest —
6367
8730
  // this only declines to claim a ticket into a build that would immediately
6368
8731
  // sit held.
8732
+ // Saturated, an urgent ticket still runs the preflight: it claims an
8733
+ // urgent budget, or counts as urgent demand waiting for a slot.
8734
+ const urgentReady = ready.some((ticket) => urgentClaim(ticket) && !withheld.has(ticket.ref.id))
8735
+ const noBudget = targeted
8736
+ ? ready.every((ticket) => targeted.budgets[startTier(ticket)] <= 0)
8737
+ : capacity <= 0 && !urgentReady
6369
8738
  if (
6370
8739
  paused ||
6371
- (capacity <= 0 &&
8740
+ (!targeted &&
8741
+ normalPaused &&
8742
+ !ready.some((ticket) => tierOf(ticket) === 'urgent' && !withheld.has(ticket.ref.id))) ||
8743
+ (noBudget &&
6372
8744
  !ready.some(
6373
8745
  (ticket) =>
6374
- ticket.kind === 'node' ||
6375
- (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0),
8746
+ (targeted || !normalPaused || tierOf(ticket) === 'urgent') &&
8747
+ (ticket.kind === 'node' ||
8748
+ (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0)),
6376
8749
  ))
6377
8750
  ) {
8751
+ if (checkpoint === undefined) return
6378
8752
  await this.sourceCondition(undefined, 'ready-scan')
6379
- if (!this.outOfBudget(opts)) await this.completeScan(checkpoint, report)
8753
+ if (!this.outOfBudget(opts)) {
8754
+ await this.completeScan(checkpoint, report)
8755
+ // No urgent ticket is ready: this scan decided urgent claims.
8756
+ if (!paused) this.urgentEvaluated = true
8757
+ }
6380
8758
  return
6381
8759
  }
6382
8760
  // One dependency-node cache per scan: blockers are commonly shared across
@@ -6460,6 +8838,7 @@ export class Dispatcher {
6460
8838
  targetBlocked.add(ticket.ref.id)
6461
8839
  report.dependencyBlocked += 1
6462
8840
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
8841
+ settle(ticket, { outcome: 'blocked', detail: target })
6463
8842
  continue
6464
8843
  }
6465
8844
  preflightTargets.set(ticket.ref.id, JSON.stringify(target))
@@ -6555,23 +8934,47 @@ export class Dispatcher {
6555
8934
  })
6556
8935
  }
6557
8936
  }
6558
- for (const verdict of verdicts.values()) {
8937
+ for (const [id, verdict] of verdicts) {
6559
8938
  if (verdict.unresolved.length > 0) {
6560
8939
  report.dependencyBlocked += 1
6561
8940
  report.dependencyDiagnostics.push(...verdict.diagnostics)
8941
+ targeted?.outcomes.set(id, {
8942
+ outcome: 'blocked',
8943
+ detail:
8944
+ verdict.diagnostics.join('; ') ||
8945
+ `unresolved blockers: ${verdict.unresolved.join(', ')}`,
8946
+ })
6562
8947
  }
6563
8948
  }
8949
+ let claimLoopCompleted = true
6564
8950
  for (const ticket of ready) {
6565
- if (this.outOfBudget(opts)) break
6566
- if (ticket.kind !== 'node' && capacity <= 0) continue
8951
+ if (this.outOfBudget(opts)) {
8952
+ claimLoopCompleted = false
8953
+ break
8954
+ }
8955
+ if (!targeted && normalPaused && tierOf(ticket) !== 'urgent') continue
8956
+ const urgent = urgentClaim(ticket)
8957
+ const budget = targeted
8958
+ ? targeted.budgets[startTier(ticket)]
8959
+ : urgent
8960
+ ? urgentCapacity
8961
+ : capacity
8962
+ if (ticket.kind !== 'node' && budget <= 0 && !urgent) continue
6567
8963
  if (withheld.has(ticket.ref.id)) continue
6568
8964
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
6569
8965
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
8966
+ // An urgent ticket that passed every gate but capacity is demand that
8967
+ // normal parked work yields to until the next admission scan.
8968
+ if (ticket.kind !== 'node' && budget <= 0) {
8969
+ urgentWaiting += 1
8970
+ continue
8971
+ }
6570
8972
 
6571
8973
  const target = await this.resolveNodeTarget(ticket, targetScan)
6572
8974
  if (typeof target === 'string') {
6573
8975
  report.dependencyBlocked += 1
6574
8976
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
8977
+ settle(ticket, { outcome: 'blocked', detail: target })
6575
8978
  continue
6576
8979
  }
6577
8980
  if (hasNodes && preflightTargets.get(ticket.ref.id) !== JSON.stringify(target)) {
@@ -6606,7 +9009,12 @@ export class Dispatcher {
6606
9009
  }
6607
9010
  await store.ensureRepo(this.deps.repo)
6608
9011
  // A lapsed run leaves the ticket Ready for whoever holds the repository.
6609
- if (this.deps.holdsRepoAuthority?.() === false) break
9012
+ if (this.deps.holdsRepoAuthority?.() === false) {
9013
+ claimLoopCompleted = false
9014
+ break
9015
+ }
9016
+ // Cancellation and a priority change are checked again before claiming.
9017
+ if (targeted && !(await this.startStillPending(targeted, ticket))) continue
6610
9018
  await store.appendRepo(this.deps.repo, {
6611
9019
  actor: DISPATCHER,
6612
9020
  type: 'ticket-preparation.intended',
@@ -6624,8 +9032,26 @@ export class Dispatcher {
6624
9032
  let authoredSession: string | undefined
6625
9033
  let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
6626
9034
  try {
6627
- if (!(await tickets.claim(ticket.ref.id))) {
9035
+ let claimed: boolean
9036
+ try {
9037
+ claimed = await tickets.claim(ticket.ref.id, { blockedBy: ticket.blockedBy ?? [] })
9038
+ } catch (error) {
9039
+ if (!(error instanceof TicketClaimBlockedError)) throw error
9040
+ // A blocker recorded after the dependency check (GitHub's summary
9041
+ // lags its edges): still ready, so the next scan sees the blocker.
9042
+ const detail = `ticket ${ticket.ref.id}: blockers ${error.blockers.join(', ')} were recorded after the dependency check; waiting for the next scan`
9043
+ await this.preparationResolved(attempt, 'lost-claim', error.message)
9044
+ report.dependencyBlocked += 1
9045
+ report.dependencyDiagnostics.push(detail)
9046
+ settle(ticket, { outcome: 'blocked', detail })
9047
+ continue
9048
+ }
9049
+ if (!claimed) {
6628
9050
  await this.preparationResolved(attempt, 'lost-claim')
9051
+ settle(ticket, {
9052
+ outcome: 'claim-refused',
9053
+ detail: `the ${tickets.name} ticket source refused the claim of ${ticket.ref.id}`,
9054
+ })
6629
9055
  report.claimRaces += 1
6630
9056
  report.queued -= 1
6631
9057
  continue
@@ -6645,10 +9071,23 @@ export class Dispatcher {
6645
9071
  // Quality gate (§6.3): import a conforming ticket body as the spec;
6646
9072
  // author one for thin-but-groomed tickets; otherwise bounce.
6647
9073
  stage = 'spec'
6648
- let conformance = specConformance(body)
6649
- if (!conformance.conforms && this.deps.authorSpec) {
9074
+ // An objective refusal bounces before any authoring: an authored spec
9075
+ // could strip the block and open a plain node instead (SPEC §13.1).
9076
+ const refusals = objectiveRefusals(body, {
9077
+ kind: ticket.kind ?? 'work',
9078
+ rejectedState: this.rejectedState(),
9079
+ })
9080
+ let conformance =
9081
+ refusals.length > 0 ? { conforms: false, missing: refusals } : specConformance(body)
9082
+ if (
9083
+ !conformance.conforms &&
9084
+ refusals.length === 0 &&
9085
+ objectiveBlocks(body).length === 0 &&
9086
+ this.deps.authorSpec
9087
+ ) {
6650
9088
  const authored = await this.deps.authorSpec(ticket)
6651
- if (authored !== null) {
9089
+ // An authored spec never gains the marker the ticket did not carry.
9090
+ if (authored !== null && objectiveBlocks(authored).length === 0) {
6652
9091
  conformance = specConformance(authored)
6653
9092
  if (conformance.conforms) {
6654
9093
  body = authored
@@ -6671,7 +9110,7 @@ export class Dispatcher {
6671
9110
  },
6672
9111
  })
6673
9112
  stage = 'bounce'
6674
- await this.bounce(ticket, conformance.missing)
9113
+ await this.bounce(ticket, conformance.missing, refusals.length > 0)
6675
9114
  stage = 'handback-report'
6676
9115
  await this.reportPreparationHandback(attempt, {
6677
9116
  ticket: ticket.ref,
@@ -6682,6 +9121,12 @@ export class Dispatcher {
6682
9121
  ...(missing ? { missing } : {}),
6683
9122
  })
6684
9123
  await this.preparationResolved(attempt, 'bounced')
9124
+ settle(ticket, {
9125
+ outcome: 'invalid',
9126
+ detail: `bounced to ${attempt.handback}${
9127
+ conformance.missing.length > 0 ? `; missing: ${conformance.missing.join('; ')}` : ''
9128
+ }`,
9129
+ })
6685
9130
  report.bounced += 1
6686
9131
  report.queued -= 1
6687
9132
  continue
@@ -6715,6 +9160,12 @@ export class Dispatcher {
6715
9160
  ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
6716
9161
  // Fixed at claim from the same sample: relabelling never changes it.
6717
9162
  ...this.selectedProfile(ticket),
9163
+ // `manual` is admission-only; an explicit urgent start is urgent.
9164
+ ...(startTier(ticket) === 'urgent' && targeted
9165
+ ? { priority: 'urgent' as const }
9166
+ : tierOf(ticket) === 'urgent'
9167
+ ? { priority: 'urgent' as const }
9168
+ : {}),
6718
9169
  }
6719
9170
  // `build.created` rides with the record so the pinned assets and the
6720
9171
  // record exist together or not at all.
@@ -6747,6 +9198,7 @@ export class Dispatcher {
6747
9198
  })
6748
9199
  established = true
6749
9200
  await this.preparationResolved(attempt, 'owned')
9201
+ settle(ticket, { outcome: 'started', slug: record.slug })
6750
9202
  } catch (error) {
6751
9203
  // A lapse is not a preparation failure: the successor recovers the
6752
9204
  // intended attempt through `recoverTicketPreparations`.
@@ -6786,7 +9238,11 @@ export class Dispatcher {
6786
9238
  )
6787
9239
  }
6788
9240
  report.queued -= 1
6789
- if (ticket.kind !== 'node') capacity -= 1
9241
+ if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
9242
+ else if (ticket.kind !== 'node') {
9243
+ capacity -= 1
9244
+ urgentCapacity -= 1
9245
+ }
6790
9246
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
6791
9247
  ticket,
6792
9248
  body,
@@ -6797,7 +9253,93 @@ export class Dispatcher {
6797
9253
  // means the remote provisioning continuation owns the rest.
6798
9254
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
6799
9255
  }
6800
- if (scanSuccessful && !this.outOfBudget(opts)) await this.completeScan(checkpoint, report)
9256
+ if (checkpoint !== undefined && scanSuccessful && !this.outOfBudget(opts)) {
9257
+ await this.completeScan(checkpoint, report, urgentWaiting)
9258
+ // The only other place this tick authorizes deferred normal admissions.
9259
+ if (claimLoopCompleted) this.urgentEvaluated = true
9260
+ }
9261
+ }
9262
+
9263
+ /** Builds whose ticket resolves to `target` under the repository's
9264
+ * ticket migrations, newest first. A pure scan of the tick's listing. */
9265
+ private targetBuilds(
9266
+ target: string,
9267
+ source: string,
9268
+ all: readonly { record: BuildRecord; digest: BuildDigest }[],
9269
+ ): { record: BuildRecord; digest: BuildDigest }[] {
9270
+ const migrations = this.store.repositoryFacts().ticketMigrations
9271
+ return all
9272
+ .filter(({ record }) => {
9273
+ if (!record.ticket) return false
9274
+ try {
9275
+ return resolveTicketRef(migrations, record.ticket, source, record.slug).id === target
9276
+ } catch {
9277
+ return false
9278
+ }
9279
+ })
9280
+ .sort(
9281
+ (a, b) =>
9282
+ b.record.createdAt.localeCompare(a.record.createdAt) ||
9283
+ b.record.slug.localeCompare(a.record.slug),
9284
+ )
9285
+ }
9286
+
9287
+ /** The ticket identity the attempt claim gate and claim tier match
9288
+ * attempts under: the configured source after recorded migrations. */
9289
+ private attemptIdentity(): (ref: TicketRef) => string {
9290
+ const migrations = this.store.repositoryFacts().ticketMigrations
9291
+ return (ref) => {
9292
+ try {
9293
+ const resolved = resolveTicketRef(migrations, ref, this.deps.tickets.name)
9294
+ return `${resolved.source}\u0000${resolved.id}`
9295
+ } catch {
9296
+ return `${ref.source}\u0000${ref.id}`
9297
+ }
9298
+ }
9299
+ }
9300
+
9301
+ /**
9302
+ * The claim tier of each ready optimization attempt: its node's current
9303
+ * build priority (`ab priority <node>`), decided at claim, whatever the
9304
+ * ticket says or whether its source stores priority. Nothing is reserved;
9305
+ * other tickets keep their own tier. Costs one served node state per open,
9306
+ * unstopped optimization node a ready ticket targets, and none otherwise.
9307
+ */
9308
+ private async attemptClaimTiers(
9309
+ tickets: readonly Ticket[],
9310
+ ): Promise<Map<string, TicketPriority>> {
9311
+ const tiers = new Map<string, TicketPriority>()
9312
+ const candidates = tickets.filter(
9313
+ (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
9314
+ )
9315
+ if (candidates.length === 0) return tiers
9316
+ const all = await this.repoBuildDigests()
9317
+ const nodes = new Map<string, BuildState>()
9318
+ const key = this.attemptIdentity()
9319
+ for (const ticket of candidates) {
9320
+ const [latest, tied] = this.targetBuilds(ticket.target!, ticket.ref.source, all)
9321
+ if (latest === undefined || tied?.record.createdAt === latest.record.createdAt) continue
9322
+ const { record, digest } = latest
9323
+ if (digest.terminal !== undefined || !digest.nodeOpened) continue
9324
+ let signal: ReturnType<typeof digestOptimization>
9325
+ try {
9326
+ signal = digestOptimization(digest)
9327
+ } catch (error) {
9328
+ // An older store's digest: the ticket keeps its own tier.
9329
+ if (error instanceof BuildDigestCapabilityError) continue
9330
+ throw error
9331
+ }
9332
+ if (!signal || signal.stopped) continue
9333
+ let state = nodes.get(record.slug)
9334
+ if (state === undefined) {
9335
+ state = (await this.store.buildFacts(record.slug)).state
9336
+ nodes.set(record.slug, state)
9337
+ }
9338
+ if (state.optimization === undefined || state.optimization.stopped !== undefined) continue
9339
+ if (optimizationAttempt(state.optimization, ticket.ref, key) !== undefined)
9340
+ tiers.set(ticket.ref.id, buildPriority(state))
9341
+ }
9342
+ return tiers
6801
9343
  }
6802
9344
 
6803
9345
  /**
@@ -6824,29 +9366,7 @@ export class Dispatcher {
6824
9366
  if (ticket.target === undefined) return undefined
6825
9367
  const migrations = this.store.repositoryFacts().ticketMigrations
6826
9368
  const all = await this.repoBuildDigests()
6827
- const entries = all
6828
- .filter(
6829
- ({ record }) =>
6830
- record.ticket &&
6831
- (() => {
6832
- try {
6833
- const ref = resolveTicketRef(
6834
- migrations,
6835
- record.ticket,
6836
- ticket.ref.source,
6837
- record.slug,
6838
- )
6839
- return ref.id === ticket.target
6840
- } catch {
6841
- return false
6842
- }
6843
- })(),
6844
- )
6845
- .sort(
6846
- (a, b) =>
6847
- b.record.createdAt.localeCompare(a.record.createdAt) ||
6848
- b.record.slug.localeCompare(a.record.slug),
6849
- )
9369
+ const entries = this.targetBuilds(ticket.target, ticket.ref.source, all)
6850
9370
  const latest = entries[0]
6851
9371
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
6852
9372
  return `target node ${ticket.target} has ambiguous build generations at ${latest.record.createdAt}`
@@ -6865,6 +9385,15 @@ export class Dispatcher {
6865
9385
  return `target node ${ticket.target} is ${state.prState === 'merged' ? 'landed' : 'closed'}`
6866
9386
  if (state.pendingCommands.some((c) => c.command === 'abort'))
6867
9387
  return `target node ${ticket.target} is closing`
9388
+ if (state.optimization?.stopped !== undefined) {
9389
+ const key = this.attemptIdentity()
9390
+ const wanted = key(ticket.ref)
9391
+ if (
9392
+ optimizationAttempt(state.optimization, ticket.ref, key) !== undefined ||
9393
+ state.optimization.stoppedTickets?.some((ref) => key(ref) === wanted)
9394
+ )
9395
+ return `target optimization node ${ticket.target} has stopped; attempt ${ticket.ref.id} is cancelled`
9396
+ }
6868
9397
  if (state.integration?.intent && !state.integration.landing)
6869
9398
  return `target node ${ticket.target} is merging`
6870
9399
  if (!digest.nodeOpened || !record.branch) return `target node ${ticket.target} is not yet open`
@@ -6899,8 +9428,23 @@ export class Dispatcher {
6899
9428
  }
6900
9429
  const sha = await forge.createNodeBranch(intent.branch, intent.sha)
6901
9430
  await this.store.refreshBuild(record.slug)
6902
- const latest = (await this.store.buildFacts(record.slug)).state
9431
+ let latest = (await this.store.buildFacts(record.slug)).state
6903
9432
  if (latest.status !== 'queued' || latest.pendingCommands.length > 0 || latest.nodeOpened) return
9433
+ // An optimization node's objective is accepted before it opens, so an
9434
+ // opened node without its accepted objective never exists (SPEC §13.1).
9435
+ if (latest.optimization === undefined) {
9436
+ const objective = await this.specObjective(record.slug, latest.specRev)
9437
+ if (objective !== undefined) {
9438
+ const accepted = await this.store.appendIfCurrent(record.slug, latest.lastSeq, {
9439
+ actor: DISPATCHER,
9440
+ type: 'optimization.objective-accepted',
9441
+ payload: { objective, revision: 1, harnessPin: sha, specRev: latest.specRev ?? 0 },
9442
+ })
9443
+ if (!accepted) return
9444
+ await this.store.refreshBuild(record.slug)
9445
+ latest = (await this.store.buildFacts(record.slug)).state
9446
+ }
9447
+ }
6904
9448
  await this.store.appendIfCurrent(record.slug, latest.lastSeq, {
6905
9449
  actor: DISPATCHER,
6906
9450
  type: 'node.opened',
@@ -6908,6 +9452,65 @@ export class Dispatcher {
6908
9452
  })
6909
9453
  }
6910
9454
 
9455
+ /** Re-accept an optimization node's objective after a spec revision
9456
+ * (SPEC §13.1). The harness is pinned again at the node head only when the
9457
+ * revision starts a new ruler. Returns whether a fact was written. */
9458
+ private async acceptRevisedObjective(
9459
+ record: BuildRecord,
9460
+ state: BuildState,
9461
+ report: TickReport,
9462
+ ): Promise<boolean> {
9463
+ const optimization = state.optimization!
9464
+ let objective: Objective | undefined
9465
+ try {
9466
+ objective = await this.specObjective(record.slug, state.specRev)
9467
+ } catch (error) {
9468
+ report.janitorDiagnostics.push(
9469
+ `${record.slug}: ${error instanceof Error ? error.message : String(error)}`,
9470
+ )
9471
+ return false
9472
+ }
9473
+ if (objective === undefined) {
9474
+ report.janitorDiagnostics.push(
9475
+ `${record.slug}: spec revision ${state.specRev} removed the autobuild-objective block`,
9476
+ )
9477
+ return false
9478
+ }
9479
+ const forge = this.deps.forge
9480
+ const harnessPin =
9481
+ objectiveRulerChanged(optimization.accepted.objective, objective) && record.branch
9482
+ ? await forge.remoteBranchSha?.(record.branch)
9483
+ : optimization.accepted.harnessPin
9484
+ if (harnessPin === undefined) return false
9485
+ const written = await this.store.appendIfCurrent(record.slug, state.lastSeq, {
9486
+ actor: DISPATCHER,
9487
+ type: 'optimization.objective-accepted',
9488
+ payload: {
9489
+ objective,
9490
+ revision: optimization.revision + 1,
9491
+ harnessPin,
9492
+ specRev: state.specRev ?? 0,
9493
+ },
9494
+ })
9495
+ return written !== null
9496
+ }
9497
+
9498
+ /** The objective a recorded spec revision declares: undefined for a plain
9499
+ * node or no recorded spec, a thrown refusal for a spec that cannot open as
9500
+ * either kind. One artifact read. */
9501
+ private async specObjective(
9502
+ slug: string,
9503
+ rev: number | undefined,
9504
+ ): Promise<Objective | undefined> {
9505
+ if (rev === undefined) return undefined
9506
+ const artifact = await this.store.getArtifact(slug, 'spec', rev)
9507
+ if (artifact === null) throw new Error(`spec revision ${rev} is unreadable`)
9508
+ const parsed = parseObjective(new TextDecoder().decode(artifact.content))
9509
+ if ('refusal' in parsed)
9510
+ throw new Error(`spec revision ${rev} cannot open as an optimization node: ${parsed.refusal}`)
9511
+ return 'objective' in parsed ? parsed.objective : undefined
9512
+ }
9513
+
6911
9514
  private kernelForge(): Forge {
6912
9515
  const forge = this.deps.forge
6913
9516
  if (!forge.kernelRewrite) return forge
@@ -7243,12 +9846,19 @@ export class Dispatcher {
7243
9846
  }
7244
9847
 
7245
9848
  if (!this.accountsAvailable()) return
7246
- if (!(await this.nodeHasCapacity(record.slug))) return
7247
- if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
7248
- const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
9849
+ if ((await this.nodeHasCapacity(record.slug, false)) !== 'admit') return
9850
+ // `launch()` refuses a flagged workspace and leaves the reap to its
9851
+ // callers; this is the node's caller for conflict work.
9852
+ const current = await this.replaceFlaggedWorkspace(record, facts, launched)
9853
+ if (current === undefined) return
9854
+ if (openWorkspace(current) === null && this.deps.workspaces.recovery) {
9855
+ const kicked = await this.ensureProvisionContinuation(record, current, 'launch')
7249
9856
  if (kicked === 'kicked') report.provisioning += 1
9857
+ else if (kicked === 'budget-wait') report.provisioningDeferred += 1
9858
+ // After a reap, this tick's sweep leaves the replacement alone.
9859
+ if (kicked === 'kicked' && current !== facts) launched.add(record.slug)
7250
9860
  } else {
7251
- if (openWorkspace(facts) === null) {
9861
+ if (openWorkspace(current) === null) {
7252
9862
  const handle = await this.provisionWorkspace(record.slug, {
7253
9863
  repo: checkout,
7254
9864
  baseBranch: state.baseBranch!,
@@ -7346,6 +9956,7 @@ export class Dispatcher {
7346
9956
  if (
7347
9957
  state.integration?.cycle &&
7348
9958
  !state.nodeRestack?.active &&
9959
+ !proposeRunDue(state.optimization) &&
7349
9960
  (!integrationCurrent(state) || integrationFailed(state))
7350
9961
  ) {
7351
9962
  const stale = (await readBuildFacts(this.store, record.slug)).value
@@ -7354,6 +9965,7 @@ export class Dispatcher {
7354
9965
  }
7355
9966
  if (
7356
9967
  unchangedFailure ||
9968
+ state.integration?.landing ||
7357
9969
  !integrationComplete(state) ||
7358
9970
  state.nodeRestack?.active ||
7359
9971
  state.integration?.intent ||
@@ -7380,6 +9992,9 @@ export class Dispatcher {
7380
9992
  !integrationCurrent(state) ||
7381
9993
  state.integration?.cycle?.config !== integrationConfig(config)
7382
9994
  ) {
9995
+ // An empty owned range (everything already upstream) has nothing to
9996
+ // verify: never prepare a new cycle for it.
9997
+ if (comparison.ahead === 0 || comparison.headSha === comparison.parentSha) return
7383
9998
  await this.observeIntegration(record.slug)
7384
9999
  state = (await this.store.buildFacts(record.slug)).state
7385
10000
  if (!integrationComplete(state)) return
@@ -7396,6 +10011,8 @@ export class Dispatcher {
7396
10011
  return
7397
10012
  const exact = await forge.compareBranches(state.baseBranch!, record.branch!)
7398
10013
  if (exact.parentSha !== comparison.parentSha || exact.headSha !== comparison.headSha) return
10014
+ if (exact.ahead === 0 || exact.headSha === exact.parentSha || current.integration?.landing)
10015
+ return
7399
10016
  const cycle = {
7400
10017
  id: this.deps.ids('integration-cycle'),
7401
10018
  parent: exact.parentSha,
@@ -7403,6 +10020,7 @@ export class Dispatcher {
7403
10020
  }
7404
10021
  let context: string | undefined
7405
10022
  let headPaths: HeadPathsArtifact | undefined
10023
+ let retained: RetentionOutcome | undefined
7406
10024
  await this.withKernelRepository(async (path) => {
7407
10025
  const head = await forge.rewrite!.snapshot({
7408
10026
  workspacePath: path,
@@ -7411,11 +10029,6 @@ export class Dispatcher {
7411
10029
  })
7412
10030
  if (head !== exact.headSha)
7413
10031
  throw new Error('node head moved while preparing verification')
7414
- await forge.rewrite!.archive({
7415
- workspacePath: path,
7416
- ref: `refs/autobuild/archive/${record.slug}/${head}`,
7417
- sha: head,
7418
- })
7419
10032
  const exec = forge.kernelExec ?? this.deps.exec
7420
10033
  // Snapshot fetch brings the complete head ancestry, including merge sides.
7421
10034
  // A parent may have advanced independently and need its own fetch.
@@ -7429,6 +10042,22 @@ export class Dispatcher {
7429
10042
  if (fetched.exitCode !== 0)
7430
10043
  throw new Error(`cannot fetch node verification parent: ${fetched.stderr}`)
7431
10044
  }
10045
+ // Best effort, once the parent a store copy excludes is present: the
10046
+ // head stays reachable from the published node branch.
10047
+ retained = await retainCommit(
10048
+ {
10049
+ store: this.store,
10050
+ slug: record.slug,
10051
+ exec,
10052
+ workspacePath: path,
10053
+ archive: forge.rewrite!.archive,
10054
+ exclude: exact.parentSha,
10055
+ local: forge.name === 'local-git',
10056
+ branch: record.branch!,
10057
+ targetBranch: state.baseBranch!,
10058
+ },
10059
+ head,
10060
+ )
7432
10061
  // The cycle's candidate head is recorded once, with the cycle.
7433
10062
  if (!headPathsFor(current, exact.headSha).recorded)
7434
10063
  headPaths = await computeHeadPaths(exec, path, {
@@ -7450,6 +10079,31 @@ export class Dispatcher {
7450
10079
  })
7451
10080
  if (!(await this.store.renewNodeWriter(record.slug, holder))) return
7452
10081
  let expectedSeq = current.lastSeq
10082
+ if (retained !== undefined && retained.in !== 'forge') {
10083
+ // Recorded under the writer lease, then the guards are re-read so the
10084
+ // compare-and-append below starts from the retention fact.
10085
+ await recordRetention(
10086
+ this.store,
10087
+ record.slug,
10088
+ {
10089
+ event: 'node.history-retained',
10090
+ operation: 'verify',
10091
+ id: cycle.id,
10092
+ base: exact.parentSha,
10093
+ },
10094
+ [retained],
10095
+ )
10096
+ const latest = (await this.store.buildFacts(record.slug)).state
10097
+ if (
10098
+ latest.nodeRestack?.active ||
10099
+ latest.nodeRestack?.parentRequest ||
10100
+ latest.nodeRestack?.parentChange ||
10101
+ latest.pendingCommands.length ||
10102
+ latest.integration?.landing
10103
+ )
10104
+ return
10105
+ expectedSeq = latest.lastSeq
10106
+ }
7453
10107
  if (headPaths !== undefined) {
7454
10108
  const { artifacts, makeEvent } = headPathsWrite(headPaths, 'integration', DISPATCHER)
7455
10109
  const recorded = await this.store.appendWithArtifactsIfCurrent(
@@ -7490,18 +10144,47 @@ export class Dispatcher {
7490
10144
  }
7491
10145
  if (integrationFailed(state) || integrationVerified(state, config)) {
7492
10146
  const facts = (await readBuildFacts(this.store, record.slug)).value
7493
- if (openWorkspace(facts)) await this.releaseWorkspace(record.slug, facts)
10147
+ // The proposer's workspace is released by its filing.
10148
+ if (openWorkspace(facts) && !proposeRunDue(state.optimization))
10149
+ await this.releaseWorkspace(record.slug, facts)
7494
10150
  return
7495
10151
  }
7496
- if (!(await this.nodeHasCapacity(record.slug))) return
10152
+ if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
7497
10153
  await this.observeIntegration(record.slug)
7498
10154
  state = (await this.store.buildFacts(record.slug)).state
7499
10155
  if (!integrationCurrent(state)) return
7500
10156
  if (!this.accountsAvailable()) return
7501
10157
  const facts = (await readBuildFacts(this.store, record.slug)).value
10158
+ await this.provisionNodeAndLaunch(
10159
+ record,
10160
+ facts,
10161
+ report,
10162
+ launched,
10163
+ state.integration!.cycle!.head,
10164
+ )
10165
+ }
10166
+
10167
+ /** Provision a node's workspace when it has none, then launch its runner. A
10168
+ * recovery-capable provider provisions and launches in its background
10169
+ * continuation instead. */
10170
+ private async provisionNodeAndLaunch(
10171
+ record: BuildRecord,
10172
+ read: CurrentBuildFacts,
10173
+ report: TickReport,
10174
+ launched: Set<string>,
10175
+ revision?: string,
10176
+ ): Promise<void> {
10177
+ const branch = record.branch
10178
+ if (!branch) return
10179
+ // Both verification and baseline measurement must recover flagged workspaces.
10180
+ const facts = await this.replaceFlaggedWorkspace(record, read, launched)
10181
+ if (facts === undefined) return
7502
10182
  if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
7503
10183
  const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
7504
10184
  if (kicked === 'kicked') report.provisioning++
10185
+ else if (kicked === 'budget-wait') report.provisioningDeferred++
10186
+ // After a reap, this tick's sweep leaves the replacement alone.
10187
+ if (kicked === 'kicked' && facts !== read) launched.add(record.slug)
7505
10188
  return
7506
10189
  }
7507
10190
  if (openWorkspace(facts) === null) {
@@ -7509,9 +10192,9 @@ export class Dispatcher {
7509
10192
  try {
7510
10193
  handle = await this.provisionWorkspace(record.slug, {
7511
10194
  repo: this.deps.checkout ?? this.deps.repo,
7512
- baseBranch: record.branch,
7513
- branch: record.branch,
7514
- revision: state.integration!.cycle!.head,
10195
+ baseBranch: branch,
10196
+ branch,
10197
+ ...(revision !== undefined ? { revision } : {}),
7515
10198
  })
7516
10199
  } catch (error) {
7517
10200
  if (await this.holdForMissingAccounts(error)) return
@@ -8030,14 +10713,18 @@ export class Dispatcher {
8030
10713
  /** Bounce (§6.3): back to Triage with a comment citing the standard and
8031
10714
  * WHICH parts are missing — failure at the cheapest point, not a build
8032
10715
  * that thrashes and escalates. No build is created. */
8033
- private async bounce(ticket: Ticket, missing: string[]): Promise<void> {
10716
+ private async bounce(ticket: Ticket, missing: string[], refused = false): Promise<void> {
8034
10717
  const triageState = this.triageState()
8035
10718
  await this.deps.tickets.transition(ticket.ref.id, triageState)
8036
10719
  await this.deps.tickets.comment(
8037
10720
  ticket.ref.id,
8038
- `Bounced back to ${triageState}: this ticket does not conform to ` +
8039
- `the spec standard (.agents/skills/ab-guide/references/spec-standard.md) and cannot be dispatched.\n` +
8040
- `Missing: ${missing.join('; ')}.`,
10721
+ refused
10722
+ ? `Bounced back to ${triageState}: this ticket's spec cannot open as dispatched ` +
10723
+ `(.agents/skills/ab-guide/references/optimization-nodes.md).\n` +
10724
+ `Refused: it needs ${missing.join('; ')}.`
10725
+ : `Bounced back to ${triageState}: this ticket does not conform to ` +
10726
+ `the spec standard (.agents/skills/ab-guide/references/spec-standard.md) and cannot be dispatched.\n` +
10727
+ `Missing: ${missing.join('; ')}.`,
8041
10728
  )
8042
10729
  }
8043
10730
 
@@ -8164,17 +10851,25 @@ export class Dispatcher {
8164
10851
  return verdict
8165
10852
  }
8166
10853
 
8167
- /** Valid bounded base, deduped with -2/-3/… against this store's builds and,
10854
+ /** Valid bounded base, deduped with -2/-3/… against this store's builds,
8168
10855
  * when the forge can answer, against build branches already on the remote
8169
- * (another store's builds, AUT-1106). Claim-time only; a forge failure fails
8170
- * the naming stage and the claim is handed back. */
10856
+ * (another store's builds, AUT-1106), and, when the workspace provider
10857
+ * creates branches in a local checkout, against local branches there: a
10858
+ * stale local `ab/<slug>` must never become a new build's branch (#1261).
10859
+ * Claim-time only; a probe failure fails the naming stage and the claim is
10860
+ * handed back. */
8171
10861
  private async uniqueSlug(base: string, prefix: 'ab' | 'ab-node'): Promise<string> {
8172
10862
  const forge = this.deps.forge
8173
10863
  const exists = forge.remoteBranchExists
10864
+ const workspaces = this.deps.workspaces
10865
+ const local = workspaces.localBranchExists
10866
+ const checkout = this.deps.checkout ?? this.deps.repo
8174
10867
  for (let n = 1; n <= MAX_SLUG_CANDIDATES; n += 1) {
8175
10868
  const slug = n === 1 ? base : `${base}-${n}`
8176
10869
  if ((await this.store.getBuild(slug)) !== null) continue
8177
- if (exists !== undefined && (await exists.call(forge, `${prefix}/${slug}`))) continue
10870
+ const branch = `${prefix}/${slug}`
10871
+ if (exists !== undefined && (await exists.call(forge, branch))) continue
10872
+ if (local !== undefined && (await local.call(workspaces, checkout, branch))) continue
8178
10873
  return slug
8179
10874
  }
8180
10875
  throw new Error(`no free slug for ${base} after ${MAX_SLUG_CANDIDATES} candidates`)