@defrex/autobuild 1.11.1 → 1.13.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 (213) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +601 -203
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +32 -2
  5. package/docs/architecture.md +188 -57
  6. package/docs/assets/headline-wide.png +0 -0
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +120 -23
  9. package/docs/dispatcher.md +19 -8
  10. package/docs/integration-overview.md +1 -1
  11. package/docs/integration-tree.md +33 -18
  12. package/docs/merge-policy.md +7 -2
  13. package/docs/operating.md +5 -3
  14. package/docs/operator-api.md +48 -25
  15. package/docs/operator-surfaces.md +39 -3
  16. package/docs/optimization-nodes.md +10 -8
  17. package/docs/plugin-authoring.md +46 -18
  18. package/docs/remote-store-protocol.md +51 -12
  19. package/docs/remote-ticket-protocol.md +85 -38
  20. package/docs/restacking.md +48 -3
  21. package/docs/setup.md +2 -1
  22. package/docs/ticket-migration.md +2 -2
  23. package/docs/ticket-sources.md +23 -8
  24. package/docs/tickets.md +4 -4
  25. package/docs/troubleshooting.md +17 -2
  26. package/docs/verification.md +3 -1
  27. package/package.json +3 -3
  28. package/packages/core/src/cli/ambient-errors.ts +17 -0
  29. package/packages/core/src/cli/bounded-io.ts +174 -0
  30. package/packages/core/src/cli/build-control.ts +72 -6
  31. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  32. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  33. package/packages/core/src/cli/dashboard/model.ts +93 -29
  34. package/packages/core/src/cli/dashboard/poll.ts +231 -34
  35. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  36. package/packages/core/src/cli/dashboard/render.ts +14 -37
  37. package/packages/core/src/cli/dashboard/row-text.ts +26 -8
  38. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  39. package/packages/core/src/cli/dashboard/vocabulary.ts +165 -20
  40. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  41. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  42. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  43. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  44. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  45. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  46. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  47. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  48. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  49. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  50. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  51. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  52. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  53. package/packages/core/src/cli/dispatch.ts +595 -149
  54. package/packages/core/src/cli/env.ts +2 -15
  55. package/packages/core/src/cli/help.ts +43 -28
  56. package/packages/core/src/cli/main.ts +11 -7
  57. package/packages/core/src/cli/production-store.ts +102 -0
  58. package/packages/core/src/cli/publication-settlement.ts +4 -0
  59. package/packages/core/src/cli/remote-poll.ts +22 -5
  60. package/packages/core/src/cli/repo-state.ts +2 -3
  61. package/packages/core/src/cli/repository-status.ts +44 -28
  62. package/packages/core/src/cli/sessionless-store.ts +26 -0
  63. package/packages/core/src/cli/status.ts +188 -47
  64. package/packages/core/src/cli/store-opening.ts +26 -57
  65. package/packages/core/src/cli/store-ref.ts +6 -1
  66. package/packages/core/src/cli/ticket-start.ts +3 -3
  67. package/packages/core/src/cli/ticket.ts +12 -11
  68. package/packages/core/src/cli/wait.ts +8 -28
  69. package/packages/core/src/cli/watch.ts +113 -50
  70. package/packages/core/src/config/reference-metadata.ts +7 -1
  71. package/packages/core/src/config/reference.ts +5 -2
  72. package/packages/core/src/config/schema.ts +51 -16
  73. package/packages/core/src/distribution-packaging.ts +156 -18
  74. package/packages/core/src/events/catalog-identity.ts +28 -0
  75. package/packages/core/src/events/catalog.ts +3 -9
  76. package/packages/core/src/events/compatibility.ts +2 -30
  77. package/packages/core/src/events/payloads.ts +85 -14
  78. package/packages/core/src/events/policy.ts +3 -0
  79. package/packages/core/src/events/repository.ts +15 -4
  80. package/packages/core/src/events/sessions.ts +1 -1
  81. package/packages/core/src/events/validation-error.ts +12 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +36 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  92. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  93. package/packages/core/src/kernel/capacity-build.ts +21 -0
  94. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  95. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +578 -235
  97. package/packages/core/src/kernel/done-escalations.ts +269 -0
  98. package/packages/core/src/kernel/engine.ts +30 -17
  99. package/packages/core/src/kernel/integration-landing.ts +24 -4
  100. package/packages/core/src/kernel/integration-stack.ts +39 -0
  101. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  102. package/packages/core/src/kernel/log-index-value.ts +3 -0
  103. package/packages/core/src/kernel/log-index.ts +41 -2
  104. package/packages/core/src/kernel/measurement.ts +24 -0
  105. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  106. package/packages/core/src/kernel/read-facts.ts +8 -370
  107. package/packages/core/src/kernel/reducer-registry.ts +43 -125
  108. package/packages/core/src/kernel/reducer-revisions.ts +18 -0
  109. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  110. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  111. package/packages/core/src/kernel/reducer.ts +84 -16
  112. package/packages/core/src/kernel/reopen-state.ts +10 -0
  113. package/packages/core/src/kernel/repository-attention.ts +14 -5
  114. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  115. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  116. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  117. package/packages/core/src/kernel/verify-stages.ts +46 -7
  118. package/packages/core/src/operator/attention.ts +28 -3
  119. package/packages/core/src/operator/done-escalations.ts +38 -0
  120. package/packages/core/src/operator/presentation.ts +14 -1
  121. package/packages/core/src/operator/protocol.ts +8 -5
  122. package/packages/core/src/operator/query.ts +72 -57
  123. package/packages/core/src/operator/registry.ts +19 -15
  124. package/packages/core/src/operator/ticket-start.ts +8 -7
  125. package/packages/core/src/operator/tickets.ts +28 -9
  126. package/packages/core/src/plugin-sdk/index.ts +10 -0
  127. package/packages/core/src/plugins/manifest.ts +14 -1
  128. package/packages/core/src/ports/forge/create.ts +8 -0
  129. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  130. package/packages/core/src/ports/forge/github.ts +3 -0
  131. package/packages/core/src/ports/tickets/contract.ts +147 -76
  132. package/packages/core/src/ports/tickets/create.ts +47 -7
  133. package/packages/core/src/ports/tickets/fake.ts +8 -4
  134. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  135. package/packages/core/src/ports/tickets/file.ts +7 -3
  136. package/packages/core/src/ports/tickets/github.ts +1 -0
  137. package/packages/core/src/ports/tickets/grants.ts +11 -3
  138. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  139. package/packages/core/src/ports/tickets/linear.ts +28 -9
  140. package/packages/core/src/ports/tickets/migration.ts +4 -4
  141. package/packages/core/src/ports/tickets/operations.ts +4 -2
  142. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  143. package/packages/core/src/ports/tickets/priority.ts +127 -21
  144. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  145. package/packages/core/src/ports/tickets/remote.ts +104 -11
  146. package/packages/core/src/ports/tickets/revision.ts +5 -3
  147. package/packages/core/src/ports/tickets/search.ts +9 -0
  148. package/packages/core/src/ports/tickets/tree.ts +8 -6
  149. package/packages/core/src/ports/types.ts +30 -15
  150. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  151. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  152. package/packages/core/src/ports/workspace/create.ts +16 -3
  153. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  154. package/packages/core/src/ports/workspace/fake.ts +15 -3
  155. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  156. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  157. package/packages/core/src/processes/build-execution-state.ts +4 -0
  158. package/packages/core/src/processes/build-runner.ts +14 -1
  159. package/packages/core/src/processes/dispatcher.ts +777 -288
  160. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  161. package/packages/core/src/processes/execution-settlement.ts +1 -0
  162. package/packages/core/src/processes/harvest-runner.ts +12 -7
  163. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  164. package/packages/core/src/processes/invocation-budget.ts +176 -0
  165. package/packages/core/src/processes/publication-loss.ts +38 -3
  166. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  167. package/packages/core/src/store/contract.ts +81 -3
  168. package/packages/core/src/store/event-reads.ts +30 -1
  169. package/packages/core/src/store/local/capabilities.ts +115 -0
  170. package/packages/core/src/store/local/store.ts +86 -56
  171. package/packages/core/src/store/reduced-reads.ts +32 -1
  172. package/packages/core/src/store/reducer-value-read.ts +235 -0
  173. package/packages/core/src/store/reducer-value-shapes.json +6722 -6475
  174. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  175. package/packages/core/src/store/reducer-values.ts +36 -204
  176. package/packages/core/src/store/remote/client.ts +169 -29
  177. package/packages/core/src/store/remote/compatibility.ts +113 -56
  178. package/packages/core/src/store/remote/credentials.ts +4 -1
  179. package/packages/core/src/store/remote/protocol.ts +3 -0
  180. package/packages/core/src/store/remote/released-clients.json +22 -0
  181. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  182. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  183. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  184. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  185. package/packages/core/src/store/remote/retry.ts +406 -0
  186. package/packages/core/src/store/rollup-lease.ts +41 -0
  187. package/packages/core/src/store/rollups.ts +7 -38
  188. package/packages/core/src/store/snapshots.ts +1 -1
  189. package/packages/core/src/testing/dispatch-read-budget.ts +409 -14
  190. package/packages/core/src/testing/import-graph.ts +78 -0
  191. package/packages/core/src/testing/index.ts +2 -0
  192. package/packages/core/src/testing/invocation-budget.ts +42 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +602 -40
  194. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  195. package/packages/core/src/testing/slot-agreement.ts +52 -0
  196. package/packages/core/src/web/assets/app.js +5 -5
  197. package/packages/core/src/web/overview-source.ts +19 -6
  198. package/skills/guide/SKILL.md +245 -103
  199. package/skills/guide/references/integration-tree.md +33 -18
  200. package/skills/guide/references/merge-policy.md +7 -2
  201. package/skills/guide/references/operator-api.md +48 -25
  202. package/skills/guide/references/optimization-nodes.md +10 -8
  203. package/skills/guide/references/plugin-authoring.md +46 -18
  204. package/skills/guide/references/remote-store-protocol.md +51 -12
  205. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  206. package/skills/guide/references/restacking.md +48 -3
  207. package/skills/guide/references/setup.md +2 -1
  208. package/skills/guide/references/ticket-migration.md +2 -2
  209. package/skills/operate/SKILL.md +114 -65
  210. package/skills/plan/SKILL.md +4 -3
  211. package/skills/spec/SKILL.md +9 -5
  212. package/skills/tickets/SKILL.md +25 -17
  213. package/templates/hosted-service/package.json +2 -2
@@ -25,7 +25,12 @@ import {
25
25
  type MissingAccountCredential,
26
26
  } from '../accounts/availability'
27
27
 
28
- import { preserveWorkspaceBeforeRelease, supersedeRestorationHeads } from './workspace-preservation'
28
+ import {
29
+ preserveWorkspaceBeforeRelease,
30
+ recordAbortPreservationFailure,
31
+ supersedeRestorationHeads,
32
+ WorkspaceLeaseLive,
33
+ } from './workspace-preservation'
29
34
  import { WorkspaceCleanupRequired } from '../ports/types'
30
35
  import type { AgentContextCapture } from './agent-context'
31
36
  import type { AgentContextDiagnostic } from '../store/agent-context'
@@ -78,6 +83,7 @@ import {
78
83
  } from '../kernel/forge-checks'
79
84
  import { actionableCommands, leafLandingDeclineReason } from '../kernel/landing-readiness'
80
85
  import {
86
+ dispatcherAcknowledgesAbort,
81
87
  escalationsBeyondJanitor,
82
88
  janitorBlocked,
83
89
  janitorDeferral,
@@ -107,23 +113,38 @@ import {
107
113
  type ForgeRateLimitSnapshot,
108
114
  } from '../ports/forge-telemetry'
109
115
  import {
116
+ admissionBarred,
110
117
  buildPriority,
118
+ claimDemand,
111
119
  dispatchCapacity,
120
+ EARLY_START_TIERS,
121
+ LATE_START_TIERS,
122
+ START_REQUESTS_PER_TICK,
123
+ startBarrier,
124
+ type AdmissionKind,
112
125
  epilogueLeaf,
113
126
  intakeCapacity,
114
- nodeCapacity,
115
- occupiesCapacity,
127
+ leafHoldsSlot,
128
+ escalationCarryInput,
129
+ leafOutsideWait,
130
+ leafSlotRequest,
131
+ legacyNodeRunner,
132
+ legacyNodeRunnerNeed,
133
+ nodeHoldsSlot,
134
+ nodeRunnerWork,
135
+ nodeSlotNeed,
116
136
  reservedAhead,
117
137
  settlementDue,
118
138
  settlementKey,
119
- slotRequest,
120
139
  startCapacity,
121
140
  startClaimDemand,
122
141
  strandedNodeWorkspace,
123
- urgentClaimDemand,
124
142
  type CapacityBuild,
143
+ type ClaimDemand,
125
144
  type DispatchCapacity,
145
+ type NodeSlotNeed,
126
146
  } from '../kernel/dispatch-capacity'
147
+ import { launchInFlight } from '../kernel/verify-stage-state'
127
148
  import { attemptCreationKey } from '../kernel/attempt-creation-key'
128
149
  import {
129
150
  ExecutionFactsMissingError,
@@ -241,7 +262,17 @@ import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../st
241
262
  import { ensureExecutionProgress } from './execution-no-progress'
242
263
  import { ticketIdentity } from '../ports/tickets/identity'
243
264
  import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
244
- import { ticketPriority, urgentFirstBy } from '../ports/tickets/priority'
265
+ import {
266
+ byPriorityBy,
267
+ createdPriorityFields,
268
+ priorityRank,
269
+ START_TIERS,
270
+ startTierFields,
271
+ startTierOf,
272
+ TICKET_PRIORITIES,
273
+ ticketPriority,
274
+ type StartTier,
275
+ } from '../ports/tickets/priority'
245
276
  import { ensureDispatchBudget } from './dispatch-failure-budget'
246
277
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
247
278
  /**
@@ -288,11 +319,7 @@ import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
288
319
  import { isRemoteWorkspace } from '../events/workspace-remote'
289
320
  import type { AbEvent, EventWrite } from '../events/catalog'
290
321
  import type { AbortDestination, EventPayload, PinnedAsset } from '../events/payloads'
291
- import type {
292
- RepositoryEventPayload,
293
- TicketStartOutcome,
294
- TicketStartPriority,
295
- } from '../events/repository'
322
+ import type { RepositoryEventPayload, TicketStartOutcome } from '../events/repository'
296
323
  import { ticketStartKey, type PendingTicketStart, type TicketStarts } from '../kernel/ticket-starts'
297
324
  import { handbackIdentity } from '../kernel/ticket-handbacks'
298
325
  import type { IdSource } from '../ids'
@@ -315,14 +342,19 @@ import {
315
342
  import type { BuildState } from '../kernel/reducer'
316
343
  import type { ArtifactRef, TicketRef } from '../ontology'
317
344
  import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution'
345
+ import {
346
+ attributeRecoveryStep,
347
+ isRecoveryDeferred,
348
+ type WorkspaceRecoveryStep,
349
+ } from '../ports/workspace/recovery-step'
318
350
  import type {
319
351
  DependencyState,
320
352
  Forge,
321
353
  HeadChecks,
322
354
  IssueLink,
323
355
  PrState,
356
+ BuildPriority,
324
357
  Ticket,
325
- TicketPriority,
326
358
  TicketSource,
327
359
  WorkspaceProvider,
328
360
  WorkspaceProvisionResult,
@@ -364,7 +396,10 @@ import { recordInfrastructureFailure as appendInfrastructureFailure } from './in
364
396
  import { settleOpenExecution } from './execution-settlement'
365
397
  import { isWorkDigest, RepoViewStore } from './repo-view'
366
398
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
367
- import { settlePublicationFactsBeforeRelease } from './publication-loss'
399
+ import {
400
+ recordPublicationLossBeforeRelease,
401
+ settlePublicationFactsBeforeRelease,
402
+ } from './publication-loss'
368
403
 
369
404
  // ── Readiness resolution (SPEC §3.3) ─────────────────────────────────────────
370
405
 
@@ -750,7 +785,7 @@ interface TargetedDispatch {
750
785
  measured: CapacityBuild[]
751
786
  /** Slots left for each start tier (`startCapacity`). A claim spends only
752
787
  * its own tier's: lower tiers already reserved it as a pending request. */
753
- budgets: Record<TicketStartPriority, number>
788
+ budgets: Record<StartTier, number>
754
789
  }
755
790
 
756
791
  /** An active build's ticket ref, normalized through recorded migrations. */
@@ -760,9 +795,16 @@ interface ActiveTicketRef {
760
795
  ref: TicketRef
761
796
  }
762
797
 
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']
798
+ /** Gate-passing ticket claims one admission scan left waiting for a slot, by
799
+ * the levels that reserve ahead of lower-level parked work. */
800
+ type ScanClaimWaiting = { urgent?: number; high?: number; normal?: number }
801
+
802
+ /** Every request one start pass settled: its ticket (`source:id`), seq and
803
+ * tier, and whether it started a build. */
804
+ interface StartPassResult {
805
+ settled: { ticket: string; seq: number; tier: StartTier; started: boolean }[]
806
+ }
807
+
766
808
  /** Hosted active-build identities one tick resolves; each build once in its life. */
767
809
  const IDENTITY_RESOLUTIONS_PER_TICK = 16
768
810
  /** Released identity slugs one projection append carries. */
@@ -881,6 +923,11 @@ export interface TickOpts {
881
923
  * exactly as capacity exhaustion already defers tickets. Absent ⇒ unbounded
882
924
  * (today's exact behavior). */
883
925
  deadlineAt?: number
926
+ /** Bounded invocation's work signal: once aborted the tick starts no new
927
+ * unit of work, exactly as when the clock passes `deadlineAt`. In-flight
928
+ * requests made through the budgeted adapters are cancelled by the same
929
+ * signal. Absent ⇒ only `deadlineAt` bounds the tick. */
930
+ workSignal?: AbortSignal
884
931
  }
885
932
 
886
933
  /** Process-local launch coordination result. Durable lease acquisition remains
@@ -1033,6 +1080,15 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
1033
1080
 
1034
1081
  export const SWEEP_PIN_CACHE_CAPACITY = 128
1035
1082
 
1083
+ /** Name the recovery step a workspace failure happened in. Missing account
1084
+ * credentials stay unwrapped: the dispatcher holds for them by type instead
1085
+ * of recording a failure. */
1086
+ function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1087
+ return error instanceof MissingAccountCredentialsError
1088
+ ? error
1089
+ : attributeRecoveryStep(step, error)
1090
+ }
1091
+
1036
1092
  export class Dispatcher {
1037
1093
  // Only scheduling is cached. Eligibility facts still come from durable state,
1038
1094
  // and each admitted verification/publication samples the source this pass.
@@ -1284,18 +1340,21 @@ export class Dispatcher {
1284
1340
  private tickLaunched: ReadonlySet<string> = new Set()
1285
1341
  /** Per tick: finished leaves the admission gate turned away or deferred,
1286
1342
  * 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
1343
+ private readonly slotWaiters = new Map<string, BuildPriority>()
1344
+ /** Per tick, in visit order: parked admissions that would have taken a free
1345
+ * slot before this tick's dispatch evaluated higher-level claims (SPEC §12
1290
1346
  * "Slot admission order"). Nothing was written for them;
1291
1347
  * `admitDeferredParked` retries each through its generic path. */
1292
1348
  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. */
1349
+ /** Nodes `admitWaitingNodes` admitted in its current verification pass, so
1350
+ * proposer admission counts them even when provisioning or launch failed. */
1351
+ private passNodeAdmissions: Set<string> | undefined
1352
+ /** Per tick: admission may defer non-urgent parked work. Opened by
1353
+ * `runTick` when claims can run, closed once claims were evaluated. */
1295
1354
  private admissionBoundary = false
1296
- /** Per tick: this tick's admission scan completed its urgent decision. Only
1355
+ /** Per tick: this tick's admission scan decided claims at every level. Only
1297
1356
  * `dispatch` sets it. */
1298
- private urgentEvaluated = false
1357
+ private claimsEvaluated = false
1299
1358
  /** Per tick: the deferral key this tick's admission scan was forced for. */
1300
1359
  private forcedDeferralKey: string | undefined
1301
1360
  /** In memory: the last deferral key whose forced scan completed and whose
@@ -1323,6 +1382,19 @@ export class Dispatcher {
1323
1382
  /** While the start pass's targeted dispatch runs: its deferral checks
1324
1383
  * serve this tick's retained facts (`servedBuildFacts`). */
1325
1384
  private startPass = false
1385
+ /** Per tick: late start tiers already honored, inside ordinary intake or
1386
+ * after it; each is honored at most once a tick. */
1387
+ private readonly lateStartTiersHonored = new Set<StartTier>()
1388
+ /** Per tick: start requests the late passes may still evaluate. Intake runs
1389
+ * a late pass before each level's first ready ticket, so the passes share
1390
+ * one allowance and a tick reads no more requests than one late pass. */
1391
+ private lateStartRequests = START_REQUESTS_PER_TICK
1392
+ /** Per tick: the start barrier (`startBarrier`), the highest tier with a
1393
+ * pending request the tick's allowance leaves unread. Sampled when the tick
1394
+ * starts, so admission before any start pass already respects it, and
1395
+ * raised by a pass that finds a request filed since unread. Every admission
1396
+ * path consults it through `admissionBarred` (SPEC §12). */
1397
+ private startBarrier: StartTier | undefined
1326
1398
  /** Per tick: the janitor's work listing, and the nonterminal children of
1327
1399
  * each node indexed from it on the first landing turn that needs them. The
1328
1400
  * landing gate reads its turn candidates here, never from a new listing. */
@@ -1381,9 +1453,15 @@ export class Dispatcher {
1381
1453
  * loops consult this before starting each new forge/store transport call,
1382
1454
  * bounding the tick's overrun to the one call already in flight. */
1383
1455
  private outOfBudget(opts: TickOpts): boolean {
1456
+ return this.budgetSpent(opts) || this.deps.holdsRepoAuthority?.() === false
1457
+ }
1458
+
1459
+ /** The invocation-budget half of `outOfBudget`: no clock read and no
1460
+ * authority check without a deadline, so an unbounded tick is unchanged. */
1461
+ private budgetSpent(opts: TickOpts): boolean {
1384
1462
  return (
1385
1463
  (opts.deadlineAt !== undefined && this.deps.clock().getTime() >= opts.deadlineAt) ||
1386
- this.deps.holdsRepoAuthority?.() === false
1464
+ opts.workSignal?.aborted === true
1387
1465
  )
1388
1466
  }
1389
1467
 
@@ -1544,10 +1622,13 @@ export class Dispatcher {
1544
1622
  this.integrationPublicationInputs = undefined
1545
1623
  this.nodePollingTickReads.clear()
1546
1624
  this.slotWaiters.clear()
1625
+ this.lateStartTiersHonored.clear()
1626
+ this.lateStartRequests = START_REQUESTS_PER_TICK
1627
+ this.startBarrier = undefined
1547
1628
  this.parkedSettled.clear()
1548
1629
  this.deferredAdmissions.clear()
1549
1630
  this.admissionBoundary = false
1550
- this.urgentEvaluated = false
1631
+ this.claimsEvaluated = false
1551
1632
  this.forcedDeferralKey = undefined
1552
1633
  // One immutable config for this complete decision pass. A reload racing the
1553
1634
  // tick is observed by the next tick, never half-way through this one.
@@ -1575,9 +1656,16 @@ export class Dispatcher {
1575
1656
  const paused = repoFacts.settings.paused
1576
1657
  this.tickAcceptsNewWork = opts.acceptNewWork !== false
1577
1658
  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)
1659
+ // Lower-level parked work never takes a free slot before this tick's
1660
+ // dispatch has evaluated higher-level claims, while claims can run at all.
1661
+ this.admissionBoundary = !opts.observationOnly && this.claimsCanRun(opts, paused)
1662
+ // Start requests this tick cannot read hold back lower-level admission,
1663
+ // whichever stage admits it; they reserve only while they can be
1664
+ // honored (`startClaims`).
1665
+ this.startBarrier =
1666
+ Object.keys(this.startClaims()).length > 0
1667
+ ? startBarrier(Object.values(repoFacts.ticketStarts.pending))
1668
+ : undefined
1581
1669
  const autoMergeSeedFact = undefined
1582
1670
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
1583
1671
  // provider liveness and settle their completion, lease, and publication.
@@ -1619,26 +1707,27 @@ export class Dispatcher {
1619
1707
  if (this.outOfBudget(opts)) return report
1620
1708
  // Operator start requests are independent of intake: they claim only the
1621
1709
  // 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
- ])
1710
+ // requests run here, ahead of ordinary claims; high, normal and low
1711
+ // requests run inside intake, after higher-level claims and before their
1712
+ // own level's ready tickets, or after intake when it reaches no ticket of
1713
+ // their level (SPEC §12 "Slot admission order").
1714
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, EARLY_START_TIERS)
1628
1715
  if (this.outOfBudget(opts)) return report
1629
1716
  if (opts.acceptNewWork !== false) {
1630
1717
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1631
1718
  }
1632
1719
  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'])
1720
+ // Late tiers intake did not reach: ordinary claims left their reserved
1721
+ // slots free.
1722
+ const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1723
+ if (!this.outOfBudget(opts) && lateTiers.length > 0)
1724
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, lateTiers)
1636
1725
  // Fire-and-forget by contract: long synthesize/review sessions must not
1637
1726
  // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1638
1727
  // watch ticks. Durable pause and infrastructure-error stops suppress
1639
1728
  // launch. Pending control commands still launch the runner so the kernel
1640
1729
  // can settle them under the repository lease.
1641
- await this.triggerHarvest()
1730
+ if (!this.budgetSpent(opts)) await this.triggerHarvest()
1642
1731
  await this.captureAgentContext(report, opts)
1643
1732
  return report
1644
1733
  }
@@ -1879,8 +1968,9 @@ export class Dispatcher {
1879
1968
  /** Admit pending operator start requests of the given tiers through
1880
1969
  * `dispatch()`'s gates and settle each one that reaches a decision. Zero
1881
1970
  * 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,
1971
+ * per request over the view-cached build digests: at most
1972
+ * START_REQUESTS_PER_TICK a tick for the early tiers, and as many shared by
1973
+ * every late pass of the tick. Waiting conditions (pause, no slot in the request's tier,
1884
1974
  * creation holds, an in-flight preparation, a failed dependency read, a
1885
1975
  * source error, the tick budget) leave the request pending. */
1886
1976
  private async honorStartRequests(
@@ -1889,15 +1979,45 @@ export class Dispatcher {
1889
1979
  autoMergeUser: string | undefined,
1890
1980
  paused: boolean,
1891
1981
  opts: TickOpts,
1892
- tiers: readonly TicketStartPriority[],
1982
+ tiers: readonly StartTier[],
1983
+ ): Promise<StartPassResult> {
1984
+ const result: StartPassResult = { settled: [] }
1985
+ for (const tier of tiers)
1986
+ if (LATE_START_TIERS.includes(tier)) this.lateStartTiersHonored.add(tier)
1987
+ await this.honorStartRequestTiers(report, launched, autoMergeUser, paused, opts, tiers, result)
1988
+ return result
1989
+ }
1990
+
1991
+ private async honorStartRequestTiers(
1992
+ report: TickReport,
1993
+ launched: Set<string>,
1994
+ autoMergeUser: string | undefined,
1995
+ paused: boolean,
1996
+ opts: TickOpts,
1997
+ tiers: readonly StartTier[],
1998
+ result: StartPassResult,
1893
1999
  ): Promise<void> {
1894
2000
  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))
2001
+ const rank = (request: PendingTicketStart) => START_TIERS.indexOf(startTierOf(request))
2002
+ const late = tiers.every((tier) => LATE_START_TIERS.includes(tier))
2003
+ // A higher tier's unread request stays ahead of these tiers' starts.
2004
+ const readable = tiers.filter((tier) => !this.admissionBarred('start', tier))
2005
+ const matching = Object.values(starts.pending)
2006
+ .filter((request) => readable.includes(startTierOf(request)))
1898
2007
  .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
2008
+ const pending = matching.slice(0, late ? this.lateStartRequests : START_REQUESTS_PER_TICK)
2009
+ if (paused) return
2010
+ // A request filed since the tick started can push one it sampled out of
2011
+ // the allowance: the barrier rises to the highest unread tier.
2012
+ const unread = matching[pending.length]
2013
+ if (
2014
+ unread !== undefined &&
2015
+ this.claimGateOpen() &&
2016
+ (this.startBarrier === undefined || rank(unread) < START_TIERS.indexOf(this.startBarrier))
2017
+ )
2018
+ this.startBarrier = startTierOf(unread)
2019
+ if (pending.length === 0) return
2020
+ if (late) this.lateStartRequests -= pending.length
1901
2021
  const { tickets, config } = this.deps
1902
2022
  const migrations = this.store.repositoryFacts().ticketMigrations
1903
2023
  // Deferred mixed-version builds are still active: include them, so a
@@ -1992,20 +2112,18 @@ export class Dispatcher {
1992
2112
  // checked, needs the pass.
1993
2113
  const now = this.deps.clock()
1994
2114
  const measured = await this.capacityBuilds(launched, true)
1995
- const projection = dispatchCapacity(measured, config.capacity, now, undefined, {
1996
- urgentClaims: this.urgentClaims(),
2115
+ const projection = dispatchCapacity(measured, config.capacity, now, {
2116
+ claims: this.claims(),
1997
2117
  startRequests: this.startClaims(),
1998
2118
  })
1999
2119
  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
- }
2120
+ const budgets = Object.fromEntries(
2121
+ START_TIERS.map((tier) => [tier, startCapacity(projection, adjust, tier)]),
2122
+ ) as Record<StartTier, number>
2005
2123
  const open = new Set(Object.values(starts.pending).map(({ seq }) => seq))
2006
2124
  for (const seq of this.startBlockersChecked)
2007
2125
  if (!open.has(seq)) this.startBlockersChecked.delete(seq)
2008
- const free = (request: PendingTicketStart) => budgets[request.priority] > 0
2126
+ const free = (request: PendingTicketStart) => budgets[startTierOf(request)] > 0
2009
2127
  const passing = candidates.filter(
2010
2128
  ({ request, ticket }) =>
2011
2129
  free(request) ||
@@ -2048,6 +2166,12 @@ export class Dispatcher {
2048
2166
  if (settled === undefined) continue
2049
2167
  const { outcome, ...extra } = settled
2050
2168
  await this.settleStartRequest(request, outcome, extra)
2169
+ result.settled.push({
2170
+ ticket: `${ticket.ref.source}:${ticket.ref.id}`,
2171
+ seq: request.seq,
2172
+ tier: startTierOf(request),
2173
+ started: outcome === 'started',
2174
+ })
2051
2175
  }
2052
2176
  }
2053
2177
  }
@@ -2135,7 +2259,7 @@ export class Dispatcher {
2135
2259
  await this.store.refreshJournal()
2136
2260
  const current =
2137
2261
  this.store.repositoryFacts().ticketStarts.pending[ticketStartKey(request.ticket)]
2138
- return current?.seq === request.seq && current.priority === request.priority
2262
+ return current?.seq === request.seq && startTierOf(current) === startTierOf(request)
2139
2263
  }
2140
2264
 
2141
2265
  /** Settle one start request once. The journal is refreshed first, so a
@@ -2158,7 +2282,7 @@ export class Dispatcher {
2158
2282
  payload: {
2159
2283
  request: request.seq,
2160
2284
  ticket: request.ticket,
2161
- priority: current.priority,
2285
+ ...startTierFields(startTierOf(current)),
2162
2286
  outcome,
2163
2287
  ...(extra.slug !== undefined ? { slug: extra.slug } : {}),
2164
2288
  ...(detail ? { detail } : {}),
@@ -2328,7 +2452,7 @@ export class Dispatcher {
2328
2452
  }
2329
2453
 
2330
2454
  /** `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. */
2455
+ * deferral: a deferred admission waits on this tick's higher-level claims. */
2332
2456
  private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
2333
2457
  const digest = (await this.repoBuildDigests())
2334
2458
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
@@ -2365,8 +2489,9 @@ export class Dispatcher {
2365
2489
  private async completeScan(
2366
2490
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
2367
2491
  report: TickReport,
2368
- urgentWaiting = 0,
2492
+ waiting: ScanClaimWaiting = {},
2369
2493
  ): Promise<void> {
2494
+ const { urgent: urgentWaiting = 0, high: highWaiting = 0, normal: normalWaiting = 0 } = waiting
2370
2495
  const payload = {
2371
2496
  startedAt: checkpoint.startedAt,
2372
2497
  mode: checkpoint.mode,
@@ -2380,11 +2505,16 @@ export class Dispatcher {
2380
2505
  creationWithheld: report.creationWithheld,
2381
2506
  creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
2382
2507
  ...(urgentWaiting > 0 ? { urgentWaiting } : {}),
2508
+ ...(highWaiting > 0 ? { highWaiting } : {}),
2509
+ ...(normalWaiting > 0 ? { normalWaiting } : {}),
2383
2510
  }
2384
2511
  const previous = this.latestScan()
2512
+ // The key loop sees only present keys, so absent counts compare here.
2385
2513
  const unchanged =
2386
2514
  previous !== undefined &&
2387
2515
  previous.urgentWaiting === payload.urgentWaiting &&
2516
+ previous.highWaiting === payload.highWaiting &&
2517
+ previous.normalWaiting === payload.normalWaiting &&
2388
2518
  Object.keys(payload)
2389
2519
  .filter((key) => key !== 'startedAt')
2390
2520
  .every(
@@ -2487,7 +2617,8 @@ export class Dispatcher {
2487
2617
  if (!this.accountsAvailable()) return 'already-active'
2488
2618
  if (await this.forgeCoolingDown()) return 'already-active'
2489
2619
  if (await deferMixedVersion(this.store, slug)) return 'already-active'
2490
- const launchState = (await this.store.buildFacts(slug)).state
2620
+ const launchFacts = await this.store.buildFacts(slug)
2621
+ const launchState = launchFacts.state
2491
2622
  // A landed node has nothing left to run; the janitor settles it.
2492
2623
  if (nodeLanded(launchState)) return 'already-active'
2493
2624
  if (launchState.kind === 'node' && !launchState.nodeRestack?.conflict) {
@@ -2508,6 +2639,14 @@ export class Dispatcher {
2508
2639
  if (launched.has(slug)) return 'already-active'
2509
2640
  if (launchState.kind !== 'node' && (await this.leafAdmission(slug)) !== 'admit')
2510
2641
  return 'already-active'
2642
+ // Every node launch path (cascade, admission, sweep, startup resume) runs
2643
+ // only work the node holds a slot for (SPEC §12); abort and pause
2644
+ // acknowledgements stay ungated.
2645
+ if (launchState.kind === 'node') {
2646
+ const record = await this.store.getBuild(slug)
2647
+ if (record === null || !this.nodeRelaunchAdmitted(record, launchFacts))
2648
+ return 'already-active'
2649
+ }
2511
2650
  launched.add(slug)
2512
2651
  const facts = (await readBuildFacts(this.store, slug)).value
2513
2652
  // Callers reap and reprovision a flagged workspace; an agent never starts
@@ -3158,35 +3297,57 @@ export class Dispatcher {
3158
3297
  * then release each one's provisioning lease, in that order. Never awaited
3159
3298
  * by a tick. */
3160
3299
  async stopProvisioning(): Promise<void> {
3161
- const entries = [...this.continuations.values()]
3162
- for (const entry of entries) entry.controller.abort()
3163
- for (const entry of entries) {
3164
- try {
3165
- const events = (await readBuildFacts(this.store, entry.slug)).value
3166
- if (this.openProvisionMarker(events) !== undefined) {
3167
- const attempt = events.dispatchFailureCount + 1
3168
- await this.store.append(entry.slug, {
3169
- actor: DISPATCHER,
3170
- type: 'dispatch.failed',
3171
- payload: {
3172
- stage: 'workspace',
3173
- attempt,
3174
- error:
3175
- 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3176
- abandoned: 'teardown',
3177
- },
3178
- })
3300
+ this.abortProvisioning()
3301
+ // Every signalled continuation, including one that already exited on its
3302
+ // abort since `abortProvisioning` ran at a bounded invocation's deadline.
3303
+ const entries = [...this.abortedContinuations.values()]
3304
+ this.abortedContinuations.clear()
3305
+ // Entries settle independently, each keeping fact-then-release order, so
3306
+ // one entry whose store call stalls cannot starve the others.
3307
+ await Promise.allSettled(
3308
+ entries.map(async (entry) => {
3309
+ try {
3310
+ const events = (await readBuildFacts(this.store, entry.slug)).value
3311
+ if (this.openProvisionMarker(events) !== undefined) {
3312
+ const attempt = events.dispatchFailureCount + 1
3313
+ await this.store.append(entry.slug, {
3314
+ actor: DISPATCHER,
3315
+ type: 'dispatch.failed',
3316
+ payload: {
3317
+ stage: 'workspace',
3318
+ attempt,
3319
+ error:
3320
+ 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3321
+ abandoned: 'teardown',
3322
+ },
3323
+ })
3324
+ }
3325
+ } catch {
3326
+ // The durable marker plus the released lease still gate adoption.
3179
3327
  }
3180
- } catch {
3181
- // The durable marker plus the released lease still gate adoption.
3182
- }
3183
- try {
3184
- await this.store.releaseLease(entry.slug, entry.instance)
3185
- } catch {
3186
- // Expiry fences an ambiguous release.
3187
- }
3328
+ try {
3329
+ await this.store.releaseLease(entry.slug, entry.instance)
3330
+ } catch {
3331
+ // Expiry fences an ambiguous release.
3332
+ }
3333
+ }),
3334
+ )
3335
+ }
3336
+
3337
+ /** Synchronously signal every live provisioning continuation. A bounded
3338
+ * invocation calls it the moment its work deadline passes, so an aborted
3339
+ * provider call is classified as teardown abandonment, never a failure;
3340
+ * `stopProvisioning` later records the facts and releases the leases. */
3341
+ abortProvisioning(): void {
3342
+ for (const entry of this.continuations.values()) {
3343
+ this.abortedContinuations.set(entry.instance, entry)
3344
+ entry.controller.abort()
3188
3345
  }
3189
3346
  }
3347
+ /** Continuations signalled for teardown whose abandonment `stopProvisioning`
3348
+ * has not recorded yet. An aborted continuation removes itself from
3349
+ * `continuations` as it exits, so teardown keeps its own record. */
3350
+ private readonly abortedContinuations = new Map<string, ProvisionContinuation>()
3190
3351
 
3191
3352
  // ── a. Janitor (SPEC §15.7, D1) ────────────────────────────────────────────
3192
3353
 
@@ -3580,19 +3741,19 @@ export class Dispatcher {
3580
3741
  return
3581
3742
  }
3582
3743
  }
3583
- // Abort is destructive human judgment and therefore outranks a queued
3584
- // discard when both requests raced into the same stream.
3585
- if (
3586
- !executionLeaseLive &&
3587
- janitorStatus(state) === 'queued' &&
3588
- state.pendingCommands.some((command) => command.command === 'abort')
3589
- ) {
3590
- const acknowledged = await this.store.append(record.slug, {
3744
+ // The dispatcher acknowledges any leaf abort with no runner to hear
3745
+ // it: queued, paused or blocked with no live execution lease. The
3746
+ // lease sweep and startup resume stand aside for the same builds, so
3747
+ // no workspace is provisioned and no runner started just to
3748
+ // acknowledge. Abort is destructive human judgment and therefore
3749
+ // outranks a queued discard when both requests raced into the same
3750
+ // stream.
3751
+ if (!executionLeaseLive && dispatcherAcknowledgesAbort(state)) {
3752
+ await this.store.append(record.slug, {
3591
3753
  actor: DISPATCHER,
3592
3754
  type: 'build.aborted',
3593
3755
  payload: {},
3594
3756
  } satisfies EventWrite<'build.aborted'>)
3595
- void acknowledged
3596
3757
  // The view folded the acknowledgement it just appended.
3597
3758
  loaded = undefined
3598
3759
  operation = 'abort cleanup'
@@ -4081,8 +4242,9 @@ export class Dispatcher {
4081
4242
  const builds: CapacityBuild[] = []
4082
4243
  for (const { record, digest } of await this.repoBuildDigests(true)) {
4083
4244
  if (digest.terminal) continue
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.
4245
+ // A leaf with a runner provisioning or launched this tick has an
4246
+ // admission or launch record its served facts already include, so any
4247
+ // read this tick serves it, launch or not.
4086
4248
  const allocatedLeaf =
4087
4249
  digest.kind !== 'node' &&
4088
4250
  (this.continuations.has(record.slug) || !!launched?.has(record.slug))
@@ -4090,32 +4252,63 @@ export class Dispatcher {
4090
4252
  ? ((allocatedLeaf ? this.store.retainedBuildFacts(record.slug) : undefined) ??
4091
4253
  (await this.store.servedBuildFacts(record.slug)))
4092
4254
  : await this.store.buildFacts(record.slug)
4255
+ // A node's marker no longer holds a slot: it feeds the stranded
4256
+ // workspace release, the proposer skip and the anchor of a runner an
4257
+ // older dispatcher launched (`legacyNodeRunner`).
4258
+ const marker =
4259
+ digest.kind === 'node'
4260
+ ? served
4261
+ ? facts.provisionMarker
4262
+ : (await readBuildFacts(this.store, record.slug)).value.provisionMarker
4263
+ : undefined
4093
4264
  builds.push({
4094
4265
  record,
4095
4266
  state: facts.state,
4096
4267
  workspace: facts.workspace !== null,
4097
4268
  provisioning:
4098
4269
  digest.kind === 'node'
4099
- ? (served
4100
- ? facts.provisionMarker
4101
- : (await readBuildFacts(this.store, record.slug)).value.provisionMarker) !==
4102
- undefined
4270
+ ? marker !== undefined
4103
4271
  : this.continuations.has(record.slug) || !!launched?.has(record.slug),
4272
+ ...(marker !== undefined ? { provisioningSeq: marker.seq } : {}),
4104
4273
  restackDue: landingRestackDue(facts.state, facts.log),
4105
4274
  })
4106
4275
  }
4107
4276
  return builds
4108
4277
  }
4109
4278
 
4279
+ /** Whether this tick's start barrier holds back admission of this kind at
4280
+ * this level (`admissionBarred`): the one guard waiting work (parked
4281
+ * leaves, nodes and proposers through `slotAdmission`), ordinary claims and
4282
+ * start passes consult. */
4283
+ private admissionBarred(kind: AdmissionKind, level: StartTier): boolean {
4284
+ return admissionBarred(this.startBarrier, kind, level)
4285
+ }
4286
+
4110
4287
  /** 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()
4288
+ * `dispatch` and the admission boundary use. */
4289
+ private claimsCanRun(opts: Pick<TickOpts, 'acceptNewWork'>, paused: boolean): boolean {
4290
+ return opts.acceptNewWork !== false && !paused && this.claimGateOpen()
4291
+ }
4292
+
4293
+ /** Whether a ticket claim ranked above `level` can exist: in memory, over
4294
+ * builds the caller already read. Nothing outranks urgent. With the
4295
+ * source's priority capability any higher level can be on a ready ticket,
4296
+ * and normal tickets exist in every source, so low always may. Otherwise
4297
+ * only an open optimization node's attempts claim above normal, at the
4298
+ * node's level (`attemptClaimTiers`); this over-approximates a node with
4299
+ * no ready attempt by at most one deferral. */
4300
+ private higherClaimsPossible(level: BuildPriority, builds: readonly CapacityBuild[]): boolean {
4301
+ if (level === 'urgent') return false
4302
+ if (this.deps.tickets.priority || level === 'low') return true
4303
+ const rank = priorityRank(level)
4304
+ return builds.some(
4305
+ ({ state }) =>
4306
+ state.kind === 'node' &&
4307
+ state.status !== 'done' &&
4308
+ state.status !== 'aborted' &&
4309
+ state.optimization !== undefined &&
4310
+ state.optimization.stopped === undefined &&
4311
+ priorityRank(buildPriority(state)) < rank,
4119
4312
  )
4120
4313
  }
4121
4314
 
@@ -4127,51 +4320,76 @@ export class Dispatcher {
4127
4320
  return !(health && Date.parse(health.resetAt) > this.deps.clock().getTime())
4128
4321
  }
4129
4322
 
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
4323
+ /** Ticket claims by level the latest admission scan found waiting for a
4324
+ * slot. In memory: the journal view is refreshed each tick. */
4325
+ private claims(): ClaimDemand {
4326
+ return this.tickAcceptsNewWork ? claimDemand(this.store.repositoryFacts()) : {}
4134
4327
  }
4135
4328
 
4136
4329
  /** Pending operator start requests by tier; nothing while no claim can
4137
- * run. In memory, like `urgentClaims`. */
4138
- private startClaims(): Partial<Record<TicketStartPriority, number>> {
4330
+ * run. In memory, like `claims`. */
4331
+ private startClaims(): Partial<Record<StartTier, number>> {
4139
4332
  return this.claimGateOpen() ? startClaimDemand(this.store.repositoryFacts()) : {}
4140
4333
  }
4141
4334
 
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
4335
  /** 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. */
4336
+ * order"): for each level, urgent first, its parked work and then its
4337
+ * claims. `occupied` counts every other build holding a slot. A waiter
4338
+ * defers while claims can run, this tick's dispatch has not yet evaluated
4339
+ * them, and a higher-level claim can exist (`higherClaimsPossible`). */
4154
4340
  private slotAdmission(
4155
4341
  slug: string,
4156
- priority: TicketPriority,
4342
+ priority: BuildPriority,
4157
4343
  occupied: number,
4158
4344
  projection: DispatchCapacity,
4345
+ builds: readonly CapacityBuild[],
4159
4346
  ): 'admit' | 'wait' | 'defer' {
4347
+ if (this.admissionBarred('waiting', priority)) return 'wait'
4160
4348
  if (occupied + reservedAhead(projection, { slug, priority }) >= this.deps.config.capacity)
4161
4349
  return 'wait'
4162
- return priority === 'normal' && this.urgentBoundaryOpen() ? 'defer' : 'admit'
4163
- }
4164
-
4165
- /** Whether a leaf may reserve a runner now. A leaf that has not finished its
4166
- * pipeline already holds its slot, and abort and pause acknowledgements park
4167
- * at once, so only a finished leaf that must run again is gated: it needs
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. */
4350
+ const boundary =
4351
+ this.admissionBoundary &&
4352
+ this.claimsCanRun({ acceptNewWork: this.tickAcceptsNewWork }, this.tickPaused) &&
4353
+ this.higherClaimsPossible(priority, builds)
4354
+ return boundary ? 'defer' : 'admit'
4355
+ }
4356
+
4357
+ /** Whether a leaf may reserve a runner now (SPEC §12 "What holds a slot").
4358
+ * A leaf that holds its slot is admitted at once, and so are a leaf waiting
4359
+ * on the outside world and abort and pause acknowledgements, which are never
4360
+ * gated and confer no slot. Every other
4361
+ * leaf needs a free slot among every other build, after the work ahead of
4362
+ * it. Admission is the durable `slot.admitted` fact, appended on the state
4363
+ * this decision read before any lease claim, provisioning or launch, so a
4364
+ * crash after it keeps the slot; runner liveness never admits. A holding
4365
+ * leaf's launch appends one too, its launch record (`launchInFlight`),
4366
+ * unless one is already in flight or another runner's live lease will
4367
+ * refuse this launch; an acknowledgement appends none. A denial or
4368
+ * deferral is recorded only in memory, for this tick's intake reservation;
4369
+ * a deferral is retried after this tick's dispatch. */
4171
4370
  private async leafAdmission(slug: string): Promise<'admit' | 'wait' | 'defer'> {
4172
- const { state } = await this.store.buildFacts(slug)
4371
+ const facts = await this.store.buildFacts(slug)
4372
+ const { state } = facts
4373
+ const self = { state, restackDue: landingRestackDue(state, facts.log) }
4374
+ if (leafHoldsSlot(self)) {
4375
+ if (launchInFlight(escalationCarryInput(state))) return 'admit'
4376
+ // A live runner (a restarted dispatcher re-attempting a running build)
4377
+ // wins the lease claim, so this attempt launches nothing to record.
4378
+ const record = await this.store.getBuild(slug)
4379
+ if (record !== null && this.hasLiveExecutionLease(record)) return 'admit'
4380
+ const recorded = await this.store.appendIfCurrent(slug, state.lastSeq, {
4381
+ actor: DISPATCHER,
4382
+ type: 'slot.admitted',
4383
+ payload: {},
4384
+ })
4385
+ if (recorded === null) return 'wait'
4386
+ await this.store.servedBuildFacts(slug)
4387
+ return 'admit'
4388
+ }
4389
+ // A leaf waiting on the outside world can hold no slot, so what runs for
4390
+ // it (an acknowledgement) is neither gated nor admitted.
4173
4391
  if (
4174
- !(epilogueLeaf(state) || waitParked(state)) ||
4392
+ leafOutsideWait(self) ||
4175
4393
  state.pendingCommands.some(
4176
4394
  (command) => command.command === 'abort' || command.command === 'pause',
4177
4395
  )
@@ -4182,18 +4400,32 @@ export class Dispatcher {
4182
4400
  const capacity = this.deps.config.capacity
4183
4401
  const now = this.deps.clock()
4184
4402
  const priority = buildPriority(state)
4185
- const outcome = this.slotAdmission(
4403
+ let outcome = this.slotAdmission(
4186
4404
  slug,
4187
4405
  priority,
4188
4406
  dispatchCapacity(others, capacity, now).occupied,
4189
- dispatchCapacity(builds, capacity, now, undefined, {
4190
- urgentClaims: this.urgentClaims(),
4407
+ dispatchCapacity(builds, capacity, now, {
4408
+ claims: this.claims(),
4191
4409
  startRequests: this.startClaims(),
4192
4410
  }),
4411
+ builds,
4193
4412
  )
4194
4413
  if (outcome === 'admit') {
4195
- this.slotWaiters.delete(slug)
4196
- return 'admit'
4414
+ const request = leafSlotRequest(self)
4415
+ const admitted = await this.store.appendIfCurrent(slug, state.lastSeq, {
4416
+ actor: DISPATCHER,
4417
+ type: 'slot.admitted',
4418
+ payload: request === undefined ? {} : { request },
4419
+ })
4420
+ if (admitted !== null) {
4421
+ this.slotWaiters.delete(slug)
4422
+ // Retain the admitted facts, so this tick's capacity counts the
4423
+ // build as holding its slot from here on.
4424
+ await this.store.servedBuildFacts(slug)
4425
+ return 'admit'
4426
+ }
4427
+ // The state moved under the decision: decide again next tick.
4428
+ outcome = 'wait'
4197
4429
  }
4198
4430
  this.slotWaiters.set(slug, priority)
4199
4431
  if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
@@ -4203,11 +4435,11 @@ export class Dispatcher {
4203
4435
 
4204
4436
  /**
4205
4437
  * 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
4438
+ * has evaluated claims at every level. Each retry re-enters its generic path with
4207
4439
  * fresh state: a leaf through the lease sweep's per-build pass, a node
4208
4440
  * through node admission, a proposer through proposer admission. Without a
4209
4441
  * completed evaluation nothing launches: the waiters stay reserved in
4210
- * `slotWaiters` against normal claims and are decided again next tick.
4442
+ * `slotWaiters` against claims at their level and are decided again next tick.
4211
4443
  */
4212
4444
  private async admitDeferredParked(
4213
4445
  report: TickReport,
@@ -4221,7 +4453,10 @@ export class Dispatcher {
4221
4453
  this.lastForcedDeferralKey = undefined
4222
4454
  return
4223
4455
  }
4224
- if (!this.urgentEvaluated) return
4456
+ if (!this.claimsEvaluated) return
4457
+ // Tail stage: a spent invocation budget admits nothing and reads nothing;
4458
+ // the parked builds stay durable work for the next invocation.
4459
+ if (this.budgetSpent(opts)) return
4225
4460
  this.admissionBoundary = false
4226
4461
  for (const [slug, kind] of deferred) {
4227
4462
  if (this.outOfBudget(opts)) return
@@ -4234,14 +4469,22 @@ export class Dispatcher {
4234
4469
  else if (kind === 'node') {
4235
4470
  const builds = await this.capacityBuilds()
4236
4471
  const build = builds.find((entry) => entry.record.slug === slug)
4237
- if (build) await this.admitNode(build, this.deps.clock(), report, launched)
4472
+ // A deferred reconcile launches only through the cascade.
4473
+ if (build && nodeSlotNeed(build, this.deps.clock())?.request === 'reconcile')
4474
+ await this.cascadeNode(record, build.state, report, launched, opts)
4475
+ else if (build) await this.admitNode(build, this.deps.clock(), report, launched)
4238
4476
  } else {
4239
4477
  const builds = await this.capacityBuilds()
4240
- await this.admitProposers(builds, this.deps.clock(), 0, report, launched, opts, slug)
4478
+ await this.admitProposers(builds, this.deps.clock(), report, launched, opts, slug)
4241
4479
  }
4242
4480
  } catch (error) {
4243
4481
  rethrowAuthorityLapse(error)
4244
- if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4482
+ if (
4483
+ error instanceof ForgeRequestDeferred ||
4484
+ error instanceof MixedVersionDeferral ||
4485
+ isRecoveryDeferred(error)
4486
+ )
4487
+ continue
4245
4488
  if (error instanceof ForgeCooldown) throw error
4246
4489
  const message =
4247
4490
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -4282,19 +4525,58 @@ export class Dispatcher {
4282
4525
  )
4283
4526
  await this.releaseStrandedNodeWorkspaces(builds, now, launched, report, opts)
4284
4527
  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)
4528
+ await this.adoptLegacyNodeRunners(builds, now, report)
4529
+ // A node asking for a verification slot, and one admitted for
4530
+ // verification whose runner never started or was lost: nothing else
4531
+ // relaunches it.
4532
+ const waiting = builds.filter((build) => nodeRunnerWork(build, now)?.request === 'verification')
4533
+ const admitted = new Set<string>()
4534
+ this.passNodeAdmissions = admitted
4535
+ try {
4536
+ for (const build of waiting) {
4537
+ if (this.outOfBudget(opts)) return
4538
+ await this.admitNode(build, now, report, launched)
4539
+ }
4540
+ } finally {
4541
+ this.passNodeAdmissions = undefined
4542
+ }
4543
+ // A node admitted this pass holds its slot whatever its provisioning or
4544
+ // launch did: the proposers' capacity counts it from its durable facts,
4545
+ // and a holder that merely relaunched is already counted.
4546
+ for (const build of waiting)
4547
+ if (admitted.has(build.record.slug))
4548
+ build.state = (await this.store.servedBuildFacts(build.record.slug)).state
4549
+ await this.admitProposers(builds, now, report, launched, opts)
4550
+ }
4551
+
4552
+ /**
4553
+ * The version transition (SPEC §15 `slot.admitted`): record, once, the
4554
+ * admission of every node runner an older dispatcher launched without one
4555
+ * (`legacyNodeRunner`). The predicate counts such a runner as holding its
4556
+ * slot from the first tick, before this write; the fact keeps the slot
4557
+ * through a later crash or expired lease until that work is done. Pure over
4558
+ * the states this pass loaded, so nothing is read once no legacy runner
4559
+ * remains. An adopted entry is updated in place; a lost race is decided
4560
+ * again next pass.
4561
+ */
4562
+ private async adoptLegacyNodeRunners(
4563
+ builds: CapacityBuild[],
4564
+ now: Date,
4565
+ report: TickReport,
4566
+ ): Promise<void> {
4567
+ for (const build of builds) {
4568
+ const need = legacyNodeRunnerNeed(build, now)
4569
+ if (need === undefined) continue
4570
+ try {
4571
+ if (await this.admitNodeNeed(build.record.slug, build.state, need))
4572
+ build.state = (await this.store.servedBuildFacts(build.record.slug)).state
4573
+ } catch (error) {
4574
+ rethrowAuthorityLapse(error)
4575
+ report.janitorDiagnostics.push(
4576
+ `build ${build.record.slug}: node runner adoption failed — ${String(error)}`,
4577
+ )
4578
+ }
4296
4579
  }
4297
- await this.admitProposers(builds, now, launched.size - before, report, launched, opts)
4298
4580
  }
4299
4581
 
4300
4582
  /** One waiting node's admission: a measurement or its integration
@@ -4314,7 +4596,7 @@ export class Dispatcher {
4314
4596
  return
4315
4597
  await withForgeRequestContext({ build: record.slug }, async () => {
4316
4598
  try {
4317
- if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
4599
+ if ((await this.nodeAdmission(record.slug)) !== 'admit') return
4318
4600
  if (nodeMeasurementDue(state)) await this.prepareNodeMeasurement(record, report, launched)
4319
4601
  else await this.prepareIntegration(record, state, report, launched)
4320
4602
  } catch (error) {
@@ -4374,7 +4656,6 @@ export class Dispatcher {
4374
4656
  private async admitProposers(
4375
4657
  builds: CapacityBuild[],
4376
4658
  now: Date,
4377
- admittedThisPass: number,
4378
4659
  report: TickReport,
4379
4660
  launched: Set<string>,
4380
4661
  opts: TickOpts,
@@ -4387,11 +4668,11 @@ export class Dispatcher {
4387
4668
  (only === undefined || build.record.slug === only),
4388
4669
  )
4389
4670
  if (proposers.length === 0) return
4390
- const projection = dispatchCapacity(builds, this.deps.config.capacity, now, undefined, {
4391
- urgentClaims: this.urgentClaims(),
4671
+ const projection = dispatchCapacity(builds, this.deps.config.capacity, now, {
4672
+ claims: this.claims(),
4392
4673
  startRequests: this.startClaims(),
4393
4674
  })
4394
- let occupied = projection.occupied + admittedThisPass
4675
+ let occupied = projection.occupied
4395
4676
  for (const build of proposers) {
4396
4677
  if (this.outOfBudget(opts)) return
4397
4678
  const { record, state } = build
@@ -4418,27 +4699,30 @@ export class Dispatcher {
4418
4699
  await this.releaseWorkspace(record.slug, facts)
4419
4700
  return
4420
4701
  }
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
4702
+ // An admitted proposer holds its slot (one that lost its runner
4703
+ // relaunches); otherwise it needs a free one.
4704
+ const holding = nodeHoldsSlot(build, now) || legacyNodeRunner(build, now)
4705
+ const need = holding ? undefined : nodeSlotNeed(build, now)
4424
4706
  if (
4425
4707
  (holding
4426
4708
  ? state.status === 'paused' || state.status === 'blocked'
4427
- : slotRequest(build, now) !== 'propose') ||
4709
+ : need?.request !== 'propose') ||
4428
4710
  !state.nodeOpened ||
4429
4711
  !janitorDue(state.janitor, now)
4430
4712
  )
4431
4713
  return
4432
- if (!holding) {
4714
+ if (need !== undefined) {
4433
4715
  if (!this.accountsAvailable()) return
4434
4716
  const outcome = this.slotAdmission(
4435
4717
  record.slug,
4436
4718
  buildPriority(state),
4437
4719
  occupied,
4438
4720
  projection,
4721
+ builds,
4439
4722
  )
4440
4723
  if (outcome === 'defer') this.deferredAdmissions.set(record.slug, 'proposer')
4441
4724
  if (outcome !== 'admit') return
4725
+ if (!(await this.admitNodeNeed(record.slug, state, need))) return
4442
4726
  occupied++
4443
4727
  }
4444
4728
  await this.launchProposer(record, report, launched)
@@ -4782,40 +5066,88 @@ export class Dispatcher {
4782
5066
  await this.recordExhausted(record.slug)
4783
5067
  }
4784
5068
 
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'> {
5069
+ /** Whether a node may start runner work now (SPEC §12 "What holds a
5070
+ * slot"). A node that holds its slot is admitted at once: a relaunch after
5071
+ * a crashed runner or an expired lease, or continued provisioning. Every
5072
+ * other node's current request (`verification`, `reconcile` or `propose`)
5073
+ * needs a free slot among every other build, after the work ahead of it,
5074
+ * under the same tiers and urgent ordering as parked leaves. Admission is
5075
+ * the durable `slot.admitted {request, need}` fact, appended on the state
5076
+ * this decision read before anything is provisioned or launched, so a
5077
+ * crash or restart after it keeps the slot until that need is done. A
5078
+ * denial is recorded nowhere; a deferral is retried after this tick's
5079
+ * dispatch. */
5080
+ private async nodeAdmission(slug: string): Promise<'admit' | 'wait' | 'defer'> {
4795
5081
  const builds = await this.capacityBuilds()
4796
5082
  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
5083
  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'
5084
+ if (node === undefined) return 'wait'
5085
+ if (nodeHoldsSlot(node, now) || legacyNodeRunner(node, now)) return 'admit'
5086
+ const need = nodeSlotNeed(node, now)
5087
+ if (need === undefined) return 'wait'
5088
+ const capacity = this.deps.config.capacity
4805
5089
  const outcome = this.slotAdmission(
4806
5090
  slug,
4807
- node ? buildPriority(node.state) : 'normal',
4808
- occupied,
4809
- dispatchCapacity(builds, this.deps.config.capacity, now, identity, {
4810
- urgentClaims: this.urgentClaims(),
5091
+ buildPriority(node.state),
5092
+ dispatchCapacity(
5093
+ builds.filter((build) => build.record.slug !== slug),
5094
+ capacity,
5095
+ now,
5096
+ ).occupied,
5097
+ dispatchCapacity(builds, capacity, now, {
5098
+ claims: this.claims(),
4811
5099
  startRequests: this.startClaims(),
4812
5100
  }),
5101
+ builds,
4813
5102
  )
5103
+ if (outcome === 'admit')
5104
+ return (await this.admitNodeNeed(slug, node.state, need)) ? 'admit' : 'wait'
4814
5105
  if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
4815
5106
  this.deferredAdmissions.set(slug, 'node')
4816
5107
  return outcome
4817
5108
  }
4818
5109
 
5110
+ /** Record a node's admission for one runner need on the state the decision
5111
+ * read; false when the state moved under it (decided again next tick).
5112
+ * The admitted facts are retained so this tick's capacity counts the node
5113
+ * as holding its slot. */
5114
+ private async admitNodeNeed(
5115
+ slug: string,
5116
+ state: BuildState,
5117
+ need: NodeSlotNeed,
5118
+ ): Promise<boolean> {
5119
+ const admitted = await this.store.appendIfCurrent(slug, state.lastSeq, {
5120
+ actor: DISPATCHER,
5121
+ type: 'slot.admitted',
5122
+ payload: { request: need.request, need: need.key },
5123
+ } satisfies EventWrite<'slot.admitted'>)
5124
+ if (admitted === null) return false
5125
+ this.passNodeAdmissions?.add(slug)
5126
+ await this.store.servedBuildFacts(slug)
5127
+ return true
5128
+ }
5129
+
5130
+ /** A node's runner may be relaunched by the sweep: it holds its slot (or is
5131
+ * a legacy runner counted as holding one), or an abort or pause awaits its
5132
+ * acknowledgement. */
5133
+ private nodeRelaunchAdmitted(record: BuildRecord, facts: CurrentBuildFacts): boolean {
5134
+ const { state } = facts
5135
+ if (
5136
+ state.pendingCommands.some(
5137
+ (command) => command.command === 'abort' || command.command === 'pause',
5138
+ )
5139
+ )
5140
+ return true
5141
+ const now = this.deps.clock()
5142
+ const build: CapacityBuild = {
5143
+ record,
5144
+ state,
5145
+ workspace: facts.workspace !== null,
5146
+ restackDue: landingRestackDue(state, facts.log),
5147
+ }
5148
+ return nodeHoldsSlot(build, now) || legacyNodeRunner(build, now)
5149
+ }
5150
+
4819
5151
  private hasLiveExecutionLease(record: BuildRecord): boolean {
4820
5152
  return (
4821
5153
  record.lease !== undefined &&
@@ -7033,6 +7365,7 @@ export class Dispatcher {
7033
7365
  // publication's fate BEFORE the destructive reap. A guard failure is
7034
7366
  // recorded against the build — a stale workspace with an unrecorded
7035
7367
  // pending request is never reaped (the next tick retries).
7368
+ let step: WorkspaceRecoveryStep = 'fence'
7036
7369
  try {
7037
7370
  await preserveWorkspaceBeforeRelease({
7038
7371
  store: this.store,
@@ -7042,8 +7375,12 @@ export class Dispatcher {
7042
7375
  exec: this.deps.exec,
7043
7376
  reason,
7044
7377
  now: this.deps.clock(),
7378
+ onStep: (next) => {
7379
+ step = next
7380
+ },
7045
7381
  })
7046
7382
  events = (await readBuildFacts(this.store, slug)).value
7383
+ step = 'preserve'
7047
7384
  events = await settlePublicationFactsBeforeRelease(
7048
7385
  { store: this.store, settlePublication: this.settlePublication },
7049
7386
  slug,
@@ -7058,14 +7395,18 @@ export class Dispatcher {
7058
7395
  // A repository-wide forge cooldown or version deferral is not this
7059
7396
  // build's failure; the tick-level handlers own it.
7060
7397
  if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
7398
+ // The invocation deadline cut recovery short: nothing failed, so keep
7399
+ // the workspace and record nothing; the next invocation retries.
7400
+ if (isRecoveryDeferred(error)) return false
7061
7401
  // Any other preservation or settlement failure (an unknown fence, a
7062
7402
  // checkout that could not be inspected) retains the workspace and its
7063
7403
  // pending work and is attributed to this build, never to the tick.
7404
+ // The recorded error names the recovery step that failed.
7064
7405
  await this.recordInfrastructureFailure(slug, events, {
7065
7406
  provider: open.provider,
7066
7407
  workspaceRef: open.ref,
7067
7408
  operation: 'reconcile',
7068
- error,
7409
+ error: stepAttributed(step, error),
7069
7410
  cleanupPending: true,
7070
7411
  })
7071
7412
  return false
@@ -7101,8 +7442,12 @@ export class Dispatcher {
7101
7442
  return true
7102
7443
  } catch (error) {
7103
7444
  rethrowAuthorityLapse(error)
7445
+ // A cleanup the invocation deadline cut short is retried next time; it
7446
+ // is neither a cleanup attempt nor a failure.
7447
+ if (isRecoveryDeferred(error)) return false
7448
+ const failure = stepAttributed('cleanup', error)
7104
7449
  const message =
7105
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
7450
+ failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
7106
7451
  const _failed = await this.store.append(slug, {
7107
7452
  actor: DISPATCHER,
7108
7453
  type: 'infrastructure.cleanup-attempted',
@@ -7120,7 +7465,7 @@ export class Dispatcher {
7120
7465
  provider: open.provider,
7121
7466
  workspaceRef: open.ref,
7122
7467
  operation: 'reconcile',
7123
- error,
7468
+ error: failure,
7124
7469
  cleanupPending: true,
7125
7470
  })
7126
7471
  return false
@@ -7150,22 +7495,35 @@ export class Dispatcher {
7150
7495
  // pending publication BEFORE any provider cleanup call, while the
7151
7496
  // workspace still exists. The guard's append failure propagates — the
7152
7497
  // release never proceeds past an unrecorded pending request.
7153
- await preserveWorkspaceBeforeRelease({
7154
- store: this.store,
7155
- slug,
7156
- owner,
7157
- forge: this.deps.forge,
7158
- exec: this.deps.exec,
7159
- reason,
7160
- now: this.deps.clock(),
7161
- })
7162
- events = (await readBuildFacts(this.store, slug)).value
7163
- events = await settlePublicationFactsBeforeRelease(
7164
- { store: this.store, settlePublication: this.settlePublication },
7165
- slug,
7166
- events,
7167
- reason,
7168
- )
7498
+ if (reason === 'abort') {
7499
+ // Abort discards the build's work: preservation is best effort and the
7500
+ // pending publication is recorded lost without settling it, so a broken
7501
+ // workspace, guest or forge never holds the teardown hostage.
7502
+ await this.preserveBeforeAbortRelease(slug, owner)
7503
+ events = await recordPublicationLossBeforeRelease(
7504
+ { store: this.store },
7505
+ slug,
7506
+ (await readBuildFacts(this.store, slug)).value,
7507
+ reason,
7508
+ )
7509
+ } else {
7510
+ await preserveWorkspaceBeforeRelease({
7511
+ store: this.store,
7512
+ slug,
7513
+ owner,
7514
+ forge: this.deps.forge,
7515
+ exec: this.deps.exec,
7516
+ reason,
7517
+ now: this.deps.clock(),
7518
+ })
7519
+ events = (await readBuildFacts(this.store, slug)).value
7520
+ events = await settlePublicationFactsBeforeRelease(
7521
+ { store: this.store, settlePublication: this.settlePublication },
7522
+ slug,
7523
+ events,
7524
+ reason,
7525
+ )
7526
+ }
7169
7527
  const recovery = owner.recovery
7170
7528
  if (recovery !== undefined) {
7171
7529
  const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
@@ -7186,8 +7544,11 @@ export class Dispatcher {
7186
7544
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
7187
7545
  } catch (error) {
7188
7546
  rethrowAuthorityLapse(error)
7547
+ // Deferred to the next invocation: record nothing, keep the workspace.
7548
+ if (isRecoveryDeferred(error)) throw error
7549
+ const failure = stepAttributed('cleanup', error)
7189
7550
  const message =
7190
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
7551
+ failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
7191
7552
  const _failed = await this.store.append(slug, {
7192
7553
  actor: DISPATCHER,
7193
7554
  type: 'infrastructure.cleanup-attempted',
@@ -7205,7 +7566,7 @@ export class Dispatcher {
7205
7566
  provider: open.provider,
7206
7567
  workspaceRef: open.ref,
7207
7568
  operation: 'delete',
7208
- error,
7569
+ error: failure,
7209
7570
  cleanupPending: true,
7210
7571
  })
7211
7572
  throw error
@@ -7220,6 +7581,37 @@ export class Dispatcher {
7220
7581
  } satisfies EventWrite<'workspace.released'>)
7221
7582
  }
7222
7583
 
7584
+ /**
7585
+ * One best-effort preservation attempt ahead of an abort release. Only three
7586
+ * refusals stop the release: lost repository authority, a mixed-version
7587
+ * deferral, and a live execution lease. Every other failure records
7588
+ * `workspace.commits-lost` and returns so teardown continues.
7589
+ *
7590
+ * This is the one place a forge deferral (`ForgeRequestDeferred`, including
7591
+ * `ForgeCooldown`) does not propagate. The guarded forge has already refused
7592
+ * the archive and recorded the degradation, so no further forge call is made;
7593
+ * the archive is best effort under abort, and the release that follows is a
7594
+ * provider call, not a forge call. Do not route this catch through `fail()`
7595
+ * or a shared transient classifier: deferrals would gate teardown again.
7596
+ */
7597
+ private async preserveBeforeAbortRelease(slug: string, owner: WorkspaceProvider): Promise<void> {
7598
+ try {
7599
+ await preserveWorkspaceBeforeRelease({
7600
+ store: this.store,
7601
+ slug,
7602
+ owner,
7603
+ forge: this.deps.forge,
7604
+ exec: this.deps.exec,
7605
+ reason: 'abort',
7606
+ now: this.deps.clock(),
7607
+ })
7608
+ } catch (error) {
7609
+ rethrowAuthorityLapse(error)
7610
+ if (error instanceof MixedVersionDeferral || error instanceof WorkspaceLeaseLive) throw error
7611
+ await recordAbortPreservationFailure({ store: this.store, slug, error })
7612
+ }
7613
+ }
7614
+
7223
7615
  /** Only the authoritative forge may resolve a destination tip. */
7224
7616
  private async baseSha(baseBranch: string): Promise<string> {
7225
7617
  const read = this.deps.forge.remoteBranchSha
@@ -7282,6 +7674,7 @@ export class Dispatcher {
7282
7674
  target?: EventPayload<'build.created'>['target']
7283
7675
  baseBranch?: string
7284
7676
  priority?: 'urgent'
7677
+ level?: 'high' | 'low'
7285
7678
  }
7286
7679
  | undefined,
7287
7680
  ): EventPayload<'build.created'> {
@@ -7308,14 +7701,18 @@ export class Dispatcher {
7308
7701
  : {}),
7309
7702
  ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
7310
7703
  ...(seed?.priority !== undefined ? { priority: seed.priority } : {}),
7704
+ ...(seed?.level !== undefined ? { level: seed.level } : {}),
7311
7705
  }
7312
7706
  }
7313
7707
 
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
- : {}
7708
+ /** The level a claim freezes on `build.created`: a non-manual start
7709
+ * request's own level, otherwise the ticket's claim tier (`tierOf`). */
7710
+ private claimedLevel(
7711
+ ticket: Ticket,
7712
+ tier: StartTier,
7713
+ tierOf: (ticket: Ticket) => BuildPriority,
7714
+ ): BuildPriority {
7715
+ return tier === 'manual' ? tierOf(ticket) : tier
7319
7716
  }
7320
7717
 
7321
7718
  /** Every boundary before runner attachment is derived from durable facts.
@@ -7343,6 +7740,8 @@ export class Dispatcher {
7343
7740
  autoMergeUser?: string
7344
7741
  autoMergeDefaultSeq?: number
7345
7742
  assets?: PinnedAsset[]
7743
+ priority?: 'urgent'
7744
+ level?: 'high' | 'low'
7346
7745
  },
7347
7746
  ): Promise<DispatchOutcome> {
7348
7747
  if (!this.accountsAvailable()) return 'parked'
@@ -7385,7 +7784,6 @@ export class Dispatcher {
7385
7784
  ? { issueLinks: seed.ticket.issueLinks }
7386
7785
  : {}),
7387
7786
  ...(seed !== undefined ? this.selectedProfile(seed.ticket) : {}),
7388
- ...(seed !== undefined ? this.claimedPriority(seed.ticket) : {}),
7389
7787
  }),
7390
7788
  })
7391
7789
  events = (await readBuildFacts(store, record.slug)).value
@@ -7661,6 +8059,9 @@ export class Dispatcher {
7661
8059
  if (
7662
8060
  state.status !== 'queued' ||
7663
8061
  state.discardRequest !== undefined ||
8062
+ // A janitor that failed or ran out of budget before acknowledging
8063
+ // retries next tick; dispatch never provisions to acknowledge abort.
8064
+ dispatcherAcknowledgesAbort(state) ||
7664
8065
  heldByRepositoryPause(state, paused)
7665
8066
  ) {
7666
8067
  continue
@@ -7707,6 +8108,8 @@ export class Dispatcher {
7707
8108
  state.status === 'done' ||
7708
8109
  state.status === 'aborted' ||
7709
8110
  (state.status === 'queued' && state.discardRequest !== undefined) ||
8111
+ // The janitor acknowledges this abort; startup never launches for it.
8112
+ dispatcherAcknowledgesAbort(state) ||
7710
8113
  heldByRepositoryPause(state, paused)
7711
8114
  ) {
7712
8115
  continue
@@ -7877,7 +8280,7 @@ export class Dispatcher {
7877
8280
  /**
7878
8281
  * End open ticket waits whose tickets settled (SPEC §11 "Ticket waits").
7879
8282
  * Every waited ticket completed: `wait.ended {cause: automatic}`, and the
7880
- * build resumes ahead of normal claims. Any waited ticket rejected (the
8283
+ * build resumes ahead of claims at its level. Any waited ticket rejected (the
7881
8284
  * configured rejected role) or deleted: one `policy/wait-unresolvable`
7882
8285
  * escalation naming it, which the reducer reads as the wait's end. A wait
7883
8286
  * with tickets still pending stays in place.
@@ -8021,7 +8424,12 @@ export class Dispatcher {
8021
8424
  // Per-build containment: one build's failure never stops the sweep
8022
8425
  // from advancing the others. Workspace failures are already durable
8023
8426
  // against the build; a repository-wide cooldown still ends the tick.
8024
- if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
8427
+ if (
8428
+ error instanceof ForgeRequestDeferred ||
8429
+ error instanceof MixedVersionDeferral ||
8430
+ isRecoveryDeferred(error)
8431
+ )
8432
+ continue
8025
8433
  if (error instanceof ForgeCooldown) throw error
8026
8434
  const message =
8027
8435
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -8098,6 +8506,9 @@ export class Dispatcher {
8098
8506
  await deferMixedVersion(this.store, record.slug)
8099
8507
  return
8100
8508
  }
8509
+ // The janitor owns this abort: a sweep must never reap, provision or
8510
+ // launch a runner only to acknowledge it.
8511
+ if (dispatcherAcknowledgesAbort(state)) return
8101
8512
  if (
8102
8513
  (state.status === 'queued' && state.discardRequest !== undefined) ||
8103
8514
  heldByRepositoryPause(state, paused)
@@ -8257,6 +8668,9 @@ export class Dispatcher {
8257
8668
  // A finished leaf with work to run waits for a slot before anything is
8258
8669
  // reaped, provisioned or launched for it.
8259
8670
  if (runs && state.kind !== 'node' && (await this.leafAdmission(record.slug)) !== 'admit') return
8671
+ // A node relaunches only for work it holds a slot for: a retained
8672
+ // workspace confers none. Abort and pause acknowledgements are ungated.
8673
+ if (runs && state.kind === 'node' && !this.nodeRelaunchAdmitted(record, facts)) return
8260
8674
  // A finished parked leaf keeps its workspace until merge or close; a
8261
8675
  // stale environment is reaped only for an admitted replacement.
8262
8676
  // A leaf waiting on tickets, or on the dispatcher's check of its wait,
@@ -8563,7 +8977,7 @@ export class Dispatcher {
8563
8977
  if (!this.claimGateOpen()) return
8564
8978
  const store = this.store
8565
8979
  const { tickets, config } = this.deps
8566
- // A normal parked admission deferred this tick waits on urgent claims:
8980
+ // A parked admission deferred this tick waits on higher-level claims:
8567
8981
  // list now, once per deferral key; an unchanged key waits for a scan that
8568
8982
  // is due on its own.
8569
8983
  let force = false
@@ -8597,12 +9011,12 @@ export class Dispatcher {
8597
9011
  const capacityBuilds =
8598
9012
  targeted?.measured ?? deferralBuilds ?? (await this.capacityBuilds(launched))
8599
9013
  // A node awaiting verification, or a parked build that must run again,
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
9014
+ // reserves its slot ahead of claims of its own or a lower level until it
9015
+ // is admitted; this only ever lowers the claim budgets. A claim waits
9016
+ // only for parked work at its level or above (SPEC §12 "Slot admission
9017
+ // order"). Open-PR backpressure gates new high, normal and low claims
9018
+ // only: admission, the janitor, reconciles, landings and urgent claims
9019
+ // are untouched, and capacity accounting is unchanged. Engagement is a durable repository
8606
9020
  // fact recorded only on transitions, so hysteresis survives restarts.
8607
9021
  const engagement = this.store.repositoryFacts().openPrBackpressure
8608
9022
  const engaged = engagement !== undefined
@@ -8612,13 +9026,14 @@ export class Dispatcher {
8612
9026
  engaged,
8613
9027
  )
8614
9028
  // 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
- )
9029
+ // Sampled with the requests themselves, so a start pass inside intake can
9030
+ // tell a reserved request from one filed since.
9031
+ const pendingStarts = this.store.repositoryFacts().ticketStarts.pending
9032
+ const startDemand = this.startClaims()
9033
+ const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
9034
+ openPrs: { policy: config.policy, engaged },
9035
+ startRequests: startDemand,
9036
+ })
8622
9037
  const transition = backpressureTransition(
8623
9038
  backpressure,
8624
9039
  engaged,
@@ -8628,25 +9043,60 @@ export class Dispatcher {
8628
9043
  await store.ensureRepo(this.deps.repo)
8629
9044
  await store.appendRepo(this.deps.repo, { actor: DISPATCHER, ...transition })
8630
9045
  }
8631
- const normalPaused = backpressure?.active === true
9046
+ const nonUrgentPaused = backpressure?.active === true
8632
9047
  const activeRefs: TicketRef[] = capacityBuilds
8633
9048
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
8634
9049
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
8635
9050
  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
9051
+ // Each level's claim budget; a claim spends every level's slot, and ready
9052
+ // tickets are visited highest level first.
9053
+ const budgets = Object.fromEntries(
9054
+ TICKET_PRIORITIES.map((level) => [level, intakeCapacity(projection, adjust, level)]),
9055
+ ) as Record<BuildPriority, number>
9056
+ const waiting = { urgent: 0, high: 0, normal: 0 }
9057
+ // A ready ticket with a pending non-manual start request is left to the
9058
+ // start pass of its tier, which claims requests oldest first ahead of
9059
+ // that level's ready tickets. In memory over the tick's repository facts.
9060
+ // The requests the budgets reserved for (`startClaims`).
9061
+ const reservedStarts = new Set(
9062
+ Object.keys(startDemand).length > 0 ? Object.values(pendingStarts).map(({ seq }) => seq) : [],
9063
+ )
9064
+ const requested = (ticket: Ticket): boolean => {
9065
+ const request = pendingStarts[ticketStartKey(ticket.ref)]
9066
+ return request !== undefined && startTierOf(request) !== 'manual'
9067
+ }
8639
9068
  // Each ready ticket's claim tier: an optimization attempt claims at its
8640
9069
  // node's current build priority, any other ticket at its own priority
8641
9070
  // 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 =>
9071
+ let attemptTiers = new Map<string, BuildPriority>()
9072
+ const tierOf = (ticket: Ticket): BuildPriority =>
8644
9073
  attemptTiers.get(ticket.ref.id) ?? (tickets.priority ? ticketPriority(ticket) : 'normal')
8645
- const urgentClaim = (ticket: Ticket) =>
8646
- !targeted && ticket.kind !== 'node' && tierOf(ticket) === 'urgent'
9074
+ // A saturated claim counts as demand reserving ahead of lower-level
9075
+ // parked work: always at urgent; at high or normal only while work of a
9076
+ // lower level waits (a parked waiter or a start request), so the extra
9077
+ // preflight runs only where it can matter; never at low.
9078
+ const lowerWaiting = (level: BuildPriority): boolean => {
9079
+ const rank = priorityRank(level)
9080
+ const below = (entry: { priority?: BuildPriority }) =>
9081
+ priorityRank(entry.priority ?? 'normal') > rank
9082
+ return (
9083
+ (projection.waitingNodes ?? []).some(below) ||
9084
+ (projection.waitingBuilds ?? []).some(below) ||
9085
+ [...this.slotWaiters.values()].some((priority) => below({ priority })) ||
9086
+ START_TIERS.slice(START_TIERS.indexOf(level) + 1).some(
9087
+ (tier) => (projection.startRequests?.[tier] ?? 0) > 0,
9088
+ )
9089
+ )
9090
+ }
9091
+ const countsDemand = (level: BuildPriority): level is keyof typeof waiting =>
9092
+ level === 'urgent' || (level !== 'low' && lowerWaiting(level))
9093
+ const demandClaim = (ticket: Ticket) =>
9094
+ !targeted && ticket.kind !== 'node' && countsDemand(tierOf(ticket))
8647
9095
  // 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'
9096
+ const startTier = (ticket: Ticket): StartTier => {
9097
+ const request = targeted?.requests.get(ticket.ref.id)
9098
+ return request === undefined ? 'manual' : startTierOf(request)
9099
+ }
8650
9100
 
8651
9101
  // The ready scan runs even at full capacity: `queued` is the operator's
8652
9102
  // standing queue-depth report and must stay honest exactly when the
@@ -8679,8 +9129,9 @@ export class Dispatcher {
8679
9129
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
8680
9130
  !this.preparing(ticket.ref.source, ticket.ref.id),
8681
9131
  )
8682
- // Urgent first, each class in source order (stable). Every gate below is
8683
- // unchanged; a source without the priority capability is all normal.
9132
+ // By level, urgent first, each level in source order (stable). Every gate
9133
+ // below is unchanged; a source without the priority capability is all
9134
+ // normal.
8684
9135
  // A ticket whose labels select two profiles is never claimed (SPEC §9).
8685
9136
  const conflicts = this.profileConflicts(eligible)
8686
9137
  // Conflicts and their diagnostics are produced in the same order.
@@ -8689,12 +9140,18 @@ export class Dispatcher {
8689
9140
  const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
8690
9141
  if (!targeted) attemptTiers = await this.attemptClaimTiers(claimable)
8691
9142
  // A targeted pass keeps its tier-then-request order.
8692
- const ready = targeted ? claimable : urgentFirstBy(claimable, tierOf)
9143
+ const toStarts = targeted ? [] : claimable.filter(requested)
9144
+ const ready = targeted
9145
+ ? claimable
9146
+ : byPriorityBy(
9147
+ claimable.filter((ticket) => !requested(ticket)),
9148
+ tierOf,
9149
+ )
8693
9150
  report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
8694
9151
  report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
8695
- if (!targeted && normalPaused)
9152
+ if (!targeted && nonUrgentPaused)
8696
9153
  report.ticketDiagnostics.push(backpressureExplanation(backpressure))
8697
- report.queued = ready.length
9154
+ report.queued = ready.length + toStarts.length
8698
9155
  const withheld = new Set<string>()
8699
9156
  for (const ticket of ready) {
8700
9157
  if (ticket.creationKey === undefined) continue
@@ -8729,21 +9186,22 @@ export class Dispatcher {
8729
9186
  // still runs either way, so the standing queue-depth report stays honest —
8730
9187
  // this only declines to claim a ticket into a build that would immediately
8731
9188
  // 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))
9189
+ // Saturated, a demand-counting ticket still runs the preflight: it claims
9190
+ // its level's budget, or counts as demand waiting for a slot.
9191
+ const demandReady = ready.some((ticket) => demandClaim(ticket) && !withheld.has(ticket.ref.id))
8735
9192
  const noBudget = targeted
8736
9193
  ? ready.every((ticket) => targeted.budgets[startTier(ticket)] <= 0)
8737
- : capacity <= 0 && !urgentReady
9194
+ : !demandReady &&
9195
+ ready.every((ticket) => withheld.has(ticket.ref.id) || budgets[tierOf(ticket)] <= 0)
8738
9196
  if (
8739
9197
  paused ||
8740
9198
  (!targeted &&
8741
- normalPaused &&
9199
+ nonUrgentPaused &&
8742
9200
  !ready.some((ticket) => tierOf(ticket) === 'urgent' && !withheld.has(ticket.ref.id))) ||
8743
9201
  (noBudget &&
8744
9202
  !ready.some(
8745
9203
  (ticket) =>
8746
- (targeted || !normalPaused || tierOf(ticket) === 'urgent') &&
9204
+ (targeted || !nonUrgentPaused || tierOf(ticket) === 'urgent') &&
8747
9205
  (ticket.kind === 'node' ||
8748
9206
  (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0)),
8749
9207
  ))
@@ -8752,8 +9210,9 @@ export class Dispatcher {
8752
9210
  await this.sourceCondition(undefined, 'ready-scan')
8753
9211
  if (!this.outOfBudget(opts)) {
8754
9212
  await this.completeScan(checkpoint, report)
8755
- // No urgent ticket is ready: this scan decided urgent claims.
8756
- if (!paused) this.urgentEvaluated = true
9213
+ // No ticket can claim or count as demand: this scan decided claims
9214
+ // at every level.
9215
+ if (!paused) this.claimsEvaluated = true
8757
9216
  }
8758
9217
  return
8759
9218
  }
@@ -8952,21 +9411,59 @@ export class Dispatcher {
8952
9411
  claimLoopCompleted = false
8953
9412
  break
8954
9413
  }
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
9414
+ const level = tierOf(ticket)
9415
+ // Before this level's first ready ticket, its own and every higher late
9416
+ // start tier claims its pending requests (SPEC §12 "Slot admission
9417
+ // order"). A request it settles without starting frees its reservation.
9418
+ const startTiers = targeted
9419
+ ? []
9420
+ : LATE_START_TIERS.filter(
9421
+ (tier) =>
9422
+ !this.lateStartTiersHonored.has(tier) &&
9423
+ priorityRank(tier as BuildPriority) <= priorityRank(level),
9424
+ )
9425
+ if (startTiers.length > 0) {
9426
+ const pass = await this.honorStartRequests(
9427
+ report,
9428
+ launched,
9429
+ autoMergeUser,
9430
+ paused,
9431
+ opts,
9432
+ startTiers,
9433
+ )
9434
+ const listed = new Set(toStarts.map(({ ref }) => `${ref.source}:${ref.id}`))
9435
+ for (const decision of pass.settled) {
9436
+ if (decision.started && listed.has(decision.ticket)) report.queued -= 1
9437
+ // A reserved request frees its reservation, which a start then
9438
+ // occupies; one the budgets never reserved occupies a slot of every
9439
+ // level when it starts.
9440
+ const reserved = reservedStarts.has(decision.seq)
9441
+ for (const entry of TICKET_PRIORITIES) {
9442
+ const covered = priorityRank(entry) >= priorityRank(decision.tier as BuildPriority)
9443
+ if (reserved && covered && !decision.started) budgets[entry] += 1
9444
+ if (!reserved && decision.started) budgets[entry] -= 1
9445
+ }
9446
+ }
9447
+ if (this.outOfBudget(opts)) {
9448
+ claimLoopCompleted = false
9449
+ break
9450
+ }
9451
+ }
9452
+ if (!targeted && nonUrgentPaused && tierOf(ticket) !== 'urgent') continue
9453
+ // Start requests this tick cannot read stay ahead of ready tickets at
9454
+ // their tier and below until a later scan. A node ticket's claim takes
9455
+ // no slot.
9456
+ if (!targeted && ticket.kind !== 'node' && this.admissionBarred('claim', level)) continue
9457
+ const demand = demandClaim(ticket)
9458
+ const budget = targeted ? targeted.budgets[startTier(ticket)] : budgets[level]
9459
+ if (ticket.kind !== 'node' && budget <= 0 && !demand) continue
8963
9460
  if (withheld.has(ticket.ref.id)) continue
8964
9461
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
8965
9462
  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.
9463
+ // A ticket that passed every gate but capacity is demand that
9464
+ // lower-level parked work yields to until the next admission scan.
8968
9465
  if (ticket.kind !== 'node' && budget <= 0) {
8969
- urgentWaiting += 1
9466
+ if (countsDemand(level)) waiting[level] += 1
8970
9467
  continue
8971
9468
  }
8972
9469
 
@@ -9160,12 +9657,9 @@ export class Dispatcher {
9160
9657
  ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
9161
9658
  // Fixed at claim from the same sample: relabelling never changes it.
9162
9659
  ...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
- : {}),
9660
+ // `manual` is admission-only: a build started by any other request
9661
+ // takes the request's level, every other build its ticket's.
9662
+ ...createdPriorityFields(this.claimedLevel(ticket, startTier(ticket), tierOf)),
9169
9663
  }
9170
9664
  // `build.created` rides with the record so the pinned assets and the
9171
9665
  // record exist together or not at all.
@@ -9239,10 +9733,7 @@ export class Dispatcher {
9239
9733
  }
9240
9734
  report.queued -= 1
9241
9735
  if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
9242
- else if (ticket.kind !== 'node') {
9243
- capacity -= 1
9244
- urgentCapacity -= 1
9245
- }
9736
+ else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
9246
9737
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
9247
9738
  ticket,
9248
9739
  body,
@@ -9254,9 +9745,9 @@ export class Dispatcher {
9254
9745
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
9255
9746
  }
9256
9747
  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
9748
+ await this.completeScan(checkpoint, report, waiting)
9749
+ // The only other place this tick authorizes deferred admissions.
9750
+ if (claimLoopCompleted) this.claimsEvaluated = true
9260
9751
  }
9261
9752
  }
9262
9753
 
@@ -9305,10 +9796,8 @@ export class Dispatcher {
9305
9796
  * other tickets keep their own tier. Costs one served node state per open,
9306
9797
  * unstopped optimization node a ready ticket targets, and none otherwise.
9307
9798
  */
9308
- private async attemptClaimTiers(
9309
- tickets: readonly Ticket[],
9310
- ): Promise<Map<string, TicketPriority>> {
9311
- const tiers = new Map<string, TicketPriority>()
9799
+ private async attemptClaimTiers(tickets: readonly Ticket[]): Promise<Map<string, BuildPriority>> {
9800
+ const tiers = new Map<string, BuildPriority>()
9312
9801
  const candidates = tickets.filter(
9313
9802
  (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
9314
9803
  )
@@ -9846,7 +10335,7 @@ export class Dispatcher {
9846
10335
  }
9847
10336
 
9848
10337
  if (!this.accountsAvailable()) return
9849
- if ((await this.nodeHasCapacity(record.slug, false)) !== 'admit') return
10338
+ if ((await this.nodeAdmission(record.slug)) !== 'admit') return
9850
10339
  // `launch()` refuses a flagged workspace and leaves the reap to its
9851
10340
  // callers; this is the node's caller for conflict work.
9852
10341
  const current = await this.replaceFlaggedWorkspace(record, facts, launched)
@@ -10149,7 +10638,7 @@ export class Dispatcher {
10149
10638
  await this.releaseWorkspace(record.slug, facts)
10150
10639
  return
10151
10640
  }
10152
- if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
10641
+ if ((await this.nodeAdmission(record.slug)) !== 'admit') return
10153
10642
  await this.observeIntegration(record.slug)
10154
10643
  state = (await this.store.buildFacts(record.slug)).state
10155
10644
  if (!integrationCurrent(state)) return