@defrex/autobuild 1.0.0-beta.2 → 1.0.0-beta.4

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 (145) hide show
  1. package/SPEC.md +342 -23
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +170 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +91 -4
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +9 -1
  10. package/docs/remote-ticket-protocol.md +5 -0
  11. package/docs/restacking.md +4 -1
  12. package/docs/setup.md +24 -0
  13. package/docs/spec-standard.md +94 -5
  14. package/docs/ticket-migration.md +50 -4
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/artifact.ts +5 -4
  17. package/packages/core/src/cli/attention.ts +2 -0
  18. package/packages/core/src/cli/binary-direct.ts +190 -0
  19. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  20. package/packages/core/src/cli/binary.ts +24 -210
  21. package/packages/core/src/cli/build-control.ts +108 -5
  22. package/packages/core/src/cli/context.ts +41 -1
  23. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  24. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  25. package/packages/core/src/cli/dashboard/integration-detail.ts +11 -6
  26. package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
  27. package/packages/core/src/cli/dashboard/model.ts +41 -10
  28. package/packages/core/src/cli/dashboard/render.ts +24 -2
  29. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  30. package/packages/core/src/cli/dispatch-args.ts +53 -0
  31. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +57 -5
  33. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  34. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  35. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  36. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  38. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  39. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  40. package/packages/core/src/cli/dispatch-process.ts +22 -90
  41. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +6 -1
  43. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  44. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  45. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  46. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  47. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  48. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  49. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  50. package/packages/core/src/cli/dispatch.ts +609 -60
  51. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  52. package/packages/core/src/cli/harvest.ts +28 -11
  53. package/packages/core/src/cli/help.ts +7 -3
  54. package/packages/core/src/cli/installation.ts +5 -3
  55. package/packages/core/src/cli/main-checkout.ts +59 -0
  56. package/packages/core/src/cli/main.ts +26 -53
  57. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  58. package/packages/core/src/cli/repo-state.ts +3 -58
  59. package/packages/core/src/cli/repository-status.ts +74 -4
  60. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  61. package/packages/core/src/cli/status.ts +57 -3
  62. package/packages/core/src/cli/ticket.ts +35 -11
  63. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  64. package/packages/core/src/cli/wait.ts +3 -0
  65. package/packages/core/src/cli/watch.ts +7 -0
  66. package/packages/core/src/config/live.ts +1 -0
  67. package/packages/core/src/config/schema.ts +8 -4
  68. package/packages/core/src/distribution-packaging.ts +116 -0
  69. package/packages/core/src/events/catalog.ts +6 -0
  70. package/packages/core/src/events/payloads.ts +55 -9
  71. package/packages/core/src/events/policy.ts +26 -0
  72. package/packages/core/src/events/repository.ts +205 -4
  73. package/packages/core/src/events/runtime.ts +16 -0
  74. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +6537 -4053
  75. package/packages/core/src/kernel/change-presence.ts +7 -1
  76. package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
  77. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  78. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  79. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  80. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  81. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  82. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  83. package/packages/core/src/kernel/harvest.ts +98 -4
  84. package/packages/core/src/kernel/integration-attention.ts +20 -0
  85. package/packages/core/src/kernel/integration-completeness.ts +54 -16
  86. package/packages/core/src/kernel/integration-state.ts +80 -11
  87. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  88. package/packages/core/src/kernel/mixed-version.ts +34 -0
  89. package/packages/core/src/kernel/node-parent.ts +35 -10
  90. package/packages/core/src/kernel/node-polling.ts +160 -0
  91. package/packages/core/src/kernel/read-facts.ts +47 -5
  92. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  93. package/packages/core/src/kernel/reducer.ts +75 -14
  94. package/packages/core/src/kernel/service-facts.ts +11 -4
  95. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  96. package/packages/core/src/operator/presentation.ts +7 -0
  97. package/packages/core/src/operator/query.ts +13 -3
  98. package/packages/core/src/operator/registry.ts +1 -1
  99. package/packages/core/src/operator/tickets.ts +30 -26
  100. package/packages/core/src/plugins/load.ts +4 -1
  101. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  102. package/packages/core/src/ports/forge/contract.ts +29 -0
  103. package/packages/core/src/ports/forge/github.ts +189 -61
  104. package/packages/core/src/ports/forge-failure.ts +1 -0
  105. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  106. package/packages/core/src/ports/runner/session-env.ts +1 -0
  107. package/packages/core/src/ports/tickets/linear.ts +180 -12
  108. package/packages/core/src/ports/tickets/migration.ts +92 -9
  109. package/packages/core/src/ports/types.ts +17 -0
  110. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  111. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  112. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  113. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  114. package/packages/core/src/processes/build-child-exit.ts +5 -26
  115. package/packages/core/src/processes/build-runner.ts +81 -11
  116. package/packages/core/src/processes/dispatcher.ts +418 -59
  117. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  118. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  119. package/packages/core/src/processes/execution-settlement.ts +16 -7
  120. package/packages/core/src/processes/harvest-runner.ts +328 -292
  121. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  122. package/packages/core/src/runtime-identity.ts +22 -3
  123. package/packages/core/src/store/contract.ts +183 -0
  124. package/packages/core/src/store/local/store.ts +197 -72
  125. package/packages/core/src/store/reduced-reads.ts +8 -0
  126. package/packages/core/src/store/reducer-value-shapes.json +8915 -6344
  127. package/packages/core/src/store/remote/client.ts +43 -0
  128. package/packages/core/src/store/repo-state-events.ts +21 -3
  129. package/packages/core/src/store/types.ts +7 -0
  130. package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
  131. package/skills/guide/SKILL.md +234 -24
  132. package/skills/guide/references/integration-tree.md +91 -4
  133. package/skills/guide/references/operator-api.md +53 -4
  134. package/skills/guide/references/plugin-authoring.md +45 -4
  135. package/skills/guide/references/remote-store-protocol.md +9 -1
  136. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  137. package/skills/guide/references/restacking.md +4 -1
  138. package/skills/guide/references/setup.md +24 -0
  139. package/skills/guide/references/spec-standard.md +94 -5
  140. package/skills/guide/references/ticket-migration.md +50 -4
  141. package/skills/harvest/SKILL.md +4 -0
  142. package/skills/harvest-review/SKILL.md +4 -0
  143. package/skills/operate/SKILL.md +78 -8
  144. package/skills/spec/SKILL.md +35 -5
  145. package/skills/tickets/SKILL.md +19 -0
@@ -1,4 +1,20 @@
1
- import { formatDispatcherError } from '../runtime-identity'
1
+ import { migrationIdentity } from '../kernel/ticket-migrations'
2
+ import { recordRuntimeRollback } from './dispatch-handoff'
3
+ import { syncRollbackRetention } from './dispatch-runtime-use'
4
+ import { dirname as runtimeDirname } from 'node:path'
5
+ import { releaseDispatchPresentation } from './dispatch-presentation-ownership'
6
+ import { validateWorkspaceDispatchConfiguration } from './dispatch-readiness'
7
+ import { releasePreparedRuntime } from './dispatch-runtime-use'
8
+ import { authorizeRemoteHandoffs, recoverDispatchDrain } from '../kernel/dispatch-drain-recovery'
9
+ import { distributionRoot } from '../distribution'
10
+ import { readDistributionIdentity } from './installation'
11
+ import { launchContext } from './dispatch-launch-contract'
12
+ import { DispatchUpgradeController } from './dispatch-upgrade-controller'
13
+ import { resolveUpgradeTarget } from './dispatch-upgrade-target'
14
+ import { prepareUpgrade } from './dispatch-upgrade-install'
15
+ import { readDispatchUpgrade } from '../store/reduced-reads'
16
+ import type { Handoff, UpgradeRun } from '../kernel/dispatch-upgrade'
17
+ import { RUNTIME_IDENTITY, formatDispatcherError } from '../runtime-identity'
2
18
 
3
19
  import { isDeepStrictEqual } from 'node:util'
4
20
  import { guardForge } from '../kernel/guarded-forge'
@@ -478,37 +494,7 @@ async function defaultWire(
478
494
  // Origin mode: no checkout exists, so the provider's host git seams are
479
495
  // replaced by the injected origin and the forge's remote reads.
480
496
  const originMode = opts.repository !== undefined
481
- // Dispatch preflight is capability-driven (AUT-516): forge support, origin
482
- // validation, and required environment all read the selected provider's
483
- // registration declarations — builtin and plugin alike — instead of naming
484
- // a provider.
485
- const workspaceCaps = plugins.workspaceProviders.get(config.workspace.provider)?.capabilities
486
- if (workspaceCaps?.supportedForges !== undefined) {
487
- if (!workspaceCaps.supportedForges.includes(config.forge)) {
488
- throw new Error(
489
- workspaceCaps.forgeDispatchMessage ??
490
- `workspace provider "${config.workspace.provider}" does not support forge "${config.forge}"`,
491
- )
492
- }
493
- }
494
- if (workspaceCaps?.validateOrigin !== undefined && !originMode) {
495
- const origin = await opts.exec(['git', 'remote', 'get-url', 'origin'], {
496
- cwd: opts.targetRepo,
497
- })
498
- if (origin.exitCode !== 0)
499
- throw new Error(
500
- workspaceCaps.originReadFailureMessage ??
501
- `workspace provider "${config.workspace.provider}" requires a readable Git origin`,
502
- )
503
- workspaceCaps.validateOrigin(origin.stdout.trim())
504
- }
505
- for (const group of workspaceCaps?.requiredEnv ?? []) {
506
- if (group.dispatchMessage === undefined) continue
507
- const satisfied = group.alternatives.some((names) =>
508
- names.every((name) => opts.env[name] !== undefined && opts.env[name] !== ''),
509
- )
510
- if (!satisfied) throw new Error(group.dispatchMessage)
511
- }
497
+ await validateWorkspaceDispatchConfiguration(config, opts, plugins)
512
498
  // The builtin GitHub forge resolves its credential lazily on its first
513
499
  // request (GITHUB_TOKEN, GH_TOKEN, then the gh CLI login) and names the
514
500
  // miss reason on any request that had to go out anonymously; nothing is
@@ -639,6 +625,8 @@ class DispatchLoop {
639
625
  private readonly activeBuildRuns = new Map<string, ActiveBuildExecution>()
640
626
  private acceptingBuildLaunches = true
641
627
  /** Process-local fast path; the repository lease is the cross-process gate. */
628
+ private localHarvestShutdown = new AbortController()
629
+ private localHarvestFailure: unknown
642
630
  private harvestInFlight: Promise<void> | undefined
643
631
  /** Live hosted-harvest execution: the environment-supervised handle whose
644
632
  * completion chain classifies, releases, and journals the close fact.
@@ -707,6 +695,9 @@ class DispatchLoop {
707
695
  /** Process-local, persistent release notice. It never shares the replaceable
708
696
  * warning slot and is re-applied to every store projection. */
709
697
  private availableUpgrade: string | undefined
698
+ private upgradeController?: DispatchUpgradeController
699
+ private cutoverRequested = false
700
+ private handoffCompleted = false
710
701
  private stopUpgradeNotice: (() => void) | undefined
711
702
  /** Startup, configuration-level notices — constant for the life of the
712
703
  * process. Rendered ABOVE the transient warning line and never overwritten by
@@ -1111,6 +1102,7 @@ class DispatchLoop {
1111
1102
  }
1112
1103
 
1113
1104
  await this.publishActiveBuildConfigs(outcome.snapshot)
1105
+ this.upgradeController?.changed()
1114
1106
  this.announce(`autobuild.toml reloaded (revision ${outcome.snapshot.revision})`)
1115
1107
  if (outcome.restartRequired.length > 0) {
1116
1108
  this.warn(
@@ -1144,6 +1136,7 @@ class DispatchLoop {
1144
1136
  // Refresh before every watch decision. The owner publishes atomically;
1145
1137
  // everything below captures the resulting one snapshot for this tick.
1146
1138
  await this.refreshConfig()
1139
+ if (await this.acceptUpgradeYield()) return emptyTickReport()
1147
1140
  // Every tick verifies local lease currency, reclaiming when necessary. Without it,
1148
1141
  // this invocation records the yield and performs no claims, launches,
1149
1142
  // or publications — including no tick-completed status publication.
@@ -1151,6 +1144,9 @@ class DispatchLoop {
1151
1144
  await this.recordTickYielded()
1152
1145
  return emptyTickReport()
1153
1146
  }
1147
+ // Initialization can read/write the store. Retry it at the tick boundary
1148
+ // after a transient failure, even while our repository lease stays valid.
1149
+ await this.initializeAutomaticUpgrade()
1154
1150
  await this.reportForgeReadiness()
1155
1151
  const startedAt = await this.repoView.beginRepoTick(this.repoIdentity, this.runId)
1156
1152
  if (startedAt === null) {
@@ -1180,6 +1176,17 @@ class DispatchLoop {
1180
1176
  // Sample inside the serialized tick, not at process startup. Every
1181
1177
  // dispatcher therefore gates claims from the latest repository facts.
1182
1178
  await this.repoView.refresh()
1179
+ const executionSlugs = new Set(
1180
+ [...(await this.repoView.getRepoBuildDigests(this.repoIdentity))]
1181
+ .filter(([, digest]) => digest.executionOpen)
1182
+ .map(([slug]) => slug),
1183
+ )
1184
+ await authorizeRemoteHandoffs(
1185
+ this.wiring.store,
1186
+ this.repoIdentity,
1187
+ this.repoView.repositoryFacts().upgrades,
1188
+ executionSlugs,
1189
+ )
1183
1190
  const settings = await this.readDispatchSettings()
1184
1191
  const readyObservation =
1185
1192
  settings.intake || (!this.dashboard && this.opts.kernelRunId === undefined)
@@ -2250,11 +2257,13 @@ class DispatchLoop {
2250
2257
  private launchHarvest(): void {
2251
2258
  // Do not even start a second local contender while one is active. A second
2252
2259
  // dispatch process is independently excluded by the repository lease.
2253
- if (this.harvestInFlight !== undefined) return
2260
+ if (this.stopped || this.harvestInFlight !== undefined) return
2254
2261
 
2255
2262
  let tracked: Promise<void>
2256
2263
  tracked = this.launchHarvestIfNeeded()
2257
2264
  .catch((error: unknown) => {
2265
+ if (this.stopped || this.localHarvestShutdown.signal.aborted)
2266
+ this.localHarvestFailure = error
2258
2267
  // The gate may read the backing store after tick work dirties the view.
2259
2268
  // Contain that failure too, without relying on another store write.
2260
2269
  if (!this.stopped) {
@@ -2283,6 +2292,7 @@ class DispatchLoop {
2283
2292
  })
2284
2293
  if (pressure.trigger === undefined) return
2285
2294
  }
2295
+ if (this.stopped) return
2286
2296
  const hosted = this.wiring.workspaces.harvestExecution
2287
2297
  if (hosted !== undefined) {
2288
2298
  const execution = `${this.host}-harvest-${this.wiring.ids('inst')}`
@@ -2297,6 +2307,12 @@ class DispatchLoop {
2297
2307
 
2298
2308
  const { store, tickets, runtimes, ids, uuids, clock, storeRef, token } = this.wiring
2299
2309
  const harvestDeps = {
2310
+ shutdownSignal: AbortSignal.any([
2311
+ this.localHarvestShutdown.signal,
2312
+ this.inputStop.signal,
2313
+ ...(this.opts.signal ? [this.opts.signal] : []),
2314
+ ]),
2315
+ shutdownCause: (): 'cutover' | 'shutdown' => (this.cutoverRequested ? 'cutover' : 'shutdown'),
2300
2316
  store,
2301
2317
  tickets,
2302
2318
  config: this.currentConfig().config,
@@ -2493,6 +2509,10 @@ class DispatchLoop {
2493
2509
  }
2494
2510
  })
2495
2511
  .catch(async (error: unknown) => {
2512
+ if (this.stopped || this.localHarvestShutdown.signal.aborted) {
2513
+ this.localHarvestFailure = error
2514
+ return
2515
+ }
2496
2516
  this.pendingHarvest.harvestFailed += 1
2497
2517
  await this.appendStatus({
2498
2518
  actor: DISPATCHER,
@@ -2817,9 +2837,13 @@ class DispatchLoop {
2817
2837
  }
2818
2838
  }
2819
2839
 
2820
- /** Teardown: detach the local wait only. The guest keeps running and
2821
- * heartbeating its adopted repository lease; the execution stays open and
2822
- * a later invocation settles it from the Store plus provider liveness. */
2840
+ /** Suspend local harvest and join its durable shutdown before lease release. */
2841
+ private async stopLocalHarvest(): Promise<void> {
2842
+ this.localHarvestShutdown.abort()
2843
+ if (this.wiring.workspaces.harvestExecution === undefined) await this.harvestInFlight
2844
+ if (this.localHarvestFailure !== undefined) throw this.localHarvestFailure
2845
+ }
2846
+
2823
2847
  private async stopHostedHarvest(): Promise<void> {
2824
2848
  const entry = this.hostedHarvest
2825
2849
  if (entry === undefined) return
@@ -3182,13 +3206,16 @@ class DispatchLoop {
3182
3206
  // supervisor settles the execution from the Store.
3183
3207
  if (active.detaching) return
3184
3208
  try {
3209
+ const request = (await readBuildFacts(this.repoView, slug)).value.state
3210
+ .drainingExecutions?.[instance]?.relaunch
3211
+ const relaunch = !active.stopping && exit.exitCode === 0 && !!request
3185
3212
  await this.repoView.append(slug, {
3186
3213
  actor: DISPATCHER,
3187
3214
  type: 'execution.ended',
3188
3215
  payload: {
3189
3216
  instance,
3190
3217
  workspaceRef,
3191
- outcome: active.stopping ? 'stopped' : 'completed',
3218
+ outcome: active.stopping ? 'stopped' : relaunch ? 'relaunch' : 'completed',
3192
3219
  exitCode: exit.exitCode,
3193
3220
  },
3194
3221
  })
@@ -3213,11 +3240,15 @@ class DispatchLoop {
3213
3240
  payload: {
3214
3241
  run: this.runId,
3215
3242
  slug,
3216
- outcome: 'parked',
3243
+ outcome: relaunch ? 'relaunch' : 'parked',
3217
3244
  status: state.status,
3218
3245
  },
3219
3246
  })
3220
- this.failureNotice(`build ${slug} parked (${state.status})`)
3247
+ this.failureNotice(
3248
+ relaunch
3249
+ ? `build ${slug} relaunching on the accepted runtime`
3250
+ : `build ${slug} parked (${state.status})`,
3251
+ )
3221
3252
  return
3222
3253
  }
3223
3254
 
@@ -3232,7 +3263,7 @@ class DispatchLoop {
3232
3263
  this.warn(`build ${slug} runner failed: ${detail}`)
3233
3264
  } finally {
3234
3265
  await this.repoView.releaseLease(slug, instance)
3235
- await this.settlePendingPublication(slug)
3266
+ if (!this.retirement) await this.settlePendingPublication(slug)
3236
3267
  }
3237
3268
  },
3238
3269
  async (error) => {
@@ -3304,7 +3335,16 @@ class DispatchLoop {
3304
3335
  }
3305
3336
 
3306
3337
  private get stopped(): boolean {
3307
- return this.opts.signal?.aborted === true || this.inputStop.signal.aborted
3338
+ return (
3339
+ this.cutoverRequested || this.opts.signal?.aborted === true || this.inputStop.signal.aborted
3340
+ )
3341
+ }
3342
+
3343
+ /** An unresolved yield keeps watching until durable state decides it. */
3344
+ private get watchStopped(): boolean {
3345
+ return this.yieldPending
3346
+ ? this.opts.signal?.aborted === true || this.inputStop.signal.aborted
3347
+ : this.stopped
3308
3348
  }
3309
3349
 
3310
3350
  /** `--once` awaits everything in `inFlight` that is not tagged
@@ -3364,9 +3404,11 @@ class DispatchLoop {
3364
3404
  * is DETACHED: the guest keeps running and heartbeating its lease; the next
3365
3405
  * invocation settles the execution from the Store plus provider liveness
3366
3406
  * (AC: a restarted dispatcher never replaces a healthy environment). */
3367
- private async stopBuildExecutions(): Promise<void> {
3407
+ private async stopBuildExecutions(supervision?: 'environment'): Promise<void> {
3368
3408
  this.acceptingBuildLaunches = false
3369
- const active = [...this.activeBuildRuns.entries()]
3409
+ const active = [...this.activeBuildRuns.entries()].filter(
3410
+ ([, entry]) => !supervision || entry.handle?.supervision === supervision,
3411
+ )
3370
3412
  for (const [, entry] of active) {
3371
3413
  if (entry.handle?.supervision === 'environment') entry.detaching = true
3372
3414
  else entry.stopping = true
@@ -3427,6 +3469,7 @@ class DispatchLoop {
3427
3469
  }
3428
3470
 
3429
3471
  private say(line: string): void {
3472
+ if (this.presentationReleased) return
3430
3473
  if (!this.dashboard && this.opts.silent !== true) this.opts.stdout(line)
3431
3474
  }
3432
3475
 
@@ -3436,12 +3479,14 @@ class DispatchLoop {
3436
3479
  }
3437
3480
 
3438
3481
  private warn(line: string): void {
3482
+ if (this.presentationReleased) return
3439
3483
  if (this.dashboard) this.setWarning(line)
3440
3484
  else if (this.opts.silent !== true) this.opts.stderr(line)
3441
3485
  }
3442
3486
 
3443
3487
  /** Failure-severity dashboard notice whose historical plain sink is stdout. */
3444
3488
  private failureNotice(line: string): void {
3489
+ if (this.presentationReleased) return
3445
3490
  if (this.dashboard) this.setWarning(line)
3446
3491
  else if (this.opts.silent !== true) this.opts.stdout(line)
3447
3492
  }
@@ -3667,6 +3712,10 @@ class DispatchLoop {
3667
3712
  buildSnapshot.capacityBuilds ?? [],
3668
3713
  configSnapshot.config.capacity,
3669
3714
  this.wiring.clock(),
3715
+ migrationIdentity(
3716
+ repositoryEvents.ticketMigrations,
3717
+ configSnapshot.config.tickets.source,
3718
+ ),
3670
3719
  ),
3671
3720
  observationCount: this.observationCount,
3672
3721
  observationLimit: configSnapshot.config.policy.harvestThreshold,
@@ -3921,6 +3970,7 @@ class DispatchLoop {
3921
3970
  const requestedAt = this.wiring.clock().getTime()
3922
3971
  this.wiring.store.heartbeatRepo(this.repoIdentity, holder).then(
3923
3972
  (alive) => {
3973
+ if (this.retirement && this.repoLeaseHolder === undefined) return
3924
3974
  if (alive) {
3925
3975
  this.repoLeaseValidUntil = requestedAt + REPO_LEASE_TTL_MS
3926
3976
  return
@@ -3981,6 +4031,484 @@ class DispatchLoop {
3981
4031
  }
3982
4032
  }
3983
4033
 
4034
+ private retirement?: {
4035
+ handoff: Handoff
4036
+ successor: string
4037
+ mode: 'drain' | 'cutover'
4038
+ startedAt: string
4039
+ deadline: string
4040
+ builds: Array<{ slug: string; instance: string }>
4041
+ }
4042
+ private yieldPending = false
4043
+ private presentationReleased = false
4044
+ private upgradeRetirementSettled = true
4045
+ private handledPreflightFailure?: string
4046
+
4047
+ /** Called only inside the tick serialization boundary, before any new work. */
4048
+ private async acceptUpgradeYield(): Promise<boolean> {
4049
+ const launch = launchContext(this.opts.env)
4050
+ if (
4051
+ launch?.overlapVersion !== 1 ||
4052
+ this.watchStopped ||
4053
+ this.superseded ||
4054
+ this.repoLeaseHolder !== this.runId
4055
+ )
4056
+ return false
4057
+ const retirementPredecessor =
4058
+ launch.rollback?.predecessor ?? launch.recovery?.predecessor ?? launch.predecessor
4059
+ if (retirementPredecessor && !this.upgradeRetirementSettled)
4060
+ this.upgradeRetirementSettled = await recoverDispatchDrain(
4061
+ this.wiring.store,
4062
+ this.repoIdentity,
4063
+ retirementPredecessor,
4064
+ this.wiring.clock(),
4065
+ launch.rollback || launch.recovery ? this.runId : undefined,
4066
+ )
4067
+ const state = (await readDispatchUpgrade(this.wiring.store, this.repoIdentity)).value.runs[
4068
+ this.runId
4069
+ ]
4070
+ // A prior attempt may have committed acceptance before a read or build
4071
+ // authorization failed. Resume that decision before any repository work.
4072
+ if (state?.handoff && state.handoff.payload.lineage === launch.lineage)
4073
+ return this.adoptUpgradeYield(state.handoff)
4074
+ if (
4075
+ state?.failure &&
4076
+ state.prepared &&
4077
+ this.handledPreflightFailure !== state.failure.payload.correlation
4078
+ ) {
4079
+ this.handledPreflightFailure = state.failure.payload.correlation
4080
+ releasePreparedRuntime(state.prepared.payload.root, launch.launcherPid)
4081
+ releasePreparedRuntime(state.prepared.payload.root)
4082
+ await this.upgradeController?.stop()
4083
+ this.upgradeController = undefined
4084
+ await this.initializeAutomaticUpgrade()
4085
+ }
4086
+ const request = state?.request?.payload
4087
+ if (
4088
+ !request ||
4089
+ state.failure ||
4090
+ state.handoff ||
4091
+ request.lineage !== launch.lineage ||
4092
+ !this.currentConfig().config.upgrade.automatic
4093
+ ) {
4094
+ this.abandonUpgradeYield()
4095
+ return false
4096
+ }
4097
+ const facts = (await readDispatcherRunFacts(this.wiring.store, this.repoIdentity, this.runId))
4098
+ .value
4099
+ if (facts.stopRequest) {
4100
+ this.abandonUpgradeYield()
4101
+ return false
4102
+ }
4103
+ const lease = (await this.wiring.store.getRepo(this.repoIdentity))?.lease
4104
+ if (
4105
+ lease?.holder !== this.runId ||
4106
+ Date.parse(lease.expiresAt) <= this.wiring.clock().getTime()
4107
+ ) {
4108
+ this.superseded = true
4109
+ return false
4110
+ }
4111
+ // No launch, claim, tick or target continuation may cross this boundary.
4112
+ this.yieldPending = true
4113
+ this.acceptingBuildLaunches = false
4114
+ this.cutoverRequested = true
4115
+ // Suspend local harvest durably before transferring repository authority.
4116
+ await this.stopLocalHarvest()
4117
+ // A hosted launch can still be provisioning when yield is requested.
4118
+ // Keep joining that continuation and detach as soon as its handle exists.
4119
+ while (this.harvestInFlight) {
4120
+ await this.stopHostedHarvest()
4121
+ await Promise.race([
4122
+ this.harvestInFlight,
4123
+ new Promise<void>((resolve) => setTimeout(resolve, 25)),
4124
+ ])
4125
+ }
4126
+ await this.dispatcher.stopProvisioning()
4127
+ const currentLease = (await this.wiring.store.getRepo(this.repoIdentity))?.lease
4128
+ if (
4129
+ currentLease?.holder !== this.runId ||
4130
+ Date.parse(currentLease.expiresAt) <= this.wiring.clock().getTime()
4131
+ ) {
4132
+ this.superseded = true
4133
+ return false
4134
+ }
4135
+ const startedAt = this.wiring.clock().toISOString()
4136
+ const deadline = new Date(
4137
+ Date.parse(startedAt) + this.currentConfig().config.policy.upgradeDrainSeconds * 1000,
4138
+ ).toISOString()
4139
+ const builds = [...this.activeBuildRuns]
4140
+ .filter(([, entry]) => entry.handle?.supervision === 'local-parent')
4141
+ .map(([slug, entry]) => ({ slug, instance: entry.instance }))
4142
+ const remoteBuilds = []
4143
+ for (const [slug, digest] of await this.repoView.getRepoBuildDigests(this.repoIdentity)) {
4144
+ if (!digest.executionOpen) continue
4145
+ const facts = (await readBuildFacts(this.wiring.store, slug)).value
4146
+ if (!facts.remoteWorkspace || !facts.open) continue
4147
+ const instance = facts.open.instance
4148
+ const runtime = facts.runnerAttaches.findLast((a) => a.instance === instance)?.runtime
4149
+ remoteBuilds.push({ slug, instance, ...(runtime ? { runtime } : {}) })
4150
+ }
4151
+ const handoff: Handoff = {
4152
+ correlation: request.correlation,
4153
+ run: request.run,
4154
+ lineage: request.lineage,
4155
+ from: request.from,
4156
+ to: request.to,
4157
+ root: request.root,
4158
+ cacheId: request.cacheId,
4159
+ target: request.target,
4160
+ }
4161
+ let acceptanceError: unknown
4162
+ try {
4163
+ await this.repoView.appendRepo(this.repoIdentity, {
4164
+ actor: DISPATCHER,
4165
+ type: 'dispatcher.handoff-started',
4166
+ payload: {
4167
+ ...handoff,
4168
+ successor: request.successor,
4169
+ mode: request.mode,
4170
+ startedAt,
4171
+ deadline,
4172
+ builds,
4173
+ remoteBuilds,
4174
+ },
4175
+ })
4176
+ } catch (error) {
4177
+ acceptanceError = error
4178
+ }
4179
+
4180
+ // An append can commit before its response is lost. Only durable state
4181
+ // decides whether repository authority must transfer. If this read fails,
4182
+ // keep admission closed; a later watch attempt adopts the durable acceptance
4183
+ // before it can tick, claim or launch again.
4184
+ const accepted = (await readDispatchUpgrade(this.wiring.store, this.repoIdentity)).value.runs[
4185
+ this.runId
4186
+ ]?.handoff
4187
+ if (accepted?.payload.correlation !== handoff.correlation) {
4188
+ this.abandonUpgradeYield()
4189
+ if (acceptanceError !== undefined)
4190
+ await this.repoView.appendRepo(this.repoIdentity, {
4191
+ actor: DISPATCHER,
4192
+ type: 'dispatcher.upgrade-failed',
4193
+ payload: {
4194
+ correlation: handoff.correlation,
4195
+ run: handoff.run,
4196
+ lineage: handoff.lineage,
4197
+ from: handoff.from,
4198
+ target: handoff.target,
4199
+ reason: createReadinessRedactor(this.opts.env)(
4200
+ acceptanceError instanceof Error
4201
+ ? acceptanceError.message
4202
+ : 'handoff preparation rejected',
4203
+ ),
4204
+ },
4205
+ })
4206
+ return false
4207
+ }
4208
+ return this.adoptUpgradeYield(accepted)
4209
+ }
4210
+
4211
+ /** Reopen admission after a yield that did not durably transfer authority. */
4212
+ private abandonUpgradeYield(): void {
4213
+ if (!this.yieldPending) return
4214
+ // The joined local workflow is suspended, but subsequent ticks must be
4215
+ // able to resume it with a fresh shutdown signal.
4216
+ this.localHarvestShutdown = new AbortController()
4217
+ this.yieldPending = false
4218
+ this.cutoverRequested = false
4219
+ this.acceptingBuildLaunches = true
4220
+ }
4221
+
4222
+ /** Enter retirement from the persisted acceptance, which may predate this tick. */
4223
+ private async adoptUpgradeYield(accepted: NonNullable<UpgradeRun['handoff']>): Promise<boolean> {
4224
+ const handoff = accepted.payload
4225
+ // Legacy cutovers do not have the negotiated overlap capture.
4226
+ if (
4227
+ handoff.run !== this.runId ||
4228
+ handoff.successor === undefined ||
4229
+ handoff.mode === undefined ||
4230
+ handoff.startedAt === undefined ||
4231
+ handoff.deadline === undefined ||
4232
+ handoff.builds === undefined
4233
+ )
4234
+ return false
4235
+ this.yieldPending = true
4236
+ this.acceptingBuildLaunches = false
4237
+ this.cutoverRequested = true
4238
+ for (const build of handoff.builds)
4239
+ await this.repoView.append(build.slug, {
4240
+ actor: DISPATCHER,
4241
+ type: 'execution.drain-authorized',
4242
+ payload: {
4243
+ correlation: handoff.correlation,
4244
+ run: this.runId,
4245
+ runtime: handoff.from,
4246
+ targetRuntime: handoff.to,
4247
+ instance: build.instance,
4248
+ },
4249
+ })
4250
+ await authorizeRemoteHandoffs(
4251
+ this.wiring.store,
4252
+ this.repoIdentity,
4253
+ undefined,
4254
+ new Set((handoff.remoteBuilds ?? []).map((build) => build.slug)),
4255
+ )
4256
+ this.retirement = {
4257
+ handoff: {
4258
+ correlation: handoff.correlation,
4259
+ run: handoff.run,
4260
+ lineage: handoff.lineage,
4261
+ from: handoff.from,
4262
+ to: handoff.to,
4263
+ root: handoff.root,
4264
+ cacheId: handoff.cacheId,
4265
+ target: handoff.target,
4266
+ },
4267
+ successor: handoff.successor,
4268
+ mode: handoff.mode,
4269
+ startedAt: handoff.startedAt,
4270
+ deadline: handoff.deadline,
4271
+ builds: handoff.builds,
4272
+ }
4273
+ this.yieldPending = false
4274
+ this.inputStop.abort()
4275
+ return true
4276
+ }
4277
+
4278
+ private async retireGeneration(): Promise<void> {
4279
+ const retirement = this.retirement!
4280
+ await this.stopBuildExecutions('environment')
4281
+ await this.finishRendering()
4282
+ this.presentationReleased = true
4283
+ if (this.opts.kernelRunId === undefined) releaseDispatchPresentation()
4284
+ // Interactive kernels have no terminal authority. Their frontend must
4285
+ // acknowledge removal and joining of input/render work itself.
4286
+ if (this.opts.kernelRunId === undefined) {
4287
+ await this.repoView.appendRepo(this.repoIdentity, {
4288
+ actor: DISPATCHER,
4289
+ type: 'dispatcher.terminal-released',
4290
+ payload: retirement.handoff,
4291
+ })
4292
+ } else {
4293
+ for (;;) {
4294
+ const state = (await readDispatchUpgrade(this.wiring.store, this.repoIdentity)).value.runs[
4295
+ this.runId
4296
+ ]
4297
+ if (state?.released) break
4298
+ if (this.opts.signal?.aborted) break
4299
+ await new Promise<void>((resolve) => setTimeout(resolve, 50))
4300
+ }
4301
+ }
4302
+ await this.releaseRepoLease()
4303
+ const pending = new Map(retirement.builds.map((build) => [build.slug, build.instance]))
4304
+ const settle = async (
4305
+ slug: string,
4306
+ instance: string,
4307
+ outcome: 'drained' | 'suspended' | 'unknown',
4308
+ ) => {
4309
+ await this.repoView.append(slug, {
4310
+ actor: DISPATCHER,
4311
+ type: 'execution.drain-settled',
4312
+ payload: { correlation: retirement.handoff.correlation, instance },
4313
+ })
4314
+ await this.repoView.appendRepo(this.repoIdentity, {
4315
+ actor: DISPATCHER,
4316
+ type: 'dispatcher.drain-settled',
4317
+ payload: { ...retirement.handoff, slug, instance, outcome },
4318
+ })
4319
+ pending.delete(slug)
4320
+ }
4321
+ while (pending.size) {
4322
+ for (const [slug, instance] of pending)
4323
+ if (this.activeBuildRuns.get(slug)?.instance !== instance)
4324
+ await settle(slug, instance, 'drained')
4325
+ if (!pending.size) break
4326
+ if (
4327
+ retirement.mode === 'cutover' ||
4328
+ this.opts.signal?.aborted ||
4329
+ this.wiring.clock().getTime() >= Date.parse(retirement.deadline)
4330
+ )
4331
+ break
4332
+ // Read-only policy supervision: never another tick or config fan-out.
4333
+ try {
4334
+ const { loadConfig } = await import('../config/load')
4335
+ const config = await loadConfig(join(this.opts.targetRepo, 'autobuild.toml'))
4336
+ const { createRuntimeResolver } = await import('../ports/runner/routing')
4337
+ createRuntimeResolver(
4338
+ this.wiring.runtimes,
4339
+ config.roles,
4340
+ config.policy.sessionBudgetSeconds,
4341
+ )
4342
+ const deadline = new Date(
4343
+ Date.parse(retirement.startedAt) + config.policy.upgradeDrainSeconds * 1000,
4344
+ ).toISOString()
4345
+ if (deadline !== retirement.deadline) {
4346
+ await this.repoView.appendRepo(this.repoIdentity, {
4347
+ actor: DISPATCHER,
4348
+ type: 'dispatcher.drain-deadline',
4349
+ payload: { ...retirement.handoff, deadline },
4350
+ })
4351
+ retirement.deadline = deadline
4352
+ }
4353
+ } catch {
4354
+ /* Retain the last accepted policy. */
4355
+ }
4356
+ await new Promise<void>((resolve) => setTimeout(resolve, 250))
4357
+ }
4358
+ // Existing stop orders native suspension before process-group reaping.
4359
+ await this.stopBuildExecutions()
4360
+ for (const [slug, instance] of pending) {
4361
+ const execution = (await readBuildFacts(this.wiring.store, slug)).value.state
4362
+ .drainingExecutions?.[instance]
4363
+ const suspendedHere = execution?.suspended
4364
+ const ended = execution?.ended
4365
+ await settle(slug, instance, suspendedHere ? 'suspended' : ended ? 'drained' : 'unknown')
4366
+ }
4367
+ const settled = (await readDispatchUpgrade(this.wiring.store, this.repoIdentity)).value.runs[
4368
+ this.runId
4369
+ ]!
4370
+ if (settled.completed) return
4371
+ await this.repoView.appendRepo(this.repoIdentity, {
4372
+ actor: DISPATCHER,
4373
+ type: 'dispatcher.handoff-completed',
4374
+ payload: {
4375
+ ...retirement.handoff,
4376
+ successor: retirement.successor,
4377
+ mode: retirement.mode,
4378
+ startedAt: retirement.startedAt,
4379
+ endedAt: this.wiring.clock().toISOString(),
4380
+ drained: settled.drained,
4381
+ suspended: settled.suspended,
4382
+ },
4383
+ })
4384
+ }
4385
+
4386
+ private async initializeAutomaticUpgrade(): Promise<void> {
4387
+ if (this.upgradeController) return
4388
+ const launch = launchContext(this.opts.env)
4389
+ if (!launch || this.opts.once || this.opts.repository || this.repoLeaseHolder !== this.runId)
4390
+ return
4391
+ await recordRuntimeRollback(this.wiring.store, this.repoIdentity, launch, this.runId)
4392
+ const upgrades = (await readDispatchUpgrade(this.wiring.store, this.repoIdentity)).value
4393
+ const hold = upgrades.holds[launch.lineage!]
4394
+ syncRollbackRetention(
4395
+ runtimeDirname(runtimeDirname(launch.runtimeRoot)),
4396
+ launch.lineage!,
4397
+ hold?.payload.failedRoot,
4398
+ )
4399
+ const retirementPredecessor =
4400
+ launch.rollback?.predecessor ?? launch.recovery?.predecessor ?? launch.predecessor
4401
+ this.upgradeRetirementSettled =
4402
+ !retirementPredecessor ||
4403
+ !upgrades.runs[retirementPredecessor]?.request ||
4404
+ !!upgrades.runs[retirementPredecessor]?.completed
4405
+ if (
4406
+ !this.handoffCompleted &&
4407
+ launch.predecessor &&
4408
+ !upgrades.runs[launch.predecessor]?.request
4409
+ ) {
4410
+ const previous = upgrades.runs[launch.predecessor]
4411
+ const handoff = previous?.handoff?.payload
4412
+ if (
4413
+ !handoff ||
4414
+ previous.completed ||
4415
+ handoff.lineage !== launch.lineage ||
4416
+ handoff.root !== launch.runtimeRoot
4417
+ )
4418
+ throw new Error('successor has no matching durable handoff')
4419
+ await this.repoView.appendRepo(this.repoIdentity, {
4420
+ actor: DISPATCHER,
4421
+ type: 'dispatcher.handoff-completed',
4422
+ payload: { ...handoff, successor: this.runId },
4423
+ })
4424
+ this.handoffCompleted = true
4425
+ }
4426
+ if (this.upgradeController) return
4427
+ const redact = createReadinessRedactor(this.opts.env)
4428
+ const inspectStore = async () =>
4429
+ (await this.wiring.store.inspectDispatcherOverlap?.(AbortSignal.timeout(30_000)))?.evidence
4430
+ let failedStoreEvidence = Object.values(upgrades.runs).some((state) => state.failure)
4431
+ ? await inspectStore().catch(() => undefined)
4432
+ : undefined
4433
+ this.upgradeController = new DispatchUpgradeController({
4434
+ run: this.runId,
4435
+ lineage: launch.lineage!,
4436
+ from: RUNTIME_IDENTITY,
4437
+ runningBunTag: (await readDistributionIdentity(distributionRoot())).bunTag,
4438
+ reservationOwner: launch.launcherPid,
4439
+ resolved: upgrades.runs[this.runId]?.resolved,
4440
+ currentKey:
4441
+ (launch.recovery?.predecessor ?? launch.predecessor)
4442
+ ? upgrades.runs[(launch.recovery?.predecessor ?? launch.predecessor)!]?.handoff?.payload
4443
+ .target.key
4444
+ : launch.sourceLaunch?.baseline,
4445
+ storeChangedSinceFailure: async () => {
4446
+ const evidence = await inspectStore().catch(() => undefined)
4447
+ const changed =
4448
+ failedStoreEvidence !== undefined &&
4449
+ evidence !== undefined &&
4450
+ evidence !== failedStoreEvidence
4451
+ if (evidence !== undefined) failedStoreEvidence = evidence
4452
+ return changed
4453
+ },
4454
+ hold,
4455
+ clearHold: () =>
4456
+ syncRollbackRetention(runtimeDirname(runtimeDirname(launch.runtimeRoot)), launch.lineage!),
4457
+ failedKeys: Object.values(upgrades.runs).flatMap((state) =>
4458
+ state.failure && state.failure.payload.lineage === launch.lineage
4459
+ ? [state.failure.payload.target.key]
4460
+ : [],
4461
+ ),
4462
+ enabled: () =>
4463
+ !this.stopped &&
4464
+ !this.superseded &&
4465
+ this.currentConfig().config.upgrade.automatic &&
4466
+ this.upgradeRetirementSettled,
4467
+ resolve: (signal) =>
4468
+ resolveUpgradeTarget({
4469
+ checkout: this.opts.targetRepo,
4470
+ base: this.currentConfig().config.baseBranch,
4471
+ originalInstall: launch.originalInstall!,
4472
+ sourceLaunch: launch.sourceLaunch,
4473
+ forge: this.wiring.forge,
4474
+ exec: this.opts.exec,
4475
+ signal,
4476
+ }),
4477
+ prepare: (target, signal) =>
4478
+ prepareUpgrade({ target, checkout: this.opts.targetRepo, signal, env: this.opts.env }),
4479
+ redact,
4480
+ append: (event) => this.repoView.appendRepo(this.repoIdentity, event),
4481
+ cutover: (handoff: Handoff) =>
4482
+ this.serialize(async () => {
4483
+ if (
4484
+ this.stopped ||
4485
+ this.superseded ||
4486
+ !this.currentConfig().config.upgrade.automatic ||
4487
+ this.repoLeaseHolder !== this.runId
4488
+ )
4489
+ return false
4490
+ if (launch.overlapVersion !== 1)
4491
+ throw new Error(
4492
+ 'launcher lacks overlapping preflight supervision; manual restart required',
4493
+ )
4494
+ await this.repoView.appendRepo(this.repoIdentity, {
4495
+ actor: DISPATCHER,
4496
+ type: 'dispatcher.target-prepared',
4497
+ payload: handoff,
4498
+ })
4499
+ return true
4500
+ }),
4501
+ })
4502
+ this.opts.signal?.addEventListener(
4503
+ 'abort',
4504
+ () => {
4505
+ void this.upgradeController?.stop()
4506
+ },
4507
+ { once: true },
4508
+ )
4509
+ this.upgradeController.start()
4510
+ }
4511
+
3984
4512
  async run(): Promise<void> {
3985
4513
  // Before the `--once` branch, so both modes report it exactly once.
3986
4514
  this.reportRoleDiagnostics()
@@ -4037,7 +4565,9 @@ class DispatchLoop {
4037
4565
  this.printReport(emptyTickReport())
4038
4566
  }
4039
4567
  } finally {
4568
+ this.localHarvestShutdown.abort()
4040
4569
  await this.stopBuildExecutions()
4570
+ await this.stopLocalHarvest()
4041
4571
  await this.stopHostedHarvest()
4042
4572
  // Signal provisioning continuations and release their leases before
4043
4573
  // the repository lease, so the next supervisor adopts immediately.
@@ -4063,7 +4593,7 @@ class DispatchLoop {
4063
4593
  this.startRendering()
4064
4594
  this.startUpgradeChecks()
4065
4595
  let startup = true
4066
- while (!this.stopped && !this.superseded) {
4596
+ while (!this.watchStopped && !this.superseded) {
4067
4597
  try {
4068
4598
  const report = await this.dispatcherTick(startup)
4069
4599
  this.printReport(report, this.harvestInFlight === undefined)
@@ -4074,26 +4604,33 @@ class DispatchLoop {
4074
4604
  await this.publishTickFailure(error)
4075
4605
  this.warn(`tick failed: ${message}`)
4076
4606
  }
4077
- if (this.stopped || this.superseded) break
4607
+ if (this.watchStopped || this.superseded) break
4078
4608
  await sleep(intervalMs)
4079
4609
  }
4080
4610
  if (this.superseded) {
4081
4611
  this.warn('dispatcher superseded by another invocation — detaching')
4082
4612
  }
4083
4613
  } finally {
4084
- await this.stopBuildExecutions()
4085
- await this.stopHostedHarvest()
4086
- // Signal provisioning continuations and release their leases before
4087
- // the repository lease, so the next supervisor adopts immediately.
4088
- await this.dispatcher.stopProvisioning()
4089
- // Stop input and join teardown work first so every result that becomes
4090
- // reportable at that boundary is included. Active Harvest work is still
4091
- // deliberately not awaited in watch mode.
4092
- await this.finishRendering()
4093
- for (const report of await this.publishSettlementReports()) {
4094
- this.printReport(report, false)
4614
+ this.localHarvestShutdown.abort()
4615
+ await this.upgradeController?.stop()
4616
+ if (this.retirement) {
4617
+ await this.retireGeneration()
4618
+ } else {
4619
+ await this.stopBuildExecutions()
4620
+ await this.stopLocalHarvest()
4621
+ await this.stopHostedHarvest()
4622
+ // Signal provisioning continuations and release their leases before
4623
+ // the repository lease, so the next supervisor adopts immediately.
4624
+ await this.dispatcher.stopProvisioning()
4625
+ // Stop input and join teardown work first so every result that becomes
4626
+ // reportable at that boundary is included. Local harvest suspension
4627
+ // is durable before lease release.
4628
+ await this.finishRendering()
4629
+ for (const report of await this.publishSettlementReports()) {
4630
+ this.printReport(report, false)
4631
+ }
4632
+ await this.releaseRepoLease()
4095
4633
  }
4096
- await this.releaseRepoLease()
4097
4634
  }
4098
4635
  // The finished interactive frame stays on screen; never append a late line
4099
4636
  // beneath it. Plain mode retains its historical shutdown line.
@@ -4429,7 +4966,10 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4429
4966
  // is `randomIds()`, so a getter re-evaluating it would re-mint per access.
4430
4967
  // Everything below (startup deposits, the loop's journal payloads, both
4431
4968
  // lease sites) carries this one value.
4432
- const runId = resolvedOpts.kernelRunId ?? `${hostname()}-dispatch-${wiring.ids('inst')}`
4969
+ const runId =
4970
+ resolvedOpts.kernelRunId ??
4971
+ launchContext(resolvedOpts.env)?.run ??
4972
+ `${hostname()}-dispatch-${wiring.ids('inst')}`
4433
4973
  resolvedOpts.runId = runId
4434
4974
  // Construction eagerly validates every startup role before repository
4435
4975
  // settings or runner work can mutate durable state. The publisher is used
@@ -4503,7 +5043,7 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4503
5043
  })
4504
5044
  }
4505
5045
 
4506
- await view.appendRepoWithArtifacts(
5046
+ const started = await view.appendRepoWithArtifacts(
4507
5047
  state.repo,
4508
5048
  [
4509
5049
  {
@@ -4520,6 +5060,9 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4520
5060
  type: 'dispatcher.run-started',
4521
5061
  payload: {
4522
5062
  run: runId,
5063
+ ...(launchContext(resolvedOpts.env)?.lineage
5064
+ ? { lineage: launchContext(resolvedOpts.env)!.lineage }
5065
+ : {}),
4523
5066
  pid: process.pid,
4524
5067
  host: hostname(),
4525
5068
  effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
@@ -4529,8 +5072,14 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4529
5072
  },
4530
5073
  )
4531
5074
 
4532
- const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
4533
5075
  try {
5076
+ await view.appendRepo(state.repo, {
5077
+ actor: DISPATCHER,
5078
+ type: 'dispatcher.runtime-recorded',
5079
+ payload: { run: runId, startedSeq: started.event.seq, runtime: RUNTIME_IDENTITY },
5080
+ })
5081
+
5082
+ const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
4534
5083
  await loop.run()
4535
5084
  const stopRequest =
4536
5085
  resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted