@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
@@ -867,7 +867,7 @@ export const TOOLS: readonly ToolEntry[] = [
867
867
  'builds.list',
868
868
  'List one repository’s builds, newest first, with effective status derived from the build log.',
869
869
  buildListInput,
870
- 'JSON array of build summaries: slug, ticket ref, effective status, phase/round/attempt, PR number/url/state, updatedAt, lease health, durable-event progress, any ticket wait (`wait` with its state and tickets; `waitOnly` when the wait is the only open escalation), and an optimization node’s objective progress (`objective`).',
870
+ 'JSON array of build summaries: slug, ticket ref, effective status, phase/round/attempt, PR number/url/state, updatedAt, lease health, durable-event progress, any ticket wait (`wait` with its state and tickets; `waitOnly` when the wait is the only open escalation), an optimization node’s objective progress (`objective`), and each nonterminal build’s slot state (`slot`: `{state: "held"}`, `{state: "requested", request, priority?: "urgent"}` or `{state: "none"}`; absent means unknown, never none).',
871
871
  async (raw, ctx) => {
872
872
  const input = raw as z.infer<typeof buildListInput>
873
873
  return listOperatorBuilds({
@@ -882,7 +882,7 @@ export const TOOLS: readonly ToolEntry[] = [
882
882
  'builds.get',
883
883
  'Show detailed state for one build: open escalations, verify progress, PR lifecycle, lease health, and the dashboard row.',
884
884
  buildDetailInput,
885
- '{detail, dashboardRow}: the full build detail projection and the dashboard row a terminal dashboard would render (null when the build has no dashboard row). An optimization node carries its objective progress as `detail.objective` and `dashboardRow.objectiveRow`.',
885
+ '{detail, dashboardRow}: the full build detail projection and the dashboard row a terminal dashboard would render (null when the build has no dashboard row). An optimization node carries its objective progress as `detail.objective` and `dashboardRow.objectiveRow`. A nonterminal build reports its slot state as `detail.slot` and `dashboardRow.slot`, shaped as in builds.list.',
886
886
  async (raw, ctx) => {
887
887
  const input = raw as z.infer<typeof buildDetailInput>
888
888
  return getOperatorBuild({
@@ -1152,7 +1152,7 @@ export const TOOLS: readonly ToolEntry[] = [
1152
1152
  'repository.status',
1153
1153
  'Report one repository’s durable dispatcher settings and journal state.',
1154
1154
  repositoryStatusInput,
1155
- 'The repository status projection: dispatcherRunning is true for a holder, expired holder or unfinished draining handoff; ticket intake, repository-wide pause, claim-time auto-merge default, and the harvest/dispatch journal state the sessionless CLI and dashboard read. operator.presence is "unavailable" here because this tool does not load presence registrations; that is not evidence that no operator is present.',
1155
+ 'The repository status projection: dispatcherRunning is true for a holder, expired holder or unfinished draining handoff; ticket intake, repository-wide pause, claim-time auto-merge default, and the harvest/dispatch journal state the sessionless CLI and dashboard read. capacity.slots maps each nonterminal build to its slot state, shaped as in builds.list; occupied counts its held entries. operator.presence is "unavailable" here because this tool does not load presence registrations; that is not evidence that no operator is present.',
1156
1156
  async (raw, ctx) => {
1157
1157
  const input = raw as z.infer<typeof repositoryStatusInput>
1158
1158
  return getRepositoryStatus(ctx.store, input.repo)
@@ -406,7 +406,8 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
406
406
  })
407
407
  // Its own process group, so a cancel stops setup and its children
408
408
  // together and releases the pipes awaited below (mirrors the real
409
- // provider).
409
+ // provider). A cancel also waits for the group to be gone, so close
410
+ // returns only once no setup process remains.
410
411
  const proc = Bun.spawn(['sh', '-c', this.sandboxSetupCommand], {
411
412
  cwd: identity.workspacePath,
412
413
  stdin: 'ignore',
@@ -415,7 +416,10 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
415
416
  env: this.sandboxEnv(),
416
417
  detached: true,
417
418
  })
418
- const onAbort = (): void => void terminateProcessGroup(proc.pid)
419
+ let terminating: Promise<boolean> | undefined
420
+ const onAbort = (): void => {
421
+ terminating ??= terminateProcessGroup(proc.pid)
422
+ }
419
423
  if (signal?.aborted) onAbort()
420
424
  else signal?.addEventListener('abort', onAbort, { once: true })
421
425
  const [stdout, stderr, exitCode] = await Promise.all([
@@ -423,7 +427,15 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
423
427
  new Response(proc.stderr).text(),
424
428
  proc.exited,
425
429
  ]).finally(() => signal?.removeEventListener('abort', onAbort))
426
- if (signal?.aborted) throw new SandboxCancelledError()
430
+ if (signal?.aborted) {
431
+ // The pipes close when the last member exits, before it is reaped;
432
+ // a killed-but-unreaped member (a zombie re-parented to init) still
433
+ // answers kill(pid, 0). Wait for the whole group to be reaped so
434
+ // close returns only once no setup process remains. A `false`
435
+ // result (a member stuck past SIGKILL) still settles as cancelled.
436
+ await terminating
437
+ throw new SandboxCancelledError()
438
+ }
427
439
  if (exitCode !== 0) {
428
440
  throw new SandboxOperationError(
429
441
  'provision',
@@ -111,19 +111,27 @@ import {
111
111
  dispatchCapacity,
112
112
  epilogueLeaf,
113
113
  intakeCapacity,
114
- nodeCapacity,
115
- occupiesCapacity,
114
+ leafHoldsSlot,
115
+ escalationCarryInput,
116
+ leafOutsideWait,
117
+ leafSlotRequest,
118
+ legacyNodeRunner,
119
+ legacyNodeRunnerNeed,
120
+ nodeHoldsSlot,
121
+ nodeRunnerWork,
122
+ nodeSlotNeed,
116
123
  reservedAhead,
117
124
  settlementDue,
118
125
  settlementKey,
119
- slotRequest,
120
126
  startCapacity,
121
127
  startClaimDemand,
122
128
  strandedNodeWorkspace,
123
129
  urgentClaimDemand,
124
130
  type CapacityBuild,
125
131
  type DispatchCapacity,
132
+ type NodeSlotNeed,
126
133
  } from '../kernel/dispatch-capacity'
134
+ import { launchInFlight } from '../kernel/verify-stage-state'
127
135
  import { attemptCreationKey } from '../kernel/attempt-creation-key'
128
136
  import {
129
137
  ExecutionFactsMissingError,
@@ -1290,6 +1298,9 @@ export class Dispatcher {
1290
1298
  * "Slot admission order"). Nothing was written for them;
1291
1299
  * `admitDeferredParked` retries each through its generic path. */
1292
1300
  private readonly deferredAdmissions = new Map<string, 'leaf' | 'node' | 'proposer'>()
1301
+ /** Nodes `admitWaitingNodes` admitted in its current verification pass, so
1302
+ * proposer admission counts them even when provisioning or launch failed. */
1303
+ private passNodeAdmissions: Set<string> | undefined
1293
1304
  /** Per tick: admission may defer normal parked work. Opened by `runTick`
1294
1305
  * when claims can run, closed once urgent claims were evaluated. */
1295
1306
  private admissionBoundary = false
@@ -1992,7 +2003,7 @@ export class Dispatcher {
1992
2003
  // checked, needs the pass.
1993
2004
  const now = this.deps.clock()
1994
2005
  const measured = await this.capacityBuilds(launched, true)
1995
- const projection = dispatchCapacity(measured, config.capacity, now, undefined, {
2006
+ const projection = dispatchCapacity(measured, config.capacity, now, {
1996
2007
  urgentClaims: this.urgentClaims(),
1997
2008
  startRequests: this.startClaims(),
1998
2009
  })
@@ -2487,7 +2498,8 @@ export class Dispatcher {
2487
2498
  if (!this.accountsAvailable()) return 'already-active'
2488
2499
  if (await this.forgeCoolingDown()) return 'already-active'
2489
2500
  if (await deferMixedVersion(this.store, slug)) return 'already-active'
2490
- const launchState = (await this.store.buildFacts(slug)).state
2501
+ const launchFacts = await this.store.buildFacts(slug)
2502
+ const launchState = launchFacts.state
2491
2503
  // A landed node has nothing left to run; the janitor settles it.
2492
2504
  if (nodeLanded(launchState)) return 'already-active'
2493
2505
  if (launchState.kind === 'node' && !launchState.nodeRestack?.conflict) {
@@ -2508,6 +2520,14 @@ export class Dispatcher {
2508
2520
  if (launched.has(slug)) return 'already-active'
2509
2521
  if (launchState.kind !== 'node' && (await this.leafAdmission(slug)) !== 'admit')
2510
2522
  return 'already-active'
2523
+ // Every node launch path (cascade, admission, sweep, startup resume) runs
2524
+ // only work the node holds a slot for (SPEC §12); abort and pause
2525
+ // acknowledgements stay ungated.
2526
+ if (launchState.kind === 'node') {
2527
+ const record = await this.store.getBuild(slug)
2528
+ if (record === null || !this.nodeRelaunchAdmitted(record, launchFacts))
2529
+ return 'already-active'
2530
+ }
2511
2531
  launched.add(slug)
2512
2532
  const facts = (await readBuildFacts(this.store, slug)).value
2513
2533
  // Callers reap and reprovision a flagged workspace; an agent never starts
@@ -4081,8 +4101,9 @@ export class Dispatcher {
4081
4101
  const builds: CapacityBuild[] = []
4082
4102
  for (const { record, digest } of await this.repoBuildDigests(true)) {
4083
4103
  if (digest.terminal) continue
4084
- // A leaf with a runner provisioning holds its slot and requests none
4085
- // whatever its state, so any read this tick serves it, launch or not.
4104
+ // A leaf with a runner provisioning or launched this tick has an
4105
+ // admission or launch record its served facts already include, so any
4106
+ // read this tick serves it, launch or not.
4086
4107
  const allocatedLeaf =
4087
4108
  digest.kind !== 'node' &&
4088
4109
  (this.continuations.has(record.slug) || !!launched?.has(record.slug))
@@ -4090,17 +4111,24 @@ export class Dispatcher {
4090
4111
  ? ((allocatedLeaf ? this.store.retainedBuildFacts(record.slug) : undefined) ??
4091
4112
  (await this.store.servedBuildFacts(record.slug)))
4092
4113
  : await this.store.buildFacts(record.slug)
4114
+ // A node's marker no longer holds a slot: it feeds the stranded
4115
+ // workspace release, the proposer skip and the anchor of a runner an
4116
+ // older dispatcher launched (`legacyNodeRunner`).
4117
+ const marker =
4118
+ digest.kind === 'node'
4119
+ ? served
4120
+ ? facts.provisionMarker
4121
+ : (await readBuildFacts(this.store, record.slug)).value.provisionMarker
4122
+ : undefined
4093
4123
  builds.push({
4094
4124
  record,
4095
4125
  state: facts.state,
4096
4126
  workspace: facts.workspace !== null,
4097
4127
  provisioning:
4098
4128
  digest.kind === 'node'
4099
- ? (served
4100
- ? facts.provisionMarker
4101
- : (await readBuildFacts(this.store, record.slug)).value.provisionMarker) !==
4102
- undefined
4129
+ ? marker !== undefined
4103
4130
  : this.continuations.has(record.slug) || !!launched?.has(record.slug),
4131
+ ...(marker !== undefined ? { provisioningSeq: marker.seq } : {}),
4104
4132
  restackDue: landingRestackDue(facts.state, facts.log),
4105
4133
  })
4106
4134
  }
@@ -4162,16 +4190,42 @@ export class Dispatcher {
4162
4190
  return priority === 'normal' && this.urgentBoundaryOpen() ? 'defer' : 'admit'
4163
4191
  }
4164
4192
 
4165
- /** Whether a leaf may reserve a runner now. A leaf that has not finished its
4166
- * pipeline already holds its slot, and abort and pause acknowledgements park
4167
- * at once, so only a finished leaf that must run again is gated: it needs
4168
- * a free slot among every other build, after urgent work ahead of it. A
4169
- * denial or deferral is recorded only in memory, for this tick's intake
4170
- * reservation; a deferral is retried after this tick's dispatch. */
4193
+ /** Whether a leaf may reserve a runner now (SPEC §12 "What holds a slot").
4194
+ * A leaf that holds its slot is admitted at once, and so are a leaf waiting
4195
+ * on the outside world and abort and pause acknowledgements, which are never
4196
+ * gated and confer no slot. Every other
4197
+ * leaf needs a free slot among every other build, after the work ahead of
4198
+ * it. Admission is the durable `slot.admitted` fact, appended on the state
4199
+ * this decision read before any lease claim, provisioning or launch, so a
4200
+ * crash after it keeps the slot; runner liveness never admits. A holding
4201
+ * leaf's launch appends one too, its launch record (`launchInFlight`),
4202
+ * unless one is already in flight or another runner's live lease will
4203
+ * refuse this launch; an acknowledgement appends none. A denial or
4204
+ * deferral is recorded only in memory, for this tick's intake reservation;
4205
+ * a deferral is retried after this tick's dispatch. */
4171
4206
  private async leafAdmission(slug: string): Promise<'admit' | 'wait' | 'defer'> {
4172
- const { state } = await this.store.buildFacts(slug)
4207
+ const facts = await this.store.buildFacts(slug)
4208
+ const { state } = facts
4209
+ const self = { state, restackDue: landingRestackDue(state, facts.log) }
4210
+ if (leafHoldsSlot(self)) {
4211
+ if (launchInFlight(escalationCarryInput(state))) return 'admit'
4212
+ // A live runner (a restarted dispatcher re-attempting a running build)
4213
+ // wins the lease claim, so this attempt launches nothing to record.
4214
+ const record = await this.store.getBuild(slug)
4215
+ if (record !== null && this.hasLiveExecutionLease(record)) return 'admit'
4216
+ const recorded = await this.store.appendIfCurrent(slug, state.lastSeq, {
4217
+ actor: DISPATCHER,
4218
+ type: 'slot.admitted',
4219
+ payload: {},
4220
+ })
4221
+ if (recorded === null) return 'wait'
4222
+ await this.store.servedBuildFacts(slug)
4223
+ return 'admit'
4224
+ }
4225
+ // A leaf waiting on the outside world can hold no slot, so what runs for
4226
+ // it (an acknowledgement) is neither gated nor admitted.
4173
4227
  if (
4174
- !(epilogueLeaf(state) || waitParked(state)) ||
4228
+ leafOutsideWait(self) ||
4175
4229
  state.pendingCommands.some(
4176
4230
  (command) => command.command === 'abort' || command.command === 'pause',
4177
4231
  )
@@ -4182,18 +4236,31 @@ export class Dispatcher {
4182
4236
  const capacity = this.deps.config.capacity
4183
4237
  const now = this.deps.clock()
4184
4238
  const priority = buildPriority(state)
4185
- const outcome = this.slotAdmission(
4239
+ let outcome = this.slotAdmission(
4186
4240
  slug,
4187
4241
  priority,
4188
4242
  dispatchCapacity(others, capacity, now).occupied,
4189
- dispatchCapacity(builds, capacity, now, undefined, {
4243
+ dispatchCapacity(builds, capacity, now, {
4190
4244
  urgentClaims: this.urgentClaims(),
4191
4245
  startRequests: this.startClaims(),
4192
4246
  }),
4193
4247
  )
4194
4248
  if (outcome === 'admit') {
4195
- this.slotWaiters.delete(slug)
4196
- return 'admit'
4249
+ const request = leafSlotRequest(self)
4250
+ const admitted = await this.store.appendIfCurrent(slug, state.lastSeq, {
4251
+ actor: DISPATCHER,
4252
+ type: 'slot.admitted',
4253
+ payload: request === undefined ? {} : { request },
4254
+ })
4255
+ if (admitted !== null) {
4256
+ this.slotWaiters.delete(slug)
4257
+ // Retain the admitted facts, so this tick's capacity counts the
4258
+ // build as holding its slot from here on.
4259
+ await this.store.servedBuildFacts(slug)
4260
+ return 'admit'
4261
+ }
4262
+ // The state moved under the decision: decide again next tick.
4263
+ outcome = 'wait'
4197
4264
  }
4198
4265
  this.slotWaiters.set(slug, priority)
4199
4266
  if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
@@ -4234,10 +4301,13 @@ export class Dispatcher {
4234
4301
  else if (kind === 'node') {
4235
4302
  const builds = await this.capacityBuilds()
4236
4303
  const build = builds.find((entry) => entry.record.slug === slug)
4237
- if (build) await this.admitNode(build, this.deps.clock(), report, launched)
4304
+ // A deferred reconcile launches only through the cascade.
4305
+ if (build && nodeSlotNeed(build, this.deps.clock())?.request === 'reconcile')
4306
+ await this.cascadeNode(record, build.state, report, launched, opts)
4307
+ else if (build) await this.admitNode(build, this.deps.clock(), report, launched)
4238
4308
  } else {
4239
4309
  const builds = await this.capacityBuilds()
4240
- await this.admitProposers(builds, this.deps.clock(), 0, report, launched, opts, slug)
4310
+ await this.admitProposers(builds, this.deps.clock(), report, launched, opts, slug)
4241
4311
  }
4242
4312
  } catch (error) {
4243
4313
  rethrowAuthorityLapse(error)
@@ -4282,19 +4352,58 @@ export class Dispatcher {
4282
4352
  )
4283
4353
  await this.releaseStrandedNodeWorkspaces(builds, now, launched, report, opts)
4284
4354
  if (this.outOfBudget(opts)) return
4285
- const waiting = builds.filter(
4286
- (build) =>
4287
- slotRequest(build, now) === 'verification' ||
4288
- (nodeMeasurementDue(build.state) &&
4289
- !proposeStarted(build.state) &&
4290
- slotRequest({ ...build, workspace: false }, now) === 'verification'),
4291
- )
4292
- const before = launched.size
4293
- for (const build of waiting) {
4294
- if (this.outOfBudget(opts)) return
4295
- await this.admitNode(build, now, report, launched)
4355
+ await this.adoptLegacyNodeRunners(builds, now, report)
4356
+ // A node asking for a verification slot, and one admitted for
4357
+ // verification whose runner never started or was lost: nothing else
4358
+ // relaunches it.
4359
+ const waiting = builds.filter((build) => nodeRunnerWork(build, now)?.request === 'verification')
4360
+ const admitted = new Set<string>()
4361
+ this.passNodeAdmissions = admitted
4362
+ try {
4363
+ for (const build of waiting) {
4364
+ if (this.outOfBudget(opts)) return
4365
+ await this.admitNode(build, now, report, launched)
4366
+ }
4367
+ } finally {
4368
+ this.passNodeAdmissions = undefined
4369
+ }
4370
+ // A node admitted this pass holds its slot whatever its provisioning or
4371
+ // launch did: the proposers' capacity counts it from its durable facts,
4372
+ // and a holder that merely relaunched is already counted.
4373
+ for (const build of waiting)
4374
+ if (admitted.has(build.record.slug))
4375
+ build.state = (await this.store.servedBuildFacts(build.record.slug)).state
4376
+ await this.admitProposers(builds, now, report, launched, opts)
4377
+ }
4378
+
4379
+ /**
4380
+ * The version transition (SPEC §15 `slot.admitted`): record, once, the
4381
+ * admission of every node runner an older dispatcher launched without one
4382
+ * (`legacyNodeRunner`). The predicate counts such a runner as holding its
4383
+ * slot from the first tick, before this write; the fact keeps the slot
4384
+ * through a later crash or expired lease until that work is done. Pure over
4385
+ * the states this pass loaded, so nothing is read once no legacy runner
4386
+ * remains. An adopted entry is updated in place; a lost race is decided
4387
+ * again next pass.
4388
+ */
4389
+ private async adoptLegacyNodeRunners(
4390
+ builds: CapacityBuild[],
4391
+ now: Date,
4392
+ report: TickReport,
4393
+ ): Promise<void> {
4394
+ for (const build of builds) {
4395
+ const need = legacyNodeRunnerNeed(build, now)
4396
+ if (need === undefined) continue
4397
+ try {
4398
+ if (await this.admitNodeNeed(build.record.slug, build.state, need))
4399
+ build.state = (await this.store.servedBuildFacts(build.record.slug)).state
4400
+ } catch (error) {
4401
+ rethrowAuthorityLapse(error)
4402
+ report.janitorDiagnostics.push(
4403
+ `build ${build.record.slug}: node runner adoption failed — ${String(error)}`,
4404
+ )
4405
+ }
4296
4406
  }
4297
- await this.admitProposers(builds, now, launched.size - before, report, launched, opts)
4298
4407
  }
4299
4408
 
4300
4409
  /** One waiting node's admission: a measurement or its integration
@@ -4314,7 +4423,7 @@ export class Dispatcher {
4314
4423
  return
4315
4424
  await withForgeRequestContext({ build: record.slug }, async () => {
4316
4425
  try {
4317
- if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
4426
+ if ((await this.nodeAdmission(record.slug)) !== 'admit') return
4318
4427
  if (nodeMeasurementDue(state)) await this.prepareNodeMeasurement(record, report, launched)
4319
4428
  else await this.prepareIntegration(record, state, report, launched)
4320
4429
  } catch (error) {
@@ -4374,7 +4483,6 @@ export class Dispatcher {
4374
4483
  private async admitProposers(
4375
4484
  builds: CapacityBuild[],
4376
4485
  now: Date,
4377
- admittedThisPass: number,
4378
4486
  report: TickReport,
4379
4487
  launched: Set<string>,
4380
4488
  opts: TickOpts,
@@ -4387,11 +4495,11 @@ export class Dispatcher {
4387
4495
  (only === undefined || build.record.slug === only),
4388
4496
  )
4389
4497
  if (proposers.length === 0) return
4390
- const projection = dispatchCapacity(builds, this.deps.config.capacity, now, undefined, {
4498
+ const projection = dispatchCapacity(builds, this.deps.config.capacity, now, {
4391
4499
  urgentClaims: this.urgentClaims(),
4392
4500
  startRequests: this.startClaims(),
4393
4501
  })
4394
- let occupied = projection.occupied + admittedThisPass
4502
+ let occupied = projection.occupied
4395
4503
  for (const build of proposers) {
4396
4504
  if (this.outOfBudget(opts)) return
4397
4505
  const { record, state } = build
@@ -4418,18 +4526,19 @@ export class Dispatcher {
4418
4526
  await this.releaseWorkspace(record.slug, facts)
4419
4527
  return
4420
4528
  }
4421
- // A workspace already holds this node's slot (a proposer that lost
4422
- // its runner); otherwise it needs a free one.
4423
- const holding = build.workspace
4529
+ // An admitted proposer holds its slot (one that lost its runner
4530
+ // relaunches); otherwise it needs a free one.
4531
+ const holding = nodeHoldsSlot(build, now) || legacyNodeRunner(build, now)
4532
+ const need = holding ? undefined : nodeSlotNeed(build, now)
4424
4533
  if (
4425
4534
  (holding
4426
4535
  ? state.status === 'paused' || state.status === 'blocked'
4427
- : slotRequest(build, now) !== 'propose') ||
4536
+ : need?.request !== 'propose') ||
4428
4537
  !state.nodeOpened ||
4429
4538
  !janitorDue(state.janitor, now)
4430
4539
  )
4431
4540
  return
4432
- if (!holding) {
4541
+ if (need !== undefined) {
4433
4542
  if (!this.accountsAvailable()) return
4434
4543
  const outcome = this.slotAdmission(
4435
4544
  record.slug,
@@ -4439,6 +4548,7 @@ export class Dispatcher {
4439
4548
  )
4440
4549
  if (outcome === 'defer') this.deferredAdmissions.set(record.slug, 'proposer')
4441
4550
  if (outcome !== 'admit') return
4551
+ if (!(await this.admitNodeNeed(record.slug, state, need))) return
4442
4552
  occupied++
4443
4553
  }
4444
4554
  await this.launchProposer(record, report, launched)
@@ -4782,40 +4892,87 @@ export class Dispatcher {
4782
4892
  await this.recordExhausted(record.slug)
4783
4893
  }
4784
4894
 
4785
- /** A node's admission into a free slot. A verification or measurement
4786
- * request (`reserving`) yields to urgent work ahead of it and defers while
4787
- * urgent claims are unevaluated. A node that already holds its slot — a
4788
- * restack-conflict reconcile, or runner work that kept its workspace across
4789
- * a failed launch or expired lease — only needs the node's own room:
4790
- * priority orders free slots, never one the node owns. */
4791
- private async nodeHasCapacity(
4792
- slug: string,
4793
- reserving = true,
4794
- ): Promise<'admit' | 'wait' | 'defer'> {
4895
+ /** Whether a node may start runner work now (SPEC §12 "What holds a
4896
+ * slot"). A node that holds its slot is admitted at once: a relaunch after
4897
+ * a crashed runner or an expired lease, or continued provisioning. Every
4898
+ * other node's current request (`verification`, `reconcile` or `propose`)
4899
+ * needs a free slot among every other build, after the work ahead of it,
4900
+ * under the same tiers and urgent ordering as parked leaves. Admission is
4901
+ * the durable `slot.admitted {request, need}` fact, appended on the state
4902
+ * this decision read before anything is provisioned or launched, so a
4903
+ * crash or restart after it keeps the slot until that need is done. A
4904
+ * denial is recorded nowhere; a deferral is retried after this tick's
4905
+ * dispatch. */
4906
+ private async nodeAdmission(slug: string): Promise<'admit' | 'wait' | 'defer'> {
4795
4907
  const builds = await this.capacityBuilds()
4796
4908
  const now = this.deps.clock()
4797
- const identity = migrationIdentity(
4798
- this.store.repositoryFacts().ticketMigrations,
4799
- this.deps.tickets.name,
4800
- )
4801
- const { occupied } = nodeCapacity(builds, slug, now, identity)
4802
4909
  const node = builds.find((build) => build.record.slug === slug)
4803
- if (!reserving || (node && occupiesCapacity(node, now)))
4804
- return occupied < this.deps.config.capacity ? 'admit' : 'wait'
4910
+ if (node === undefined) return 'wait'
4911
+ if (nodeHoldsSlot(node, now) || legacyNodeRunner(node, now)) return 'admit'
4912
+ const need = nodeSlotNeed(node, now)
4913
+ if (need === undefined) return 'wait'
4914
+ const capacity = this.deps.config.capacity
4805
4915
  const outcome = this.slotAdmission(
4806
4916
  slug,
4807
- node ? buildPriority(node.state) : 'normal',
4808
- occupied,
4809
- dispatchCapacity(builds, this.deps.config.capacity, now, identity, {
4917
+ buildPriority(node.state),
4918
+ dispatchCapacity(
4919
+ builds.filter((build) => build.record.slug !== slug),
4920
+ capacity,
4921
+ now,
4922
+ ).occupied,
4923
+ dispatchCapacity(builds, capacity, now, {
4810
4924
  urgentClaims: this.urgentClaims(),
4811
4925
  startRequests: this.startClaims(),
4812
4926
  }),
4813
4927
  )
4928
+ if (outcome === 'admit')
4929
+ return (await this.admitNodeNeed(slug, node.state, need)) ? 'admit' : 'wait'
4814
4930
  if (outcome === 'defer' && !this.deferredAdmissions.has(slug))
4815
4931
  this.deferredAdmissions.set(slug, 'node')
4816
4932
  return outcome
4817
4933
  }
4818
4934
 
4935
+ /** Record a node's admission for one runner need on the state the decision
4936
+ * read; false when the state moved under it (decided again next tick).
4937
+ * The admitted facts are retained so this tick's capacity counts the node
4938
+ * as holding its slot. */
4939
+ private async admitNodeNeed(
4940
+ slug: string,
4941
+ state: BuildState,
4942
+ need: NodeSlotNeed,
4943
+ ): Promise<boolean> {
4944
+ const admitted = await this.store.appendIfCurrent(slug, state.lastSeq, {
4945
+ actor: DISPATCHER,
4946
+ type: 'slot.admitted',
4947
+ payload: { request: need.request, need: need.key },
4948
+ } satisfies EventWrite<'slot.admitted'>)
4949
+ if (admitted === null) return false
4950
+ this.passNodeAdmissions?.add(slug)
4951
+ await this.store.servedBuildFacts(slug)
4952
+ return true
4953
+ }
4954
+
4955
+ /** A node's runner may be relaunched by the sweep: it holds its slot (or is
4956
+ * a legacy runner counted as holding one), or an abort or pause awaits its
4957
+ * acknowledgement. */
4958
+ private nodeRelaunchAdmitted(record: BuildRecord, facts: CurrentBuildFacts): boolean {
4959
+ const { state } = facts
4960
+ if (
4961
+ state.pendingCommands.some(
4962
+ (command) => command.command === 'abort' || command.command === 'pause',
4963
+ )
4964
+ )
4965
+ return true
4966
+ const now = this.deps.clock()
4967
+ const build: CapacityBuild = {
4968
+ record,
4969
+ state,
4970
+ workspace: facts.workspace !== null,
4971
+ restackDue: landingRestackDue(state, facts.log),
4972
+ }
4973
+ return nodeHoldsSlot(build, now) || legacyNodeRunner(build, now)
4974
+ }
4975
+
4819
4976
  private hasLiveExecutionLease(record: BuildRecord): boolean {
4820
4977
  return (
4821
4978
  record.lease !== undefined &&
@@ -8257,6 +8414,9 @@ export class Dispatcher {
8257
8414
  // A finished leaf with work to run waits for a slot before anything is
8258
8415
  // reaped, provisioned or launched for it.
8259
8416
  if (runs && state.kind !== 'node' && (await this.leafAdmission(record.slug)) !== 'admit') return
8417
+ // A node relaunches only for work it holds a slot for: a retained
8418
+ // workspace confers none. Abort and pause acknowledgements are ungated.
8419
+ if (runs && state.kind === 'node' && !this.nodeRelaunchAdmitted(record, facts)) return
8260
8420
  // A finished parked leaf keeps its workspace until merge or close; a
8261
8421
  // stale environment is reaped only for an admitted replacement.
8262
8422
  // A leaf waiting on tickets, or on the dispatcher's check of its wait,
@@ -8612,13 +8772,10 @@ export class Dispatcher {
8612
8772
  engaged,
8613
8773
  )
8614
8774
  // Pending start requests reserve ahead of the ordinary claims they outrank.
8615
- const projection = dispatchCapacity(
8616
- capacityBuilds,
8617
- config.capacity,
8618
- this.deps.clock(),
8619
- undefined,
8620
- { openPrs: { policy: config.policy, engaged }, startRequests: this.startClaims() },
8621
- )
8775
+ const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
8776
+ openPrs: { policy: config.policy, engaged },
8777
+ startRequests: this.startClaims(),
8778
+ })
8622
8779
  const transition = backpressureTransition(
8623
8780
  backpressure,
8624
8781
  engaged,
@@ -9846,7 +10003,7 @@ export class Dispatcher {
9846
10003
  }
9847
10004
 
9848
10005
  if (!this.accountsAvailable()) return
9849
- if ((await this.nodeHasCapacity(record.slug, false)) !== 'admit') return
10006
+ if ((await this.nodeAdmission(record.slug)) !== 'admit') return
9850
10007
  // `launch()` refuses a flagged workspace and leaves the reap to its
9851
10008
  // callers; this is the node's caller for conflict work.
9852
10009
  const current = await this.replaceFlaggedWorkspace(record, facts, launched)
@@ -10149,7 +10306,7 @@ export class Dispatcher {
10149
10306
  await this.releaseWorkspace(record.slug, facts)
10150
10307
  return
10151
10308
  }
10152
- if ((await this.nodeHasCapacity(record.slug)) !== 'admit') return
10309
+ if ((await this.nodeAdmission(record.slug)) !== 'admit') return
10153
10310
  await this.observeIntegration(record.slug)
10154
10311
  state = (await this.store.buildFacts(record.slug)).state
10155
10312
  if (!integrationCurrent(state)) return
@@ -34,6 +34,7 @@ export const executionProgress = {
34
34
  'landing.native-applied': 'bookkeeping',
35
35
  'target.distance': 'bookkeeping',
36
36
  'pipeline.settled': 'bookkeeping',
37
+ 'slot.admitted': 'bookkeeping',
37
38
  'target.rewritten': 'bookkeeping',
38
39
  'target.rewrite-cleared': 'bookkeeping',
39
40
  'target.moved': 'bookkeeping',