@defrex/autobuild 1.0.0-beta.3 → 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 (130) hide show
  1. package/SPEC.md +317 -20
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +166 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +87 -2
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +4 -1
  10. package/docs/restacking.md +4 -1
  11. package/docs/setup.md +20 -0
  12. package/docs/spec-standard.md +23 -5
  13. package/package.json +3 -3
  14. package/packages/core/src/cli/artifact.ts +5 -4
  15. package/packages/core/src/cli/attention.ts +2 -0
  16. package/packages/core/src/cli/binary-direct.ts +190 -0
  17. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  18. package/packages/core/src/cli/binary.ts +24 -210
  19. package/packages/core/src/cli/build-control.ts +105 -2
  20. package/packages/core/src/cli/context.ts +41 -1
  21. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  22. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  23. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  24. package/packages/core/src/cli/dashboard/model.ts +34 -10
  25. package/packages/core/src/cli/dashboard/render.ts +24 -2
  26. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  27. package/packages/core/src/cli/dispatch-args.ts +53 -0
  28. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  29. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  30. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  31. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  32. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  33. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  34. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  35. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  36. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  37. package/packages/core/src/cli/dispatch-process.ts +22 -90
  38. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  39. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  40. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  41. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  42. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  43. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  44. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  45. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  46. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  47. package/packages/core/src/cli/dispatch.ts +604 -60
  48. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  49. package/packages/core/src/cli/harvest.ts +28 -11
  50. package/packages/core/src/cli/help.ts +6 -3
  51. package/packages/core/src/cli/installation.ts +5 -3
  52. package/packages/core/src/cli/main-checkout.ts +59 -0
  53. package/packages/core/src/cli/main.ts +15 -45
  54. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  55. package/packages/core/src/cli/repo-state.ts +3 -58
  56. package/packages/core/src/cli/repository-status.ts +67 -3
  57. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  58. package/packages/core/src/cli/status.ts +57 -3
  59. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  60. package/packages/core/src/cli/wait.ts +3 -0
  61. package/packages/core/src/cli/watch.ts +7 -0
  62. package/packages/core/src/config/live.ts +1 -0
  63. package/packages/core/src/config/schema.ts +8 -4
  64. package/packages/core/src/distribution-packaging.ts +116 -0
  65. package/packages/core/src/events/catalog.ts +6 -0
  66. package/packages/core/src/events/payloads.ts +53 -9
  67. package/packages/core/src/events/policy.ts +25 -0
  68. package/packages/core/src/events/repository.ts +184 -4
  69. package/packages/core/src/events/runtime.ts +16 -0
  70. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  71. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  72. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  73. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  74. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  75. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  76. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  77. package/packages/core/src/kernel/harvest.ts +98 -4
  78. package/packages/core/src/kernel/integration-attention.ts +20 -0
  79. package/packages/core/src/kernel/integration-state.ts +80 -11
  80. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  81. package/packages/core/src/kernel/mixed-version.ts +34 -0
  82. package/packages/core/src/kernel/node-polling.ts +160 -0
  83. package/packages/core/src/kernel/read-facts.ts +40 -5
  84. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  85. package/packages/core/src/kernel/reducer.ts +75 -14
  86. package/packages/core/src/kernel/service-facts.ts +11 -4
  87. package/packages/core/src/operator/presentation.ts +7 -0
  88. package/packages/core/src/operator/query.ts +6 -2
  89. package/packages/core/src/operator/registry.ts +1 -1
  90. package/packages/core/src/plugins/load.ts +4 -1
  91. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  92. package/packages/core/src/ports/forge/contract.ts +29 -0
  93. package/packages/core/src/ports/forge/github.ts +189 -61
  94. package/packages/core/src/ports/forge-failure.ts +1 -0
  95. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  96. package/packages/core/src/ports/runner/session-env.ts +1 -0
  97. package/packages/core/src/ports/types.ts +10 -0
  98. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  99. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  100. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  101. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  102. package/packages/core/src/processes/build-child-exit.ts +5 -26
  103. package/packages/core/src/processes/build-runner.ts +81 -11
  104. package/packages/core/src/processes/dispatcher.ts +254 -23
  105. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  106. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  107. package/packages/core/src/processes/execution-settlement.ts +16 -7
  108. package/packages/core/src/processes/harvest-runner.ts +328 -292
  109. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  110. package/packages/core/src/runtime-identity.ts +22 -3
  111. package/packages/core/src/store/contract.ts +153 -0
  112. package/packages/core/src/store/local/store.ts +197 -72
  113. package/packages/core/src/store/reduced-reads.ts +8 -0
  114. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  115. package/packages/core/src/store/remote/client.ts +43 -0
  116. package/packages/core/src/store/repo-state-events.ts +20 -3
  117. package/packages/core/src/store/types.ts +7 -0
  118. package/skills/guide/SKILL.md +231 -23
  119. package/skills/guide/references/integration-tree.md +87 -2
  120. package/skills/guide/references/operator-api.md +53 -4
  121. package/skills/guide/references/plugin-authoring.md +45 -4
  122. package/skills/guide/references/remote-store-protocol.md +4 -1
  123. package/skills/guide/references/restacking.md +4 -1
  124. package/skills/guide/references/setup.md +20 -0
  125. package/skills/guide/references/spec-standard.md +23 -5
  126. package/skills/harvest/SKILL.md +4 -0
  127. package/skills/harvest-review/SKILL.md +4 -0
  128. package/skills/operate/SKILL.md +78 -8
  129. package/skills/spec/SKILL.md +19 -1
  130. package/skills/tickets/SKILL.md +19 -0
@@ -1,5 +1,20 @@
1
1
  import { migrationIdentity } from '../kernel/ticket-migrations'
2
- import { formatDispatcherError } from '../runtime-identity'
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'
3
18
 
4
19
  import { isDeepStrictEqual } from 'node:util'
5
20
  import { guardForge } from '../kernel/guarded-forge'
@@ -479,37 +494,7 @@ async function defaultWire(
479
494
  // Origin mode: no checkout exists, so the provider's host git seams are
480
495
  // replaced by the injected origin and the forge's remote reads.
481
496
  const originMode = opts.repository !== undefined
482
- // Dispatch preflight is capability-driven (AUT-516): forge support, origin
483
- // validation, and required environment all read the selected provider's
484
- // registration declarations — builtin and plugin alike — instead of naming
485
- // a provider.
486
- const workspaceCaps = plugins.workspaceProviders.get(config.workspace.provider)?.capabilities
487
- if (workspaceCaps?.supportedForges !== undefined) {
488
- if (!workspaceCaps.supportedForges.includes(config.forge)) {
489
- throw new Error(
490
- workspaceCaps.forgeDispatchMessage ??
491
- `workspace provider "${config.workspace.provider}" does not support forge "${config.forge}"`,
492
- )
493
- }
494
- }
495
- if (workspaceCaps?.validateOrigin !== undefined && !originMode) {
496
- const origin = await opts.exec(['git', 'remote', 'get-url', 'origin'], {
497
- cwd: opts.targetRepo,
498
- })
499
- if (origin.exitCode !== 0)
500
- throw new Error(
501
- workspaceCaps.originReadFailureMessage ??
502
- `workspace provider "${config.workspace.provider}" requires a readable Git origin`,
503
- )
504
- workspaceCaps.validateOrigin(origin.stdout.trim())
505
- }
506
- for (const group of workspaceCaps?.requiredEnv ?? []) {
507
- if (group.dispatchMessage === undefined) continue
508
- const satisfied = group.alternatives.some((names) =>
509
- names.every((name) => opts.env[name] !== undefined && opts.env[name] !== ''),
510
- )
511
- if (!satisfied) throw new Error(group.dispatchMessage)
512
- }
497
+ await validateWorkspaceDispatchConfiguration(config, opts, plugins)
513
498
  // The builtin GitHub forge resolves its credential lazily on its first
514
499
  // request (GITHUB_TOKEN, GH_TOKEN, then the gh CLI login) and names the
515
500
  // miss reason on any request that had to go out anonymously; nothing is
@@ -640,6 +625,8 @@ class DispatchLoop {
640
625
  private readonly activeBuildRuns = new Map<string, ActiveBuildExecution>()
641
626
  private acceptingBuildLaunches = true
642
627
  /** Process-local fast path; the repository lease is the cross-process gate. */
628
+ private localHarvestShutdown = new AbortController()
629
+ private localHarvestFailure: unknown
643
630
  private harvestInFlight: Promise<void> | undefined
644
631
  /** Live hosted-harvest execution: the environment-supervised handle whose
645
632
  * completion chain classifies, releases, and journals the close fact.
@@ -708,6 +695,9 @@ class DispatchLoop {
708
695
  /** Process-local, persistent release notice. It never shares the replaceable
709
696
  * warning slot and is re-applied to every store projection. */
710
697
  private availableUpgrade: string | undefined
698
+ private upgradeController?: DispatchUpgradeController
699
+ private cutoverRequested = false
700
+ private handoffCompleted = false
711
701
  private stopUpgradeNotice: (() => void) | undefined
712
702
  /** Startup, configuration-level notices — constant for the life of the
713
703
  * process. Rendered ABOVE the transient warning line and never overwritten by
@@ -1112,6 +1102,7 @@ class DispatchLoop {
1112
1102
  }
1113
1103
 
1114
1104
  await this.publishActiveBuildConfigs(outcome.snapshot)
1105
+ this.upgradeController?.changed()
1115
1106
  this.announce(`autobuild.toml reloaded (revision ${outcome.snapshot.revision})`)
1116
1107
  if (outcome.restartRequired.length > 0) {
1117
1108
  this.warn(
@@ -1145,6 +1136,7 @@ class DispatchLoop {
1145
1136
  // Refresh before every watch decision. The owner publishes atomically;
1146
1137
  // everything below captures the resulting one snapshot for this tick.
1147
1138
  await this.refreshConfig()
1139
+ if (await this.acceptUpgradeYield()) return emptyTickReport()
1148
1140
  // Every tick verifies local lease currency, reclaiming when necessary. Without it,
1149
1141
  // this invocation records the yield and performs no claims, launches,
1150
1142
  // or publications — including no tick-completed status publication.
@@ -1152,6 +1144,9 @@ class DispatchLoop {
1152
1144
  await this.recordTickYielded()
1153
1145
  return emptyTickReport()
1154
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()
1155
1150
  await this.reportForgeReadiness()
1156
1151
  const startedAt = await this.repoView.beginRepoTick(this.repoIdentity, this.runId)
1157
1152
  if (startedAt === null) {
@@ -1181,6 +1176,17 @@ class DispatchLoop {
1181
1176
  // Sample inside the serialized tick, not at process startup. Every
1182
1177
  // dispatcher therefore gates claims from the latest repository facts.
1183
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
+ )
1184
1190
  const settings = await this.readDispatchSettings()
1185
1191
  const readyObservation =
1186
1192
  settings.intake || (!this.dashboard && this.opts.kernelRunId === undefined)
@@ -2251,11 +2257,13 @@ class DispatchLoop {
2251
2257
  private launchHarvest(): void {
2252
2258
  // Do not even start a second local contender while one is active. A second
2253
2259
  // dispatch process is independently excluded by the repository lease.
2254
- if (this.harvestInFlight !== undefined) return
2260
+ if (this.stopped || this.harvestInFlight !== undefined) return
2255
2261
 
2256
2262
  let tracked: Promise<void>
2257
2263
  tracked = this.launchHarvestIfNeeded()
2258
2264
  .catch((error: unknown) => {
2265
+ if (this.stopped || this.localHarvestShutdown.signal.aborted)
2266
+ this.localHarvestFailure = error
2259
2267
  // The gate may read the backing store after tick work dirties the view.
2260
2268
  // Contain that failure too, without relying on another store write.
2261
2269
  if (!this.stopped) {
@@ -2284,6 +2292,7 @@ class DispatchLoop {
2284
2292
  })
2285
2293
  if (pressure.trigger === undefined) return
2286
2294
  }
2295
+ if (this.stopped) return
2287
2296
  const hosted = this.wiring.workspaces.harvestExecution
2288
2297
  if (hosted !== undefined) {
2289
2298
  const execution = `${this.host}-harvest-${this.wiring.ids('inst')}`
@@ -2298,6 +2307,12 @@ class DispatchLoop {
2298
2307
 
2299
2308
  const { store, tickets, runtimes, ids, uuids, clock, storeRef, token } = this.wiring
2300
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'),
2301
2316
  store,
2302
2317
  tickets,
2303
2318
  config: this.currentConfig().config,
@@ -2494,6 +2509,10 @@ class DispatchLoop {
2494
2509
  }
2495
2510
  })
2496
2511
  .catch(async (error: unknown) => {
2512
+ if (this.stopped || this.localHarvestShutdown.signal.aborted) {
2513
+ this.localHarvestFailure = error
2514
+ return
2515
+ }
2497
2516
  this.pendingHarvest.harvestFailed += 1
2498
2517
  await this.appendStatus({
2499
2518
  actor: DISPATCHER,
@@ -2818,9 +2837,13 @@ class DispatchLoop {
2818
2837
  }
2819
2838
  }
2820
2839
 
2821
- /** Teardown: detach the local wait only. The guest keeps running and
2822
- * heartbeating its adopted repository lease; the execution stays open and
2823
- * 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
+
2824
2847
  private async stopHostedHarvest(): Promise<void> {
2825
2848
  const entry = this.hostedHarvest
2826
2849
  if (entry === undefined) return
@@ -3183,13 +3206,16 @@ class DispatchLoop {
3183
3206
  // supervisor settles the execution from the Store.
3184
3207
  if (active.detaching) return
3185
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
3186
3212
  await this.repoView.append(slug, {
3187
3213
  actor: DISPATCHER,
3188
3214
  type: 'execution.ended',
3189
3215
  payload: {
3190
3216
  instance,
3191
3217
  workspaceRef,
3192
- outcome: active.stopping ? 'stopped' : 'completed',
3218
+ outcome: active.stopping ? 'stopped' : relaunch ? 'relaunch' : 'completed',
3193
3219
  exitCode: exit.exitCode,
3194
3220
  },
3195
3221
  })
@@ -3214,11 +3240,15 @@ class DispatchLoop {
3214
3240
  payload: {
3215
3241
  run: this.runId,
3216
3242
  slug,
3217
- outcome: 'parked',
3243
+ outcome: relaunch ? 'relaunch' : 'parked',
3218
3244
  status: state.status,
3219
3245
  },
3220
3246
  })
3221
- 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
+ )
3222
3252
  return
3223
3253
  }
3224
3254
 
@@ -3233,7 +3263,7 @@ class DispatchLoop {
3233
3263
  this.warn(`build ${slug} runner failed: ${detail}`)
3234
3264
  } finally {
3235
3265
  await this.repoView.releaseLease(slug, instance)
3236
- await this.settlePendingPublication(slug)
3266
+ if (!this.retirement) await this.settlePendingPublication(slug)
3237
3267
  }
3238
3268
  },
3239
3269
  async (error) => {
@@ -3305,7 +3335,16 @@ class DispatchLoop {
3305
3335
  }
3306
3336
 
3307
3337
  private get stopped(): boolean {
3308
- 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
3309
3348
  }
3310
3349
 
3311
3350
  /** `--once` awaits everything in `inFlight` that is not tagged
@@ -3365,9 +3404,11 @@ class DispatchLoop {
3365
3404
  * is DETACHED: the guest keeps running and heartbeating its lease; the next
3366
3405
  * invocation settles the execution from the Store plus provider liveness
3367
3406
  * (AC: a restarted dispatcher never replaces a healthy environment). */
3368
- private async stopBuildExecutions(): Promise<void> {
3407
+ private async stopBuildExecutions(supervision?: 'environment'): Promise<void> {
3369
3408
  this.acceptingBuildLaunches = false
3370
- const active = [...this.activeBuildRuns.entries()]
3409
+ const active = [...this.activeBuildRuns.entries()].filter(
3410
+ ([, entry]) => !supervision || entry.handle?.supervision === supervision,
3411
+ )
3371
3412
  for (const [, entry] of active) {
3372
3413
  if (entry.handle?.supervision === 'environment') entry.detaching = true
3373
3414
  else entry.stopping = true
@@ -3428,6 +3469,7 @@ class DispatchLoop {
3428
3469
  }
3429
3470
 
3430
3471
  private say(line: string): void {
3472
+ if (this.presentationReleased) return
3431
3473
  if (!this.dashboard && this.opts.silent !== true) this.opts.stdout(line)
3432
3474
  }
3433
3475
 
@@ -3437,12 +3479,14 @@ class DispatchLoop {
3437
3479
  }
3438
3480
 
3439
3481
  private warn(line: string): void {
3482
+ if (this.presentationReleased) return
3440
3483
  if (this.dashboard) this.setWarning(line)
3441
3484
  else if (this.opts.silent !== true) this.opts.stderr(line)
3442
3485
  }
3443
3486
 
3444
3487
  /** Failure-severity dashboard notice whose historical plain sink is stdout. */
3445
3488
  private failureNotice(line: string): void {
3489
+ if (this.presentationReleased) return
3446
3490
  if (this.dashboard) this.setWarning(line)
3447
3491
  else if (this.opts.silent !== true) this.opts.stdout(line)
3448
3492
  }
@@ -3926,6 +3970,7 @@ class DispatchLoop {
3926
3970
  const requestedAt = this.wiring.clock().getTime()
3927
3971
  this.wiring.store.heartbeatRepo(this.repoIdentity, holder).then(
3928
3972
  (alive) => {
3973
+ if (this.retirement && this.repoLeaseHolder === undefined) return
3929
3974
  if (alive) {
3930
3975
  this.repoLeaseValidUntil = requestedAt + REPO_LEASE_TTL_MS
3931
3976
  return
@@ -3986,6 +4031,484 @@ class DispatchLoop {
3986
4031
  }
3987
4032
  }
3988
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
+
3989
4512
  async run(): Promise<void> {
3990
4513
  // Before the `--once` branch, so both modes report it exactly once.
3991
4514
  this.reportRoleDiagnostics()
@@ -4042,7 +4565,9 @@ class DispatchLoop {
4042
4565
  this.printReport(emptyTickReport())
4043
4566
  }
4044
4567
  } finally {
4568
+ this.localHarvestShutdown.abort()
4045
4569
  await this.stopBuildExecutions()
4570
+ await this.stopLocalHarvest()
4046
4571
  await this.stopHostedHarvest()
4047
4572
  // Signal provisioning continuations and release their leases before
4048
4573
  // the repository lease, so the next supervisor adopts immediately.
@@ -4068,7 +4593,7 @@ class DispatchLoop {
4068
4593
  this.startRendering()
4069
4594
  this.startUpgradeChecks()
4070
4595
  let startup = true
4071
- while (!this.stopped && !this.superseded) {
4596
+ while (!this.watchStopped && !this.superseded) {
4072
4597
  try {
4073
4598
  const report = await this.dispatcherTick(startup)
4074
4599
  this.printReport(report, this.harvestInFlight === undefined)
@@ -4079,26 +4604,33 @@ class DispatchLoop {
4079
4604
  await this.publishTickFailure(error)
4080
4605
  this.warn(`tick failed: ${message}`)
4081
4606
  }
4082
- if (this.stopped || this.superseded) break
4607
+ if (this.watchStopped || this.superseded) break
4083
4608
  await sleep(intervalMs)
4084
4609
  }
4085
4610
  if (this.superseded) {
4086
4611
  this.warn('dispatcher superseded by another invocation — detaching')
4087
4612
  }
4088
4613
  } finally {
4089
- await this.stopBuildExecutions()
4090
- await this.stopHostedHarvest()
4091
- // Signal provisioning continuations and release their leases before
4092
- // the repository lease, so the next supervisor adopts immediately.
4093
- await this.dispatcher.stopProvisioning()
4094
- // Stop input and join teardown work first so every result that becomes
4095
- // reportable at that boundary is included. Active Harvest work is still
4096
- // deliberately not awaited in watch mode.
4097
- await this.finishRendering()
4098
- for (const report of await this.publishSettlementReports()) {
4099
- 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()
4100
4633
  }
4101
- await this.releaseRepoLease()
4102
4634
  }
4103
4635
  // The finished interactive frame stays on screen; never append a late line
4104
4636
  // beneath it. Plain mode retains its historical shutdown line.
@@ -4434,7 +4966,10 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4434
4966
  // is `randomIds()`, so a getter re-evaluating it would re-mint per access.
4435
4967
  // Everything below (startup deposits, the loop's journal payloads, both
4436
4968
  // lease sites) carries this one value.
4437
- 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')}`
4438
4973
  resolvedOpts.runId = runId
4439
4974
  // Construction eagerly validates every startup role before repository
4440
4975
  // settings or runner work can mutate durable state. The publisher is used
@@ -4508,7 +5043,7 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4508
5043
  })
4509
5044
  }
4510
5045
 
4511
- await view.appendRepoWithArtifacts(
5046
+ const started = await view.appendRepoWithArtifacts(
4512
5047
  state.repo,
4513
5048
  [
4514
5049
  {
@@ -4525,6 +5060,9 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4525
5060
  type: 'dispatcher.run-started',
4526
5061
  payload: {
4527
5062
  run: runId,
5063
+ ...(launchContext(resolvedOpts.env)?.lineage
5064
+ ? { lineage: launchContext(resolvedOpts.env)!.lineage }
5065
+ : {}),
4528
5066
  pid: process.pid,
4529
5067
  host: hostname(),
4530
5068
  effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
@@ -4534,8 +5072,14 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
4534
5072
  },
4535
5073
  )
4536
5074
 
4537
- const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
4538
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)
4539
5083
  await loop.run()
4540
5084
  const stopRequest =
4541
5085
  resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted