@defrex/autobuild 1.12.0 → 1.14.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 (167) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +465 -163
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +28 -4
  5. package/docs/architecture.md +136 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +120 -17
  8. package/docs/dispatcher.md +19 -8
  9. package/docs/integration-overview.md +1 -1
  10. package/docs/integration-tree.md +12 -9
  11. package/docs/merge-policy.md +7 -2
  12. package/docs/operating.md +13 -3
  13. package/docs/operator-api.md +46 -23
  14. package/docs/operator-surfaces.md +7 -6
  15. package/docs/optimization-nodes.md +7 -6
  16. package/docs/plugin-authoring.md +46 -18
  17. package/docs/remote-store-protocol.md +52 -13
  18. package/docs/remote-ticket-protocol.md +85 -38
  19. package/docs/restacking.md +48 -3
  20. package/docs/setup.md +2 -1
  21. package/docs/ticket-migration.md +2 -2
  22. package/docs/ticket-sources.md +23 -8
  23. package/docs/tickets.md +4 -4
  24. package/docs/troubleshooting.md +32 -2
  25. package/docs/verification.md +3 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/build-control.ts +72 -6
  28. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  29. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  30. package/packages/core/src/cli/dashboard/model.ts +14 -8
  31. package/packages/core/src/cli/dashboard/poll.ts +218 -10
  32. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  33. package/packages/core/src/cli/dashboard/row-text.ts +2 -1
  34. package/packages/core/src/cli/dashboard/vocabulary.ts +5 -1
  35. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  36. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  37. package/packages/core/src/cli/dispatch.ts +547 -145
  38. package/packages/core/src/cli/help.ts +38 -24
  39. package/packages/core/src/cli/main.ts +7 -5
  40. package/packages/core/src/cli/publication-settlement.ts +4 -0
  41. package/packages/core/src/cli/remote-poll.ts +22 -5
  42. package/packages/core/src/cli/repository-status.ts +19 -9
  43. package/packages/core/src/cli/status.ts +23 -11
  44. package/packages/core/src/cli/store-opening.ts +12 -0
  45. package/packages/core/src/cli/ticket-start.ts +3 -3
  46. package/packages/core/src/cli/ticket.ts +12 -11
  47. package/packages/core/src/cli/wait.ts +8 -28
  48. package/packages/core/src/cli/watch.ts +113 -50
  49. package/packages/core/src/config/reference-metadata.ts +7 -1
  50. package/packages/core/src/config/reference.ts +5 -2
  51. package/packages/core/src/config/schema.ts +51 -16
  52. package/packages/core/src/events/payloads.ts +74 -14
  53. package/packages/core/src/events/policy.ts +1 -0
  54. package/packages/core/src/events/repository.ts +33 -3
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  63. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  64. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  65. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  67. package/packages/core/src/kernel/done-escalations.ts +273 -0
  68. package/packages/core/src/kernel/engine.ts +28 -9
  69. package/packages/core/src/kernel/integration-landing.ts +24 -4
  70. package/packages/core/src/kernel/integration-stack.ts +39 -0
  71. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  72. package/packages/core/src/kernel/log-index-value.ts +3 -0
  73. package/packages/core/src/kernel/log-index.ts +41 -2
  74. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  75. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  76. package/packages/core/src/kernel/reducer-revisions.ts +19 -0
  77. package/packages/core/src/kernel/reducer.ts +42 -8
  78. package/packages/core/src/kernel/repository-attention.ts +14 -5
  79. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  80. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  81. package/packages/core/src/kernel/verify-stages.ts +46 -7
  82. package/packages/core/src/operator/attention.ts +28 -3
  83. package/packages/core/src/operator/done-escalations.ts +38 -0
  84. package/packages/core/src/operator/presentation.ts +1 -1
  85. package/packages/core/src/operator/protocol.ts +8 -5
  86. package/packages/core/src/operator/query.ts +33 -19
  87. package/packages/core/src/operator/registry.ts +17 -13
  88. package/packages/core/src/operator/ticket-start.ts +8 -7
  89. package/packages/core/src/operator/tickets.ts +28 -9
  90. package/packages/core/src/plugin-sdk/index.ts +10 -0
  91. package/packages/core/src/plugins/manifest.ts +14 -1
  92. package/packages/core/src/ports/forge/create.ts +8 -0
  93. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  94. package/packages/core/src/ports/forge/github.ts +3 -0
  95. package/packages/core/src/ports/tickets/contract.ts +147 -76
  96. package/packages/core/src/ports/tickets/create.ts +47 -7
  97. package/packages/core/src/ports/tickets/fake.ts +8 -4
  98. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  99. package/packages/core/src/ports/tickets/file.ts +7 -3
  100. package/packages/core/src/ports/tickets/github.ts +1 -0
  101. package/packages/core/src/ports/tickets/grants.ts +11 -3
  102. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  103. package/packages/core/src/ports/tickets/linear.ts +28 -9
  104. package/packages/core/src/ports/tickets/migration.ts +4 -4
  105. package/packages/core/src/ports/tickets/operations.ts +4 -2
  106. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  107. package/packages/core/src/ports/tickets/priority.ts +127 -21
  108. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  109. package/packages/core/src/ports/tickets/remote.ts +104 -11
  110. package/packages/core/src/ports/tickets/revision.ts +5 -3
  111. package/packages/core/src/ports/tickets/search.ts +9 -0
  112. package/packages/core/src/ports/tickets/tree.ts +8 -6
  113. package/packages/core/src/ports/types.ts +30 -15
  114. package/packages/core/src/ports/workspace/build-execution.ts +13 -1
  115. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  116. package/packages/core/src/ports/workspace/create.ts +16 -3
  117. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  118. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  119. package/packages/core/src/ports/workspace/vercel-sandbox.ts +596 -144
  120. package/packages/core/src/processes/build-execution-state.ts +4 -0
  121. package/packages/core/src/processes/build-runner.ts +14 -1
  122. package/packages/core/src/processes/dispatcher.ts +841 -230
  123. package/packages/core/src/processes/execution-settlement.ts +25 -3
  124. package/packages/core/src/processes/harvest-runner.ts +12 -7
  125. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  126. package/packages/core/src/processes/invocation-budget.ts +176 -0
  127. package/packages/core/src/processes/publication-loss.ts +38 -3
  128. package/packages/core/src/processes/tick-publication.ts +1 -0
  129. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  130. package/packages/core/src/store/contract.ts +88 -3
  131. package/packages/core/src/store/event-reads.ts +30 -1
  132. package/packages/core/src/store/reduced-reads.ts +23 -0
  133. package/packages/core/src/store/reducer-value-shapes.json +6759 -6490
  134. package/packages/core/src/store/reducer-value-validation.ts +188 -33
  135. package/packages/core/src/store/remote/client.ts +169 -29
  136. package/packages/core/src/store/remote/compatibility.ts +113 -56
  137. package/packages/core/src/store/remote/credentials.ts +4 -1
  138. package/packages/core/src/store/remote/protocol.ts +3 -0
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  143. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  144. package/packages/core/src/store/remote/retry.ts +406 -0
  145. package/packages/core/src/store/repo-state-events.ts +1 -0
  146. package/packages/core/src/testing/dispatch-read-budget.ts +155 -11
  147. package/packages/core/src/testing/index.ts +2 -0
  148. package/packages/core/src/testing/invocation-budget.ts +42 -0
  149. package/packages/core/src/testing/reduced-read-budget.ts +589 -19
  150. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  151. package/packages/core/src/web/overview-source.ts +19 -6
  152. package/skills/guide/SKILL.md +147 -67
  153. package/skills/guide/references/integration-tree.md +12 -9
  154. package/skills/guide/references/merge-policy.md +7 -2
  155. package/skills/guide/references/operator-api.md +46 -23
  156. package/skills/guide/references/optimization-nodes.md +7 -6
  157. package/skills/guide/references/plugin-authoring.md +46 -18
  158. package/skills/guide/references/remote-store-protocol.md +52 -13
  159. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  160. package/skills/guide/references/restacking.md +48 -3
  161. package/skills/guide/references/setup.md +2 -1
  162. package/skills/guide/references/ticket-migration.md +2 -2
  163. package/skills/operate/SKILL.md +136 -55
  164. package/skills/plan/SKILL.md +4 -3
  165. package/skills/spec/SKILL.md +9 -5
  166. package/skills/tickets/SKILL.md +25 -17
  167. 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,8 +113,15 @@ 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
127
  leafHoldsSlot,
@@ -126,8 +139,8 @@ import {
126
139
  startCapacity,
127
140
  startClaimDemand,
128
141
  strandedNodeWorkspace,
129
- urgentClaimDemand,
130
142
  type CapacityBuild,
143
+ type ClaimDemand,
131
144
  type DispatchCapacity,
132
145
  type NodeSlotNeed,
133
146
  } from '../kernel/dispatch-capacity'
@@ -249,7 +262,17 @@ import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../st
249
262
  import { ensureExecutionProgress } from './execution-no-progress'
250
263
  import { ticketIdentity } from '../ports/tickets/identity'
251
264
  import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
252
- 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'
253
276
  import { ensureDispatchBudget } from './dispatch-failure-budget'
254
277
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
255
278
  /**
@@ -296,11 +319,7 @@ import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
296
319
  import { isRemoteWorkspace } from '../events/workspace-remote'
297
320
  import type { AbEvent, EventWrite } from '../events/catalog'
298
321
  import type { AbortDestination, EventPayload, PinnedAsset } from '../events/payloads'
299
- import type {
300
- RepositoryEventPayload,
301
- TicketStartOutcome,
302
- TicketStartPriority,
303
- } from '../events/repository'
322
+ import type { RepositoryEventPayload, TicketStartOutcome } from '../events/repository'
304
323
  import { ticketStartKey, type PendingTicketStart, type TicketStarts } from '../kernel/ticket-starts'
305
324
  import { handbackIdentity } from '../kernel/ticket-handbacks'
306
325
  import type { IdSource } from '../ids'
@@ -323,14 +342,20 @@ import {
323
342
  import type { BuildState } from '../kernel/reducer'
324
343
  import type { ArtifactRef, TicketRef } from '../ontology'
325
344
  import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution'
345
+ import {
346
+ attributeRecoveryStep,
347
+ isRecoveryDeferred,
348
+ recoveryStepOf,
349
+ type WorkspaceRecoveryStep,
350
+ } from '../ports/workspace/recovery-step'
326
351
  import type {
327
352
  DependencyState,
328
353
  Forge,
329
354
  HeadChecks,
330
355
  IssueLink,
331
356
  PrState,
357
+ BuildPriority,
332
358
  Ticket,
333
- TicketPriority,
334
359
  TicketSource,
335
360
  WorkspaceProvider,
336
361
  WorkspaceProvisionResult,
@@ -372,7 +397,10 @@ import { recordInfrastructureFailure as appendInfrastructureFailure } from './in
372
397
  import { settleOpenExecution } from './execution-settlement'
373
398
  import { isWorkDigest, RepoViewStore } from './repo-view'
374
399
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
375
- import { settlePublicationFactsBeforeRelease } from './publication-loss'
400
+ import {
401
+ recordPublicationLossBeforeRelease,
402
+ settlePublicationFactsBeforeRelease,
403
+ } from './publication-loss'
376
404
 
377
405
  // ── Readiness resolution (SPEC §3.3) ─────────────────────────────────────────
378
406
 
@@ -648,6 +676,13 @@ export interface TickReport {
648
676
  * invocation's remaining budget was shorter than the provider's
649
677
  * provisioning estimate. Nothing is written; a later invocation starts it. */
650
678
  provisioningDeferred: number
679
+ /** Builds whose stopped-sandbox recovery, or a launch waiting on one, the
680
+ * invocation budget deferred this tick. Nothing is charged; the build is
681
+ * recorded in `dispatcher.work-deferred` and the next tick runs it first. */
682
+ recoveryDeferred: number
683
+ /** One line per build whose deadline-gated work (a provision or a recovery
684
+ * step) this tick deferred for budget, naming the step. */
685
+ deferredDiagnostics: string[]
651
686
  /** Dispatch (§12): builds created and launched. With durable supervision
652
687
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
653
688
  * awaited launches: a dispatch whose remote provisioning continues in the
@@ -715,6 +750,8 @@ export function emptyTickReport(): TickReport {
715
750
  settled: 0,
716
751
  provisioning: 0,
717
752
  provisioningDeferred: 0,
753
+ recoveryDeferred: 0,
754
+ deferredDiagnostics: [],
718
755
  dispatched: 0,
719
756
  authored: 0,
720
757
  bounced: 0,
@@ -758,7 +795,7 @@ interface TargetedDispatch {
758
795
  measured: CapacityBuild[]
759
796
  /** Slots left for each start tier (`startCapacity`). A claim spends only
760
797
  * its own tier's: lower tiers already reserved it as a pending request. */
761
- budgets: Record<TicketStartPriority, number>
798
+ budgets: Record<StartTier, number>
762
799
  }
763
800
 
764
801
  /** An active build's ticket ref, normalized through recorded migrations. */
@@ -768,9 +805,16 @@ interface ActiveTicketRef {
768
805
  ref: TicketRef
769
806
  }
770
807
 
771
- /** Start requests one pass evaluates, in tier order, oldest first. */
772
- const START_REQUESTS_PER_TICK = 8
773
- const START_TIER_ORDER: readonly TicketStartPriority[] = ['manual', 'urgent', 'normal']
808
+ /** Gate-passing ticket claims one admission scan left waiting for a slot, by
809
+ * the levels that reserve ahead of lower-level parked work. */
810
+ type ScanClaimWaiting = { urgent?: number; high?: number; normal?: number }
811
+
812
+ /** Every request one start pass settled: its ticket (`source:id`), seq and
813
+ * tier, and whether it started a build. */
814
+ interface StartPassResult {
815
+ settled: { ticket: string; seq: number; tier: StartTier; started: boolean }[]
816
+ }
817
+
774
818
  /** Hosted active-build identities one tick resolves; each build once in its life. */
775
819
  const IDENTITY_RESOLUTIONS_PER_TICK = 16
776
820
  /** Released identity slugs one projection append carries. */
@@ -889,8 +933,27 @@ export interface TickOpts {
889
933
  * exactly as capacity exhaustion already defers tickets. Absent ⇒ unbounded
890
934
  * (today's exact behavior). */
891
935
  deadlineAt?: number
936
+ /** Bounded invocation's work signal: once aborted the tick starts no new
937
+ * unit of work, exactly as when the clock passes `deadlineAt`. In-flight
938
+ * requests made through the budgeted adapters are cancelled by the same
939
+ * signal. Absent ⇒ only `deadlineAt` bounds the tick. */
940
+ workSignal?: AbortSignal
941
+ /** Bounded invocation's teardown write scope: runs one write under the
942
+ * cleanup phase's signal. A budget deferral noted after `workSignal`
943
+ * aborted (a recovery whose cleanup stop ran into the work deadline) still
944
+ * records its `dispatcher.work-deferred` hint through it, while the
945
+ * repository lease is held, so the next invocation serves it first. Absent
946
+ * ⇒ such a late hint write is skipped. */
947
+ teardownWrite?: <T>(write: () => Promise<T>) => Promise<T>
892
948
  }
893
949
 
950
+ /** Deadline-gated work a bounded invocation can defer for budget: a
951
+ * provision, or a stopped-sandbox recovery step. */
952
+ export type DeferredWorkStep = 'provision' | WorkspaceRecoveryStep
953
+
954
+ /** Most entries one `dispatcher.work-deferred` hint carries. */
955
+ const MAX_DEFERRED_WORK = 64
956
+
894
957
  /** Process-local launch coordination result. Durable lease acquisition remains
895
958
  * the BuildRunner's responsibility; "scheduled" means only that this process
896
959
  * accepted a runner launch rather than suppressing a known in-flight slug. */
@@ -1041,6 +1104,19 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
1041
1104
 
1042
1105
  export const SWEEP_PIN_CACHE_CAPACITY = 128
1043
1106
 
1107
+ /** Name the recovery step a workspace failure happened in. Missing account
1108
+ * credentials stay unwrapped: the dispatcher holds for them by type instead
1109
+ * of recording a failure. */
1110
+ function errorText(error: unknown): string {
1111
+ return error instanceof Error ? error.message : String(error)
1112
+ }
1113
+
1114
+ function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1115
+ return error instanceof MissingAccountCredentialsError
1116
+ ? error
1117
+ : attributeRecoveryStep(step, error)
1118
+ }
1119
+
1044
1120
  export class Dispatcher {
1045
1121
  // Only scheduling is cached. Eligibility facts still come from durable state,
1046
1122
  // and each admitted verification/publication samples the source this pass.
@@ -1290,23 +1366,42 @@ export class Dispatcher {
1290
1366
  /** Per tick, rebuilt from durable state: builds launched so far, which
1291
1367
  * occupy a slot before their runner claims a lease. */
1292
1368
  private tickLaunched: ReadonlySet<string> = new Set()
1369
+ /** Per tick, in insertion order: builds whose deadline-gated work this tick
1370
+ * deferred for budget, with the first step seen and an optional detail. */
1371
+ private readonly tickDeferrals = new Map<string, { step: DeferredWorkStep; detail?: string }>()
1372
+ /** Per tick: carried builds the early stage took up, which the lease sweep
1373
+ * then skips so no build is swept twice in one tick. */
1374
+ private readonly tickPrioritized = new Set<string>()
1375
+ /** Per tick, in carried order: the durable `dispatcher.work-deferred` hint
1376
+ * entries not yet retired. An entry leaves only through `retireCarried`,
1377
+ * after its own early-stage pass showed it no longer needs priority. */
1378
+ private readonly carriedOutstanding = new Map<
1379
+ string,
1380
+ { step: DeferredWorkStep; visited: boolean }
1381
+ >()
1382
+ /** The durable hint as last read or written. */
1383
+ private recordedDeferrals: { slug: string; step: DeferredWorkStep }[] = []
1384
+ /** The current tick's options, for writes made from deferral sites. */
1385
+ private tickOpts: TickOpts = {}
1386
+ /** Serializes hint writes so concurrent deferral notes never race. */
1387
+ private deferralWrites: Promise<void> = Promise.resolve()
1293
1388
  /** Per tick: finished leaves the admission gate turned away or deferred,
1294
1389
  * with their priority. Intake reserves their slots. */
1295
- private readonly slotWaiters = new Map<string, TicketPriority>()
1296
- /** Per tick, in visit order: normal parked admissions that would have taken
1297
- * a free slot before this tick's dispatch evaluated urgent claims (SPEC §12
1390
+ private readonly slotWaiters = new Map<string, BuildPriority>()
1391
+ /** Per tick, in visit order: parked admissions that would have taken a free
1392
+ * slot before this tick's dispatch evaluated higher-level claims (SPEC §12
1298
1393
  * "Slot admission order"). Nothing was written for them;
1299
1394
  * `admitDeferredParked` retries each through its generic path. */
1300
1395
  private readonly deferredAdmissions = new Map<string, 'leaf' | 'node' | 'proposer'>()
1301
1396
  /** Nodes `admitWaitingNodes` admitted in its current verification pass, so
1302
1397
  * proposer admission counts them even when provisioning or launch failed. */
1303
1398
  private passNodeAdmissions: Set<string> | undefined
1304
- /** Per tick: admission may defer normal parked work. Opened by `runTick`
1305
- * when claims can run, closed once urgent claims were evaluated. */
1399
+ /** Per tick: admission may defer non-urgent parked work. Opened by
1400
+ * `runTick` when claims can run, closed once claims were evaluated. */
1306
1401
  private admissionBoundary = false
1307
- /** Per tick: this tick's admission scan completed its urgent decision. Only
1402
+ /** Per tick: this tick's admission scan decided claims at every level. Only
1308
1403
  * `dispatch` sets it. */
1309
- private urgentEvaluated = false
1404
+ private claimsEvaluated = false
1310
1405
  /** Per tick: the deferral key this tick's admission scan was forced for. */
1311
1406
  private forcedDeferralKey: string | undefined
1312
1407
  /** In memory: the last deferral key whose forced scan completed and whose
@@ -1334,6 +1429,19 @@ export class Dispatcher {
1334
1429
  /** While the start pass's targeted dispatch runs: its deferral checks
1335
1430
  * serve this tick's retained facts (`servedBuildFacts`). */
1336
1431
  private startPass = false
1432
+ /** Per tick: late start tiers already honored, inside ordinary intake or
1433
+ * after it; each is honored at most once a tick. */
1434
+ private readonly lateStartTiersHonored = new Set<StartTier>()
1435
+ /** Per tick: start requests the late passes may still evaluate. Intake runs
1436
+ * a late pass before each level's first ready ticket, so the passes share
1437
+ * one allowance and a tick reads no more requests than one late pass. */
1438
+ private lateStartRequests = START_REQUESTS_PER_TICK
1439
+ /** Per tick: the start barrier (`startBarrier`), the highest tier with a
1440
+ * pending request the tick's allowance leaves unread. Sampled when the tick
1441
+ * starts, so admission before any start pass already respects it, and
1442
+ * raised by a pass that finds a request filed since unread. Every admission
1443
+ * path consults it through `admissionBarred` (SPEC §12). */
1444
+ private startBarrier: StartTier | undefined
1337
1445
  /** Per tick: the janitor's work listing, and the nonterminal children of
1338
1446
  * each node indexed from it on the first landing turn that needs them. The
1339
1447
  * landing gate reads its turn candidates here, never from a new listing. */
@@ -1382,8 +1490,9 @@ export class Dispatcher {
1382
1490
  }
1383
1491
 
1384
1492
  /**
1385
- * One cron-friendly pass (§3.3): janitor → interrupted dispatch recovery →
1386
- * optional startup resume → lease sweep → dispatch. Startup resume is opt-in
1493
+ * One cron-friendly pass (§3.3): deferred deadline-gated work → settlement →
1494
+ * janitor → interrupted dispatch recovery → optional startup resume →
1495
+ * lease sweep → dispatch. Startup resume is opt-in
1387
1496
  * because the CLI invokes it
1388
1497
  * once per command, while ordinary watch ticks must preserve policy parks.
1389
1498
  */
@@ -1392,9 +1501,15 @@ export class Dispatcher {
1392
1501
  * loops consult this before starting each new forge/store transport call,
1393
1502
  * bounding the tick's overrun to the one call already in flight. */
1394
1503
  private outOfBudget(opts: TickOpts): boolean {
1504
+ return this.budgetSpent(opts) || this.deps.holdsRepoAuthority?.() === false
1505
+ }
1506
+
1507
+ /** The invocation-budget half of `outOfBudget`: no clock read and no
1508
+ * authority check without a deadline, so an unbounded tick is unchanged. */
1509
+ private budgetSpent(opts: TickOpts): boolean {
1395
1510
  return (
1396
1511
  (opts.deadlineAt !== undefined && this.deps.clock().getTime() >= opts.deadlineAt) ||
1397
- this.deps.holdsRepoAuthority?.() === false
1512
+ opts.workSignal?.aborted === true
1398
1513
  )
1399
1514
  }
1400
1515
 
@@ -1512,6 +1627,7 @@ export class Dispatcher {
1512
1627
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1513
1628
  : this.runTick(opts))
1514
1629
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1630
+ this.finishDeferrals(report)
1515
1631
  report.janitorDiagnostics.push(...this.tickAbandonments)
1516
1632
  return report
1517
1633
  } catch (error) {
@@ -1555,15 +1671,31 @@ export class Dispatcher {
1555
1671
  this.integrationPublicationInputs = undefined
1556
1672
  this.nodePollingTickReads.clear()
1557
1673
  this.slotWaiters.clear()
1674
+ this.lateStartTiersHonored.clear()
1675
+ this.lateStartRequests = START_REQUESTS_PER_TICK
1676
+ this.startBarrier = undefined
1558
1677
  this.parkedSettled.clear()
1559
1678
  this.deferredAdmissions.clear()
1679
+ this.tickDeferrals.clear()
1680
+ this.tickPrioritized.clear()
1681
+ this.carriedOutstanding.clear()
1682
+ this.deferralWriteFailure = undefined
1683
+ this.tickOpts = opts
1560
1684
  this.admissionBoundary = false
1561
- this.urgentEvaluated = false
1685
+ this.claimsEvaluated = false
1562
1686
  this.forcedDeferralKey = undefined
1563
1687
  // One immutable config for this complete decision pass. A reload racing the
1564
1688
  // tick is observed by the next tick, never half-way through this one.
1565
1689
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1566
1690
  if (opts.viewRefreshed !== true) await this.store.refresh()
1691
+ // The durable deferral hint from the previous invocation: zero extra
1692
+ // reads, it is part of the repository facts the refresh reduced.
1693
+ this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1694
+ ({ slug, step }) => ({ slug, step }),
1695
+ )
1696
+ for (const { slug, step } of this.recordedDeferrals)
1697
+ if (!this.carriedOutstanding.has(slug))
1698
+ this.carriedOutstanding.set(slug, { step, visited: false })
1567
1699
  // A pending start request measures capacity from the facts this tick's
1568
1700
  // fleet-wide stages read anyway; keep them only then.
1569
1701
  this.store.retainBuildFacts(
@@ -1586,9 +1718,16 @@ export class Dispatcher {
1586
1718
  const paused = repoFacts.settings.paused
1587
1719
  this.tickAcceptsNewWork = opts.acceptNewWork !== false
1588
1720
  this.tickPaused = paused
1589
- // Normal parked work never takes a free slot before this tick's dispatch
1590
- // has evaluated urgent claims, while claims can run at all.
1591
- this.admissionBoundary = !opts.observationOnly && this.claimsPossible(opts, paused)
1721
+ // Lower-level parked work never takes a free slot before this tick's
1722
+ // dispatch has evaluated higher-level claims, while claims can run at all.
1723
+ this.admissionBoundary = !opts.observationOnly && this.claimsCanRun(opts, paused)
1724
+ // Start requests this tick cannot read hold back lower-level admission,
1725
+ // whichever stage admits it; they reserve only while they can be
1726
+ // honored (`startClaims`).
1727
+ this.startBarrier =
1728
+ Object.keys(this.startClaims()).length > 0
1729
+ ? startBarrier(Object.values(repoFacts.ticketStarts.pending))
1730
+ : undefined
1592
1731
  const autoMergeSeedFact = undefined
1593
1732
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
1594
1733
  // provider liveness and settle their completion, lease, and publication.
@@ -1598,6 +1737,11 @@ export class Dispatcher {
1598
1737
  // open the first record listing of the next stage; each stage's own
1599
1738
  // per-iteration gate (below) covers a deadline that passes mid-stage.
1600
1739
  if (this.outOfBudget(opts)) return report
1740
+ // Stage −1 — DEFERRED WORK: builds whose provision or stopped-sandbox
1741
+ // recovery an earlier invocation deferred for budget are swept first,
1742
+ // while nearly the whole work window remains.
1743
+ if (!opts.observationOnly) await this.serviceDeferredWork(report, launched, paused, opts)
1744
+ if (this.outOfBudget(opts)) return report
1601
1745
  await this.settleForeignExecutions(report, opts)
1602
1746
  if (this.outOfBudget(opts)) return report
1603
1747
  await this.settleHarvestExecutions(opts)
@@ -1630,26 +1774,27 @@ export class Dispatcher {
1630
1774
  if (this.outOfBudget(opts)) return report
1631
1775
  // Operator start requests are independent of intake: they claim only the
1632
1776
  // named tickets, and read nothing when none is pending. Manual and urgent
1633
- // requests run here, ahead of ordinary claims; normal requests run after
1634
- // urgent claims and normal parked work (SPEC §12 "Slot admission order").
1635
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, [
1636
- 'manual',
1637
- 'urgent',
1638
- ])
1777
+ // requests run here, ahead of ordinary claims; high, normal and low
1778
+ // requests run inside intake, after higher-level claims and before their
1779
+ // own level's ready tickets, or after intake when it reaches no ticket of
1780
+ // their level (SPEC §12 "Slot admission order").
1781
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, EARLY_START_TIERS)
1639
1782
  if (this.outOfBudget(opts)) return report
1640
1783
  if (opts.acceptNewWork !== false) {
1641
1784
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1642
1785
  }
1643
1786
  await this.admitDeferredParked(report, launched, paused, opts)
1644
- // Ordinary normal claims left this pass's reserved slots free.
1645
- if (!this.outOfBudget(opts))
1646
- await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, ['normal'])
1787
+ // Late tiers intake did not reach: ordinary claims left their reserved
1788
+ // slots free.
1789
+ const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1790
+ if (!this.outOfBudget(opts) && lateTiers.length > 0)
1791
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, lateTiers)
1647
1792
  // Fire-and-forget by contract: long synthesize/review sessions must not
1648
1793
  // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1649
1794
  // watch ticks. Durable pause and infrastructure-error stops suppress
1650
1795
  // launch. Pending control commands still launch the runner so the kernel
1651
1796
  // can settle them under the repository lease.
1652
- await this.triggerHarvest()
1797
+ if (!this.budgetSpent(opts)) await this.triggerHarvest()
1653
1798
  await this.captureAgentContext(report, opts)
1654
1799
  return report
1655
1800
  }
@@ -1890,8 +2035,9 @@ export class Dispatcher {
1890
2035
  /** Admit pending operator start requests of the given tiers through
1891
2036
  * `dispatch()`'s gates and settle each one that reaches a decision. Zero
1892
2037
  * reads while none of those tiers is pending; otherwise one targeted `get`
1893
- * per request (at most START_REQUESTS_PER_TICK) over the view-cached build
1894
- * digests. Waiting conditions (pause, no slot in the request's tier,
2038
+ * per request over the view-cached build digests: at most
2039
+ * START_REQUESTS_PER_TICK a tick for the early tiers, and as many shared by
2040
+ * every late pass of the tick. Waiting conditions (pause, no slot in the request's tier,
1895
2041
  * creation holds, an in-flight preparation, a failed dependency read, a
1896
2042
  * source error, the tick budget) leave the request pending. */
1897
2043
  private async honorStartRequests(
@@ -1900,15 +2046,45 @@ export class Dispatcher {
1900
2046
  autoMergeUser: string | undefined,
1901
2047
  paused: boolean,
1902
2048
  opts: TickOpts,
1903
- tiers: readonly TicketStartPriority[],
2049
+ tiers: readonly StartTier[],
2050
+ ): Promise<StartPassResult> {
2051
+ const result: StartPassResult = { settled: [] }
2052
+ for (const tier of tiers)
2053
+ if (LATE_START_TIERS.includes(tier)) this.lateStartTiersHonored.add(tier)
2054
+ await this.honorStartRequestTiers(report, launched, autoMergeUser, paused, opts, tiers, result)
2055
+ return result
2056
+ }
2057
+
2058
+ private async honorStartRequestTiers(
2059
+ report: TickReport,
2060
+ launched: Set<string>,
2061
+ autoMergeUser: string | undefined,
2062
+ paused: boolean,
2063
+ opts: TickOpts,
2064
+ tiers: readonly StartTier[],
2065
+ result: StartPassResult,
1904
2066
  ): Promise<void> {
1905
2067
  const starts = this.store.repositoryFacts().ticketStarts
1906
- const rank = (request: PendingTicketStart) => START_TIER_ORDER.indexOf(request.priority)
1907
- const pending = Object.values(starts.pending)
1908
- .filter((request) => tiers.includes(request.priority))
2068
+ const rank = (request: PendingTicketStart) => START_TIERS.indexOf(startTierOf(request))
2069
+ const late = tiers.every((tier) => LATE_START_TIERS.includes(tier))
2070
+ // A higher tier's unread request stays ahead of these tiers' starts.
2071
+ const readable = tiers.filter((tier) => !this.admissionBarred('start', tier))
2072
+ const matching = Object.values(starts.pending)
2073
+ .filter((request) => readable.includes(startTierOf(request)))
1909
2074
  .sort((a, b) => rank(a) - rank(b) || a.seq - b.seq)
1910
- .slice(0, START_REQUESTS_PER_TICK)
1911
- if (pending.length === 0 || paused) return
2075
+ const pending = matching.slice(0, late ? this.lateStartRequests : START_REQUESTS_PER_TICK)
2076
+ if (paused) return
2077
+ // A request filed since the tick started can push one it sampled out of
2078
+ // the allowance: the barrier rises to the highest unread tier.
2079
+ const unread = matching[pending.length]
2080
+ if (
2081
+ unread !== undefined &&
2082
+ this.claimGateOpen() &&
2083
+ (this.startBarrier === undefined || rank(unread) < START_TIERS.indexOf(this.startBarrier))
2084
+ )
2085
+ this.startBarrier = startTierOf(unread)
2086
+ if (pending.length === 0) return
2087
+ if (late) this.lateStartRequests -= pending.length
1912
2088
  const { tickets, config } = this.deps
1913
2089
  const migrations = this.store.repositoryFacts().ticketMigrations
1914
2090
  // Deferred mixed-version builds are still active: include them, so a
@@ -2004,19 +2180,17 @@ export class Dispatcher {
2004
2180
  const now = this.deps.clock()
2005
2181
  const measured = await this.capacityBuilds(launched, true)
2006
2182
  const projection = dispatchCapacity(measured, config.capacity, now, {
2007
- urgentClaims: this.urgentClaims(),
2183
+ claims: this.claims(),
2008
2184
  startRequests: this.startClaims(),
2009
2185
  })
2010
2186
  const adjust = { settled: this.parkedSettled, denied: this.slotWaiters }
2011
- const budgets = {
2012
- manual: startCapacity(projection, adjust, 'manual'),
2013
- urgent: startCapacity(projection, adjust, 'urgent'),
2014
- normal: startCapacity(projection, adjust, 'normal'),
2015
- }
2187
+ const budgets = Object.fromEntries(
2188
+ START_TIERS.map((tier) => [tier, startCapacity(projection, adjust, tier)]),
2189
+ ) as Record<StartTier, number>
2016
2190
  const open = new Set(Object.values(starts.pending).map(({ seq }) => seq))
2017
2191
  for (const seq of this.startBlockersChecked)
2018
2192
  if (!open.has(seq)) this.startBlockersChecked.delete(seq)
2019
- const free = (request: PendingTicketStart) => budgets[request.priority] > 0
2193
+ const free = (request: PendingTicketStart) => budgets[startTierOf(request)] > 0
2020
2194
  const passing = candidates.filter(
2021
2195
  ({ request, ticket }) =>
2022
2196
  free(request) ||
@@ -2059,6 +2233,12 @@ export class Dispatcher {
2059
2233
  if (settled === undefined) continue
2060
2234
  const { outcome, ...extra } = settled
2061
2235
  await this.settleStartRequest(request, outcome, extra)
2236
+ result.settled.push({
2237
+ ticket: `${ticket.ref.source}:${ticket.ref.id}`,
2238
+ seq: request.seq,
2239
+ tier: startTierOf(request),
2240
+ started: outcome === 'started',
2241
+ })
2062
2242
  }
2063
2243
  }
2064
2244
  }
@@ -2146,7 +2326,7 @@ export class Dispatcher {
2146
2326
  await this.store.refreshJournal()
2147
2327
  const current =
2148
2328
  this.store.repositoryFacts().ticketStarts.pending[ticketStartKey(request.ticket)]
2149
- return current?.seq === request.seq && current.priority === request.priority
2329
+ return current?.seq === request.seq && startTierOf(current) === startTierOf(request)
2150
2330
  }
2151
2331
 
2152
2332
  /** Settle one start request once. The journal is refreshed first, so a
@@ -2169,7 +2349,7 @@ export class Dispatcher {
2169
2349
  payload: {
2170
2350
  request: request.seq,
2171
2351
  ticket: request.ticket,
2172
- priority: current.priority,
2352
+ ...startTierFields(startTierOf(current)),
2173
2353
  outcome,
2174
2354
  ...(extra.slug !== undefined ? { slug: extra.slug } : {}),
2175
2355
  ...(detail ? { detail } : {}),
@@ -2339,7 +2519,7 @@ export class Dispatcher {
2339
2519
  }
2340
2520
 
2341
2521
  /** `force` makes the scan due now, skipping the interval and the journal
2342
- * deferral: a deferred normal admission waits on this tick's urgent claims. */
2522
+ * deferral: a deferred admission waits on this tick's higher-level claims. */
2343
2523
  private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
2344
2524
  const digest = (await this.repoBuildDigests())
2345
2525
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
@@ -2376,8 +2556,9 @@ export class Dispatcher {
2376
2556
  private async completeScan(
2377
2557
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
2378
2558
  report: TickReport,
2379
- urgentWaiting = 0,
2559
+ waiting: ScanClaimWaiting = {},
2380
2560
  ): Promise<void> {
2561
+ const { urgent: urgentWaiting = 0, high: highWaiting = 0, normal: normalWaiting = 0 } = waiting
2381
2562
  const payload = {
2382
2563
  startedAt: checkpoint.startedAt,
2383
2564
  mode: checkpoint.mode,
@@ -2391,11 +2572,16 @@ export class Dispatcher {
2391
2572
  creationWithheld: report.creationWithheld,
2392
2573
  creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
2393
2574
  ...(urgentWaiting > 0 ? { urgentWaiting } : {}),
2575
+ ...(highWaiting > 0 ? { highWaiting } : {}),
2576
+ ...(normalWaiting > 0 ? { normalWaiting } : {}),
2394
2577
  }
2395
2578
  const previous = this.latestScan()
2579
+ // The key loop sees only present keys, so absent counts compare here.
2396
2580
  const unchanged =
2397
2581
  previous !== undefined &&
2398
2582
  previous.urgentWaiting === payload.urgentWaiting &&
2583
+ previous.highWaiting === payload.highWaiting &&
2584
+ previous.normalWaiting === payload.normalWaiting &&
2399
2585
  Object.keys(payload)
2400
2586
  .filter((key) => key !== 'startedAt')
2401
2587
  .every(
@@ -2565,7 +2751,16 @@ export class Dispatcher {
2565
2751
  ) {
2566
2752
  return 'already-active'
2567
2753
  }
2568
- return this.deps.launchRunner(slug)
2754
+ try {
2755
+ return await this.deps.launchRunner(slug)
2756
+ } catch (error) {
2757
+ // A launch waiting on a stopped-sandbox recovery the budget deferred:
2758
+ // nothing started and nothing is charged. Record it so the next
2759
+ // invocation runs it first; callers see the same result as before.
2760
+ if (!isRecoveryDeferred(error)) throw error
2761
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
2762
+ return 'already-active'
2763
+ }
2569
2764
  }
2570
2765
 
2571
2766
  // ── 0. Settlement stage (durable supervision) ──────────────────────────────
@@ -2587,6 +2782,8 @@ export class Dispatcher {
2587
2782
  const active = this.deps.activeExecutions?.() ?? new Set<string>()
2588
2783
  for (const record of await this.workBuilds()) {
2589
2784
  if (active.has(record.slug)) continue
2785
+ // The early stage already observed and settled it this tick.
2786
+ if (this.tickPrioritized.has(record.slug)) continue
2590
2787
  // Budget gate: once spent, stop settling further foreign executions.
2591
2788
  if (this.outOfBudget(opts)) break
2592
2789
  try {
@@ -2603,14 +2800,18 @@ export class Dispatcher {
2603
2800
  ...(this.settlePublication !== undefined
2604
2801
  ? { settlePublication: this.settlePublication }
2605
2802
  : {}),
2803
+ onDeferred: (slug, step, detail) => this.noteDeferral(slug, step, detail),
2606
2804
  },
2607
2805
  record.slug,
2608
2806
  open,
2609
2807
  )
2610
2808
  if (settlement === 'settled') report.settled += 1
2611
- } catch {
2809
+ } catch (error) {
2612
2810
  // An unobservable build must not stall settlement of the rest; the
2613
- // next tick retries it.
2811
+ // next tick retries it. A budget deferral is recorded so the next
2812
+ // invocation observes it first.
2813
+ if (isRecoveryDeferred(error))
2814
+ await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
2614
2815
  }
2615
2816
  }
2616
2817
  }
@@ -2930,8 +3131,14 @@ export class Dispatcher {
2930
3131
  estimate !== undefined &&
2931
3132
  this.tickDeadlineAt !== undefined &&
2932
3133
  this.tickDeadlineAt - this.deps.clock().getTime() < estimate
2933
- )
3134
+ ) {
3135
+ await this.noteDeferral(
3136
+ slug,
3137
+ 'provision',
3138
+ `${Math.max(0, this.tickDeadlineAt - this.deps.clock().getTime())} ms remain but a provision needs about ${estimate} ms`,
3139
+ )
2934
3140
  return 'budget-wait'
3141
+ }
2935
3142
  // A finished leaf waits for a slot before its continuation reserves one.
2936
3143
  // Nothing is written: the wait costs no attempt and raises no attention.
2937
3144
  if (tail === 'launch' && (await this.leafAdmission(slug)) !== 'admit') return 'slot-wait'
@@ -3178,35 +3385,57 @@ export class Dispatcher {
3178
3385
  * then release each one's provisioning lease, in that order. Never awaited
3179
3386
  * by a tick. */
3180
3387
  async stopProvisioning(): Promise<void> {
3181
- const entries = [...this.continuations.values()]
3182
- for (const entry of entries) entry.controller.abort()
3183
- for (const entry of entries) {
3184
- try {
3185
- const events = (await readBuildFacts(this.store, entry.slug)).value
3186
- if (this.openProvisionMarker(events) !== undefined) {
3187
- const attempt = events.dispatchFailureCount + 1
3188
- await this.store.append(entry.slug, {
3189
- actor: DISPATCHER,
3190
- type: 'dispatch.failed',
3191
- payload: {
3192
- stage: 'workspace',
3193
- attempt,
3194
- error:
3195
- 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3196
- abandoned: 'teardown',
3197
- },
3198
- })
3388
+ this.abortProvisioning()
3389
+ // Every signalled continuation, including one that already exited on its
3390
+ // abort since `abortProvisioning` ran at a bounded invocation's deadline.
3391
+ const entries = [...this.abortedContinuations.values()]
3392
+ this.abortedContinuations.clear()
3393
+ // Entries settle independently, each keeping fact-then-release order, so
3394
+ // one entry whose store call stalls cannot starve the others.
3395
+ await Promise.allSettled(
3396
+ entries.map(async (entry) => {
3397
+ try {
3398
+ const events = (await readBuildFacts(this.store, entry.slug)).value
3399
+ if (this.openProvisionMarker(events) !== undefined) {
3400
+ const attempt = events.dispatchFailureCount + 1
3401
+ await this.store.append(entry.slug, {
3402
+ actor: DISPATCHER,
3403
+ type: 'dispatch.failed',
3404
+ payload: {
3405
+ stage: 'workspace',
3406
+ attempt,
3407
+ error:
3408
+ 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3409
+ abandoned: 'teardown',
3410
+ },
3411
+ })
3412
+ }
3413
+ } catch {
3414
+ // The durable marker plus the released lease still gate adoption.
3199
3415
  }
3200
- } catch {
3201
- // The durable marker plus the released lease still gate adoption.
3202
- }
3203
- try {
3204
- await this.store.releaseLease(entry.slug, entry.instance)
3205
- } catch {
3206
- // Expiry fences an ambiguous release.
3207
- }
3416
+ try {
3417
+ await this.store.releaseLease(entry.slug, entry.instance)
3418
+ } catch {
3419
+ // Expiry fences an ambiguous release.
3420
+ }
3421
+ }),
3422
+ )
3423
+ }
3424
+
3425
+ /** Synchronously signal every live provisioning continuation. A bounded
3426
+ * invocation calls it the moment its work deadline passes, so an aborted
3427
+ * provider call is classified as teardown abandonment, never a failure;
3428
+ * `stopProvisioning` later records the facts and releases the leases. */
3429
+ abortProvisioning(): void {
3430
+ for (const entry of this.continuations.values()) {
3431
+ this.abortedContinuations.set(entry.instance, entry)
3432
+ entry.controller.abort()
3208
3433
  }
3209
3434
  }
3435
+ /** Continuations signalled for teardown whose abandonment `stopProvisioning`
3436
+ * has not recorded yet. An aborted continuation removes itself from
3437
+ * `continuations` as it exits, so teardown keeps its own record. */
3438
+ private readonly abortedContinuations = new Map<string, ProvisionContinuation>()
3210
3439
 
3211
3440
  // ── a. Janitor (SPEC §15.7, D1) ────────────────────────────────────────────
3212
3441
 
@@ -3503,6 +3732,8 @@ export class Dispatcher {
3503
3732
  payload: {},
3504
3733
  })
3505
3734
  if (command.command === 'abort') {
3735
+ // The abort ended the janitor episode (§15.5).
3736
+ previous = undefined
3506
3737
  operation = 'abort cleanup'
3507
3738
  await this.cleanupAborted(record, await history(), report)
3508
3739
  }
@@ -3600,19 +3831,21 @@ export class Dispatcher {
3600
3831
  return
3601
3832
  }
3602
3833
  }
3603
- // Abort is destructive human judgment and therefore outranks a queued
3604
- // discard when both requests raced into the same stream.
3605
- if (
3606
- !executionLeaseLive &&
3607
- janitorStatus(state) === 'queued' &&
3608
- state.pendingCommands.some((command) => command.command === 'abort')
3609
- ) {
3610
- const acknowledged = await this.store.append(record.slug, {
3834
+ // The dispatcher acknowledges any leaf abort with no runner to hear
3835
+ // it: queued, paused or blocked with no live execution lease. The
3836
+ // lease sweep and startup resume stand aside for the same builds, so
3837
+ // no workspace is provisioned and no runner started just to
3838
+ // acknowledge. Abort is destructive human judgment and therefore
3839
+ // outranks a queued discard when both requests raced into the same
3840
+ // stream.
3841
+ if (!executionLeaseLive && dispatcherAcknowledgesAbort(state)) {
3842
+ await this.store.append(record.slug, {
3611
3843
  actor: DISPATCHER,
3612
3844
  type: 'build.aborted',
3613
3845
  payload: {},
3614
3846
  } satisfies EventWrite<'build.aborted'>)
3615
- void acknowledged
3847
+ // The abort ended the janitor episode (§15.5).
3848
+ previous = undefined
3616
3849
  // The view folded the acknowledgement it just appended.
3617
3850
  loaded = undefined
3618
3851
  operation = 'abort cleanup'
@@ -3746,6 +3979,12 @@ export class Dispatcher {
3746
3979
  // this build's janitor episode.
3747
3980
  if (janitorDeferral(error)) {
3748
3981
  attempted = false
3982
+ if (isRecoveryDeferred(error))
3983
+ await this.noteDeferral(
3984
+ record.slug,
3985
+ recoveryStepOf(error) ?? 'cleanup',
3986
+ errorText(error),
3987
+ )
3749
3988
  return
3750
3989
  }
3751
3990
  if (error instanceof MixedVersionDeferral) {
@@ -4135,15 +4374,39 @@ export class Dispatcher {
4135
4374
  return builds
4136
4375
  }
4137
4376
 
4377
+ /** Whether this tick's start barrier holds back admission of this kind at
4378
+ * this level (`admissionBarred`): the one guard waiting work (parked
4379
+ * leaves, nodes and proposers through `slotAdmission`), ordinary claims and
4380
+ * start passes consult. */
4381
+ private admissionBarred(kind: AdmissionKind, level: StartTier): boolean {
4382
+ return admissionBarred(this.startBarrier, kind, level)
4383
+ }
4384
+
4138
4385
  /** Whether ticket claims can run this tick: the one predicate both
4139
- * `dispatch` and the urgent admission boundary use. Without the source's
4140
- * priority capability every claim is normal, so nothing ever defers. */
4141
- private claimsPossible(opts: Pick<TickOpts, 'acceptNewWork'>, paused: boolean): boolean {
4142
- return (
4143
- !!this.deps.tickets.priority &&
4144
- opts.acceptNewWork !== false &&
4145
- !paused &&
4146
- this.claimGateOpen()
4386
+ * `dispatch` and the admission boundary use. */
4387
+ private claimsCanRun(opts: Pick<TickOpts, 'acceptNewWork'>, paused: boolean): boolean {
4388
+ return opts.acceptNewWork !== false && !paused && this.claimGateOpen()
4389
+ }
4390
+
4391
+ /** Whether a ticket claim ranked above `level` can exist: in memory, over
4392
+ * builds the caller already read. Nothing outranks urgent. With the
4393
+ * source's priority capability any higher level can be on a ready ticket,
4394
+ * and normal tickets exist in every source, so low always may. Otherwise
4395
+ * only an open optimization node's attempts claim above normal, at the
4396
+ * node's level (`attemptClaimTiers`); this over-approximates a node with
4397
+ * no ready attempt by at most one deferral. */
4398
+ private higherClaimsPossible(level: BuildPriority, builds: readonly CapacityBuild[]): boolean {
4399
+ if (level === 'urgent') return false
4400
+ if (this.deps.tickets.priority || level === 'low') return true
4401
+ const rank = priorityRank(level)
4402
+ return builds.some(
4403
+ ({ state }) =>
4404
+ state.kind === 'node' &&
4405
+ state.status !== 'done' &&
4406
+ state.status !== 'aborted' &&
4407
+ state.optimization !== undefined &&
4408
+ state.optimization.stopped === undefined &&
4409
+ priorityRank(buildPriority(state)) < rank,
4147
4410
  )
4148
4411
  }
4149
4412
 
@@ -4155,39 +4418,38 @@ export class Dispatcher {
4155
4418
  return !(health && Date.parse(health.resetAt) > this.deps.clock().getTime())
4156
4419
  }
4157
4420
 
4158
- /** Urgent ticket claims the latest admission scan found waiting for a slot.
4159
- * In memory: the journal view is refreshed each tick. */
4160
- private urgentClaims(): number {
4161
- return this.tickAcceptsNewWork ? urgentClaimDemand(this.store.repositoryFacts()) : 0
4421
+ /** Ticket claims by level the latest admission scan found waiting for a
4422
+ * slot. In memory: the journal view is refreshed each tick. */
4423
+ private claims(): ClaimDemand {
4424
+ return this.tickAcceptsNewWork ? claimDemand(this.store.repositoryFacts()) : {}
4162
4425
  }
4163
4426
 
4164
4427
  /** Pending operator start requests by tier; nothing while no claim can
4165
- * run. In memory, like `urgentClaims`. */
4166
- private startClaims(): Partial<Record<TicketStartPriority, number>> {
4428
+ * run. In memory, like `claims`. */
4429
+ private startClaims(): Partial<Record<StartTier, number>> {
4167
4430
  return this.claimGateOpen() ? startClaimDemand(this.store.repositoryFacts()) : {}
4168
4431
  }
4169
4432
 
4170
- /** A normal waiter must defer: claims can run and this tick's dispatch has
4171
- * not yet evaluated urgent claims. */
4172
- private urgentBoundaryOpen(): boolean {
4173
- return (
4174
- this.admissionBoundary &&
4175
- this.claimsPossible({ acceptNewWork: this.tickAcceptsNewWork }, this.tickPaused)
4176
- )
4177
- }
4178
-
4179
4433
  /** One parked waiter's admission into a free slot (SPEC §12 "Slot admission
4180
- * order"): urgent parked work, urgent claims, normal parked work, normal
4181
- * claims. `occupied` counts every other build holding a slot. */
4434
+ * order"): for each level, urgent first, its parked work and then its
4435
+ * claims. `occupied` counts every other build holding a slot. A waiter
4436
+ * defers while claims can run, this tick's dispatch has not yet evaluated
4437
+ * them, and a higher-level claim can exist (`higherClaimsPossible`). */
4182
4438
  private slotAdmission(
4183
4439
  slug: string,
4184
- priority: TicketPriority,
4440
+ priority: BuildPriority,
4185
4441
  occupied: number,
4186
4442
  projection: DispatchCapacity,
4443
+ builds: readonly CapacityBuild[],
4187
4444
  ): 'admit' | 'wait' | 'defer' {
4445
+ if (this.admissionBarred('waiting', priority)) return 'wait'
4188
4446
  if (occupied + reservedAhead(projection, { slug, priority }) >= this.deps.config.capacity)
4189
4447
  return 'wait'
4190
- return priority === 'normal' && this.urgentBoundaryOpen() ? 'defer' : 'admit'
4448
+ const boundary =
4449
+ this.admissionBoundary &&
4450
+ this.claimsCanRun({ acceptNewWork: this.tickAcceptsNewWork }, this.tickPaused) &&
4451
+ this.higherClaimsPossible(priority, builds)
4452
+ return boundary ? 'defer' : 'admit'
4191
4453
  }
4192
4454
 
4193
4455
  /** Whether a leaf may reserve a runner now (SPEC §12 "What holds a slot").
@@ -4241,9 +4503,10 @@ export class Dispatcher {
4241
4503
  priority,
4242
4504
  dispatchCapacity(others, capacity, now).occupied,
4243
4505
  dispatchCapacity(builds, capacity, now, {
4244
- urgentClaims: this.urgentClaims(),
4506
+ claims: this.claims(),
4245
4507
  startRequests: this.startClaims(),
4246
4508
  }),
4509
+ builds,
4247
4510
  )
4248
4511
  if (outcome === 'admit') {
4249
4512
  const request = leafSlotRequest(self)
@@ -4270,11 +4533,11 @@ export class Dispatcher {
4270
4533
 
4271
4534
  /**
4272
4535
  * Retry every admission deferred this tick, once this tick's admission scan
4273
- * has evaluated urgent claims. Each retry re-enters its generic path with
4536
+ * has evaluated claims at every level. Each retry re-enters its generic path with
4274
4537
  * fresh state: a leaf through the lease sweep's per-build pass, a node
4275
4538
  * through node admission, a proposer through proposer admission. Without a
4276
4539
  * completed evaluation nothing launches: the waiters stay reserved in
4277
- * `slotWaiters` against normal claims and are decided again next tick.
4540
+ * `slotWaiters` against claims at their level and are decided again next tick.
4278
4541
  */
4279
4542
  private async admitDeferredParked(
4280
4543
  report: TickReport,
@@ -4288,7 +4551,10 @@ export class Dispatcher {
4288
4551
  this.lastForcedDeferralKey = undefined
4289
4552
  return
4290
4553
  }
4291
- if (!this.urgentEvaluated) return
4554
+ if (!this.claimsEvaluated) return
4555
+ // Tail stage: a spent invocation budget admits nothing and reads nothing;
4556
+ // the parked builds stay durable work for the next invocation.
4557
+ if (this.budgetSpent(opts)) return
4292
4558
  this.admissionBoundary = false
4293
4559
  for (const [slug, kind] of deferred) {
4294
4560
  if (this.outOfBudget(opts)) return
@@ -4311,6 +4577,10 @@ export class Dispatcher {
4311
4577
  }
4312
4578
  } catch (error) {
4313
4579
  rethrowAuthorityLapse(error)
4580
+ if (isRecoveryDeferred(error)) {
4581
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
4582
+ continue
4583
+ }
4314
4584
  if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4315
4585
  if (error instanceof ForgeCooldown) throw error
4316
4586
  const message =
@@ -4496,7 +4766,7 @@ export class Dispatcher {
4496
4766
  )
4497
4767
  if (proposers.length === 0) return
4498
4768
  const projection = dispatchCapacity(builds, this.deps.config.capacity, now, {
4499
- urgentClaims: this.urgentClaims(),
4769
+ claims: this.claims(),
4500
4770
  startRequests: this.startClaims(),
4501
4771
  })
4502
4772
  let occupied = projection.occupied
@@ -4545,6 +4815,7 @@ export class Dispatcher {
4545
4815
  buildPriority(state),
4546
4816
  occupied,
4547
4817
  projection,
4818
+ builds,
4548
4819
  )
4549
4820
  if (outcome === 'defer') this.deferredAdmissions.set(record.slug, 'proposer')
4550
4821
  if (outcome !== 'admit') return
@@ -4921,9 +5192,10 @@ export class Dispatcher {
4921
5192
  now,
4922
5193
  ).occupied,
4923
5194
  dispatchCapacity(builds, capacity, now, {
4924
- urgentClaims: this.urgentClaims(),
5195
+ claims: this.claims(),
4925
5196
  startRequests: this.startClaims(),
4926
5197
  }),
5198
+ builds,
4927
5199
  )
4928
5200
  if (outcome === 'admit')
4929
5201
  return (await this.admitNodeNeed(slug, node.state, need)) ? 'admit' : 'wait'
@@ -7190,6 +7462,7 @@ export class Dispatcher {
7190
7462
  // publication's fate BEFORE the destructive reap. A guard failure is
7191
7463
  // recorded against the build — a stale workspace with an unrecorded
7192
7464
  // pending request is never reaped (the next tick retries).
7465
+ let step: WorkspaceRecoveryStep = 'fence'
7193
7466
  try {
7194
7467
  await preserveWorkspaceBeforeRelease({
7195
7468
  store: this.store,
@@ -7199,8 +7472,12 @@ export class Dispatcher {
7199
7472
  exec: this.deps.exec,
7200
7473
  reason,
7201
7474
  now: this.deps.clock(),
7475
+ onStep: (next) => {
7476
+ step = next
7477
+ },
7202
7478
  })
7203
7479
  events = (await readBuildFacts(this.store, slug)).value
7480
+ step = 'preserve'
7204
7481
  events = await settlePublicationFactsBeforeRelease(
7205
7482
  { store: this.store, settlePublication: this.settlePublication },
7206
7483
  slug,
@@ -7215,14 +7492,21 @@ export class Dispatcher {
7215
7492
  // A repository-wide forge cooldown or version deferral is not this
7216
7493
  // build's failure; the tick-level handlers own it.
7217
7494
  if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
7495
+ // The invocation deadline cut recovery short: nothing failed, so keep
7496
+ // the workspace and charge nothing; the next invocation runs it first.
7497
+ if (isRecoveryDeferred(error)) {
7498
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? step, errorText(error))
7499
+ return false
7500
+ }
7218
7501
  // Any other preservation or settlement failure (an unknown fence, a
7219
7502
  // checkout that could not be inspected) retains the workspace and its
7220
7503
  // pending work and is attributed to this build, never to the tick.
7504
+ // The recorded error names the recovery step that failed.
7221
7505
  await this.recordInfrastructureFailure(slug, events, {
7222
7506
  provider: open.provider,
7223
7507
  workspaceRef: open.ref,
7224
7508
  operation: 'reconcile',
7225
- error,
7509
+ error: stepAttributed(step, error),
7226
7510
  cleanupPending: true,
7227
7511
  })
7228
7512
  return false
@@ -7258,8 +7542,15 @@ export class Dispatcher {
7258
7542
  return true
7259
7543
  } catch (error) {
7260
7544
  rethrowAuthorityLapse(error)
7545
+ // A cleanup the invocation deadline cut short is retried next time; it
7546
+ // is neither a cleanup attempt nor a failure.
7547
+ if (isRecoveryDeferred(error)) {
7548
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'cleanup', errorText(error))
7549
+ return false
7550
+ }
7551
+ const failure = stepAttributed('cleanup', error)
7261
7552
  const message =
7262
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
7553
+ failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
7263
7554
  const _failed = await this.store.append(slug, {
7264
7555
  actor: DISPATCHER,
7265
7556
  type: 'infrastructure.cleanup-attempted',
@@ -7277,7 +7568,7 @@ export class Dispatcher {
7277
7568
  provider: open.provider,
7278
7569
  workspaceRef: open.ref,
7279
7570
  operation: 'reconcile',
7280
- error,
7571
+ error: failure,
7281
7572
  cleanupPending: true,
7282
7573
  })
7283
7574
  return false
@@ -7307,22 +7598,35 @@ export class Dispatcher {
7307
7598
  // pending publication BEFORE any provider cleanup call, while the
7308
7599
  // workspace still exists. The guard's append failure propagates — the
7309
7600
  // release never proceeds past an unrecorded pending request.
7310
- await preserveWorkspaceBeforeRelease({
7311
- store: this.store,
7312
- slug,
7313
- owner,
7314
- forge: this.deps.forge,
7315
- exec: this.deps.exec,
7316
- reason,
7317
- now: this.deps.clock(),
7318
- })
7319
- events = (await readBuildFacts(this.store, slug)).value
7320
- events = await settlePublicationFactsBeforeRelease(
7321
- { store: this.store, settlePublication: this.settlePublication },
7322
- slug,
7323
- events,
7324
- reason,
7325
- )
7601
+ if (reason === 'abort') {
7602
+ // Abort discards the build's work: preservation is best effort and the
7603
+ // pending publication is recorded lost without settling it, so a broken
7604
+ // workspace, guest or forge never holds the teardown hostage.
7605
+ await this.preserveBeforeAbortRelease(slug, owner)
7606
+ events = await recordPublicationLossBeforeRelease(
7607
+ { store: this.store },
7608
+ slug,
7609
+ (await readBuildFacts(this.store, slug)).value,
7610
+ reason,
7611
+ )
7612
+ } else {
7613
+ await preserveWorkspaceBeforeRelease({
7614
+ store: this.store,
7615
+ slug,
7616
+ owner,
7617
+ forge: this.deps.forge,
7618
+ exec: this.deps.exec,
7619
+ reason,
7620
+ now: this.deps.clock(),
7621
+ })
7622
+ events = (await readBuildFacts(this.store, slug)).value
7623
+ events = await settlePublicationFactsBeforeRelease(
7624
+ { store: this.store, settlePublication: this.settlePublication },
7625
+ slug,
7626
+ events,
7627
+ reason,
7628
+ )
7629
+ }
7326
7630
  const recovery = owner.recovery
7327
7631
  if (recovery !== undefined) {
7328
7632
  const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
@@ -7343,8 +7647,11 @@ export class Dispatcher {
7343
7647
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
7344
7648
  } catch (error) {
7345
7649
  rethrowAuthorityLapse(error)
7650
+ // Deferred to the next invocation: record nothing, keep the workspace.
7651
+ if (isRecoveryDeferred(error)) throw error
7652
+ const failure = stepAttributed('cleanup', error)
7346
7653
  const message =
7347
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
7654
+ failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
7348
7655
  const _failed = await this.store.append(slug, {
7349
7656
  actor: DISPATCHER,
7350
7657
  type: 'infrastructure.cleanup-attempted',
@@ -7362,7 +7669,7 @@ export class Dispatcher {
7362
7669
  provider: open.provider,
7363
7670
  workspaceRef: open.ref,
7364
7671
  operation: 'delete',
7365
- error,
7672
+ error: failure,
7366
7673
  cleanupPending: true,
7367
7674
  })
7368
7675
  throw error
@@ -7377,6 +7684,37 @@ export class Dispatcher {
7377
7684
  } satisfies EventWrite<'workspace.released'>)
7378
7685
  }
7379
7686
 
7687
+ /**
7688
+ * One best-effort preservation attempt ahead of an abort release. Only three
7689
+ * refusals stop the release: lost repository authority, a mixed-version
7690
+ * deferral, and a live execution lease. Every other failure records
7691
+ * `workspace.commits-lost` and returns so teardown continues.
7692
+ *
7693
+ * This is the one place a forge deferral (`ForgeRequestDeferred`, including
7694
+ * `ForgeCooldown`) does not propagate. The guarded forge has already refused
7695
+ * the archive and recorded the degradation, so no further forge call is made;
7696
+ * the archive is best effort under abort, and the release that follows is a
7697
+ * provider call, not a forge call. Do not route this catch through `fail()`
7698
+ * or a shared transient classifier: deferrals would gate teardown again.
7699
+ */
7700
+ private async preserveBeforeAbortRelease(slug: string, owner: WorkspaceProvider): Promise<void> {
7701
+ try {
7702
+ await preserveWorkspaceBeforeRelease({
7703
+ store: this.store,
7704
+ slug,
7705
+ owner,
7706
+ forge: this.deps.forge,
7707
+ exec: this.deps.exec,
7708
+ reason: 'abort',
7709
+ now: this.deps.clock(),
7710
+ })
7711
+ } catch (error) {
7712
+ rethrowAuthorityLapse(error)
7713
+ if (error instanceof MixedVersionDeferral || error instanceof WorkspaceLeaseLive) throw error
7714
+ await recordAbortPreservationFailure({ store: this.store, slug, error })
7715
+ }
7716
+ }
7717
+
7380
7718
  /** Only the authoritative forge may resolve a destination tip. */
7381
7719
  private async baseSha(baseBranch: string): Promise<string> {
7382
7720
  const read = this.deps.forge.remoteBranchSha
@@ -7439,6 +7777,7 @@ export class Dispatcher {
7439
7777
  target?: EventPayload<'build.created'>['target']
7440
7778
  baseBranch?: string
7441
7779
  priority?: 'urgent'
7780
+ level?: 'high' | 'low'
7442
7781
  }
7443
7782
  | undefined,
7444
7783
  ): EventPayload<'build.created'> {
@@ -7465,14 +7804,18 @@ export class Dispatcher {
7465
7804
  : {}),
7466
7805
  ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
7467
7806
  ...(seed?.priority !== undefined ? { priority: seed.priority } : {}),
7807
+ ...(seed?.level !== undefined ? { level: seed.level } : {}),
7468
7808
  }
7469
7809
  }
7470
7810
 
7471
- /** The claimed ticket's priority, frozen on `build.created`; normal is omitted. */
7472
- private claimedPriority(ticket: Ticket): { priority?: 'urgent' } {
7473
- return this.deps.tickets.priority && ticketPriority(ticket) === 'urgent'
7474
- ? { priority: 'urgent' }
7475
- : {}
7811
+ /** The level a claim freezes on `build.created`: a non-manual start
7812
+ * request's own level, otherwise the ticket's claim tier (`tierOf`). */
7813
+ private claimedLevel(
7814
+ ticket: Ticket,
7815
+ tier: StartTier,
7816
+ tierOf: (ticket: Ticket) => BuildPriority,
7817
+ ): BuildPriority {
7818
+ return tier === 'manual' ? tierOf(ticket) : tier
7476
7819
  }
7477
7820
 
7478
7821
  /** Every boundary before runner attachment is derived from durable facts.
@@ -7500,6 +7843,8 @@ export class Dispatcher {
7500
7843
  autoMergeUser?: string
7501
7844
  autoMergeDefaultSeq?: number
7502
7845
  assets?: PinnedAsset[]
7846
+ priority?: 'urgent'
7847
+ level?: 'high' | 'low'
7503
7848
  },
7504
7849
  ): Promise<DispatchOutcome> {
7505
7850
  if (!this.accountsAvailable()) return 'parked'
@@ -7542,7 +7887,6 @@ export class Dispatcher {
7542
7887
  ? { issueLinks: seed.ticket.issueLinks }
7543
7888
  : {}),
7544
7889
  ...(seed !== undefined ? this.selectedProfile(seed.ticket) : {}),
7545
- ...(seed !== undefined ? this.claimedPriority(seed.ticket) : {}),
7546
7890
  }),
7547
7891
  })
7548
7892
  events = (await readBuildFacts(store, record.slug)).value
@@ -7818,6 +8162,9 @@ export class Dispatcher {
7818
8162
  if (
7819
8163
  state.status !== 'queued' ||
7820
8164
  state.discardRequest !== undefined ||
8165
+ // A janitor that failed or ran out of budget before acknowledging
8166
+ // retries next tick; dispatch never provisions to acknowledge abort.
8167
+ dispatcherAcknowledgesAbort(state) ||
7821
8168
  heldByRepositoryPause(state, paused)
7822
8169
  ) {
7823
8170
  continue
@@ -7864,6 +8211,8 @@ export class Dispatcher {
7864
8211
  state.status === 'done' ||
7865
8212
  state.status === 'aborted' ||
7866
8213
  (state.status === 'queued' && state.discardRequest !== undefined) ||
8214
+ // The janitor acknowledges this abort; startup never launches for it.
8215
+ dispatcherAcknowledgesAbort(state) ||
7867
8216
  heldByRepositoryPause(state, paused)
7868
8217
  ) {
7869
8218
  continue
@@ -8034,7 +8383,7 @@ export class Dispatcher {
8034
8383
  /**
8035
8384
  * End open ticket waits whose tickets settled (SPEC §11 "Ticket waits").
8036
8385
  * Every waited ticket completed: `wait.ended {cause: automatic}`, and the
8037
- * build resumes ahead of normal claims. Any waited ticket rejected (the
8386
+ * build resumes ahead of claims at its level. Any waited ticket rejected (the
8038
8387
  * configured rejected role) or deleted: one `policy/wait-unresolvable`
8039
8388
  * escalation naming it, which the reducer reads as the wait's end. A wait
8040
8389
  * with tickets still pending stays in place.
@@ -8171,21 +8520,190 @@ export class Dispatcher {
8171
8520
  if (digest.waitPending && digest.kind !== 'node')
8172
8521
  await this.serviceWaitRequests(record, report)
8173
8522
  if (launched.has(record.slug)) continue
8523
+ // The early stage already swept it this tick.
8524
+ if (this.tickPrioritized.has(record.slug)) continue
8525
+ await this.sweepContained(record, report, launched, paused, now)
8526
+ }
8527
+ }
8528
+
8529
+ /** One build's lease-sweep pass under the sweep's per-build containment:
8530
+ * one build's failure never stops the caller from advancing the others.
8531
+ * Workspace failures are already durable against the build; a
8532
+ * repository-wide cooldown or an authority lapse still ends the tick.
8533
+ * `waiting` is a try-again-later outcome (a forge, mixed-version or budget
8534
+ * deferral); `failed` is a contained failure reported in diagnostics. */
8535
+ private async sweepContained(
8536
+ record: BuildRecord,
8537
+ report: TickReport,
8538
+ launched: Set<string>,
8539
+ paused: boolean,
8540
+ now: number,
8541
+ ): Promise<'done' | 'waiting' | 'failed'> {
8542
+ try {
8543
+ return await this.sweepBuild(record, report, launched, paused, now)
8544
+ } catch (error) {
8545
+ rethrowAuthorityLapse(error)
8546
+ if (isRecoveryDeferred(error)) {
8547
+ await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
8548
+ return 'waiting'
8549
+ }
8550
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral)
8551
+ return 'waiting'
8552
+ if (error instanceof ForgeCooldown) throw error
8553
+ const message =
8554
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8555
+ report.janitorFailed += 1
8556
+ report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8557
+ return 'failed'
8558
+ }
8559
+ }
8560
+
8561
+ /**
8562
+ * Stage −1 — deferred deadline-gated work. Builds the previous invocation
8563
+ * recorded in `dispatcher.work-deferred` (a provision or a stopped-sandbox
8564
+ * recovery the budget deferred) get the ordinary `sweepBuild` pass first,
8565
+ * before settlement and the janitor spend the window. The hint is never
8566
+ * authority: each pass re-derives every decision from fresh build state,
8567
+ * and a stale entry does nothing and is retired.
8568
+ *
8569
+ * Per-tick cost: zero reads when nothing is carried (the hint comes from
8570
+ * the repository facts the tick already reduced). Otherwise the record
8571
+ * listing and digests from this tick's epoch cache, with no fleet-wide
8572
+ * compatibility pass, plus one reduced `buildFacts` read per carried build
8573
+ * visited — a read the lease sweep would otherwise make later, and which
8574
+ * it now skips. Writes: at most one hint append when the list changes.
8575
+ */
8576
+ private async serviceDeferredWork(
8577
+ report: TickReport,
8578
+ launched: Set<string>,
8579
+ paused: boolean,
8580
+ opts: TickOpts,
8581
+ ): Promise<void> {
8582
+ if (this.carriedOutstanding.size === 0) return
8583
+ // Never the default form: it would run the mixed-version check for every
8584
+ // compatibility-bearing build. `sweepBuild` checks each carried build.
8585
+ const entries = new Map(
8586
+ (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
8587
+ )
8588
+ for (const slug of [...this.carriedOutstanding.keys()]) {
8589
+ if (this.outOfBudget(opts)) break
8590
+ const entry = this.carriedOutstanding.get(slug)!
8591
+ const found = entries.get(slug)
8592
+ if (found === undefined || found.digest.terminal !== undefined) {
8593
+ this.retireCarried(slug)
8594
+ continue
8595
+ }
8596
+ entry.visited = true
8597
+ this.tickPrioritized.add(slug)
8598
+ if (launched.has(slug)) {
8599
+ this.retireCarried(slug)
8600
+ continue
8601
+ }
8602
+ const outcome = await this.sweepContained(
8603
+ found.record,
8604
+ report,
8605
+ launched,
8606
+ paused,
8607
+ this.deps.clock().getTime(),
8608
+ )
8609
+ const interrupted = this.budgetSpent(opts)
8610
+ if (outcome !== 'waiting' && !interrupted && !this.tickDeferrals.has(slug))
8611
+ this.retireCarried(slug)
8612
+ }
8613
+ await this.persistDeferrals()
8614
+ }
8615
+
8616
+ /** A carried hint entry whose own pass showed it no longer needs priority.
8617
+ * Never writes: the next hint write simply omits it. */
8618
+ private retireCarried(slug: string): void {
8619
+ this.carriedOutstanding.delete(slug)
8620
+ }
8621
+
8622
+ /** Record that this tick deferred `slug`'s deadline-gated `step` for
8623
+ * budget, and keep the durable hint current. */
8624
+ private async noteDeferral(slug: string, step: DeferredWorkStep, detail?: string): Promise<void> {
8625
+ if (!this.tickDeferrals.has(slug))
8626
+ this.tickDeferrals.set(slug, { step, ...(detail !== undefined ? { detail } : {}) })
8627
+ await this.persistDeferrals()
8628
+ }
8629
+
8630
+ /** The hint this tick would write: unvisited carried entries first, in
8631
+ * carried order; then visited carried entries that are still outstanding
8632
+ * (re-deferred or interrupted); then this tick's new deferrals. Capped
8633
+ * from the tail, so new entries are dropped first. */
8634
+ private nextDeferralList(): { slug: string; step: DeferredWorkStep }[] {
8635
+ const list: { slug: string; step: DeferredWorkStep }[] = []
8636
+ const seen = new Set<string>()
8637
+ const push = (slug: string, step: DeferredWorkStep) => {
8638
+ if (seen.has(slug)) return
8639
+ seen.add(slug)
8640
+ list.push({ slug, step })
8641
+ }
8642
+ for (const [slug, entry] of this.carriedOutstanding) if (!entry.visited) push(slug, entry.step)
8643
+ for (const [slug, entry] of this.carriedOutstanding)
8644
+ if (entry.visited) push(slug, this.tickDeferrals.get(slug)?.step ?? entry.step)
8645
+ for (const [slug, { step }] of this.tickDeferrals) push(slug, step)
8646
+ return list.slice(0, MAX_DEFERRED_WORK)
8647
+ }
8648
+
8649
+ /** Append the merged hint when it differs from the one last read or
8650
+ * written. Every write keeps every unretired carried entry, so a pass cut
8651
+ * short at any point leaves a durable superset of what still needs
8652
+ * priority. A deferral noted after the work signal aborted is written in
8653
+ * the tick's teardown scope. Best effort: a failure costs only the hint. */
8654
+ private persistDeferrals(): Promise<void> {
8655
+ const write = this.deferralWrites.then(async () => {
8656
+ const next = this.nextDeferralList()
8657
+ const recorded = this.recordedDeferrals
8658
+ if (
8659
+ next.length === recorded.length &&
8660
+ next.every(
8661
+ (entry, i) => entry.slug === recorded[i]!.slug && entry.step === recorded[i]!.step,
8662
+ )
8663
+ )
8664
+ return
8665
+ if (this.deps.holdsRepoAuthority?.() === false) return
8666
+ // Past the work deadline, abandoned work writes nothing, except this
8667
+ // hint through the bounded, authorized teardown scope.
8668
+ const late = this.tickOpts.workSignal?.aborted === true
8669
+ const teardown = this.tickOpts.teardownWrite
8670
+ if (late && teardown === undefined) return
8671
+ const append = () =>
8672
+ this.store.appendRepo(this.deps.repo, {
8673
+ actor: DISPATCHER,
8674
+ type: 'dispatcher.work-deferred',
8675
+ payload: { builds: next },
8676
+ })
8174
8677
  try {
8175
- await this.sweepBuild(record, report, launched, paused, now)
8678
+ await (late ? teardown!(append) : append())
8679
+ this.recordedDeferrals = next
8176
8680
  } catch (error) {
8177
8681
  rethrowAuthorityLapse(error)
8178
- // Per-build containment: one build's failure never stops the sweep
8179
- // from advancing the others. Workspace failures are already durable
8180
- // against the build; a repository-wide cooldown still ends the tick.
8181
- if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
8182
- if (error instanceof ForgeCooldown) throw error
8183
- const message =
8184
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8185
- report.janitorFailed += 1
8186
- report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8682
+ this.deferralWriteFailure = errorText(error)
8187
8683
  }
8684
+ })
8685
+ this.deferralWrites = write.catch(() => {})
8686
+ return write
8687
+ }
8688
+
8689
+ /** A hint write failure this tick, reported once in the tick's diagnostics. */
8690
+ private deferralWriteFailure: string | undefined
8691
+
8692
+ /** Count and name this tick's deferrals on its report. Runs in `tick()`,
8693
+ * so every early return of `runTick` is covered. */
8694
+ private finishDeferrals(report: TickReport): void {
8695
+ for (const [slug, { step, detail }] of this.tickDeferrals) {
8696
+ if (step !== 'provision') report.recoveryDeferred += 1
8697
+ report.deferredDiagnostics.push(
8698
+ `build ${slug}: ${step} deferred by the invocation budget; the next invocation runs it first` +
8699
+ (detail !== undefined ? ` — ${detail}` : ''),
8700
+ )
8188
8701
  }
8702
+ if (this.deferralWriteFailure !== undefined)
8703
+ report.deferredDiagnostics.push(
8704
+ `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
8705
+ )
8706
+ this.deferralWriteFailure = undefined
8189
8707
  }
8190
8708
 
8191
8709
  /**
@@ -8238,23 +8756,37 @@ export class Dispatcher {
8238
8756
  })
8239
8757
  }
8240
8758
 
8241
- /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
8759
+ /** One build's lease-sweep pass; `sweepContained` contains its failures.
8760
+ * Resolves `waiting` when a mixed-version deferral holds the build, and
8761
+ * `done` otherwise. */
8242
8762
  private async sweepBuild(
8243
8763
  record: BuildRecord,
8244
8764
  report: TickReport,
8245
8765
  launched: Set<string>,
8246
8766
  paused: boolean,
8247
8767
  now: number,
8248
- ): Promise<void> {
8768
+ ): Promise<'done' | 'waiting'> {
8769
+ return (await this.sweepBuildPass(record, report, launched, paused, now)) ?? 'done'
8770
+ }
8771
+
8772
+ private async sweepBuildPass(
8773
+ record: BuildRecord,
8774
+ report: TickReport,
8775
+ launched: Set<string>,
8776
+ paused: boolean,
8777
+ now: number,
8778
+ ): Promise<'waiting' | undefined> {
8249
8779
  if (record.lease) {
8250
8780
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
8251
8781
  }
8252
8782
  const facts = await this.store.buildFacts(record.slug)
8253
8783
  const state = facts.state
8254
8784
  if (mixedVersionDeferred(state)) {
8255
- await deferMixedVersion(this.store, record.slug)
8256
- return
8785
+ return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
8257
8786
  }
8787
+ // The janitor owns this abort: a sweep must never reap, provision or
8788
+ // launch a runner only to acknowledge it.
8789
+ if (dispatcherAcknowledgesAbort(state)) return
8258
8790
  if (
8259
8791
  (state.status === 'queued' && state.discardRequest !== undefined) ||
8260
8792
  heldByRepositoryPause(state, paused)
@@ -8386,6 +8918,7 @@ export class Dispatcher {
8386
8918
  ...(this.settlePublication !== undefined
8387
8919
  ? { settlePublication: this.settlePublication }
8388
8920
  : {}),
8921
+ onDeferred: (slug, step, detail) => this.noteDeferral(slug, step, detail),
8389
8922
  },
8390
8923
  record.slug,
8391
8924
  foreignExecution,
@@ -8723,7 +9256,7 @@ export class Dispatcher {
8723
9256
  if (!this.claimGateOpen()) return
8724
9257
  const store = this.store
8725
9258
  const { tickets, config } = this.deps
8726
- // A normal parked admission deferred this tick waits on urgent claims:
9259
+ // A parked admission deferred this tick waits on higher-level claims:
8727
9260
  // list now, once per deferral key; an unchanged key waits for a scan that
8728
9261
  // is due on its own.
8729
9262
  let force = false
@@ -8757,12 +9290,12 @@ export class Dispatcher {
8757
9290
  const capacityBuilds =
8758
9291
  targeted?.measured ?? deferralBuilds ?? (await this.capacityBuilds(launched))
8759
9292
  // A node awaiting verification, or a parked build that must run again,
8760
- // reserves its slot ahead of claims of its own or a lower priority until
8761
- // it is admitted; this only ever lowers the claim budgets. Urgent claims
8762
- // wait only for urgent parked work (SPEC §12 "Slot admission order").
8763
- // Open-PR backpressure gates new normal-priority claims only: admission,
8764
- // the janitor, reconciles, landings and urgent claims are untouched, and
8765
- // capacity accounting is unchanged. Engagement is a durable repository
9293
+ // reserves its slot ahead of claims of its own or a lower level until it
9294
+ // is admitted; this only ever lowers the claim budgets. A claim waits
9295
+ // only for parked work at its level or above (SPEC §12 "Slot admission
9296
+ // order"). Open-PR backpressure gates new high, normal and low claims
9297
+ // only: admission, the janitor, reconciles, landings and urgent claims
9298
+ // are untouched, and capacity accounting is unchanged. Engagement is a durable repository
8766
9299
  // fact recorded only on transitions, so hysteresis survives restarts.
8767
9300
  const engagement = this.store.repositoryFacts().openPrBackpressure
8768
9301
  const engaged = engagement !== undefined
@@ -8772,9 +9305,13 @@ export class Dispatcher {
8772
9305
  engaged,
8773
9306
  )
8774
9307
  // Pending start requests reserve ahead of the ordinary claims they outrank.
9308
+ // Sampled with the requests themselves, so a start pass inside intake can
9309
+ // tell a reserved request from one filed since.
9310
+ const pendingStarts = this.store.repositoryFacts().ticketStarts.pending
9311
+ const startDemand = this.startClaims()
8775
9312
  const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
8776
9313
  openPrs: { policy: config.policy, engaged },
8777
- startRequests: this.startClaims(),
9314
+ startRequests: startDemand,
8778
9315
  })
8779
9316
  const transition = backpressureTransition(
8780
9317
  backpressure,
@@ -8785,25 +9322,60 @@ export class Dispatcher {
8785
9322
  await store.ensureRepo(this.deps.repo)
8786
9323
  await store.appendRepo(this.deps.repo, { actor: DISPATCHER, ...transition })
8787
9324
  }
8788
- const normalPaused = backpressure?.active === true
9325
+ const nonUrgentPaused = backpressure?.active === true
8789
9326
  const activeRefs: TicketRef[] = capacityBuilds
8790
9327
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
8791
9328
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
8792
9329
  const adjust = { settled: this.parkedSettled, denied: this.slotWaiters }
8793
- let capacity = intakeCapacity(projection, adjust)
8794
- let urgentCapacity = intakeCapacity(projection, adjust, 'urgent')
8795
- let urgentWaiting = 0
9330
+ // Each level's claim budget; a claim spends every level's slot, and ready
9331
+ // tickets are visited highest level first.
9332
+ const budgets = Object.fromEntries(
9333
+ TICKET_PRIORITIES.map((level) => [level, intakeCapacity(projection, adjust, level)]),
9334
+ ) as Record<BuildPriority, number>
9335
+ const waiting = { urgent: 0, high: 0, normal: 0 }
9336
+ // A ready ticket with a pending non-manual start request is left to the
9337
+ // start pass of its tier, which claims requests oldest first ahead of
9338
+ // that level's ready tickets. In memory over the tick's repository facts.
9339
+ // The requests the budgets reserved for (`startClaims`).
9340
+ const reservedStarts = new Set(
9341
+ Object.keys(startDemand).length > 0 ? Object.values(pendingStarts).map(({ seq }) => seq) : [],
9342
+ )
9343
+ const requested = (ticket: Ticket): boolean => {
9344
+ const request = pendingStarts[ticketStartKey(ticket.ref)]
9345
+ return request !== undefined && startTierOf(request) !== 'manual'
9346
+ }
8796
9347
  // Each ready ticket's claim tier: an optimization attempt claims at its
8797
9348
  // node's current build priority, any other ticket at its own priority
8798
9349
  // when the source stores one. Filled once the claimable set is known.
8799
- let attemptTiers = new Map<string, TicketPriority>()
8800
- const tierOf = (ticket: Ticket): TicketPriority =>
9350
+ let attemptTiers = new Map<string, BuildPriority>()
9351
+ const tierOf = (ticket: Ticket): BuildPriority =>
8801
9352
  attemptTiers.get(ticket.ref.id) ?? (tickets.priority ? ticketPriority(ticket) : 'normal')
8802
- const urgentClaim = (ticket: Ticket) =>
8803
- !targeted && ticket.kind !== 'node' && tierOf(ticket) === 'urgent'
9353
+ // A saturated claim counts as demand reserving ahead of lower-level
9354
+ // parked work: always at urgent; at high or normal only while work of a
9355
+ // lower level waits (a parked waiter or a start request), so the extra
9356
+ // preflight runs only where it can matter; never at low.
9357
+ const lowerWaiting = (level: BuildPriority): boolean => {
9358
+ const rank = priorityRank(level)
9359
+ const below = (entry: { priority?: BuildPriority }) =>
9360
+ priorityRank(entry.priority ?? 'normal') > rank
9361
+ return (
9362
+ (projection.waitingNodes ?? []).some(below) ||
9363
+ (projection.waitingBuilds ?? []).some(below) ||
9364
+ [...this.slotWaiters.values()].some((priority) => below({ priority })) ||
9365
+ START_TIERS.slice(START_TIERS.indexOf(level) + 1).some(
9366
+ (tier) => (projection.startRequests?.[tier] ?? 0) > 0,
9367
+ )
9368
+ )
9369
+ }
9370
+ const countsDemand = (level: BuildPriority): level is keyof typeof waiting =>
9371
+ level === 'urgent' || (level !== 'low' && lowerWaiting(level))
9372
+ const demandClaim = (ticket: Ticket) =>
9373
+ !targeted && ticket.kind !== 'node' && countsDemand(tierOf(ticket))
8804
9374
  // A targeted ticket's tier is its request's, never its ticket's priority.
8805
- const startTier = (ticket: Ticket): TicketStartPriority =>
8806
- targeted?.requests.get(ticket.ref.id)?.priority ?? 'manual'
9375
+ const startTier = (ticket: Ticket): StartTier => {
9376
+ const request = targeted?.requests.get(ticket.ref.id)
9377
+ return request === undefined ? 'manual' : startTierOf(request)
9378
+ }
8807
9379
 
8808
9380
  // The ready scan runs even at full capacity: `queued` is the operator's
8809
9381
  // standing queue-depth report and must stay honest exactly when the
@@ -8836,8 +9408,9 @@ export class Dispatcher {
8836
9408
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
8837
9409
  !this.preparing(ticket.ref.source, ticket.ref.id),
8838
9410
  )
8839
- // Urgent first, each class in source order (stable). Every gate below is
8840
- // unchanged; a source without the priority capability is all normal.
9411
+ // By level, urgent first, each level in source order (stable). Every gate
9412
+ // below is unchanged; a source without the priority capability is all
9413
+ // normal.
8841
9414
  // A ticket whose labels select two profiles is never claimed (SPEC §9).
8842
9415
  const conflicts = this.profileConflicts(eligible)
8843
9416
  // Conflicts and their diagnostics are produced in the same order.
@@ -8846,12 +9419,18 @@ export class Dispatcher {
8846
9419
  const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
8847
9420
  if (!targeted) attemptTiers = await this.attemptClaimTiers(claimable)
8848
9421
  // A targeted pass keeps its tier-then-request order.
8849
- const ready = targeted ? claimable : urgentFirstBy(claimable, tierOf)
9422
+ const toStarts = targeted ? [] : claimable.filter(requested)
9423
+ const ready = targeted
9424
+ ? claimable
9425
+ : byPriorityBy(
9426
+ claimable.filter((ticket) => !requested(ticket)),
9427
+ tierOf,
9428
+ )
8850
9429
  report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
8851
9430
  report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
8852
- if (!targeted && normalPaused)
9431
+ if (!targeted && nonUrgentPaused)
8853
9432
  report.ticketDiagnostics.push(backpressureExplanation(backpressure))
8854
- report.queued = ready.length
9433
+ report.queued = ready.length + toStarts.length
8855
9434
  const withheld = new Set<string>()
8856
9435
  for (const ticket of ready) {
8857
9436
  if (ticket.creationKey === undefined) continue
@@ -8886,21 +9465,22 @@ export class Dispatcher {
8886
9465
  // still runs either way, so the standing queue-depth report stays honest —
8887
9466
  // this only declines to claim a ticket into a build that would immediately
8888
9467
  // sit held.
8889
- // Saturated, an urgent ticket still runs the preflight: it claims an
8890
- // urgent budget, or counts as urgent demand waiting for a slot.
8891
- const urgentReady = ready.some((ticket) => urgentClaim(ticket) && !withheld.has(ticket.ref.id))
9468
+ // Saturated, a demand-counting ticket still runs the preflight: it claims
9469
+ // its level's budget, or counts as demand waiting for a slot.
9470
+ const demandReady = ready.some((ticket) => demandClaim(ticket) && !withheld.has(ticket.ref.id))
8892
9471
  const noBudget = targeted
8893
9472
  ? ready.every((ticket) => targeted.budgets[startTier(ticket)] <= 0)
8894
- : capacity <= 0 && !urgentReady
9473
+ : !demandReady &&
9474
+ ready.every((ticket) => withheld.has(ticket.ref.id) || budgets[tierOf(ticket)] <= 0)
8895
9475
  if (
8896
9476
  paused ||
8897
9477
  (!targeted &&
8898
- normalPaused &&
9478
+ nonUrgentPaused &&
8899
9479
  !ready.some((ticket) => tierOf(ticket) === 'urgent' && !withheld.has(ticket.ref.id))) ||
8900
9480
  (noBudget &&
8901
9481
  !ready.some(
8902
9482
  (ticket) =>
8903
- (targeted || !normalPaused || tierOf(ticket) === 'urgent') &&
9483
+ (targeted || !nonUrgentPaused || tierOf(ticket) === 'urgent') &&
8904
9484
  (ticket.kind === 'node' ||
8905
9485
  (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0)),
8906
9486
  ))
@@ -8909,8 +9489,9 @@ export class Dispatcher {
8909
9489
  await this.sourceCondition(undefined, 'ready-scan')
8910
9490
  if (!this.outOfBudget(opts)) {
8911
9491
  await this.completeScan(checkpoint, report)
8912
- // No urgent ticket is ready: this scan decided urgent claims.
8913
- if (!paused) this.urgentEvaluated = true
9492
+ // No ticket can claim or count as demand: this scan decided claims
9493
+ // at every level.
9494
+ if (!paused) this.claimsEvaluated = true
8914
9495
  }
8915
9496
  return
8916
9497
  }
@@ -9109,21 +9690,59 @@ export class Dispatcher {
9109
9690
  claimLoopCompleted = false
9110
9691
  break
9111
9692
  }
9112
- if (!targeted && normalPaused && tierOf(ticket) !== 'urgent') continue
9113
- const urgent = urgentClaim(ticket)
9114
- const budget = targeted
9115
- ? targeted.budgets[startTier(ticket)]
9116
- : urgent
9117
- ? urgentCapacity
9118
- : capacity
9119
- if (ticket.kind !== 'node' && budget <= 0 && !urgent) continue
9693
+ const level = tierOf(ticket)
9694
+ // Before this level's first ready ticket, its own and every higher late
9695
+ // start tier claims its pending requests (SPEC §12 "Slot admission
9696
+ // order"). A request it settles without starting frees its reservation.
9697
+ const startTiers = targeted
9698
+ ? []
9699
+ : LATE_START_TIERS.filter(
9700
+ (tier) =>
9701
+ !this.lateStartTiersHonored.has(tier) &&
9702
+ priorityRank(tier as BuildPriority) <= priorityRank(level),
9703
+ )
9704
+ if (startTiers.length > 0) {
9705
+ const pass = await this.honorStartRequests(
9706
+ report,
9707
+ launched,
9708
+ autoMergeUser,
9709
+ paused,
9710
+ opts,
9711
+ startTiers,
9712
+ )
9713
+ const listed = new Set(toStarts.map(({ ref }) => `${ref.source}:${ref.id}`))
9714
+ for (const decision of pass.settled) {
9715
+ if (decision.started && listed.has(decision.ticket)) report.queued -= 1
9716
+ // A reserved request frees its reservation, which a start then
9717
+ // occupies; one the budgets never reserved occupies a slot of every
9718
+ // level when it starts.
9719
+ const reserved = reservedStarts.has(decision.seq)
9720
+ for (const entry of TICKET_PRIORITIES) {
9721
+ const covered = priorityRank(entry) >= priorityRank(decision.tier as BuildPriority)
9722
+ if (reserved && covered && !decision.started) budgets[entry] += 1
9723
+ if (!reserved && decision.started) budgets[entry] -= 1
9724
+ }
9725
+ }
9726
+ if (this.outOfBudget(opts)) {
9727
+ claimLoopCompleted = false
9728
+ break
9729
+ }
9730
+ }
9731
+ if (!targeted && nonUrgentPaused && tierOf(ticket) !== 'urgent') continue
9732
+ // Start requests this tick cannot read stay ahead of ready tickets at
9733
+ // their tier and below until a later scan. A node ticket's claim takes
9734
+ // no slot.
9735
+ if (!targeted && ticket.kind !== 'node' && this.admissionBarred('claim', level)) continue
9736
+ const demand = demandClaim(ticket)
9737
+ const budget = targeted ? targeted.budgets[startTier(ticket)] : budgets[level]
9738
+ if (ticket.kind !== 'node' && budget <= 0 && !demand) continue
9120
9739
  if (withheld.has(ticket.ref.id)) continue
9121
9740
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
9122
9741
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
9123
- // An urgent ticket that passed every gate but capacity is demand that
9124
- // normal parked work yields to until the next admission scan.
9742
+ // A ticket that passed every gate but capacity is demand that
9743
+ // lower-level parked work yields to until the next admission scan.
9125
9744
  if (ticket.kind !== 'node' && budget <= 0) {
9126
- urgentWaiting += 1
9745
+ if (countsDemand(level)) waiting[level] += 1
9127
9746
  continue
9128
9747
  }
9129
9748
 
@@ -9317,12 +9936,9 @@ export class Dispatcher {
9317
9936
  ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
9318
9937
  // Fixed at claim from the same sample: relabelling never changes it.
9319
9938
  ...this.selectedProfile(ticket),
9320
- // `manual` is admission-only; an explicit urgent start is urgent.
9321
- ...(startTier(ticket) === 'urgent' && targeted
9322
- ? { priority: 'urgent' as const }
9323
- : tierOf(ticket) === 'urgent'
9324
- ? { priority: 'urgent' as const }
9325
- : {}),
9939
+ // `manual` is admission-only: a build started by any other request
9940
+ // takes the request's level, every other build its ticket's.
9941
+ ...createdPriorityFields(this.claimedLevel(ticket, startTier(ticket), tierOf)),
9326
9942
  }
9327
9943
  // `build.created` rides with the record so the pinned assets and the
9328
9944
  // record exist together or not at all.
@@ -9396,10 +10012,7 @@ export class Dispatcher {
9396
10012
  }
9397
10013
  report.queued -= 1
9398
10014
  if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
9399
- else if (ticket.kind !== 'node') {
9400
- capacity -= 1
9401
- urgentCapacity -= 1
9402
- }
10015
+ else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
9403
10016
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
9404
10017
  ticket,
9405
10018
  body,
@@ -9411,9 +10024,9 @@ export class Dispatcher {
9411
10024
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
9412
10025
  }
9413
10026
  if (checkpoint !== undefined && scanSuccessful && !this.outOfBudget(opts)) {
9414
- await this.completeScan(checkpoint, report, urgentWaiting)
9415
- // The only other place this tick authorizes deferred normal admissions.
9416
- if (claimLoopCompleted) this.urgentEvaluated = true
10027
+ await this.completeScan(checkpoint, report, waiting)
10028
+ // The only other place this tick authorizes deferred admissions.
10029
+ if (claimLoopCompleted) this.claimsEvaluated = true
9417
10030
  }
9418
10031
  }
9419
10032
 
@@ -9462,10 +10075,8 @@ export class Dispatcher {
9462
10075
  * other tickets keep their own tier. Costs one served node state per open,
9463
10076
  * unstopped optimization node a ready ticket targets, and none otherwise.
9464
10077
  */
9465
- private async attemptClaimTiers(
9466
- tickets: readonly Ticket[],
9467
- ): Promise<Map<string, TicketPriority>> {
9468
- const tiers = new Map<string, TicketPriority>()
10078
+ private async attemptClaimTiers(tickets: readonly Ticket[]): Promise<Map<string, BuildPriority>> {
10079
+ const tiers = new Map<string, BuildPriority>()
9469
10080
  const candidates = tickets.filter(
9470
10081
  (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
9471
10082
  )