@defrex/autobuild 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +85 -14
  3. package/docs/answering-blocked-builds.md +7 -4
  4. package/docs/architecture.md +38 -10
  5. package/docs/configuration.md +55 -5
  6. package/docs/dispatcher.md +2 -2
  7. package/docs/glossary.md +1 -1
  8. package/docs/operating.md +1 -1
  9. package/docs/operator-api.md +14 -2
  10. package/docs/plugin-authoring.md +4 -0
  11. package/docs/remote-store-protocol.md +14 -4
  12. package/docs/restacking.md +4 -0
  13. package/docs/tickets.md +1 -1
  14. package/docs/troubleshooting.md +1 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/attention.ts +2 -0
  17. package/packages/core/src/cli/dashboard/model.ts +14 -4
  18. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  19. package/packages/core/src/cli/dashboard/render.ts +3 -0
  20. package/packages/core/src/cli/dispatch-preflight.ts +4 -1
  21. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  22. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  23. package/packages/core/src/cli/dispatch.ts +368 -98
  24. package/packages/core/src/cli/help.ts +4 -2
  25. package/packages/core/src/cli/repo-lease.ts +225 -0
  26. package/packages/core/src/cli/repository-status.ts +3 -1
  27. package/packages/core/src/cli/status.ts +13 -13
  28. package/packages/core/src/cli/wait.ts +4 -1
  29. package/packages/core/src/cli/watch.ts +15 -4
  30. package/packages/core/src/config/schema.ts +38 -2
  31. package/packages/core/src/events/catalog.ts +2 -0
  32. package/packages/core/src/events/payloads.ts +15 -0
  33. package/packages/core/src/events/policy.ts +2 -0
  34. package/packages/core/src/events/repository.ts +2 -0
  35. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +196 -230
  36. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  37. package/packages/core/src/kernel/engine.ts +13 -6
  38. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  39. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  40. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  41. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  42. package/packages/core/src/kernel/log-index.ts +1 -1
  43. package/packages/core/src/kernel/node-landing.ts +2 -1
  44. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  45. package/packages/core/src/kernel/reducer.ts +58 -4
  46. package/packages/core/src/kernel/ticket-preparation.ts +11 -7
  47. package/packages/core/src/operator/query.ts +15 -12
  48. package/packages/core/src/ports/tickets/create.ts +19 -5
  49. package/packages/core/src/ports/types.ts +4 -0
  50. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  51. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  52. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  53. package/packages/core/src/ports/workspace/vercel-sandbox.ts +3 -0
  54. package/packages/core/src/processes/build-runner.ts +2 -1
  55. package/packages/core/src/processes/dispatcher.ts +231 -41
  56. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  57. package/packages/core/src/processes/harvest-child.ts +4 -2
  58. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  59. package/packages/core/src/processes/harvest-runner.ts +246 -17
  60. package/packages/core/src/scenarios/harness.ts +145 -35
  61. package/packages/core/src/store/reduced-reads.ts +10 -0
  62. package/packages/core/src/store/reducer-value-shapes.json +1463 -1215
  63. package/packages/core/src/store/remote/released-clients.json +11 -0
  64. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  65. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  66. package/packages/core/src/testing/reduced-read-budget.ts +339 -2
  67. package/skills/guide/SKILL.md +53 -17
  68. package/skills/guide/references/operator-api.md +14 -2
  69. package/skills/guide/references/plugin-authoring.md +4 -0
  70. package/skills/guide/references/remote-store-protocol.md +14 -4
  71. package/skills/guide/references/restacking.md +4 -0
  72. package/skills/operate/SKILL.md +50 -11
  73. package/skills/tickets/SKILL.md +4 -2
  74. package/templates/hosted-service/package.json +2 -2
@@ -168,6 +168,7 @@ import { GitHubForge } from '../ports/forge/github'
168
168
  import { createProductionRuntimes } from '../ports/runner/production'
169
169
  import type { RuntimeRegistry } from '../ports/runner/runtime'
170
170
  import { createTicketSource } from '../ports/tickets/create'
171
+ import { dispatcherTicketSource } from './dispatch-tickets'
171
172
  import type {
172
173
  Forge,
173
174
  TicketSource,
@@ -236,6 +237,14 @@ import {
236
237
  } from '../store/types'
237
238
  import { availableRelease } from './self-update'
238
239
  import { TriageCountSampler, triageReader } from './triage-count-sampler'
240
+ import {
241
+ fenceEffects,
242
+ fenceExec,
243
+ fenceForge,
244
+ isRepositoryAuthorityLapse,
245
+ RepositoryAuthorityLapsed,
246
+ resolveLapsedRepoLease,
247
+ } from './repo-lease'
239
248
  import {
240
249
  startUpgradeNotice,
241
250
  type AvailableReleaseProbe,
@@ -245,11 +254,13 @@ import {
245
254
  /** Watch-loop default cadence between ticks (§3.3 re-run safety makes this a
246
255
  * pure knob — a shorter interval only polls the forge more often). */
247
256
  const DEFAULT_INTERVAL_MS = 10_000
248
- /** Repository supervisor lease (§12 serialization): TTL and heartbeat cadence.
249
- * The heartbeat renews at a third of the TTL, so one lost beat still leaves a
250
- * full interval of margin before a peer can take over. */
251
- const REPO_LEASE_TTL_MS = 60_000
252
- const REPO_LEASE_HEARTBEAT_MS = 20_000
257
+ /** Repository supervisor lease (§12 serialization) timing, as stored by the
258
+ * claim that set it: `[policy].dispatchLeaseTimeoutSeconds` and
259
+ * `dispatchLeaseRenewalSeconds`. */
260
+ interface RepoLeaseTiming {
261
+ ttlMs: number
262
+ renewalMs: number
263
+ }
253
264
  /** Repository artifact containing the schema-validated composed Config used by
254
265
  * one dispatch run. It is the frontend's only config source. Defined in
255
266
  * `store/retention.ts` beside the other kind constants and re-exported here
@@ -584,10 +595,10 @@ async function defaultWire(
584
595
  : {}
585
596
  const opened = openStoreForRepoState(state, { env: opts.env })
586
597
 
587
- const tickets = await createTicketSource(
598
+ const tickets = await dispatcherTicketSource(
588
599
  config.tickets,
589
- opts.env,
590
- state.repo,
600
+ opts,
601
+ state,
591
602
  opened.localStateRoot,
592
603
  plugins,
593
604
  )
@@ -743,6 +754,10 @@ class DispatchLoop {
743
754
  * frontend's tick-path journal reads and writes share. Resident for a
744
755
  * watch loop; `--once` builds it cold for its single tick. */
745
756
  private readonly repoView: RepoViewStore
757
+ /** This loop's adapters, with every effect fenced on repository authority. */
758
+ private readonly wiring: DispatchWiring
759
+ /** `opts.exec` with `git push` fenced on repository authority. */
760
+ private readonly exec: Exec
746
761
  private readonly host = hostname()
747
762
  private readonly maxHarvestRecoveryAttempts = DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS
748
763
  /** In-flight build and harvest runs (fire-and-forget) — awaited before a
@@ -874,9 +889,20 @@ class DispatchLoop {
874
889
  private repoLeaseValidUntil = 0
875
890
  private repoLeaseHolder: string | undefined
876
891
  private repoLeaseHeartbeat: ReturnType<typeof setInterval> | undefined
877
- /** Set when the store reports this supervisor's repo lease was taken over:
878
- * stop accepting launches, detach/reap, signal continuations, and exit watch
879
- * mode cleanly. */
892
+ /** The timing pair the last successful repository-lease claim stored. Set
893
+ * only by a claim, so the local deadline, the beat cadence and the store's
894
+ * renewal TTL always agree. */
895
+ private heldLease: RepoLeaseTiming | undefined
896
+ /** Advances whenever the stored lease timing may change or the lease is
897
+ * released. A beat answers for the timing it was sent under, so a response
898
+ * from an older generation is discarded rather than trusted. */
899
+ private leaseGeneration = 0
900
+ /** Serializes lease claims and timing adoption, so a claim never captures a
901
+ * timing pair that a concurrent claim is replacing. */
902
+ private leaseMutation: Promise<unknown> = Promise.resolve()
903
+ /** Set only when the lease resolver proves another run took the repository
904
+ * lease: stop accepting launches, detach/reap, signal continuations, and
905
+ * exit watch mode cleanly. An expired lease of our own is never proof. */
880
906
  private superseded = false
881
907
  /** Public teardown fact for the durable `dispatcher.run-stopped` reason. */
882
908
  get supersededByPeer(): boolean {
@@ -905,11 +931,62 @@ class DispatchLoop {
905
931
 
906
932
  constructor(
907
933
  private readonly liveConfig: LiveConfig,
908
- private readonly wiring: DispatchWiring,
934
+ wiring: DispatchWiring,
909
935
  private readonly opts: DispatchOpts,
910
936
  /** The view `abDispatch` already used for its lifecycle appends. */
911
937
  view?: RepoViewStore,
912
938
  ) {
939
+ // Every effect this loop or its Dispatcher calls is fenced where it
940
+ // happens: a continuation that resumes after this run's repository lease
941
+ // lapsed throws `RepositoryAuthorityLapsed` instead of starting it. The
942
+ // caller's wiring object is never mutated, so a second loop over the same
943
+ // wiring cannot inherit this loop's guard.
944
+ const guard = () => this.requireRepoAuthority()
945
+ const fencedWorkspaces = (provider: WorkspaceProvider): WorkspaceProvider =>
946
+ fenceEffects(
947
+ provider,
948
+ {
949
+ methods: ['provision'],
950
+ nested: {
951
+ publication: { methods: ['recoverCandidate', 'preserve', 'rewrite', 'publish'] },
952
+ buildExecution: { methods: ['start'] },
953
+ harvestExecution: { methods: ['start'] },
954
+ },
955
+ },
956
+ guard,
957
+ )
958
+ wiring = {
959
+ ...wiring,
960
+ tickets: fenceEffects(
961
+ wiring.tickets,
962
+ {
963
+ methods: [
964
+ 'claim',
965
+ 'comment',
966
+ 'transition',
967
+ 'create',
968
+ 'update',
969
+ 'addBlocker',
970
+ 'removeBlocker',
971
+ 'addState',
972
+ 'mutateIfRevision',
973
+ ],
974
+ },
975
+ guard,
976
+ ),
977
+ workspaces: fencedWorkspaces(wiring.workspaces),
978
+ buildExecution: fenceEffects(wiring.buildExecution, { methods: ['start'] }, guard),
979
+ ...(wiring.retiredWorkspaces === undefined
980
+ ? {}
981
+ : {
982
+ retiredWorkspaces: wiring.retiredWorkspaces.map((runtime) => ({
983
+ provider: fencedWorkspaces(runtime.provider),
984
+ execution: fenceEffects(runtime.execution, { methods: ['start'] }, guard),
985
+ })),
986
+ }),
987
+ }
988
+ this.wiring = wiring
989
+ this.exec = fenceExec(opts.exec, guard)
913
990
  const config = liveConfig.current().config
914
991
  this.startupRootBranch = config.baseBranch
915
992
  // Minted exactly once per invocation: `wiring.ids` is `randomIds()` and a
@@ -964,13 +1041,18 @@ class DispatchLoop {
964
1041
 
965
1042
  // `abDispatch` hands over a view it already used for the lifecycle appends,
966
1043
  // so those rows are folded, not re-read, and one flush covers them all.
967
- this.repoView =
1044
+ this.repoView = fenceEffects(
968
1045
  view ??
969
- new RepoViewStore(wiring.store, {
970
- repo: this.repoIdentity,
971
- resident: opts.once !== true,
972
- })
973
- wiring.forge = guardForge(wiring.forge, {
1046
+ new RepoViewStore(wiring.store, {
1047
+ repo: this.repoIdentity,
1048
+ resident: opts.once !== true,
1049
+ }),
1050
+ { methods: ['createBuild', 'claimLease'] },
1051
+ guard,
1052
+ )
1053
+ // The fence sits under the health guard, so the Dispatcher's own
1054
+ // `guardForge` call recognises this object and adds no second wrapper.
1055
+ wiring.forge = guardForge(fenceForge(wiring.forge, guard), {
974
1056
  store: this.repoView,
975
1057
  repo: this.repoIdentity,
976
1058
  name: config.forge,
@@ -996,7 +1078,8 @@ class DispatchLoop {
996
1078
  ? { repoOrigin: normalizeGitRemoteUrl(opts.repository) }
997
1079
  : {}),
998
1080
  checkout: opts.targetRepo,
999
- exec: opts.exec,
1081
+ exec: this.exec,
1082
+ holdsRepoAuthority: () => this.holdsRepoAuthority(),
1000
1083
  launchRunner: (slug) => this.launchRunner(slug),
1001
1084
  startHarvest: () => this.launchHarvest(),
1002
1085
  nameSlug,
@@ -1051,7 +1134,7 @@ class DispatchLoop {
1051
1134
  mode: this.opts.repository !== undefined ? 'origin' : 'checkout',
1052
1135
  forge: this.wiring.forge,
1053
1136
  checkout: this.opts.targetRepo,
1054
- exec: this.opts.exec,
1137
+ exec: this.exec,
1055
1138
  ...(workspace !== null ? { workspacePath: workspace.path } : {}),
1056
1139
  onFailure: (failure) => failures.push(failure),
1057
1140
  })
@@ -1229,7 +1312,17 @@ class DispatchLoop {
1229
1312
  )
1230
1313
  }
1231
1314
 
1315
+ /** Status telemetry is new work: a run that held the repository lease
1316
+ * writes none once a peer replaced it, and a lapsed holder resolves its
1317
+ * lease first. A standby that never held it reports as before. */
1232
1318
  private async appendStatus(event: RepositoryEventWrite): Promise<void> {
1319
+ if (this.superseded) return
1320
+ if (
1321
+ this.repoLeaseHolder !== undefined &&
1322
+ !this.holdsRepoAuthority() &&
1323
+ !(await this.reconfirmRepoLease())
1324
+ )
1325
+ return
1233
1326
  await this.repoView.appendRepo(this.repoIdentity, event)
1234
1327
  }
1235
1328
 
@@ -1327,15 +1420,19 @@ class DispatchLoop {
1327
1420
  await this.recordTickYielded()
1328
1421
  return emptyTickReport()
1329
1422
  }
1423
+ // A reloaded `[policy]` lease pair takes effect here, through a claim.
1424
+ await this.adoptConfiguredLease()
1425
+ if (this.superseded) return emptyTickReport()
1330
1426
  // Initialization can read/write the store. Retry it at the tick boundary
1331
1427
  // after a transient failure, even while our repository lease stays valid.
1332
1428
  await this.initializeAutomaticUpgrade()
1333
1429
  await this.reportForgeReadiness()
1334
- const startedAt = await this.repoView.beginRepoTick(this.repoIdentity, this.runId)
1335
- if (startedAt === null) {
1336
- this.superseded = true
1337
- return emptyTickReport()
1338
- }
1430
+ let startedAt = await this.repoView.beginRepoTick(this.repoIdentity, this.runId)
1431
+ // The store refuses a boundary on an expired lease. Ours may only have
1432
+ // lapsed: reclaim it and retry once; the resolver decides supersession.
1433
+ if (startedAt === null && (await this.reconfirmRepoLease()))
1434
+ startedAt = await this.repoView.beginRepoTick(this.repoIdentity, this.runId)
1435
+ if (startedAt === null) return emptyTickReport()
1339
1436
  this.tickStartedAt = startedAt
1340
1437
 
1341
1438
  // Refresh inside the serialized tick so claims and the display both see
@@ -2430,6 +2527,7 @@ class DispatchLoop {
2430
2527
  let tracked: Promise<void>
2431
2528
  tracked = this.launchHarvestIfNeeded()
2432
2529
  .catch((error: unknown) => {
2530
+ if (isRepositoryAuthorityLapse(error)) return
2433
2531
  if (this.stopped || this.localHarvestShutdown.signal.aborted)
2434
2532
  this.localHarvestFailure = error
2435
2533
  // The gate may read the backing store after tick work dirties the view.
@@ -2493,11 +2591,14 @@ class DispatchLoop {
2493
2591
  clock,
2494
2592
  instance: `${this.host}-harvest-${ids('inst')}`,
2495
2593
  ...(this.repoLeaseHolder !== undefined ? { leaseHolder: this.repoLeaseHolder } : {}),
2594
+ holdsAuthority: () => this.holdsRepoAuthority(),
2496
2595
  sessionEnv: {
2497
2596
  AB_STORE: storeRef,
2498
2597
  },
2499
2598
  opts: {
2500
2599
  maxRecoveryAttempts: this.maxHarvestRecoveryAttempts,
2600
+ // Harvest renews this loop's lease; it must never rewrite its TTL.
2601
+ ...(this.heldLease !== undefined ? { leaseTtlMs: this.heldLease.ttlMs } : {}),
2501
2602
  },
2502
2603
  }
2503
2604
 
@@ -2531,6 +2632,7 @@ class DispatchLoop {
2531
2632
  return prepared
2532
2633
  }
2533
2634
  preparedRun = { run: prepared.run }
2635
+ this.requireRepoAuthority()
2534
2636
  await this.repoView.appendRepo(this.repoIdentity, {
2535
2637
  actor: DISPATCHER,
2536
2638
  type: 'harvest.execution.authorized',
@@ -2576,6 +2678,7 @@ class DispatchLoop {
2576
2678
  this.opts.targetRepo,
2577
2679
  undefined,
2578
2680
  this.wiring.plugins,
2681
+ this.opts.repository !== undefined ? { repository: this.repoIdentity } : {},
2579
2682
  )
2580
2683
  const result = await new HarvestRunner({
2581
2684
  ...harvestDeps,
@@ -2609,6 +2712,7 @@ class DispatchLoop {
2609
2712
  if (!/^https?:/i.test(storeRef)) return new HarvestRunner(harvestDeps).run()
2610
2713
  const prepared = await new HarvestRunner(harvestDeps).run(true)
2611
2714
  if (prepared.outcome !== 'prepared') return prepared
2715
+ this.requireRepoAuthority()
2612
2716
  await this.repoView.appendRepo(this.repoIdentity, {
2613
2717
  actor: DISPATCHER,
2614
2718
  type: 'harvest.execution.authorized',
@@ -2645,6 +2749,7 @@ class DispatchLoop {
2645
2749
  storeRef,
2646
2750
  }).localStateRoot,
2647
2751
  this.wiring.plugins,
2752
+ this.opts.repository !== undefined ? { repository: this.repoIdentity } : {},
2648
2753
  )
2649
2754
  : harvestDeps.tickets
2650
2755
  return await new HarvestRunner({
@@ -2681,6 +2786,8 @@ class DispatchLoop {
2681
2786
  this.localHarvestFailure = error
2682
2787
  return
2683
2788
  }
2789
+ // Nothing started without authority; a later tick retries.
2790
+ if (isRepositoryAuthorityLapse(error)) return
2684
2791
  this.pendingHarvest.harvestFailed += 1
2685
2792
  await this.appendStatus({
2686
2793
  actor: DISPATCHER,
@@ -2718,7 +2825,11 @@ class DispatchLoop {
2718
2825
  clock: this.wiring.clock,
2719
2826
  instance,
2720
2827
  ...(this.repoLeaseHolder ? { leaseHolder: this.repoLeaseHolder } : {}),
2721
- opts: { maxRecoveryAttempts: this.maxHarvestRecoveryAttempts },
2828
+ holdsAuthority: () => this.holdsRepoAuthority(),
2829
+ opts: {
2830
+ maxRecoveryAttempts: this.maxHarvestRecoveryAttempts,
2831
+ ...(this.heldLease !== undefined ? { leaseTtlMs: this.heldLease.ttlMs } : {}),
2832
+ },
2722
2833
  }).run(true)
2723
2834
  }
2724
2835
 
@@ -2776,6 +2887,7 @@ class DispatchLoop {
2776
2887
 
2777
2888
  const prepared = await this.prepareHarvest(execution)
2778
2889
  if (prepared.outcome !== 'prepared') return
2890
+ this.requireRepoAuthority()
2779
2891
  await this.repoView.appendRepo(repo, {
2780
2892
  actor: DISPATCHER,
2781
2893
  type: 'harvest.execution.authorized',
@@ -2873,6 +2985,8 @@ class DispatchLoop {
2873
2985
  if (detached.value) {
2874
2986
  // Teardown detached the local wait; the guest keeps running and the
2875
2987
  // execution stays open for durable settlement by a later invocation.
2988
+ // Releasing this invocation's lease does not fence the guest: its
2989
+ // authority is the execution's durable authorization.
2876
2990
  return
2877
2991
  }
2878
2992
  // The guest exit code carries no pipeline outcome: classify from the
@@ -2909,6 +3023,8 @@ class DispatchLoop {
2909
3023
  await this.dispatcher.holdForMissingAccounts(error)
2910
3024
  return
2911
3025
  }
3026
+ // Nothing started without authority; a later tick retries.
3027
+ if (isRepositoryAuthorityLapse(error)) return
2912
3028
  this.pendingHarvest.harvestFailed += 1
2913
3029
  await this.appendStatus({
2914
3030
  actor: DISPATCHER,
@@ -3115,11 +3231,10 @@ class DispatchLoop {
3115
3231
  completed,
3116
3232
  ]
3117
3233
  : []
3118
- const result = await this.finishTick({ outcome: 'completed', counters }, events)
3119
- if (result === null) {
3120
- this.superseded = true
3121
- throw new Error('repository tick lease lost')
3122
- }
3234
+ let result = await this.finishTick({ outcome: 'completed', counters }, events)
3235
+ if (result === null && (await this.reconfirmRepoLease()))
3236
+ result = await this.finishTick({ outcome: 'completed', counters }, events)
3237
+ if (result === null) throw new Error('repository tick lease lost')
3123
3238
  this.tickStartedAt = undefined
3124
3239
  }
3125
3240
 
@@ -3178,6 +3293,15 @@ class DispatchLoop {
3178
3293
  | { original: string; first: string; last: string; count: number }
3179
3294
  | undefined
3180
3295
 
3296
+ /** A tick stopped by a fenced effect is not a failed tick: publish no
3297
+ * `tick-failed`, abandon the open boundary (a successor's or our own next
3298
+ * `beginRepoTick` overwrites it), and resolve the lease. That either stops
3299
+ * this run as superseded or reclaims so the next tick runs normally. */
3300
+ private async settleAuthorityLapse(): Promise<void> {
3301
+ this.tickStartedAt = undefined
3302
+ await this.reconfirmRepoLease()
3303
+ }
3304
+
3181
3305
  /** Reporting is diagnostic: its failure must never replace the operational error. */
3182
3306
  private async reportTickFailure(error: unknown): Promise<void> {
3183
3307
  const original = formatDispatcherError(error)
@@ -3228,25 +3352,23 @@ class DispatchLoop {
3228
3352
  await this.wiring.store.appendRepo(this.repoIdentity, failed)
3229
3353
  return
3230
3354
  }
3231
- const result = await this.finishTick(
3355
+ const completion: RepoTickCompletion = {
3356
+ outcome: 'failed',
3357
+ error: failed.payload.error,
3358
+ forgeRequests: this.dispatcher.lastForgeRequests,
3359
+ }
3360
+ const events: RepositoryEventWrite[] = [
3232
3361
  {
3233
- outcome: 'failed',
3234
- error: failed.payload.error,
3235
- forgeRequests: this.dispatcher.lastForgeRequests,
3362
+ actor: DISPATCHER,
3363
+ type: 'dispatcher.tick-started',
3364
+ payload: { run: this.runId, startedAt: this.tickStartedAt },
3236
3365
  },
3237
- [
3238
- {
3239
- actor: DISPATCHER,
3240
- type: 'dispatcher.tick-started',
3241
- payload: { run: this.runId, startedAt: this.tickStartedAt },
3242
- },
3243
- failed,
3244
- ],
3245
- )
3246
- if (result === null) {
3247
- this.superseded = true
3248
- return
3249
- }
3366
+ failed,
3367
+ ]
3368
+ let result = await this.finishTick(completion, events)
3369
+ if (result === null && (await this.reconfirmRepoLease()))
3370
+ result = await this.finishTick(completion, events)
3371
+ if (result === null) return
3250
3372
  this.tickStartedAt = undefined
3251
3373
  }
3252
3374
 
@@ -3287,7 +3409,7 @@ class DispatchLoop {
3287
3409
  forge: this.wiring.forge,
3288
3410
  workspacePath: this.opts.targetRepo,
3289
3411
  checkoutless: this.opts.repository !== undefined,
3290
- exec: this.opts.exec,
3412
+ exec: this.exec,
3291
3413
  ids: this.wiring.ids,
3292
3414
  runId: this.runId,
3293
3415
  clock: this.wiring.clock,
@@ -3311,7 +3433,9 @@ class DispatchLoop {
3311
3433
  try {
3312
3434
  await this.settlePendingPublication(slug)
3313
3435
  } catch (error) {
3314
- if (!(error instanceof ForgeRequestDeferred)) throw error
3436
+ // A lapsed run publishes nothing; the successor settles from durable facts.
3437
+ if (!(error instanceof ForgeRequestDeferred) && !isRepositoryAuthorityLapse(error))
3438
+ throw error
3315
3439
  }
3316
3440
  }
3317
3441
 
@@ -3541,6 +3665,14 @@ class DispatchLoop {
3541
3665
  this.inFlightKinds.set(tracked, handle.supervision)
3542
3666
  return 'scheduled'
3543
3667
  } catch (error) {
3668
+ if (isRepositoryAuthorityLapse(error)) {
3669
+ // Nothing was started. Release the execution lease (teardown) so a
3670
+ // successor can launch at once, and record no settlement or failure.
3671
+ if (leaseClaimed) await this.repoView.releaseLease(slug, instance).catch(() => {})
3672
+ if (this.activeBuildRuns.get(slug)?.reservation === reservation)
3673
+ this.activeBuildRuns.delete(slug)
3674
+ return 'already-active'
3675
+ }
3544
3676
  if (error instanceof MissingAccountCredentialsError) {
3545
3677
  await this.dispatcher.holdForMissingAccounts(error)
3546
3678
  if (leaseClaimed) await this.repoView.releaseLease(slug, instance)
@@ -4203,17 +4335,59 @@ class DispatchLoop {
4203
4335
 
4204
4336
  // ── Repository supervisor lease (§12 serialization) ────────────────────────
4205
4337
 
4338
+ /** The timing pair the accepted configuration asks for. */
4339
+ private configuredLease(): RepoLeaseTiming {
4340
+ const policy = this.currentConfig().config.policy
4341
+ return {
4342
+ ttlMs: policy.dispatchLeaseTimeoutSeconds * 1000,
4343
+ renewalMs: policy.dispatchLeaseRenewalSeconds * 1000,
4344
+ }
4345
+ }
4346
+
4347
+ /** Whether this run may start an effect now. No I/O: the deadline is the
4348
+ * claim or beat request time plus the held TTL, never later than the
4349
+ * store's expiry, so no peer can have claimed the lease before it. */
4350
+ private holdsRepoAuthority(): boolean {
4351
+ return (
4352
+ !this.superseded &&
4353
+ this.repoLeaseHolder !== undefined &&
4354
+ this.wiring.clock().getTime() < this.repoLeaseValidUntil
4355
+ )
4356
+ }
4357
+
4358
+ /** The synchronous effect fence: throw instead of starting an effect. */
4359
+ private requireRepoAuthority(): void {
4360
+ if (!this.holdsRepoAuthority()) throw new RepositoryAuthorityLapsed()
4361
+ }
4362
+
4206
4363
  /** Claim an unknown or expired repository lease and start the
4207
- * heartbeat timer. False means another supervisor holds it: the caller
4208
- * yields — no claims, launches, or publications. */
4364
+ * heartbeat timer. False means this run may not act this tick: another
4365
+ * supervisor holds the lease, or our own lapsed lease could not be
4366
+ * confirmed yet. The caller yields — no claims, launches, or publications. */
4209
4367
  private async ensureRepoLease(holder: string): Promise<boolean> {
4210
4368
  if (this.superseded) return false
4211
- if (this.repoLeaseHolder === holder && this.wiring.clock().getTime() < this.repoLeaseValidUntil)
4369
+ if (this.repoLeaseHolder === holder) {
4370
+ if (this.wiring.clock().getTime() < this.repoLeaseValidUntil) return true
4371
+ // Our own deadline lapsed (a stall, or beats lost to a store outage).
4372
+ // Only the resolver decides between "reclaim" and "replaced".
4373
+ return await this.reconfirmRepoLease()
4374
+ }
4375
+ const claimed = await this.mutateLease(async () => {
4376
+ if (this.superseded) return false
4377
+ if (this.repoLeaseHolder === holder) return this.holdsRepoAuthority()
4378
+ const lease = this.configuredLease()
4379
+ const requestedAt = this.wiring.clock().getTime()
4380
+ const granted = await this.wiring.store
4381
+ .claimRepoLease(this.repoIdentity, holder, lease.ttlMs)
4382
+ .catch(() => false)
4383
+ if (!granted || this.superseded) return false
4384
+ this.leaseGeneration++
4385
+ this.heldLease = lease
4386
+ this.repoLeaseValidUntil = requestedAt + lease.ttlMs
4387
+ this.repoLeaseHolder = holder
4388
+ this.restartRepoLeaseHeartbeat()
4212
4389
  return true
4213
- const requestedAt = this.wiring.clock().getTime()
4214
- const claimed = await this.wiring.store
4215
- .claimRepoLease(this.repoIdentity, holder, REPO_LEASE_TTL_MS)
4216
- .catch(() => false)
4390
+ })
4217
4391
  if (this.dashboard && !this.opts.once) {
4218
4392
  this.standbyResolver ??= new StandbyIdentityResolver(this.wiring.store, this.repoIdentity)
4219
4393
  this.standby = claimed
@@ -4226,44 +4400,128 @@ class DispatchLoop {
4226
4400
  this.syncModelControls()
4227
4401
  this.paint()
4228
4402
  }
4229
- if (!claimed) {
4230
- if (this.repoLeaseHolder !== undefined) {
4231
- // We held the lease and the store says it is gone: a peer took over.
4232
- this.superseded = true
4233
- }
4403
+ return claimed
4404
+ }
4405
+
4406
+ /** Run one lease claim or timing change after every earlier one settles. */
4407
+ private mutateLease<T>(mutation: () => Promise<T>): Promise<T> {
4408
+ const result = this.leaseMutation.then(mutation)
4409
+ this.leaseMutation = result.catch(() => {})
4410
+ return result
4411
+ }
4412
+
4413
+ /** Resolve a lease that looks lapsed: reclaim it when the record still
4414
+ * names this run, stop as superseded when another run took it, and do
4415
+ * nothing on a store error (the next beat or tick asks again). True only
4416
+ * when this run holds the lease again. A released lease is never
4417
+ * resurrected. */
4418
+ private reconfirmRepoLease(): Promise<boolean> {
4419
+ return this.mutateLease(() => this.reconfirmHeldLease())
4420
+ }
4421
+
4422
+ /** `reconfirmRepoLease` for a caller already inside `mutateLease`. */
4423
+ private async reconfirmHeldLease(): Promise<boolean> {
4424
+ const holder = this.repoLeaseHolder
4425
+ if (this.superseded || holder === undefined) return false
4426
+ const lease = this.heldLease ?? this.configuredLease()
4427
+ const generation = this.leaseGeneration
4428
+ const requestedAt = this.wiring.clock().getTime()
4429
+ const resolution = await resolveLapsedRepoLease(
4430
+ this.wiring.store,
4431
+ this.repoIdentity,
4432
+ holder,
4433
+ lease.ttlMs,
4434
+ )
4435
+ if (this.superseded || this.repoLeaseHolder !== holder || this.leaseGeneration !== generation)
4234
4436
  return false
4437
+ if (resolution === 'held') {
4438
+ this.repoLeaseValidUntil = Math.max(this.repoLeaseValidUntil, requestedAt + lease.ttlMs)
4439
+ return true
4235
4440
  }
4236
- this.repoLeaseValidUntil = requestedAt + REPO_LEASE_TTL_MS
4237
- if (this.repoLeaseHolder === undefined) {
4238
- this.repoLeaseHolder = holder
4239
- this.startRepoLeaseHeartbeat(holder)
4441
+ if (resolution === 'superseded') {
4442
+ // A peer holds or held the repository since. Exit watch mode cleanly
4443
+ // after the same teardown every stop takes (detach remote / reap local,
4444
+ // signal continuations, release the lease).
4445
+ this.superseded = true
4446
+ this.inputStop.abort()
4240
4447
  }
4241
- return true
4448
+ return false
4449
+ }
4450
+
4451
+ /** Adopt a changed `[policy]` lease pair through a same-holder claim, which
4452
+ * rewrites the stored TTL in every adapter. Unchanged configuration costs
4453
+ * no store request.
4454
+ *
4455
+ * While the claim is in flight the stored TTL may be either pair, so the
4456
+ * beat stops, the generation advances (an in-flight beat's answer is
4457
+ * discarded) and the deadline is held to the shorter TTL. An ambiguous
4458
+ * failure keeps the shorter of both pairs until a later claim settles it. */
4459
+ private adoptConfiguredLease(): Promise<void> {
4460
+ return this.mutateLease(async () => {
4461
+ const holder = this.repoLeaseHolder
4462
+ const held = this.heldLease
4463
+ if (holder === undefined || held === undefined || !this.holdsRepoAuthority()) return
4464
+ const wanted = this.configuredLease()
4465
+ if (wanted.ttlMs === held.ttlMs && wanted.renewalMs === held.renewalMs) return
4466
+ const requestedAt = this.wiring.clock().getTime()
4467
+ this.stopRepoLeaseHeartbeat()
4468
+ this.leaseGeneration++
4469
+ this.repoLeaseValidUntil = Math.min(this.repoLeaseValidUntil, requestedAt + wanted.ttlMs)
4470
+ let claimed: boolean
4471
+ try {
4472
+ claimed = await this.wiring.store.claimRepoLease(this.repoIdentity, holder, wanted.ttlMs)
4473
+ } catch {
4474
+ // The claim may or may not have landed. The next tick retries.
4475
+ claimed = false
4476
+ if (!this.superseded && this.repoLeaseHolder === holder) {
4477
+ this.heldLease = {
4478
+ ttlMs: Math.min(held.ttlMs, wanted.ttlMs),
4479
+ renewalMs: Math.min(held.renewalMs, wanted.renewalMs),
4480
+ }
4481
+ this.restartRepoLeaseHeartbeat()
4482
+ }
4483
+ return
4484
+ }
4485
+ if (this.superseded || this.repoLeaseHolder !== holder) return
4486
+ if (!claimed) {
4487
+ this.restartRepoLeaseHeartbeat()
4488
+ await this.reconfirmHeldLease()
4489
+ return
4490
+ }
4491
+ this.heldLease = wanted
4492
+ this.repoLeaseValidUntil = requestedAt + wanted.ttlMs
4493
+ this.restartRepoLeaseHeartbeat()
4494
+ })
4242
4495
  }
4243
4496
 
4244
- private startRepoLeaseHeartbeat(holder: string): void {
4245
- if (this.repoLeaseHeartbeat !== undefined) return
4497
+ /** (Re)start the beat at the held renewal interval. A beat that finds the
4498
+ * lease no longer renewable hands the decision to the resolver; it never
4499
+ * concludes takeover by itself. */
4500
+ private restartRepoLeaseHeartbeat(): void {
4501
+ this.stopRepoLeaseHeartbeat()
4502
+ const holder = this.repoLeaseHolder
4503
+ const lease = this.heldLease
4504
+ if (holder === undefined || lease === undefined) return
4246
4505
  this.repoLeaseHeartbeat = setInterval(() => {
4506
+ const generation = this.leaseGeneration
4247
4507
  const requestedAt = this.wiring.clock().getTime()
4248
4508
  this.wiring.store.heartbeatRepo(this.repoIdentity, holder).then(
4249
4509
  (alive) => {
4250
- if (this.retirement && this.repoLeaseHolder === undefined) return
4510
+ // Released (retirement, shutdown), or the stored timing may have
4511
+ // changed, since this beat was sent: its answer no longer applies.
4512
+ if (this.repoLeaseHolder !== holder || this.leaseGeneration !== generation) return
4251
4513
  if (alive) {
4252
- this.repoLeaseValidUntil = requestedAt + REPO_LEASE_TTL_MS
4514
+ this.repoLeaseValidUntil = requestedAt + lease.ttlMs
4253
4515
  return
4254
4516
  }
4255
- // A peer holds the repository now. Exit watch mode cleanly after
4256
- // the same teardown every stop takes (detach remote / reap local,
4257
- // signal continuations, release the lease).
4258
- this.superseded = true
4259
- this.inputStop.abort()
4517
+ void this.reconfirmRepoLease()
4260
4518
  },
4261
4519
  () => {
4262
- // Store unreachable: retry on the next beat; a later false result
4263
- // proves takeover.
4520
+ // Store unreachable: retry on the next beat. Tick start reclaims
4521
+ // once the store answers again.
4264
4522
  },
4265
4523
  )
4266
- }, REPO_LEASE_HEARTBEAT_MS)
4524
+ }, lease.renewalMs)
4267
4525
  this.repoLeaseHeartbeat.unref?.()
4268
4526
  }
4269
4527
 
@@ -4280,7 +4538,8 @@ class DispatchLoop {
4280
4538
  try {
4281
4539
  const record = await this.wiring.store.getRepo(this.repoIdentity).catch(() => null)
4282
4540
  const holder = record?.lease?.holder
4283
- if (holder === undefined || this.yieldedTo === holder) return
4541
+ // Never a yield to ourselves: our own lapsed lease is resolved, not yielded to.
4542
+ if (holder === undefined || holder === this.runId || this.yieldedTo === holder) return
4284
4543
  this.yieldedTo = holder
4285
4544
  await this.repoView.appendRepo(this.repoIdentity, {
4286
4545
  actor: DISPATCHER,
@@ -4300,6 +4559,7 @@ class DispatchLoop {
4300
4559
  const holder = this.repoLeaseHolder
4301
4560
  this.repoLeaseHolder = undefined
4302
4561
  this.repoLeaseValidUntil = 0
4562
+ this.leaseGeneration++
4303
4563
  if (holder === undefined) return
4304
4564
  try {
4305
4565
  await this.wiring.store.releaseRepoLease(this.repoIdentity, holder)
@@ -4377,14 +4637,7 @@ class DispatchLoop {
4377
4637
  this.abandonUpgradeYield()
4378
4638
  return false
4379
4639
  }
4380
- const lease = (await this.wiring.store.getRepo(this.repoIdentity))?.lease
4381
- if (
4382
- lease?.holder !== this.runId ||
4383
- Date.parse(lease.expiresAt) <= this.wiring.clock().getTime()
4384
- ) {
4385
- this.superseded = true
4386
- return false
4387
- }
4640
+ if (!(await this.upgradeLeaseCurrent())) return false
4388
4641
  // No launch, claim, tick or target continuation may cross this boundary.
4389
4642
  this.yieldPending = true
4390
4643
  this.acceptingBuildLaunches = false
@@ -4401,12 +4654,8 @@ class DispatchLoop {
4401
4654
  ])
4402
4655
  }
4403
4656
  await this.dispatcher.stopProvisioning()
4404
- const currentLease = (await this.wiring.store.getRepo(this.repoIdentity))?.lease
4405
- if (
4406
- currentLease?.holder !== this.runId ||
4407
- Date.parse(currentLease.expiresAt) <= this.wiring.clock().getTime()
4408
- ) {
4409
- this.superseded = true
4657
+ if (!(await this.upgradeLeaseCurrent())) {
4658
+ if (!this.superseded) this.abandonUpgradeYield()
4410
4659
  return false
4411
4660
  }
4412
4661
  const startedAt = this.wiring.clock().toISOString()
@@ -4486,6 +4735,19 @@ class DispatchLoop {
4486
4735
  return this.adoptUpgradeYield(accepted)
4487
4736
  }
4488
4737
 
4738
+ /** Repository authority may transfer only from a current holder. A record
4739
+ * naming another run, or no record, means a peer replaced us. An expired
4740
+ * lease that still names us is resolved like any other lapse. */
4741
+ private async upgradeLeaseCurrent(): Promise<boolean> {
4742
+ const lease = (await this.wiring.store.getRepo(this.repoIdentity))?.lease
4743
+ if (lease?.holder !== this.runId) {
4744
+ this.superseded = true
4745
+ return false
4746
+ }
4747
+ if (Date.parse(lease.expiresAt) > this.wiring.clock().getTime()) return true
4748
+ return await this.reconfirmRepoLease()
4749
+ }
4750
+
4489
4751
  /** Reopen admission after a yield that did not durably transfer authority. */
4490
4752
  private abandonUpgradeYield(): void {
4491
4753
  if (!this.yieldPending) return
@@ -4741,7 +5003,7 @@ class DispatchLoop {
4741
5003
  ),
4742
5004
  enabled: () =>
4743
5005
  !this.stopped &&
4744
- !this.superseded &&
5006
+ this.holdsRepoAuthority() &&
4745
5007
  this.currentConfig().config.upgrade.automatic &&
4746
5008
  this.upgradeRetirementSettled,
4747
5009
  resolve: (signal) =>
@@ -4751,7 +5013,7 @@ class DispatchLoop {
4751
5013
  originalInstall: launch.originalInstall!,
4752
5014
  sourceLaunch: launch.sourceLaunch,
4753
5015
  forge: this.wiring.forge,
4754
- exec: this.opts.exec,
5016
+ exec: this.exec,
4755
5017
  signal,
4756
5018
  }),
4757
5019
  prepare: (target, signal) =>
@@ -4837,6 +5099,10 @@ class DispatchLoop {
4837
5099
  // One background triage read before the single tick, never inside it.
4838
5100
  this.triageSampler?.poke()
4839
5101
  const initial = await this.dispatcherTick(true).catch(async (error: unknown) => {
5102
+ if (isRepositoryAuthorityLapse(error)) {
5103
+ await this.settleAuthorityLapse()
5104
+ return emptyTickReport()
5105
+ }
4840
5106
  await this.reportTickFailure(error)
4841
5107
  throw error
4842
5108
  })
@@ -4890,8 +5156,12 @@ class DispatchLoop {
4890
5156
  startup = false
4891
5157
  } catch (error) {
4892
5158
  if (this.forgePublicationFailed) throw error
4893
- failed = true
4894
- await this.reportTickFailure(error)
5159
+ if (isRepositoryAuthorityLapse(error)) {
5160
+ await this.settleAuthorityLapse()
5161
+ } else {
5162
+ failed = true
5163
+ await this.reportTickFailure(error)
5164
+ }
4895
5165
  }
4896
5166
  this.triageSampler?.poke()
4897
5167
  if (this.watchStopped || this.superseded) break