@defrex/autobuild 1.11.1 → 1.12.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 (102) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +177 -54
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +66 -6
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +13 -11
  7. package/docs/dispatcher.md +1 -1
  8. package/docs/integration-tree.md +28 -16
  9. package/docs/operator-api.md +4 -4
  10. package/docs/operator-surfaces.md +35 -0
  11. package/docs/optimization-nodes.md +3 -2
  12. package/docs/tickets.md +1 -1
  13. package/docs/troubleshooting.md +1 -1
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/ambient-errors.ts +17 -0
  16. package/packages/core/src/cli/bounded-io.ts +174 -0
  17. package/packages/core/src/cli/dashboard/model.ts +81 -23
  18. package/packages/core/src/cli/dashboard/poll.ts +20 -31
  19. package/packages/core/src/cli/dashboard/render.ts +14 -37
  20. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  21. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  22. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  23. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  24. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  25. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  26. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  27. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  28. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  29. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  30. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  31. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  32. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  33. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  34. package/packages/core/src/cli/dispatch.ts +68 -5
  35. package/packages/core/src/cli/env.ts +2 -15
  36. package/packages/core/src/cli/help.ts +5 -4
  37. package/packages/core/src/cli/main.ts +4 -2
  38. package/packages/core/src/cli/production-store.ts +102 -0
  39. package/packages/core/src/cli/repo-state.ts +2 -3
  40. package/packages/core/src/cli/repository-status.ts +28 -22
  41. package/packages/core/src/cli/sessionless-store.ts +26 -0
  42. package/packages/core/src/cli/status.ts +169 -40
  43. package/packages/core/src/cli/store-opening.ts +15 -58
  44. package/packages/core/src/cli/store-ref.ts +6 -1
  45. package/packages/core/src/config/schema.ts +1 -1
  46. package/packages/core/src/distribution-packaging.ts +156 -18
  47. package/packages/core/src/events/catalog-identity.ts +28 -0
  48. package/packages/core/src/events/catalog.ts +3 -9
  49. package/packages/core/src/events/compatibility.ts +2 -30
  50. package/packages/core/src/events/payloads.ts +11 -0
  51. package/packages/core/src/events/policy.ts +3 -0
  52. package/packages/core/src/events/repository.ts +1 -1
  53. package/packages/core/src/events/sessions.ts +1 -1
  54. package/packages/core/src/events/validation-error.ts +12 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +9 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  59. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  60. package/packages/core/src/kernel/capacity-build.ts +21 -0
  61. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  63. package/packages/core/src/kernel/engine.ts +2 -8
  64. package/packages/core/src/kernel/measurement.ts +24 -0
  65. package/packages/core/src/kernel/read-facts.ts +8 -370
  66. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  67. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  68. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  69. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  70. package/packages/core/src/kernel/reducer.ts +57 -9
  71. package/packages/core/src/kernel/reopen-state.ts +10 -0
  72. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  73. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  74. package/packages/core/src/operator/presentation.ts +13 -0
  75. package/packages/core/src/operator/query.ts +40 -39
  76. package/packages/core/src/operator/registry.ts +3 -3
  77. package/packages/core/src/ports/workspace/fake.ts +15 -3
  78. package/packages/core/src/processes/dispatcher.ts +232 -75
  79. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  80. package/packages/core/src/store/local/capabilities.ts +115 -0
  81. package/packages/core/src/store/local/store.ts +86 -56
  82. package/packages/core/src/store/reduced-reads.ts +9 -1
  83. package/packages/core/src/store/reducer-value-read.ts +235 -0
  84. package/packages/core/src/store/reducer-value-shapes.json +1437 -1349
  85. package/packages/core/src/store/reducer-values.ts +36 -204
  86. package/packages/core/src/store/remote/released-clients.json +11 -0
  87. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  88. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  89. package/packages/core/src/store/rollup-lease.ts +41 -0
  90. package/packages/core/src/store/rollups.ts +7 -38
  91. package/packages/core/src/store/snapshots.ts +1 -1
  92. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  93. package/packages/core/src/testing/import-graph.ts +78 -0
  94. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  95. package/packages/core/src/testing/slot-agreement.ts +52 -0
  96. package/packages/core/src/web/assets/app.js +5 -5
  97. package/skills/guide/SKILL.md +115 -44
  98. package/skills/guide/references/integration-tree.md +28 -16
  99. package/skills/guide/references/operator-api.md +4 -4
  100. package/skills/guide/references/optimization-nodes.md +3 -2
  101. package/skills/operate/SKILL.md +38 -20
  102. package/templates/hosted-service/package.json +2 -2
@@ -1,13 +1,18 @@
1
1
  import type { TicketStartPriority } from '../events/repository'
2
- import type { TicketRef } from '../ontology'
3
2
  import type { TicketPriority } from '../ports/types'
4
3
  import type { BuildRecord } from '../store/types'
5
4
  import type { BuildState } from './reducer'
6
5
  import { integrationAdmissible, integrationNeedsRunner } from './integration-state'
7
6
  import { proposeAdmissible, proposeRunDue, proposeStarted } from './optimization-admission'
8
7
  import { waitParked, waitResumeDue } from './ticket-wait'
9
- import { nodeMeasurementDue, pendingMeasurementRequest } from './measurement'
10
- import { reopenRestart, reopenSpecPending, reopenUnsettled } from './reopen-state'
8
+ import { nodeMeasurementDue, nodeMeasurementNeed, pendingMeasurementRequest } from './measurement'
9
+ import { escalationCarried, type EscalationCarryInput } from './verify-stage-state'
10
+ import {
11
+ reopenRestart,
12
+ reopenSpecPending,
13
+ reopenUnsettled,
14
+ reviseSpecPending,
15
+ } from './reopen-state'
11
16
  import type { PolicyConfig } from '../config/schema'
12
17
  import {
13
18
  backpressureExplanation,
@@ -16,52 +21,79 @@ import {
16
21
  type OpenPrBackpressure,
17
22
  } from './open-pr-backpressure'
18
23
 
19
- /** Repository-scoped, reduced facts. Provisioning reserves a slot before a workspace exists.
24
+ /** Repository-scoped, reduced facts (SPEC §12 "What holds a slot").
20
25
  *
21
- * `capacity` counts builds running work. A leaf that holds no runner is
22
- * parked when it has finished its pipeline (settled, see `epilogueLeaf`) and
23
- * waits for a merge decision, merge gates or the forge, or when it waits on
24
- * other tickets (`waitParked`). A parked leaf holds no slot, though it keeps
25
- * its workspace. Every other unfinished leaf holds a slot, paused or blocked
26
- * on a question included. A reopened leaf (SPEC §15.7) stays a finished leaf,
27
- * so it re-enters through the same slot queue and, like a blocked reconcile,
28
- * holds no slot while it waits on a question. Nodes hold a slot only while
29
- * they need a runner. */
26
+ * A leaf takes a slot only by admission: its `build.created` (a ticket claim
27
+ * or start request) or the dispatcher's `slot.admitted`. It holds the slot
28
+ * while Autobuild owes its next move, whether or not a runner works, and
29
+ * releases it as soon as it waits on the outside world (`leafOutsideWait`): a
30
+ * human (an open escalation, an acknowledged pause, a `revise-spec` answer
31
+ * awaiting its revision, a merge decision or hold), another ticket, or the
32
+ * forge. An open escalation that work Autobuild started still outruns (a
33
+ * verify stage's other members, a recorded launch or its execution:
34
+ * `escalationCarried`) does not release it, and its answer releases nothing.
35
+ * Release follows state; acquisition never does, so a leaf whose outside
36
+ * wait ended asks for a slot (`slotRequest`) and holds none until it is
37
+ * admitted again. Runner liveness plays no part in a leaf's hold (only launch
38
+ * records and execution facts do), and its workspace never counts. A node
39
+ * holds a slot only once the dispatcher admitted it for a runner need it still has (`nodeHoldsSlot`); a workspace,
40
+ * a lease or a provisioning marker never takes one. */
30
41
  export interface CapacityBuild {
31
42
  record: BuildRecord
32
43
  state: BuildState
33
44
  workspace: boolean
34
45
  provisioning?: boolean
46
+ /** seq of the open provisioning marker's `workspace.provision-started`;
47
+ * omitted when `provisioning` is, or unknown. Anchors a runner launched
48
+ * before node admissions were recorded (`legacyNodeRunner`). */
49
+ provisioningSeq?: number
35
50
  /** The engine's awaiting-landing restack is due (`landingRestackDue`); omitted means false. */
36
51
  restackDue?: boolean
37
52
  }
38
53
 
39
- /** The runner a node or parked leaf has durably requested and does not yet
40
- * hold. `resume` is a leaf whose ticket wait ended; `reopen` is a leaf an
54
+ /** The slot a node or a leaf that holds none has durably requested. `resume`
55
+ * is a leaf whose escalation was answered, whose pause was resumed, whose
56
+ * ticket wait ended or whose target was rewritten; `reopen` is a leaf an
41
57
  * operator reopened; `propose` is an optimization node's open, still
42
- * eligible proposal request. */
58
+ * eligible proposal request. A node requests `verification`, `reconcile` or
59
+ * `propose` for runner work it has not been admitted for. */
43
60
  export type SlotRequest = 'verification' | 'reconcile' | 'resume' | 'reopen' | 'propose'
44
61
 
45
- /** One node or parked leaf waiting for a slot. `priority` is omitted for
46
- * normal builds, and by an older server. */
62
+ /** One node or leaf waiting for a slot. `priority` is omitted for normal
63
+ * builds, and by an older server. */
47
64
  export interface SlotWaiter {
48
65
  slug: string
49
66
  request: SlotRequest
50
67
  priority?: 'urgent'
51
68
  }
52
69
 
70
+ /** One build's slot state (SPEC §12 "What holds a slot"), by the rules
71
+ * admission counts: `held` exactly when `occupiesCapacity`, otherwise
72
+ * `requested` exactly when `slotRequest` names one (`priority` as the
73
+ * build's `SlotWaiter` carries it), otherwise `none`. */
74
+ export type SlotState =
75
+ | { state: 'held' }
76
+ | { state: 'requested'; request: SlotRequest; priority?: 'urgent' }
77
+ | { state: 'none' }
78
+
53
79
  /** Slot admission order for free slots (SPEC §12, "Slot admission order"):
54
80
  * manual start requests, urgent parked work, urgent ticket claims (urgent
55
81
  * start requests first), normal parked work, normal ticket claims (normal
56
82
  * start requests first); each tier keeps its own order. */
57
83
  export interface DispatchCapacity {
58
84
  configured: number
85
+ /** Builds holding a slot; never above `configured` once admitted by the
86
+ * slot arithmetic. */
59
87
  occupied: number
88
+ /** @deprecated Always `configured`. Kept for clients in the version window,
89
+ * which read it as the effective capacity. */
60
90
  effective: number
91
+ /** @deprecated Always empty. Kept for clients in the version window, which
92
+ * read it as the nodes borrowing descendant-held slots. */
61
93
  borrowingNodes: string[]
62
94
  /** Nodes waiting for a slot; omitted when none wait, and by an older server. */
63
95
  waitingNodes?: SlotWaiter[]
64
- /** Parked leaves waiting for a slot; omitted when none wait, and by an older server. */
96
+ /** Leaves waiting for a slot; omitted when none wait, and by an older server. */
65
97
  waitingBuilds?: SlotWaiter[]
66
98
  /** Urgent ticket claims the latest admission scan found waiting for a slot
67
99
  * (`urgentClaimDemand`); they go ahead of normal parked work. Omitted when
@@ -73,6 +105,10 @@ export interface DispatchCapacity {
73
105
  * reserves a slot ahead of the lower tiers. Omitted when none, by an older
74
106
  * server, and when the caller has no repository facts. */
75
107
  startRequests?: Partial<Record<TicketStartPriority, number>>
108
+ /** Each projected build's `slotState` by slug; empty when no build's is
109
+ * known. Omitted by an older server. A missing entry, or a missing map,
110
+ * is unknown, never `none`. */
111
+ slots?: Record<string, SlotState>
76
112
  }
77
113
 
78
114
  /** A build's slot-admission priority; absent (historical builds, sources
@@ -119,7 +155,7 @@ function startsOf(capacity: DispatchCapacity, tiers: readonly TicketStartPriorit
119
155
  return tiers.reduce((sum, tier) => sum + (capacity.startRequests?.[tier] ?? 0), 0)
120
156
  }
121
157
 
122
- /** A provisioning marker or continuation, or a live lease: a runner is working. */
158
+ /** A node's provisioning marker or continuation, or a live lease: a runner is working. */
123
159
  function runnerAllocated(build: CapacityBuild, now: Date): boolean {
124
160
  return (
125
161
  !!build.provisioning ||
@@ -127,11 +163,6 @@ function runnerAllocated(build: CapacityBuild, now: Date): boolean {
127
163
  )
128
164
  }
129
165
 
130
- /** A workspace, a provisioning marker or a live lease holds runner capacity. */
131
- function allocated(build: CapacityBuild, now: Date): boolean {
132
- return build.workspace || runnerAllocated(build, now)
133
- }
134
-
135
166
  /** The position the dispatcher records as settled: the later of the current
136
167
  * verify cycle's start and the latest finalize completion. A reconcile,
137
168
  * restack or config supersession opens a new cycle and so a new key. */
@@ -164,13 +195,98 @@ function executionOpen(state: BuildState): boolean {
164
195
  return state.openExecution?.commandId !== undefined
165
196
  }
166
197
 
167
- /** A finished or ticket-waiting leaf with no runner working. It holds no
168
- * slot; its workspace does not count. */
169
- export function parkedLeaf(build: CapacityBuild, now: Date): boolean {
198
+ /** What a leaf's slot depends on: its reduced state and whether the engine's
199
+ * awaiting-landing restack is due. */
200
+ export type LeafSlotFacts = Pick<CapacityBuild, 'state' | 'restackDue'>
201
+
202
+ /** The build was admitted since its last release (SPEC §12 "What holds a
203
+ * slot"). A value from an older server carries neither seq and reads as
204
+ * admitted. */
205
+ export function slotAdmitted(
206
+ state: Pick<BuildState, 'slotAdmittedSeq' | 'slotReleasedSeq'>,
207
+ ): boolean {
208
+ return state.slotAdmittedSeq === undefined || state.slotAdmittedSeq > (state.slotReleasedSeq ?? 0)
209
+ }
210
+
211
+ /** A finished leaf still owes work before it waits for its merge decision:
212
+ * a rewritten target, a conflicted PR, a reopen (its spec publication
213
+ * included), a restack, an unsettled verify cycle or finalize, a pending
214
+ * measurement request, or an open session to recover or close. */
215
+ function epilogueWorkDue(build: LeafSlotFacts): boolean {
216
+ const { state } = build
170
217
  return (
171
- (epilogueLeaf(build.state) || waitParked(build.state)) &&
172
- !runnerAllocated(build, now) &&
173
- !executionOpen(build.state)
218
+ state.sessions.open.length > 0 ||
219
+ state.targetRewrite !== undefined ||
220
+ state.prState === 'conflicted' ||
221
+ reopenSpecPending(state) ||
222
+ reopenUnsettled(state) ||
223
+ !!build.restackDue ||
224
+ epilogueUnsettled(state) ||
225
+ pendingMeasurementRequest(state) !== undefined
226
+ )
227
+ }
228
+
229
+ /** A leaf waiting on the outside world, which holds no slot: an open
230
+ * escalation (an entered ticket wait's included), an acknowledged pause no
231
+ * resume was requested for, a `revise-spec` answer awaiting its revision, or
232
+ * a finished pipeline with no epilogue work due (a merge decision or hold,
233
+ * merge gates or the forge). */
234
+ export function leafOutsideWait(build: LeafSlotFacts): boolean {
235
+ const { state } = build
236
+ if (humanWait(state, state.status)) return true
237
+ if (reviseSpecPending(state)) return true
238
+ return epilogueLeaf(state) && !epilogueWorkDue(build)
239
+ }
240
+
241
+ /** Blocked on a question, or paused with no resume requested (or with an
242
+ * open escalation): the build waits on a human. */
243
+ function humanWait(state: BuildState, status: BuildState['status']): boolean {
244
+ if (status === 'blocked') return true
245
+ return (
246
+ status === 'paused' &&
247
+ (state.openEscalations.length > 0 ||
248
+ !state.pendingCommands.some((command) => command.command === 'resume'))
249
+ )
250
+ }
251
+
252
+ /** The carry input of a leaf's reduced state (`escalationCarried`). */
253
+ export function escalationCarryInput(state: BuildState): EscalationCarryInput {
254
+ return {
255
+ openEscalations: state.openEscalations,
256
+ verifyStage: state.verifyStage,
257
+ verifyCycle: state.verify.cycleSince,
258
+ maxAttemptSeen: state.verify.maxAttemptSeen,
259
+ executions: state.executions,
260
+ liveExecution: state.openExecution,
261
+ slotAdmittedSeq: state.slotAdmittedSeq,
262
+ failures: [state.dispatchFailures, state.infrastructureFailures, state.setupFailures],
263
+ }
264
+ }
265
+
266
+ /** A leaf whose only outside wait is its open escalations: blocked, with no
267
+ * `revise-spec` answer awaiting its revision and no finished pipeline
268
+ * waiting for its merge decision. */
269
+ function blockedOnlyByEscalations(build: LeafSlotFacts): boolean {
270
+ const { state } = build
271
+ return (
272
+ state.status === 'blocked' &&
273
+ state.openEscalations.length > 0 &&
274
+ !reviseSpecPending(state) &&
275
+ !(epilogueLeaf(state) && !epilogueWorkDue(build))
276
+ )
277
+ }
278
+
279
+ /** A nonterminal leaf holds a slot when it was admitted since its last
280
+ * release and either does not wait on the outside world or waits only on
281
+ * escalations that work Autobuild started still outruns (`escalationCarried`).
282
+ * No lease or provisioning marker enters: a runner left over from before a
283
+ * release never takes the slot back. */
284
+ export function leafHoldsSlot(build: LeafSlotFacts): boolean {
285
+ return (
286
+ !terminal(build.state) &&
287
+ slotAdmitted(build.state) &&
288
+ (!leafOutsideWait(build) ||
289
+ (blockedOnlyByEscalations(build) && escalationCarried(escalationCarryInput(build.state))))
174
290
  )
175
291
  }
176
292
 
@@ -221,33 +337,153 @@ export function settlementDue(state: BuildState): boolean {
221
337
  )
222
338
  }
223
339
 
340
+ /** One runner need of a node and the slot request that admits it. The key
341
+ * names the work, not when a tick saw it, so it stays the same from admission
342
+ * until that work is done (SPEC §12 "What holds a slot"). */
343
+ export interface NodeSlotNeed {
344
+ request: 'verification' | 'reconcile' | 'propose'
345
+ key: string
346
+ }
347
+
348
+ function reconcileNeed(state: BuildState): NodeSlotNeed | undefined {
349
+ const restack = state.nodeRestack
350
+ const id = restack?.active?.id ?? restack?.conflict?.id
351
+ return id === undefined ? undefined : { request: 'reconcile', key: `reconcile:${id}` }
352
+ }
353
+
354
+ function proposeNeed(state: BuildState): NodeSlotNeed | undefined {
355
+ const proposal = state.optimization?.proposal
356
+ return proposal === undefined ? undefined : { request: 'propose', key: `propose:${proposal.id}` }
357
+ }
358
+
359
+ function measurementNeed(state: BuildState): NodeSlotNeed | undefined {
360
+ const key = nodeMeasurementNeed(state)
361
+ return key === undefined ? undefined : { request: 'verification', key }
362
+ }
363
+
364
+ function integrationNeed(state: BuildState): NodeSlotNeed | undefined {
365
+ const cycle = state.integration?.cycle
366
+ return cycle === undefined
367
+ ? undefined
368
+ : { request: 'verification', key: `integration:${cycle.id}:${cycle.seq}` }
369
+ }
370
+
371
+ /** Every runner need a node has now, reconcile first: an active restack (held
372
+ * across the kernel's replay of the items between conflicts, so the slot it
373
+ * was admitted for is not dropped and retaken without admission), a starting
374
+ * or progress measurement, an undeposited proposal, and an integration cycle
375
+ * that needs a runner. Pure over reduced state, with no clock. Completing the
376
+ * work removes its key, which releases a slot admitted for it with no write. */
377
+ export function nodeRunnerNeeds(state: BuildState): NodeSlotNeed[] {
378
+ if (state.kind !== 'node' || terminal(state)) return []
379
+ const needs: NodeSlotNeed[] = []
380
+ const reconcile = reconcileNeed(state)
381
+ if (reconcile) needs.push(reconcile)
382
+ const measurement = measurementNeed(state)
383
+ if (measurement) needs.push(measurement)
384
+ if (proposeRunDue(state.optimization)) needs.push(proposeNeed(state)!)
385
+ if (integrationNeedsRunner(state)) needs.push(integrationNeed(state)!)
386
+ return needs
387
+ }
388
+
389
+ /** A node waiting on the outside world, which holds no slot: blocked on a
390
+ * question (a restack conflict's escalation included) or paused with no
391
+ * resume requested. The janitor's own escalation is not an outside wait: the
392
+ * dispatcher keeps retrying the work it blocks, so Autobuild still owes the
393
+ * next move. */
394
+ export function nodeOutsideWait(state: BuildState): boolean {
395
+ return humanWait(state, state.statusWithoutJanitorEscalation ?? state.status)
396
+ }
397
+
398
+ /** A nonterminal node holds a slot when it does not wait on the outside world,
399
+ * was admitted since its last release, and the runner need that admission
400
+ * named is still one it has (SPEC §12 "What holds a slot"). A workspace, a
401
+ * lease or a provisioning marker never enters; finished work releases the
402
+ * slot by dropping its need. A value from an older server, which carries no
403
+ * slot seqs, falls back to the version-window rule: a runner need with a
404
+ * provisioning marker or live lease. */
405
+ export function nodeHoldsSlot(build: CapacityBuild, now: Date): boolean {
406
+ const { state } = build
407
+ if (state.kind !== 'node' || terminal(state) || nodeOutsideWait(state)) return false
408
+ const needs = nodeRunnerNeeds(state)
409
+ if (state.slotAdmittedSeq === undefined) return needs.length > 0 && runnerAllocated(build, now)
410
+ const need = state.slotAdmittedNeed
411
+ return slotAdmitted(state) && need !== undefined && needs.some((entry) => entry.key === need)
412
+ }
413
+
414
+ /** The version transition (SPEC §15 `slot.admitted`): a runner an older
415
+ * dispatcher launched before node admissions were recorded, which that
416
+ * dispatcher counted as holding a slot. The node was never admitted under
417
+ * this model, does not wait on the outside world, has a runner need (a
418
+ * reconcile only with its conflict open, as the older rule held) and runner
419
+ * evidence later than its last release: an open execution or provisioning
420
+ * marker, or, with neither and no release ever recorded, a live lease. With
421
+ * a pause or abort pending, only a runner anchored before the earliest one
422
+ * counts; one started after it only acknowledges. The dispatcher records its
423
+ * admission once (`legacyNodeRunnerNeed`), after which `slotAdmittedNeed` is
424
+ * set and this never matches the node again. */
425
+ export function legacyNodeRunner(build: CapacityBuild, now: Date): boolean {
426
+ return legacyNodeRunnerNeed(build, now) !== undefined
427
+ }
428
+
429
+ /** The need a legacy node runner (`legacyNodeRunner`) is adopted for. */
430
+ export function legacyNodeRunnerNeed(build: CapacityBuild, now: Date): NodeSlotNeed | undefined {
431
+ const { state } = build
432
+ if (
433
+ state.kind !== 'node' ||
434
+ terminal(state) ||
435
+ state.slotAdmittedSeq === undefined ||
436
+ state.slotAdmittedNeed !== undefined ||
437
+ nodeOutsideWait(state)
438
+ )
439
+ return undefined
440
+ const need = nodeRunnerNeeds(state).find(
441
+ (entry) => entry.request !== 'reconcile' || state.nodeRestack?.conflict !== undefined,
442
+ )
443
+ if (need === undefined) return undefined
444
+ const start = state.openExecution?.seq ?? (build.provisioning ? build.provisioningSeq : undefined)
445
+ const lease =
446
+ build.record.lease !== undefined && Date.parse(build.record.lease.expiresAt) > now.getTime()
447
+ const evidence =
448
+ start !== undefined
449
+ ? start > (state.slotReleasedSeq ?? 0)
450
+ : lease && state.slotReleasedSeq === undefined
451
+ if (!evidence) return undefined
452
+ const controls = state.pendingCommands
453
+ .filter((command) => command.command === 'pause' || command.command === 'abort')
454
+ .map((command) => command.seq)
455
+ if (controls.length && (start === undefined || start >= Math.min(...controls))) return undefined
456
+ return need
457
+ }
458
+
224
459
  export function occupiesCapacity(build: CapacityBuild, now: Date): boolean {
225
460
  const { state } = build
226
461
  if (terminal(state)) return false
227
- if (state.kind !== 'node') return !parkedLeaf(build, now)
228
- return (
229
- !!state.nodeRestack?.conflict ||
230
- ((integrationNeedsRunner(state) || nodeMeasurementDue(state)) && allocated(build, now)) ||
231
- (proposeRunDue(state.optimization) && allocated(build, now))
232
- )
462
+ if (state.kind !== 'node') return leafHoldsSlot(build)
463
+ return nodeHoldsSlot(build, now) || legacyNodeRunner(build, now)
233
464
  }
234
465
 
235
- /** A parked leaf's durable request for a runner, or undefined. */
236
- function leafSlotRequest(build: CapacityBuild, now: Date): SlotRequest | undefined {
466
+ /** The durable slot request of a leaf that holds none and no longer waits on
467
+ * the outside world, or undefined. */
468
+ export function leafSlotRequest(build: LeafSlotFacts): SlotRequest | undefined {
237
469
  const { state } = build
238
470
  if (
239
- !parkedLeaf(build, now) ||
240
- state.status === 'paused' ||
241
- state.status === 'blocked' ||
471
+ terminal(state) ||
472
+ leafHoldsSlot(build) ||
473
+ leafOutsideWait(build) ||
474
+ // Mixed-version deferral withholds every decision, admission included.
242
475
  (state.compatibility?.decisiveFacts ?? 0) > 0
243
476
  )
244
477
  return undefined
245
- // A parked leaf on a rewritten target needs a runner to leave the wait: it
478
+ // A leaf on a rewritten target needs a runner to leave the wait: it
246
479
  // reprovisions itself or raises its one escalation (SPEC §7.4).
247
480
  if (state.targetRewrite !== undefined) return 'resume'
248
481
  // A ticket wait parks a leaf mid-pipeline: it asks for a slot only once the
249
482
  // wait has ended, to resume the phase that declared it.
250
483
  if (waitParked(state)) return waitResumeDue(state) ? 'resume' : undefined
484
+ // Every other unfinished leaf an outside wait released resumes where it
485
+ // stopped: an answered escalation, a resumed pause, a landed spec revision.
486
+ if (!epilogueLeaf(state)) return 'resume'
251
487
  if (state.prState === 'conflicted') return 'reconcile'
252
488
  // A reopen asks for a slot once any replacement spec is published.
253
489
  if (reopenSpecPending(state)) return undefined
@@ -263,93 +499,80 @@ function leafSlotRequest(build: CapacityBuild, now: Date): SlotRequest | undefin
263
499
  return undefined
264
500
  }
265
501
 
266
- /** A node's or parked leaf's durable request for a runner it does not hold
267
- * yet. Admission outranks ticket claims of the same priority, so this never
268
- * depends on when a tick saw it. */
269
- export function slotRequest(build: CapacityBuild, now: Date): SlotRequest | undefined {
502
+ /** A node's durable request for a slot it does not hold: the runner need it
503
+ * would be admitted for, or undefined. A node that holds its slot, or a
504
+ * legacy runner counted as holding one, requests nothing. */
505
+ export function nodeSlotNeed(build: CapacityBuild, now: Date): NodeSlotNeed | undefined {
270
506
  const { state } = build
271
- if (state.kind !== 'node') return leafSlotRequest(build, now)
272
507
  if (
508
+ state.kind !== 'node' ||
273
509
  state.status === 'done' ||
274
510
  state.status === 'aborted' ||
275
511
  state.status === 'paused' ||
276
512
  state.status === 'blocked' ||
277
513
  // Mixed-version deferral withholds every decision, admission included.
278
514
  (state.compatibility?.decisiveFacts ?? 0) > 0 ||
279
- allocated(build, now)
515
+ nodeHoldsSlot(build, now) ||
516
+ legacyNodeRunner(build, now)
280
517
  )
281
518
  return undefined
282
- if (state.nodeRestack?.conflict) return state.openEscalations.length ? undefined : 'reconcile'
283
- if (proposeStarted(state)) return 'propose'
519
+ if (state.nodeRestack?.conflict)
520
+ return state.openEscalations.length ? undefined : reconcileNeed(state)
521
+ if (proposeStarted(state)) return proposeNeed(state)
284
522
  // A node measurement (starting or progress) is admitted as a re-verify is.
285
- if (nodeMeasurementDue(state)) return 'verification'
523
+ if (nodeMeasurementDue(state)) return measurementNeed(state)
286
524
  // A stale request (stopped, spent or shrunk below its room) reserves
287
525
  // nothing; the dispatcher withdraws it. A started session was admitted
288
526
  // already and resumes whatever its eligibility.
289
- if (proposeAdmissible(state.optimization, now)) return 'propose'
290
- if (integrationAdmissible(state) && integrationNeedsRunner(state)) return 'verification'
527
+ if (proposeAdmissible(state.optimization, now)) return proposeNeed(state)
528
+ if (integrationAdmissible(state) && integrationNeedsRunner(state)) return integrationNeed(state)
291
529
  return undefined
292
530
  }
293
531
 
294
- type Identity = (ref: TicketRef, build?: string) => string
295
- const exactIdentity: Identity = (ref) => JSON.stringify([ref.source, ref.id])
296
-
297
- /** Follow accepted build identities, validating the source-qualified ticket at every edge. */
298
- function descendsFrom(
299
- build: CapacityBuild,
300
- node: string,
301
- builds: Map<string, CapacityBuild>,
302
- identity: Identity,
303
- ): boolean {
304
- const seen = new Set<string>([build.record.slug])
305
- let target = build.state.target
306
- while (target) {
307
- if (seen.has(target.build)) return false
308
- seen.add(target.build)
309
- const parent = builds.get(target.build)
310
- if (
311
- parent?.state.kind !== 'node' ||
312
- parent.record.repo !== build.record.repo ||
313
- !parent.record.ticket ||
314
- identity(parent.record.ticket, parent.record.slug) !==
315
- identity(target.ticket, build.record.slug)
532
+ /** A nonterminal build's slot state, or undefined when it is unknown: a
533
+ * `done` build reports none, and a value from a server older than durable
534
+ * admission (no `slotAdmittedSeq`, which every current reducer sets on
535
+ * `build.created`) was decided by older rules. A held slot outranks a
536
+ * request: an admitted node reports `held` until its need ends or it waits
537
+ * outside Autobuild. An aborted build in cleanup
538
+ * reports `none`. */
539
+ export function slotState(build: CapacityBuild, now: Date): SlotState | undefined {
540
+ const { state } = build
541
+ if (state.status === 'done' || state.slotAdmittedSeq === undefined) return undefined
542
+ if (occupiesCapacity(build, now)) return { state: 'held' }
543
+ const request = slotRequest(build, now)
544
+ if (!request) return { state: 'none' }
545
+ return buildPriority(state) === 'urgent'
546
+ ? { state: 'requested', request, priority: 'urgent' }
547
+ : { state: 'requested', request }
548
+ }
549
+
550
+ /** The runner work a node has a slot for or is asking one for: its held need
551
+ * when it holds its slot, otherwise its request. The dispatcher starts or
552
+ * restarts the runner of a holder; a requester waits for admission. */
553
+ export function nodeRunnerWork(build: CapacityBuild, now: Date): NodeSlotNeed | undefined {
554
+ if (nodeHoldsSlot(build, now)) {
555
+ const held = build.state.slotAdmittedNeed
556
+ return (
557
+ nodeRunnerNeeds(build.state).find((need) => need.key === held) ??
558
+ nodeRunnerNeeds(build.state)[0]
316
559
  )
317
- return false
318
- if (parent.record.slug === node) return true
319
- target = parent.state.target
320
560
  }
321
- return false
561
+ return nodeSlotNeed(build, now)
322
562
  }
323
563
 
324
- export function nodeCapacity(
325
- builds: readonly CapacityBuild[],
326
- node: string,
327
- now: Date,
328
- identity: Identity = exactIdentity,
329
- ): {
330
- occupied: number
331
- excludedDescendants: string[]
332
- } {
333
- const identities = new Map(builds.map((build) => [build.record.slug, build]))
334
- const excludedDescendants: string[] = []
335
- let occupied = 0
336
- for (const build of identities.values()) {
337
- if (build.record.slug === node || !occupiesCapacity(build, now)) continue
338
- if (
339
- (build.state.status === 'blocked' || build.state.status === 'paused') &&
340
- descendsFrom(build, node, identities, identity)
341
- )
342
- excludedDescendants.push(build.record.slug)
343
- else occupied++
344
- }
345
- return { occupied, excludedDescendants: excludedDescendants.sort() }
564
+ /** A node's or leaf's durable request for a slot it does not hold yet.
565
+ * Admission outranks ticket claims of the same priority, so this never
566
+ * depends on when a tick saw it. */
567
+ export function slotRequest(build: CapacityBuild, now: Date): SlotRequest | undefined {
568
+ if (build.state.kind !== 'node') return leafSlotRequest(build)
569
+ return nodeSlotNeed(build, now)?.request
346
570
  }
347
571
 
348
572
  export function dispatchCapacity(
349
573
  builds: readonly CapacityBuild[],
350
574
  configured: number,
351
575
  now: Date,
352
- identity: Identity = exactIdentity,
353
576
  options: {
354
577
  urgentClaims?: number
355
578
  openPrs?: OpenPrBackpressureInput
@@ -358,20 +581,6 @@ export function dispatchCapacity(
358
581
  ): DispatchCapacity {
359
582
  const unique = [...new Map(builds.map((build) => [build.record.slug, build])).values()]
360
583
  const occupied = unique.filter((build) => occupiesCapacity(build, now)).length
361
- const borrowingNodes = unique
362
- .filter((build) => {
363
- if (build.state.kind !== 'node' || !occupiesCapacity(build, now)) return false
364
- // A waiting conflict owns capacity too, but only allocated runner work borrows.
365
- if (!allocated(build, now)) return false
366
- const admission = nodeCapacity(unique, build.record.slug, now, identity)
367
- return (
368
- occupied > configured &&
369
- admission.excludedDescendants.length > 0 &&
370
- admission.occupied < configured
371
- )
372
- })
373
- .map((build) => build.record.slug)
374
- .sort()
375
584
  const waiting = (kind: 'node' | 'leaf') =>
376
585
  unique
377
586
  .flatMap((build) => {
@@ -385,6 +594,11 @@ export function dispatchCapacity(
385
594
  .sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))
386
595
  const waitingNodes = waiting('node')
387
596
  const waitingBuilds = waiting('leaf')
597
+ const slots: Record<string, SlotState> = {}
598
+ for (const build of unique) {
599
+ const slot = slotState(build, now)
600
+ if (slot) slots[build.record.slug] = slot
601
+ }
388
602
  const backpressure = options.openPrs
389
603
  ? openPrBackpressure(
390
604
  unique,
@@ -395,13 +609,14 @@ export function dispatchCapacity(
395
609
  return {
396
610
  configured,
397
611
  occupied,
398
- effective: borrowingNodes.length ? Math.max(configured, occupied) : configured,
399
- borrowingNodes,
612
+ effective: configured,
613
+ borrowingNodes: [],
400
614
  ...(waitingNodes.length ? { waitingNodes } : {}),
401
615
  ...(waitingBuilds.length ? { waitingBuilds } : {}),
402
616
  ...(options.urgentClaims ? { urgentClaims: options.urgentClaims } : {}),
403
617
  ...(backpressure ? { backpressure } : {}),
404
618
  ...startRequestsOf(options.startRequests),
619
+ slots,
405
620
  }
406
621
  }
407
622
 
@@ -414,12 +629,6 @@ function startRequestsOf(
414
629
  return Object.keys(startRequests).length ? { startRequests } : {}
415
630
  }
416
631
 
417
- /** A node verification or propose request reserves a slot until the node
418
- * holds it; a node reconcile request already occupies one. */
419
- function nodeReserves(node: SlotWaiter): boolean {
420
- return node.request === 'verification' || node.request === 'propose'
421
- }
422
-
423
632
  /** Slots reserved ahead of one parked waiter: manual start requests for
424
633
  * urgent work; for normal work, also every other urgent reservation, the
425
634
  * urgent start requests and the urgent ticket claims still waiting. A waiter
@@ -432,7 +641,7 @@ export function reservedAhead(
432
641
  if (waiter.priority === 'urgent') return startsOf(capacity, ['manual'])
433
642
  const urgent = (entry: SlotWaiter) => entry.priority === 'urgent' && entry.slug !== waiter.slug
434
643
  return (
435
- (capacity.waitingNodes ?? []).filter((node) => nodeReserves(node) && urgent(node)).length +
644
+ (capacity.waitingNodes ?? []).filter(urgent).length +
436
645
  (capacity.waitingBuilds ?? []).filter(urgent).length +
437
646
  (capacity.urgentClaims ?? 0) +
438
647
  startsOf(capacity, ['manual', 'urgent'])
@@ -453,9 +662,7 @@ function waitersAhead(
453
662
  ): number {
454
663
  const counts = (entry: { priority?: TicketPriority }) =>
455
664
  priority === 'normal' || entry.priority === 'urgent'
456
- const nodes = (capacity.waitingNodes ?? []).filter(
457
- (node) => nodeReserves(node) && counts(node),
458
- ).length
665
+ const nodes = (capacity.waitingNodes ?? []).filter(counts).length
459
666
  const builds = new Set(
460
667
  (capacity.waitingBuilds ?? [])
461
668
  .filter((build) => counts(build) && !adjust.settled?.has(build.slug))
@@ -470,10 +677,8 @@ function waitersAhead(
470
677
  * same or a higher priority reserves ahead of them: an urgent claim waits only
471
678
  * for urgent parked work, a normal claim for every waiter. Pending start
472
679
  * requests of the same or a higher tier reserve ahead too: manual and urgent
473
- * ones for an urgent claim, every one for a normal claim. A node verification or
474
- * propose request reserves one slot until the node holds it; a node reconcile
475
- * request already occupies one. A parked build's request occupies nothing, so
476
- * each one reserves a slot. Never more than the configured budget minus
680
+ * ones for an urgent claim, every one for a normal claim. A waiting node's or
681
+ * parked build's request occupies nothing, so each one reserves a slot. Never more than the configured budget minus
477
682
  * occupied builds.
478
683
  *
479
684
  * The dispatcher refines the projection with its own decisions this tick:
@@ -538,14 +743,18 @@ export function waitingExplanation(
538
743
  ]
539
744
  return notes.length ? `${entry.slug} (${notes.join(', ')})` : entry.slug
540
745
  }
541
- const clause = (noun: string, waiting: SlotWaiter[]) => {
542
- if (!waiting.length) return []
543
- const ordered = [
544
- ...waiting.filter((entry) => entry.priority === 'urgent'),
545
- ...waiting.filter((entry) => entry.priority !== 'urgent'),
546
- ]
746
+ const clause = (noun: string, waiting: SlotWaiter[]) =>
747
+ waiting.length
748
+ ? [
749
+ `${waiting.length} ${noun}${waiting.length === 1 ? '' : 's'} waiting for a slot ahead of normal ticket claims: ${waiting.map(label).join(', ')}`,
750
+ ]
751
+ : []
752
+ const parked = (priority: TicketPriority) => {
753
+ const of = (waiting: SlotWaiter[] | undefined) =>
754
+ (waiting ?? []).filter((entry) => (entry.priority ?? 'normal') === priority)
547
755
  return [
548
- `${waiting.length} ${noun}${waiting.length === 1 ? '' : 's'} waiting for a slot ahead of normal ticket claims: ${ordered.map(label).join(', ')}`,
756
+ ...clause('node', of(capacity?.waitingNodes)),
757
+ ...clause('parked build', of(capacity?.waitingBuilds)),
549
758
  ]
550
759
  }
551
760
  const urgentClaims = capacity?.urgentClaims ?? 0
@@ -553,17 +762,19 @@ export function waitingExplanation(
553
762
  const count = capacity?.startRequests?.[tier] ?? 0
554
763
  return count ? [`${count} ${tier} start request${count === 1 ? '' : 's'} ${waiting}`] : []
555
764
  }
765
+ // Slot admission order (SPEC §12): manual starts, urgent parked work,
766
+ // urgent claims (start requests first), normal parked work, normal claims.
556
767
  return [
557
768
  ...starts('manual', 'waiting ahead of all other work'),
769
+ ...parked('urgent'),
558
770
  ...starts('urgent', 'waiting ahead of normal parked work'),
559
- ...starts('normal', 'waiting for a slot'),
560
- ...clause('node', capacity?.waitingNodes ?? []),
561
- ...clause('parked build', capacity?.waitingBuilds ?? []),
562
771
  ...(urgentClaims
563
772
  ? [
564
773
  `${urgentClaims} urgent ticket claim${urgentClaims === 1 ? '' : 's'} waiting ahead of normal parked work`,
565
774
  ]
566
775
  : []),
776
+ ...parked('normal'),
777
+ ...starts('normal', 'waiting for a slot'),
567
778
  ].join('; ')
568
779
  }
569
780
 
@@ -571,10 +782,6 @@ export function waitingExplanation(
571
782
  export function capacityExplanation(capacity?: DispatchCapacity): string {
572
783
  if (!capacity) return ''
573
784
  const clauses: string[] = []
574
- if (capacity.borrowingNodes.length)
575
- clauses.push(
576
- `${capacity.borrowingNodes.length} node${capacity.borrowingNodes.length === 1 ? '' : 's'} using descendant-held slots: ${capacity.borrowingNodes.join(', ')}`,
577
- )
578
785
  const waiting = waitingExplanation(capacity)
579
786
  if (waiting) clauses.push(waiting)
580
787
  const backpressure = backpressureExplanation(capacity.backpressure)