@defrex/autobuild 1.2.0 → 1.4.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 (164) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +416 -36
  3. package/docs/accounts.md +50 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +298 -17
  6. package/docs/build-store.md +18 -0
  7. package/docs/builds.md +7 -1
  8. package/docs/cli.md +1 -1
  9. package/docs/configuration-overview.md +6 -0
  10. package/docs/configuration.md +44 -19
  11. package/docs/dispatcher-hosting.md +42 -0
  12. package/docs/dispatcher.md +41 -0
  13. package/docs/forges.md +5 -0
  14. package/docs/integration-tree.md +24 -5
  15. package/docs/operating.md +11 -3
  16. package/docs/operator-api.md +81 -10
  17. package/docs/operator-surfaces.md +29 -0
  18. package/docs/plugin-authoring.md +51 -2
  19. package/docs/remote-store-protocol.md +321 -46
  20. package/docs/remote-ticket-protocol.md +12 -10
  21. package/docs/restacking.md +105 -3
  22. package/docs/setup.md +37 -8
  23. package/docs/skills.md +1 -1
  24. package/docs/spec-standard.md +41 -5
  25. package/docs/ticket-dependencies.md +8 -0
  26. package/docs/troubleshooting.md +9 -0
  27. package/docs/workspaces.md +1 -1
  28. package/package.json +4 -3
  29. package/packages/core/src/accounts/availability.ts +96 -0
  30. package/packages/core/src/accounts/local-owner.ts +49 -2
  31. package/packages/core/src/cli/attention.ts +2 -0
  32. package/packages/core/src/cli/binary.ts +17 -1
  33. package/packages/core/src/cli/context.ts +62 -0
  34. package/packages/core/src/cli/dashboard/model.ts +12 -3
  35. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  36. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  37. package/packages/core/src/cli/dashboard/render.ts +46 -5
  38. package/packages/core/src/cli/dispatch-args.ts +27 -3
  39. package/packages/core/src/cli/dispatch-frontend.ts +179 -52
  40. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  41. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +150 -33
  43. package/packages/core/src/cli/dispatch.ts +209 -36
  44. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  45. package/packages/core/src/cli/forge-clear.ts +30 -0
  46. package/packages/core/src/cli/harvest.ts +2 -1
  47. package/packages/core/src/cli/help.ts +17 -3
  48. package/packages/core/src/cli/historical-build-state.ts +6 -0
  49. package/packages/core/src/cli/main.ts +43 -2
  50. package/packages/core/src/cli/publication-settlement.ts +17 -0
  51. package/packages/core/src/cli/remote-poll.ts +11 -1
  52. package/packages/core/src/cli/repository-status.ts +11 -0
  53. package/packages/core/src/cli/status.ts +7 -1
  54. package/packages/core/src/cli/wait.ts +9 -2
  55. package/packages/core/src/cli/watch.ts +47 -16
  56. package/packages/core/src/config/roles.ts +16 -1
  57. package/packages/core/src/events/catalog.ts +8 -0
  58. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  59. package/packages/core/src/events/payloads.ts +95 -2
  60. package/packages/core/src/events/policy.ts +19 -0
  61. package/packages/core/src/events/repository.ts +108 -2
  62. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +464 -0
  63. package/packages/core/src/kernel/change-presence.ts +74 -8
  64. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  65. package/packages/core/src/kernel/engine.ts +27 -12
  66. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  67. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  68. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  69. package/packages/core/src/kernel/log-index.ts +1 -1
  70. package/packages/core/src/kernel/node-landing.ts +27 -10
  71. package/packages/core/src/kernel/node-polling.ts +40 -7
  72. package/packages/core/src/kernel/node-restack-demand.ts +75 -0
  73. package/packages/core/src/kernel/node-restack-state.ts +20 -1
  74. package/packages/core/src/kernel/node-restack-transaction.ts +47 -1
  75. package/packages/core/src/kernel/read-facts.ts +120 -9
  76. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  77. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  78. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  79. package/packages/core/src/kernel/reducer.ts +20 -2
  80. package/packages/core/src/kernel/replay-retention.ts +176 -0
  81. package/packages/core/src/kernel/target-lineage.ts +65 -0
  82. package/packages/core/src/kernel/target-observation.ts +117 -0
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +2 -0
  87. package/packages/core/src/operator/registry.ts +25 -13
  88. package/packages/core/src/operator/tickets.ts +8 -2
  89. package/packages/core/src/plugin-sdk/index.ts +1 -0
  90. package/packages/core/src/ports/forge/fake.ts +22 -0
  91. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  92. package/packages/core/src/ports/forge/github.ts +42 -10
  93. package/packages/core/src/ports/forge/local-git.ts +16 -1
  94. package/packages/core/src/ports/runner/account-env.ts +60 -9
  95. package/packages/core/src/ports/runner/claude.ts +49 -45
  96. package/packages/core/src/ports/types.ts +58 -4
  97. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  98. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  99. package/packages/core/src/ports/workspace/create.ts +2 -0
  100. package/packages/core/src/ports/workspace/fake.ts +4 -0
  101. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  102. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  103. package/packages/core/src/processes/build-runner.ts +240 -111
  104. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  105. package/packages/core/src/processes/dispatcher.ts +732 -201
  106. package/packages/core/src/processes/execution-no-progress.ts +8 -0
  107. package/packages/core/src/processes/harvest-runner.ts +6 -7
  108. package/packages/core/src/processes/harvest.ts +11 -16
  109. package/packages/core/src/processes/publication-state.ts +2 -1
  110. package/packages/core/src/processes/repo-view.ts +25 -0
  111. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  112. package/packages/core/src/scenarios/harness.ts +7 -0
  113. package/packages/core/src/store/adapter.ts +9 -0
  114. package/packages/core/src/store/artifact-meta.ts +7 -0
  115. package/packages/core/src/store/build-scope.ts +28 -0
  116. package/packages/core/src/store/contract.ts +182 -0
  117. package/packages/core/src/store/event-reads.ts +156 -0
  118. package/packages/core/src/store/local/schema.ts +11 -0
  119. package/packages/core/src/store/local/store.ts +117 -2
  120. package/packages/core/src/store/memory.ts +241 -0
  121. package/packages/core/src/store/phase-session.ts +47 -0
  122. package/packages/core/src/store/reduced-reads.ts +8 -0
  123. package/packages/core/src/store/reducer-value-shapes.json +10546 -8877
  124. package/packages/core/src/store/reducer-value-validation.ts +109 -6
  125. package/packages/core/src/store/reducer-values.ts +62 -2
  126. package/packages/core/src/store/remote/client.ts +208 -23
  127. package/packages/core/src/store/remote/compatibility.ts +195 -25
  128. package/packages/core/src/store/remote/errors.ts +16 -0
  129. package/packages/core/src/store/remote/index.ts +17 -0
  130. package/packages/core/src/store/remote/protocol.ts +30 -1
  131. package/packages/core/src/store/remote/released-clients.json +37 -0
  132. package/packages/core/src/store/remote/released-clients.ts +88 -0
  133. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  135. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  136. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  137. package/packages/core/src/store/remote/version.ts +8 -1
  138. package/packages/core/src/store/repo-state-events.ts +6 -3
  139. package/packages/core/src/store/scan-cadence.ts +15 -0
  140. package/packages/core/src/store/session-handle.ts +18 -0
  141. package/packages/core/src/store/snapshots.ts +16 -3
  142. package/packages/core/src/store/types.ts +29 -6
  143. package/packages/core/src/testing/dispatch-read-budget.ts +457 -7
  144. package/packages/core/src/testing/index.ts +6 -1
  145. package/packages/core/src/testing/reduced-read-budget.ts +1240 -9
  146. package/skills/guide/SKILL.md +220 -22
  147. package/skills/guide/references/accounts.md +50 -1
  148. package/skills/guide/references/integration-tree.md +24 -5
  149. package/skills/guide/references/operator-api.md +81 -10
  150. package/skills/guide/references/plugin-authoring.md +51 -2
  151. package/skills/guide/references/remote-store-protocol.md +321 -46
  152. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  153. package/skills/guide/references/restacking.md +105 -3
  154. package/skills/guide/references/setup.md +37 -8
  155. package/skills/guide/references/spec-standard.md +41 -5
  156. package/skills/guide/references/ticket-dependencies.md +8 -0
  157. package/skills/implement/SKILL.md +12 -3
  158. package/skills/operate/SKILL.md +85 -12
  159. package/skills/plan/SKILL.md +27 -4
  160. package/skills/plan-review/SKILL.md +22 -2
  161. package/skills/reconcile/SKILL.md +16 -1
  162. package/skills/spec/SKILL.md +7 -4
  163. package/skills/tickets/SKILL.md +7 -3
  164. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,16 @@
1
+ import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import { assertTargetOid, observeTarget } from '../kernel/target-observation'
3
+ import {
4
+ MissingAccountCredentialsError,
5
+ missingAccountCredentials,
6
+ reconcileMissingAccounts,
7
+ type MissingAccountCredential,
8
+ } from '../accounts/availability'
9
+
10
+ import { WorkspaceFenceUnknown, preserveWorkspaceBeforeRelease } from './workspace-preservation'
11
+ import { WorkspaceCleanupRequired } from '../ports/types'
12
+ import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
13
+ import type { TicketPreparation } from '../kernel/ticket-preparation'
1
14
  import { sampleTargetDistance } from '../kernel/target-distance'
2
15
  import { capturedBuildConfig } from './verify-cycle-config'
3
16
  import { publicationRetryGate } from '../kernel/publication-retry'
@@ -8,6 +21,8 @@ import {
8
21
  import {
9
22
  nodeActivityKey,
10
23
  nodePollingSchedule,
24
+ nodePollingCheckpointRequired,
25
+ nodePollingEvidenceValid,
11
26
  nodePollingUnsettled,
12
27
  nodeTicketObservationKey,
13
28
  } from '../kernel/node-polling'
@@ -17,7 +32,13 @@ import {
17
32
  migrationIdentity,
18
33
  historicalTicketIdentity,
19
34
  } from '../kernel/ticket-migrations'
20
- import { nodeRestackDemand, presenceRestackPath } from '../kernel/node-restack-demand'
35
+ import { suspendNativeLanding } from '../kernel/landing-publication'
36
+ import {
37
+ actionableRestackDemand,
38
+ restackAvailabilityFingerprint,
39
+ restackLandingKey,
40
+ presenceRestackPath,
41
+ } from '../kernel/node-restack-demand'
21
42
  import {
22
43
  deferMixedVersion,
23
44
  mixedVersionDeferred,
@@ -59,7 +80,11 @@ import {
59
80
  blockerBuild,
60
81
  missingChanges,
61
82
  presenceInputs,
62
- observePresence,
83
+ confirmedLandings,
84
+ presenceWitness,
85
+ projectPresence,
86
+ presenceEvidence,
87
+ destinationAliases,
63
88
  ownedContribution,
64
89
  type ChangeIdentity,
65
90
  type PresenceInputs,
@@ -141,6 +166,7 @@ import type {
141
166
  Ticket,
142
167
  TicketSource,
143
168
  WorkspaceProvider,
169
+ WorkspaceProvisionResult,
144
170
  } from '../ports/types'
145
171
  import { NoCommitsBetweenBranchesError, TicketSourceRateLimitError } from '../ports/types'
146
172
  import type { Exec } from '../ports/workspace/git-worktree'
@@ -371,9 +397,9 @@ export interface TickReport {
371
397
  abandoned: number
372
398
  /** Janitor: queued builds explicitly discarded and returned to Ready. */
373
399
  discarded: number
374
- /** Janitor failures contained to individual builds during this pass. */
400
+ /** Contained build janitor and ticket-preparation recovery failures this pass. */
375
401
  janitorFailed: number
376
- /** One actionable line per contained janitor failure, attributed by slug. */
402
+ /** One actionable line per contained failure, attributed by build or attempt. */
377
403
  janitorDiagnostics: string[]
378
404
  /** Ordinary-tick recovery completed an interrupted post-creation dispatch. */
379
405
  recovered: number
@@ -581,6 +607,9 @@ export interface TickOpts {
581
607
  export type LaunchRunnerResult = 'scheduled' | 'already-active'
582
608
 
583
609
  export interface DispatcherDeps {
610
+ /** Current selected-account presence; no store reads. */
611
+ missingAccounts?: () => MissingAccountCredential[]
612
+ accountCredentialSource?: MissingAccountCredential['source']
584
613
  store: BuildStore
585
614
  tickets: TicketSource
586
615
  workspaces: WorkspaceProvider
@@ -687,6 +716,8 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
687
716
  return paused && state.status === 'queued'
688
717
  }
689
718
 
719
+ export const SWEEP_PIN_CACHE_CAPACITY = 128
720
+
690
721
  export class Dispatcher {
691
722
  // Only scheduling is cached. Eligibility facts still come from durable state,
692
723
  // and each admitted verification/publication samples the source this pass.
@@ -779,28 +810,72 @@ export class Dispatcher {
779
810
  })
780
811
  }
781
812
 
813
+ // Disposable parsed pins only. Current facts, live policy and cycle captures
814
+ // are recomputed on every decision; action boundaries never use this cache.
815
+ private readonly sweepPins = new Map<string, { revision: number; config: Config }>()
816
+
782
817
  /** Read at each decision boundary: artifact revisions are independent of events. */
783
818
  private async decideBuild(
784
819
  slug: string,
785
820
  state: Parameters<typeof decideNextFromFacts>[0],
786
821
  log: Parameters<typeof decideNextFromFacts>[1],
787
822
  report: TickReport,
823
+ sweep = false,
788
824
  ): Promise<ReturnType<typeof decideNextFromFacts> | undefined> {
789
825
  let revision: number | undefined
790
826
  try {
791
- let artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
792
- if (artifact === null) return decideNextFromFacts(state, log, this.deps.config)
793
- revision = artifact.meta.revision
794
- let pinned: Config
795
- try {
796
- pinned = parseEffectiveBuildConfig(artifact)
797
- } catch (error) {
798
- if (this.deps.repairBuildConfig === undefined) throw error
799
- await this.deps.repairBuildConfig(slug)
800
- artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
801
- if (artifact === null) throw new Error('configuration repair deposited no pipeline')
827
+ let pinned: Config | undefined
828
+ let cacheable = false
829
+ if (sweep && this.store.getLatestArtifactMeta) {
830
+ try {
831
+ const meta = await this.store.getLatestArtifactMeta(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
832
+ if (meta === null) {
833
+ this.sweepPins.delete(slug)
834
+ return decideNextFromFacts(state, log, this.deps.config)
835
+ }
836
+ revision = meta.revision
837
+ cacheable = true
838
+ const cached = this.sweepPins.get(slug)
839
+ if (cached?.revision === revision) {
840
+ pinned = cached.config
841
+ // Map insertion order is the deterministic LRU order.
842
+ this.sweepPins.delete(slug)
843
+ this.sweepPins.set(slug, cached)
844
+ } else {
845
+ this.sweepPins.delete(slug)
846
+ }
847
+ } catch (error) {
848
+ if (!(error instanceof ArtifactMetaUnsupportedError)) throw error
849
+ this.sweepPins.delete(slug)
850
+ }
851
+ }
852
+ if (pinned === undefined) {
853
+ let artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
854
+ if (artifact === null) {
855
+ this.sweepPins.delete(slug)
856
+ return decideNextFromFacts(state, log, this.deps.config)
857
+ }
802
858
  revision = artifact.meta.revision
803
- pinned = parseEffectiveBuildConfig(artifact)
859
+ try {
860
+ pinned = parseEffectiveBuildConfig(artifact)
861
+ } catch (error) {
862
+ this.sweepPins.delete(slug)
863
+ if (this.deps.repairBuildConfig === undefined) throw error
864
+ await this.deps.repairBuildConfig(slug)
865
+ artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
866
+ if (artifact === null) throw new Error('configuration repair deposited no pipeline')
867
+ revision = artifact.meta.revision
868
+ pinned = parseEffectiveBuildConfig(artifact)
869
+ }
870
+ if (cacheable) {
871
+ // A concurrent deposit may have advanced the revision after the probe:
872
+ // label the bytes with the full response's revision, never the probe's.
873
+ this.sweepPins.delete(slug)
874
+ this.sweepPins.set(slug, { revision, config: pinned })
875
+ if (this.sweepPins.size > SWEEP_PIN_CACHE_CAPACITY) {
876
+ this.sweepPins.delete(this.sweepPins.keys().next().value!)
877
+ }
878
+ }
804
879
  }
805
880
  return decideNextFromFacts(
806
881
  state,
@@ -813,6 +888,7 @@ export class Dispatcher {
813
888
  ),
814
889
  )
815
890
  } catch (error) {
891
+ this.sweepPins.delete(slug)
816
892
  report.blockedDiagnostics.push(
817
893
  `build ${slug} pipeline${revision === undefined ? '' : ` revision ${revision}`} unavailable: pipeline decisions withheld; next tick retries. Restore readable build-branch configuration or use a compatible dispatcher version. ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
818
894
  )
@@ -855,6 +931,12 @@ export class Dispatcher {
855
931
  * slug here defers to the continuation; it never blocks on it. */
856
932
  private readonly continuations = new Map<string, ProvisionContinuation>()
857
933
 
934
+ // Batched confirmed landing evidence is shared across nodes for this tick.
935
+ // Only durable availability facts authorize the shortcut after restart.
936
+ private availabilityLandings?: ReturnType<typeof confirmedLandings>
937
+ private availabilityLandingKey?: string
938
+ private availabilityEntries?: ReturnType<Dispatcher['repoBuildDigests']>
939
+
858
940
  /** The incremental repository view every stage reads and writes through
859
941
  * (AUT-647): `deps.store` itself when the caller already wrapped it. */
860
942
  private readonly store: RepoViewStore
@@ -909,6 +991,9 @@ export class Dispatcher {
909
991
 
910
992
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
911
993
  async tick(opts: TickOpts = {}): Promise<TickReport> {
994
+ this.availabilityEntries = undefined
995
+ this.availabilityLandings = undefined
996
+ this.availabilityLandingKey = undefined
912
997
  const builds = new Map<string, number>()
913
998
  let total = 0
914
999
  let unattributed = 0
@@ -967,6 +1052,7 @@ export class Dispatcher {
967
1052
  // the durable driver of this tick's fan-out below. Neither control
968
1053
  // pretends to a serialization the store does not offer.
969
1054
  const repoFacts = this.store.repositoryFacts()
1055
+ if (this.deps.missingAccounts) await this.reconcileAccountPresence(this.deps.missingAccounts())
970
1056
  const paused = repoFacts.settings.paused
971
1057
  const autoMergeSeedFact = undefined
972
1058
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
@@ -990,6 +1076,8 @@ export class Dispatcher {
990
1076
  // durable fact drives it, so a second dispatcher polling the same
991
1077
  // repository converges the same state.
992
1078
  if (this.outOfBudget(opts)) return report
1079
+ await this.recoverTicketPreparations(report, opts)
1080
+ if (this.outOfBudget(opts)) return report
993
1081
  await this.janitor(report, launched, opts)
994
1082
  if (this.outOfBudget(opts)) return report
995
1083
  await this.recoverDispatches(report, launched, paused, opts)
@@ -1212,7 +1300,17 @@ export class Dispatcher {
1212
1300
  }
1213
1301
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
1214
1302
  report.queued = listing.tickets.filter(
1215
- (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
1303
+ (ticket) =>
1304
+ !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
1305
+ !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
1306
+ const ref = resolveTicketRef(
1307
+ this.store.repositoryFacts().ticketMigrations,
1308
+ attempt.ticket,
1309
+ this.deps.tickets.name,
1310
+ attempt.slug ?? attempt.attempt,
1311
+ )
1312
+ return ref.source === ticket.ref.source && ref.id === ticket.ref.id
1313
+ }),
1216
1314
  ).length
1217
1315
  report.invalidTickets = listing.diagnostics.length
1218
1316
  report.ticketDiagnostics = [...listing.diagnostics]
@@ -1263,13 +1361,25 @@ export class Dispatcher {
1263
1361
  const criteriaFingerprint = hash(readyCriteria(this.deps.config))
1264
1362
  const startedAt = this.deps.clock().toISOString()
1265
1363
  const previous = this.latestScan()
1364
+ const cached = await this.store.getScanCadence(this.deps.repo)
1365
+ // Outcomes always come from the reduction. This row only acknowledges their cadence.
1366
+ const valid =
1367
+ previous !== undefined &&
1368
+ cached !== null &&
1369
+ cached.scanSeq === this.store.repositoryFacts().scanSeq &&
1370
+ cached.mode === previous.mode &&
1371
+ cached.readinessFingerprint === previous.readinessFingerprint &&
1372
+ cached.criteriaFingerprint === previous.criteriaFingerprint &&
1373
+ Number.isFinite(Date.parse(cached.startedAt))
1374
+ const baseline = valid ? cached : previous
1266
1375
  const elapsed =
1267
- previous === undefined ? Infinity : Date.parse(startedAt) - Date.parse(previous.startedAt)
1376
+ baseline === undefined ? Infinity : Date.parse(startedAt) - Date.parse(baseline.startedAt)
1268
1377
  return {
1269
1378
  startedAt,
1270
1379
  mode,
1271
1380
  readinessFingerprint,
1272
1381
  criteriaFingerprint,
1382
+ allowClockRollback: elapsed < 0,
1273
1383
  due:
1274
1384
  previous === undefined ||
1275
1385
  elapsed < 0 ||
@@ -1284,27 +1394,94 @@ export class Dispatcher {
1284
1394
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
1285
1395
  report: TickReport,
1286
1396
  ): Promise<void> {
1397
+ const payload = {
1398
+ startedAt: checkpoint.startedAt,
1399
+ mode: checkpoint.mode,
1400
+ readinessFingerprint: checkpoint.readinessFingerprint,
1401
+ criteriaFingerprint: checkpoint.criteriaFingerprint,
1402
+ queued: report.queued,
1403
+ invalidTickets: report.invalidTickets,
1404
+ ticketDiagnostics: report.ticketDiagnostics.slice(0, 1000),
1405
+ dependencyBlocked: report.dependencyBlocked,
1406
+ dependencyDiagnostics: report.dependencyDiagnostics.slice(0, 1000),
1407
+ creationWithheld: report.creationWithheld,
1408
+ creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
1409
+ }
1410
+ const previous = this.latestScan()
1411
+ const unchanged =
1412
+ previous !== undefined &&
1413
+ Object.keys(payload)
1414
+ .filter((key) => key !== 'startedAt')
1415
+ .every(
1416
+ (key) =>
1417
+ JSON.stringify(previous[key as keyof typeof payload]) ===
1418
+ JSON.stringify(payload[key as keyof typeof payload]),
1419
+ )
1287
1420
  await this.store.ensureRepo(this.deps.repo)
1288
- await this.store.appendRepo(this.deps.repo, {
1289
- actor: DISPATCHER,
1290
- type: 'dispatcher.ticket-scan-completed',
1291
- payload: {
1421
+ let scanSeq = this.store.repositoryFacts().scanSeq
1422
+ if (!unchanged) {
1423
+ const event = await this.store.appendRepo(this.deps.repo, {
1424
+ actor: DISPATCHER,
1425
+ type: 'dispatcher.ticket-scan-completed',
1426
+ payload,
1427
+ })
1428
+ scanSeq = event.seq
1429
+ }
1430
+ if (scanSeq === undefined) throw new Error('completed scan has no canonical fact')
1431
+ await this.store.putScanCadence(
1432
+ this.deps.repo,
1433
+ {
1434
+ scanSeq,
1292
1435
  startedAt: checkpoint.startedAt,
1293
1436
  mode: checkpoint.mode,
1294
1437
  readinessFingerprint: checkpoint.readinessFingerprint,
1295
1438
  criteriaFingerprint: checkpoint.criteriaFingerprint,
1296
- queued: report.queued,
1297
- invalidTickets: report.invalidTickets,
1298
- ticketDiagnostics: report.ticketDiagnostics.slice(0, 1000),
1299
- dependencyBlocked: report.dependencyBlocked,
1300
- dependencyDiagnostics: report.dependencyDiagnostics.slice(0, 1000),
1301
- creationWithheld: report.creationWithheld,
1302
- creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
1303
1439
  },
1440
+ checkpoint.allowClockRollback,
1441
+ )
1442
+ }
1443
+
1444
+ private accountsAvailable(): boolean {
1445
+ return !this.deps.missingAccounts?.().length
1446
+ }
1447
+
1448
+ private accountReconciliation: Promise<unknown> = Promise.resolve()
1449
+
1450
+ private reconcileAccountPresence(
1451
+ missing: readonly MissingAccountCredential[],
1452
+ merge = false,
1453
+ ): Promise<void> {
1454
+ const operation = this.accountReconciliation.then(async () => {
1455
+ if (missing.length && !this.store.journalRecorded())
1456
+ await this.store.ensureRepo(this.deps.repo)
1457
+ const current = this.store.repositoryFacts().missingAccounts
1458
+ const next = merge
1459
+ ? Object.values({
1460
+ ...current,
1461
+ ...Object.fromEntries(missing.map((account) => [account.name, account])),
1462
+ })
1463
+ : missing
1464
+ await reconcileMissingAccounts(next, current, (event) =>
1465
+ this.store.appendRepo(this.deps.repo, event),
1466
+ )
1304
1467
  })
1468
+ this.accountReconciliation = operation.catch(() => {})
1469
+ return operation
1470
+ }
1471
+
1472
+ async holdForMissingAccounts(error: unknown): Promise<boolean> {
1473
+ if (!(error instanceof MissingAccountCredentialsError)) return false
1474
+ const absent = missingAccountCredentials(
1475
+ Object.fromEntries(error.missing.map((account) => [account.name, account.descriptor])),
1476
+ {},
1477
+ this.deps.accountCredentialSource,
1478
+ )
1479
+ await this.reconcileAccountPresence(absent, true)
1480
+ return true
1305
1481
  }
1306
1482
 
1307
1483
  private async triggerHarvest(): Promise<void> {
1484
+ if (!this.accountsAvailable()) return
1308
1485
  const start = this.deps.startHarvest
1309
1486
  if (start === undefined) return
1310
1487
  // Use the tick sample, advanced by any local repository append.
@@ -1329,6 +1506,7 @@ export class Dispatcher {
1329
1506
  launched: Set<string>,
1330
1507
  report: TickReport = emptyTickReport(),
1331
1508
  ): Promise<LaunchRunnerResult> {
1509
+ if (!this.accountsAvailable()) return 'already-active'
1332
1510
  if (await this.forgeCoolingDown()) return 'already-active'
1333
1511
  if (await deferMixedVersion(this.store, slug)) return 'already-active'
1334
1512
  const launchState = (await this.store.buildFacts(slug)).state
@@ -1665,6 +1843,7 @@ export class Dispatcher {
1665
1843
  },
1666
1844
  ): Promise<'kicked' | 'in-flight' | 'foreign-live'> {
1667
1845
  const slug = record.slug
1846
+ if (!this.accountsAvailable()) return 'in-flight'
1668
1847
  if (this.continuations.has(slug)) return 'in-flight'
1669
1848
  const marker = this.openProvisionMarker(events)
1670
1849
  if (marker !== undefined) {
@@ -1771,7 +1950,7 @@ export class Dispatcher {
1771
1950
  return
1772
1951
  }
1773
1952
  const priorGenerations = events.workspaceGenerations
1774
- const handle = await workspaces.provision({
1953
+ const handle = await this.provisionWorkspace(slug, {
1775
1954
  // Local providers provision FROM the physical checkout; remote
1776
1955
  // providers ignore the value (their host seams are injected).
1777
1956
  repo: this.deps.checkout ?? this.deps.repo,
@@ -1820,12 +1999,13 @@ export class Dispatcher {
1820
1999
  const queued = (await readBuildFacts(store, slug)).value.state.status === 'queued'
1821
2000
  boundary = input.tail === 'dispatch' || queued ? 'dispatch' : 'launch'
1822
2001
  if (boundary === 'dispatch') await this.completeDispatchBoundaries(record, input.seed)
1823
- else await this.deps.launchRunner(slug)
2002
+ else if (this.accountsAvailable()) await this.deps.launchRunner(slug)
1824
2003
  } catch (error) {
1825
2004
  // Dispatch boundaries own their failure facts and exhaustion repair.
1826
2005
  // A failed tail read/write leaves durable unfinished work for the next
1827
2006
  // tick; it is not another provider workspace failure. Replacement
1828
2007
  // runner launch errors retain the existing infrastructure-budget path.
2008
+ if (await this.holdForMissingAccounts(error)) return
1829
2009
  if (boundary === 'read' || boundary === 'dispatch') return
1830
2010
  const events = (await readBuildFacts(store, slug)).value
1831
2011
  if (workspaces.recovery !== undefined) {
@@ -2042,21 +2222,24 @@ export class Dispatcher {
2042
2222
  )
2043
2223
  return
2044
2224
  const now = this.deps.clock().toISOString()
2045
- const previousCheck = pollStart.nodePolling
2225
+ const previousCheck = current.nodePolling
2226
+ if (
2227
+ !nodePollingCheckpointRequired(current, key, this.deps.config.policy, new Date(now))
2228
+ )
2229
+ return
2046
2230
  await this.store.appendIfCurrent(record.slug, current.lastSeq, {
2047
2231
  actor: DISPATCHER,
2048
2232
  type: 'node.poll-checked',
2049
2233
  payload: {
2050
2234
  activityKey: key,
2051
- unchangedSince:
2052
- previousCheck?.activityKey === key &&
2053
- previousCheck.nodeIdleAfterSeconds ===
2054
- this.deps.config.policy.nodeIdleAfterSeconds &&
2055
- previousCheck.nodeIdlePollSeconds ===
2056
- this.deps.config.policy.nodeIdlePollSeconds &&
2057
- Date.parse(previousCheck.unchangedSince) <= Date.parse(now)
2058
- ? previousCheck.unchangedSince
2059
- : now,
2235
+ unchangedSince: nodePollingEvidenceValid(
2236
+ current,
2237
+ key,
2238
+ this.deps.config.policy,
2239
+ new Date(now),
2240
+ )
2241
+ ? previousCheck!.unchangedSince
2242
+ : now,
2060
2243
  nodeIdleAfterSeconds: this.deps.config.policy.nodeIdleAfterSeconds,
2061
2244
  nodeIdlePollSeconds: this.deps.config.policy.nodeIdlePollSeconds,
2062
2245
  },
@@ -2646,25 +2829,36 @@ export class Dispatcher {
2646
2829
  private async observeTarget(
2647
2830
  slug: string,
2648
2831
  branch: string,
2649
- previous: string | undefined,
2832
+ _previous: string | undefined,
2650
2833
  report: TickReport,
2651
2834
  ): Promise<boolean> {
2652
- let sha: string
2653
2835
  try {
2654
- sha = await this.baseSha(branch)
2836
+ const sha = await this.baseSha(branch)
2837
+ return (
2838
+ (await observeTarget({
2839
+ store: this.store,
2840
+ forge: this.deps.forge,
2841
+ slug,
2842
+ branch,
2843
+ sha,
2844
+ actor: DISPATCHER,
2845
+ proveRewrite: (node, from) =>
2846
+ proveTargetLineage({
2847
+ store: this.store,
2848
+ forge: this.deps.forge,
2849
+ node,
2850
+ from,
2851
+ branch,
2852
+ sha,
2853
+ }),
2854
+ })) !== 'unchanged'
2855
+ )
2655
2856
  } catch (error) {
2656
2857
  const message =
2657
2858
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
2658
2859
  report.janitorDiagnostics.push(`build ${slug}: target observation failed — ${message}`)
2659
2860
  return false
2660
2861
  }
2661
- if (sha === previous) return false
2662
- await this.store.append(slug, {
2663
- actor: DISPATCHER,
2664
- type: 'target.moved',
2665
- payload: { branch, sha },
2666
- })
2667
- return true
2668
2862
  }
2669
2863
 
2670
2864
  private forgeWorkspacePath(events: CurrentBuildFacts): string {
@@ -3759,6 +3953,32 @@ export class Dispatcher {
3759
3953
  }
3760
3954
  }
3761
3955
 
3956
+ private async provisionWorkspace(
3957
+ slug: string,
3958
+ input: Parameters<WorkspaceProvider['provision']>[0],
3959
+ ) {
3960
+ const facts = (await readBuildFacts(this.store, slug)).value
3961
+ try {
3962
+ return await this.deps.workspaces.provision({
3963
+ ...input,
3964
+ restoration: facts.workspacePreservation?.payload.heads,
3965
+ })
3966
+ } catch (error) {
3967
+ if (error instanceof WorkspaceCleanupRequired) {
3968
+ await this.store.append(slug, {
3969
+ actor: DISPATCHER,
3970
+ type: 'workspace.cleanup-required',
3971
+ payload: {
3972
+ ...error.workspace,
3973
+ base: error.workspace.base ?? facts.latestWorkspace!.payload.base,
3974
+ remote: this.deps.workspaces.publication !== undefined,
3975
+ },
3976
+ })
3977
+ }
3978
+ throw error
3979
+ }
3980
+ }
3981
+
3762
3982
  private async confirmedWorkspacePublication(events: CurrentBuildFacts, slug: string) {
3763
3983
  const sha = await readBuildSelector(this.store, slug, 'publishedBranchHead')
3764
3984
  return sha === undefined ? undefined : { sha, cacheHeads: events.gitTips }
@@ -3779,6 +3999,7 @@ export class Dispatcher {
3779
3999
  cleanupPending: boolean
3780
4000
  },
3781
4001
  ): Promise<void> {
4002
+ if (await this.holdForMissingAccounts(input.error)) return
3782
4003
  const execution = events.state.executions.at(-1)
3783
4004
  const _appended = await appendInfrastructureFailure(
3784
4005
  { store: this.store, ids: this.deps.ids },
@@ -3828,6 +4049,16 @@ export class Dispatcher {
3828
4049
  // failure propagates — a stale workspace with an unrecorded pending
3829
4050
  // request is never reaped (the next tick retries).
3830
4051
  try {
4052
+ await preserveWorkspaceBeforeRelease({
4053
+ store: this.store,
4054
+ slug,
4055
+ owner: this.workspaceOwner(open)!,
4056
+ forge: this.deps.forge,
4057
+ exec: this.deps.exec,
4058
+ reason,
4059
+ now: this.deps.clock(),
4060
+ })
4061
+ events = (await readBuildFacts(this.store, slug)).value
3831
4062
  events = await settlePublicationFactsBeforeRelease(
3832
4063
  { store: this.store, settlePublication: this.settlePublication },
3833
4064
  slug,
@@ -3838,7 +4069,15 @@ export class Dispatcher {
3838
4069
  // Keep this generation and its pending work until forge recovery,
3839
4070
  // while allowing the sweep to supervise the remaining builds.
3840
4071
  if (error instanceof ForgeRequestDeferred) return false
3841
- throw error
4072
+ if (!(error instanceof WorkspaceFenceUnknown)) throw error
4073
+ await this.recordInfrastructureFailure(slug, events, {
4074
+ provider: open.provider,
4075
+ workspaceRef: open.ref,
4076
+ operation: 'reconcile',
4077
+ error,
4078
+ cleanupPending: true,
4079
+ })
4080
+ return false
3842
4081
  }
3843
4082
  const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
3844
4083
  try {
@@ -3919,6 +4158,16 @@ export class Dispatcher {
3919
4158
  // pending publication BEFORE any provider cleanup call, while the
3920
4159
  // workspace still exists. The guard's append failure propagates — the
3921
4160
  // release never proceeds past an unrecorded pending request.
4161
+ await preserveWorkspaceBeforeRelease({
4162
+ store: this.store,
4163
+ slug,
4164
+ owner,
4165
+ forge: this.deps.forge,
4166
+ exec: this.deps.exec,
4167
+ reason,
4168
+ now: this.deps.clock(),
4169
+ })
4170
+ events = (await readBuildFacts(this.store, slug)).value
3922
4171
  events = await settlePublicationFactsBeforeRelease(
3923
4172
  { store: this.store, settlePublication: this.settlePublication },
3924
4173
  slug,
@@ -3978,42 +4227,12 @@ export class Dispatcher {
3978
4227
  } satisfies EventWrite<'workspace.released'>)
3979
4228
  }
3980
4229
 
3981
- /** Current tip of the base branch. A forge with the checkout-less
3982
- * `remoteBranchSha` capability answers from the GitHub API (origin mode);
3983
- * otherwise `git ls-remote <path> refs/heads/<b>` against the dispatcher's
3984
- * physical checkout (§15.7: no network). The checkout, not the store
3985
- * identity — `deps.repo` is the normalized origin since the identity
3986
- * change, and ls-remote against it would hit the network from a URL.
3987
- * Origin-less fixtures whose identity is a path keep working through the
3988
- * fallback. */
4230
+ /** Only the authoritative forge may resolve a destination tip. */
3989
4231
  private async baseSha(baseBranch: string): Promise<string> {
3990
- const remoteBranchSha = this.deps.forge.remoteBranchSha
3991
- if (remoteBranchSha !== undefined) {
3992
- try {
3993
- return await remoteBranchSha.call(this.deps.forge, baseBranch)
3994
- } catch {
3995
- // A forge that advertises the capability but cannot resolve this branch
3996
- // (a checkout-mode adapter, an unseeded test fake, or a transient
3997
- // remote failure) falls through to the physical checkout's git read.
3998
- // In origin mode there is no checkout, so the git read's failure is the
3999
- // actionable error and the tick still fails closed.
4000
- }
4001
- }
4002
- const args = [
4003
- 'git',
4004
- 'ls-remote',
4005
- this.deps.checkout ?? this.deps.repo,
4006
- `refs/heads/${baseBranch}`,
4007
- ]
4008
- const result = await this.deps.exec(args, {})
4009
- const sha = result.stdout.trim().split(/\s+/)[0]
4010
- if (result.exitCode !== 0 || !sha) {
4011
- throw new Error(
4012
- `${args.join(' ')} exited ${result.exitCode}: ${
4013
- result.stderr.trim() || result.stdout.trim() || '(no output)'
4014
- }`,
4015
- )
4016
- }
4232
+ const read = this.deps.forge.remoteBranchSha
4233
+ if (!read) throw new Error('forge remoteBranchSha capability unavailable')
4234
+ const sha = await read.call(this.deps.forge, baseBranch)
4235
+ assertTargetOid(sha)
4017
4236
  return sha
4018
4237
  }
4019
4238
 
@@ -4088,6 +4307,7 @@ export class Dispatcher {
4088
4307
  assets?: PinnedAsset[]
4089
4308
  },
4090
4309
  ): Promise<DispatchOutcome> {
4310
+ if (!this.accountsAvailable()) return 'parked'
4091
4311
  const store = this.store
4092
4312
  const { config } = this.deps
4093
4313
  if (await deferMixedVersion(this.store, record.slug)) return 'parked'
@@ -4145,7 +4365,7 @@ export class Dispatcher {
4145
4365
  return 'deferred'
4146
4366
  }
4147
4367
  const priorGenerations = events.workspaceGenerations
4148
- const handle = await this.deps.workspaces.provision({
4368
+ const handle = await this.provisionWorkspace(record.slug, {
4149
4369
  // Local providers provision FROM the physical checkout; remote
4150
4370
  // providers ignore the value (their host seams are injected).
4151
4371
  repo: this.deps.checkout ?? this.deps.repo,
@@ -4175,6 +4395,7 @@ export class Dispatcher {
4175
4395
  events = (await readBuildFacts(store, record.slug)).value
4176
4396
  }
4177
4397
  } catch (error) {
4398
+ if (await this.holdForMissingAccounts(error)) return 'parked'
4178
4399
  if (error instanceof MixedVersionDeferral) return 'parked'
4179
4400
  const events = (await readBuildFacts(store, record.slug)).value
4180
4401
  if (stage === 'workspace' && this.deps.workspaces.recovery !== undefined) {
@@ -4321,11 +4542,13 @@ export class Dispatcher {
4321
4542
  if (launchState.status !== 'queued' || launchState.discardRequest !== undefined) {
4322
4543
  return 'parked'
4323
4544
  }
4545
+ if (!this.accountsAvailable()) return 'parked'
4324
4546
  if (launched === undefined) await this.deps.launchRunner(record.slug)
4325
4547
  else await this.launch(record.slug, launched, report)
4326
4548
  if (authored && report !== undefined) report.authored += 1
4327
4549
  return 'completed'
4328
4550
  } catch (error) {
4551
+ if (await this.holdForMissingAccounts(error)) return 'parked'
4329
4552
  const events = (await readBuildFacts(store, record.slug)).value
4330
4553
  const attempt = events.dispatchFailureCount + 1
4331
4554
  const message = (
@@ -4483,14 +4706,6 @@ export class Dispatcher {
4483
4706
  if (this.outOfBudget(opts)) break
4484
4707
  if (record.lease) {
4485
4708
  if (new Date(record.lease.expiresAt).getTime() > now) continue // healthy
4486
- } else if (now - new Date(record.updatedAt).getTime() < this.leaseTtlMs) {
4487
- const facts = await this.store.buildFacts(record.slug)
4488
- const cleanup = facts.state.verifyStage.cleanupExecutionSeq
4489
- if (
4490
- facts.lastExecution !== 'relaunch' &&
4491
- !(cleanup !== undefined && facts.state.verifyStage.executionSeq <= cleanup)
4492
- )
4493
- continue // absent lease within the first-claim grace (see DispatcherOpts)
4494
4709
  }
4495
4710
  const facts = await this.store.buildFacts(record.slug)
4496
4711
  const state = facts.state
@@ -4531,9 +4746,27 @@ export class Dispatcher {
4531
4746
  throw error
4532
4747
  }
4533
4748
  }
4534
- const decision = await this.decideBuild(record.slug, state, facts.log, report)
4749
+ const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4535
4750
  if (decision === undefined) continue
4536
4751
  if (state.status === 'done' || state.status === 'aborted') continue
4752
+ const orphanEligible = (state: BuildState) =>
4753
+ !paused &&
4754
+ state.status === 'running' &&
4755
+ (state.kind !== 'node' || integrationCurrent(state)) &&
4756
+ state.sessions.open.some((session) => session.suspensionCause === undefined)
4757
+ const provedEnded =
4758
+ facts.open === null &&
4759
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
4760
+ const cleanup = state.verifyStage.cleanupExecutionSeq
4761
+ if (
4762
+ !record.lease &&
4763
+ now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
4764
+ facts.lastExecution !== 'relaunch' &&
4765
+ !(cleanup !== undefined && state.verifyStage.executionSeq <= cleanup) &&
4766
+ !(provedEnded && (decision.kind !== 'wait' || orphanEligible(state)))
4767
+ )
4768
+ continue // preserve first-claim grace, but never postpone proved-ended work
4769
+
4537
4770
  if (
4538
4771
  state.kind === 'node' &&
4539
4772
  (!integrationCurrent(state) || facts.workspace === null) &&
@@ -4553,12 +4786,23 @@ export class Dispatcher {
4553
4786
  // proved end settles first (completion facts, lease release, publication)
4554
4787
  // and then falls through to the normal decision; a provider-proved loss
4555
4788
  // falls through to the existing stale path below.
4789
+ let orphanRecoveryDue = orphanEligible(state) && facts.open === null
4556
4790
  const foreignExecution = facts.open
4557
4791
  // A provider- or log-proved end in the same generation re-attaches in
4558
4792
  // place: the guest finished its work, the workspace is still the
4559
4793
  // build's, and replacing the environment would discard a healthy
4560
4794
  // generation. Only an unproven stale lease or a proved loss reaps.
4561
- let endedInPlace = facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch'
4795
+ // A start that later found the open workspace missing is a proved loss
4796
+ // too: the recorded end no longer vouches for an environment that is
4797
+ // gone, and re-attaching would fail against the same ref forever.
4798
+ const failure = state.infrastructureFailure
4799
+ const workspaceMissing =
4800
+ failure?.cause === 'missing' &&
4801
+ failure.operation === 'start' &&
4802
+ failure.workspaceRef === facts.workspace?.ref
4803
+ let endedInPlace =
4804
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4805
+ !workspaceMissing
4562
4806
  if (
4563
4807
  foreignExecution !== null &&
4564
4808
  foreignExecution.commandId !== undefined &&
@@ -4579,6 +4823,10 @@ export class Dispatcher {
4579
4823
  foreignExecution,
4580
4824
  )
4581
4825
  if (settlement === 'running') continue
4826
+ // Unknown liveness is never proof that an open execution is dead.
4827
+ // Settlement may itself raise provider attention. Revalidate cleanup
4828
+ // eligibility from the advanced canonical state before admission.
4829
+ orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
4582
4830
  if (settlement === 'settled') {
4583
4831
  report.settled += 1
4584
4832
  endedInPlace = true
@@ -4595,7 +4843,7 @@ export class Dispatcher {
4595
4843
  // build's, and replacing the environment would discard a healthy
4596
4844
  // generation. Only an unproven stale lease or a proved loss reaps.
4597
4845
  if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
4598
- const parked = decision.kind === 'wait' && !publicationRecoveryDue
4846
+ const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
4599
4847
  const reason =
4600
4848
  state.status === 'paused'
4601
4849
  ? ('pause' as const)
@@ -4623,7 +4871,7 @@ export class Dispatcher {
4623
4871
  // fresh runner for a paused or blocked build whose workspace was just
4624
4872
  // reaped. Every other path that reaches this line with a wait decision
4625
4873
  // already continued earlier.
4626
- if (decision.kind === 'wait' && !publicationRecoveryDue) continue
4874
+ if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) continue
4627
4875
  if (
4628
4876
  facts.workspace === null &&
4629
4877
  this.deps.workspaces.recovery !== undefined &&
@@ -4639,8 +4887,165 @@ export class Dispatcher {
4639
4887
  // boundaries and the launch; this tick performs neither.
4640
4888
  continue
4641
4889
  }
4642
- const result = await this.launch(record.slug, launched, report)
4643
- if (result === 'scheduled') report.swept += 1
4890
+ try {
4891
+ const result = await this.launch(record.slug, launched, report)
4892
+ if (result === 'scheduled') report.swept += 1
4893
+ } catch (error) {
4894
+ // Launchers normally record provider failures themselves. Preserve
4895
+ // durable attention if orphan cleanup fails before that boundary,
4896
+ // without counting an already-recorded failure twice.
4897
+ if (orphanRecoveryDue && open !== null) {
4898
+ const current = (await readBuildFacts(this.store, record.slug)).value
4899
+ if (current.infrastructureCount === facts.infrastructureCount)
4900
+ await this.recordInfrastructureFailure(record.slug, current, {
4901
+ provider: open.provider,
4902
+ workspaceRef: open.ref,
4903
+ operation: 'start',
4904
+ error,
4905
+ cleanupPending: false,
4906
+ })
4907
+ }
4908
+ throw error
4909
+ }
4910
+ }
4911
+ }
4912
+
4913
+ /** Retry a fixed batch under the same repository ownership as intake.
4914
+ * No provider calls for parked deadlines; no history or orphan scans. */
4915
+ private async recoverTicketPreparations(report: TickReport, opts: TickOpts): Promise<void> {
4916
+ const pending = Object.values(this.store.repositoryFacts().preparation)
4917
+ .filter(
4918
+ (attempt) => !attempt.retryAt || Date.parse(attempt.retryAt) <= this.deps.clock().getTime(),
4919
+ )
4920
+ .sort(
4921
+ (a, b) =>
4922
+ Date.parse(a.retryAt ?? '1970-01-01T00:00:00.000Z') -
4923
+ Date.parse(b.retryAt ?? '1970-01-01T00:00:00.000Z') ||
4924
+ a.attempt.localeCompare(b.attempt),
4925
+ )
4926
+ .slice(0, 8)
4927
+ const failures: unknown[] = []
4928
+ for (const attempt of pending) {
4929
+ if (this.outOfBudget(opts)) break
4930
+ try {
4931
+ await this.recoverTicketPreparation(attempt)
4932
+ } catch (error) {
4933
+ failures.push(error)
4934
+ }
4935
+ }
4936
+ for (const error of failures) {
4937
+ report.janitorFailed += 1
4938
+ report.janitorDiagnostics.push(String(error))
4939
+ }
4940
+ }
4941
+
4942
+ private async preparationResolved(
4943
+ attempt: TicketPreparation,
4944
+ outcome: 'lost-claim' | 'handed-back' | 'bounced' | 'owned' | 'abandoned',
4945
+ reason?: string,
4946
+ ): Promise<void> {
4947
+ await this.store.appendRepo(this.deps.repo, {
4948
+ actor: DISPATCHER,
4949
+ type: 'ticket-preparation.resolved',
4950
+ payload: {
4951
+ attempt: attempt.attempt,
4952
+ ticket: attempt.ticket,
4953
+ outcome,
4954
+ ...(reason ? { reason: reason.slice(0, 4000) } : {}),
4955
+ },
4956
+ })
4957
+ }
4958
+
4959
+ private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
4960
+ try {
4961
+ // A rejected create can have committed. Unavailable or conflicting readback
4962
+ // is never absence and must not authorize a ticket transition.
4963
+ if (attempt.slug) {
4964
+ const record = await this.store.getBuild(attempt.slug)
4965
+ if (record) {
4966
+ const created = (await this.store.buildFacts(attempt.slug)).created
4967
+ if (
4968
+ record.repo !== this.deps.repo ||
4969
+ record.ticket?.source !== attempt.ticket.source ||
4970
+ record.ticket?.id !== attempt.ticket.id ||
4971
+ created?.payload.repo !== this.deps.repo ||
4972
+ created.payload.ticket?.source !== attempt.ticket.source ||
4973
+ created.payload.ticket?.id !== attempt.ticket.id
4974
+ )
4975
+ return await this.preparationResolved(
4976
+ attempt,
4977
+ 'abandoned',
4978
+ `Conflicting build ownership at ${attempt.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
4979
+ )
4980
+ await this.preparationResolved(attempt, 'owned')
4981
+ return
4982
+ }
4983
+ }
4984
+ const ref = resolveTicketRef(
4985
+ this.store.repositoryFacts().ticketMigrations,
4986
+ attempt.ticket,
4987
+ this.deps.tickets.name,
4988
+ attempt.slug ?? attempt.attempt,
4989
+ )
4990
+ const ticket = await this.deps.tickets.get(ref.id)
4991
+ if (!ticket)
4992
+ return await this.preparationResolved(
4993
+ attempt,
4994
+ 'abandoned',
4995
+ 'Ticket no longer exists; ticket unchanged.',
4996
+ )
4997
+ if (ticket.state === undefined)
4998
+ return await this.preparationResolved(
4999
+ attempt,
5000
+ 'abandoned',
5001
+ 'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
5002
+ )
5003
+ const state = (value: string) => value.toLowerCase()
5004
+ const handback = attempt.handback ?? attempt.readyState
5005
+ if (state(ticket.state) === state(handback)) {
5006
+ await this.preparationResolved(
5007
+ attempt,
5008
+ handback === attempt.readyState ? 'handed-back' : 'bounced',
5009
+ )
5010
+ return
5011
+ }
5012
+ if (!attempt.claimed || state(ticket.state) !== state(attempt.claimedState))
5013
+ return await this.preparationResolved(
5014
+ attempt,
5015
+ 'abandoned',
5016
+ `Uncertain claim or externally changed ticket state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5017
+ )
5018
+ await this.deps.tickets.transition(ref.id, handback)
5019
+ await this.preparationResolved(
5020
+ attempt,
5021
+ handback === attempt.readyState ? 'handed-back' : 'bounced',
5022
+ )
5023
+ } catch (error) {
5024
+ const message = error instanceof Error ? error.message : String(error)
5025
+ try {
5026
+ await this.store.appendRepo(this.deps.repo, {
5027
+ actor: DISPATCHER,
5028
+ type: 'ticket-preparation.recovery-failed',
5029
+ payload: {
5030
+ attempt: attempt.attempt,
5031
+ ticket: attempt.ticket,
5032
+ claimed: attempt.claimed,
5033
+ handback: attempt.handback ?? attempt.readyState,
5034
+ ...(attempt.error ? { preparationError: attempt.error } : {}),
5035
+ error: message.slice(0, 4000) || 'unknown recovery failure',
5036
+ retryAt: new Date(this.deps.clock().getTime() + 30_000).toISOString(),
5037
+ },
5038
+ })
5039
+ } catch (diagnosticError) {
5040
+ throw new AggregateError(
5041
+ [error, diagnosticError],
5042
+ `ticket preparation recovery failed: ${message}; diagnostic append failed: ${String(diagnosticError)}`,
5043
+ )
5044
+ }
5045
+ throw new Error(
5046
+ `ticket preparation recovery failed: ${message}; original preparation failure: ${attempt.error ?? 'unfinished durable preparation'}`,
5047
+ { cause: error },
5048
+ )
4644
5049
  }
4645
5050
  }
4646
5051
 
@@ -4654,6 +5059,7 @@ export class Dispatcher {
4654
5059
  opts: TickOpts = {},
4655
5060
  autoMergeSeedFact: AutoMergeDefaultFact | undefined = undefined,
4656
5061
  ): Promise<void> {
5062
+ if (!this.accountsAvailable()) return
4657
5063
  const health = this.store.repositoryFacts().forgeHealth
4658
5064
  if (health && Date.parse(health.resetAt) > this.deps.clock().getTime()) return
4659
5065
  const store = this.store
@@ -4696,7 +5102,17 @@ export class Dispatcher {
4696
5102
  ]),
4697
5103
  )
4698
5104
  const ready = listing.tickets.filter(
4699
- (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
5105
+ (ticket) =>
5106
+ !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
5107
+ !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
5108
+ const ref = resolveTicketRef(
5109
+ this.store.repositoryFacts().ticketMigrations,
5110
+ attempt.ticket,
5111
+ this.deps.tickets.name,
5112
+ attempt.slug ?? attempt.attempt,
5113
+ )
5114
+ return ref.source === ticket.ref.source && ref.id === ticket.ref.id
5115
+ }),
4700
5116
  )
4701
5117
  report.invalidTickets += listing.diagnostics.length
4702
5118
  report.ticketDiagnostics.push(...listing.diagnostics)
@@ -4926,70 +5342,156 @@ export class Dispatcher {
4926
5342
  continue
4927
5343
  }
4928
5344
  }
4929
- // Claim-before-launch (§12): losing the claim means another dispatcher
4930
- // (or an earlier tick) owns this ticket.
4931
- if (!(await tickets.claim(ticket.ref.id))) {
4932
- report.claimRaces += 1
4933
- report.queued -= 1
4934
- continue
5345
+ const attempt: TicketPreparation = {
5346
+ attempt: this.deps.ids('prep'),
5347
+ ticket: ticket.ref,
5348
+ readyState: config.tickets.readyState,
5349
+ claimedState: ticketLifecycle(config.tickets).doing,
5350
+ claimed: false,
4935
5351
  }
4936
-
4937
- // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
4938
- // spec-authoring interval so edits made during it are never pinned.
4939
- const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
4940
-
4941
- // Quality gate (§6.3): import a conforming ticket body as the spec;
4942
- // author one for thin-but-groomed tickets; otherwise bounce.
5352
+ await store.ensureRepo(this.deps.repo)
5353
+ await store.appendRepo(this.deps.repo, {
5354
+ actor: DISPATCHER,
5355
+ type: 'ticket-preparation.intended',
5356
+ payload: {
5357
+ attempt: attempt.attempt,
5358
+ ticket: attempt.ticket,
5359
+ readyState: attempt.readyState,
5360
+ claimedState: attempt.claimedState,
5361
+ },
5362
+ })
5363
+ let stage = 'claim'
5364
+ let established = false
5365
+ let record: BuildRecord
4943
5366
  let body = ticket.body
4944
- let conformance = specConformance(body)
4945
5367
  let authoredSession: string | undefined
4946
- if (!conformance.conforms && this.deps.authorSpec) {
4947
- const authored = await this.deps.authorSpec(ticket)
4948
- if (authored !== null) {
4949
- conformance = specConformance(authored)
4950
- if (conformance.conforms) {
4951
- body = authored
4952
- authoredSession = this.deps.ids('s')
5368
+ let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
5369
+ try {
5370
+ if (!(await tickets.claim(ticket.ref.id))) {
5371
+ await this.preparationResolved(attempt, 'lost-claim')
5372
+ report.claimRaces += 1
5373
+ report.queued -= 1
5374
+ continue
5375
+ }
5376
+ attempt.claimed = true
5377
+ stage = 'claim-confirmation'
5378
+ await store.appendRepo(this.deps.repo, {
5379
+ actor: DISPATCHER,
5380
+ type: 'ticket-preparation.claimed',
5381
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket },
5382
+ })
5383
+ stage = 'assets'
5384
+ // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
5385
+ // spec-authoring interval so edits made during it are never pinned.
5386
+ const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
5387
+
5388
+ // Quality gate (§6.3): import a conforming ticket body as the spec;
5389
+ // author one for thin-but-groomed tickets; otherwise bounce.
5390
+ stage = 'spec'
5391
+ let conformance = specConformance(body)
5392
+ if (!conformance.conforms && this.deps.authorSpec) {
5393
+ const authored = await this.deps.authorSpec(ticket)
5394
+ if (authored !== null) {
5395
+ conformance = specConformance(authored)
5396
+ if (conformance.conforms) {
5397
+ body = authored
5398
+ authoredSession = this.deps.ids('s')
5399
+ }
4953
5400
  }
4954
5401
  }
4955
- }
4956
- if (!conformance.conforms) {
4957
- await this.bounce(ticket, conformance.missing)
4958
- report.bounced += 1
4959
- report.queued -= 1
4960
- continue
4961
- }
5402
+ if (!conformance.conforms) {
5403
+ attempt.handback = this.triageState()
5404
+ await store.appendRepo(this.deps.repo, {
5405
+ actor: DISPATCHER,
5406
+ type: 'ticket-preparation.handback-selected',
5407
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket, state: attempt.handback },
5408
+ })
5409
+ stage = 'bounce'
5410
+ await this.bounce(ticket, conformance.missing)
5411
+ await this.preparationResolved(attempt, 'bounced')
5412
+ report.bounced += 1
5413
+ report.queued -= 1
5414
+ continue
5415
+ }
4962
5416
 
4963
- const baseSlug = await this.chooseSlugBase(ticket.title, body)
4964
- const slug = await this.uniqueSlug(baseSlug)
4965
- const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
4966
- const repoOrigin = await this.resolveRepoOriginOnce()
4967
- const createdSeed = {
4968
- ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
4969
- ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
4970
- ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
4971
- // Claim-time provenance: the newest durable default fact that agrees
4972
- // with the launch sample, recorded on `build.created` so the fan-out's
4973
- // seq comparison sees the claim as already answering that fact — and
4974
- // so a newer opposite fact (an interleaved toggle) stays strictly
4975
- // ahead of it and reconciles this build on the next tick (f_b851c0e8).
4976
- ...(autoMergeSeedFact !== undefined ? { autoMergeDefaultSeq: autoMergeSeedFact.seq } : {}),
4977
- assets,
4978
- }
4979
- // `build.created` rides with the record so the pinned assets and the
4980
- // record exist together or not at all.
4981
- const record = await store.createBuild({
4982
- slug,
4983
- repo: this.deps.repo,
4984
- ticket: ticket.ref,
4985
- branch,
4986
- ...(repoOrigin !== undefined ? { repoOrigin } : {}),
4987
- created: {
5417
+ stage = 'naming'
5418
+ const baseSlug = await this.chooseSlugBase(ticket.title, body)
5419
+ const slug = await this.uniqueSlug(baseSlug)
5420
+ const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
5421
+ const repoOrigin = await this.resolveRepoOriginOnce()
5422
+ createdSeed = {
5423
+ ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
5424
+ ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
5425
+ ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
5426
+ // Claim-time provenance: the newest durable default fact that agrees
5427
+ // with the launch sample, recorded on `build.created` so the fan-out's
5428
+ // seq comparison sees the claim as already answering that fact — and
5429
+ // so a newer opposite fact (an interleaved toggle) stays strictly
5430
+ // ahead of it and reconciles this build on the next tick (f_b851c0e8).
5431
+ ...(autoMergeSeedFact !== undefined
5432
+ ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
5433
+ : {}),
5434
+ assets,
5435
+ }
5436
+ // `build.created` rides with the record so the pinned assets and the
5437
+ // record exist together or not at all.
5438
+ stage = 'creation-identity'
5439
+ attempt.slug = slug
5440
+ await store.appendRepo(this.deps.repo, {
4988
5441
  actor: DISPATCHER,
4989
- type: 'build.created',
4990
- payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
4991
- },
4992
- })
5442
+ type: 'ticket-preparation.creation-selected',
5443
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket, slug },
5444
+ })
5445
+ stage = 'create-build'
5446
+ record = await store.createBuild({
5447
+ slug,
5448
+ repo: this.deps.repo,
5449
+ ticket: ticket.ref,
5450
+ branch,
5451
+ ...(repoOrigin !== undefined ? { repoOrigin } : {}),
5452
+ created: {
5453
+ actor: DISPATCHER,
5454
+ type: 'build.created',
5455
+ payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
5456
+ },
5457
+ })
5458
+ established = true
5459
+ await this.preparationResolved(attempt, 'owned')
5460
+ } catch (error) {
5461
+ // Settlement and completion errors after successful creation cannot
5462
+ // release the claim. A later tick settles the retained creation identity.
5463
+ if (established) throw error
5464
+ const errors: unknown[] = [error]
5465
+ attempt.error =
5466
+ (error instanceof Error ? error.message : String(error)).slice(0, 4000) ||
5467
+ 'unknown preparation failure'
5468
+ attempt.stage = stage
5469
+ try {
5470
+ await store.appendRepo(this.deps.repo, {
5471
+ actor: DISPATCHER,
5472
+ type: 'ticket-preparation.failed',
5473
+ payload: {
5474
+ attempt: attempt.attempt,
5475
+ ticket: attempt.ticket,
5476
+ stage,
5477
+ claimed: attempt.claimed,
5478
+ handback: attempt.handback ?? attempt.readyState,
5479
+ error: attempt.error,
5480
+ },
5481
+ })
5482
+ } catch (diagnosticError) {
5483
+ errors.push(diagnosticError)
5484
+ }
5485
+ try {
5486
+ await this.recoverTicketPreparation(attempt)
5487
+ } catch (recoveryError) {
5488
+ errors.push(recoveryError)
5489
+ }
5490
+ throw new AggregateError(
5491
+ errors,
5492
+ `ticket preparation failed (${stage}): ${errors.map(String).join('; ')}`,
5493
+ )
5494
+ }
4993
5495
  report.queued -= 1
4994
5496
  if (ticket.kind !== 'node') capacity -= 1
4995
5497
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
@@ -5201,12 +5703,35 @@ export class Dispatcher {
5201
5703
  forge.remoteBranchSha(state.baseBranch),
5202
5704
  forge.remoteBranchSha(record.branch),
5203
5705
  ])
5706
+ this.availabilityEntries ??= this.repoBuildDigests()
5707
+ const entries = await this.availabilityEntries
5708
+ this.availabilityLandings ??= confirmedLandings(entries)
5709
+ this.availabilityLandingKey ??= restackLandingKey(this.availabilityLandings)
5710
+ const evidence = await presenceInputs(
5711
+ this.store,
5712
+ entries,
5713
+ [record.slug],
5714
+ this.availabilityLandings,
5715
+ )
5716
+ const fingerprint =
5717
+ parent && head
5718
+ ? restackAvailabilityFingerprint(
5719
+ state,
5720
+ record.branch,
5721
+ state.baseBranch,
5722
+ head,
5723
+ parent,
5724
+ evidence,
5725
+ this.availabilityLandingKey,
5726
+ )
5727
+ : ''
5728
+ const actionable = actionableRestackDemand(state, fingerprint)
5204
5729
  if (
5205
- (parent === state.nodeRestack?.contributionBase || !nodeRestackDemand(state)) &&
5730
+ (parent === state.nodeRestack?.contributionBase || !actionable) &&
5206
5731
  state.nodeRestack?.distance?.parent === parent &&
5207
5732
  state.nodeRestack.distance.base === state.nodeRestack.contributionBase &&
5208
5733
  head === state.nodeRestack?.inventory?.head &&
5209
- !Object.keys(state.nodeRestack?.requests ?? {}).length
5734
+ (!Object.keys(state.nodeRestack?.requests ?? {}).length || !actionable)
5210
5735
  )
5211
5736
  return
5212
5737
  }
@@ -5280,15 +5805,7 @@ export class Dispatcher {
5280
5805
  )
5281
5806
  if (result.exitCode !== 0) throw new Error(result.stderr)
5282
5807
  added = true
5283
- const parentHead = forge.remoteBranchSha
5284
- ? await forge.remoteBranchSha(state.baseBranch!)
5285
- : undefined
5286
- if (
5287
- state.nodeRestack?.active ||
5288
- (nodeRestackDemand(state) && parentHead !== state.nodeRestack?.contributionBase)
5289
- ) {
5290
- // Upgrade recovery: an old dispatcher may have left a native request
5291
- // armed. Cancel every targeting leaf before admitting a node rewrite.
5808
+ const beforeReplay = async (operation: string) => {
5292
5809
  for (const child of await this.repoBuildDigests()) {
5293
5810
  if (child.digest.terminal || child.digest.kind === 'node') continue
5294
5811
  const childState = (await this.store.buildFacts(child.record.slug)).state
@@ -5298,11 +5815,10 @@ export class Dispatcher {
5298
5815
  childState.prState !== 'open'
5299
5816
  )
5300
5817
  continue
5301
- const cancelled = await forge.setAutoMerge(checkout, childState.pr.number, false)
5302
- if (cancelled.kind !== 'applied')
5303
- throw new Error(
5304
- `node restack waits for native auto-merge cancellation on ${child.record.slug}`,
5305
- )
5818
+ await suspendNativeLanding(
5819
+ { store: this.store, forge, slug: child.record.slug, workspacePath: checkout },
5820
+ `node:${record.slug}:${operation}`,
5821
+ )
5306
5822
  }
5307
5823
  }
5308
5824
  const outcome = await runNodeTransaction(
@@ -5313,6 +5829,7 @@ export class Dispatcher {
5313
5829
  exec: forge.kernelExec ?? this.deps.exec,
5314
5830
  workspacePath,
5315
5831
  holder,
5832
+ beforeReplay,
5316
5833
  canWrite: async () => {
5317
5834
  if (await deferMixedVersion(this.store, record.slug)) return false
5318
5835
  if (this.outOfBudget(opts)) return false
@@ -5375,13 +5892,14 @@ export class Dispatcher {
5375
5892
  }
5376
5893
  }
5377
5894
 
5895
+ if (!this.accountsAvailable()) return
5378
5896
  if (!(await this.nodeHasCapacity(record.slug))) return
5379
5897
  if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
5380
5898
  const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
5381
5899
  if (kicked === 'kicked') report.provisioning += 1
5382
5900
  } else {
5383
5901
  if (openWorkspace(facts) === null) {
5384
- const handle = await this.deps.workspaces.provision({
5902
+ const handle = await this.provisionWorkspace(record.slug, {
5385
5903
  repo: checkout,
5386
5904
  baseBranch: state.baseBranch!,
5387
5905
  branch: record.branch!,
@@ -5404,6 +5922,7 @@ export class Dispatcher {
5404
5922
  }
5405
5923
  }
5406
5924
  } catch (error) {
5925
+ if (await this.holdForMissingAccounts(error)) return
5407
5926
  const message =
5408
5927
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
5409
5928
  // Safety refusals require human judgment. Infrastructure failures remain
@@ -5445,6 +5964,7 @@ export class Dispatcher {
5445
5964
  sampling: { refreshOnly?: boolean } = {},
5446
5965
  ): Promise<void> {
5447
5966
  if (
5967
+ state.targetRewrite ||
5448
5968
  state.status === 'paused' ||
5449
5969
  state.status === 'done' ||
5450
5970
  state.status === 'aborted' ||
@@ -5610,6 +6130,7 @@ export class Dispatcher {
5610
6130
  await this.observeIntegration(record.slug)
5611
6131
  state = (await this.store.buildFacts(record.slug)).state
5612
6132
  if (!integrationCurrent(state)) return
6133
+ if (!this.accountsAvailable()) return
5613
6134
  const facts = (await readBuildFacts(this.store, record.slug)).value
5614
6135
  if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
5615
6136
  const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
@@ -5617,12 +6138,18 @@ export class Dispatcher {
5617
6138
  return
5618
6139
  }
5619
6140
  if (openWorkspace(facts) === null) {
5620
- const handle = await this.deps.workspaces.provision({
5621
- repo: this.deps.checkout ?? this.deps.repo,
5622
- baseBranch: record.branch,
5623
- branch: record.branch,
5624
- revision: state.integration!.cycle!.head,
5625
- })
6141
+ let handle: WorkspaceProvisionResult
6142
+ try {
6143
+ handle = await this.provisionWorkspace(record.slug, {
6144
+ repo: this.deps.checkout ?? this.deps.repo,
6145
+ baseBranch: record.branch,
6146
+ branch: record.branch,
6147
+ revision: state.integration!.cycle!.head,
6148
+ })
6149
+ } catch (error) {
6150
+ if (await this.holdForMissingAccounts(error)) return
6151
+ throw error
6152
+ }
5626
6153
  await this.store.append(record.slug, {
5627
6154
  actor: DISPATCHER,
5628
6155
  type: 'workspace.provisioned',
@@ -5818,22 +6345,25 @@ export class Dispatcher {
5818
6345
  let observed = observations.get(destination)
5819
6346
  if (!observed) {
5820
6347
  const forge = this.kernelForge()
5821
- if (!forge.remoteBranchSha || (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite))
5822
- throw new Error('forge cannot snapshot destination presence')
6348
+ if (!forge.remoteBranchSha) throw new Error('forge cannot read destination head')
5823
6349
  const head = await forge.remoteBranchSha(branch)
5824
- const evidence = JSON.stringify({
5825
- version: 2,
5826
- revisions: [
5827
- ...inputs.entries
5828
- .filter(({ digest }) => digest.mergedSha || digest.nodeContribution)
5829
- .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq]),
5830
- ...[...inputs.states].map(([slug, state]) => [slug, state.lastSeq]),
5831
- ].sort(),
5832
- })
6350
+ const aliases = destinationAliases(inputs, target?.target.build)
5833
6351
  const cached = this.store.repositoryFacts().presence[destination]
5834
- if (cached?.head === head && cached.branch === branch && cached.evidence === evidence)
5835
- observed = cached
5836
- else
6352
+ if (cached?.head === head && cached.branch === branch && cached.witness?.version === 1) {
6353
+ const identities = projectPresence(cached.witness, inputs.landings, aliases)
6354
+ const evidence = presenceEvidence(cached.witness, identities)
6355
+ observed = { ...cached, identities }
6356
+ if (cached.evidence !== evidence) {
6357
+ await this.store.ensureRepo(this.deps.repo)
6358
+ await this.store.appendRepo(this.deps.repo, {
6359
+ actor: DISPATCHER,
6360
+ type: 'change-presence.observed',
6361
+ payload: { ...cached, identities, evidence },
6362
+ })
6363
+ }
6364
+ } else {
6365
+ if (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite)
6366
+ throw new Error('forge cannot snapshot destination presence')
5837
6367
  observed = await this.withKernelRepository(async (path) => {
5838
6368
  const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
5839
6369
  let sampled: string
@@ -5872,13 +6402,13 @@ export class Dispatcher {
5872
6402
  sampled = resolved.stdout.trim()
5873
6403
  }
5874
6404
  if (sampled !== head) throw new Error('destination moved while sampling presence')
5875
- const identities = await observePresence(
6405
+ const witness = await presenceWitness(
5876
6406
  { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
5877
6407
  head,
5878
- inputs.landings,
5879
- inputs.aliases,
5880
6408
  )
5881
- const payload = { branch, destination, head, evidence, identities }
6409
+ const identities = projectPresence(witness, inputs.landings, aliases)
6410
+ const evidence = presenceEvidence(witness, identities)
6411
+ const payload = { branch, destination, head, evidence, identities, witness }
5882
6412
  await this.store.ensureRepo(this.deps.repo)
5883
6413
  await this.store.appendRepo(this.deps.repo, {
5884
6414
  actor: DISPATCHER,
@@ -5887,6 +6417,7 @@ export class Dispatcher {
5887
6417
  })
5888
6418
  return payload
5889
6419
  })
6420
+ }
5890
6421
  observations.set(destination, observed)
5891
6422
  }
5892
6423
  return observed!