@defrex/autobuild 1.1.0 → 1.3.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 (157) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +249 -15
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +130 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +4 -1
  7. package/docs/architecture.md +224 -12
  8. package/docs/build-store.md +3 -41
  9. package/docs/builds.md +2 -0
  10. package/docs/cli.md +14 -0
  11. package/docs/configuration-overview.md +117 -0
  12. package/docs/configuration.md +266 -141
  13. package/docs/dispatcher-hosting.md +18 -33
  14. package/docs/intake.md +2 -0
  15. package/docs/integration-tree.md +16 -5
  16. package/docs/merge-policy.md +1 -3
  17. package/docs/operating.md +1 -2
  18. package/docs/operator-api.md +144 -53
  19. package/docs/operator-surfaces.md +32 -20
  20. package/docs/overview.md +1 -1
  21. package/docs/plugin-authoring.md +27 -1
  22. package/docs/remote-store-protocol.md +259 -91
  23. package/docs/remote-ticket-protocol.md +29 -49
  24. package/docs/restacking.md +45 -0
  25. package/docs/seams.md +8 -8
  26. package/docs/setup.md +34 -129
  27. package/docs/spec-standard.md +4 -2
  28. package/docs/ticket-dependencies.md +8 -0
  29. package/docs/ticket-sources.md +18 -0
  30. package/docs/troubleshooting.md +7 -11
  31. package/docs/upgrading.md +1 -1
  32. package/docs/workspaces.md +4 -4
  33. package/package.json +14 -5
  34. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  35. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  36. package/packages/core/src/accounts/local-credentials.ts +194 -0
  37. package/packages/core/src/accounts/local-inference.ts +106 -0
  38. package/packages/core/src/accounts/local-owner.ts +123 -0
  39. package/packages/core/src/accounts/sensitive.ts +2 -0
  40. package/packages/core/src/cli/accounts.ts +147 -0
  41. package/packages/core/src/cli/binary.ts +3 -1
  42. package/packages/core/src/cli/connect.ts +3 -3
  43. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  44. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  45. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  46. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  47. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  48. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  49. package/packages/core/src/cli/dispatch.ts +135 -27
  50. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  51. package/packages/core/src/cli/forge-clear.ts +30 -0
  52. package/packages/core/src/cli/help.ts +17 -0
  53. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  54. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  55. package/packages/core/src/cli/init-validation.ts +160 -18
  56. package/packages/core/src/cli/main.ts +72 -0
  57. package/packages/core/src/cli/publication-settlement.ts +4 -1
  58. package/packages/core/src/cli/secrets.ts +173 -0
  59. package/packages/core/src/cli/store-opening.ts +11 -1
  60. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  61. package/packages/core/src/cli/watch.ts +12 -14
  62. package/packages/core/src/config/accounts.ts +101 -0
  63. package/packages/core/src/config/live.ts +14 -1
  64. package/packages/core/src/config/roles.ts +54 -3
  65. package/packages/core/src/config/schema.ts +60 -0
  66. package/packages/core/src/events/catalog.ts +1 -0
  67. package/packages/core/src/events/compatibility.ts +2 -1
  68. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  69. package/packages/core/src/events/payloads.ts +13 -0
  70. package/packages/core/src/events/policy.ts +9 -0
  71. package/packages/core/src/events/repository.ts +75 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +278 -0
  73. package/packages/core/src/kernel/change-presence.ts +74 -8
  74. package/packages/core/src/kernel/engine.ts +8 -0
  75. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  76. package/packages/core/src/kernel/node-polling.ts +40 -7
  77. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  78. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  79. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  80. package/packages/core/src/kernel/read-facts.ts +6 -0
  81. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  82. package/packages/core/src/kernel/reducer.ts +4 -1
  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 +4 -0
  87. package/packages/core/src/operator/protocol.ts +6 -0
  88. package/packages/core/src/operator/registry.ts +42 -1
  89. package/packages/core/src/operator/tickets.ts +25 -4
  90. package/packages/core/src/plugins/manifest.ts +2 -1
  91. package/packages/core/src/ports/runner/account-env.ts +139 -0
  92. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  93. package/packages/core/src/ports/runner/claude.ts +70 -42
  94. package/packages/core/src/ports/runner/codex.ts +63 -31
  95. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  96. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  97. package/packages/core/src/ports/runner/routing.ts +35 -4
  98. package/packages/core/src/ports/tickets/contract.ts +58 -0
  99. package/packages/core/src/ports/tickets/tree.ts +1 -1
  100. package/packages/core/src/ports/types.ts +28 -7
  101. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  102. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  103. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  104. package/packages/core/src/ports/workspace/create.ts +2 -0
  105. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  106. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  107. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  108. package/packages/core/src/processes/build-runner.ts +32 -1
  109. package/packages/core/src/processes/dispatcher.ts +493 -121
  110. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  111. package/packages/core/src/processes/execution-settlement.ts +21 -3
  112. package/packages/core/src/processes/harvest-runner.ts +68 -8
  113. package/packages/core/src/processes/harvest.ts +11 -16
  114. package/packages/core/src/processes/repo-view.ts +3 -0
  115. package/packages/core/src/project-secrets.ts +105 -0
  116. package/packages/core/src/secret-name.ts +41 -0
  117. package/packages/core/src/store/account-redaction.ts +156 -0
  118. package/packages/core/src/store/artifact-meta.ts +7 -0
  119. package/packages/core/src/store/contract.ts +60 -1
  120. package/packages/core/src/store/memory.ts +4 -0
  121. package/packages/core/src/store/reducer-value-shapes.json +7389 -6647
  122. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  123. package/packages/core/src/store/remote/client.ts +85 -50
  124. package/packages/core/src/store/remote/compatibility.ts +57 -0
  125. package/packages/core/src/store/remote/index.ts +6 -0
  126. package/packages/core/src/store/remote/protocol.ts +8 -1
  127. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  128. package/packages/core/src/store/remote/version.ts +4 -0
  129. package/packages/core/src/store/repo-state-events.ts +4 -2
  130. package/packages/core/src/store/snapshots.ts +16 -3
  131. package/packages/core/src/store/types.ts +2 -0
  132. package/packages/core/src/testing/dispatch-read-budget.ts +266 -5
  133. package/packages/core/src/testing/index.ts +2 -1
  134. package/packages/core/src/testing/reduced-read-budget.ts +560 -5
  135. package/skills/guide/SKILL.md +164 -37
  136. package/skills/guide/references/accounts.md +130 -0
  137. package/skills/guide/references/integration-tree.md +16 -5
  138. package/skills/guide/references/merge-policy.md +1 -3
  139. package/skills/guide/references/operator-api.md +144 -53
  140. package/skills/guide/references/plugin-authoring.md +27 -1
  141. package/skills/guide/references/remote-store-protocol.md +259 -91
  142. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  143. package/skills/guide/references/restacking.md +45 -0
  144. package/skills/guide/references/setup.md +34 -129
  145. package/skills/guide/references/spec-standard.md +4 -2
  146. package/skills/guide/references/ticket-dependencies.md +8 -0
  147. package/skills/harvest/SKILL.md +3 -1
  148. package/skills/harvest-review/SKILL.md +3 -1
  149. package/skills/operate/SKILL.md +26 -11
  150. package/skills/reconcile/SKILL.md +6 -0
  151. package/skills/spec/SKILL.md +1 -1
  152. package/skills/tickets/SKILL.md +10 -5
  153. package/templates/hosted-service/package.json +2 -2
  154. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  155. package/docs/hosted-dispatcher.md +0 -278
  156. package/docs/hosted-service.md +0 -304
  157. package/docs/mcp.md +0 -150
@@ -1,3 +1,5 @@
1
+ import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
2
+ import type { TicketPreparation } from '../kernel/ticket-preparation'
1
3
  import { sampleTargetDistance } from '../kernel/target-distance'
2
4
  import { capturedBuildConfig } from './verify-cycle-config'
3
5
  import { publicationRetryGate } from '../kernel/publication-retry'
@@ -8,6 +10,8 @@ import {
8
10
  import {
9
11
  nodeActivityKey,
10
12
  nodePollingSchedule,
13
+ nodePollingCheckpointRequired,
14
+ nodePollingEvidenceValid,
11
15
  nodePollingUnsettled,
12
16
  nodeTicketObservationKey,
13
17
  } from '../kernel/node-polling'
@@ -17,7 +21,13 @@ import {
17
21
  migrationIdentity,
18
22
  historicalTicketIdentity,
19
23
  } from '../kernel/ticket-migrations'
20
- import { nodeRestackDemand, presenceRestackPath } from '../kernel/node-restack-demand'
24
+ import { suspendNativeLanding } from '../kernel/landing-publication'
25
+ import {
26
+ actionableRestackDemand,
27
+ restackAvailabilityFingerprint,
28
+ restackLandingKey,
29
+ presenceRestackPath,
30
+ } from '../kernel/node-restack-demand'
21
31
  import {
22
32
  deferMixedVersion,
23
33
  mixedVersionDeferred,
@@ -59,7 +69,11 @@ import {
59
69
  blockerBuild,
60
70
  missingChanges,
61
71
  presenceInputs,
62
- observePresence,
72
+ confirmedLandings,
73
+ presenceWitness,
74
+ projectPresence,
75
+ presenceEvidence,
76
+ destinationAliases,
63
77
  ownedContribution,
64
78
  type ChangeIdentity,
65
79
  type PresenceInputs,
@@ -371,9 +385,9 @@ export interface TickReport {
371
385
  abandoned: number
372
386
  /** Janitor: queued builds explicitly discarded and returned to Ready. */
373
387
  discarded: number
374
- /** Janitor failures contained to individual builds during this pass. */
388
+ /** Contained build janitor and ticket-preparation recovery failures this pass. */
375
389
  janitorFailed: number
376
- /** One actionable line per contained janitor failure, attributed by slug. */
390
+ /** One actionable line per contained failure, attributed by build or attempt. */
377
391
  janitorDiagnostics: string[]
378
392
  /** Ordinary-tick recovery completed an interrupted post-creation dispatch. */
379
393
  recovered: number
@@ -551,6 +565,8 @@ export interface TickOpts {
551
565
  * resume, lease sweep, and in-flight runners continue. Absent defaults true.
552
566
  */
553
567
  acceptNewWork?: boolean
568
+ /** Repair/settle active execution policies only; suppress all intake and launches. */
569
+ observationOnly?: boolean
554
570
  /**
555
571
  * Repository-derived claim-time default supplied by the CLI for this tick.
556
572
  * True records the existing durable auto-merge request only on builds
@@ -685,6 +701,8 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
685
701
  return paused && state.status === 'queued'
686
702
  }
687
703
 
704
+ export const SWEEP_PIN_CACHE_CAPACITY = 128
705
+
688
706
  export class Dispatcher {
689
707
  // Only scheduling is cached. Eligibility facts still come from durable state,
690
708
  // and each admitted verification/publication samples the source this pass.
@@ -777,28 +795,72 @@ export class Dispatcher {
777
795
  })
778
796
  }
779
797
 
798
+ // Disposable parsed pins only. Current facts, live policy and cycle captures
799
+ // are recomputed on every decision; action boundaries never use this cache.
800
+ private readonly sweepPins = new Map<string, { revision: number; config: Config }>()
801
+
780
802
  /** Read at each decision boundary: artifact revisions are independent of events. */
781
803
  private async decideBuild(
782
804
  slug: string,
783
805
  state: Parameters<typeof decideNextFromFacts>[0],
784
806
  log: Parameters<typeof decideNextFromFacts>[1],
785
807
  report: TickReport,
808
+ sweep = false,
786
809
  ): Promise<ReturnType<typeof decideNextFromFacts> | undefined> {
787
810
  let revision: number | undefined
788
811
  try {
789
- let artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
790
- if (artifact === null) return decideNextFromFacts(state, log, this.deps.config)
791
- revision = artifact.meta.revision
792
- let pinned: Config
793
- try {
794
- pinned = parseEffectiveBuildConfig(artifact)
795
- } catch (error) {
796
- if (this.deps.repairBuildConfig === undefined) throw error
797
- await this.deps.repairBuildConfig(slug)
798
- artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
799
- if (artifact === null) throw new Error('configuration repair deposited no pipeline')
812
+ let pinned: Config | undefined
813
+ let cacheable = false
814
+ if (sweep && this.store.getLatestArtifactMeta) {
815
+ try {
816
+ const meta = await this.store.getLatestArtifactMeta(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
817
+ if (meta === null) {
818
+ this.sweepPins.delete(slug)
819
+ return decideNextFromFacts(state, log, this.deps.config)
820
+ }
821
+ revision = meta.revision
822
+ cacheable = true
823
+ const cached = this.sweepPins.get(slug)
824
+ if (cached?.revision === revision) {
825
+ pinned = cached.config
826
+ // Map insertion order is the deterministic LRU order.
827
+ this.sweepPins.delete(slug)
828
+ this.sweepPins.set(slug, cached)
829
+ } else {
830
+ this.sweepPins.delete(slug)
831
+ }
832
+ } catch (error) {
833
+ if (!(error instanceof ArtifactMetaUnsupportedError)) throw error
834
+ this.sweepPins.delete(slug)
835
+ }
836
+ }
837
+ if (pinned === undefined) {
838
+ let artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
839
+ if (artifact === null) {
840
+ this.sweepPins.delete(slug)
841
+ return decideNextFromFacts(state, log, this.deps.config)
842
+ }
800
843
  revision = artifact.meta.revision
801
- pinned = parseEffectiveBuildConfig(artifact)
844
+ try {
845
+ pinned = parseEffectiveBuildConfig(artifact)
846
+ } catch (error) {
847
+ this.sweepPins.delete(slug)
848
+ if (this.deps.repairBuildConfig === undefined) throw error
849
+ await this.deps.repairBuildConfig(slug)
850
+ artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
851
+ if (artifact === null) throw new Error('configuration repair deposited no pipeline')
852
+ revision = artifact.meta.revision
853
+ pinned = parseEffectiveBuildConfig(artifact)
854
+ }
855
+ if (cacheable) {
856
+ // A concurrent deposit may have advanced the revision after the probe:
857
+ // label the bytes with the full response's revision, never the probe's.
858
+ this.sweepPins.delete(slug)
859
+ this.sweepPins.set(slug, { revision, config: pinned })
860
+ if (this.sweepPins.size > SWEEP_PIN_CACHE_CAPACITY) {
861
+ this.sweepPins.delete(this.sweepPins.keys().next().value!)
862
+ }
863
+ }
802
864
  }
803
865
  return decideNextFromFacts(
804
866
  state,
@@ -811,6 +873,7 @@ export class Dispatcher {
811
873
  ),
812
874
  )
813
875
  } catch (error) {
876
+ this.sweepPins.delete(slug)
814
877
  report.blockedDiagnostics.push(
815
878
  `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)}`,
816
879
  )
@@ -853,6 +916,12 @@ export class Dispatcher {
853
916
  * slug here defers to the continuation; it never blocks on it. */
854
917
  private readonly continuations = new Map<string, ProvisionContinuation>()
855
918
 
919
+ // Batched confirmed landing evidence is shared across nodes for this tick.
920
+ // Only durable availability facts authorize the shortcut after restart.
921
+ private availabilityLandings?: ReturnType<typeof confirmedLandings>
922
+ private availabilityLandingKey?: string
923
+ private availabilityEntries?: ReturnType<Dispatcher['repoBuildDigests']>
924
+
856
925
  /** The incremental repository view every stage reads and writes through
857
926
  * (AUT-647): `deps.store` itself when the caller already wrapped it. */
858
927
  private readonly store: RepoViewStore
@@ -907,6 +976,9 @@ export class Dispatcher {
907
976
 
908
977
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
909
978
  async tick(opts: TickOpts = {}): Promise<TickReport> {
979
+ this.availabilityEntries = undefined
980
+ this.availabilityLandings = undefined
981
+ this.availabilityLandingKey = undefined
910
982
  const builds = new Map<string, number>()
911
983
  let total = 0
912
984
  let unattributed = 0
@@ -980,6 +1052,7 @@ export class Dispatcher {
980
1052
  await this.settleHarvestExecutions(opts)
981
1053
  if (this.outOfBudget(opts)) return report
982
1054
  await this.settleOrchestratorSandboxes(report, opts)
1055
+ if (opts.observationOnly) return report
983
1056
  if (this.outOfBudget(opts)) return report
984
1057
  // The default fan-out runs before the janitor so one tick both records the
985
1058
  // consent and lets the janitor act on it (the janitor reduces a fresh read
@@ -987,6 +1060,8 @@ export class Dispatcher {
987
1060
  // durable fact drives it, so a second dispatcher polling the same
988
1061
  // repository converges the same state.
989
1062
  if (this.outOfBudget(opts)) return report
1063
+ await this.recoverTicketPreparations(report, opts)
1064
+ if (this.outOfBudget(opts)) return report
990
1065
  await this.janitor(report, launched, opts)
991
1066
  if (this.outOfBudget(opts)) return report
992
1067
  await this.recoverDispatches(report, launched, paused, opts)
@@ -1209,7 +1284,17 @@ export class Dispatcher {
1209
1284
  }
1210
1285
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
1211
1286
  report.queued = listing.tickets.filter(
1212
- (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
1287
+ (ticket) =>
1288
+ !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
1289
+ !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
1290
+ const ref = resolveTicketRef(
1291
+ this.store.repositoryFacts().ticketMigrations,
1292
+ attempt.ticket,
1293
+ this.deps.tickets.name,
1294
+ attempt.slug ?? attempt.attempt,
1295
+ )
1296
+ return ref.source === ticket.ref.source && ref.id === ticket.ref.id
1297
+ }),
1213
1298
  ).length
1214
1299
  report.invalidTickets = listing.diagnostics.length
1215
1300
  report.ticketDiagnostics = [...listing.diagnostics]
@@ -1387,6 +1472,7 @@ export class Dispatcher {
1387
1472
  {
1388
1473
  store: this.store,
1389
1474
  execution,
1475
+ ids: this.deps.ids,
1390
1476
  ...(this.settlePublication !== undefined
1391
1477
  ? { settlePublication: this.settlePublication }
1392
1478
  : {}),
@@ -1437,6 +1523,25 @@ export class Dispatcher {
1437
1523
  ...(execution.sessionId !== undefined ? { sessionId: execution.sessionId } : {}),
1438
1524
  commandId: execution.commandId,
1439
1525
  })
1526
+ if (observation.attention) {
1527
+ const current = this.store.repositoryFacts()
1528
+ const authorization = current.harvestAuthorizations[JSON.stringify(execution.execution)]
1529
+ const run = current.harvest.runs.find((run) => run.run === authorization?.payload.run)
1530
+ // A model session has a durable run authorization. Escalation is
1531
+ // terminal and deduplicates across ticks and dispatcher restarts;
1532
+ // the execution itself remains observable until its command exits.
1533
+ if (run?.status === 'running')
1534
+ await this.store.appendRepo(this.deps.repo, {
1535
+ actor: KERNEL,
1536
+ type: 'harvest.escalated',
1537
+ payload: {
1538
+ run: run.run,
1539
+ source: 'policy',
1540
+ reason: observation.attention,
1541
+ observations: run.observations,
1542
+ },
1543
+ })
1544
+ }
1440
1545
  // Conservatism: an unresolvable observation (provider error) throws
1441
1546
  // and is contained below — it never reaps.
1442
1547
  if (observation.state === 'running') continue
@@ -2019,21 +2124,24 @@ export class Dispatcher {
2019
2124
  )
2020
2125
  return
2021
2126
  const now = this.deps.clock().toISOString()
2022
- const previousCheck = pollStart.nodePolling
2127
+ const previousCheck = current.nodePolling
2128
+ if (
2129
+ !nodePollingCheckpointRequired(current, key, this.deps.config.policy, new Date(now))
2130
+ )
2131
+ return
2023
2132
  await this.store.appendIfCurrent(record.slug, current.lastSeq, {
2024
2133
  actor: DISPATCHER,
2025
2134
  type: 'node.poll-checked',
2026
2135
  payload: {
2027
2136
  activityKey: key,
2028
- unchangedSince:
2029
- previousCheck?.activityKey === key &&
2030
- previousCheck.nodeIdleAfterSeconds ===
2031
- this.deps.config.policy.nodeIdleAfterSeconds &&
2032
- previousCheck.nodeIdlePollSeconds ===
2033
- this.deps.config.policy.nodeIdlePollSeconds &&
2034
- Date.parse(previousCheck.unchangedSince) <= Date.parse(now)
2035
- ? previousCheck.unchangedSince
2036
- : now,
2137
+ unchangedSince: nodePollingEvidenceValid(
2138
+ current,
2139
+ key,
2140
+ this.deps.config.policy,
2141
+ new Date(now),
2142
+ )
2143
+ ? previousCheck!.unchangedSince
2144
+ : now,
2037
2145
  nodeIdleAfterSeconds: this.deps.config.policy.nodeIdleAfterSeconds,
2038
2146
  nodeIdlePollSeconds: this.deps.config.policy.nodeIdlePollSeconds,
2039
2147
  },
@@ -4508,7 +4616,7 @@ export class Dispatcher {
4508
4616
  throw error
4509
4617
  }
4510
4618
  }
4511
- const decision = await this.decideBuild(record.slug, state, facts.log, report)
4619
+ const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4512
4620
  if (decision === undefined) continue
4513
4621
  if (state.status === 'done' || state.status === 'aborted') continue
4514
4622
  if (
@@ -4535,7 +4643,17 @@ export class Dispatcher {
4535
4643
  // place: the guest finished its work, the workspace is still the
4536
4644
  // build's, and replacing the environment would discard a healthy
4537
4645
  // generation. Only an unproven stale lease or a proved loss reaps.
4538
- let endedInPlace = facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch'
4646
+ // A start that later found the open workspace missing is a proved loss
4647
+ // too: the recorded end no longer vouches for an environment that is
4648
+ // gone, and re-attaching would fail against the same ref forever.
4649
+ const failure = state.infrastructureFailure
4650
+ const workspaceMissing =
4651
+ failure?.cause === 'missing' &&
4652
+ failure.operation === 'start' &&
4653
+ failure.workspaceRef === facts.workspace?.ref
4654
+ let endedInPlace =
4655
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4656
+ !workspaceMissing
4539
4657
  if (
4540
4658
  foreignExecution !== null &&
4541
4659
  foreignExecution.commandId !== undefined &&
@@ -4621,6 +4739,145 @@ export class Dispatcher {
4621
4739
  }
4622
4740
  }
4623
4741
 
4742
+ /** Retry a fixed batch under the same repository ownership as intake.
4743
+ * No provider calls for parked deadlines; no history or orphan scans. */
4744
+ private async recoverTicketPreparations(report: TickReport, opts: TickOpts): Promise<void> {
4745
+ const pending = Object.values(this.store.repositoryFacts().preparation)
4746
+ .filter(
4747
+ (attempt) => !attempt.retryAt || Date.parse(attempt.retryAt) <= this.deps.clock().getTime(),
4748
+ )
4749
+ .sort(
4750
+ (a, b) =>
4751
+ Date.parse(a.retryAt ?? '1970-01-01T00:00:00.000Z') -
4752
+ Date.parse(b.retryAt ?? '1970-01-01T00:00:00.000Z') ||
4753
+ a.attempt.localeCompare(b.attempt),
4754
+ )
4755
+ .slice(0, 8)
4756
+ const failures: unknown[] = []
4757
+ for (const attempt of pending) {
4758
+ if (this.outOfBudget(opts)) break
4759
+ try {
4760
+ await this.recoverTicketPreparation(attempt)
4761
+ } catch (error) {
4762
+ failures.push(error)
4763
+ }
4764
+ }
4765
+ for (const error of failures) {
4766
+ report.janitorFailed += 1
4767
+ report.janitorDiagnostics.push(String(error))
4768
+ }
4769
+ }
4770
+
4771
+ private async preparationResolved(
4772
+ attempt: TicketPreparation,
4773
+ outcome: 'lost-claim' | 'handed-back' | 'bounced' | 'owned' | 'abandoned',
4774
+ reason?: string,
4775
+ ): Promise<void> {
4776
+ await this.store.appendRepo(this.deps.repo, {
4777
+ actor: DISPATCHER,
4778
+ type: 'ticket-preparation.resolved',
4779
+ payload: {
4780
+ attempt: attempt.attempt,
4781
+ ticket: attempt.ticket,
4782
+ outcome,
4783
+ ...(reason ? { reason: reason.slice(0, 4000) } : {}),
4784
+ },
4785
+ })
4786
+ }
4787
+
4788
+ private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
4789
+ try {
4790
+ // A rejected create can have committed. Unavailable or conflicting readback
4791
+ // is never absence and must not authorize a ticket transition.
4792
+ if (attempt.slug) {
4793
+ const record = await this.store.getBuild(attempt.slug)
4794
+ if (record) {
4795
+ const created = (await this.store.buildFacts(attempt.slug)).created
4796
+ if (
4797
+ record.repo !== this.deps.repo ||
4798
+ record.ticket?.source !== attempt.ticket.source ||
4799
+ record.ticket?.id !== attempt.ticket.id ||
4800
+ created?.payload.repo !== this.deps.repo ||
4801
+ created.payload.ticket?.source !== attempt.ticket.source ||
4802
+ created.payload.ticket?.id !== attempt.ticket.id
4803
+ )
4804
+ return await this.preparationResolved(
4805
+ attempt,
4806
+ 'abandoned',
4807
+ `Conflicting build ownership at ${attempt.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
4808
+ )
4809
+ await this.preparationResolved(attempt, 'owned')
4810
+ return
4811
+ }
4812
+ }
4813
+ const ref = resolveTicketRef(
4814
+ this.store.repositoryFacts().ticketMigrations,
4815
+ attempt.ticket,
4816
+ this.deps.tickets.name,
4817
+ attempt.slug ?? attempt.attempt,
4818
+ )
4819
+ const ticket = await this.deps.tickets.get(ref.id)
4820
+ if (!ticket)
4821
+ return await this.preparationResolved(
4822
+ attempt,
4823
+ 'abandoned',
4824
+ 'Ticket no longer exists; ticket unchanged.',
4825
+ )
4826
+ if (ticket.state === undefined)
4827
+ return await this.preparationResolved(
4828
+ attempt,
4829
+ 'abandoned',
4830
+ 'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
4831
+ )
4832
+ const state = (value: string) => value.toLowerCase()
4833
+ const handback = attempt.handback ?? attempt.readyState
4834
+ if (state(ticket.state) === state(handback)) {
4835
+ await this.preparationResolved(
4836
+ attempt,
4837
+ handback === attempt.readyState ? 'handed-back' : 'bounced',
4838
+ )
4839
+ return
4840
+ }
4841
+ if (!attempt.claimed || state(ticket.state) !== state(attempt.claimedState))
4842
+ return await this.preparationResolved(
4843
+ attempt,
4844
+ 'abandoned',
4845
+ `Uncertain claim or externally changed ticket state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
4846
+ )
4847
+ await this.deps.tickets.transition(ref.id, handback)
4848
+ await this.preparationResolved(
4849
+ attempt,
4850
+ handback === attempt.readyState ? 'handed-back' : 'bounced',
4851
+ )
4852
+ } catch (error) {
4853
+ const message = error instanceof Error ? error.message : String(error)
4854
+ try {
4855
+ await this.store.appendRepo(this.deps.repo, {
4856
+ actor: DISPATCHER,
4857
+ type: 'ticket-preparation.recovery-failed',
4858
+ payload: {
4859
+ attempt: attempt.attempt,
4860
+ ticket: attempt.ticket,
4861
+ claimed: attempt.claimed,
4862
+ handback: attempt.handback ?? attempt.readyState,
4863
+ ...(attempt.error ? { preparationError: attempt.error } : {}),
4864
+ error: message.slice(0, 4000) || 'unknown recovery failure',
4865
+ retryAt: new Date(this.deps.clock().getTime() + 30_000).toISOString(),
4866
+ },
4867
+ })
4868
+ } catch (diagnosticError) {
4869
+ throw new AggregateError(
4870
+ [error, diagnosticError],
4871
+ `ticket preparation recovery failed: ${message}; diagnostic append failed: ${String(diagnosticError)}`,
4872
+ )
4873
+ }
4874
+ throw new Error(
4875
+ `ticket preparation recovery failed: ${message}; original preparation failure: ${attempt.error ?? 'unfinished durable preparation'}`,
4876
+ { cause: error },
4877
+ )
4878
+ }
4879
+ }
4880
+
4624
4881
  // ── e. Dispatch (SPEC §12, §6.3) ───────────────────────────────────────────
4625
4882
 
4626
4883
  private async dispatch(
@@ -4673,7 +4930,17 @@ export class Dispatcher {
4673
4930
  ]),
4674
4931
  )
4675
4932
  const ready = listing.tickets.filter(
4676
- (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
4933
+ (ticket) =>
4934
+ !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
4935
+ !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
4936
+ const ref = resolveTicketRef(
4937
+ this.store.repositoryFacts().ticketMigrations,
4938
+ attempt.ticket,
4939
+ this.deps.tickets.name,
4940
+ attempt.slug ?? attempt.attempt,
4941
+ )
4942
+ return ref.source === ticket.ref.source && ref.id === ticket.ref.id
4943
+ }),
4677
4944
  )
4678
4945
  report.invalidTickets += listing.diagnostics.length
4679
4946
  report.ticketDiagnostics.push(...listing.diagnostics)
@@ -4903,70 +5170,156 @@ export class Dispatcher {
4903
5170
  continue
4904
5171
  }
4905
5172
  }
4906
- // Claim-before-launch (§12): losing the claim means another dispatcher
4907
- // (or an earlier tick) owns this ticket.
4908
- if (!(await tickets.claim(ticket.ref.id))) {
4909
- report.claimRaces += 1
4910
- report.queued -= 1
4911
- continue
5173
+ const attempt: TicketPreparation = {
5174
+ attempt: this.deps.ids('prep'),
5175
+ ticket: ticket.ref,
5176
+ readyState: config.tickets.readyState,
5177
+ claimedState: ticketLifecycle(config.tickets).doing,
5178
+ claimed: false,
4912
5179
  }
4913
-
4914
- // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
4915
- // spec-authoring interval so edits made during it are never pinned.
4916
- const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
4917
-
4918
- // Quality gate (§6.3): import a conforming ticket body as the spec;
4919
- // author one for thin-but-groomed tickets; otherwise bounce.
5180
+ await store.ensureRepo(this.deps.repo)
5181
+ await store.appendRepo(this.deps.repo, {
5182
+ actor: DISPATCHER,
5183
+ type: 'ticket-preparation.intended',
5184
+ payload: {
5185
+ attempt: attempt.attempt,
5186
+ ticket: attempt.ticket,
5187
+ readyState: attempt.readyState,
5188
+ claimedState: attempt.claimedState,
5189
+ },
5190
+ })
5191
+ let stage = 'claim'
5192
+ let established = false
5193
+ let record: BuildRecord
4920
5194
  let body = ticket.body
4921
- let conformance = specConformance(body)
4922
5195
  let authoredSession: string | undefined
4923
- if (!conformance.conforms && this.deps.authorSpec) {
4924
- const authored = await this.deps.authorSpec(ticket)
4925
- if (authored !== null) {
4926
- conformance = specConformance(authored)
4927
- if (conformance.conforms) {
4928
- body = authored
4929
- authoredSession = this.deps.ids('s')
5196
+ let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
5197
+ try {
5198
+ if (!(await tickets.claim(ticket.ref.id))) {
5199
+ await this.preparationResolved(attempt, 'lost-claim')
5200
+ report.claimRaces += 1
5201
+ report.queued -= 1
5202
+ continue
5203
+ }
5204
+ attempt.claimed = true
5205
+ stage = 'claim-confirmation'
5206
+ await store.appendRepo(this.deps.repo, {
5207
+ actor: DISPATCHER,
5208
+ type: 'ticket-preparation.claimed',
5209
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket },
5210
+ })
5211
+ stage = 'assets'
5212
+ // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
5213
+ // spec-authoring interval so edits made during it are never pinned.
5214
+ const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
5215
+
5216
+ // Quality gate (§6.3): import a conforming ticket body as the spec;
5217
+ // author one for thin-but-groomed tickets; otherwise bounce.
5218
+ stage = 'spec'
5219
+ let conformance = specConformance(body)
5220
+ if (!conformance.conforms && this.deps.authorSpec) {
5221
+ const authored = await this.deps.authorSpec(ticket)
5222
+ if (authored !== null) {
5223
+ conformance = specConformance(authored)
5224
+ if (conformance.conforms) {
5225
+ body = authored
5226
+ authoredSession = this.deps.ids('s')
5227
+ }
4930
5228
  }
4931
5229
  }
4932
- }
4933
- if (!conformance.conforms) {
4934
- await this.bounce(ticket, conformance.missing)
4935
- report.bounced += 1
4936
- report.queued -= 1
4937
- continue
4938
- }
5230
+ if (!conformance.conforms) {
5231
+ attempt.handback = this.triageState()
5232
+ await store.appendRepo(this.deps.repo, {
5233
+ actor: DISPATCHER,
5234
+ type: 'ticket-preparation.handback-selected',
5235
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket, state: attempt.handback },
5236
+ })
5237
+ stage = 'bounce'
5238
+ await this.bounce(ticket, conformance.missing)
5239
+ await this.preparationResolved(attempt, 'bounced')
5240
+ report.bounced += 1
5241
+ report.queued -= 1
5242
+ continue
5243
+ }
4939
5244
 
4940
- const baseSlug = await this.chooseSlugBase(ticket.title, body)
4941
- const slug = await this.uniqueSlug(baseSlug)
4942
- const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
4943
- const repoOrigin = await this.resolveRepoOriginOnce()
4944
- const createdSeed = {
4945
- ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
4946
- ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
4947
- ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
4948
- // Claim-time provenance: the newest durable default fact that agrees
4949
- // with the launch sample, recorded on `build.created` so the fan-out's
4950
- // seq comparison sees the claim as already answering that fact — and
4951
- // so a newer opposite fact (an interleaved toggle) stays strictly
4952
- // ahead of it and reconciles this build on the next tick (f_b851c0e8).
4953
- ...(autoMergeSeedFact !== undefined ? { autoMergeDefaultSeq: autoMergeSeedFact.seq } : {}),
4954
- assets,
4955
- }
4956
- // `build.created` rides with the record so the pinned assets and the
4957
- // record exist together or not at all.
4958
- const record = await store.createBuild({
4959
- slug,
4960
- repo: this.deps.repo,
4961
- ticket: ticket.ref,
4962
- branch,
4963
- ...(repoOrigin !== undefined ? { repoOrigin } : {}),
4964
- created: {
5245
+ stage = 'naming'
5246
+ const baseSlug = await this.chooseSlugBase(ticket.title, body)
5247
+ const slug = await this.uniqueSlug(baseSlug)
5248
+ const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
5249
+ const repoOrigin = await this.resolveRepoOriginOnce()
5250
+ createdSeed = {
5251
+ ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
5252
+ ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
5253
+ ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
5254
+ // Claim-time provenance: the newest durable default fact that agrees
5255
+ // with the launch sample, recorded on `build.created` so the fan-out's
5256
+ // seq comparison sees the claim as already answering that fact — and
5257
+ // so a newer opposite fact (an interleaved toggle) stays strictly
5258
+ // ahead of it and reconciles this build on the next tick (f_b851c0e8).
5259
+ ...(autoMergeSeedFact !== undefined
5260
+ ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
5261
+ : {}),
5262
+ assets,
5263
+ }
5264
+ // `build.created` rides with the record so the pinned assets and the
5265
+ // record exist together or not at all.
5266
+ stage = 'creation-identity'
5267
+ attempt.slug = slug
5268
+ await store.appendRepo(this.deps.repo, {
4965
5269
  actor: DISPATCHER,
4966
- type: 'build.created',
4967
- payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
4968
- },
4969
- })
5270
+ type: 'ticket-preparation.creation-selected',
5271
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket, slug },
5272
+ })
5273
+ stage = 'create-build'
5274
+ record = await store.createBuild({
5275
+ slug,
5276
+ repo: this.deps.repo,
5277
+ ticket: ticket.ref,
5278
+ branch,
5279
+ ...(repoOrigin !== undefined ? { repoOrigin } : {}),
5280
+ created: {
5281
+ actor: DISPATCHER,
5282
+ type: 'build.created',
5283
+ payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
5284
+ },
5285
+ })
5286
+ established = true
5287
+ await this.preparationResolved(attempt, 'owned')
5288
+ } catch (error) {
5289
+ // Settlement and completion errors after successful creation cannot
5290
+ // release the claim. A later tick settles the retained creation identity.
5291
+ if (established) throw error
5292
+ const errors: unknown[] = [error]
5293
+ attempt.error =
5294
+ (error instanceof Error ? error.message : String(error)).slice(0, 4000) ||
5295
+ 'unknown preparation failure'
5296
+ attempt.stage = stage
5297
+ try {
5298
+ await store.appendRepo(this.deps.repo, {
5299
+ actor: DISPATCHER,
5300
+ type: 'ticket-preparation.failed',
5301
+ payload: {
5302
+ attempt: attempt.attempt,
5303
+ ticket: attempt.ticket,
5304
+ stage,
5305
+ claimed: attempt.claimed,
5306
+ handback: attempt.handback ?? attempt.readyState,
5307
+ error: attempt.error,
5308
+ },
5309
+ })
5310
+ } catch (diagnosticError) {
5311
+ errors.push(diagnosticError)
5312
+ }
5313
+ try {
5314
+ await this.recoverTicketPreparation(attempt)
5315
+ } catch (recoveryError) {
5316
+ errors.push(recoveryError)
5317
+ }
5318
+ throw new AggregateError(
5319
+ errors,
5320
+ `ticket preparation failed (${stage}): ${errors.map(String).join('; ')}`,
5321
+ )
5322
+ }
4970
5323
  report.queued -= 1
4971
5324
  if (ticket.kind !== 'node') capacity -= 1
4972
5325
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
@@ -5178,12 +5531,35 @@ export class Dispatcher {
5178
5531
  forge.remoteBranchSha(state.baseBranch),
5179
5532
  forge.remoteBranchSha(record.branch),
5180
5533
  ])
5534
+ this.availabilityEntries ??= this.repoBuildDigests()
5535
+ const entries = await this.availabilityEntries
5536
+ this.availabilityLandings ??= confirmedLandings(entries)
5537
+ this.availabilityLandingKey ??= restackLandingKey(this.availabilityLandings)
5538
+ const evidence = await presenceInputs(
5539
+ this.store,
5540
+ entries,
5541
+ [record.slug],
5542
+ this.availabilityLandings,
5543
+ )
5544
+ const fingerprint =
5545
+ parent && head
5546
+ ? restackAvailabilityFingerprint(
5547
+ state,
5548
+ record.branch,
5549
+ state.baseBranch,
5550
+ head,
5551
+ parent,
5552
+ evidence,
5553
+ this.availabilityLandingKey,
5554
+ )
5555
+ : ''
5556
+ const actionable = actionableRestackDemand(state, fingerprint)
5181
5557
  if (
5182
- (parent === state.nodeRestack?.contributionBase || !nodeRestackDemand(state)) &&
5558
+ (parent === state.nodeRestack?.contributionBase || !actionable) &&
5183
5559
  state.nodeRestack?.distance?.parent === parent &&
5184
5560
  state.nodeRestack.distance.base === state.nodeRestack.contributionBase &&
5185
5561
  head === state.nodeRestack?.inventory?.head &&
5186
- !Object.keys(state.nodeRestack?.requests ?? {}).length
5562
+ (!Object.keys(state.nodeRestack?.requests ?? {}).length || !actionable)
5187
5563
  )
5188
5564
  return
5189
5565
  }
@@ -5257,15 +5633,7 @@ export class Dispatcher {
5257
5633
  )
5258
5634
  if (result.exitCode !== 0) throw new Error(result.stderr)
5259
5635
  added = true
5260
- const parentHead = forge.remoteBranchSha
5261
- ? await forge.remoteBranchSha(state.baseBranch!)
5262
- : undefined
5263
- if (
5264
- state.nodeRestack?.active ||
5265
- (nodeRestackDemand(state) && parentHead !== state.nodeRestack?.contributionBase)
5266
- ) {
5267
- // Upgrade recovery: an old dispatcher may have left a native request
5268
- // armed. Cancel every targeting leaf before admitting a node rewrite.
5636
+ const beforeReplay = async (operation: string) => {
5269
5637
  for (const child of await this.repoBuildDigests()) {
5270
5638
  if (child.digest.terminal || child.digest.kind === 'node') continue
5271
5639
  const childState = (await this.store.buildFacts(child.record.slug)).state
@@ -5275,11 +5643,10 @@ export class Dispatcher {
5275
5643
  childState.prState !== 'open'
5276
5644
  )
5277
5645
  continue
5278
- const cancelled = await forge.setAutoMerge(checkout, childState.pr.number, false)
5279
- if (cancelled.kind !== 'applied')
5280
- throw new Error(
5281
- `node restack waits for native auto-merge cancellation on ${child.record.slug}`,
5282
- )
5646
+ await suspendNativeLanding(
5647
+ { store: this.store, forge, slug: child.record.slug, workspacePath: checkout },
5648
+ `node:${record.slug}:${operation}`,
5649
+ )
5283
5650
  }
5284
5651
  }
5285
5652
  const outcome = await runNodeTransaction(
@@ -5290,6 +5657,7 @@ export class Dispatcher {
5290
5657
  exec: forge.kernelExec ?? this.deps.exec,
5291
5658
  workspacePath,
5292
5659
  holder,
5660
+ beforeReplay,
5293
5661
  canWrite: async () => {
5294
5662
  if (await deferMixedVersion(this.store, record.slug)) return false
5295
5663
  if (this.outOfBudget(opts)) return false
@@ -5795,22 +6163,25 @@ export class Dispatcher {
5795
6163
  let observed = observations.get(destination)
5796
6164
  if (!observed) {
5797
6165
  const forge = this.kernelForge()
5798
- if (!forge.remoteBranchSha || (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite))
5799
- throw new Error('forge cannot snapshot destination presence')
6166
+ if (!forge.remoteBranchSha) throw new Error('forge cannot read destination head')
5800
6167
  const head = await forge.remoteBranchSha(branch)
5801
- const evidence = JSON.stringify({
5802
- version: 2,
5803
- revisions: [
5804
- ...inputs.entries
5805
- .filter(({ digest }) => digest.mergedSha || digest.nodeContribution)
5806
- .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq]),
5807
- ...[...inputs.states].map(([slug, state]) => [slug, state.lastSeq]),
5808
- ].sort(),
5809
- })
6168
+ const aliases = destinationAliases(inputs, target?.target.build)
5810
6169
  const cached = this.store.repositoryFacts().presence[destination]
5811
- if (cached?.head === head && cached.branch === branch && cached.evidence === evidence)
5812
- observed = cached
5813
- else
6170
+ if (cached?.head === head && cached.branch === branch && cached.witness?.version === 1) {
6171
+ const identities = projectPresence(cached.witness, inputs.landings, aliases)
6172
+ const evidence = presenceEvidence(cached.witness, identities)
6173
+ observed = { ...cached, identities }
6174
+ if (cached.evidence !== evidence) {
6175
+ await this.store.ensureRepo(this.deps.repo)
6176
+ await this.store.appendRepo(this.deps.repo, {
6177
+ actor: DISPATCHER,
6178
+ type: 'change-presence.observed',
6179
+ payload: { ...cached, identities, evidence },
6180
+ })
6181
+ }
6182
+ } else {
6183
+ if (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite)
6184
+ throw new Error('forge cannot snapshot destination presence')
5814
6185
  observed = await this.withKernelRepository(async (path) => {
5815
6186
  const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
5816
6187
  let sampled: string
@@ -5849,13 +6220,13 @@ export class Dispatcher {
5849
6220
  sampled = resolved.stdout.trim()
5850
6221
  }
5851
6222
  if (sampled !== head) throw new Error('destination moved while sampling presence')
5852
- const identities = await observePresence(
6223
+ const witness = await presenceWitness(
5853
6224
  { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
5854
6225
  head,
5855
- inputs.landings,
5856
- inputs.aliases,
5857
6226
  )
5858
- const payload = { branch, destination, head, evidence, identities }
6227
+ const identities = projectPresence(witness, inputs.landings, aliases)
6228
+ const evidence = presenceEvidence(witness, identities)
6229
+ const payload = { branch, destination, head, evidence, identities, witness }
5859
6230
  await this.store.ensureRepo(this.deps.repo)
5860
6231
  await this.store.appendRepo(this.deps.repo, {
5861
6232
  actor: DISPATCHER,
@@ -5864,6 +6235,7 @@ export class Dispatcher {
5864
6235
  })
5865
6236
  return payload
5866
6237
  })
6238
+ }
5867
6239
  observations.set(destination, observed)
5868
6240
  }
5869
6241
  return observed!