@defrex/autobuild 1.5.0 → 1.7.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 (126) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +192 -24
  3. package/docs/agent-runtimes.md +1 -1
  4. package/docs/answering-blocked-builds.md +7 -4
  5. package/docs/architecture.md +100 -32
  6. package/docs/configuration-overview.md +10 -0
  7. package/docs/configuration.md +340 -10
  8. package/docs/dispatcher.md +2 -2
  9. package/docs/forges.md +1 -0
  10. package/docs/glossary.md +1 -1
  11. package/docs/operating.md +1 -1
  12. package/docs/operator-api.md +33 -10
  13. package/docs/operator-surfaces.md +6 -3
  14. package/docs/plugin-authoring.md +48 -6
  15. package/docs/remote-store-protocol.md +33 -10
  16. package/docs/restacking.md +16 -7
  17. package/docs/ticket-sources.md +34 -6
  18. package/docs/tickets.md +7 -1
  19. package/docs/troubleshooting.md +1 -1
  20. package/docs/workspaces.md +1 -1
  21. package/package.json +3 -3
  22. package/packages/core/src/cli/attention.ts +3 -0
  23. package/packages/core/src/cli/binary-direct.ts +1 -0
  24. package/packages/core/src/cli/dashboard/model.ts +14 -4
  25. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  26. package/packages/core/src/cli/dashboard/render.ts +3 -0
  27. package/packages/core/src/cli/dispatch-frontend.ts +10 -14
  28. package/packages/core/src/cli/dispatch-preflight.ts +5 -1
  29. package/packages/core/src/cli/dispatch-repository-feed.ts +145 -109
  30. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  31. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  32. package/packages/core/src/cli/dispatch.ts +377 -101
  33. package/packages/core/src/cli/help.ts +15 -6
  34. package/packages/core/src/cli/init-validation.ts +14 -1
  35. package/packages/core/src/cli/repo-lease.ts +225 -0
  36. package/packages/core/src/cli/repository-status.ts +40 -3
  37. package/packages/core/src/cli/status.ts +21 -13
  38. package/packages/core/src/cli/ticket.ts +22 -4
  39. package/packages/core/src/cli/wait.ts +4 -1
  40. package/packages/core/src/cli/watch.ts +17 -4
  41. package/packages/core/src/config/live.ts +4 -0
  42. package/packages/core/src/config/profiles.ts +96 -0
  43. package/packages/core/src/config/ready-assignee.ts +43 -11
  44. package/packages/core/src/config/roles.ts +33 -10
  45. package/packages/core/src/config/schema.ts +204 -26
  46. package/packages/core/src/events/catalog.ts +2 -0
  47. package/packages/core/src/events/compatibility.ts +3 -1
  48. package/packages/core/src/events/forge-degradation-policy.ts +16 -2
  49. package/packages/core/src/events/payloads.ts +23 -0
  50. package/packages/core/src/events/policy.ts +3 -0
  51. package/packages/core/src/events/repository.ts +19 -0
  52. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +267 -352
  53. package/packages/core/src/kernel/build-creation.ts +29 -0
  54. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  55. package/packages/core/src/kernel/engine.ts +13 -6
  56. package/packages/core/src/kernel/forge-health.ts +47 -0
  57. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  58. package/packages/core/src/kernel/guarded-forge.ts +76 -18
  59. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  60. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  61. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  62. package/packages/core/src/kernel/log-index.ts +1 -1
  63. package/packages/core/src/kernel/node-landing.ts +2 -1
  64. package/packages/core/src/kernel/node-parent.ts +2 -0
  65. package/packages/core/src/kernel/read-facts.ts +9 -1
  66. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  67. package/packages/core/src/kernel/reducer.ts +75 -4
  68. package/packages/core/src/kernel/ticket-preparation.ts +15 -8
  69. package/packages/core/src/operator/protocol.ts +10 -0
  70. package/packages/core/src/operator/query.ts +16 -13
  71. package/packages/core/src/operator/registry.ts +25 -5
  72. package/packages/core/src/operator/sandbox-host.ts +3 -0
  73. package/packages/core/src/operator/tickets.ts +15 -3
  74. package/packages/core/src/plugin-sdk/index.ts +4 -0
  75. package/packages/core/src/ports/forge/create.ts +6 -0
  76. package/packages/core/src/ports/forge/github-transport.ts +40 -3
  77. package/packages/core/src/ports/forge/github.ts +12 -1
  78. package/packages/core/src/ports/forge/workspace-ancestry.ts +60 -0
  79. package/packages/core/src/ports/forge-failure.ts +31 -2
  80. package/packages/core/src/ports/runner/routing.ts +66 -5
  81. package/packages/core/src/ports/tickets/assignees.ts +54 -0
  82. package/packages/core/src/ports/tickets/contract.ts +164 -4
  83. package/packages/core/src/ports/tickets/create.ts +35 -7
  84. package/packages/core/src/ports/tickets/github-fake.ts +18 -2
  85. package/packages/core/src/ports/tickets/github.ts +247 -29
  86. package/packages/core/src/ports/tickets/hosted-index.ts +1 -0
  87. package/packages/core/src/ports/tickets/operations.ts +6 -1
  88. package/packages/core/src/ports/tickets/tree.ts +12 -2
  89. package/packages/core/src/ports/tickets/update.ts +6 -2
  90. package/packages/core/src/ports/types.ts +37 -3
  91. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  92. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  93. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  94. package/packages/core/src/ports/workspace/vercel-sandbox.ts +12 -0
  95. package/packages/core/src/processes/build-child.ts +28 -7
  96. package/packages/core/src/processes/build-execution-state.ts +4 -1
  97. package/packages/core/src/processes/build-runner.ts +17 -2
  98. package/packages/core/src/processes/dispatcher.ts +329 -59
  99. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  100. package/packages/core/src/processes/harvest-child.ts +8 -2
  101. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  102. package/packages/core/src/processes/harvest-runner.ts +251 -17
  103. package/packages/core/src/processes/repo-view.ts +2 -0
  104. package/packages/core/src/scenarios/harness.ts +160 -36
  105. package/packages/core/src/store/reduced-reads.ts +10 -0
  106. package/packages/core/src/store/reducer-value-shapes.json +3339 -2898
  107. package/packages/core/src/store/remote/client.ts +21 -8
  108. package/packages/core/src/store/remote/index.ts +4 -0
  109. package/packages/core/src/store/remote/protocol.ts +7 -0
  110. package/packages/core/src/store/remote/released-clients.json +22 -0
  111. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  112. package/packages/core/src/store/remote/released-reducer-values/1.7.0.json +27366 -0
  113. package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
  114. package/packages/core/src/store/repo-state-events.ts +1 -0
  115. package/packages/core/src/store/types.ts +11 -0
  116. package/packages/core/src/testing/dispatch-read-budget.ts +84 -58
  117. package/packages/core/src/testing/index.ts +2 -0
  118. package/packages/core/src/testing/reduced-read-budget.ts +411 -11
  119. package/skills/guide/SKILL.md +166 -35
  120. package/skills/guide/references/operator-api.md +33 -10
  121. package/skills/guide/references/plugin-authoring.md +48 -6
  122. package/skills/guide/references/remote-store-protocol.md +33 -10
  123. package/skills/guide/references/restacking.md +16 -7
  124. package/skills/operate/SKILL.md +79 -14
  125. package/skills/tickets/SKILL.md +22 -4
  126. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,9 @@
1
1
  import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import {
3
+ isRepositoryAuthorityLapse,
4
+ RepositoryAuthorityLapsed,
5
+ rethrowAuthorityLapse,
6
+ } from '../cli/repo-lease'
2
7
  import { assertTargetOid, observeTarget } from '../kernel/target-observation'
3
8
  import {
4
9
  MissingAccountCredentialsError,
@@ -50,7 +55,16 @@ import {
50
55
  MixedVersionDeferral,
51
56
  } from '../kernel/mixed-version'
52
57
  import { guardForge, ForgeCooldown } from '../kernel/guarded-forge'
53
- import { janitorDeferral, recordJanitorFailure } from '../kernel/janitor-failure'
58
+ import {
59
+ escalationsBeyondJanitor,
60
+ janitorBlocked,
61
+ janitorDeferral,
62
+ janitorDue,
63
+ janitorStatus,
64
+ recordJanitorFailure,
65
+ withoutJanitorEscalation,
66
+ type JanitorOperation,
67
+ } from '../kernel/janitor-failure'
54
68
  import { KernelGitUnavailable, kernelGitUnavailableDetail } from '../kernel/kernel-git'
55
69
  import { isForgeFailure } from '../ports/forge-failure'
56
70
  import {
@@ -60,8 +74,11 @@ import {
60
74
  } from '../ports/forge-request-context'
61
75
  import {
62
76
  dispatchCapacity,
77
+ epilogueLeaf,
63
78
  intakeCapacity,
64
79
  nodeCapacity,
80
+ settlementDue,
81
+ settlementKey,
65
82
  slotRequest,
66
83
  type CapacityBuild,
67
84
  } from '../kernel/dispatch-capacity'
@@ -168,8 +185,9 @@ import type { EventPayload, PinnedAsset } from '../events/payloads'
168
185
  import type { IdSource } from '../ids'
169
186
  import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
170
187
  import type { AutoMergeDefaultFact } from '../kernel/auto-merge-default'
171
- import { decideNextFromFacts } from '../kernel/engine'
188
+ import { decideNextFromFacts, landingRestackDue } from '../kernel/engine'
172
189
  import { composeBuildConfig } from '../config/live'
190
+ import { profileConflictDiagnostic, selectProfile } from '../config/profiles'
173
191
  import { BUILD_EFFECTIVE_CONFIG_ARTIFACT, parseEffectiveBuildConfig } from './build-execution-state'
174
192
  import {
175
193
  DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS,
@@ -197,6 +215,7 @@ import {
197
215
  } from '../kernel/node-issue-links'
198
216
  import type { Exec, ExecResult } from '../ports/workspace/git-worktree'
199
217
  import type { ArtifactMeta, BuildDigest, BuildRecord, BuildStore, Clock } from '../store/types'
218
+ import { creationBuildSlug } from '../kernel/build-creation'
200
219
  import { preparePinnedAssets } from '../store/ticket-assets'
201
220
  import { resolveRepoOrigin } from '../cli/repo-state'
202
221
  import { specConformance } from '../spec-standard'
@@ -680,6 +699,11 @@ export interface TickOpts {
680
699
  export type LaunchRunnerResult = 'scheduled' | 'already-active'
681
700
 
682
701
  export interface DispatcherDeps {
702
+ /** Whether this process currently holds repository authority (SPEC §12).
703
+ * Synchronous and without I/O. Absent means always true. When false, the
704
+ * tick starts no further unit of work, and its durable new-work writes are
705
+ * refused with `RepositoryAuthorityLapsed`. */
706
+ holdsRepoAuthority?: () => boolean
683
707
  /** Current selected-account presence; no store reads. */
684
708
  missingAccounts?: () => MissingAccountCredential[]
685
709
  accountCredentialSource?: MissingAccountCredential['source']
@@ -1037,6 +1061,14 @@ export class Dispatcher {
1037
1061
  /** Process-local background provisioning, keyed by slug. A tick that sees a
1038
1062
  * slug here defers to the continuation; it never blocks on it. */
1039
1063
  private readonly continuations = new Map<string, ProvisionContinuation>()
1064
+ /** Per tick, rebuilt from durable state: builds launched so far, which
1065
+ * occupy a slot before their runner claims a lease. */
1066
+ private tickLaunched: ReadonlySet<string> = new Set()
1067
+ /** Per tick: finished leaves the admission gate turned away. Intake reserves their slots. */
1068
+ private readonly slotWaiters = new Set<string>()
1069
+ /** Per tick: parked leaves whose sweep decision was `wait awaiting-pr`. A
1070
+ * projected wait for one of these is one tick stale and reserves nothing. */
1071
+ private readonly parkedSettled = new Set<string>()
1040
1072
 
1041
1073
  // Batched confirmed landing evidence is shared across nodes for this tick.
1042
1074
  // Only durable availability facts authorize the shortcut after restart. The
@@ -1098,7 +1130,10 @@ export class Dispatcher {
1098
1130
  * loops consult this before starting each new forge/store transport call,
1099
1131
  * bounding the tick's overrun to the one call already in flight. */
1100
1132
  private outOfBudget(opts: TickOpts): boolean {
1101
- return opts.deadlineAt !== undefined && this.deps.clock().getTime() >= opts.deadlineAt
1133
+ return (
1134
+ (opts.deadlineAt !== undefined && this.deps.clock().getTime() >= opts.deadlineAt) ||
1135
+ this.deps.holdsRepoAuthority?.() === false
1136
+ )
1102
1137
  }
1103
1138
 
1104
1139
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
@@ -1175,6 +1210,8 @@ export class Dispatcher {
1175
1210
  this.integrationInputs = undefined
1176
1211
  this.integrationPublicationInputs = undefined
1177
1212
  this.nodePollingTickReads.clear()
1213
+ this.slotWaiters.clear()
1214
+ this.parkedSettled.clear()
1178
1215
  // One immutable config for this complete decision pass. A reload racing the
1179
1216
  // tick is observed by the next tick, never half-way through this one.
1180
1217
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
@@ -1185,6 +1222,7 @@ export class Dispatcher {
1185
1222
  /** Builds already launched this tick — a janitor/startup re-attach must
1186
1223
  * not be doubled by the sweep, nor a fresh dispatch by anything. */
1187
1224
  const launched = new Set<string>()
1225
+ this.tickLaunched = launched
1188
1226
  // One journal read for both repository-wide controls: a pause that lands
1189
1227
  // mid-tick takes effect on the next tick, matching intake (which the CLI
1190
1228
  // likewise samples before calling `tick`); the auto-merge default fact is
@@ -1447,9 +1485,15 @@ export class Dispatcher {
1447
1485
  if (record.ticket && digest.terminal === undefined) refs.push(record.ticket)
1448
1486
  }
1449
1487
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
1488
+ const conflicts = this.profileConflicts(
1489
+ listing.tickets.filter(
1490
+ (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
1491
+ ),
1492
+ )
1450
1493
  report.queued = listing.tickets.filter(
1451
1494
  (ticket) =>
1452
1495
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
1496
+ !conflicts.tickets.has(ticket) &&
1453
1497
  !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
1454
1498
  const ref = resolveTicketRef(
1455
1499
  this.store.repositoryFacts().ticketMigrations,
@@ -1460,8 +1504,8 @@ export class Dispatcher {
1460
1504
  return ref.source === ticket.ref.source && ref.id === ticket.ref.id
1461
1505
  }),
1462
1506
  ).length
1463
- report.invalidTickets = listing.diagnostics.length
1464
- report.ticketDiagnostics = [...listing.diagnostics]
1507
+ report.invalidTickets = listing.diagnostics.length + conflicts.diagnostics.length
1508
+ report.ticketDiagnostics = [...listing.diagnostics, ...conflicts.diagnostics]
1465
1509
  report.dependencyBlocked = 0
1466
1510
  report.dependencyDiagnostics = []
1467
1511
  report.creationWithheld = 0
@@ -1655,6 +1699,7 @@ export class Dispatcher {
1655
1699
  )
1656
1700
  return 'already-active'
1657
1701
  if (launched.has(slug)) return 'already-active'
1702
+ if (launchState.kind !== 'node' && !(await this.leafAdmission(slug))) return 'already-active'
1658
1703
  launched.add(slug)
1659
1704
  const facts = (await readBuildFacts(this.store, slug)).value
1660
1705
  // Callers reap and reprovision a flagged workspace; an agent never starts
@@ -1743,8 +1788,10 @@ export class Dispatcher {
1743
1788
  * execution is not supervised by this process is observed through the
1744
1789
  * owning provider. `lost`/`ended` reaps the disposable environment and
1745
1790
  * journals the close fact with the snapshot purge outcome; `running`
1746
- * leaves it — the guest is the live supervisor and holds the adopted
1747
- * repository lease, and the next pass reaps it after it ends. Until the
1791
+ * leaves it — the guest is the live supervisor and its authority is its
1792
+ * durable `harvest.execution.authorized`, not any invocation's repository
1793
+ * lease, which it leaves to dispatch; the next pass reaps it after it
1794
+ * ends. Until the
1748
1795
  * release is journaled, an open observable execution also suppresses
1749
1796
  * harvest launch (`liveForeignHarvestExecution`). The run itself needs no
1750
1797
  * settlement here: an interrupted run stays open in the journal, and the
@@ -1967,6 +2014,7 @@ export class Dispatcher {
1967
2014
  report.sandboxIdleStops += 1
1968
2015
  }
1969
2016
  } catch (error) {
2017
+ rethrowAuthorityLapse(error)
1970
2018
  // Contained: the next tick retries this environment.
1971
2019
  report.sandboxSettleFailures += 1
1972
2020
  report.janitorDiagnostics.push(
@@ -2012,7 +2060,7 @@ export class Dispatcher {
2012
2060
  autoMergeDefaultSeq?: number
2013
2061
  assets?: PinnedAsset[]
2014
2062
  },
2015
- ): Promise<'kicked' | 'in-flight' | 'foreign-live'> {
2063
+ ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait'> {
2016
2064
  const slug = record.slug
2017
2065
  if (!this.accountsAvailable()) return 'in-flight'
2018
2066
  if (this.continuations.has(slug)) return 'in-flight'
@@ -2033,8 +2081,12 @@ export class Dispatcher {
2033
2081
  }
2034
2082
  // Expired lease, failed attempt, or an old lease-less marker: adopt.
2035
2083
  }
2084
+ // A finished leaf waits for a slot before its continuation reserves one.
2085
+ // Nothing is written: the wait costs no attempt and raises no attention.
2086
+ if (tail === 'launch' && !(await this.leafAdmission(slug))) return 'slot-wait'
2036
2087
  const branch = record.branch ?? `ab/${slug}`
2037
2088
  const generation = events.workspaceGenerations
2089
+ if (this.deps.holdsRepoAuthority?.() === false) return 'in-flight'
2038
2090
  await this.store.append(slug, {
2039
2091
  actor: DISPATCHER,
2040
2092
  type: 'workspace.provision-started',
@@ -2173,8 +2225,13 @@ export class Dispatcher {
2173
2225
  const queued = (await readBuildFacts(store, slug)).value.state.status === 'queued'
2174
2226
  boundary = input.tail === 'dispatch' || queued ? 'dispatch' : 'launch'
2175
2227
  if (boundary === 'dispatch') await this.completeDispatchBoundaries(record, input.seed)
2228
+ // Deliberately ungated: admission was decided when this continuation
2229
+ // was kicked, and its lease and map entry have held the slot since.
2176
2230
  else if (this.accountsAvailable()) await this.startRunner(slug, emptyTickReport())
2177
2231
  } catch (error) {
2232
+ // A lapsed repository lease started nothing: no failure fact. The
2233
+ // finally releases the execution lease; the successor adopts the marker.
2234
+ if (isRepositoryAuthorityLapse(error)) return
2178
2235
  // Dispatch boundaries own their failure facts and exhaustion repair.
2179
2236
  // A failed tail read/write leaves durable unfinished work for the next
2180
2237
  // tick; it is not another provider workspace failure. Replacement
@@ -2295,6 +2352,7 @@ export class Dispatcher {
2295
2352
  try {
2296
2353
  await reportIntegrationFailures(this.store, record.slug)
2297
2354
  } catch (error) {
2355
+ rethrowAuthorityLapse(error)
2298
2356
  report.janitorDiagnostics.push(
2299
2357
  `build ${record.slug}: integration attention recovery failed — ${String(error)}`,
2300
2358
  )
@@ -2308,6 +2366,8 @@ export class Dispatcher {
2308
2366
  if (this.outOfBudget(opts)) break
2309
2367
  await withForgeRequestContext({ build: record.slug }, async () => {
2310
2368
  let previous: BuildState['janitor']
2369
+ // The stage in progress, named if this attempt's failure escalates.
2370
+ let operation: JanitorOperation = 'build state read'
2311
2371
  let attempted = false
2312
2372
  let failed = false
2313
2373
  try {
@@ -2323,12 +2383,8 @@ export class Dispatcher {
2323
2383
  (state.pr &&
2324
2384
  state.landing?.command &&
2325
2385
  state.landing.command.seq !== state.landing.acknowledgedSeq)
2326
- if (
2327
- !controlDue &&
2328
- previous &&
2329
- Date.parse(previous.nextAttemptAt) > this.deps.clock().getTime()
2330
- )
2331
- return
2386
+ // Read the clock only inside an episode, as before episodes could escalate.
2387
+ if (!controlDue && previous && !janitorDue(previous, this.deps.clock())) return
2332
2388
  if (mixedVersionDeferred(state)) {
2333
2389
  await deferMixedVersion(this.store, record.slug)
2334
2390
  return
@@ -2429,6 +2485,7 @@ export class Dispatcher {
2429
2485
  state.pr &&
2430
2486
  state.landing?.native?.operation
2431
2487
  ) {
2488
+ operation = 'native auto-merge cancellation'
2432
2489
  const path = this.forgeWorkspacePathOf(workspace)
2433
2490
  const observed = await this.deps.forge.getPrState(path, state.pr.number)
2434
2491
  observedPr = observed
@@ -2466,6 +2523,7 @@ export class Dispatcher {
2466
2523
  state.integration?.landing?.operation &&
2467
2524
  !state.integration.audit
2468
2525
  ) {
2526
+ operation = 'integration landing audit'
2469
2527
  await this.withKernelRepository((path) =>
2470
2528
  auditIntegrationLanding({
2471
2529
  store: this.store,
@@ -2479,6 +2537,7 @@ export class Dispatcher {
2479
2537
  }
2480
2538
  if (state.status === 'done') {
2481
2539
  if (digest.reclaimPending === true) {
2540
+ operation = 'PR attachment reclaim'
2482
2541
  await this.reclaimPrAttachments(record.slug, await history())
2483
2542
  }
2484
2543
  return
@@ -2488,6 +2547,7 @@ export class Dispatcher {
2488
2547
  state.pendingCommands.find((c) => c.command === 'abort') ??
2489
2548
  state.pendingCommands.at(0)
2490
2549
  if (command !== undefined && !executionLeaseLive) {
2550
+ operation = 'control command'
2491
2551
  await this.store.append(record.slug, {
2492
2552
  actor: DISPATCHER,
2493
2553
  type:
@@ -2498,16 +2558,19 @@ export class Dispatcher {
2498
2558
  : 'build.resumed',
2499
2559
  payload: {},
2500
2560
  })
2501
- if (command.command === 'abort')
2561
+ if (command.command === 'abort') {
2562
+ operation = 'abort cleanup'
2502
2563
  await this.cleanupAborted(record, await history(), report)
2564
+ }
2503
2565
  return
2504
2566
  }
2505
2567
  if (state.nodeOpened) {
2568
+ operation = 'target observation'
2506
2569
  let primed = false
2507
2570
  if (
2508
2571
  record.branch &&
2509
2572
  state.baseBranch &&
2510
- !((state.status === 'paused' || state.status === 'blocked') && !state.pr)
2573
+ !((state.status === 'paused' || janitorBlocked(state)) && !state.pr)
2511
2574
  ) {
2512
2575
  primed = await this.primeNodeReads(record, state, report)
2513
2576
  }
@@ -2521,6 +2584,7 @@ export class Dispatcher {
2521
2584
  )
2522
2585
  ).state !== 'open'
2523
2586
  ) {
2587
+ operation = 'PR check'
2524
2588
  await this.checkPr(
2525
2589
  record,
2526
2590
  {
@@ -2546,8 +2610,9 @@ export class Dispatcher {
2546
2610
  await this.primeNodeReads(record, state, report)
2547
2611
  }
2548
2612
  }
2549
- if ((state.status === 'paused' || state.status === 'blocked') && !state.pr) return
2613
+ if ((state.status === 'paused' || janitorBlocked(state)) && !state.pr) return
2550
2614
  if (state.nodeOpened && state.baseBranch) {
2615
+ operation = 'target observation'
2551
2616
  if (
2552
2617
  await this.observeTarget(
2553
2618
  record.slug,
@@ -2563,11 +2628,12 @@ export class Dispatcher {
2563
2628
  if (
2564
2629
  state.nodeOpened &&
2565
2630
  state.status !== 'paused' &&
2566
- (state.status !== 'blocked' || integrationFailed(state)) &&
2631
+ (!janitorBlocked(state) || integrationFailed(state)) &&
2567
2632
  state.prState !== 'merged' &&
2568
2633
  state.prState !== 'closed' &&
2569
2634
  !executionLeaseLive
2570
2635
  ) {
2636
+ operation = 'node cascade'
2571
2637
  await this.prepareIntegration(record, state, report, launched, { refreshOnly: true })
2572
2638
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
2573
2639
  await this.cascadeNode(record, state, report, launched, opts)
@@ -2575,11 +2641,13 @@ export class Dispatcher {
2575
2641
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
2576
2642
  }
2577
2643
  if (state.nodeOpened && !executionLeaseLive) {
2644
+ operation = 'node integration'
2578
2645
  await this.prepareIntegration(record, state, report, launched)
2579
2646
  loaded = undefined
2580
2647
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
2581
2648
  }
2582
2649
  if (state.nodeOpened !== undefined && state.pr === undefined) {
2650
+ operation = 'empty node poll'
2583
2651
  await this.pollEmptyNode(record, state)
2584
2652
  await completeNodePoll()
2585
2653
  return
@@ -2589,7 +2657,7 @@ export class Dispatcher {
2589
2657
  // discard when both requests raced into the same stream.
2590
2658
  if (
2591
2659
  !executionLeaseLive &&
2592
- state.status === 'queued' &&
2660
+ janitorStatus(state) === 'queued' &&
2593
2661
  state.pendingCommands.some((command) => command.command === 'abort')
2594
2662
  ) {
2595
2663
  const acknowledged = await this.store.append(record.slug, {
@@ -2600,6 +2668,7 @@ export class Dispatcher {
2600
2668
  void acknowledged
2601
2669
  // The view folded the acknowledgement it just appended.
2602
2670
  loaded = undefined
2671
+ operation = 'abort cleanup'
2603
2672
  await this.cleanupAborted(record, await history(), report)
2604
2673
  return
2605
2674
  }
@@ -2608,19 +2677,26 @@ export class Dispatcher {
2608
2677
  // runner's workspace down or return its ticket for a duplicate build.
2609
2678
  if (
2610
2679
  !executionLeaseLive &&
2611
- state.status === 'queued' &&
2680
+ janitorStatus(state) === 'queued' &&
2612
2681
  state.discardRequest !== undefined
2613
2682
  ) {
2683
+ operation = 'discard cleanup'
2614
2684
  await this.cleanupDiscarded(record, await history(), report)
2615
2685
  return
2616
2686
  }
2617
2687
  if (!executionLeaseLive && state.status === 'aborted') {
2688
+ operation = 'abort cleanup'
2618
2689
  await this.cleanupAborted(record, await history(), report)
2619
2690
  return
2620
2691
  }
2692
+ operation = 'target observation'
2621
2693
  if (state.kind !== 'node' && state.status !== 'aborted')
2622
2694
  await this.observeTicketTarget(record, state, report)
2623
- if (state.kind !== 'node' && state.status !== 'aborted' && state.status !== 'queued') {
2695
+ if (
2696
+ state.kind !== 'node' &&
2697
+ state.status !== 'aborted' &&
2698
+ janitorStatus(state) !== 'queued'
2699
+ ) {
2624
2700
  const branch = await readBuildSelector(this.store, record.slug, 'baseBranch')
2625
2701
  if (branch !== undefined) {
2626
2702
  if (await this.observeTarget(record.slug, branch, log.restack.target?.sha, report)) {
@@ -2631,7 +2707,7 @@ export class Dispatcher {
2631
2707
  }
2632
2708
  if (
2633
2709
  state.kind !== 'node' &&
2634
- state.status !== 'queued' &&
2710
+ janitorStatus(state) !== 'queued' &&
2635
2711
  state.status !== 'aborted' &&
2636
2712
  state.prState !== 'merged' &&
2637
2713
  state.prState !== 'closed'
@@ -2656,6 +2732,7 @@ export class Dispatcher {
2656
2732
  forge: this.deps.forge,
2657
2733
  })
2658
2734
  } catch (error) {
2735
+ rethrowAuthorityLapse(error)
2659
2736
  if (janitorDeferral(error)) throw error
2660
2737
  if (facts.log.restack.distance?.count != null)
2661
2738
  report.janitorDiagnostics.push(
@@ -2687,6 +2764,7 @@ export class Dispatcher {
2687
2764
  }
2688
2765
  }
2689
2766
  if (state.pr) {
2767
+ operation = 'PR check'
2690
2768
  await this.checkPr(
2691
2769
  record,
2692
2770
  {
@@ -2705,6 +2783,11 @@ export class Dispatcher {
2705
2783
  }
2706
2784
  await completeNodePoll()
2707
2785
  } catch (error) {
2786
+ // A lapsed repository lease is not this build's janitor failure.
2787
+ if (isRepositoryAuthorityLapse(error)) {
2788
+ attempted = false
2789
+ throw error
2790
+ }
2708
2791
  // The guarded forge already recorded a classified rate limit as repository
2709
2792
  // degradation; like the cooldown that follows it, it neither starts nor ages
2710
2793
  // this build's janitor episode.
@@ -2726,6 +2809,7 @@ export class Dispatcher {
2726
2809
  message,
2727
2810
  this.deps.clock(),
2728
2811
  this.deps.config.policy,
2812
+ operation,
2729
2813
  )
2730
2814
  report.janitorFailed += 1
2731
2815
  report.janitorDiagnostics.push(`build ${record.slug}: janitor failed — ${message}`)
@@ -2757,6 +2841,7 @@ export class Dispatcher {
2757
2841
  })
2758
2842
  return true
2759
2843
  } catch (error) {
2844
+ rethrowAuthorityLapse(error)
2760
2845
  if (janitorDeferral(error)) throw error
2761
2846
  report.janitorDiagnostics.push(
2762
2847
  `build ${record.slug}: node read priming failed — ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
@@ -2784,6 +2869,7 @@ export class Dispatcher {
2784
2869
  if (state.kind === 'node') await this.observeNodeParent(record, state, report)
2785
2870
  else await this.observeWorkTarget(record, state, report)
2786
2871
  } catch (error) {
2872
+ rethrowAuthorityLapse(error)
2787
2873
  report.janitorDiagnostics.push(
2788
2874
  `build ${record.slug}: ticket target observation failed — ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
2789
2875
  )
@@ -2956,6 +3042,7 @@ export class Dispatcher {
2956
3042
  )
2957
3043
  throw new Error('destination generation changed; retry target update')
2958
3044
  } catch (error) {
3045
+ rethrowAuthorityLapse(error)
2959
3046
  if (request)
2960
3047
  await this.store.append(record.slug, {
2961
3048
  actor: DISPATCHER,
@@ -3023,6 +3110,7 @@ export class Dispatcher {
3023
3110
  })) !== 'unchanged'
3024
3111
  )
3025
3112
  } catch (error) {
3113
+ rethrowAuthorityLapse(error)
3026
3114
  const message =
3027
3115
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
3028
3116
  report.janitorDiagnostics.push(`build ${slug}: target observation failed — ${message}`)
@@ -3042,8 +3130,10 @@ export class Dispatcher {
3042
3130
  return open?.localPath ?? open?.path ?? open?.ref ?? this.deps.checkout ?? this.deps.repo
3043
3131
  }
3044
3132
 
3045
- /** Deferral withholds decisions, but cannot free an existing capacity reservation. */
3046
- private async capacityBuilds(): Promise<CapacityBuild[]> {
3133
+ /** Deferral withholds decisions, but cannot free an existing capacity reservation.
3134
+ * A leaf's runner reservation is this process's continuation or a launch
3135
+ * this tick; another process's continuation holds a heartbeat lease. */
3136
+ private async capacityBuilds(launched?: ReadonlySet<string>): Promise<CapacityBuild[]> {
3047
3137
  const builds: CapacityBuild[] = []
3048
3138
  for (const { record, digest } of await this.repoBuildDigests(true)) {
3049
3139
  if (digest.terminal) continue
@@ -3053,13 +3143,41 @@ export class Dispatcher {
3053
3143
  state: facts.state,
3054
3144
  workspace: facts.workspace !== null,
3055
3145
  provisioning:
3056
- digest.kind === 'node' &&
3057
- (await readBuildFacts(this.store, record.slug)).value.provisionMarker !== undefined,
3146
+ digest.kind === 'node'
3147
+ ? (await readBuildFacts(this.store, record.slug)).value.provisionMarker !== undefined
3148
+ : this.continuations.has(record.slug) || !!launched?.has(record.slug),
3149
+ restackDue: landingRestackDue(facts.state, facts.log),
3058
3150
  })
3059
3151
  }
3060
3152
  return builds
3061
3153
  }
3062
3154
 
3155
+ /** Whether a leaf may reserve a runner now. A leaf that has not finished its
3156
+ * pipeline already holds its slot, and abort and pause acknowledgements park
3157
+ * at once, so only a finished leaf that must run again is gated: it needs
3158
+ * a free slot among every other build. A denial is recorded only in memory,
3159
+ * for this tick's intake reservation. */
3160
+ private async leafAdmission(slug: string): Promise<boolean> {
3161
+ const { state } = await this.store.buildFacts(slug)
3162
+ if (
3163
+ !epilogueLeaf(state) ||
3164
+ state.pendingCommands.some(
3165
+ (command) => command.command === 'abort' || command.command === 'pause',
3166
+ )
3167
+ )
3168
+ return true
3169
+ const others = (await this.capacityBuilds(this.tickLaunched)).filter(
3170
+ (build) => build.record.slug !== slug,
3171
+ )
3172
+ const capacity = this.deps.config.capacity
3173
+ if (dispatchCapacity(others, capacity, this.deps.clock()).occupied < capacity) {
3174
+ this.slotWaiters.delete(slug)
3175
+ return true
3176
+ }
3177
+ this.slotWaiters.add(slug)
3178
+ return false
3179
+ }
3180
+
3063
3181
  /** Admit every node awaiting verification that has a slot, in slug order,
3064
3182
  * through the janitor's own admission path. Independent of `acceptNewWork`:
3065
3183
  * node admission is existing work, never intake. */
@@ -3084,7 +3202,7 @@ export class Dispatcher {
3084
3202
  launched.has(record.slug) ||
3085
3203
  this.hasLiveExecutionLease(record) ||
3086
3204
  !state.nodeOpened ||
3087
- (state.janitor && Date.parse(state.janitor.nextAttemptAt) > now.getTime())
3205
+ !janitorDue(state.janitor, now)
3088
3206
  )
3089
3207
  continue
3090
3208
  await withForgeRequestContext({ build: record.slug }, async () => {
@@ -3092,6 +3210,7 @@ export class Dispatcher {
3092
3210
  if (!(await this.nodeHasCapacity(record.slug))) return
3093
3211
  await this.prepareIntegration(record, state, report, launched)
3094
3212
  } catch (error) {
3213
+ rethrowAuthorityLapse(error)
3095
3214
  report.janitorDiagnostics.push(
3096
3215
  `build ${record.slug}: node admission failed — ${String(error)}`,
3097
3216
  )
@@ -3209,6 +3328,7 @@ export class Dispatcher {
3209
3328
  Object.assign(events, (await readBuildFacts(store, record.slug)).value)
3210
3329
  }
3211
3330
  const fail = (operation: string, identity: string, error: unknown): never => {
3331
+ rethrowAuthorityLapse(error)
3212
3332
  if (error instanceof ForgeCooldown || isForgeFailure(error)) throw error
3213
3333
  const detail = error instanceof Error || isForgeFailure(error) ? error.message : String(error)
3214
3334
  throw new Error(
@@ -3413,6 +3533,7 @@ export class Dispatcher {
3413
3533
  const message = await read.call(this.deps.forge, workspacePath, sha)
3414
3534
  return { sha, buildTrailerPresent: hasBuildTrailer(message, record.slug) }
3415
3535
  } catch (error) {
3536
+ rethrowAuthorityLapse(error)
3416
3537
  await this.store.append(record.slug, {
3417
3538
  actor: KERNEL,
3418
3539
  type: 'observation.recorded',
@@ -3506,7 +3627,7 @@ export class Dispatcher {
3506
3627
  candidate.status === 'paused' ||
3507
3628
  candidate.status === 'done' ||
3508
3629
  candidate.status === 'aborted' ||
3509
- candidate.openEscalations.length ||
3630
+ escalationsBeyondJanitor(candidate).length ||
3510
3631
  candidate.pendingCommands.length
3511
3632
  )
3512
3633
  return false
@@ -3521,7 +3642,12 @@ export class Dispatcher {
3521
3642
  )
3522
3643
  }
3523
3644
  const facts = await store.buildFacts(record.slug)
3524
- const decision = await this.decideBuild(record.slug, facts.state, facts.log, report)
3645
+ const decision = await this.decideBuild(
3646
+ record.slug,
3647
+ withoutJanitorEscalation(facts.state),
3648
+ facts.log,
3649
+ report,
3650
+ )
3525
3651
  return decision?.kind === 'wait' && decision.reason === 'awaiting-pr'
3526
3652
  }
3527
3653
  const candidateOf = async (current: BuildState) =>
@@ -3664,6 +3790,19 @@ export class Dispatcher {
3664
3790
  report.conflicted += 1
3665
3791
  return
3666
3792
  }
3793
+ // A finished build keeps its workspace while parked, even after its
3794
+ // environment was lost; the lease sweep reaps and replaces it once the
3795
+ // build is admitted, never a runner started in the lost environment.
3796
+ const retained = openWorkspace(events)
3797
+ if (
3798
+ retained !== null &&
3799
+ this.workspaceOwner(retained)?.recovery !== undefined &&
3800
+ (events.lastExecution === 'lost' || events.lastExecution === 'stopped') &&
3801
+ epilogueLeaf(events.state)
3802
+ ) {
3803
+ report.conflicted += 1
3804
+ return
3805
+ }
3667
3806
  // The dispatcher never runs agents (§15.7): re-attach a build-runner,
3668
3807
  // which executes the reconcile epilogue phase.
3669
3808
  await this.launch(record.slug, launched, report)
@@ -3692,7 +3831,7 @@ export class Dispatcher {
3692
3831
  candidate.status === 'paused' ||
3693
3832
  candidate.status === 'done' ||
3694
3833
  candidate.status === 'aborted' ||
3695
- candidate.openEscalations.length ||
3834
+ escalationsBeyondJanitor(candidate).length ||
3696
3835
  candidate.pendingCommands.length ||
3697
3836
  !integrationVerified(
3698
3837
  candidate,
@@ -3711,14 +3850,19 @@ export class Dispatcher {
3711
3850
  current.status !== 'paused' &&
3712
3851
  current.status !== 'aborted' &&
3713
3852
  current.status !== 'done' &&
3714
- !current.openEscalations.length &&
3853
+ !escalationsBeyondJanitor(current).length &&
3715
3854
  !current.pendingCommands.length &&
3716
3855
  integrationVerified(current, config) &&
3717
3856
  cycle?.head === exact.headSha &&
3718
3857
  cycle.parent === exact.parentSha
3719
3858
  )
3720
3859
  }
3721
- const decision = await this.decideBuild(record.slug, latest.state, latest.log, report)
3860
+ const decision = await this.decideBuild(
3861
+ record.slug,
3862
+ withoutJanitorEscalation(latest.state),
3863
+ latest.log,
3864
+ report,
3865
+ )
3722
3866
  return (
3723
3867
  latest.state.pr?.number === pr.number &&
3724
3868
  latest.state.prState === 'open' &&
@@ -4199,6 +4343,7 @@ export class Dispatcher {
4199
4343
  payload: { hostedSeq: hosted.seq },
4200
4344
  })
4201
4345
  } catch (error) {
4346
+ rethrowAuthorityLapse(error)
4202
4347
  if (error instanceof ForgeCooldown) throw error
4203
4348
  try {
4204
4349
  await this.store.append(slug, {
@@ -4236,6 +4381,11 @@ export class Dispatcher {
4236
4381
  ...input,
4237
4382
  restoration,
4238
4383
  ...(facts.replacedHeads.length ? { restorationReplaced: facts.replacedHeads } : {}),
4384
+ // Same predicate preservation archives under: only local-git keeps
4385
+ // archive refs in the local repository.
4386
+ ...(restoration?.length
4387
+ ? { restorationArchives: this.deps.forge.name === 'local-git' ? 'local' : 'remote' }
4388
+ : {}),
4239
4389
  })
4240
4390
  const skipped = [
4241
4391
  ...superseded.map((sha) => ({ sha, reason: 'superseded' as const })),
@@ -4345,6 +4495,7 @@ export class Dispatcher {
4345
4495
  reason,
4346
4496
  )
4347
4497
  } catch (error) {
4498
+ rethrowAuthorityLapse(error)
4348
4499
  // Keep this generation and its pending work until forge recovery,
4349
4500
  // while allowing the sweep to supervise the remaining builds.
4350
4501
  if (error instanceof ForgeRequestDeferred) return false
@@ -4393,6 +4544,7 @@ export class Dispatcher {
4393
4544
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
4394
4545
  return true
4395
4546
  } catch (error) {
4547
+ rethrowAuthorityLapse(error)
4396
4548
  const message =
4397
4549
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4398
4550
  const _failed = await this.store.append(slug, {
@@ -4477,6 +4629,7 @@ export class Dispatcher {
4477
4629
  })
4478
4630
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
4479
4631
  } catch (error) {
4632
+ rethrowAuthorityLapse(error)
4480
4633
  const message =
4481
4634
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4482
4635
  const _failed = await this.store.append(slug, {
@@ -4535,11 +4688,36 @@ export class Dispatcher {
4535
4688
  /** The claim-time `build.created` payload. Assets and issue links are
4536
4689
  * omitted when the ticket had none, so such a build's log is exactly what it
4537
4690
  * was before. */
4691
+ /** Ready tickets whose labels select two or more profiles (SPEC §9). They
4692
+ * are never claimed; each gets a ticket diagnostic until relabelled. Pure
4693
+ * over the listing the scan already holds. */
4694
+ private profileConflicts(tickets: readonly Ticket[]): {
4695
+ tickets: Set<Ticket>
4696
+ diagnostics: string[]
4697
+ } {
4698
+ const conflicting = new Set<Ticket>()
4699
+ const diagnostics: string[] = []
4700
+ for (const ticket of tickets) {
4701
+ const selection = selectProfile(this.deps.config.profiles, ticket.labels)
4702
+ if (selection.kind !== 'conflict') continue
4703
+ conflicting.add(ticket)
4704
+ diagnostics.push(profileConflictDiagnostic(ticket.ref.id, selection.matches))
4705
+ }
4706
+ return { tickets: conflicting, diagnostics }
4707
+ }
4708
+
4709
+ /** The profile a ticket's labels select at claim, if exactly one. */
4710
+ private selectedProfile(ticket: Ticket): { profile: string } | Record<string, never> {
4711
+ const selection = selectProfile(this.deps.config.profiles, ticket.labels)
4712
+ return selection.kind === 'selected' ? { profile: selection.name } : {}
4713
+ }
4714
+
4538
4715
  private buildCreatedPayload(
4539
4716
  ticket: TicketRef,
4540
4717
  repo: string,
4541
4718
  seed:
4542
4719
  | {
4720
+ profile?: string
4543
4721
  autoMergeUser?: string
4544
4722
  autoMergeDefaultSeq?: number
4545
4723
  assets?: PinnedAsset[]
@@ -4566,6 +4744,7 @@ export class Dispatcher {
4566
4744
  ...(seed?.issueLinks !== undefined && seed.issueLinks.length > 0
4567
4745
  ? { issueLinks: seed.issueLinks.map(({ issue, intent }) => ({ issue, intent })) }
4568
4746
  : {}),
4747
+ ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
4569
4748
  }
4570
4749
  }
4571
4750
 
@@ -4635,6 +4814,7 @@ export class Dispatcher {
4635
4814
  ...(seed?.ticket.issueLinks !== undefined
4636
4815
  ? { issueLinks: seed.ticket.issueLinks }
4637
4816
  : {}),
4817
+ ...(seed !== undefined ? this.selectedProfile(seed.ticket) : {}),
4638
4818
  }),
4639
4819
  })
4640
4820
  events = (await readBuildFacts(store, record.slug)).value
@@ -4710,6 +4890,7 @@ export class Dispatcher {
4710
4890
  events = (await readBuildFacts(store, record.slug)).value
4711
4891
  }
4712
4892
  } catch (error) {
4893
+ rethrowAuthorityLapse(error)
4713
4894
  if (await this.holdForMissingAccounts(error)) return 'parked'
4714
4895
  if (error instanceof MixedVersionDeferral) return 'parked'
4715
4896
  const events = (await readBuildFacts(store, record.slug)).value
@@ -4863,6 +5044,7 @@ export class Dispatcher {
4863
5044
  if (authored && report !== undefined) report.authored += 1
4864
5045
  return 'completed'
4865
5046
  } catch (error) {
5047
+ rethrowAuthorityLapse(error)
4866
5048
  if (await this.holdForMissingAccounts(error)) return 'parked'
4867
5049
  const events = (await readBuildFacts(store, record.slug)).value
4868
5050
  const attempt = events.dispatchFailureCount + 1
@@ -5022,6 +5204,7 @@ export class Dispatcher {
5022
5204
  try {
5023
5205
  await this.sweepBuild(record, report, launched, paused, now)
5024
5206
  } catch (error) {
5207
+ rethrowAuthorityLapse(error)
5025
5208
  // Per-build containment: one build's failure never stops the sweep
5026
5209
  // from advancing the others. Workspace failures are already durable
5027
5210
  // against the build; a repository-wide cooldown still ends the tick.
@@ -5088,6 +5271,18 @@ export class Dispatcher {
5088
5271
  const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
5089
5272
  if (decision === undefined) return
5090
5273
  if (state.status === 'done' || state.status === 'aborted') return
5274
+ if (decision.kind === 'wait' && decision.reason === 'awaiting-pr' && state.kind !== 'node') {
5275
+ this.parkedSettled.add(record.slug)
5276
+ // The engine reached the end of the pipeline: record it once per
5277
+ // settlement key so capacity stops counting the parked build. A lost
5278
+ // race is decided again next tick.
5279
+ if (settlementDue(state))
5280
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5281
+ actor: DISPATCHER,
5282
+ type: 'pipeline.settled',
5283
+ payload: { cycle: settlementKey(state) },
5284
+ })
5285
+ }
5091
5286
  const orphanEligible = (state: BuildState) =>
5092
5287
  !paused &&
5093
5288
  state.status === 'running' &&
@@ -5181,6 +5376,18 @@ export class Dispatcher {
5181
5376
  // is reaped and replaced by the next generation.
5182
5377
  if (endedInPlace && open !== null && cleanupRequiredWorkspace(await history()))
5183
5378
  endedInPlace = false
5379
+ const runs = decision.kind !== 'wait' || publicationRecoveryDue || orphanRecoveryDue
5380
+ // A finished leaf with work to run waits for a slot before anything is
5381
+ // reaped, provisioned or launched for it.
5382
+ if (runs && state.kind !== 'node' && !(await this.leafAdmission(record.slug))) return
5383
+ // A finished parked leaf keeps its workspace until merge or close; a
5384
+ // stale environment is reaped only for an admitted replacement.
5385
+ if (
5386
+ !runs &&
5387
+ state.kind !== 'node' &&
5388
+ ((decision.kind === 'wait' && decision.reason === 'awaiting-pr') || epilogueLeaf(state))
5389
+ )
5390
+ return
5184
5391
  // A provider- or log-proved END in the same generation re-attaches in
5185
5392
  // place: the guest finished its work, the workspace is still the
5186
5393
  // build's, and replacing the environment would discard a healthy
@@ -5234,6 +5441,7 @@ export class Dispatcher {
5234
5441
  const result = await this.launch(record.slug, launched, report)
5235
5442
  if (result === 'scheduled') report.swept += 1
5236
5443
  } catch (error) {
5444
+ rethrowAuthorityLapse(error)
5237
5445
  // Launchers normally record provider failures themselves. Preserve
5238
5446
  // durable attention if orphan cleanup fails before that boundary,
5239
5447
  // without counting an already-recorded failure twice.
@@ -5272,6 +5480,7 @@ export class Dispatcher {
5272
5480
  try {
5273
5481
  await this.recoverTicketPreparation(attempt)
5274
5482
  } catch (error) {
5483
+ rethrowAuthorityLapse(error)
5275
5484
  failures.push(error)
5276
5485
  }
5277
5486
  }
@@ -5294,6 +5503,7 @@ export class Dispatcher {
5294
5503
  ticket: attempt.ticket,
5295
5504
  outcome,
5296
5505
  ...(reason ? { reason: reason.slice(0, 4000) } : {}),
5506
+ ...(outcome === 'abandoned' ? { claimed: attempt.claimed } : {}),
5297
5507
  },
5298
5508
  })
5299
5509
  }
@@ -5306,29 +5516,58 @@ export class Dispatcher {
5306
5516
  this.tickAbandonments.push(abandonedPreparationDiagnostic(attempt, recorded))
5307
5517
  }
5308
5518
 
5519
+ /** Whether the build at `slug` was created for this attempt's ticket. */
5520
+ private async preparationOwns(attempt: TicketPreparation, record: BuildRecord): Promise<boolean> {
5521
+ const created = (await this.store.buildFacts(record.slug)).created
5522
+ return (
5523
+ record.repo === this.deps.repo &&
5524
+ record.ticket?.source === attempt.ticket.source &&
5525
+ record.ticket?.id === attempt.ticket.id &&
5526
+ created?.payload.repo === this.deps.repo &&
5527
+ created.payload.ticket?.source === attempt.ticket.source &&
5528
+ created.payload.ticket?.id === attempt.ticket.id
5529
+ )
5530
+ }
5531
+
5309
5532
  private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
5310
5533
  try {
5311
5534
  // A rejected create can have committed. Unavailable or conflicting readback
5312
- // is never absence and must not authorize a ticket transition.
5535
+ // is never absence and must not authorize a ticket transition. A keyed
5536
+ // attempt's build is at its proposed slug (exact-slug store) or the slug
5537
+ // its own key derives (allocating store): at most two point reads, and
5538
+ // never another attempt's build.
5313
5539
  if (attempt.slug) {
5314
- const record = await this.store.getBuild(attempt.slug)
5315
- if (record) {
5316
- const created = (await this.store.buildFacts(attempt.slug)).created
5317
- if (
5318
- record.repo !== this.deps.repo ||
5319
- record.ticket?.source !== attempt.ticket.source ||
5320
- record.ticket?.id !== attempt.ticket.id ||
5321
- created?.payload.repo !== this.deps.repo ||
5322
- created.payload.ticket?.source !== attempt.ticket.source ||
5323
- created.payload.ticket?.id !== attempt.ticket.id
5540
+ const candidates = attempt.creationKey
5541
+ ? [attempt.slug, creationBuildSlug(this.deps.repo, attempt.slug, attempt.creationKey)]
5542
+ : [attempt.slug]
5543
+ const found: BuildRecord[] = []
5544
+ for (const slug of candidates) {
5545
+ const record = await this.store.getBuild(slug)
5546
+ if (record) found.push(record)
5547
+ }
5548
+ if (found.length > 1)
5549
+ return await this.abandonPreparation(
5550
+ attempt,
5551
+ `Ambiguous creation identity: builds at ${found.map((record) => record.slug).join(' and ')} both answer this attempt; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5324
5552
  )
5553
+ const [record] = found
5554
+ if (record) {
5555
+ if (!(await this.preparationOwns(attempt, record)))
5325
5556
  return await this.abandonPreparation(
5326
5557
  attempt,
5327
- `Conflicting build ownership at ${attempt.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5558
+ `Conflicting build ownership at ${record.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5328
5559
  )
5329
5560
  await this.preparationResolved(attempt, 'owned')
5330
5561
  return
5331
5562
  }
5563
+ // Absence is evidence only where the creation slug is known: an
5564
+ // allocating store may have committed an unkeyed create under a slug
5565
+ // no point read can find, and enumerating builds is never a fallback.
5566
+ if (!attempt.creationKey && (await this.store.buildCreationIdentity?.()) !== undefined)
5567
+ return await this.abandonPreparation(
5568
+ attempt,
5569
+ `Creation outcome unknown: the build store allocates canonical slugs and this attempt recorded no creation key, so a build created under an unrecorded slug cannot be ruled out; ticket unchanged. Inspect the repository's builds for ticket ${attempt.ticket.id} before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5570
+ )
5332
5571
  }
5333
5572
  const ref = resolveTicketRef(
5334
5573
  this.store.repositoryFacts().ticketMigrations,
@@ -5369,6 +5608,7 @@ export class Dispatcher {
5369
5608
  handback === attempt.readyState ? 'handed-back' : 'bounced',
5370
5609
  )
5371
5610
  } catch (error) {
5611
+ rethrowAuthorityLapse(error)
5372
5612
  const message = error instanceof Error ? error.message : String(error)
5373
5613
  try {
5374
5614
  await this.store.appendRepo(this.deps.repo, {
@@ -5419,17 +5659,22 @@ export class Dispatcher {
5419
5659
  report.ticketDiagnostics = []
5420
5660
  report.dependencyDiagnostics = []
5421
5661
  report.creationDiagnostics = []
5422
- // Blocked and paused builds still occupy a slot: their workspaces and
5423
- // pending work are live, only waiting on a human. Capacity is per repo
5424
- // (§16.1) — another repo's builds never consume this repo's slots.
5425
- const capacityBuilds = await this.capacityBuilds()
5426
- // A node awaiting verification reserves its slot ahead of new claims until
5427
- // `admitWaitingNodes` gives it one; this only ever lowers the claim budget.
5662
+ // Capacity counts builds running work. An unfinished build holds its slot
5663
+ // even while blocked or paused; a finished build parked for its merge
5664
+ // decision holds none. Capacity is per repo (§16.1) — another repo's
5665
+ // builds never consume this repo's slots.
5666
+ const capacityBuilds = await this.capacityBuilds(launched)
5667
+ // A node awaiting verification, or a parked build that must run again,
5668
+ // reserves its slot ahead of new claims until it is admitted; this only
5669
+ // ever lowers the claim budget.
5428
5670
  const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock())
5429
5671
  const activeRefs: TicketRef[] = capacityBuilds
5430
5672
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
5431
5673
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
5432
- let capacity = intakeCapacity(projection)
5674
+ let capacity = intakeCapacity(projection, {
5675
+ settled: this.parkedSettled,
5676
+ denied: this.slotWaiters,
5677
+ })
5433
5678
 
5434
5679
  // The ready scan runs even at full capacity: `queued` is the operator's
5435
5680
  // standing queue-depth report and must stay honest exactly when the
@@ -5458,9 +5703,12 @@ export class Dispatcher {
5458
5703
  )
5459
5704
  // Urgent first, each class in source order (stable). Every gate below is
5460
5705
  // unchanged; a source without the priority capability is all normal.
5461
- const ready = this.deps.tickets.priority ? urgentFirst(eligible) : eligible
5462
- report.invalidTickets += listing.diagnostics.length
5463
- report.ticketDiagnostics.push(...listing.diagnostics)
5706
+ // A ticket whose labels select two profiles is never claimed (SPEC §9).
5707
+ const conflicts = this.profileConflicts(eligible)
5708
+ const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
5709
+ const ready = this.deps.tickets.priority ? urgentFirst(claimable) : claimable
5710
+ report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
5711
+ report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
5464
5712
  report.queued = ready.length
5465
5713
  const withheld = new Set<string>()
5466
5714
  for (const ticket of ready) {
@@ -5719,6 +5967,8 @@ export class Dispatcher {
5719
5967
  claimed: false,
5720
5968
  }
5721
5969
  await store.ensureRepo(this.deps.repo)
5970
+ // A lapsed run leaves the ticket Ready for whoever holds the repository.
5971
+ if (this.deps.holdsRepoAuthority?.() === false) break
5722
5972
  await store.appendRepo(this.deps.repo, {
5723
5973
  actor: DISPATCHER,
5724
5974
  type: 'ticket-preparation.intended',
@@ -5789,6 +6039,10 @@ export class Dispatcher {
5789
6039
  const slug = await this.uniqueSlug(baseSlug, prefix)
5790
6040
  const branch = `${prefix}/${slug}`
5791
6041
  const repoOrigin = await this.resolveRepoOriginOnce()
6042
+ // Recorded only on the store's attestation, so recovery never treats
6043
+ // an unkeyed creation's absence at the derived slug as evidence.
6044
+ const creationKey =
6045
+ (await store.buildCreationIdentity?.()) === 'keyed' ? attempt.attempt : undefined
5792
6046
  createdSeed = {
5793
6047
  ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
5794
6048
  ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
@@ -5805,15 +6059,23 @@ export class Dispatcher {
5805
6059
  // Frozen from the same claimed ticket sample as the body (SPEC
5806
6060
  // "Forge issue links"); later ticket edits never reach this build.
5807
6061
  ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
6062
+ // Fixed at claim from the same sample: relabelling never changes it.
6063
+ ...this.selectedProfile(ticket),
5808
6064
  }
5809
6065
  // `build.created` rides with the record so the pinned assets and the
5810
6066
  // record exist together or not at all.
5811
6067
  stage = 'creation-identity'
5812
6068
  attempt.slug = slug
6069
+ if (creationKey !== undefined) attempt.creationKey = creationKey
5813
6070
  await store.appendRepo(this.deps.repo, {
5814
6071
  actor: DISPATCHER,
5815
6072
  type: 'ticket-preparation.creation-selected',
5816
- payload: { attempt: attempt.attempt, ticket: attempt.ticket, slug },
6073
+ payload: {
6074
+ attempt: attempt.attempt,
6075
+ ticket: attempt.ticket,
6076
+ slug,
6077
+ ...(creationKey !== undefined ? { creationKey } : {}),
6078
+ },
5817
6079
  })
5818
6080
  stage = 'create-build'
5819
6081
  record = await store.createBuild({
@@ -5822,6 +6084,7 @@ export class Dispatcher {
5822
6084
  ticket: ticket.ref,
5823
6085
  branch,
5824
6086
  ...(repoOrigin !== undefined ? { repoOrigin } : {}),
6087
+ ...(creationKey !== undefined ? { creationKey } : {}),
5825
6088
  created: {
5826
6089
  actor: DISPATCHER,
5827
6090
  type: 'build.created',
@@ -5831,6 +6094,9 @@ export class Dispatcher {
5831
6094
  established = true
5832
6095
  await this.preparationResolved(attempt, 'owned')
5833
6096
  } catch (error) {
6097
+ // A lapse is not a preparation failure: the successor recovers the
6098
+ // intended attempt through `recoverTicketPreparations`.
6099
+ rethrowAuthorityLapse(error)
5834
6100
  // Settlement and completion errors after successful creation cannot
5835
6101
  // release the claim. A later tick settles the retained creation identity.
5836
6102
  if (established) throw error
@@ -6252,6 +6518,8 @@ export class Dispatcher {
6252
6518
  beforeReplay,
6253
6519
  canWrite: async () => {
6254
6520
  if (await deferMixedVersion(this.store, record.slug)) return false
6521
+ // A lapse is not lost writer authority: it must escape unrecorded.
6522
+ if (this.deps.holdsRepoAuthority?.() === false) throw new RepositoryAuthorityLapsed()
6255
6523
  if (this.outOfBudget(opts)) return false
6256
6524
  if (state.pr && (await forge.getPrState(checkout, state.pr.number)).state !== 'open')
6257
6525
  return false
@@ -6261,7 +6529,7 @@ export class Dispatcher {
6261
6529
  current.status !== 'done' &&
6262
6530
  current.status !== 'aborted' &&
6263
6531
  current.status !== 'paused' &&
6264
- (current.status !== 'blocked' || integrationFailed(current)) &&
6532
+ (!janitorBlocked(current) || integrationFailed(current)) &&
6265
6533
  current.prState !== 'merged' &&
6266
6534
  current.prState !== 'closed' &&
6267
6535
  current.pendingCommands.length === 0 &&
@@ -6345,6 +6613,7 @@ export class Dispatcher {
6345
6613
  }
6346
6614
  }
6347
6615
  } catch (error) {
6616
+ rethrowAuthorityLapse(error)
6348
6617
  if (await this.holdForMissingAccounts(error)) return
6349
6618
  const message =
6350
6619
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -6357,7 +6626,7 @@ export class Dispatcher {
6357
6626
  ) {
6358
6627
  await this.store.refreshBuild(record.slug)
6359
6628
  const current = (await this.store.buildFacts(record.slug)).state
6360
- if (!current.openEscalations.length)
6629
+ if (!escalationsBeyondJanitor(current).length)
6361
6630
  await this.store.append(record.slug, {
6362
6631
  actor: KERNEL,
6363
6632
  type: 'escalation.raised',
@@ -6386,7 +6655,8 @@ export class Dispatcher {
6386
6655
  launched: Set<string>,
6387
6656
  sampling: { refreshOnly?: boolean } = {},
6388
6657
  ): Promise<void> {
6389
- if (!integrationAdmissible(state)) return
6658
+ // The janitor's own escalation never skips the preparation that would recover it.
6659
+ if (!integrationAdmissible(withoutJanitorEscalation(state))) return
6390
6660
  const forge = this.kernelForge()
6391
6661
  if (!record.branch || !state.baseBranch || !forge.compareBranches) return
6392
6662
  const comparison = await forge.compareBranches(state.baseBranch!, record.branch!)
@@ -6426,7 +6696,7 @@ export class Dispatcher {
6426
6696
  state.nodeRestack?.active ||
6427
6697
  state.integration?.intent ||
6428
6698
  state.nodeRestack?.contributionBase !== comparison.parentSha ||
6429
- state.openEscalations.length ||
6699
+ escalationsBeyondJanitor(state).length ||
6430
6700
  state.status === 'paused' ||
6431
6701
  state.status === 'done' ||
6432
6702
  state.status === 'aborted' ||