@defrex/autobuild 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +435 -160
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +25 -3
  5. package/docs/architecture.md +124 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +110 -15
  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 +5 -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 +51 -12
  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 +17 -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 +527 -144
  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/repository.ts +14 -3
  54. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +27 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  61. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  63. package/packages/core/src/kernel/done-escalations.ts +269 -0
  64. package/packages/core/src/kernel/engine.ts +28 -9
  65. package/packages/core/src/kernel/integration-landing.ts +24 -4
  66. package/packages/core/src/kernel/integration-stack.ts +39 -0
  67. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  68. package/packages/core/src/kernel/log-index-value.ts +3 -0
  69. package/packages/core/src/kernel/log-index.ts +41 -2
  70. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  71. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  72. package/packages/core/src/kernel/reducer-revisions.ts +15 -0
  73. package/packages/core/src/kernel/reducer.ts +27 -7
  74. package/packages/core/src/kernel/repository-attention.ts +14 -5
  75. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  76. package/packages/core/src/kernel/verify-stages.ts +46 -7
  77. package/packages/core/src/operator/attention.ts +28 -3
  78. package/packages/core/src/operator/done-escalations.ts +38 -0
  79. package/packages/core/src/operator/presentation.ts +1 -1
  80. package/packages/core/src/operator/protocol.ts +8 -5
  81. package/packages/core/src/operator/query.ts +33 -19
  82. package/packages/core/src/operator/registry.ts +17 -13
  83. package/packages/core/src/operator/ticket-start.ts +8 -7
  84. package/packages/core/src/operator/tickets.ts +28 -9
  85. package/packages/core/src/plugin-sdk/index.ts +10 -0
  86. package/packages/core/src/plugins/manifest.ts +14 -1
  87. package/packages/core/src/ports/forge/create.ts +8 -0
  88. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  89. package/packages/core/src/ports/forge/github.ts +3 -0
  90. package/packages/core/src/ports/tickets/contract.ts +147 -76
  91. package/packages/core/src/ports/tickets/create.ts +47 -7
  92. package/packages/core/src/ports/tickets/fake.ts +8 -4
  93. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  94. package/packages/core/src/ports/tickets/file.ts +7 -3
  95. package/packages/core/src/ports/tickets/github.ts +1 -0
  96. package/packages/core/src/ports/tickets/grants.ts +11 -3
  97. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  98. package/packages/core/src/ports/tickets/linear.ts +28 -9
  99. package/packages/core/src/ports/tickets/migration.ts +4 -4
  100. package/packages/core/src/ports/tickets/operations.ts +4 -2
  101. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  102. package/packages/core/src/ports/tickets/priority.ts +127 -21
  103. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  104. package/packages/core/src/ports/tickets/remote.ts +104 -11
  105. package/packages/core/src/ports/tickets/revision.ts +5 -3
  106. package/packages/core/src/ports/tickets/search.ts +9 -0
  107. package/packages/core/src/ports/tickets/tree.ts +8 -6
  108. package/packages/core/src/ports/types.ts +30 -15
  109. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  110. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  111. package/packages/core/src/ports/workspace/create.ts +16 -3
  112. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  113. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  114. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  115. package/packages/core/src/processes/build-execution-state.ts +4 -0
  116. package/packages/core/src/processes/build-runner.ts +14 -1
  117. package/packages/core/src/processes/dispatcher.ts +544 -212
  118. package/packages/core/src/processes/execution-settlement.ts +1 -0
  119. package/packages/core/src/processes/harvest-runner.ts +12 -7
  120. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  121. package/packages/core/src/processes/invocation-budget.ts +176 -0
  122. package/packages/core/src/processes/publication-loss.ts +38 -3
  123. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  124. package/packages/core/src/store/contract.ts +81 -3
  125. package/packages/core/src/store/event-reads.ts +30 -1
  126. package/packages/core/src/store/reduced-reads.ts +23 -0
  127. package/packages/core/src/store/reducer-value-shapes.json +6628 -6469
  128. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  129. package/packages/core/src/store/remote/client.ts +169 -29
  130. package/packages/core/src/store/remote/compatibility.ts +113 -56
  131. package/packages/core/src/store/remote/credentials.ts +4 -1
  132. package/packages/core/src/store/remote/protocol.ts +3 -0
  133. package/packages/core/src/store/remote/released-clients.json +11 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  135. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  136. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  137. package/packages/core/src/store/remote/retry.ts +406 -0
  138. package/packages/core/src/testing/dispatch-read-budget.ts +144 -10
  139. package/packages/core/src/testing/index.ts +2 -0
  140. package/packages/core/src/testing/invocation-budget.ts +42 -0
  141. package/packages/core/src/testing/reduced-read-budget.ts +381 -18
  142. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  143. package/packages/core/src/web/overview-source.ts +19 -6
  144. package/skills/guide/SKILL.md +138 -67
  145. package/skills/guide/references/integration-tree.md +12 -9
  146. package/skills/guide/references/merge-policy.md +7 -2
  147. package/skills/guide/references/operator-api.md +46 -23
  148. package/skills/guide/references/optimization-nodes.md +7 -6
  149. package/skills/guide/references/plugin-authoring.md +46 -18
  150. package/skills/guide/references/remote-store-protocol.md +51 -12
  151. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  152. package/skills/guide/references/restacking.md +48 -3
  153. package/skills/guide/references/setup.md +2 -1
  154. package/skills/guide/references/ticket-migration.md +2 -2
  155. package/skills/operate/SKILL.md +82 -51
  156. package/skills/plan/SKILL.md +4 -3
  157. package/skills/spec/SKILL.md +9 -5
  158. package/skills/tickets/SKILL.md +25 -17
  159. 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,19 @@ 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
+ type WorkspaceRecoveryStep,
349
+ } from '../ports/workspace/recovery-step'
326
350
  import type {
327
351
  DependencyState,
328
352
  Forge,
329
353
  HeadChecks,
330
354
  IssueLink,
331
355
  PrState,
356
+ BuildPriority,
332
357
  Ticket,
333
- TicketPriority,
334
358
  TicketSource,
335
359
  WorkspaceProvider,
336
360
  WorkspaceProvisionResult,
@@ -372,7 +396,10 @@ import { recordInfrastructureFailure as appendInfrastructureFailure } from './in
372
396
  import { settleOpenExecution } from './execution-settlement'
373
397
  import { isWorkDigest, RepoViewStore } from './repo-view'
374
398
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
375
- import { settlePublicationFactsBeforeRelease } from './publication-loss'
399
+ import {
400
+ recordPublicationLossBeforeRelease,
401
+ settlePublicationFactsBeforeRelease,
402
+ } from './publication-loss'
376
403
 
377
404
  // ── Readiness resolution (SPEC §3.3) ─────────────────────────────────────────
378
405
 
@@ -758,7 +785,7 @@ interface TargetedDispatch {
758
785
  measured: CapacityBuild[]
759
786
  /** Slots left for each start tier (`startCapacity`). A claim spends only
760
787
  * its own tier's: lower tiers already reserved it as a pending request. */
761
- budgets: Record<TicketStartPriority, number>
788
+ budgets: Record<StartTier, number>
762
789
  }
763
790
 
764
791
  /** An active build's ticket ref, normalized through recorded migrations. */
@@ -768,9 +795,16 @@ interface ActiveTicketRef {
768
795
  ref: TicketRef
769
796
  }
770
797
 
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']
798
+ /** Gate-passing ticket claims one admission scan left waiting for a slot, by
799
+ * the levels that reserve ahead of lower-level parked work. */
800
+ type ScanClaimWaiting = { urgent?: number; high?: number; normal?: number }
801
+
802
+ /** Every request one start pass settled: its ticket (`source:id`), seq and
803
+ * tier, and whether it started a build. */
804
+ interface StartPassResult {
805
+ settled: { ticket: string; seq: number; tier: StartTier; started: boolean }[]
806
+ }
807
+
774
808
  /** Hosted active-build identities one tick resolves; each build once in its life. */
775
809
  const IDENTITY_RESOLUTIONS_PER_TICK = 16
776
810
  /** Released identity slugs one projection append carries. */
@@ -889,6 +923,11 @@ export interface TickOpts {
889
923
  * exactly as capacity exhaustion already defers tickets. Absent ⇒ unbounded
890
924
  * (today's exact behavior). */
891
925
  deadlineAt?: number
926
+ /** Bounded invocation's work signal: once aborted the tick starts no new
927
+ * unit of work, exactly as when the clock passes `deadlineAt`. In-flight
928
+ * requests made through the budgeted adapters are cancelled by the same
929
+ * signal. Absent ⇒ only `deadlineAt` bounds the tick. */
930
+ workSignal?: AbortSignal
892
931
  }
893
932
 
894
933
  /** Process-local launch coordination result. Durable lease acquisition remains
@@ -1041,6 +1080,15 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
1041
1080
 
1042
1081
  export const SWEEP_PIN_CACHE_CAPACITY = 128
1043
1082
 
1083
+ /** Name the recovery step a workspace failure happened in. Missing account
1084
+ * credentials stay unwrapped: the dispatcher holds for them by type instead
1085
+ * of recording a failure. */
1086
+ function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1087
+ return error instanceof MissingAccountCredentialsError
1088
+ ? error
1089
+ : attributeRecoveryStep(step, error)
1090
+ }
1091
+
1044
1092
  export class Dispatcher {
1045
1093
  // Only scheduling is cached. Eligibility facts still come from durable state,
1046
1094
  // and each admitted verification/publication samples the source this pass.
@@ -1292,21 +1340,21 @@ export class Dispatcher {
1292
1340
  private tickLaunched: ReadonlySet<string> = new Set()
1293
1341
  /** Per tick: finished leaves the admission gate turned away or deferred,
1294
1342
  * 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
1343
+ private readonly slotWaiters = new Map<string, BuildPriority>()
1344
+ /** Per tick, in visit order: parked admissions that would have taken a free
1345
+ * slot before this tick's dispatch evaluated higher-level claims (SPEC §12
1298
1346
  * "Slot admission order"). Nothing was written for them;
1299
1347
  * `admitDeferredParked` retries each through its generic path. */
1300
1348
  private readonly deferredAdmissions = new Map<string, 'leaf' | 'node' | 'proposer'>()
1301
1349
  /** Nodes `admitWaitingNodes` admitted in its current verification pass, so
1302
1350
  * proposer admission counts them even when provisioning or launch failed. */
1303
1351
  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. */
1352
+ /** Per tick: admission may defer non-urgent parked work. Opened by
1353
+ * `runTick` when claims can run, closed once claims were evaluated. */
1306
1354
  private admissionBoundary = false
1307
- /** Per tick: this tick's admission scan completed its urgent decision. Only
1355
+ /** Per tick: this tick's admission scan decided claims at every level. Only
1308
1356
  * `dispatch` sets it. */
1309
- private urgentEvaluated = false
1357
+ private claimsEvaluated = false
1310
1358
  /** Per tick: the deferral key this tick's admission scan was forced for. */
1311
1359
  private forcedDeferralKey: string | undefined
1312
1360
  /** In memory: the last deferral key whose forced scan completed and whose
@@ -1334,6 +1382,19 @@ export class Dispatcher {
1334
1382
  /** While the start pass's targeted dispatch runs: its deferral checks
1335
1383
  * serve this tick's retained facts (`servedBuildFacts`). */
1336
1384
  private startPass = false
1385
+ /** Per tick: late start tiers already honored, inside ordinary intake or
1386
+ * after it; each is honored at most once a tick. */
1387
+ private readonly lateStartTiersHonored = new Set<StartTier>()
1388
+ /** Per tick: start requests the late passes may still evaluate. Intake runs
1389
+ * a late pass before each level's first ready ticket, so the passes share
1390
+ * one allowance and a tick reads no more requests than one late pass. */
1391
+ private lateStartRequests = START_REQUESTS_PER_TICK
1392
+ /** Per tick: the start barrier (`startBarrier`), the highest tier with a
1393
+ * pending request the tick's allowance leaves unread. Sampled when the tick
1394
+ * starts, so admission before any start pass already respects it, and
1395
+ * raised by a pass that finds a request filed since unread. Every admission
1396
+ * path consults it through `admissionBarred` (SPEC §12). */
1397
+ private startBarrier: StartTier | undefined
1337
1398
  /** Per tick: the janitor's work listing, and the nonterminal children of
1338
1399
  * each node indexed from it on the first landing turn that needs them. The
1339
1400
  * landing gate reads its turn candidates here, never from a new listing. */
@@ -1392,9 +1453,15 @@ export class Dispatcher {
1392
1453
  * loops consult this before starting each new forge/store transport call,
1393
1454
  * bounding the tick's overrun to the one call already in flight. */
1394
1455
  private outOfBudget(opts: TickOpts): boolean {
1456
+ return this.budgetSpent(opts) || this.deps.holdsRepoAuthority?.() === false
1457
+ }
1458
+
1459
+ /** The invocation-budget half of `outOfBudget`: no clock read and no
1460
+ * authority check without a deadline, so an unbounded tick is unchanged. */
1461
+ private budgetSpent(opts: TickOpts): boolean {
1395
1462
  return (
1396
1463
  (opts.deadlineAt !== undefined && this.deps.clock().getTime() >= opts.deadlineAt) ||
1397
- this.deps.holdsRepoAuthority?.() === false
1464
+ opts.workSignal?.aborted === true
1398
1465
  )
1399
1466
  }
1400
1467
 
@@ -1555,10 +1622,13 @@ export class Dispatcher {
1555
1622
  this.integrationPublicationInputs = undefined
1556
1623
  this.nodePollingTickReads.clear()
1557
1624
  this.slotWaiters.clear()
1625
+ this.lateStartTiersHonored.clear()
1626
+ this.lateStartRequests = START_REQUESTS_PER_TICK
1627
+ this.startBarrier = undefined
1558
1628
  this.parkedSettled.clear()
1559
1629
  this.deferredAdmissions.clear()
1560
1630
  this.admissionBoundary = false
1561
- this.urgentEvaluated = false
1631
+ this.claimsEvaluated = false
1562
1632
  this.forcedDeferralKey = undefined
1563
1633
  // One immutable config for this complete decision pass. A reload racing the
1564
1634
  // tick is observed by the next tick, never half-way through this one.
@@ -1586,9 +1656,16 @@ export class Dispatcher {
1586
1656
  const paused = repoFacts.settings.paused
1587
1657
  this.tickAcceptsNewWork = opts.acceptNewWork !== false
1588
1658
  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)
1659
+ // Lower-level parked work never takes a free slot before this tick's
1660
+ // dispatch has evaluated higher-level claims, while claims can run at all.
1661
+ this.admissionBoundary = !opts.observationOnly && this.claimsCanRun(opts, paused)
1662
+ // Start requests this tick cannot read hold back lower-level admission,
1663
+ // whichever stage admits it; they reserve only while they can be
1664
+ // honored (`startClaims`).
1665
+ this.startBarrier =
1666
+ Object.keys(this.startClaims()).length > 0
1667
+ ? startBarrier(Object.values(repoFacts.ticketStarts.pending))
1668
+ : undefined
1592
1669
  const autoMergeSeedFact = undefined
1593
1670
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
1594
1671
  // provider liveness and settle their completion, lease, and publication.
@@ -1630,26 +1707,27 @@ export class Dispatcher {
1630
1707
  if (this.outOfBudget(opts)) return report
1631
1708
  // Operator start requests are independent of intake: they claim only the
1632
1709
  // 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
- ])
1710
+ // requests run here, ahead of ordinary claims; high, normal and low
1711
+ // requests run inside intake, after higher-level claims and before their
1712
+ // own level's ready tickets, or after intake when it reaches no ticket of
1713
+ // their level (SPEC §12 "Slot admission order").
1714
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, EARLY_START_TIERS)
1639
1715
  if (this.outOfBudget(opts)) return report
1640
1716
  if (opts.acceptNewWork !== false) {
1641
1717
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1642
1718
  }
1643
1719
  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'])
1720
+ // Late tiers intake did not reach: ordinary claims left their reserved
1721
+ // slots free.
1722
+ const lateTiers = LATE_START_TIERS.filter((tier) => !this.lateStartTiersHonored.has(tier))
1723
+ if (!this.outOfBudget(opts) && lateTiers.length > 0)
1724
+ await this.honorStartRequests(report, launched, autoMergeUser, paused, opts, lateTiers)
1647
1725
  // Fire-and-forget by contract: long synthesize/review sessions must not
1648
1726
  // stop janitor, lease sweep, ticket dispatch, or signal handling on later
1649
1727
  // watch ticks. Durable pause and infrastructure-error stops suppress
1650
1728
  // launch. Pending control commands still launch the runner so the kernel
1651
1729
  // can settle them under the repository lease.
1652
- await this.triggerHarvest()
1730
+ if (!this.budgetSpent(opts)) await this.triggerHarvest()
1653
1731
  await this.captureAgentContext(report, opts)
1654
1732
  return report
1655
1733
  }
@@ -1890,8 +1968,9 @@ export class Dispatcher {
1890
1968
  /** Admit pending operator start requests of the given tiers through
1891
1969
  * `dispatch()`'s gates and settle each one that reaches a decision. Zero
1892
1970
  * 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,
1971
+ * per request over the view-cached build digests: at most
1972
+ * START_REQUESTS_PER_TICK a tick for the early tiers, and as many shared by
1973
+ * every late pass of the tick. Waiting conditions (pause, no slot in the request's tier,
1895
1974
  * creation holds, an in-flight preparation, a failed dependency read, a
1896
1975
  * source error, the tick budget) leave the request pending. */
1897
1976
  private async honorStartRequests(
@@ -1900,15 +1979,45 @@ export class Dispatcher {
1900
1979
  autoMergeUser: string | undefined,
1901
1980
  paused: boolean,
1902
1981
  opts: TickOpts,
1903
- tiers: readonly TicketStartPriority[],
1982
+ tiers: readonly StartTier[],
1983
+ ): Promise<StartPassResult> {
1984
+ const result: StartPassResult = { settled: [] }
1985
+ for (const tier of tiers)
1986
+ if (LATE_START_TIERS.includes(tier)) this.lateStartTiersHonored.add(tier)
1987
+ await this.honorStartRequestTiers(report, launched, autoMergeUser, paused, opts, tiers, result)
1988
+ return result
1989
+ }
1990
+
1991
+ private async honorStartRequestTiers(
1992
+ report: TickReport,
1993
+ launched: Set<string>,
1994
+ autoMergeUser: string | undefined,
1995
+ paused: boolean,
1996
+ opts: TickOpts,
1997
+ tiers: readonly StartTier[],
1998
+ result: StartPassResult,
1904
1999
  ): Promise<void> {
1905
2000
  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))
2001
+ const rank = (request: PendingTicketStart) => START_TIERS.indexOf(startTierOf(request))
2002
+ const late = tiers.every((tier) => LATE_START_TIERS.includes(tier))
2003
+ // A higher tier's unread request stays ahead of these tiers' starts.
2004
+ const readable = tiers.filter((tier) => !this.admissionBarred('start', tier))
2005
+ const matching = Object.values(starts.pending)
2006
+ .filter((request) => readable.includes(startTierOf(request)))
1909
2007
  .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
2008
+ const pending = matching.slice(0, late ? this.lateStartRequests : START_REQUESTS_PER_TICK)
2009
+ if (paused) return
2010
+ // A request filed since the tick started can push one it sampled out of
2011
+ // the allowance: the barrier rises to the highest unread tier.
2012
+ const unread = matching[pending.length]
2013
+ if (
2014
+ unread !== undefined &&
2015
+ this.claimGateOpen() &&
2016
+ (this.startBarrier === undefined || rank(unread) < START_TIERS.indexOf(this.startBarrier))
2017
+ )
2018
+ this.startBarrier = startTierOf(unread)
2019
+ if (pending.length === 0) return
2020
+ if (late) this.lateStartRequests -= pending.length
1912
2021
  const { tickets, config } = this.deps
1913
2022
  const migrations = this.store.repositoryFacts().ticketMigrations
1914
2023
  // Deferred mixed-version builds are still active: include them, so a
@@ -2004,19 +2113,17 @@ export class Dispatcher {
2004
2113
  const now = this.deps.clock()
2005
2114
  const measured = await this.capacityBuilds(launched, true)
2006
2115
  const projection = dispatchCapacity(measured, config.capacity, now, {
2007
- urgentClaims: this.urgentClaims(),
2116
+ claims: this.claims(),
2008
2117
  startRequests: this.startClaims(),
2009
2118
  })
2010
2119
  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
- }
2120
+ const budgets = Object.fromEntries(
2121
+ START_TIERS.map((tier) => [tier, startCapacity(projection, adjust, tier)]),
2122
+ ) as Record<StartTier, number>
2016
2123
  const open = new Set(Object.values(starts.pending).map(({ seq }) => seq))
2017
2124
  for (const seq of this.startBlockersChecked)
2018
2125
  if (!open.has(seq)) this.startBlockersChecked.delete(seq)
2019
- const free = (request: PendingTicketStart) => budgets[request.priority] > 0
2126
+ const free = (request: PendingTicketStart) => budgets[startTierOf(request)] > 0
2020
2127
  const passing = candidates.filter(
2021
2128
  ({ request, ticket }) =>
2022
2129
  free(request) ||
@@ -2059,6 +2166,12 @@ export class Dispatcher {
2059
2166
  if (settled === undefined) continue
2060
2167
  const { outcome, ...extra } = settled
2061
2168
  await this.settleStartRequest(request, outcome, extra)
2169
+ result.settled.push({
2170
+ ticket: `${ticket.ref.source}:${ticket.ref.id}`,
2171
+ seq: request.seq,
2172
+ tier: startTierOf(request),
2173
+ started: outcome === 'started',
2174
+ })
2062
2175
  }
2063
2176
  }
2064
2177
  }
@@ -2146,7 +2259,7 @@ export class Dispatcher {
2146
2259
  await this.store.refreshJournal()
2147
2260
  const current =
2148
2261
  this.store.repositoryFacts().ticketStarts.pending[ticketStartKey(request.ticket)]
2149
- return current?.seq === request.seq && current.priority === request.priority
2262
+ return current?.seq === request.seq && startTierOf(current) === startTierOf(request)
2150
2263
  }
2151
2264
 
2152
2265
  /** Settle one start request once. The journal is refreshed first, so a
@@ -2169,7 +2282,7 @@ export class Dispatcher {
2169
2282
  payload: {
2170
2283
  request: request.seq,
2171
2284
  ticket: request.ticket,
2172
- priority: current.priority,
2285
+ ...startTierFields(startTierOf(current)),
2173
2286
  outcome,
2174
2287
  ...(extra.slug !== undefined ? { slug: extra.slug } : {}),
2175
2288
  ...(detail ? { detail } : {}),
@@ -2339,7 +2452,7 @@ export class Dispatcher {
2339
2452
  }
2340
2453
 
2341
2454
  /** `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. */
2455
+ * deferral: a deferred admission waits on this tick's higher-level claims. */
2343
2456
  private async scanCheckpoint(mode: 'admission' | 'observation', { force = false } = {}) {
2344
2457
  const digest = (await this.repoBuildDigests())
2345
2458
  .filter(({ digest }) => digest.readinessChangeSeq !== undefined)
@@ -2376,8 +2489,9 @@ export class Dispatcher {
2376
2489
  private async completeScan(
2377
2490
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
2378
2491
  report: TickReport,
2379
- urgentWaiting = 0,
2492
+ waiting: ScanClaimWaiting = {},
2380
2493
  ): Promise<void> {
2494
+ const { urgent: urgentWaiting = 0, high: highWaiting = 0, normal: normalWaiting = 0 } = waiting
2381
2495
  const payload = {
2382
2496
  startedAt: checkpoint.startedAt,
2383
2497
  mode: checkpoint.mode,
@@ -2391,11 +2505,16 @@ export class Dispatcher {
2391
2505
  creationWithheld: report.creationWithheld,
2392
2506
  creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
2393
2507
  ...(urgentWaiting > 0 ? { urgentWaiting } : {}),
2508
+ ...(highWaiting > 0 ? { highWaiting } : {}),
2509
+ ...(normalWaiting > 0 ? { normalWaiting } : {}),
2394
2510
  }
2395
2511
  const previous = this.latestScan()
2512
+ // The key loop sees only present keys, so absent counts compare here.
2396
2513
  const unchanged =
2397
2514
  previous !== undefined &&
2398
2515
  previous.urgentWaiting === payload.urgentWaiting &&
2516
+ previous.highWaiting === payload.highWaiting &&
2517
+ previous.normalWaiting === payload.normalWaiting &&
2399
2518
  Object.keys(payload)
2400
2519
  .filter((key) => key !== 'startedAt')
2401
2520
  .every(
@@ -3178,35 +3297,57 @@ export class Dispatcher {
3178
3297
  * then release each one's provisioning lease, in that order. Never awaited
3179
3298
  * by a tick. */
3180
3299
  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
- })
3300
+ this.abortProvisioning()
3301
+ // Every signalled continuation, including one that already exited on its
3302
+ // abort since `abortProvisioning` ran at a bounded invocation's deadline.
3303
+ const entries = [...this.abortedContinuations.values()]
3304
+ this.abortedContinuations.clear()
3305
+ // Entries settle independently, each keeping fact-then-release order, so
3306
+ // one entry whose store call stalls cannot starve the others.
3307
+ await Promise.allSettled(
3308
+ entries.map(async (entry) => {
3309
+ try {
3310
+ const events = (await readBuildFacts(this.store, entry.slug)).value
3311
+ if (this.openProvisionMarker(events) !== undefined) {
3312
+ const attempt = events.dispatchFailureCount + 1
3313
+ await this.store.append(entry.slug, {
3314
+ actor: DISPATCHER,
3315
+ type: 'dispatch.failed',
3316
+ payload: {
3317
+ stage: 'workspace',
3318
+ attempt,
3319
+ error:
3320
+ 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3321
+ abandoned: 'teardown',
3322
+ },
3323
+ })
3324
+ }
3325
+ } catch {
3326
+ // The durable marker plus the released lease still gate adoption.
3199
3327
  }
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
- }
3328
+ try {
3329
+ await this.store.releaseLease(entry.slug, entry.instance)
3330
+ } catch {
3331
+ // Expiry fences an ambiguous release.
3332
+ }
3333
+ }),
3334
+ )
3335
+ }
3336
+
3337
+ /** Synchronously signal every live provisioning continuation. A bounded
3338
+ * invocation calls it the moment its work deadline passes, so an aborted
3339
+ * provider call is classified as teardown abandonment, never a failure;
3340
+ * `stopProvisioning` later records the facts and releases the leases. */
3341
+ abortProvisioning(): void {
3342
+ for (const entry of this.continuations.values()) {
3343
+ this.abortedContinuations.set(entry.instance, entry)
3344
+ entry.controller.abort()
3208
3345
  }
3209
3346
  }
3347
+ /** Continuations signalled for teardown whose abandonment `stopProvisioning`
3348
+ * has not recorded yet. An aborted continuation removes itself from
3349
+ * `continuations` as it exits, so teardown keeps its own record. */
3350
+ private readonly abortedContinuations = new Map<string, ProvisionContinuation>()
3210
3351
 
3211
3352
  // ── a. Janitor (SPEC §15.7, D1) ────────────────────────────────────────────
3212
3353
 
@@ -3600,19 +3741,19 @@ export class Dispatcher {
3600
3741
  return
3601
3742
  }
3602
3743
  }
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, {
3744
+ // The dispatcher acknowledges any leaf abort with no runner to hear
3745
+ // it: queued, paused or blocked with no live execution lease. The
3746
+ // lease sweep and startup resume stand aside for the same builds, so
3747
+ // no workspace is provisioned and no runner started just to
3748
+ // acknowledge. Abort is destructive human judgment and therefore
3749
+ // outranks a queued discard when both requests raced into the same
3750
+ // stream.
3751
+ if (!executionLeaseLive && dispatcherAcknowledgesAbort(state)) {
3752
+ await this.store.append(record.slug, {
3611
3753
  actor: DISPATCHER,
3612
3754
  type: 'build.aborted',
3613
3755
  payload: {},
3614
3756
  } satisfies EventWrite<'build.aborted'>)
3615
- void acknowledged
3616
3757
  // The view folded the acknowledgement it just appended.
3617
3758
  loaded = undefined
3618
3759
  operation = 'abort cleanup'
@@ -4135,15 +4276,39 @@ export class Dispatcher {
4135
4276
  return builds
4136
4277
  }
4137
4278
 
4279
+ /** Whether this tick's start barrier holds back admission of this kind at
4280
+ * this level (`admissionBarred`): the one guard waiting work (parked
4281
+ * leaves, nodes and proposers through `slotAdmission`), ordinary claims and
4282
+ * start passes consult. */
4283
+ private admissionBarred(kind: AdmissionKind, level: StartTier): boolean {
4284
+ return admissionBarred(this.startBarrier, kind, level)
4285
+ }
4286
+
4138
4287
  /** 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()
4288
+ * `dispatch` and the admission boundary use. */
4289
+ private claimsCanRun(opts: Pick<TickOpts, 'acceptNewWork'>, paused: boolean): boolean {
4290
+ return opts.acceptNewWork !== false && !paused && this.claimGateOpen()
4291
+ }
4292
+
4293
+ /** Whether a ticket claim ranked above `level` can exist: in memory, over
4294
+ * builds the caller already read. Nothing outranks urgent. With the
4295
+ * source's priority capability any higher level can be on a ready ticket,
4296
+ * and normal tickets exist in every source, so low always may. Otherwise
4297
+ * only an open optimization node's attempts claim above normal, at the
4298
+ * node's level (`attemptClaimTiers`); this over-approximates a node with
4299
+ * no ready attempt by at most one deferral. */
4300
+ private higherClaimsPossible(level: BuildPriority, builds: readonly CapacityBuild[]): boolean {
4301
+ if (level === 'urgent') return false
4302
+ if (this.deps.tickets.priority || level === 'low') return true
4303
+ const rank = priorityRank(level)
4304
+ return builds.some(
4305
+ ({ state }) =>
4306
+ state.kind === 'node' &&
4307
+ state.status !== 'done' &&
4308
+ state.status !== 'aborted' &&
4309
+ state.optimization !== undefined &&
4310
+ state.optimization.stopped === undefined &&
4311
+ priorityRank(buildPriority(state)) < rank,
4147
4312
  )
4148
4313
  }
4149
4314
 
@@ -4155,39 +4320,38 @@ export class Dispatcher {
4155
4320
  return !(health && Date.parse(health.resetAt) > this.deps.clock().getTime())
4156
4321
  }
4157
4322
 
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
4323
+ /** Ticket claims by level the latest admission scan found waiting for a
4324
+ * slot. In memory: the journal view is refreshed each tick. */
4325
+ private claims(): ClaimDemand {
4326
+ return this.tickAcceptsNewWork ? claimDemand(this.store.repositoryFacts()) : {}
4162
4327
  }
4163
4328
 
4164
4329
  /** Pending operator start requests by tier; nothing while no claim can
4165
- * run. In memory, like `urgentClaims`. */
4166
- private startClaims(): Partial<Record<TicketStartPriority, number>> {
4330
+ * run. In memory, like `claims`. */
4331
+ private startClaims(): Partial<Record<StartTier, number>> {
4167
4332
  return this.claimGateOpen() ? startClaimDemand(this.store.repositoryFacts()) : {}
4168
4333
  }
4169
4334
 
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
4335
  /** 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. */
4336
+ * order"): for each level, urgent first, its parked work and then its
4337
+ * claims. `occupied` counts every other build holding a slot. A waiter
4338
+ * defers while claims can run, this tick's dispatch has not yet evaluated
4339
+ * them, and a higher-level claim can exist (`higherClaimsPossible`). */
4182
4340
  private slotAdmission(
4183
4341
  slug: string,
4184
- priority: TicketPriority,
4342
+ priority: BuildPriority,
4185
4343
  occupied: number,
4186
4344
  projection: DispatchCapacity,
4345
+ builds: readonly CapacityBuild[],
4187
4346
  ): 'admit' | 'wait' | 'defer' {
4347
+ if (this.admissionBarred('waiting', priority)) return 'wait'
4188
4348
  if (occupied + reservedAhead(projection, { slug, priority }) >= this.deps.config.capacity)
4189
4349
  return 'wait'
4190
- return priority === 'normal' && this.urgentBoundaryOpen() ? 'defer' : 'admit'
4350
+ const boundary =
4351
+ this.admissionBoundary &&
4352
+ this.claimsCanRun({ acceptNewWork: this.tickAcceptsNewWork }, this.tickPaused) &&
4353
+ this.higherClaimsPossible(priority, builds)
4354
+ return boundary ? 'defer' : 'admit'
4191
4355
  }
4192
4356
 
4193
4357
  /** Whether a leaf may reserve a runner now (SPEC §12 "What holds a slot").
@@ -4241,9 +4405,10 @@ export class Dispatcher {
4241
4405
  priority,
4242
4406
  dispatchCapacity(others, capacity, now).occupied,
4243
4407
  dispatchCapacity(builds, capacity, now, {
4244
- urgentClaims: this.urgentClaims(),
4408
+ claims: this.claims(),
4245
4409
  startRequests: this.startClaims(),
4246
4410
  }),
4411
+ builds,
4247
4412
  )
4248
4413
  if (outcome === 'admit') {
4249
4414
  const request = leafSlotRequest(self)
@@ -4270,11 +4435,11 @@ export class Dispatcher {
4270
4435
 
4271
4436
  /**
4272
4437
  * 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
4438
+ * has evaluated claims at every level. Each retry re-enters its generic path with
4274
4439
  * fresh state: a leaf through the lease sweep's per-build pass, a node
4275
4440
  * through node admission, a proposer through proposer admission. Without a
4276
4441
  * completed evaluation nothing launches: the waiters stay reserved in
4277
- * `slotWaiters` against normal claims and are decided again next tick.
4442
+ * `slotWaiters` against claims at their level and are decided again next tick.
4278
4443
  */
4279
4444
  private async admitDeferredParked(
4280
4445
  report: TickReport,
@@ -4288,7 +4453,10 @@ export class Dispatcher {
4288
4453
  this.lastForcedDeferralKey = undefined
4289
4454
  return
4290
4455
  }
4291
- if (!this.urgentEvaluated) return
4456
+ if (!this.claimsEvaluated) return
4457
+ // Tail stage: a spent invocation budget admits nothing and reads nothing;
4458
+ // the parked builds stay durable work for the next invocation.
4459
+ if (this.budgetSpent(opts)) return
4292
4460
  this.admissionBoundary = false
4293
4461
  for (const [slug, kind] of deferred) {
4294
4462
  if (this.outOfBudget(opts)) return
@@ -4311,7 +4479,12 @@ export class Dispatcher {
4311
4479
  }
4312
4480
  } catch (error) {
4313
4481
  rethrowAuthorityLapse(error)
4314
- if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4482
+ if (
4483
+ error instanceof ForgeRequestDeferred ||
4484
+ error instanceof MixedVersionDeferral ||
4485
+ isRecoveryDeferred(error)
4486
+ )
4487
+ continue
4315
4488
  if (error instanceof ForgeCooldown) throw error
4316
4489
  const message =
4317
4490
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -4496,7 +4669,7 @@ export class Dispatcher {
4496
4669
  )
4497
4670
  if (proposers.length === 0) return
4498
4671
  const projection = dispatchCapacity(builds, this.deps.config.capacity, now, {
4499
- urgentClaims: this.urgentClaims(),
4672
+ claims: this.claims(),
4500
4673
  startRequests: this.startClaims(),
4501
4674
  })
4502
4675
  let occupied = projection.occupied
@@ -4545,6 +4718,7 @@ export class Dispatcher {
4545
4718
  buildPriority(state),
4546
4719
  occupied,
4547
4720
  projection,
4721
+ builds,
4548
4722
  )
4549
4723
  if (outcome === 'defer') this.deferredAdmissions.set(record.slug, 'proposer')
4550
4724
  if (outcome !== 'admit') return
@@ -4921,9 +5095,10 @@ export class Dispatcher {
4921
5095
  now,
4922
5096
  ).occupied,
4923
5097
  dispatchCapacity(builds, capacity, now, {
4924
- urgentClaims: this.urgentClaims(),
5098
+ claims: this.claims(),
4925
5099
  startRequests: this.startClaims(),
4926
5100
  }),
5101
+ builds,
4927
5102
  )
4928
5103
  if (outcome === 'admit')
4929
5104
  return (await this.admitNodeNeed(slug, node.state, need)) ? 'admit' : 'wait'
@@ -7190,6 +7365,7 @@ export class Dispatcher {
7190
7365
  // publication's fate BEFORE the destructive reap. A guard failure is
7191
7366
  // recorded against the build — a stale workspace with an unrecorded
7192
7367
  // pending request is never reaped (the next tick retries).
7368
+ let step: WorkspaceRecoveryStep = 'fence'
7193
7369
  try {
7194
7370
  await preserveWorkspaceBeforeRelease({
7195
7371
  store: this.store,
@@ -7199,8 +7375,12 @@ export class Dispatcher {
7199
7375
  exec: this.deps.exec,
7200
7376
  reason,
7201
7377
  now: this.deps.clock(),
7378
+ onStep: (next) => {
7379
+ step = next
7380
+ },
7202
7381
  })
7203
7382
  events = (await readBuildFacts(this.store, slug)).value
7383
+ step = 'preserve'
7204
7384
  events = await settlePublicationFactsBeforeRelease(
7205
7385
  { store: this.store, settlePublication: this.settlePublication },
7206
7386
  slug,
@@ -7215,14 +7395,18 @@ export class Dispatcher {
7215
7395
  // A repository-wide forge cooldown or version deferral is not this
7216
7396
  // build's failure; the tick-level handlers own it.
7217
7397
  if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
7398
+ // The invocation deadline cut recovery short: nothing failed, so keep
7399
+ // the workspace and record nothing; the next invocation retries.
7400
+ if (isRecoveryDeferred(error)) return false
7218
7401
  // Any other preservation or settlement failure (an unknown fence, a
7219
7402
  // checkout that could not be inspected) retains the workspace and its
7220
7403
  // pending work and is attributed to this build, never to the tick.
7404
+ // The recorded error names the recovery step that failed.
7221
7405
  await this.recordInfrastructureFailure(slug, events, {
7222
7406
  provider: open.provider,
7223
7407
  workspaceRef: open.ref,
7224
7408
  operation: 'reconcile',
7225
- error,
7409
+ error: stepAttributed(step, error),
7226
7410
  cleanupPending: true,
7227
7411
  })
7228
7412
  return false
@@ -7258,8 +7442,12 @@ export class Dispatcher {
7258
7442
  return true
7259
7443
  } catch (error) {
7260
7444
  rethrowAuthorityLapse(error)
7445
+ // A cleanup the invocation deadline cut short is retried next time; it
7446
+ // is neither a cleanup attempt nor a failure.
7447
+ if (isRecoveryDeferred(error)) return false
7448
+ const failure = stepAttributed('cleanup', error)
7261
7449
  const message =
7262
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
7450
+ failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
7263
7451
  const _failed = await this.store.append(slug, {
7264
7452
  actor: DISPATCHER,
7265
7453
  type: 'infrastructure.cleanup-attempted',
@@ -7277,7 +7465,7 @@ export class Dispatcher {
7277
7465
  provider: open.provider,
7278
7466
  workspaceRef: open.ref,
7279
7467
  operation: 'reconcile',
7280
- error,
7468
+ error: failure,
7281
7469
  cleanupPending: true,
7282
7470
  })
7283
7471
  return false
@@ -7307,22 +7495,35 @@ export class Dispatcher {
7307
7495
  // pending publication BEFORE any provider cleanup call, while the
7308
7496
  // workspace still exists. The guard's append failure propagates — the
7309
7497
  // 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
- )
7498
+ if (reason === 'abort') {
7499
+ // Abort discards the build's work: preservation is best effort and the
7500
+ // pending publication is recorded lost without settling it, so a broken
7501
+ // workspace, guest or forge never holds the teardown hostage.
7502
+ await this.preserveBeforeAbortRelease(slug, owner)
7503
+ events = await recordPublicationLossBeforeRelease(
7504
+ { store: this.store },
7505
+ slug,
7506
+ (await readBuildFacts(this.store, slug)).value,
7507
+ reason,
7508
+ )
7509
+ } else {
7510
+ await preserveWorkspaceBeforeRelease({
7511
+ store: this.store,
7512
+ slug,
7513
+ owner,
7514
+ forge: this.deps.forge,
7515
+ exec: this.deps.exec,
7516
+ reason,
7517
+ now: this.deps.clock(),
7518
+ })
7519
+ events = (await readBuildFacts(this.store, slug)).value
7520
+ events = await settlePublicationFactsBeforeRelease(
7521
+ { store: this.store, settlePublication: this.settlePublication },
7522
+ slug,
7523
+ events,
7524
+ reason,
7525
+ )
7526
+ }
7326
7527
  const recovery = owner.recovery
7327
7528
  if (recovery !== undefined) {
7328
7529
  const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
@@ -7343,8 +7544,11 @@ export class Dispatcher {
7343
7544
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
7344
7545
  } catch (error) {
7345
7546
  rethrowAuthorityLapse(error)
7547
+ // Deferred to the next invocation: record nothing, keep the workspace.
7548
+ if (isRecoveryDeferred(error)) throw error
7549
+ const failure = stepAttributed('cleanup', error)
7346
7550
  const message =
7347
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
7551
+ failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
7348
7552
  const _failed = await this.store.append(slug, {
7349
7553
  actor: DISPATCHER,
7350
7554
  type: 'infrastructure.cleanup-attempted',
@@ -7362,7 +7566,7 @@ export class Dispatcher {
7362
7566
  provider: open.provider,
7363
7567
  workspaceRef: open.ref,
7364
7568
  operation: 'delete',
7365
- error,
7569
+ error: failure,
7366
7570
  cleanupPending: true,
7367
7571
  })
7368
7572
  throw error
@@ -7377,6 +7581,37 @@ export class Dispatcher {
7377
7581
  } satisfies EventWrite<'workspace.released'>)
7378
7582
  }
7379
7583
 
7584
+ /**
7585
+ * One best-effort preservation attempt ahead of an abort release. Only three
7586
+ * refusals stop the release: lost repository authority, a mixed-version
7587
+ * deferral, and a live execution lease. Every other failure records
7588
+ * `workspace.commits-lost` and returns so teardown continues.
7589
+ *
7590
+ * This is the one place a forge deferral (`ForgeRequestDeferred`, including
7591
+ * `ForgeCooldown`) does not propagate. The guarded forge has already refused
7592
+ * the archive and recorded the degradation, so no further forge call is made;
7593
+ * the archive is best effort under abort, and the release that follows is a
7594
+ * provider call, not a forge call. Do not route this catch through `fail()`
7595
+ * or a shared transient classifier: deferrals would gate teardown again.
7596
+ */
7597
+ private async preserveBeforeAbortRelease(slug: string, owner: WorkspaceProvider): Promise<void> {
7598
+ try {
7599
+ await preserveWorkspaceBeforeRelease({
7600
+ store: this.store,
7601
+ slug,
7602
+ owner,
7603
+ forge: this.deps.forge,
7604
+ exec: this.deps.exec,
7605
+ reason: 'abort',
7606
+ now: this.deps.clock(),
7607
+ })
7608
+ } catch (error) {
7609
+ rethrowAuthorityLapse(error)
7610
+ if (error instanceof MixedVersionDeferral || error instanceof WorkspaceLeaseLive) throw error
7611
+ await recordAbortPreservationFailure({ store: this.store, slug, error })
7612
+ }
7613
+ }
7614
+
7380
7615
  /** Only the authoritative forge may resolve a destination tip. */
7381
7616
  private async baseSha(baseBranch: string): Promise<string> {
7382
7617
  const read = this.deps.forge.remoteBranchSha
@@ -7439,6 +7674,7 @@ export class Dispatcher {
7439
7674
  target?: EventPayload<'build.created'>['target']
7440
7675
  baseBranch?: string
7441
7676
  priority?: 'urgent'
7677
+ level?: 'high' | 'low'
7442
7678
  }
7443
7679
  | undefined,
7444
7680
  ): EventPayload<'build.created'> {
@@ -7465,14 +7701,18 @@ export class Dispatcher {
7465
7701
  : {}),
7466
7702
  ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
7467
7703
  ...(seed?.priority !== undefined ? { priority: seed.priority } : {}),
7704
+ ...(seed?.level !== undefined ? { level: seed.level } : {}),
7468
7705
  }
7469
7706
  }
7470
7707
 
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
- : {}
7708
+ /** The level a claim freezes on `build.created`: a non-manual start
7709
+ * request's own level, otherwise the ticket's claim tier (`tierOf`). */
7710
+ private claimedLevel(
7711
+ ticket: Ticket,
7712
+ tier: StartTier,
7713
+ tierOf: (ticket: Ticket) => BuildPriority,
7714
+ ): BuildPriority {
7715
+ return tier === 'manual' ? tierOf(ticket) : tier
7476
7716
  }
7477
7717
 
7478
7718
  /** Every boundary before runner attachment is derived from durable facts.
@@ -7500,6 +7740,8 @@ export class Dispatcher {
7500
7740
  autoMergeUser?: string
7501
7741
  autoMergeDefaultSeq?: number
7502
7742
  assets?: PinnedAsset[]
7743
+ priority?: 'urgent'
7744
+ level?: 'high' | 'low'
7503
7745
  },
7504
7746
  ): Promise<DispatchOutcome> {
7505
7747
  if (!this.accountsAvailable()) return 'parked'
@@ -7542,7 +7784,6 @@ export class Dispatcher {
7542
7784
  ? { issueLinks: seed.ticket.issueLinks }
7543
7785
  : {}),
7544
7786
  ...(seed !== undefined ? this.selectedProfile(seed.ticket) : {}),
7545
- ...(seed !== undefined ? this.claimedPriority(seed.ticket) : {}),
7546
7787
  }),
7547
7788
  })
7548
7789
  events = (await readBuildFacts(store, record.slug)).value
@@ -7818,6 +8059,9 @@ export class Dispatcher {
7818
8059
  if (
7819
8060
  state.status !== 'queued' ||
7820
8061
  state.discardRequest !== undefined ||
8062
+ // A janitor that failed or ran out of budget before acknowledging
8063
+ // retries next tick; dispatch never provisions to acknowledge abort.
8064
+ dispatcherAcknowledgesAbort(state) ||
7821
8065
  heldByRepositoryPause(state, paused)
7822
8066
  ) {
7823
8067
  continue
@@ -7864,6 +8108,8 @@ export class Dispatcher {
7864
8108
  state.status === 'done' ||
7865
8109
  state.status === 'aborted' ||
7866
8110
  (state.status === 'queued' && state.discardRequest !== undefined) ||
8111
+ // The janitor acknowledges this abort; startup never launches for it.
8112
+ dispatcherAcknowledgesAbort(state) ||
7867
8113
  heldByRepositoryPause(state, paused)
7868
8114
  ) {
7869
8115
  continue
@@ -8034,7 +8280,7 @@ export class Dispatcher {
8034
8280
  /**
8035
8281
  * End open ticket waits whose tickets settled (SPEC §11 "Ticket waits").
8036
8282
  * Every waited ticket completed: `wait.ended {cause: automatic}`, and the
8037
- * build resumes ahead of normal claims. Any waited ticket rejected (the
8283
+ * build resumes ahead of claims at its level. Any waited ticket rejected (the
8038
8284
  * configured rejected role) or deleted: one `policy/wait-unresolvable`
8039
8285
  * escalation naming it, which the reducer reads as the wait's end. A wait
8040
8286
  * with tickets still pending stays in place.
@@ -8178,7 +8424,12 @@ export class Dispatcher {
8178
8424
  // Per-build containment: one build's failure never stops the sweep
8179
8425
  // from advancing the others. Workspace failures are already durable
8180
8426
  // against the build; a repository-wide cooldown still ends the tick.
8181
- if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
8427
+ if (
8428
+ error instanceof ForgeRequestDeferred ||
8429
+ error instanceof MixedVersionDeferral ||
8430
+ isRecoveryDeferred(error)
8431
+ )
8432
+ continue
8182
8433
  if (error instanceof ForgeCooldown) throw error
8183
8434
  const message =
8184
8435
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -8255,6 +8506,9 @@ export class Dispatcher {
8255
8506
  await deferMixedVersion(this.store, record.slug)
8256
8507
  return
8257
8508
  }
8509
+ // The janitor owns this abort: a sweep must never reap, provision or
8510
+ // launch a runner only to acknowledge it.
8511
+ if (dispatcherAcknowledgesAbort(state)) return
8258
8512
  if (
8259
8513
  (state.status === 'queued' && state.discardRequest !== undefined) ||
8260
8514
  heldByRepositoryPause(state, paused)
@@ -8723,7 +8977,7 @@ export class Dispatcher {
8723
8977
  if (!this.claimGateOpen()) return
8724
8978
  const store = this.store
8725
8979
  const { tickets, config } = this.deps
8726
- // A normal parked admission deferred this tick waits on urgent claims:
8980
+ // A parked admission deferred this tick waits on higher-level claims:
8727
8981
  // list now, once per deferral key; an unchanged key waits for a scan that
8728
8982
  // is due on its own.
8729
8983
  let force = false
@@ -8757,12 +9011,12 @@ export class Dispatcher {
8757
9011
  const capacityBuilds =
8758
9012
  targeted?.measured ?? deferralBuilds ?? (await this.capacityBuilds(launched))
8759
9013
  // 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
9014
+ // reserves its slot ahead of claims of its own or a lower level until it
9015
+ // is admitted; this only ever lowers the claim budgets. A claim waits
9016
+ // only for parked work at its level or above (SPEC §12 "Slot admission
9017
+ // order"). Open-PR backpressure gates new high, normal and low claims
9018
+ // only: admission, the janitor, reconciles, landings and urgent claims
9019
+ // are untouched, and capacity accounting is unchanged. Engagement is a durable repository
8766
9020
  // fact recorded only on transitions, so hysteresis survives restarts.
8767
9021
  const engagement = this.store.repositoryFacts().openPrBackpressure
8768
9022
  const engaged = engagement !== undefined
@@ -8772,9 +9026,13 @@ export class Dispatcher {
8772
9026
  engaged,
8773
9027
  )
8774
9028
  // Pending start requests reserve ahead of the ordinary claims they outrank.
9029
+ // Sampled with the requests themselves, so a start pass inside intake can
9030
+ // tell a reserved request from one filed since.
9031
+ const pendingStarts = this.store.repositoryFacts().ticketStarts.pending
9032
+ const startDemand = this.startClaims()
8775
9033
  const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
8776
9034
  openPrs: { policy: config.policy, engaged },
8777
- startRequests: this.startClaims(),
9035
+ startRequests: startDemand,
8778
9036
  })
8779
9037
  const transition = backpressureTransition(
8780
9038
  backpressure,
@@ -8785,25 +9043,60 @@ export class Dispatcher {
8785
9043
  await store.ensureRepo(this.deps.repo)
8786
9044
  await store.appendRepo(this.deps.repo, { actor: DISPATCHER, ...transition })
8787
9045
  }
8788
- const normalPaused = backpressure?.active === true
9046
+ const nonUrgentPaused = backpressure?.active === true
8789
9047
  const activeRefs: TicketRef[] = capacityBuilds
8790
9048
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
8791
9049
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
8792
9050
  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
9051
+ // Each level's claim budget; a claim spends every level's slot, and ready
9052
+ // tickets are visited highest level first.
9053
+ const budgets = Object.fromEntries(
9054
+ TICKET_PRIORITIES.map((level) => [level, intakeCapacity(projection, adjust, level)]),
9055
+ ) as Record<BuildPriority, number>
9056
+ const waiting = { urgent: 0, high: 0, normal: 0 }
9057
+ // A ready ticket with a pending non-manual start request is left to the
9058
+ // start pass of its tier, which claims requests oldest first ahead of
9059
+ // that level's ready tickets. In memory over the tick's repository facts.
9060
+ // The requests the budgets reserved for (`startClaims`).
9061
+ const reservedStarts = new Set(
9062
+ Object.keys(startDemand).length > 0 ? Object.values(pendingStarts).map(({ seq }) => seq) : [],
9063
+ )
9064
+ const requested = (ticket: Ticket): boolean => {
9065
+ const request = pendingStarts[ticketStartKey(ticket.ref)]
9066
+ return request !== undefined && startTierOf(request) !== 'manual'
9067
+ }
8796
9068
  // Each ready ticket's claim tier: an optimization attempt claims at its
8797
9069
  // node's current build priority, any other ticket at its own priority
8798
9070
  // 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 =>
9071
+ let attemptTiers = new Map<string, BuildPriority>()
9072
+ const tierOf = (ticket: Ticket): BuildPriority =>
8801
9073
  attemptTiers.get(ticket.ref.id) ?? (tickets.priority ? ticketPriority(ticket) : 'normal')
8802
- const urgentClaim = (ticket: Ticket) =>
8803
- !targeted && ticket.kind !== 'node' && tierOf(ticket) === 'urgent'
9074
+ // A saturated claim counts as demand reserving ahead of lower-level
9075
+ // parked work: always at urgent; at high or normal only while work of a
9076
+ // lower level waits (a parked waiter or a start request), so the extra
9077
+ // preflight runs only where it can matter; never at low.
9078
+ const lowerWaiting = (level: BuildPriority): boolean => {
9079
+ const rank = priorityRank(level)
9080
+ const below = (entry: { priority?: BuildPriority }) =>
9081
+ priorityRank(entry.priority ?? 'normal') > rank
9082
+ return (
9083
+ (projection.waitingNodes ?? []).some(below) ||
9084
+ (projection.waitingBuilds ?? []).some(below) ||
9085
+ [...this.slotWaiters.values()].some((priority) => below({ priority })) ||
9086
+ START_TIERS.slice(START_TIERS.indexOf(level) + 1).some(
9087
+ (tier) => (projection.startRequests?.[tier] ?? 0) > 0,
9088
+ )
9089
+ )
9090
+ }
9091
+ const countsDemand = (level: BuildPriority): level is keyof typeof waiting =>
9092
+ level === 'urgent' || (level !== 'low' && lowerWaiting(level))
9093
+ const demandClaim = (ticket: Ticket) =>
9094
+ !targeted && ticket.kind !== 'node' && countsDemand(tierOf(ticket))
8804
9095
  // 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'
9096
+ const startTier = (ticket: Ticket): StartTier => {
9097
+ const request = targeted?.requests.get(ticket.ref.id)
9098
+ return request === undefined ? 'manual' : startTierOf(request)
9099
+ }
8807
9100
 
8808
9101
  // The ready scan runs even at full capacity: `queued` is the operator's
8809
9102
  // standing queue-depth report and must stay honest exactly when the
@@ -8836,8 +9129,9 @@ export class Dispatcher {
8836
9129
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
8837
9130
  !this.preparing(ticket.ref.source, ticket.ref.id),
8838
9131
  )
8839
- // Urgent first, each class in source order (stable). Every gate below is
8840
- // unchanged; a source without the priority capability is all normal.
9132
+ // By level, urgent first, each level in source order (stable). Every gate
9133
+ // below is unchanged; a source without the priority capability is all
9134
+ // normal.
8841
9135
  // A ticket whose labels select two profiles is never claimed (SPEC §9).
8842
9136
  const conflicts = this.profileConflicts(eligible)
8843
9137
  // Conflicts and their diagnostics are produced in the same order.
@@ -8846,12 +9140,18 @@ export class Dispatcher {
8846
9140
  const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
8847
9141
  if (!targeted) attemptTiers = await this.attemptClaimTiers(claimable)
8848
9142
  // A targeted pass keeps its tier-then-request order.
8849
- const ready = targeted ? claimable : urgentFirstBy(claimable, tierOf)
9143
+ const toStarts = targeted ? [] : claimable.filter(requested)
9144
+ const ready = targeted
9145
+ ? claimable
9146
+ : byPriorityBy(
9147
+ claimable.filter((ticket) => !requested(ticket)),
9148
+ tierOf,
9149
+ )
8850
9150
  report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
8851
9151
  report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
8852
- if (!targeted && normalPaused)
9152
+ if (!targeted && nonUrgentPaused)
8853
9153
  report.ticketDiagnostics.push(backpressureExplanation(backpressure))
8854
- report.queued = ready.length
9154
+ report.queued = ready.length + toStarts.length
8855
9155
  const withheld = new Set<string>()
8856
9156
  for (const ticket of ready) {
8857
9157
  if (ticket.creationKey === undefined) continue
@@ -8886,21 +9186,22 @@ export class Dispatcher {
8886
9186
  // still runs either way, so the standing queue-depth report stays honest —
8887
9187
  // this only declines to claim a ticket into a build that would immediately
8888
9188
  // 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))
9189
+ // Saturated, a demand-counting ticket still runs the preflight: it claims
9190
+ // its level's budget, or counts as demand waiting for a slot.
9191
+ const demandReady = ready.some((ticket) => demandClaim(ticket) && !withheld.has(ticket.ref.id))
8892
9192
  const noBudget = targeted
8893
9193
  ? ready.every((ticket) => targeted.budgets[startTier(ticket)] <= 0)
8894
- : capacity <= 0 && !urgentReady
9194
+ : !demandReady &&
9195
+ ready.every((ticket) => withheld.has(ticket.ref.id) || budgets[tierOf(ticket)] <= 0)
8895
9196
  if (
8896
9197
  paused ||
8897
9198
  (!targeted &&
8898
- normalPaused &&
9199
+ nonUrgentPaused &&
8899
9200
  !ready.some((ticket) => tierOf(ticket) === 'urgent' && !withheld.has(ticket.ref.id))) ||
8900
9201
  (noBudget &&
8901
9202
  !ready.some(
8902
9203
  (ticket) =>
8903
- (targeted || !normalPaused || tierOf(ticket) === 'urgent') &&
9204
+ (targeted || !nonUrgentPaused || tierOf(ticket) === 'urgent') &&
8904
9205
  (ticket.kind === 'node' ||
8905
9206
  (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0)),
8906
9207
  ))
@@ -8909,8 +9210,9 @@ export class Dispatcher {
8909
9210
  await this.sourceCondition(undefined, 'ready-scan')
8910
9211
  if (!this.outOfBudget(opts)) {
8911
9212
  await this.completeScan(checkpoint, report)
8912
- // No urgent ticket is ready: this scan decided urgent claims.
8913
- if (!paused) this.urgentEvaluated = true
9213
+ // No ticket can claim or count as demand: this scan decided claims
9214
+ // at every level.
9215
+ if (!paused) this.claimsEvaluated = true
8914
9216
  }
8915
9217
  return
8916
9218
  }
@@ -9109,21 +9411,59 @@ export class Dispatcher {
9109
9411
  claimLoopCompleted = false
9110
9412
  break
9111
9413
  }
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
9414
+ const level = tierOf(ticket)
9415
+ // Before this level's first ready ticket, its own and every higher late
9416
+ // start tier claims its pending requests (SPEC §12 "Slot admission
9417
+ // order"). A request it settles without starting frees its reservation.
9418
+ const startTiers = targeted
9419
+ ? []
9420
+ : LATE_START_TIERS.filter(
9421
+ (tier) =>
9422
+ !this.lateStartTiersHonored.has(tier) &&
9423
+ priorityRank(tier as BuildPriority) <= priorityRank(level),
9424
+ )
9425
+ if (startTiers.length > 0) {
9426
+ const pass = await this.honorStartRequests(
9427
+ report,
9428
+ launched,
9429
+ autoMergeUser,
9430
+ paused,
9431
+ opts,
9432
+ startTiers,
9433
+ )
9434
+ const listed = new Set(toStarts.map(({ ref }) => `${ref.source}:${ref.id}`))
9435
+ for (const decision of pass.settled) {
9436
+ if (decision.started && listed.has(decision.ticket)) report.queued -= 1
9437
+ // A reserved request frees its reservation, which a start then
9438
+ // occupies; one the budgets never reserved occupies a slot of every
9439
+ // level when it starts.
9440
+ const reserved = reservedStarts.has(decision.seq)
9441
+ for (const entry of TICKET_PRIORITIES) {
9442
+ const covered = priorityRank(entry) >= priorityRank(decision.tier as BuildPriority)
9443
+ if (reserved && covered && !decision.started) budgets[entry] += 1
9444
+ if (!reserved && decision.started) budgets[entry] -= 1
9445
+ }
9446
+ }
9447
+ if (this.outOfBudget(opts)) {
9448
+ claimLoopCompleted = false
9449
+ break
9450
+ }
9451
+ }
9452
+ if (!targeted && nonUrgentPaused && tierOf(ticket) !== 'urgent') continue
9453
+ // Start requests this tick cannot read stay ahead of ready tickets at
9454
+ // their tier and below until a later scan. A node ticket's claim takes
9455
+ // no slot.
9456
+ if (!targeted && ticket.kind !== 'node' && this.admissionBarred('claim', level)) continue
9457
+ const demand = demandClaim(ticket)
9458
+ const budget = targeted ? targeted.budgets[startTier(ticket)] : budgets[level]
9459
+ if (ticket.kind !== 'node' && budget <= 0 && !demand) continue
9120
9460
  if (withheld.has(ticket.ref.id)) continue
9121
9461
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
9122
9462
  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.
9463
+ // A ticket that passed every gate but capacity is demand that
9464
+ // lower-level parked work yields to until the next admission scan.
9125
9465
  if (ticket.kind !== 'node' && budget <= 0) {
9126
- urgentWaiting += 1
9466
+ if (countsDemand(level)) waiting[level] += 1
9127
9467
  continue
9128
9468
  }
9129
9469
 
@@ -9317,12 +9657,9 @@ export class Dispatcher {
9317
9657
  ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
9318
9658
  // Fixed at claim from the same sample: relabelling never changes it.
9319
9659
  ...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
- : {}),
9660
+ // `manual` is admission-only: a build started by any other request
9661
+ // takes the request's level, every other build its ticket's.
9662
+ ...createdPriorityFields(this.claimedLevel(ticket, startTier(ticket), tierOf)),
9326
9663
  }
9327
9664
  // `build.created` rides with the record so the pinned assets and the
9328
9665
  // record exist together or not at all.
@@ -9396,10 +9733,7 @@ export class Dispatcher {
9396
9733
  }
9397
9734
  report.queued -= 1
9398
9735
  if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
9399
- else if (ticket.kind !== 'node') {
9400
- capacity -= 1
9401
- urgentCapacity -= 1
9402
- }
9736
+ else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
9403
9737
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
9404
9738
  ticket,
9405
9739
  body,
@@ -9411,9 +9745,9 @@ export class Dispatcher {
9411
9745
  if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
9412
9746
  }
9413
9747
  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
9748
+ await this.completeScan(checkpoint, report, waiting)
9749
+ // The only other place this tick authorizes deferred admissions.
9750
+ if (claimLoopCompleted) this.claimsEvaluated = true
9417
9751
  }
9418
9752
  }
9419
9753
 
@@ -9462,10 +9796,8 @@ export class Dispatcher {
9462
9796
  * other tickets keep their own tier. Costs one served node state per open,
9463
9797
  * unstopped optimization node a ready ticket targets, and none otherwise.
9464
9798
  */
9465
- private async attemptClaimTiers(
9466
- tickets: readonly Ticket[],
9467
- ): Promise<Map<string, TicketPriority>> {
9468
- const tiers = new Map<string, TicketPriority>()
9799
+ private async attemptClaimTiers(tickets: readonly Ticket[]): Promise<Map<string, BuildPriority>> {
9800
+ const tiers = new Map<string, BuildPriority>()
9469
9801
  const candidates = tickets.filter(
9470
9802
  (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
9471
9803
  )