@defrex/autobuild 1.11.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +601 -203
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +32 -2
  5. package/docs/architecture.md +188 -57
  6. package/docs/assets/headline-wide.png +0 -0
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +120 -23
  9. package/docs/dispatcher.md +19 -8
  10. package/docs/integration-overview.md +1 -1
  11. package/docs/integration-tree.md +33 -18
  12. package/docs/merge-policy.md +7 -2
  13. package/docs/operating.md +5 -3
  14. package/docs/operator-api.md +48 -25
  15. package/docs/operator-surfaces.md +39 -3
  16. package/docs/optimization-nodes.md +10 -8
  17. package/docs/plugin-authoring.md +46 -18
  18. package/docs/remote-store-protocol.md +51 -12
  19. package/docs/remote-ticket-protocol.md +85 -38
  20. package/docs/restacking.md +48 -3
  21. package/docs/setup.md +2 -1
  22. package/docs/ticket-migration.md +2 -2
  23. package/docs/ticket-sources.md +23 -8
  24. package/docs/tickets.md +4 -4
  25. package/docs/troubleshooting.md +17 -2
  26. package/docs/verification.md +3 -1
  27. package/package.json +3 -3
  28. package/packages/core/src/cli/ambient-errors.ts +17 -0
  29. package/packages/core/src/cli/bounded-io.ts +174 -0
  30. package/packages/core/src/cli/build-control.ts +72 -6
  31. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  32. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  33. package/packages/core/src/cli/dashboard/model.ts +93 -29
  34. package/packages/core/src/cli/dashboard/poll.ts +231 -34
  35. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  36. package/packages/core/src/cli/dashboard/render.ts +14 -37
  37. package/packages/core/src/cli/dashboard/row-text.ts +26 -8
  38. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  39. package/packages/core/src/cli/dashboard/vocabulary.ts +165 -20
  40. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  41. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  42. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  43. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  44. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  45. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  46. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  47. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  48. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  49. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  50. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  51. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  52. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  53. package/packages/core/src/cli/dispatch.ts +595 -149
  54. package/packages/core/src/cli/env.ts +2 -15
  55. package/packages/core/src/cli/help.ts +43 -28
  56. package/packages/core/src/cli/main.ts +11 -7
  57. package/packages/core/src/cli/production-store.ts +102 -0
  58. package/packages/core/src/cli/publication-settlement.ts +4 -0
  59. package/packages/core/src/cli/remote-poll.ts +22 -5
  60. package/packages/core/src/cli/repo-state.ts +2 -3
  61. package/packages/core/src/cli/repository-status.ts +44 -28
  62. package/packages/core/src/cli/sessionless-store.ts +26 -0
  63. package/packages/core/src/cli/status.ts +188 -47
  64. package/packages/core/src/cli/store-opening.ts +26 -57
  65. package/packages/core/src/cli/store-ref.ts +6 -1
  66. package/packages/core/src/cli/ticket-start.ts +3 -3
  67. package/packages/core/src/cli/ticket.ts +12 -11
  68. package/packages/core/src/cli/wait.ts +8 -28
  69. package/packages/core/src/cli/watch.ts +113 -50
  70. package/packages/core/src/config/reference-metadata.ts +7 -1
  71. package/packages/core/src/config/reference.ts +5 -2
  72. package/packages/core/src/config/schema.ts +51 -16
  73. package/packages/core/src/distribution-packaging.ts +156 -18
  74. package/packages/core/src/events/catalog-identity.ts +28 -0
  75. package/packages/core/src/events/catalog.ts +3 -9
  76. package/packages/core/src/events/compatibility.ts +2 -30
  77. package/packages/core/src/events/payloads.ts +85 -14
  78. package/packages/core/src/events/policy.ts +3 -0
  79. package/packages/core/src/events/repository.ts +15 -4
  80. package/packages/core/src/events/sessions.ts +1 -1
  81. package/packages/core/src/events/validation-error.ts +12 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +36 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  92. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  93. package/packages/core/src/kernel/capacity-build.ts +21 -0
  94. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  95. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +578 -235
  97. package/packages/core/src/kernel/done-escalations.ts +269 -0
  98. package/packages/core/src/kernel/engine.ts +30 -17
  99. package/packages/core/src/kernel/integration-landing.ts +24 -4
  100. package/packages/core/src/kernel/integration-stack.ts +39 -0
  101. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  102. package/packages/core/src/kernel/log-index-value.ts +3 -0
  103. package/packages/core/src/kernel/log-index.ts +41 -2
  104. package/packages/core/src/kernel/measurement.ts +24 -0
  105. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  106. package/packages/core/src/kernel/read-facts.ts +8 -370
  107. package/packages/core/src/kernel/reducer-registry.ts +43 -125
  108. package/packages/core/src/kernel/reducer-revisions.ts +18 -0
  109. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  110. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  111. package/packages/core/src/kernel/reducer.ts +84 -16
  112. package/packages/core/src/kernel/reopen-state.ts +10 -0
  113. package/packages/core/src/kernel/repository-attention.ts +14 -5
  114. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  115. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  116. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  117. package/packages/core/src/kernel/verify-stages.ts +46 -7
  118. package/packages/core/src/operator/attention.ts +28 -3
  119. package/packages/core/src/operator/done-escalations.ts +38 -0
  120. package/packages/core/src/operator/presentation.ts +14 -1
  121. package/packages/core/src/operator/protocol.ts +8 -5
  122. package/packages/core/src/operator/query.ts +72 -57
  123. package/packages/core/src/operator/registry.ts +19 -15
  124. package/packages/core/src/operator/ticket-start.ts +8 -7
  125. package/packages/core/src/operator/tickets.ts +28 -9
  126. package/packages/core/src/plugin-sdk/index.ts +10 -0
  127. package/packages/core/src/plugins/manifest.ts +14 -1
  128. package/packages/core/src/ports/forge/create.ts +8 -0
  129. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  130. package/packages/core/src/ports/forge/github.ts +3 -0
  131. package/packages/core/src/ports/tickets/contract.ts +147 -76
  132. package/packages/core/src/ports/tickets/create.ts +47 -7
  133. package/packages/core/src/ports/tickets/fake.ts +8 -4
  134. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  135. package/packages/core/src/ports/tickets/file.ts +7 -3
  136. package/packages/core/src/ports/tickets/github.ts +1 -0
  137. package/packages/core/src/ports/tickets/grants.ts +11 -3
  138. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  139. package/packages/core/src/ports/tickets/linear.ts +28 -9
  140. package/packages/core/src/ports/tickets/migration.ts +4 -4
  141. package/packages/core/src/ports/tickets/operations.ts +4 -2
  142. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  143. package/packages/core/src/ports/tickets/priority.ts +127 -21
  144. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  145. package/packages/core/src/ports/tickets/remote.ts +104 -11
  146. package/packages/core/src/ports/tickets/revision.ts +5 -3
  147. package/packages/core/src/ports/tickets/search.ts +9 -0
  148. package/packages/core/src/ports/tickets/tree.ts +8 -6
  149. package/packages/core/src/ports/types.ts +30 -15
  150. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  151. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  152. package/packages/core/src/ports/workspace/create.ts +16 -3
  153. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  154. package/packages/core/src/ports/workspace/fake.ts +15 -3
  155. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  156. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  157. package/packages/core/src/processes/build-execution-state.ts +4 -0
  158. package/packages/core/src/processes/build-runner.ts +14 -1
  159. package/packages/core/src/processes/dispatcher.ts +777 -288
  160. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  161. package/packages/core/src/processes/execution-settlement.ts +1 -0
  162. package/packages/core/src/processes/harvest-runner.ts +12 -7
  163. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  164. package/packages/core/src/processes/invocation-budget.ts +176 -0
  165. package/packages/core/src/processes/publication-loss.ts +38 -3
  166. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  167. package/packages/core/src/store/contract.ts +81 -3
  168. package/packages/core/src/store/event-reads.ts +30 -1
  169. package/packages/core/src/store/local/capabilities.ts +115 -0
  170. package/packages/core/src/store/local/store.ts +86 -56
  171. package/packages/core/src/store/reduced-reads.ts +32 -1
  172. package/packages/core/src/store/reducer-value-read.ts +235 -0
  173. package/packages/core/src/store/reducer-value-shapes.json +6722 -6475
  174. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  175. package/packages/core/src/store/reducer-values.ts +36 -204
  176. package/packages/core/src/store/remote/client.ts +169 -29
  177. package/packages/core/src/store/remote/compatibility.ts +113 -56
  178. package/packages/core/src/store/remote/credentials.ts +4 -1
  179. package/packages/core/src/store/remote/protocol.ts +3 -0
  180. package/packages/core/src/store/remote/released-clients.json +22 -0
  181. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  182. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  183. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  184. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  185. package/packages/core/src/store/remote/retry.ts +406 -0
  186. package/packages/core/src/store/rollup-lease.ts +41 -0
  187. package/packages/core/src/store/rollups.ts +7 -38
  188. package/packages/core/src/store/snapshots.ts +1 -1
  189. package/packages/core/src/testing/dispatch-read-budget.ts +409 -14
  190. package/packages/core/src/testing/import-graph.ts +78 -0
  191. package/packages/core/src/testing/index.ts +2 -0
  192. package/packages/core/src/testing/invocation-budget.ts +42 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +602 -40
  194. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  195. package/packages/core/src/testing/slot-agreement.ts +52 -0
  196. package/packages/core/src/web/assets/app.js +5 -5
  197. package/packages/core/src/web/overview-source.ts +19 -6
  198. package/skills/guide/SKILL.md +245 -103
  199. package/skills/guide/references/integration-tree.md +33 -18
  200. package/skills/guide/references/merge-policy.md +7 -2
  201. package/skills/guide/references/operator-api.md +48 -25
  202. package/skills/guide/references/optimization-nodes.md +10 -8
  203. package/skills/guide/references/plugin-authoring.md +46 -18
  204. package/skills/guide/references/remote-store-protocol.md +51 -12
  205. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  206. package/skills/guide/references/restacking.md +48 -3
  207. package/skills/guide/references/setup.md +2 -1
  208. package/skills/guide/references/ticket-migration.md +2 -2
  209. package/skills/operate/SKILL.md +114 -65
  210. package/skills/plan/SKILL.md +4 -3
  211. package/skills/spec/SKILL.md +9 -5
  212. package/skills/tickets/SKILL.md +25 -17
  213. package/templates/hosted-service/package.json +2 -2
@@ -1,13 +1,25 @@
1
1
  import type { TicketStartPriority } from '../events/repository'
2
- import type { TicketRef } from '../ontology'
3
- import type { TicketPriority } from '../ports/types'
2
+ import {
3
+ priorityRank,
4
+ START_TIERS,
5
+ startTierOf,
6
+ TICKET_PRIORITIES,
7
+ type StartTier,
8
+ } from '../ports/tickets/priority'
9
+ import type { BuildPriority } from '../ports/types'
4
10
  import type { BuildRecord } from '../store/types'
5
11
  import type { BuildState } from './reducer'
6
12
  import { integrationAdmissible, integrationNeedsRunner } from './integration-state'
7
13
  import { proposeAdmissible, proposeRunDue, proposeStarted } from './optimization-admission'
8
14
  import { waitParked, waitResumeDue } from './ticket-wait'
9
- import { nodeMeasurementDue, pendingMeasurementRequest } from './measurement'
10
- import { reopenRestart, reopenSpecPending, reopenUnsettled } from './reopen-state'
15
+ import { nodeMeasurementDue, nodeMeasurementNeed, pendingMeasurementRequest } from './measurement'
16
+ import { escalationCarried, type EscalationCarryInput } from './verify-stage-state'
17
+ import {
18
+ reopenRestart,
19
+ reopenSpecPending,
20
+ reopenUnsettled,
21
+ reviseSpecPending,
22
+ } from './reopen-state'
11
23
  import type { PolicyConfig } from '../config/schema'
12
24
  import {
13
25
  backpressureExplanation,
@@ -16,80 +28,164 @@ import {
16
28
  type OpenPrBackpressure,
17
29
  } from './open-pr-backpressure'
18
30
 
19
- /** Repository-scoped, reduced facts. Provisioning reserves a slot before a workspace exists.
31
+ /** Repository-scoped, reduced facts (SPEC §12 "What holds a slot").
20
32
  *
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. */
33
+ * A leaf takes a slot only by admission: its `build.created` (a ticket claim
34
+ * or start request) or the dispatcher's `slot.admitted`. It holds the slot
35
+ * while Autobuild owes its next move, whether or not a runner works, and
36
+ * releases it as soon as it waits on the outside world (`leafOutsideWait`): a
37
+ * human (an open escalation, an acknowledged pause, a `revise-spec` answer
38
+ * awaiting its revision, a merge decision or hold), another ticket, or the
39
+ * forge. An open escalation that work Autobuild started still outruns (a
40
+ * verify stage's other members, a recorded launch or its execution:
41
+ * `escalationCarried`) does not release it, and its answer releases nothing.
42
+ * Release follows state; acquisition never does, so a leaf whose outside
43
+ * wait ended asks for a slot (`slotRequest`) and holds none until it is
44
+ * admitted again. Runner liveness plays no part in a leaf's hold (only launch
45
+ * records and execution facts do), and its workspace never counts. A node
46
+ * holds a slot only once the dispatcher admitted it for a runner need it still has (`nodeHoldsSlot`); a workspace,
47
+ * a lease or a provisioning marker never takes one. */
30
48
  export interface CapacityBuild {
31
49
  record: BuildRecord
32
50
  state: BuildState
33
51
  workspace: boolean
34
52
  provisioning?: boolean
53
+ /** seq of the open provisioning marker's `workspace.provision-started`;
54
+ * omitted when `provisioning` is, or unknown. Anchors a runner launched
55
+ * before node admissions were recorded (`legacyNodeRunner`). */
56
+ provisioningSeq?: number
35
57
  /** The engine's awaiting-landing restack is due (`landingRestackDue`); omitted means false. */
36
58
  restackDue?: boolean
37
59
  }
38
60
 
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
61
+ /** The slot a node or a leaf that holds none has durably requested. `resume`
62
+ * is a leaf whose escalation was answered, whose pause was resumed, whose
63
+ * ticket wait ended or whose target was rewritten; `reopen` is a leaf an
41
64
  * operator reopened; `propose` is an optimization node's open, still
42
- * eligible proposal request. */
65
+ * eligible proposal request. A node requests `verification`, `reconcile` or
66
+ * `propose` for runner work it has not been admitted for. */
43
67
  export type SlotRequest = 'verification' | 'reconcile' | 'resume' | 'reopen' | 'propose'
44
68
 
45
- /** One node or parked leaf waiting for a slot. `priority` is omitted for
46
- * normal builds, and by an older server. */
69
+ /** A non-normal build level as projections carry it; normal is omitted. */
70
+ export type MarkedPriority = Exclude<BuildPriority, 'normal'>
71
+
72
+ /** One node or leaf waiting for a slot. `priority` is omitted for normal
73
+ * builds, and by an older server (which knew only urgent). */
47
74
  export interface SlotWaiter {
48
75
  slug: string
49
76
  request: SlotRequest
50
- priority?: 'urgent'
77
+ priority?: MarkedPriority
78
+ }
79
+
80
+ /** One build's slot state (SPEC §12 "What holds a slot"), by the rules
81
+ * admission counts: `held` exactly when `occupiesCapacity`, otherwise
82
+ * `requested` exactly when `slotRequest` names one (`priority` as the
83
+ * build's `SlotWaiter` carries it), otherwise `none`. */
84
+ export type SlotState =
85
+ | { state: 'held' }
86
+ | { state: 'requested'; request: SlotRequest; priority?: MarkedPriority }
87
+ | { state: 'none' }
88
+
89
+ /** Ticket claims the latest admission scan found waiting for a slot, by
90
+ * level (`claimDemand`). Low claims never reserve: nothing ranks below them. */
91
+ export interface ClaimDemand {
92
+ urgent?: number
93
+ high?: number
94
+ normal?: number
51
95
  }
52
96
 
53
97
  /** Slot admission order for free slots (SPEC §12, "Slot admission order"):
54
- * manual start requests, urgent parked work, urgent ticket claims (urgent
55
- * start requests first), normal parked work, normal ticket claims (normal
56
- * start requests first); each tier keeps its own order. */
98
+ * manual start requests, then for each level, urgent, high, normal and low,
99
+ * that level's parked work, then its ticket claims (its start requests
100
+ * first); each tier keeps its own order. */
57
101
  export interface DispatchCapacity {
58
102
  configured: number
103
+ /** Builds holding a slot; never above `configured` once admitted by the
104
+ * slot arithmetic. */
59
105
  occupied: number
106
+ /** @deprecated Always `configured`. Kept for clients in the version window,
107
+ * which read it as the effective capacity. */
60
108
  effective: number
109
+ /** @deprecated Always empty. Kept for clients in the version window, which
110
+ * read it as the nodes borrowing descendant-held slots. */
61
111
  borrowingNodes: string[]
62
112
  /** Nodes waiting for a slot; omitted when none wait, and by an older server. */
63
113
  waitingNodes?: SlotWaiter[]
64
- /** Parked leaves waiting for a slot; omitted when none wait, and by an older server. */
114
+ /** Leaves waiting for a slot; omitted when none wait, and by an older server. */
65
115
  waitingBuilds?: SlotWaiter[]
66
116
  /** Urgent ticket claims the latest admission scan found waiting for a slot
67
- * (`urgentClaimDemand`); they go ahead of normal parked work. Omitted when
68
- * none, and when the caller has no repository facts. */
117
+ * (`claimDemand`); they go ahead of high, normal and low parked work.
118
+ * Omitted when none, and when the caller has no repository facts. */
69
119
  urgentClaims?: number
70
- /** Open-PR backpressure on normal-priority claims; absent when disabled. */
120
+ /** High ticket claims waiting for a slot; they go ahead of normal and low
121
+ * parked work. Omitted when none, and by an older server. */
122
+ highClaims?: number
123
+ /** Normal ticket claims waiting for a slot; they go ahead of low parked
124
+ * work. Omitted when none, and by an older server. */
125
+ normalClaims?: number
126
+ /** Open-PR backpressure on high, normal and low claims; absent when disabled. */
71
127
  backpressure?: OpenPrBackpressure
72
128
  /** Pending operator start requests by tier (`startClaimDemand`); each
73
129
  * reserves a slot ahead of the lower tiers. Omitted when none, by an older
74
130
  * server, and when the caller has no repository facts. */
75
- startRequests?: Partial<Record<TicketStartPriority, number>>
131
+ startRequests?: Partial<Record<StartTier, number>>
132
+ /** Each projected build's `slotState` by slug; empty when no build's is
133
+ * known. Omitted by an older server. A missing entry, or a missing map,
134
+ * is unknown, never `none`. */
135
+ slots?: Record<string, SlotState>
76
136
  }
77
137
 
78
- /** A build's slot-admission priority; absent (historical builds, sources
79
- * without priority) reads as normal. */
80
- export function buildPriority(state: Pick<BuildState, 'priority'>): TicketPriority {
81
- return state.priority === 'urgent' ? 'urgent' : 'normal'
138
+ /** A build's slot-admission level: a high or low `priorityLevel` refines
139
+ * the two-level `priority`; absent (historical builds, sources without
140
+ * priority) reads as normal. The only reader of those fields. */
141
+ export function buildPriority(
142
+ state: Pick<BuildState, 'priority' | 'priorityLevel'>,
143
+ ): BuildPriority {
144
+ return state.priorityLevel ?? (state.priority === 'urgent' ? 'urgent' : 'normal')
82
145
  }
83
146
 
84
- /** Urgent ticket claims still waiting for a slot, from the latest scan fact.
85
- * Only an admission scan with intake on and the repository unpaused speaks
86
- * for claims that can run. */
87
- export function urgentClaimDemand(facts: {
88
- scan?: { mode: 'admission' | 'observation'; urgentWaiting?: number }
147
+ /** A level as projections mark it: undefined for normal. */
148
+ export function markedPriority(level: BuildPriority): MarkedPriority | undefined {
149
+ return level === 'normal' ? undefined : level
150
+ }
151
+
152
+ /** A projected waiter's level; absent reads as normal. */
153
+ function waiterLevel(entry: { priority?: BuildPriority }): BuildPriority {
154
+ return entry.priority ?? 'normal'
155
+ }
156
+
157
+ /** Ticket claims still waiting for a slot by level, from the latest scan
158
+ * fact. Only an admission scan with intake on and the repository unpaused
159
+ * speaks for claims that can run. */
160
+ export function claimDemand(facts: {
161
+ scan?: {
162
+ mode: 'admission' | 'observation'
163
+ urgentWaiting?: number
164
+ highWaiting?: number
165
+ normalWaiting?: number
166
+ }
89
167
  settings: { intake: boolean; paused: boolean }
90
- }): number {
91
- if (!facts.settings.intake || facts.settings.paused || facts.scan?.mode !== 'admission') return 0
92
- return facts.scan.urgentWaiting ?? 0
168
+ }): ClaimDemand {
169
+ if (!facts.settings.intake || facts.settings.paused || facts.scan?.mode !== 'admission') return {}
170
+ const { urgentWaiting: urgent, highWaiting: high, normalWaiting: normal } = facts.scan
171
+ return {
172
+ ...(urgent ? { urgent } : {}),
173
+ ...(high ? { high } : {}),
174
+ ...(normal ? { normal } : {}),
175
+ }
176
+ }
177
+
178
+ /** Claim demand at one level in a projection. */
179
+ function claimsAt(capacity: DispatchCapacity, level: BuildPriority): number {
180
+ if (level === 'urgent') return capacity.urgentClaims ?? 0
181
+ if (level === 'high') return capacity.highClaims ?? 0
182
+ if (level === 'normal') return capacity.normalClaims ?? 0
183
+ return 0
184
+ }
185
+
186
+ /** The levels ranked strictly above one level. */
187
+ function levelsAbove(level: BuildPriority): readonly BuildPriority[] {
188
+ return TICKET_PRIORITIES.slice(0, priorityRank(level))
93
189
  }
94
190
 
95
191
  /** What a capacity projection needs to report open-PR backpressure: the
@@ -104,22 +200,84 @@ export interface OpenPrBackpressureInput {
104
200
  /** Pending operator start requests by tier, counted whatever intake says:
105
201
  * a start request bypasses intake. Nothing while the repository is paused. */
106
202
  export function startClaimDemand(facts: {
107
- ticketStarts: { pending: Record<string, { priority: TicketStartPriority }> }
203
+ ticketStarts: {
204
+ pending: Record<string, { priority: TicketStartPriority; level?: 'high' | 'low' }>
205
+ }
108
206
  settings: { paused: boolean }
109
- }): Partial<Record<TicketStartPriority, number>> {
110
- const demand: Partial<Record<TicketStartPriority, number>> = {}
207
+ }): Partial<Record<StartTier, number>> {
208
+ const demand: Partial<Record<StartTier, number>> = {}
111
209
  if (facts.settings.paused) return demand
112
- for (const { priority } of Object.values(facts.ticketStarts.pending))
113
- demand[priority] = (demand[priority] ?? 0) + 1
210
+ for (const request of Object.values(facts.ticketStarts.pending)) {
211
+ const tier = startTierOf(request)
212
+ demand[tier] = (demand[tier] ?? 0) + 1
213
+ }
114
214
  return demand
115
215
  }
116
216
 
217
+ /** Start requests the early start pass (manual, urgent) evaluates in one
218
+ * tick, and the late passes (high, normal, low) together: each pass reads
219
+ * its requests in tier order, oldest first. */
220
+ export const START_REQUESTS_PER_TICK = 8
221
+ export const EARLY_START_TIERS: readonly StartTier[] = START_TIERS.slice(0, 2)
222
+ export const LATE_START_TIERS: readonly StartTier[] = START_TIERS.slice(2)
223
+
224
+ /** The start barrier of a tick (SPEC §12 "Slot admission order"): the
225
+ * highest tier with a pending request the tick's evaluation allowance
226
+ * (`START_REQUESTS_PER_TICK` early and as many late) leaves unread, or
227
+ * undefined when every pending request is read. In memory over the
228
+ * repository's pending requests. */
229
+ export function startBarrier(
230
+ pending: Iterable<{ priority: TicketStartPriority; level?: 'high' | 'low'; seq: number }>,
231
+ ): StartTier | undefined {
232
+ const rank = (request: { priority: TicketStartPriority; level?: 'high' | 'low' }) =>
233
+ START_TIERS.indexOf(startTierOf(request))
234
+ const sorted = [...pending].sort((a, b) => rank(a) - rank(b) || a.seq - b.seq)
235
+ for (const tiers of [EARLY_START_TIERS, LATE_START_TIERS]) {
236
+ const unread = sorted.filter((request) => tiers.includes(startTierOf(request)))[
237
+ START_REQUESTS_PER_TICK
238
+ ]
239
+ if (unread !== undefined) return startTierOf(unread)
240
+ }
241
+ return undefined
242
+ }
243
+
244
+ /** What competes for a free slot at one level: `waiting` work (a parked
245
+ * leaf, a node or a proposer), an ordinary ready-ticket `claim` (an
246
+ * optimization attempt's included) or a `start` request of that tier. */
247
+ export type AdmissionKind = 'waiting' | 'claim' | 'start'
248
+
249
+ /** The one guard every admission path consults: whether a tick's start
250
+ * barrier holds back admission of this kind at this level. An unread request
251
+ * at level L outranks everything below L, and at L it outranks L's ready
252
+ * tickets but not L's waiting work, which goes ahead of L's claims, nor L's
253
+ * older requests, which were read. Higher levels are unaffected. */
254
+ export function admissionBarred(
255
+ barrier: StartTier | undefined,
256
+ kind: AdmissionKind,
257
+ level: StartTier,
258
+ ): boolean {
259
+ if (barrier === undefined) return false
260
+ const rank = START_TIERS.indexOf(level)
261
+ const held = START_TIERS.indexOf(barrier)
262
+ return kind === 'claim' ? rank >= held : rank > held
263
+ }
264
+
117
265
  /** Pending start requests of the named tiers. */
118
- function startsOf(capacity: DispatchCapacity, tiers: readonly TicketStartPriority[]): number {
266
+ function startsOf(capacity: DispatchCapacity, tiers: readonly StartTier[]): number {
119
267
  return tiers.reduce((sum, tier) => sum + (capacity.startRequests?.[tier] ?? 0), 0)
120
268
  }
121
269
 
122
- /** A provisioning marker or continuation, or a live lease: a runner is working. */
270
+ /** The start tiers ranked strictly above one tier, `manual` always first. */
271
+ function tiersAbove(tier: StartTier): readonly StartTier[] {
272
+ return START_TIERS.slice(0, START_TIERS.indexOf(tier))
273
+ }
274
+
275
+ /** The start tiers at or above one level, `manual` included. */
276
+ function tiersAtOrAbove(level: BuildPriority): readonly StartTier[] {
277
+ return START_TIERS.slice(0, START_TIERS.indexOf(level) + 1)
278
+ }
279
+
280
+ /** A node's provisioning marker or continuation, or a live lease: a runner is working. */
123
281
  function runnerAllocated(build: CapacityBuild, now: Date): boolean {
124
282
  return (
125
283
  !!build.provisioning ||
@@ -127,11 +285,6 @@ function runnerAllocated(build: CapacityBuild, now: Date): boolean {
127
285
  )
128
286
  }
129
287
 
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
288
  /** The position the dispatcher records as settled: the later of the current
136
289
  * verify cycle's start and the latest finalize completion. A reconcile,
137
290
  * restack or config supersession opens a new cycle and so a new key. */
@@ -164,13 +317,98 @@ function executionOpen(state: BuildState): boolean {
164
317
  return state.openExecution?.commandId !== undefined
165
318
  }
166
319
 
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 {
320
+ /** What a leaf's slot depends on: its reduced state and whether the engine's
321
+ * awaiting-landing restack is due. */
322
+ export type LeafSlotFacts = Pick<CapacityBuild, 'state' | 'restackDue'>
323
+
324
+ /** The build was admitted since its last release (SPEC §12 "What holds a
325
+ * slot"). A value from an older server carries neither seq and reads as
326
+ * admitted. */
327
+ export function slotAdmitted(
328
+ state: Pick<BuildState, 'slotAdmittedSeq' | 'slotReleasedSeq'>,
329
+ ): boolean {
330
+ return state.slotAdmittedSeq === undefined || state.slotAdmittedSeq > (state.slotReleasedSeq ?? 0)
331
+ }
332
+
333
+ /** A finished leaf still owes work before it waits for its merge decision:
334
+ * a rewritten target, a conflicted PR, a reopen (its spec publication
335
+ * included), a restack, an unsettled verify cycle or finalize, a pending
336
+ * measurement request, or an open session to recover or close. */
337
+ function epilogueWorkDue(build: LeafSlotFacts): boolean {
338
+ const { state } = build
170
339
  return (
171
- (epilogueLeaf(build.state) || waitParked(build.state)) &&
172
- !runnerAllocated(build, now) &&
173
- !executionOpen(build.state)
340
+ state.sessions.open.length > 0 ||
341
+ state.targetRewrite !== undefined ||
342
+ state.prState === 'conflicted' ||
343
+ reopenSpecPending(state) ||
344
+ reopenUnsettled(state) ||
345
+ !!build.restackDue ||
346
+ epilogueUnsettled(state) ||
347
+ pendingMeasurementRequest(state) !== undefined
348
+ )
349
+ }
350
+
351
+ /** A leaf waiting on the outside world, which holds no slot: an open
352
+ * escalation (an entered ticket wait's included), an acknowledged pause no
353
+ * resume was requested for, a `revise-spec` answer awaiting its revision, or
354
+ * a finished pipeline with no epilogue work due (a merge decision or hold,
355
+ * merge gates or the forge). */
356
+ export function leafOutsideWait(build: LeafSlotFacts): boolean {
357
+ const { state } = build
358
+ if (humanWait(state, state.status)) return true
359
+ if (reviseSpecPending(state)) return true
360
+ return epilogueLeaf(state) && !epilogueWorkDue(build)
361
+ }
362
+
363
+ /** Blocked on a question, or paused with no resume requested (or with an
364
+ * open escalation): the build waits on a human. */
365
+ function humanWait(state: BuildState, status: BuildState['status']): boolean {
366
+ if (status === 'blocked') return true
367
+ return (
368
+ status === 'paused' &&
369
+ (state.openEscalations.length > 0 ||
370
+ !state.pendingCommands.some((command) => command.command === 'resume'))
371
+ )
372
+ }
373
+
374
+ /** The carry input of a leaf's reduced state (`escalationCarried`). */
375
+ export function escalationCarryInput(state: BuildState): EscalationCarryInput {
376
+ return {
377
+ openEscalations: state.openEscalations,
378
+ verifyStage: state.verifyStage,
379
+ verifyCycle: state.verify.cycleSince,
380
+ maxAttemptSeen: state.verify.maxAttemptSeen,
381
+ executions: state.executions,
382
+ liveExecution: state.openExecution,
383
+ slotAdmittedSeq: state.slotAdmittedSeq,
384
+ failures: [state.dispatchFailures, state.infrastructureFailures, state.setupFailures],
385
+ }
386
+ }
387
+
388
+ /** A leaf whose only outside wait is its open escalations: blocked, with no
389
+ * `revise-spec` answer awaiting its revision and no finished pipeline
390
+ * waiting for its merge decision. */
391
+ function blockedOnlyByEscalations(build: LeafSlotFacts): boolean {
392
+ const { state } = build
393
+ return (
394
+ state.status === 'blocked' &&
395
+ state.openEscalations.length > 0 &&
396
+ !reviseSpecPending(state) &&
397
+ !(epilogueLeaf(state) && !epilogueWorkDue(build))
398
+ )
399
+ }
400
+
401
+ /** A nonterminal leaf holds a slot when it was admitted since its last
402
+ * release and either does not wait on the outside world or waits only on
403
+ * escalations that work Autobuild started still outruns (`escalationCarried`).
404
+ * No lease or provisioning marker enters: a runner left over from before a
405
+ * release never takes the slot back. */
406
+ export function leafHoldsSlot(build: LeafSlotFacts): boolean {
407
+ return (
408
+ !terminal(build.state) &&
409
+ slotAdmitted(build.state) &&
410
+ (!leafOutsideWait(build) ||
411
+ (blockedOnlyByEscalations(build) && escalationCarried(escalationCarryInput(build.state))))
174
412
  )
175
413
  }
176
414
 
@@ -221,33 +459,153 @@ export function settlementDue(state: BuildState): boolean {
221
459
  )
222
460
  }
223
461
 
462
+ /** One runner need of a node and the slot request that admits it. The key
463
+ * names the work, not when a tick saw it, so it stays the same from admission
464
+ * until that work is done (SPEC §12 "What holds a slot"). */
465
+ export interface NodeSlotNeed {
466
+ request: 'verification' | 'reconcile' | 'propose'
467
+ key: string
468
+ }
469
+
470
+ function reconcileNeed(state: BuildState): NodeSlotNeed | undefined {
471
+ const restack = state.nodeRestack
472
+ const id = restack?.active?.id ?? restack?.conflict?.id
473
+ return id === undefined ? undefined : { request: 'reconcile', key: `reconcile:${id}` }
474
+ }
475
+
476
+ function proposeNeed(state: BuildState): NodeSlotNeed | undefined {
477
+ const proposal = state.optimization?.proposal
478
+ return proposal === undefined ? undefined : { request: 'propose', key: `propose:${proposal.id}` }
479
+ }
480
+
481
+ function measurementNeed(state: BuildState): NodeSlotNeed | undefined {
482
+ const key = nodeMeasurementNeed(state)
483
+ return key === undefined ? undefined : { request: 'verification', key }
484
+ }
485
+
486
+ function integrationNeed(state: BuildState): NodeSlotNeed | undefined {
487
+ const cycle = state.integration?.cycle
488
+ return cycle === undefined
489
+ ? undefined
490
+ : { request: 'verification', key: `integration:${cycle.id}:${cycle.seq}` }
491
+ }
492
+
493
+ /** Every runner need a node has now, reconcile first: an active restack (held
494
+ * across the kernel's replay of the items between conflicts, so the slot it
495
+ * was admitted for is not dropped and retaken without admission), a starting
496
+ * or progress measurement, an undeposited proposal, and an integration cycle
497
+ * that needs a runner. Pure over reduced state, with no clock. Completing the
498
+ * work removes its key, which releases a slot admitted for it with no write. */
499
+ export function nodeRunnerNeeds(state: BuildState): NodeSlotNeed[] {
500
+ if (state.kind !== 'node' || terminal(state)) return []
501
+ const needs: NodeSlotNeed[] = []
502
+ const reconcile = reconcileNeed(state)
503
+ if (reconcile) needs.push(reconcile)
504
+ const measurement = measurementNeed(state)
505
+ if (measurement) needs.push(measurement)
506
+ if (proposeRunDue(state.optimization)) needs.push(proposeNeed(state)!)
507
+ if (integrationNeedsRunner(state)) needs.push(integrationNeed(state)!)
508
+ return needs
509
+ }
510
+
511
+ /** A node waiting on the outside world, which holds no slot: blocked on a
512
+ * question (a restack conflict's escalation included) or paused with no
513
+ * resume requested. The janitor's own escalation is not an outside wait: the
514
+ * dispatcher keeps retrying the work it blocks, so Autobuild still owes the
515
+ * next move. */
516
+ export function nodeOutsideWait(state: BuildState): boolean {
517
+ return humanWait(state, state.statusWithoutJanitorEscalation ?? state.status)
518
+ }
519
+
520
+ /** A nonterminal node holds a slot when it does not wait on the outside world,
521
+ * was admitted since its last release, and the runner need that admission
522
+ * named is still one it has (SPEC §12 "What holds a slot"). A workspace, a
523
+ * lease or a provisioning marker never enters; finished work releases the
524
+ * slot by dropping its need. A value from an older server, which carries no
525
+ * slot seqs, falls back to the version-window rule: a runner need with a
526
+ * provisioning marker or live lease. */
527
+ export function nodeHoldsSlot(build: CapacityBuild, now: Date): boolean {
528
+ const { state } = build
529
+ if (state.kind !== 'node' || terminal(state) || nodeOutsideWait(state)) return false
530
+ const needs = nodeRunnerNeeds(state)
531
+ if (state.slotAdmittedSeq === undefined) return needs.length > 0 && runnerAllocated(build, now)
532
+ const need = state.slotAdmittedNeed
533
+ return slotAdmitted(state) && need !== undefined && needs.some((entry) => entry.key === need)
534
+ }
535
+
536
+ /** The version transition (SPEC §15 `slot.admitted`): a runner an older
537
+ * dispatcher launched before node admissions were recorded, which that
538
+ * dispatcher counted as holding a slot. The node was never admitted under
539
+ * this model, does not wait on the outside world, has a runner need (a
540
+ * reconcile only with its conflict open, as the older rule held) and runner
541
+ * evidence later than its last release: an open execution or provisioning
542
+ * marker, or, with neither and no release ever recorded, a live lease. With
543
+ * a pause or abort pending, only a runner anchored before the earliest one
544
+ * counts; one started after it only acknowledges. The dispatcher records its
545
+ * admission once (`legacyNodeRunnerNeed`), after which `slotAdmittedNeed` is
546
+ * set and this never matches the node again. */
547
+ export function legacyNodeRunner(build: CapacityBuild, now: Date): boolean {
548
+ return legacyNodeRunnerNeed(build, now) !== undefined
549
+ }
550
+
551
+ /** The need a legacy node runner (`legacyNodeRunner`) is adopted for. */
552
+ export function legacyNodeRunnerNeed(build: CapacityBuild, now: Date): NodeSlotNeed | undefined {
553
+ const { state } = build
554
+ if (
555
+ state.kind !== 'node' ||
556
+ terminal(state) ||
557
+ state.slotAdmittedSeq === undefined ||
558
+ state.slotAdmittedNeed !== undefined ||
559
+ nodeOutsideWait(state)
560
+ )
561
+ return undefined
562
+ const need = nodeRunnerNeeds(state).find(
563
+ (entry) => entry.request !== 'reconcile' || state.nodeRestack?.conflict !== undefined,
564
+ )
565
+ if (need === undefined) return undefined
566
+ const start = state.openExecution?.seq ?? (build.provisioning ? build.provisioningSeq : undefined)
567
+ const lease =
568
+ build.record.lease !== undefined && Date.parse(build.record.lease.expiresAt) > now.getTime()
569
+ const evidence =
570
+ start !== undefined
571
+ ? start > (state.slotReleasedSeq ?? 0)
572
+ : lease && state.slotReleasedSeq === undefined
573
+ if (!evidence) return undefined
574
+ const controls = state.pendingCommands
575
+ .filter((command) => command.command === 'pause' || command.command === 'abort')
576
+ .map((command) => command.seq)
577
+ if (controls.length && (start === undefined || start >= Math.min(...controls))) return undefined
578
+ return need
579
+ }
580
+
224
581
  export function occupiesCapacity(build: CapacityBuild, now: Date): boolean {
225
582
  const { state } = build
226
583
  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
- )
584
+ if (state.kind !== 'node') return leafHoldsSlot(build)
585
+ return nodeHoldsSlot(build, now) || legacyNodeRunner(build, now)
233
586
  }
234
587
 
235
- /** A parked leaf's durable request for a runner, or undefined. */
236
- function leafSlotRequest(build: CapacityBuild, now: Date): SlotRequest | undefined {
588
+ /** The durable slot request of a leaf that holds none and no longer waits on
589
+ * the outside world, or undefined. */
590
+ export function leafSlotRequest(build: LeafSlotFacts): SlotRequest | undefined {
237
591
  const { state } = build
238
592
  if (
239
- !parkedLeaf(build, now) ||
240
- state.status === 'paused' ||
241
- state.status === 'blocked' ||
593
+ terminal(state) ||
594
+ leafHoldsSlot(build) ||
595
+ leafOutsideWait(build) ||
596
+ // Mixed-version deferral withholds every decision, admission included.
242
597
  (state.compatibility?.decisiveFacts ?? 0) > 0
243
598
  )
244
599
  return undefined
245
- // A parked leaf on a rewritten target needs a runner to leave the wait: it
600
+ // A leaf on a rewritten target needs a runner to leave the wait: it
246
601
  // reprovisions itself or raises its one escalation (SPEC §7.4).
247
602
  if (state.targetRewrite !== undefined) return 'resume'
248
603
  // A ticket wait parks a leaf mid-pipeline: it asks for a slot only once the
249
604
  // wait has ended, to resume the phase that declared it.
250
605
  if (waitParked(state)) return waitResumeDue(state) ? 'resume' : undefined
606
+ // Every other unfinished leaf an outside wait released resumes where it
607
+ // stopped: an answered escalation, a resumed pause, a landed spec revision.
608
+ if (!epilogueLeaf(state)) return 'resume'
251
609
  if (state.prState === 'conflicted') return 'reconcile'
252
610
  // A reopen asks for a slot once any replacement spec is published.
253
611
  if (reopenSpecPending(state)) return undefined
@@ -263,115 +621,87 @@ function leafSlotRequest(build: CapacityBuild, now: Date): SlotRequest | undefin
263
621
  return undefined
264
622
  }
265
623
 
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 {
624
+ /** A node's durable request for a slot it does not hold: the runner need it
625
+ * would be admitted for, or undefined. A node that holds its slot, or a
626
+ * legacy runner counted as holding one, requests nothing. */
627
+ export function nodeSlotNeed(build: CapacityBuild, now: Date): NodeSlotNeed | undefined {
270
628
  const { state } = build
271
- if (state.kind !== 'node') return leafSlotRequest(build, now)
272
629
  if (
630
+ state.kind !== 'node' ||
273
631
  state.status === 'done' ||
274
632
  state.status === 'aborted' ||
275
633
  state.status === 'paused' ||
276
634
  state.status === 'blocked' ||
277
635
  // Mixed-version deferral withholds every decision, admission included.
278
636
  (state.compatibility?.decisiveFacts ?? 0) > 0 ||
279
- allocated(build, now)
637
+ nodeHoldsSlot(build, now) ||
638
+ legacyNodeRunner(build, now)
280
639
  )
281
640
  return undefined
282
- if (state.nodeRestack?.conflict) return state.openEscalations.length ? undefined : 'reconcile'
283
- if (proposeStarted(state)) return 'propose'
641
+ if (state.nodeRestack?.conflict)
642
+ return state.openEscalations.length ? undefined : reconcileNeed(state)
643
+ if (proposeStarted(state)) return proposeNeed(state)
284
644
  // A node measurement (starting or progress) is admitted as a re-verify is.
285
- if (nodeMeasurementDue(state)) return 'verification'
645
+ if (nodeMeasurementDue(state)) return measurementNeed(state)
286
646
  // A stale request (stopped, spent or shrunk below its room) reserves
287
647
  // nothing; the dispatcher withdraws it. A started session was admitted
288
648
  // already and resumes whatever its eligibility.
289
- if (proposeAdmissible(state.optimization, now)) return 'propose'
290
- if (integrationAdmissible(state) && integrationNeedsRunner(state)) return 'verification'
649
+ if (proposeAdmissible(state.optimization, now)) return proposeNeed(state)
650
+ if (integrationAdmissible(state) && integrationNeedsRunner(state)) return integrationNeed(state)
291
651
  return undefined
292
652
  }
293
653
 
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)
654
+ /** A nonterminal build's slot state, or undefined when it is unknown: a
655
+ * `done` build reports none, and a value from a server older than durable
656
+ * admission (no `slotAdmittedSeq`, which every current reducer sets on
657
+ * `build.created`) was decided by older rules. A held slot outranks a
658
+ * request: an admitted node reports `held` until its need ends or it waits
659
+ * outside Autobuild. An aborted build in cleanup
660
+ * reports `none`. */
661
+ export function slotState(build: CapacityBuild, now: Date): SlotState | undefined {
662
+ const { state } = build
663
+ if (state.status === 'done' || state.slotAdmittedSeq === undefined) return undefined
664
+ if (occupiesCapacity(build, now)) return { state: 'held' }
665
+ const request = slotRequest(build, now)
666
+ if (!request) return { state: 'none' }
667
+ const priority = markedPriority(buildPriority(state))
668
+ return priority ? { state: 'requested', request, priority } : { state: 'requested', request }
669
+ }
670
+
671
+ /** The runner work a node has a slot for or is asking one for: its held need
672
+ * when it holds its slot, otherwise its request. The dispatcher starts or
673
+ * restarts the runner of a holder; a requester waits for admission. */
674
+ export function nodeRunnerWork(build: CapacityBuild, now: Date): NodeSlotNeed | undefined {
675
+ if (nodeHoldsSlot(build, now)) {
676
+ const held = build.state.slotAdmittedNeed
677
+ return (
678
+ nodeRunnerNeeds(build.state).find((need) => need.key === held) ??
679
+ nodeRunnerNeeds(build.state)[0]
316
680
  )
317
- return false
318
- if (parent.record.slug === node) return true
319
- target = parent.state.target
320
681
  }
321
- return false
682
+ return nodeSlotNeed(build, now)
322
683
  }
323
684
 
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() }
685
+ /** A node's or leaf's durable request for a slot it does not hold yet.
686
+ * Admission outranks ticket claims of the same priority, so this never
687
+ * depends on when a tick saw it. */
688
+ export function slotRequest(build: CapacityBuild, now: Date): SlotRequest | undefined {
689
+ if (build.state.kind !== 'node') return leafSlotRequest(build)
690
+ return nodeSlotNeed(build, now)?.request
346
691
  }
347
692
 
348
693
  export function dispatchCapacity(
349
694
  builds: readonly CapacityBuild[],
350
695
  configured: number,
351
696
  now: Date,
352
- identity: Identity = exactIdentity,
353
697
  options: {
354
- urgentClaims?: number
698
+ claims?: ClaimDemand
355
699
  openPrs?: OpenPrBackpressureInput
356
- startRequests?: Partial<Record<TicketStartPriority, number>>
700
+ startRequests?: Partial<Record<StartTier, number>>
357
701
  } = {},
358
702
  ): DispatchCapacity {
359
703
  const unique = [...new Map(builds.map((build) => [build.record.slug, build])).values()]
360
704
  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
705
  const waiting = (kind: 'node' | 'leaf') =>
376
706
  unique
377
707
  .flatMap((build) => {
@@ -379,12 +709,18 @@ export function dispatchCapacity(
379
709
  const request = slotRequest(build, now)
380
710
  if (!request) return []
381
711
  const waiter: SlotWaiter = { slug: build.record.slug, request }
382
- if (buildPriority(build.state) === 'urgent') waiter.priority = 'urgent'
712
+ const priority = markedPriority(buildPriority(build.state))
713
+ if (priority) waiter.priority = priority
383
714
  return [waiter]
384
715
  })
385
716
  .sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))
386
717
  const waitingNodes = waiting('node')
387
718
  const waitingBuilds = waiting('leaf')
719
+ const slots: Record<string, SlotState> = {}
720
+ for (const build of unique) {
721
+ const slot = slotState(build, now)
722
+ if (slot) slots[build.record.slug] = slot
723
+ }
388
724
  const backpressure = options.openPrs
389
725
  ? openPrBackpressure(
390
726
  unique,
@@ -395,67 +731,62 @@ export function dispatchCapacity(
395
731
  return {
396
732
  configured,
397
733
  occupied,
398
- effective: borrowingNodes.length ? Math.max(configured, occupied) : configured,
399
- borrowingNodes,
734
+ effective: configured,
735
+ borrowingNodes: [],
400
736
  ...(waitingNodes.length ? { waitingNodes } : {}),
401
737
  ...(waitingBuilds.length ? { waitingBuilds } : {}),
402
- ...(options.urgentClaims ? { urgentClaims: options.urgentClaims } : {}),
738
+ ...(options.claims?.urgent ? { urgentClaims: options.claims.urgent } : {}),
739
+ ...(options.claims?.high ? { highClaims: options.claims.high } : {}),
740
+ ...(options.claims?.normal ? { normalClaims: options.claims.normal } : {}),
403
741
  ...(backpressure ? { backpressure } : {}),
404
742
  ...startRequestsOf(options.startRequests),
743
+ slots,
405
744
  }
406
745
  }
407
746
 
408
747
  function startRequestsOf(
409
- demand: Partial<Record<TicketStartPriority, number>> | undefined,
748
+ demand: Partial<Record<StartTier, number>> | undefined,
410
749
  ): Pick<DispatchCapacity, 'startRequests'> {
411
- const startRequests: Partial<Record<TicketStartPriority, number>> = {}
412
- for (const tier of ['manual', 'urgent', 'normal'] as const)
413
- if (demand?.[tier]) startRequests[tier] = demand[tier]
750
+ const startRequests: Partial<Record<StartTier, number>> = {}
751
+ for (const tier of START_TIERS) if (demand?.[tier]) startRequests[tier] = demand[tier]
414
752
  return Object.keys(startRequests).length ? { startRequests } : {}
415
753
  }
416
754
 
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
- /** Slots reserved ahead of one parked waiter: manual start requests for
424
- * urgent work; for normal work, also every other urgent reservation, the
425
- * urgent start requests and the urgent ticket claims still waiting. A waiter
426
- * is admitted when `occupied + reservedAhead` is below the configured budget,
427
- * so the order waiters are visited in never matters across tiers. */
755
+ /** Slots reserved ahead of one parked waiter at level L: manual start
756
+ * requests, and for every level above L, that level's other waiters, its
757
+ * start requests and its ticket claims still waiting. A waiter is admitted
758
+ * when `occupied + reservedAhead` is below the configured budget, so the
759
+ * order waiters are visited in never matters across levels. */
428
760
  export function reservedAhead(
429
761
  capacity: DispatchCapacity,
430
- waiter: { slug: string; priority: TicketPriority },
762
+ waiter: { slug: string; priority: BuildPriority },
431
763
  ): number {
432
- if (waiter.priority === 'urgent') return startsOf(capacity, ['manual'])
433
- const urgent = (entry: SlotWaiter) => entry.priority === 'urgent' && entry.slug !== waiter.slug
764
+ const above = levelsAbove(waiter.priority)
765
+ const ahead = (entry: SlotWaiter) =>
766
+ entry.slug !== waiter.slug && above.includes(waiterLevel(entry))
434
767
  return (
435
- (capacity.waitingNodes ?? []).filter((node) => nodeReserves(node) && urgent(node)).length +
436
- (capacity.waitingBuilds ?? []).filter(urgent).length +
437
- (capacity.urgentClaims ?? 0) +
438
- startsOf(capacity, ['manual', 'urgent'])
768
+ (capacity.waitingNodes ?? []).filter(ahead).length +
769
+ (capacity.waitingBuilds ?? []).filter(ahead).length +
770
+ above.reduce((sum, level) => sum + claimsAt(capacity, level), 0) +
771
+ startsOf(capacity, tiersAbove(waiter.priority))
439
772
  )
440
773
  }
441
774
 
442
775
  type CapacityAdjust = {
443
776
  settled?: ReadonlySet<string>
444
- denied?: ReadonlyMap<string, TicketPriority>
777
+ denied?: ReadonlyMap<string, BuildPriority>
445
778
  }
446
779
 
447
- /** Waiters reserving a slot ahead of claims of one priority: urgent waiters
448
- * only for urgent claims, every waiter for normal ones. */
780
+ /** Waiters reserving a slot ahead of claims of one level: every waiter at
781
+ * that level or above. */
449
782
  function waitersAhead(
450
783
  capacity: DispatchCapacity,
451
784
  adjust: CapacityAdjust,
452
- priority: TicketPriority,
785
+ priority: BuildPriority,
453
786
  ): number {
454
- const counts = (entry: { priority?: TicketPriority }) =>
455
- priority === 'normal' || entry.priority === 'urgent'
456
- const nodes = (capacity.waitingNodes ?? []).filter(
457
- (node) => nodeReserves(node) && counts(node),
458
- ).length
787
+ const rank = priorityRank(priority)
788
+ const counts = (entry: { priority?: BuildPriority }) => priorityRank(waiterLevel(entry)) <= rank
789
+ const nodes = (capacity.waitingNodes ?? []).filter(counts).length
459
790
  const builds = new Set(
460
791
  (capacity.waitingBuilds ?? [])
461
792
  .filter((build) => counts(build) && !adjust.settled?.has(build.slug))
@@ -466,67 +797,70 @@ function waitersAhead(
466
797
  return nodes + builds.size
467
798
  }
468
799
 
469
- /** Slots left for ordinary ticket claims of one priority. Parked work of the
470
- * same or a higher priority reserves ahead of them: an urgent claim waits only
471
- * for urgent parked work, a normal claim for every waiter. Pending start
472
- * 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
477
- * occupied builds.
800
+ /** Slots left for ordinary ticket claims of one level. Parked work of the
801
+ * same or a higher level reserves ahead of them, and so do pending start
802
+ * requests of the same or a higher tier, manual ones included. A waiting
803
+ * node's or parked build's request occupies nothing, so each one reserves a
804
+ * slot. Never more than the configured budget minus occupied builds. Claims
805
+ * of a higher level go first because the dispatcher visits ready tickets in
806
+ * level order and every claim spends every level's budget.
478
807
  *
479
808
  * The dispatcher refines the projection with its own decisions this tick:
480
809
  * `settled` drops waiters it found waiting for their PR, `denied` adds
481
- * builds its admission gate turned away, with their priority. Status surfaces
810
+ * builds its admission gate turned away, with their level. Status surfaces
482
811
  * omit `adjust`. */
483
812
  export function intakeCapacity(
484
813
  capacity: DispatchCapacity,
485
814
  adjust: CapacityAdjust = {},
486
- priority: TicketPriority = 'normal',
815
+ priority: BuildPriority = 'normal',
487
816
  ): number {
488
817
  return (
489
818
  capacity.configured -
490
819
  capacity.occupied -
491
820
  waitersAhead(capacity, adjust, priority) -
492
- startsOf(
493
- capacity,
494
- priority === 'urgent' ? ['manual', 'urgent'] : ['manual', 'urgent', 'normal'],
495
- )
821
+ startsOf(capacity, tiersAtOrAbove(priority))
496
822
  )
497
823
  }
498
824
 
499
825
  /** Slots left for operator start requests of one tier: a manual request
500
- * waits for nothing; an urgent one for urgent parked work and manual
501
- * requests; a normal one for every waiter, the manual and urgent requests and
502
- * the urgent ticket claims still waiting. `adjust` is `intakeCapacity`'s. */
826
+ * waits for nothing; one at level L for parked work at L or above, every
827
+ * start request of a higher tier (manual included) and the ticket claims of
828
+ * every higher level still waiting. `adjust` is `intakeCapacity`'s. */
503
829
  export function startCapacity(
504
830
  capacity: DispatchCapacity,
505
831
  adjust: CapacityAdjust,
506
- tier: TicketStartPriority,
832
+ tier: StartTier,
507
833
  ): number {
508
834
  const free = capacity.configured - capacity.occupied
509
835
  if (tier === 'manual') return free
510
- if (tier === 'urgent')
511
- return free - waitersAhead(capacity, adjust, 'urgent') - startsOf(capacity, ['manual'])
512
836
  return (
513
837
  free -
514
- waitersAhead(capacity, adjust, 'normal') -
515
- startsOf(capacity, ['manual', 'urgent']) -
516
- (capacity.urgentClaims ?? 0)
838
+ waitersAhead(capacity, adjust, tier) -
839
+ startsOf(capacity, tiersAbove(tier)) -
840
+ levelsAbove(tier).reduce((sum, level) => sum + claimsAt(capacity, level), 0)
517
841
  )
518
842
  }
519
843
 
844
+ /** The levels below one level, as prose: `high, normal and low`. */
845
+ function levelsBelowText(level: BuildPriority): string {
846
+ const below = TICKET_PRIORITIES.slice(priorityRank(level) + 1)
847
+ return below.length <= 1
848
+ ? below.join('')
849
+ : `${below.slice(0, -1).join(', ')} and ${below[below.length - 1]}`
850
+ }
851
+
520
852
  /** Shared wording for one node or parked build waiting on a runner slot. */
521
- export function slotWaitText(request: SlotRequest, priority: TicketPriority = 'normal'): string {
522
- return priority === 'urgent'
523
- ? `urgent ${request} waiting for a slot ahead of normal work`
524
- : `${request} waiting for a slot ahead of normal ticket claims`
853
+ export function slotWaitText(request: SlotRequest, priority: BuildPriority = 'normal'): string {
854
+ if (priority === 'urgent')
855
+ return `urgent ${request} waiting for a slot ahead of ${levelsBelowText('urgent')} work`
856
+ return priority === 'normal'
857
+ ? `${request} waiting for a slot ahead of normal ticket claims`
858
+ : `${priority} ${request} waiting for a slot ahead of ${priority} ticket claims`
525
859
  }
526
860
 
527
861
  /** Shared wording for pending operator start requests, every node and parked
528
- * build waiting on a runner slot, and urgent ticket claims waiting ahead of
529
- * normal parked work, in slot admission order, or `''`. */
862
+ * build waiting on a runner slot, and ticket claims waiting ahead of
863
+ * lower-level parked work, in slot admission order, or `''`. */
530
864
  export function waitingExplanation(
531
865
  capacity?: DispatchCapacity,
532
866
  opts: { requests?: boolean } = {},
@@ -534,36 +868,49 @@ export function waitingExplanation(
534
868
  const label = (entry: SlotWaiter) => {
535
869
  const notes = [
536
870
  ...(opts.requests ? [entry.request] : []),
537
- ...(entry.priority === 'urgent' ? ['urgent'] : []),
871
+ ...(entry.priority !== undefined ? [entry.priority] : []),
538
872
  ]
539
873
  return notes.length ? `${entry.slug} (${notes.join(', ')})` : entry.slug
540
874
  }
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
- ]
875
+ const clause = (noun: string, level: BuildPriority, waiting: SlotWaiter[]) =>
876
+ waiting.length
877
+ ? [
878
+ `${waiting.length} ${noun}${waiting.length === 1 ? '' : 's'} waiting for a slot ahead of ${level} ticket claims: ${waiting.map(label).join(', ')}`,
879
+ ]
880
+ : []
881
+ const parked = (level: BuildPriority) => {
882
+ const of = (waiting: SlotWaiter[] | undefined) =>
883
+ (waiting ?? []).filter((entry) => waiterLevel(entry) === level)
547
884
  return [
548
- `${waiting.length} ${noun}${waiting.length === 1 ? '' : 's'} waiting for a slot ahead of normal ticket claims: ${ordered.map(label).join(', ')}`,
885
+ ...clause('node', level, of(capacity?.waitingNodes)),
886
+ ...clause('parked build', level, of(capacity?.waitingBuilds)),
549
887
  ]
550
888
  }
551
- const urgentClaims = capacity?.urgentClaims ?? 0
552
- const starts = (tier: TicketStartPriority, waiting: string) => {
889
+ const plural = (count: number) => (count === 1 ? '' : 's')
890
+ const starts = (tier: StartTier) => {
553
891
  const count = capacity?.startRequests?.[tier] ?? 0
554
- return count ? [`${count} ${tier} start request${count === 1 ? '' : 's'} ${waiting}`] : []
892
+ if (!count) return []
893
+ const waiting =
894
+ tier === 'manual'
895
+ ? 'waiting ahead of all other work'
896
+ : tier === 'low'
897
+ ? 'waiting for a slot'
898
+ : `waiting ahead of ${levelsBelowText(tier)} parked work`
899
+ return [`${count} ${tier} start request${plural(count)} ${waiting}`]
555
900
  }
556
- return [
557
- ...starts('manual', 'waiting ahead of all other work'),
558
- ...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
- ...(urgentClaims
901
+ const claims = (level: BuildPriority) => {
902
+ const count = capacity ? claimsAt(capacity, level) : 0
903
+ return count
563
904
  ? [
564
- `${urgentClaims} urgent ticket claim${urgentClaims === 1 ? '' : 's'} waiting ahead of normal parked work`,
905
+ `${count} ${level} ticket claim${plural(count)} waiting ahead of ${levelsBelowText(level)} parked work`,
565
906
  ]
566
- : []),
907
+ : []
908
+ }
909
+ // Slot admission order (SPEC §12): manual starts, then for each level its
910
+ // parked work and its claims (start requests first).
911
+ return [
912
+ ...starts('manual'),
913
+ ...TICKET_PRIORITIES.flatMap((level) => [...parked(level), ...starts(level), ...claims(level)]),
567
914
  ].join('; ')
568
915
  }
569
916
 
@@ -571,10 +918,6 @@ export function waitingExplanation(
571
918
  export function capacityExplanation(capacity?: DispatchCapacity): string {
572
919
  if (!capacity) return ''
573
920
  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
921
  const waiting = waitingExplanation(capacity)
579
922
  if (waiting) clauses.push(waiting)
580
923
  const backpressure = backpressureExplanation(capacity.backpressure)