@defrex/autobuild 0.13.0 → 1.0.0-beta.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 (210) hide show
  1. package/README.md +5 -3
  2. package/SPEC.md +673 -99
  3. package/bin/ab-dispatch-kernel.ts +4 -6
  4. package/docs/architecture.md +322 -75
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +112 -12
  7. package/docs/hosted-service.md +20 -2
  8. package/docs/integration-tree.md +117 -0
  9. package/docs/landing-policy.md +150 -0
  10. package/docs/mcp.md +24 -0
  11. package/docs/migration-1.0.md +68 -0
  12. package/docs/operator-api.md +20 -9
  13. package/docs/remote-store-protocol.md +114 -9
  14. package/docs/remote-ticket-protocol.md +26 -5
  15. package/docs/restacking.md +79 -0
  16. package/docs/setup.md +49 -6
  17. package/docs/ticket-dependencies.md +69 -0
  18. package/docs/ticket-migration.md +8 -0
  19. package/package.json +4 -3
  20. package/packages/core/src/cli/attention.ts +40 -163
  21. package/packages/core/src/cli/build-control.ts +75 -55
  22. package/packages/core/src/cli/bulk-control.ts +3 -2
  23. package/packages/core/src/cli/context.ts +68 -78
  24. package/packages/core/src/cli/dashboard/actions.ts +6 -3
  25. package/packages/core/src/cli/dashboard/landing-display.ts +6 -0
  26. package/packages/core/src/cli/dashboard/live.ts +5 -0
  27. package/packages/core/src/cli/dashboard/model.ts +178 -40
  28. package/packages/core/src/cli/dashboard/poll.ts +15 -9
  29. package/packages/core/src/cli/dashboard/refresh.ts +176 -0
  30. package/packages/core/src/cli/dashboard/render.ts +78 -28
  31. package/packages/core/src/cli/dashboard/repository-poll.ts +57 -0
  32. package/packages/core/src/cli/dashboard/selection.ts +7 -1
  33. package/packages/core/src/cli/dashboard/tree.ts +107 -0
  34. package/packages/core/src/cli/dispatch-frontend.ts +173 -169
  35. package/packages/core/src/cli/dispatch-process.ts +14 -7
  36. package/packages/core/src/cli/dispatch-repository-feed.ts +196 -0
  37. package/packages/core/src/cli/dispatch.ts +397 -214
  38. package/packages/core/src/cli/dispatcher-liveness.ts +41 -21
  39. package/packages/core/src/cli/harvest.ts +71 -39
  40. package/packages/core/src/cli/help.ts +49 -32
  41. package/packages/core/src/cli/historical-build-state.ts +27 -0
  42. package/packages/core/src/cli/init-validation.ts +43 -2
  43. package/packages/core/src/cli/keyboard.ts +6 -0
  44. package/packages/core/src/cli/landings.ts +18 -0
  45. package/packages/core/src/cli/main.ts +52 -18
  46. package/packages/core/src/cli/mcp.ts +9 -0
  47. package/packages/core/src/cli/pr-attachments.ts +10 -13
  48. package/packages/core/src/cli/pr-summary-publication.ts +27 -60
  49. package/packages/core/src/cli/pr-summary.ts +43 -13
  50. package/packages/core/src/cli/publication-settlement.ts +177 -21
  51. package/packages/core/src/cli/repository-status.ts +49 -2
  52. package/packages/core/src/cli/status.ts +133 -36
  53. package/packages/core/src/cli/terminal-restore.ts +54 -0
  54. package/packages/core/src/cli/terminal.ts +16 -2
  55. package/packages/core/src/cli/terminals.ts +121 -219
  56. package/packages/core/src/cli/ticket-editor.ts +10 -3
  57. package/packages/core/src/cli/ticket.ts +115 -20
  58. package/packages/core/src/cli/upgrade-commit.ts +4 -0
  59. package/packages/core/src/cli/upgrade-compatibility.ts +2 -2
  60. package/packages/core/src/cli/upgrade-landing.ts +69 -0
  61. package/packages/core/src/cli/upgrade.ts +16 -0
  62. package/packages/core/src/cli/wait.ts +194 -91
  63. package/packages/core/src/cli/watch.ts +111 -109
  64. package/packages/core/src/config/landing.ts +22 -0
  65. package/packages/core/src/config/live.ts +1 -0
  66. package/packages/core/src/config/pipeline-source.ts +4 -3
  67. package/packages/core/src/config/schema.ts +3 -0
  68. package/packages/core/src/events/catalog.ts +48 -3
  69. package/packages/core/src/events/payloads.ts +295 -6
  70. package/packages/core/src/events/repository.ts +38 -3
  71. package/packages/core/src/integration/harness.ts +11 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-registry.test.ts.snap +3330 -119
  73. package/packages/core/src/kernel/auto-merge-default.ts +1 -0
  74. package/packages/core/src/kernel/auto-merge.ts +29 -4
  75. package/packages/core/src/kernel/build-identity.ts +94 -0
  76. package/packages/core/src/kernel/change-presence.ts +179 -0
  77. package/packages/core/src/kernel/dispatch-status.ts +17 -1
  78. package/packages/core/src/kernel/dispatcher-liveness.ts +10 -4
  79. package/packages/core/src/kernel/engine.ts +89 -2
  80. package/packages/core/src/kernel/generators/build-log.ts +23 -0
  81. package/packages/core/src/kernel/generators/leaf-restack-log.ts +110 -0
  82. package/packages/core/src/kernel/generators/node-restack-log.ts +94 -0
  83. package/packages/core/src/kernel/generators/repository-journals.ts +25 -3
  84. package/packages/core/src/kernel/harvest.ts +25 -23
  85. package/packages/core/src/kernel/integration-completeness.ts +81 -0
  86. package/packages/core/src/kernel/integration-landing.ts +263 -0
  87. package/packages/core/src/kernel/integration-stack.ts +36 -0
  88. package/packages/core/src/kernel/integration-state.ts +135 -0
  89. package/packages/core/src/kernel/landing-policy.ts +47 -0
  90. package/packages/core/src/kernel/landing-publication.ts +41 -0
  91. package/packages/core/src/kernel/landing-readiness.ts +67 -0
  92. package/packages/core/src/kernel/landing-state.ts +96 -0
  93. package/packages/core/src/kernel/leaf-restack-completion.ts +24 -0
  94. package/packages/core/src/kernel/leaf-restack-state.ts +73 -0
  95. package/packages/core/src/kernel/log-index-value.ts +38 -0
  96. package/packages/core/src/kernel/log-index.ts +35 -5
  97. package/packages/core/src/kernel/node-landing.ts +439 -0
  98. package/packages/core/src/kernel/node-parent.ts +184 -0
  99. package/packages/core/src/kernel/node-restack-state.ts +191 -0
  100. package/packages/core/src/kernel/node-restack-transaction.ts +210 -0
  101. package/packages/core/src/kernel/node-restack.ts +274 -0
  102. package/packages/core/src/kernel/read-facts.ts +704 -0
  103. package/packages/core/src/kernel/reconcile-head.ts +51 -0
  104. package/packages/core/src/kernel/reconcile-restack.ts +560 -0
  105. package/packages/core/src/kernel/reducer-registry.ts +153 -3
  106. package/packages/core/src/kernel/reducer.ts +121 -6
  107. package/packages/core/src/kernel/repository-attention.ts +179 -0
  108. package/packages/core/src/kernel/service-facts.ts +135 -0
  109. package/packages/core/src/kernel/snapshot-parent.ts +33 -0
  110. package/packages/core/src/kernel/terminal-guard.ts +133 -0
  111. package/packages/core/src/ontology.ts +9 -1
  112. package/packages/core/src/operator/annotations.ts +12 -0
  113. package/packages/core/src/operator/control.ts +11 -6
  114. package/packages/core/src/operator/index.ts +6 -0
  115. package/packages/core/src/operator/landings.ts +35 -0
  116. package/packages/core/src/operator/presentation.ts +1 -0
  117. package/packages/core/src/operator/protocol.ts +12 -3
  118. package/packages/core/src/operator/query.ts +40 -21
  119. package/packages/core/src/operator/read-view.ts +4 -13
  120. package/packages/core/src/operator/registry.ts +48 -19
  121. package/packages/core/src/operator/requests.ts +3 -22
  122. package/packages/core/src/operator/sandbox.ts +10 -9
  123. package/packages/core/src/operator/tickets.ts +57 -11
  124. package/packages/core/src/plugin-sdk/index.ts +13 -0
  125. package/packages/core/src/ports/forge/contract.ts +91 -3
  126. package/packages/core/src/ports/forge/fake.ts +142 -4
  127. package/packages/core/src/ports/forge/git-rewrite.ts +232 -0
  128. package/packages/core/src/ports/forge/github-readiness.ts +421 -0
  129. package/packages/core/src/ports/forge/github.ts +631 -35
  130. package/packages/core/src/ports/forge/local-git.ts +119 -5
  131. package/packages/core/src/ports/forge/readiness.ts +99 -0
  132. package/packages/core/src/ports/tickets/contract.ts +41 -0
  133. package/packages/core/src/ports/tickets/create.ts +8 -1
  134. package/packages/core/src/ports/tickets/fake.ts +32 -1
  135. package/packages/core/src/ports/tickets/file-codec.ts +7 -0
  136. package/packages/core/src/ports/tickets/file.ts +18 -1
  137. package/packages/core/src/ports/tickets/hosted-index.ts +2 -0
  138. package/packages/core/src/ports/tickets/linear.ts +124 -4
  139. package/packages/core/src/ports/tickets/migration.ts +25 -1
  140. package/packages/core/src/ports/tickets/operations.ts +7 -2
  141. package/packages/core/src/ports/tickets/remote-protocol.ts +19 -0
  142. package/packages/core/src/ports/tickets/remote.ts +10 -1
  143. package/packages/core/src/ports/tickets/revision.ts +3 -1
  144. package/packages/core/src/ports/tickets/tree.ts +148 -0
  145. package/packages/core/src/ports/tickets/update.ts +15 -2
  146. package/packages/core/src/ports/types.ts +135 -5
  147. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  148. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -1
  149. package/packages/core/src/ports/workspace/vercel-sandbox.ts +60 -3
  150. package/packages/core/src/processes/build-child.ts +6 -6
  151. package/packages/core/src/processes/build-runner.ts +586 -87
  152. package/packages/core/src/processes/dispatch-failure-budget.ts +5 -4
  153. package/packages/core/src/processes/dispatcher-selectors.ts +15 -9
  154. package/packages/core/src/processes/dispatcher.ts +2239 -357
  155. package/packages/core/src/processes/execution-no-progress.ts +46 -1
  156. package/packages/core/src/processes/harvest-execution-state.ts +15 -9
  157. package/packages/core/src/processes/harvest-runner.ts +34 -70
  158. package/packages/core/src/processes/harvest.ts +38 -15
  159. package/packages/core/src/processes/infrastructure-failure-budget.ts +13 -15
  160. package/packages/core/src/processes/orchestrator-tick.ts +2 -2
  161. package/packages/core/src/processes/publication-loss.ts +35 -21
  162. package/packages/core/src/processes/publication-state.ts +30 -5
  163. package/packages/core/src/processes/repo-view.ts +244 -1130
  164. package/packages/core/src/processes/tick-publication.ts +110 -0
  165. package/packages/core/src/store/adapter.ts +23 -0
  166. package/packages/core/src/store/build-scope.ts +35 -0
  167. package/packages/core/src/store/contract.ts +909 -0
  168. package/packages/core/src/store/digest.ts +52 -4
  169. package/packages/core/src/store/local/schema.ts +26 -13
  170. package/packages/core/src/store/local/store.ts +296 -55
  171. package/packages/core/src/store/memory.ts +181 -30
  172. package/packages/core/src/store/phase-session.ts +34 -0
  173. package/packages/core/src/store/reduced-reads.ts +240 -0
  174. package/packages/core/src/store/reducer-value-shapes.json +18323 -0
  175. package/packages/core/src/store/reducer-value-validation.ts +96 -0
  176. package/packages/core/src/store/reducer-values.ts +145 -0
  177. package/packages/core/src/store/remote/client.ts +85 -0
  178. package/packages/core/src/store/remote/compatibility.ts +21 -9
  179. package/packages/core/src/store/remote/index.ts +19 -0
  180. package/packages/core/src/store/remote/protocol.ts +27 -0
  181. package/packages/core/src/store/remote/version.ts +3 -1
  182. package/packages/core/src/store/repo-state-events.ts +3 -1
  183. package/packages/core/src/store/repo-tick.ts +72 -0
  184. package/packages/core/src/store/session-handle.ts +34 -0
  185. package/packages/core/src/store/snapshots.ts +10 -0
  186. package/packages/core/src/store/subscribe.ts +1 -1
  187. package/packages/core/src/store/ticket-assets.ts +4 -4
  188. package/packages/core/src/store/types.ts +71 -6
  189. package/packages/core/src/testing/dispatch-read-budget.ts +215 -0
  190. package/packages/core/src/testing/index.ts +10 -0
  191. package/packages/core/src/testing/reduced-read-budget.ts +502 -0
  192. package/packages/core/src/testing/refresh-scheduler.ts +32 -0
  193. package/skills/guide/SKILL.md +116 -62
  194. package/skills/guide/references/integration-tree.md +117 -0
  195. package/skills/guide/references/landing-policy.md +150 -0
  196. package/skills/guide/references/migration-1.0.md +68 -0
  197. package/skills/guide/references/operator-api.md +13 -6
  198. package/skills/guide/references/plugin-authoring.md +34 -0
  199. package/skills/guide/references/remote-store-protocol.md +114 -9
  200. package/skills/guide/references/remote-ticket-protocol.md +26 -5
  201. package/skills/guide/references/restacking.md +79 -0
  202. package/skills/guide/references/setup.md +49 -6
  203. package/skills/guide/references/ticket-dependencies.md +69 -0
  204. package/skills/guide/references/ticket-migration.md +8 -0
  205. package/skills/operate/SKILL.md +55 -5
  206. package/skills/reconcile/SKILL.md +55 -48
  207. package/skills/spec/SKILL.md +67 -1
  208. package/skills/tickets/SKILL.md +55 -2
  209. package/templates/autobuild.toml +3 -0
  210. package/templates/hosted-service/package.json +2 -2
@@ -1,11 +1,49 @@
1
+ import { evaluateLandingPolicy } from '../kernel/landing-policy'
2
+ import {
3
+ landingAuthorized,
4
+ nativeLandingApplied,
5
+ sameLandingCandidate,
6
+ } from '../kernel/landing-state'
7
+ import { sameParentRejection } from '../kernel/node-restack-state'
8
+ import { validateNodeParent, nodeParentBusy, type ParentContext } from '../kernel/node-parent'
9
+ import { landIntegrationRoot, auditIntegrationLanding } from '../kernel/integration-landing'
10
+ import {
11
+ observeIntegration,
12
+ integrationObservationInputs,
13
+ type IntegrationObservationInputs,
14
+ } from '../kernel/integration-completeness'
15
+ import {
16
+ integrationComplete,
17
+ integrationCurrent,
18
+ integrationNeedsRunner,
19
+ integrationConfig,
20
+ integrationFailed,
21
+ integrationVerified,
22
+ integrationHeadVerified,
23
+ } from '../kernel/integration-state'
24
+ import {
25
+ normalizeIdentities,
26
+ blockerBuild,
27
+ missingChanges,
28
+ presenceInputs,
29
+ observePresence,
30
+ ownedContribution,
31
+ type ChangeIdentity,
32
+ type PresenceInputs,
33
+ } from '../kernel/change-presence'
34
+ import { landIntoNode, settleClosedNode, preflightNodeLanding } from '../kernel/node-landing'
35
+ import { mkdtemp, rm } from 'node:fs/promises'
36
+ import { tmpdir } from 'node:os'
37
+ import { join } from 'node:path'
38
+ import { runNodeTransaction } from '../kernel/node-restack-transaction'
39
+ import { hasBuildTrailer } from '../kernel/build-identity'
40
+ import { readBuildDigests } from '../store/reduced-reads'
41
+ import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
1
42
  import { ensureExecutionProgress } from './execution-no-progress'
2
43
  import { ticketIdentity } from '../ports/tickets/identity'
3
44
  import { ticketLifecycle } from '../ports/tickets/lifecycle'
4
45
  import { ensureDispatchBudget } from './dispatch-failure-budget'
5
- import {
6
- reduceTicketSourceHealth,
7
- type TicketSourceDegradation,
8
- } from '../kernel/ticket-source-health'
46
+ import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
9
47
  /**
10
48
  * The dispatcher process (SPEC §3.3, §12): watches the TicketSource for
11
49
  * Ready tickets, claims, provisions a workspace, and launches build-runners
@@ -48,33 +86,22 @@ import { createHash } from 'node:crypto'
48
86
  import type { Config } from '../config/schema'
49
87
  import type { LanguageModel } from 'ai'
50
88
  import { runOrchestratorTickStep } from './orchestrator-tick'
51
- import { DISPATCHER, agentActor, humanActor } from '../events/envelope'
89
+ import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
52
90
  import { isRemoteWorkspace } from '../events/workspace-remote'
53
91
  import type { AbEvent, EventWrite } from '../events/catalog'
54
92
  import type { EventPayload, PinnedAsset } from '../events/payloads'
55
93
  import type { IdSource } from '../ids'
56
- import {
57
- autoMergeApplicationType,
58
- pendingAutoMerge,
59
- recordAutoMergeDeferralObservation,
60
- } from '../kernel/auto-merge'
61
- import {
62
- autoMergeDefaultTarget,
63
- latestAutoMergeDefault,
64
- type AutoMergeDefaultFact,
65
- } from '../kernel/auto-merge-default'
66
- import { reduceDispatchSettings } from '../kernel/dispatch-settings'
94
+ import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
95
+ import type { AutoMergeDefaultFact } from '../kernel/auto-merge-default'
67
96
  import { decideNextFromFacts } from '../kernel/engine'
68
97
  import { composeBuildConfig } from '../config/live'
69
98
  import { BUILD_EFFECTIVE_CONFIG_ARTIFACT, parseEffectiveBuildConfig } from './build-execution-state'
70
99
  import {
71
100
  DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS,
72
101
  decideHarvestControl,
73
- harvestCreationsDuringReadyScan,
74
- reduceHarvest,
102
+ harvestCreationsFromStates,
75
103
  } from '../kernel/harvest'
76
- import { pendingPrAttachmentReclaims } from '../kernel/pr-attachments'
77
- import { reduceBuild, type BuildState } from '../kernel/reducer'
104
+ import type { BuildState } from '../kernel/reducer'
78
105
  import { createOperatorSandboxService, type OperatorSandboxService } from '../operator/sandbox'
79
106
  import type { ArtifactRef, TicketRef } from '../ontology'
80
107
  import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution'
@@ -85,7 +112,7 @@ import type {
85
112
  TicketSource,
86
113
  WorkspaceProvider,
87
114
  } from '../ports/types'
88
- import { TicketSourceRateLimitError } from '../ports/types'
115
+ import { NoCommitsBetweenBranchesError, TicketSourceRateLimitError } from '../ports/types'
89
116
  import type { Exec } from '../ports/workspace/git-worktree'
90
117
  import type { ArtifactMeta, BuildDigest, BuildRecord, BuildStore, Clock } from '../store/types'
91
118
  import { preparePinnedAssets } from '../store/ticket-assets'
@@ -94,19 +121,9 @@ import { specConformance } from '../spec-standard'
94
121
  export { specConformance, type SpecConformance } from '../spec-standard'
95
122
  import { recordInfrastructureFailure as appendInfrastructureFailure } from './infrastructure-failure-budget'
96
123
  import { settleOpenExecution } from './execution-settlement'
97
- import { openHarvestExecutions } from './harvest-execution-state'
98
124
  import { isWorkDigest, RepoViewStore } from './repo-view'
99
- import {
100
- baseBranchReducer,
101
- openBuildWorkspace,
102
- provisionMarkerReducer,
103
- recoveryCheckpointReducer,
104
- type OpenBuildWorkspace,
105
- type ProvisionMarker,
106
- } from './dispatcher-selectors'
107
- import type { RepositoryEvent } from '../events/repository'
108
- import { sandboxStates } from './sandbox-state'
109
- import { settlePublicationBeforeRelease } from './publication-loss'
125
+ import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
126
+ import { settlePublicationFactsBeforeRelease } from './publication-loss'
110
127
 
111
128
  // ── Readiness resolution (SPEC §3.3) ─────────────────────────────────────────
112
129
 
@@ -611,14 +628,14 @@ export interface DispatcherDeps {
611
628
  /** Latest `workspace.provisioned` not followed by a `workspace.released` —
612
629
  * the reducer deliberately ignores workspace events (liveness is the
613
630
  * dispatcher's concern), so the janitor scans the raw log. */
614
- function openWorkspace(events: AbEvent[]): OpenBuildWorkspace | null {
615
- return openBuildWorkspace(events)
631
+ function openWorkspace(events: CurrentBuildFacts): OpenBuildWorkspace | null {
632
+ return events.workspace
616
633
  }
617
634
 
618
635
  /** The build's base branch, from its own `build.created` fact (§15.3);
619
636
  * falls back to the repo config for logs missing one. */
620
- function baseBranchOf(events: AbEvent[], config: Config): string {
621
- return baseBranchReducer.reduce(events) ?? config.baseBranch
637
+ function baseBranchOf(events: CurrentBuildFacts, config: Config): string {
638
+ return events.baseBranch ?? config.baseBranch
622
639
  }
623
640
 
624
641
  function artifactRefOf(deposited: ArtifactMeta[]): ArtifactRef {
@@ -649,6 +666,59 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
649
666
  }
650
667
 
651
668
  export class Dispatcher {
669
+ // Only scheduling is cached. Eligibility facts still come from durable state,
670
+ // and each admitted verification/publication samples the source this pass.
671
+ private integrationInputs?: Promise<IntegrationObservationInputs>
672
+ private integrationPublicationInputs?: Promise<IntegrationObservationInputs>
673
+ private readonly integrationTargets = new Map<string, string | undefined>()
674
+ private readonly integrationPolls = new Map<string, { key: string; at: number }>()
675
+ private readonly integrationLandingPolls = new Map<string, { key: string; at: number }>()
676
+ private integrationPollDue(
677
+ polls: Map<string, { key: string; at: number }>,
678
+ slug: string,
679
+ key: string,
680
+ ): boolean {
681
+ const now = this.deps.clock().getTime()
682
+ const previous = polls.get(slug)
683
+ if (previous?.key === key && now - previous.at < 300_000) return false
684
+ polls.set(slug, { key, at: now })
685
+ return true
686
+ }
687
+ private async integrationClaimKey(slug: string): Promise<string> {
688
+ const children = []
689
+ for (const { record, digest } of await this.repoBuildDigests()) {
690
+ // Work targets are frozen. Node relationships can change, so refresh
691
+ // those edges before computing this parent's scheduling key.
692
+ if (!this.integrationTargets.has(record.slug) || digest.kind === 'node') {
693
+ const state = (await this.store.buildFacts(record.slug)).state
694
+ if (state.lastSeq > 0) this.integrationTargets.set(record.slug, state.target?.build)
695
+ }
696
+ if (this.integrationTargets.get(record.slug) === slug)
697
+ children.push(
698
+ `${record.slug}:${digest.terminal ?? ''}:${digest.merged ?? ''}:${digest.prClosed ?? ''}`,
699
+ )
700
+ }
701
+ return children.sort().join('|')
702
+ }
703
+ private observeIntegration(slug: string, publication = false) {
704
+ return observeIntegration(this.store, this.deps.tickets, slug, () => {
705
+ if (publication) {
706
+ this.integrationPublicationInputs ??= integrationObservationInputs(
707
+ this.store,
708
+ this.deps.tickets,
709
+ this.deps.repo,
710
+ )
711
+ return this.integrationPublicationInputs
712
+ }
713
+ this.integrationInputs ??= integrationObservationInputs(
714
+ this.store,
715
+ this.deps.tickets,
716
+ this.deps.repo,
717
+ )
718
+ return this.integrationInputs
719
+ })
720
+ }
721
+
652
722
  /** Read at each decision boundary: artifact revisions are independent of events. */
653
723
  private async decideBuild(
654
724
  slug: string,
@@ -759,28 +829,17 @@ export class Dispatcher {
759
829
  }
760
830
 
761
831
  async tick(opts: TickOpts = {}): Promise<TickReport> {
762
- try {
763
- return await this.runTick(opts)
764
- } finally {
765
- // Leave this tick's reduced state behind for the next process (a cache;
766
- // a failure to write it is never a tick failure). Throttled in a
767
- // resident dispatcher, always run by a cold single-tick process.
768
- await this.store.persistSnapshots()
769
- }
832
+ return this.runTick(opts)
770
833
  }
771
834
 
772
835
  private async runTick(opts: TickOpts): Promise<TickReport> {
836
+ this.integrationInputs = undefined
837
+ this.integrationPublicationInputs = undefined
773
838
  // One immutable config for this complete decision pass. A reload racing the
774
839
  // tick is observed by the next tick, never half-way through this one.
775
840
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
776
841
  if (opts.viewRefreshed !== true) await this.store.refresh()
777
- let autoMergeUser: string | undefined
778
- if (opts.defaultAutoMerge === true) {
779
- autoMergeUser = opts.autoMergeUser?.trim()
780
- if (autoMergeUser === undefined || autoMergeUser === '') {
781
- throw new Error('defaultAutoMerge requires nonempty human attribution in autoMergeUser')
782
- }
783
- }
842
+ const autoMergeUser = undefined
784
843
  const report = emptyTickReport()
785
844
  this.restoreScan(report)
786
845
  /** Builds already launched this tick — a janitor/startup re-attach must
@@ -791,18 +850,9 @@ export class Dispatcher {
791
850
  // likewise samples before calling `tick`); the auto-merge default fact is
792
851
  // the durable driver of this tick's fan-out below. Neither control
793
852
  // pretends to a serialization the store does not offer.
794
- const repoEvents = this.store.recordedJournal()
795
- const paused = reduceDispatchSettings(repoEvents).paused
796
- const autoMergeDefault = latestAutoMergeDefault(repoEvents)
797
- // The claim-time seed cites the newest fact whose enabled state matches
798
- // the launch sample, not blindly the newest fact: the CLI samples
799
- // `defaultAutoMerge` from its own earlier read, so an interleaved toggle
800
- // can make this tick's read newer-and-opposite. Citing the matching fact
801
- // keeps the newer opposite fact strictly ahead of the seed's provenance,
802
- // so the fan-out reconciles the build on the next tick instead of the
803
- // stale sample out-voting the durable default forever (f_b851c0e8).
804
- const autoMergeSeedFact =
805
- opts.defaultAutoMerge === true ? latestAutoMergeDefault(repoEvents, true) : undefined
853
+ const repoFacts = this.store.repositoryFacts()
854
+ const paused = repoFacts.settings.paused
855
+ const autoMergeSeedFact = undefined
806
856
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
807
857
  // provider liveness and settle their completion, lease, and publication.
808
858
  // Runs before the janitor so its executionLeaseLive checks see freshly
@@ -822,7 +872,6 @@ export class Dispatcher {
822
872
  // inside `checkPr`). Independent of intake and `acceptNewWork` — the
823
873
  // durable fact drives it, so a second dispatcher polling the same
824
874
  // repository converges the same state.
825
- await this.applyAutoMergeDefault(autoMergeDefault)
826
875
  if (this.outOfBudget(opts)) return report
827
876
  await this.janitor(report, launched, opts)
828
877
  if (this.outOfBudget(opts)) return report
@@ -916,7 +965,7 @@ export class Dispatcher {
916
965
  const store = this.store
917
966
  const { repo } = this.deps
918
967
  const records = (await store.listBuilds()).filter((record) => record.repo === repo)
919
- const digests = await store.getRepoBuildDigests(repo)
968
+ const digests = await readBuildDigests(store, repo)
920
969
  return records.map((record) => {
921
970
  const digest = digests.get(record.slug)
922
971
  if (digest === undefined) {
@@ -943,7 +992,7 @@ export class Dispatcher {
943
992
  * end. A terminal, settled build costs no event reads. */
944
993
  private async workBuilds(): Promise<BuildRecord[]> {
945
994
  return (await this.repoBuildDigests())
946
- .filter(({ digest }) => isWorkDigest(digest))
995
+ .filter(({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true)
947
996
  .map(({ record }) => record)
948
997
  }
949
998
 
@@ -951,8 +1000,7 @@ export class Dispatcher {
951
1000
  next?: TicketSourceDegradation,
952
1001
  successfulOperation?: 'ready-scan' | 'dependency-check',
953
1002
  ): Promise<void> {
954
- await this.store.refreshJournal()
955
- const current = reduceTicketSourceHealth(this.store.recordedJournal())
1003
+ const current = this.store.repositoryFacts().health
956
1004
  if (next !== undefined && current?.cause === next.cause && current.source === next.source) {
957
1005
  if (
958
1006
  next.cause === 'rate-limited' &&
@@ -1043,25 +1091,23 @@ export class Dispatcher {
1043
1091
  * disabled. It shares the active-ticket exclusion with dispatch but performs
1044
1092
  * no dependency fetch, claim, bounce, build, workspace, or launch side
1045
1093
  * effect, and deliberately does not alter TickReport compatibility. */
1046
- async observeReady(): Promise<{
1094
+ async observeReady(opts: Pick<TickOpts, 'viewRefreshed'> = {}): Promise<{
1047
1095
  queued: number
1048
1096
  invalidTickets: number
1049
1097
  ticketDiagnostics: string[]
1050
1098
  }> {
1051
1099
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1052
- await this.store.refresh()
1100
+ if (opts.viewRefreshed !== true) await this.store.refresh()
1053
1101
  const report = emptyTickReport()
1054
1102
  this.restoreScan(report)
1055
1103
  const checkpoint = await this.scanCheckpoint('observation')
1056
1104
  if (checkpoint.due) {
1057
- await this.store.refreshJournal()
1058
1105
  const listing = await this.listReady()
1059
1106
  const refs: TicketRef[] = []
1060
1107
  for (const { record, digest } of await this.repoBuildDigests()) {
1061
1108
  if (record.ticket && digest.terminal === undefined) refs.push(record.ticket)
1062
1109
  }
1063
1110
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
1064
- await this.store.refreshJournal()
1065
1111
  report.queued = listing.tickets.filter(
1066
1112
  (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
1067
1113
  ).length
@@ -1082,12 +1128,7 @@ export class Dispatcher {
1082
1128
  }
1083
1129
 
1084
1130
  private latestScan() {
1085
- return this.store
1086
- .recordedJournal()
1087
- .findLast(
1088
- (event): event is Extract<RepositoryEvent, { type: 'dispatcher.ticket-scan-completed' }> =>
1089
- event.type === 'dispatcher.ticket-scan-completed',
1090
- )?.payload
1131
+ return this.store.repositoryFacts().scan
1091
1132
  }
1092
1133
 
1093
1134
  private restoreScan(report: TickReport): void {
@@ -1160,66 +1201,16 @@ export class Dispatcher {
1160
1201
  })
1161
1202
  }
1162
1203
 
1163
- /** Apply the newest durable `dispatcher.auto-merge-default-set` fact to every
1164
- * current non-terminal build of this repository: on — request consent; off —
1165
- * cancel it. Attribution is the toggling human's own actor, exactly as if
1166
- * they had pressed `m` on each row; each command carries the fact's seq so
1167
- * the fan-out is idempotent (a settled build fails `autoMergeDefaultTarget`)
1168
- * and a per-build override stands until the default is toggled again. A fact
1169
- * whose value already matches the build's state writes a provenance-only
1170
- * `build.auto-merge-default-observed` marker instead of a duplicate command,
1171
- * so the matching fact is recorded as answered (f_28b3fba1).
1172
- *
1173
- * Per build, a compare-and-set loop (the `requestOne` shape from
1174
- * `bulk-control.ts`): the read/reduce/evaluate lives inside the loop, so a
1175
- * competing write loses at most one attempt and the next re-reads fresh
1176
- * state. No TickReport counter: the evidence is the build events, and the
1177
- * report shape stays compatible. */
1178
- private async applyAutoMergeDefault(fact: AutoMergeDefaultFact | undefined): Promise<void> {
1179
- if (fact === undefined) return
1180
- const store = this.store
1181
-
1182
- // Terminal builds are never eligible (`autoMergeDefaultEligible`).
1183
- for (const record of (await this.nonterminalBuilds()).sort((a, b) =>
1184
- a.slug.localeCompare(b.slug),
1185
- )) {
1186
- while (true) {
1187
- const { state } = await store.buildFacts(record.slug)
1188
- const target = autoMergeDefaultTarget(state, fact)
1189
- if (target === undefined) break
1190
- if (target === 'observed') {
1191
- const observed = await store.appendIfCurrent(record.slug, state.lastSeq, {
1192
- actor: DISPATCHER,
1193
- type: 'build.auto-merge-default-observed',
1194
- payload: { defaultSeq: fact.seq },
1195
- })
1196
- if (observed !== null) break
1197
- continue
1198
- }
1199
- const type =
1200
- target === 'request' ? 'build.auto-merge-requested' : 'build.auto-merge-cancelled'
1201
- const appended = await store.appendIfCurrent(record.slug, state.lastSeq, {
1202
- actor: fact.actor,
1203
- type,
1204
- payload: { defaultSeq: fact.seq },
1205
- })
1206
- if (appended !== null) break
1207
- }
1208
- }
1209
- }
1210
-
1211
1204
  private async triggerHarvest(): Promise<void> {
1212
1205
  const start = this.deps.startHarvest
1213
1206
  if (start === undefined) return
1214
- // The journal moves under foreign harvest writers while the stages run, so
1215
- // take the delta before deciding.
1216
- await this.store.refreshJournal()
1207
+ // Use the tick sample, advanced by any local repository append.
1217
1208
  if (!this.store.journalRecorded()) {
1218
1209
  start()
1219
1210
  return
1220
1211
  }
1221
1212
  // Bounded subset (AUT-489): the harvest reducer consumes durable types only.
1222
- const state = reduceHarvest(this.store.recordedJournal())
1213
+ const state = this.store.repositoryFacts().harvest
1223
1214
  if (decideHarvestControl(state, this.maxHarvestRecoveryAttempts).kind !== 'park') {
1224
1215
  start()
1225
1216
  }
@@ -1230,8 +1221,20 @@ export class Dispatcher {
1230
1221
  launched: Set<string>,
1231
1222
  report: TickReport = emptyTickReport(),
1232
1223
  ): Promise<LaunchRunnerResult> {
1224
+ const launchState = (await this.store.buildFacts(slug)).state
1225
+ if (
1226
+ launchState.kind === 'node' &&
1227
+ !launchState.nodeRestack?.conflict &&
1228
+ !integrationCurrent(launchState)
1229
+ )
1230
+ return 'already-active'
1233
1231
  if (launched.has(slug)) return 'already-active'
1234
1232
  launched.add(slug)
1233
+ const facts = (await readBuildFacts(this.store, slug)).value
1234
+ if (facts.log.restack.target === undefined && facts.lastCreated !== undefined) {
1235
+ const branch = facts.lastCreated.payload.baseBranch
1236
+ await this.observeTarget(slug, branch, undefined, report)
1237
+ }
1235
1238
  if (
1236
1239
  !(await ensureExecutionProgress(
1237
1240
  this.store,
@@ -1305,21 +1308,8 @@ export class Dispatcher {
1305
1308
  * repository lease. */
1306
1309
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
1307
1310
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
1308
- let events: RepositoryEvent[]
1309
- try {
1310
- // The earlier stages awaited providers; take the journal delta so a
1311
- // foreign append (operator activity, harvest facts) made meanwhile is
1312
- // seen before any destructive decision below.
1313
- await this.store.refreshJournal()
1314
- events = this.store.recordedJournal()
1315
- } catch {
1316
- // The read itself failed (a transient store error — a missing record
1317
- // answers `[]` inside the helper, so it never reaches this arm):
1318
- // skipping this settlement stage for this tick while the rest of the
1319
- // tick proceeds, and the next tick retries what remains.
1320
- return
1321
- }
1322
- for (const execution of openHarvestExecutions(events)) {
1311
+ const facts = this.store.repositoryFacts()
1312
+ for (const execution of facts.openHarvest) {
1323
1313
  if (active.has(execution.execution)) continue
1324
1314
  // Budget gate: once spent, stop settling further harvest executions;
1325
1315
  // the next tick retries what remains.
@@ -1408,22 +1398,9 @@ export class Dispatcher {
1408
1398
  const capability = this.deps.workspaces.orchestratorSandbox
1409
1399
  if (capability === undefined) return
1410
1400
  const providerName = this.deps.workspaces.name
1411
- let events: RepositoryEvent[]
1412
- try {
1413
- // The earlier stages awaited providers; take the journal delta so a
1414
- // foreign append (operator activity, harvest facts) made meanwhile is
1415
- // seen before any destructive decision below.
1416
- await this.store.refreshJournal()
1417
- events = this.store.recordedJournal()
1418
- } catch {
1419
- // The read itself failed (a transient store error — a missing record
1420
- // answers `[]` inside the helper, so it never reaches this arm):
1421
- // skipping this settlement stage for this tick while the rest of the
1422
- // tick proceeds, and the next tick retries what remains.
1423
- return
1424
- }
1401
+ const facts = this.store.repositoryFacts()
1425
1402
  const idleMs = config.orchestrator.sandbox.idleMinutes * 60_000
1426
- for (const environment of sandboxStates(events)) {
1403
+ for (let environment of facts.sandboxes) {
1427
1404
  if (environment.state !== 'live') continue
1428
1405
  // Budget gate: once spent, stop settling further environments; the
1429
1406
  // next tick retries what remains.
@@ -1433,6 +1410,25 @@ export class Dispatcher {
1433
1410
  continue
1434
1411
  }
1435
1412
  try {
1413
+ // Other processes may have recorded activity while earlier tick work
1414
+ // awaited an outside read. Revalidate only an impending disposition.
1415
+ await this.store.refreshJournal()
1416
+ const current = this.store
1417
+ .repositoryFacts()
1418
+ .sandboxes.find(
1419
+ (candidate) =>
1420
+ candidate.operator === environment.operator &&
1421
+ candidate.environmentId === environment.environmentId,
1422
+ )
1423
+ if (current === undefined || current.state !== 'live') continue
1424
+ const currentEvidence = Date.parse(current.lastEvidenceTs)
1425
+ if (
1426
+ Number.isFinite(currentEvidence) &&
1427
+ this.deps.clock().getTime() - currentEvidence < idleMs
1428
+ ) {
1429
+ continue
1430
+ }
1431
+ environment = current
1436
1432
  if (environment.provider !== providerName) {
1437
1433
  // Provider-mismatch disposition (AUT-377): the journaled provider no
1438
1434
  // longer matches the wired provider, so environmentIds are out of this
@@ -1505,8 +1501,8 @@ export class Dispatcher {
1505
1501
 
1506
1502
  /** The latest `workspace.provision-started` not yet followed by a
1507
1503
  * provisioned/released fact — an open provisioning marker. */
1508
- private openProvisionMarker(events: AbEvent[]): ProvisionMarker | undefined {
1509
- return provisionMarkerReducer.reduce(events)
1504
+ private openProvisionMarker(events: CurrentBuildFacts): ProvisionMarker | undefined {
1505
+ return events.provisionMarker
1510
1506
  }
1511
1507
 
1512
1508
  /** Liveness of the lease behind an open provision marker: `live` means a
@@ -1527,7 +1523,7 @@ export class Dispatcher {
1527
1523
  * report progress without awaiting any of it. */
1528
1524
  private async ensureProvisionContinuation(
1529
1525
  record: BuildRecord,
1530
- events: AbEvent[],
1526
+ events: CurrentBuildFacts,
1531
1527
  tail: 'dispatch' | 'launch',
1532
1528
  seed?: {
1533
1529
  ticket: Ticket
@@ -1543,12 +1539,7 @@ export class Dispatcher {
1543
1539
  const marker = this.openProvisionMarker(events)
1544
1540
  if (marker !== undefined) {
1545
1541
  const liveness = await this.provisionMarkerLiveness(slug)
1546
- const failedAttempt = events.some(
1547
- (event) =>
1548
- event.type === 'dispatch.failed' &&
1549
- event.payload.stage === 'workspace' &&
1550
- event.seq > marker.seq,
1551
- )
1542
+ const failedAttempt = events.latestWorkspaceFailureSeq > marker.seq
1552
1543
  if (liveness === 'live') return 'foreign-live'
1553
1544
  if (
1554
1545
  liveness === 'absent' &&
@@ -1563,7 +1554,7 @@ export class Dispatcher {
1563
1554
  // Expired lease, failed attempt, or an old lease-less marker: adopt.
1564
1555
  }
1565
1556
  const branch = record.branch ?? `ab/${slug}`
1566
- const generation = events.filter((event) => event.type === 'workspace.provisioned').length
1557
+ const generation = events.workspaceGenerations
1567
1558
  await this.store.append(slug, {
1568
1559
  actor: DISPATCHER,
1569
1560
  type: 'workspace.provision-started',
@@ -1643,19 +1634,20 @@ export class Dispatcher {
1643
1634
  // so the next supervisor adopts the marker immediately.
1644
1635
  return
1645
1636
  }
1646
- const events = await store.getEvents(slug)
1647
- const priorGenerations = events.filter(
1648
- (event) => event.type === 'workspace.provisioned',
1649
- ).length
1637
+ const events = (await readBuildFacts(store, slug)).value
1638
+ const priorGenerations = events.workspaceGenerations
1650
1639
  const handle = await workspaces.provision({
1651
1640
  // Local providers provision FROM the physical checkout; remote
1652
1641
  // providers ignore the value (their host seams are injected).
1653
1642
  repo: this.deps.checkout ?? this.deps.repo,
1654
- baseBranch: baseBranchOf(events, config),
1643
+ baseBranch:
1644
+ events.state.kind === 'node' && events.state.integration?.cycle
1645
+ ? input.branch
1646
+ : baseBranchOf(events, config),
1655
1647
  branch: input.branch,
1656
1648
  ...(priorGenerations > 0 || input.generation > 0
1657
1649
  ? {
1658
- revision: this.recoveryCheckpoint(events),
1650
+ revision: events.state.integration?.cycle?.head ?? this.recoveryCheckpoint(events),
1659
1651
  generation: Math.max(priorGenerations, input.generation),
1660
1652
  }
1661
1653
  : {}),
@@ -1689,7 +1681,7 @@ export class Dispatcher {
1689
1681
  boundary = 'read'
1690
1682
  const record = await store.getBuild(slug)
1691
1683
  if (record === null) return
1692
- const queued = reduceBuild(await store.getEvents(slug)).status === 'queued'
1684
+ const queued = (await readBuildFacts(store, slug)).value.state.status === 'queued'
1693
1685
  boundary = input.tail === 'dispatch' || queued ? 'dispatch' : 'launch'
1694
1686
  if (boundary === 'dispatch') await this.completeDispatchBoundaries(record, input.seed)
1695
1687
  else await this.deps.launchRunner(slug)
@@ -1699,10 +1691,10 @@ export class Dispatcher {
1699
1691
  // tick; it is not another provider workspace failure. Replacement
1700
1692
  // runner launch errors retain the existing infrastructure-budget path.
1701
1693
  if (boundary === 'read' || boundary === 'dispatch') return
1702
- const events = await store.getEvents(slug)
1694
+ const events = (await readBuildFacts(store, slug)).value
1703
1695
  if (workspaces.recovery !== undefined) {
1704
1696
  const open = openWorkspace(events)
1705
- const latestRef = [...events].reverse().find((event) => event.type === 'workspace.released')
1697
+ const latestRef = events.latestRelease
1706
1698
  await this.recordInfrastructureFailure(slug, events, {
1707
1699
  provider: workspaces.name,
1708
1700
  workspaceRef:
@@ -1715,7 +1707,7 @@ export class Dispatcher {
1715
1707
  cleanupPending: true,
1716
1708
  })
1717
1709
  }
1718
- const attempt = events.filter((event) => event.type === 'dispatch.failed').length + 1
1710
+ const attempt = events.dispatchFailureCount + 1
1719
1711
  const message = (error instanceof Error ? error.message : String(error)).trim()
1720
1712
  await store.append(slug, {
1721
1713
  actor: DISPATCHER,
@@ -1764,9 +1756,9 @@ export class Dispatcher {
1764
1756
  for (const entry of entries) entry.controller.abort()
1765
1757
  for (const entry of entries) {
1766
1758
  try {
1767
- const events = await this.store.getEvents(entry.slug)
1759
+ const events = (await readBuildFacts(this.store, entry.slug)).value
1768
1760
  if (this.openProvisionMarker(events) !== undefined) {
1769
- const attempt = events.filter((event) => event.type === 'dispatch.failed').length + 1
1761
+ const attempt = events.dispatchFailureCount + 1
1770
1762
  await this.store.append(entry.slug, {
1771
1763
  actor: DISPATCHER,
1772
1764
  type: 'dispatch.failed',
@@ -1801,7 +1793,9 @@ export class Dispatcher {
1801
1793
  // Only this repo's builds that still have work (§12: another repo's
1802
1794
  // builds are another dispatcher's duty; settled terminal builds cost no
1803
1795
  // event reads).
1804
- const entries = (await this.repoBuildDigests()).filter(({ digest }) => isWorkDigest(digest))
1796
+ const entries = (await this.repoBuildDigests()).filter(
1797
+ ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
1798
+ )
1805
1799
  for (const { record, digest } of entries) {
1806
1800
  // Budget gate: the janitor's per-build path issues forge/store transport
1807
1801
  // calls (PR probes, closePr, deleteBranch); once the budget is spent,
@@ -1812,24 +1806,132 @@ export class Dispatcher {
1812
1806
  // Once a record is known, contain its complete janitor path: loading
1813
1807
  // and reducing facts, cleanup, forge/ticket calls, and store writes.
1814
1808
  // Existing partial facts leave the same work due on the next tick.
1815
- const { state, workspace } = await this.store.buildFacts(record.slug)
1809
+ let { state, workspace, log } = await this.store.buildFacts(record.slug)
1816
1810
  const executionLeaseLive = this.hasLiveExecutionLease(record)
1817
1811
  // Raw history, read at most once and only by a branch that acts on it:
1818
1812
  // the facts above answer every quiet-path question without it.
1819
- let loaded: AbEvent[] | undefined
1820
- const history = async (): Promise<AbEvent[]> => {
1821
- loaded ??= await this.store.getEvents(record.slug)
1813
+ let loaded: CurrentBuildFacts | undefined
1814
+ const history = async (): Promise<CurrentBuildFacts> => {
1815
+ loaded ??= (await readBuildFacts(this.store, record.slug)).value
1822
1816
  return loaded
1823
1817
  }
1818
+ let observedPr: Awaited<ReturnType<Forge['getPrState']>> | undefined
1819
+ // A replacement head is followed first by a forge read and cancellation,
1820
+ // ahead of node cascade, controls, or any other action for this build.
1821
+ if (
1822
+ state.status !== 'done' &&
1823
+ state.status !== 'aborted' &&
1824
+ state.prState === 'open' &&
1825
+ state.pr &&
1826
+ state.landing?.native?.operation
1827
+ ) {
1828
+ const path = this.forgeWorkspacePathOf(workspace)
1829
+ const observed = await this.deps.forge.getPrState(path, state.pr.number)
1830
+ observedPr = observed
1831
+ if (observed.state !== 'open') {
1832
+ await this.checkPr(
1833
+ record,
1834
+ { history, workspace },
1835
+ state,
1836
+ report,
1837
+ launched,
1838
+ executionLeaseLive,
1839
+ observedPr,
1840
+ )
1841
+ continue
1842
+ }
1843
+ const result =
1844
+ observed.nativeAutoMerge === false
1845
+ ? { kind: 'applied' as const }
1846
+ : await this.deps.forge.setAutoMerge(path, state.pr.number, false)
1847
+ if (result.kind !== 'applied')
1848
+ throw new Error('Replacement-head native cancellation unconfirmed')
1849
+ observedPr = { ...observed, nativeAutoMerge: false }
1850
+ }
1824
1851
  // Pipeline/ticket/workspace state is settled, but release-asset cleanup
1825
1852
  // has its own crash window after build.completed. Revisit only pending
1826
1853
  // hosted handles; this never relaunches a runner or consumes capacity.
1854
+ if (
1855
+ state.kind === 'node' &&
1856
+ state.integration?.landing?.operation &&
1857
+ !state.integration.audit
1858
+ ) {
1859
+ await this.withKernelRepository((path) =>
1860
+ auditIntegrationLanding({
1861
+ store: this.store,
1862
+ forge: this.kernelForge(),
1863
+ exec: this.kernelForge().kernelExec ?? this.deps.exec,
1864
+ workspacePath: path,
1865
+ slug: record.slug,
1866
+ id: this.deps.ids('esc'),
1867
+ }),
1868
+ )
1869
+ }
1827
1870
  if (state.status === 'done') {
1828
1871
  if (digest.reclaimPending === true) {
1829
1872
  await this.reclaimPrAttachments(record.slug, await history())
1830
1873
  }
1831
1874
  continue
1832
1875
  }
1876
+ if (state.kind === 'node' && state.status !== 'aborted') {
1877
+ const command =
1878
+ state.pendingCommands.find((c) => c.command === 'abort') ?? state.pendingCommands.at(0)
1879
+ if (command !== undefined && !executionLeaseLive) {
1880
+ await this.store.append(record.slug, {
1881
+ actor: DISPATCHER,
1882
+ type:
1883
+ command.command === 'abort'
1884
+ ? 'build.aborted'
1885
+ : command.command === 'pause'
1886
+ ? 'build.paused'
1887
+ : 'build.resumed',
1888
+ payload: {},
1889
+ })
1890
+ if (command.command === 'abort')
1891
+ await this.cleanupAborted(record, await history(), report)
1892
+ continue
1893
+ }
1894
+ if (state.nodeOpened) {
1895
+ await this.observeTicketTarget(record, state, report)
1896
+ loaded = undefined
1897
+ ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
1898
+ }
1899
+ if ((state.status === 'paused' || state.status === 'blocked') && !state.pr) continue
1900
+ if (state.nodeOpened && state.baseBranch) {
1901
+ if (
1902
+ await this.observeTarget(
1903
+ record.slug,
1904
+ state.baseBranch,
1905
+ log.restack.target?.sha,
1906
+ report,
1907
+ )
1908
+ ) {
1909
+ loaded = undefined
1910
+ ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
1911
+ }
1912
+ }
1913
+ if (
1914
+ state.nodeOpened &&
1915
+ state.status !== 'paused' &&
1916
+ (state.status !== 'blocked' || integrationFailed(state)) &&
1917
+ state.prState !== 'merged' &&
1918
+ state.prState !== 'closed' &&
1919
+ !executionLeaseLive
1920
+ ) {
1921
+ await this.cascadeNode(record, state, report, launched, opts)
1922
+ loaded = undefined
1923
+ ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
1924
+ }
1925
+ if (state.nodeOpened && !executionLeaseLive) {
1926
+ await this.prepareIntegration(record, state, report, launched)
1927
+ loaded = undefined
1928
+ ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
1929
+ }
1930
+ if (state.nodeOpened !== undefined && state.pr === undefined) {
1931
+ await this.pollEmptyNode(record, state)
1932
+ continue
1933
+ }
1934
+ }
1833
1935
  // Abort is destructive human judgment and therefore outranks a queued
1834
1936
  // discard when both requests raced into the same stream.
1835
1937
  if (
@@ -1863,6 +1965,17 @@ export class Dispatcher {
1863
1965
  await this.cleanupAborted(record, await history(), report)
1864
1966
  continue
1865
1967
  }
1968
+ if (state.kind !== 'node' && state.status !== 'aborted')
1969
+ await this.observeTicketTarget(record, state, report)
1970
+ if (state.kind !== 'node' && state.status !== 'aborted' && state.status !== 'queued') {
1971
+ const branch = await readBuildSelector(this.store, record.slug, 'baseBranch')
1972
+ if (branch !== undefined) {
1973
+ if (await this.observeTarget(record.slug, branch, log.restack.target?.sha, report)) {
1974
+ loaded = undefined
1975
+ ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
1976
+ }
1977
+ }
1978
+ }
1866
1979
  if (state.pr) {
1867
1980
  await this.checkPr(
1868
1981
  record,
@@ -1871,6 +1984,7 @@ export class Dispatcher {
1871
1984
  report,
1872
1985
  launched,
1873
1986
  executionLeaseLive,
1987
+ observedPr,
1874
1988
  )
1875
1989
  }
1876
1990
  } catch (error) {
@@ -1881,7 +1995,235 @@ export class Dispatcher {
1881
1995
  }
1882
1996
  }
1883
1997
 
1884
- private forgeWorkspacePath(events: AbEvent[]): string {
1998
+ private parentContext(): ParentContext {
1999
+ return {
2000
+ store: this.store,
2001
+ source: this.deps.tickets,
2002
+ repo: this.deps.repo,
2003
+ root: this.deps.config.baseBranch,
2004
+ configuredSource: this.deps.config.tickets.source,
2005
+ supportsRetarget: async () =>
2006
+ !!this.deps.forge.retargetPr && !!this.deps.forge.inspectLandingPr,
2007
+ }
2008
+ }
2009
+
2010
+ /** Tracker observation can withhold a new parent, but cannot stop recovery
2011
+ * against the durable effective parent or observation of terminal PRs. */
2012
+ private async observeTicketTarget(record: BuildRecord, state: BuildState, report: TickReport) {
2013
+ try {
2014
+ if (state.kind === 'node') await this.observeNodeParent(record, state, report)
2015
+ else await this.observeWorkTarget(record, state, report)
2016
+ } catch (error) {
2017
+ report.janitorDiagnostics.push(
2018
+ `build ${record.slug}: ticket target observation failed — ${error instanceof Error ? error.message : String(error)}`,
2019
+ )
2020
+ }
2021
+ }
2022
+
2023
+ private async clearParentRejection(record: BuildRecord, ticket: Ticket) {
2024
+ const state = (await this.store.buildFacts(record.slug)).state
2025
+ if (!state.nodeRestack?.parentRejection) return
2026
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
2027
+ actor: DISPATCHER,
2028
+ type: 'node.parent-rejection-cleared',
2029
+ payload: { revision: ticket.revision, target: ticket.target ?? null },
2030
+ })
2031
+ }
2032
+
2033
+ private async rejectParent(
2034
+ record: BuildRecord,
2035
+ ticket: Ticket,
2036
+ reason: string,
2037
+ report: TickReport,
2038
+ ) {
2039
+ const rejection = { revision: ticket.revision, target: ticket.target ?? null, reason }
2040
+ const state = (await this.store.buildFacts(record.slug)).state
2041
+ if (!sameParentRejection(state.nodeRestack?.parentRejection, rejection))
2042
+ await this.store.append(record.slug, {
2043
+ actor: DISPATCHER,
2044
+ type: 'node.parent-rejected',
2045
+ payload: rejection,
2046
+ })
2047
+ report.janitorDiagnostics.push(`build ${record.slug}: ${reason}`)
2048
+ }
2049
+
2050
+ private async observeWorkTarget(record: BuildRecord, state: BuildState, report: TickReport) {
2051
+ if (!record.ticket || record.ticket.source !== this.deps.tickets.name) return
2052
+ const ticket = await this.deps.tickets.get(record.ticket.id)
2053
+ if (!ticket) {
2054
+ report.janitorDiagnostics.push(
2055
+ `build ${record.slug}: claimed ticket cannot be read; frozen work target retained`,
2056
+ )
2057
+ return
2058
+ }
2059
+ const effective = state.target?.ticket.id
2060
+ const canonical =
2061
+ effective && this.deps.config.tickets.source === 'hosted'
2062
+ ? ((await this.deps.tickets.get(effective))?.ref.id ?? effective)
2063
+ : effective
2064
+ if (ticket.target !== canonical)
2065
+ await this.rejectParent(
2066
+ record,
2067
+ ticket,
2068
+ 'changing a claimed work ticket target requires abort and re-dispatch',
2069
+ report,
2070
+ )
2071
+ else await this.clearParentRejection(record, ticket)
2072
+ }
2073
+
2074
+ /** Provider edits and interrupted caller writes converge through this same
2075
+ * durable path, independently of ticket readiness or caller liveness. */
2076
+ private async observeNodeParent(record: BuildRecord, state: BuildState, report: TickReport) {
2077
+ if (!record.ticket || record.ticket.source !== this.deps.tickets.name) return
2078
+ if (nodeParentBusy(state)) return
2079
+ if (
2080
+ state.pr &&
2081
+ (await this.deps.forge.getPrState(this.deps.checkout ?? this.deps.repo, state.pr.number))
2082
+ .state !== 'open'
2083
+ )
2084
+ return
2085
+ const node = state.nodeRestack
2086
+ if (node?.parentChange) {
2087
+ // Replay is frozen until its receipt, including through reconcile and
2088
+ // lease loss. Later source edits wait for both Git and PR acknowledgement.
2089
+ const move = node.parentChange
2090
+ if (node.parentReplay !== move.id) return
2091
+ const forge = this.deps.forge
2092
+ if (state.pr && node.parentPr !== move.id) {
2093
+ const path = this.deps.checkout ?? this.deps.repo
2094
+ if ((await forge.getPrState(path, state.pr.number)).state !== 'open') return
2095
+ const cancelled = await forge.setAutoMerge(path, state.pr.number, false)
2096
+ if (cancelled.kind !== 'applied') return
2097
+ await forge.retargetPr!(path, state.pr.number, move.next.branch)
2098
+ const inspected = await forge.inspectLandingPr!(path, state.pr.number)
2099
+ if (
2100
+ !inspected.open ||
2101
+ inspected.base !== move.next.branch ||
2102
+ inspected.head !== record.branch ||
2103
+ inspected.headSha !== node.inventory?.head
2104
+ )
2105
+ throw new Error('parent PR acknowledgement disagrees with effective target')
2106
+ await this.store.append(record.slug, {
2107
+ actor: DISPATCHER,
2108
+ type: 'node.parent-pr-retargeted',
2109
+ payload: { id: move.id, base: move.next.branch },
2110
+ })
2111
+ }
2112
+ await this.store.append(record.slug, {
2113
+ actor: DISPATCHER,
2114
+ type: 'node.parent-completed',
2115
+ payload: { id: move.id },
2116
+ })
2117
+ this.integrationInputs = undefined
2118
+ this.integrationPublicationInputs = undefined
2119
+ return
2120
+ }
2121
+ const ticket = await this.deps.tickets.get(record.ticket.id)
2122
+ if (!ticket) throw new Error('node ticket cannot be read; parent observation failed closed')
2123
+ const desired = ticket.target ?? null
2124
+ const request = node?.parentRequest
2125
+ const effective = state.target?.ticket.id
2126
+ const canonical =
2127
+ effective && this.deps.config.tickets.source === 'hosted'
2128
+ ? ((await this.deps.tickets.get(effective))?.ref.id ?? effective)
2129
+ : effective
2130
+ if (!request && desired === (canonical ?? null)) {
2131
+ await this.clearParentRejection(record, ticket)
2132
+ return
2133
+ }
2134
+ // Settle the current writer before sampling any new destination.
2135
+ if (node?.active || state.sessions.open.length || this.hasLiveExecutionLease(record)) return
2136
+ const holder = this.deps.ids('parent-writer')
2137
+ if (!(await this.store.claimNodeWriter(record.slug, holder, 60_000))) return
2138
+ try {
2139
+ state = (await this.store.buildFacts(record.slug)).state
2140
+ if (
2141
+ nodeParentBusy(state) ||
2142
+ state.nodeRestack?.active ||
2143
+ state.nodeRestack?.parentChange ||
2144
+ state.nodeRestack?.parentRequest?.id !== request?.id
2145
+ )
2146
+ return
2147
+ if (request && desired !== (request.next.target?.ticket.id ?? null)) {
2148
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
2149
+ actor: DISPATCHER,
2150
+ type: 'node.parent-cancelled',
2151
+ payload: { id: request.id, reason: 'source readback does not confirm requested target' },
2152
+ })
2153
+ return
2154
+ }
2155
+ let next: EventPayload<'node.parent-accepted'>['next']
2156
+ try {
2157
+ next = await validateNodeParent(this.parentContext(), record, ticket)
2158
+ if (
2159
+ request &&
2160
+ (next.branch !== request.next.branch || next.target?.build !== request.next.target?.build)
2161
+ )
2162
+ throw new Error('destination generation changed; retry target update')
2163
+ } catch (error) {
2164
+ if (request)
2165
+ await this.store.append(record.slug, {
2166
+ actor: DISPATCHER,
2167
+ type: 'node.parent-cancelled',
2168
+ payload: { id: request.id, reason: String(error) },
2169
+ })
2170
+ await this.rejectParent(
2171
+ record,
2172
+ ticket,
2173
+ error instanceof Error ? error.message : String(error),
2174
+ report,
2175
+ )
2176
+ return
2177
+ }
2178
+ if (state.pr) {
2179
+ const path = this.deps.checkout ?? this.deps.repo
2180
+ if ((await this.deps.forge.getPrState(path, state.pr.number)).state !== 'open') return
2181
+ if ((await this.deps.forge.setAutoMerge(path, state.pr.number, false)).kind !== 'applied')
2182
+ return
2183
+ }
2184
+ if (!(await this.store.renewNodeWriter(record.slug, holder))) return
2185
+ const move = {
2186
+ id: request?.id ?? this.deps.ids('node-parent'),
2187
+ old: { target: state.target ?? null, branch: state.baseBranch! },
2188
+ next,
2189
+ revision: ticket.revision,
2190
+ }
2191
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
2192
+ actor: DISPATCHER,
2193
+ type: 'node.parent-accepted',
2194
+ payload: move,
2195
+ })
2196
+ this.integrationInputs = undefined
2197
+ this.integrationPublicationInputs = undefined
2198
+ } finally {
2199
+ await this.store.releaseNodeWriter(record.slug, holder)
2200
+ }
2201
+ }
2202
+
2203
+ private async observeTarget(
2204
+ slug: string,
2205
+ branch: string,
2206
+ previous: string | undefined,
2207
+ report: TickReport,
2208
+ ): Promise<boolean> {
2209
+ let sha: string
2210
+ try {
2211
+ sha = await this.baseSha(branch)
2212
+ } catch (error) {
2213
+ const message = error instanceof Error ? error.message : String(error)
2214
+ report.janitorDiagnostics.push(`build ${slug}: target observation failed — ${message}`)
2215
+ return false
2216
+ }
2217
+ if (sha === previous) return false
2218
+ await this.store.append(slug, {
2219
+ actor: DISPATCHER,
2220
+ type: 'target.moved',
2221
+ payload: { branch, sha },
2222
+ })
2223
+ return true
2224
+ }
2225
+
2226
+ private forgeWorkspacePath(events: CurrentBuildFacts): string {
1885
2227
  return this.forgeWorkspacePathOf(openWorkspace(events))
1886
2228
  }
1887
2229
 
@@ -1905,12 +2247,57 @@ export class Dispatcher {
1905
2247
  * repeating on later ticks. `build.completed` is deliberately last. */
1906
2248
  private async cleanupAborted(
1907
2249
  record: BuildRecord,
1908
- events: AbEvent[],
2250
+ events: CurrentBuildFacts,
1909
2251
  report: TickReport,
1910
2252
  ): Promise<void> {
1911
2253
  const store = this.store
1912
2254
  const { tickets, forge } = this.deps
1913
2255
  const branch = record.branch
2256
+ if (events.state.target && branch && events.state.pr) {
2257
+ const target = await store.getBuild(events.state.target.build)
2258
+ if (target?.branch) {
2259
+ const active = (await store.buildFacts(target.slug)).state.nodeRestack?.active
2260
+ if (active?.operation === 'landing' && active.source === record.slug) {
2261
+ await this.withKernelRepository((workspacePath) =>
2262
+ landIntoNode({
2263
+ store,
2264
+ forge: this.kernelForge(),
2265
+ exec: forge.kernelExec ?? this.deps.exec,
2266
+ workspacePath,
2267
+ slug: record.slug,
2268
+ node: target.slug,
2269
+ branch,
2270
+ destination: target.branch!,
2271
+ pr: events.state.pr!.number,
2272
+ holder: this.deps.ids('node-writer'),
2273
+ id: active.id,
2274
+ eligible: async () => false,
2275
+ }),
2276
+ )
2277
+ if (
2278
+ (await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug
2279
+ )
2280
+ return
2281
+ Object.assign(events, (await readBuildFacts(store, record.slug)).value)
2282
+ }
2283
+ }
2284
+ }
2285
+ if (
2286
+ events.state.kind === 'node' &&
2287
+ branch &&
2288
+ !(await this.withKernelRepository((workspacePath) =>
2289
+ settleClosedNode({
2290
+ store,
2291
+ forge: this.kernelForge(),
2292
+ exec: forge.kernelExec ?? this.deps.exec,
2293
+ workspacePath,
2294
+ slug: record.slug,
2295
+ branch,
2296
+ holder: this.deps.ids('node-writer'),
2297
+ }),
2298
+ ))
2299
+ )
2300
+ return
1914
2301
  // Whether this build ever owned a local checkout workspace, judged on the
1915
2302
  // provisioned facts (not the open one, which is null when the build never
1916
2303
  // provisioned or already released — only the former must skip the
@@ -1919,13 +2306,11 @@ export class Dispatcher {
1919
2306
  // in the main checkout, and origin mode has no checkout at all: the
1920
2307
  // local-branch git step is skipped, and the saga's later steps tolerate
1921
2308
  // its absence.
1922
- const hadLocalWorkspace = events.some(
1923
- (event) => event.type === 'workspace.provisioned' && !isRemoteWorkspace(event.payload),
1924
- )
1925
- const has = (type: AbEvent['type']): boolean => events.some((event) => event.type === type)
2309
+ const hadLocalWorkspace = events.localWorkspace
2310
+ const has = (type: AbEvent['type']): boolean => events.seenTypes.includes(type)
1926
2311
  const append = async <T extends EventWrite['type']>(write: EventWrite<T>): Promise<void> => {
1927
- const event = await store.append(record.slug, write)
1928
- events.push(event as AbEvent)
2312
+ const _event = await store.append(record.slug, write)
2313
+ Object.assign(events, (await readBuildFacts(store, record.slug)).value)
1929
2314
  }
1930
2315
  const fail = (operation: string, identity: string, error: unknown): never => {
1931
2316
  const detail = error instanceof Error ? error.message : String(error)
@@ -1942,7 +2327,7 @@ export class Dispatcher {
1942
2327
  }
1943
2328
  }
1944
2329
 
1945
- const reduced = reduceBuild(events)
2330
+ const reduced = events.state
1946
2331
  if (reduced.pr !== undefined && !has('pr.closed') && !has('pr.merged')) {
1947
2332
  const closePr = forge.closePr
1948
2333
  if (closePr === undefined) {
@@ -1962,7 +2347,16 @@ export class Dispatcher {
1962
2347
  )
1963
2348
  await append(
1964
2349
  result.state === 'merged'
1965
- ? { actor: DISPATCHER, type: 'pr.merged', payload: { sha: result.sha } }
2350
+ ? {
2351
+ actor: DISPATCHER,
2352
+ type: 'pr.merged',
2353
+ payload: await this.mergeEvidence(
2354
+ record,
2355
+ this.forgeWorkspacePath(events),
2356
+ result.sha,
2357
+ reduced.kind,
2358
+ ),
2359
+ }
1966
2360
  : { actor: DISPATCHER, type: 'pr.closed', payload: {} },
1967
2361
  )
1968
2362
  } catch (error) {
@@ -1972,7 +2366,8 @@ export class Dispatcher {
1972
2366
 
1973
2367
  try {
1974
2368
  const released = await this.releaseWorkspace(record.slug, events, 'abort')
1975
- if (released !== undefined) events.push(released)
2369
+ if (released !== undefined)
2370
+ Object.assign(events, (await readBuildFacts(store, record.slug)).value)
1976
2371
  } catch (error) {
1977
2372
  fail('workspace release', `build ${record.slug}`, error)
1978
2373
  }
@@ -2069,7 +2464,7 @@ export class Dispatcher {
2069
2464
  * every partial cleanup is retried after a crash. */
2070
2465
  private async cleanupDiscarded(
2071
2466
  record: BuildRecord,
2072
- events: AbEvent[],
2467
+ events: CurrentBuildFacts,
2073
2468
  report: TickReport,
2074
2469
  ): Promise<void> {
2075
2470
  const store = this.store
@@ -2093,17 +2488,47 @@ export class Dispatcher {
2093
2488
  report.discarded += 1
2094
2489
  }
2095
2490
 
2491
+ /** Inspection is evidence, never a prerequisite for observing a merge. */
2492
+ private async mergeEvidence(
2493
+ record: BuildRecord,
2494
+ workspacePath: string,
2495
+ sha: string,
2496
+ kind?: 'work' | 'node',
2497
+ ): Promise<{ sha: string; buildTrailerPresent?: boolean }> {
2498
+ if (kind === 'node')
2499
+ await this.recoverNodeContributions(await this.repoBuildDigests(), { slug: record.slug, sha })
2500
+ const read = this.deps.forge.readCommitMessage
2501
+ if (read === undefined) return { sha }
2502
+ try {
2503
+ const message = await read.call(this.deps.forge, workspacePath, sha)
2504
+ return { sha, buildTrailerPresent: hasBuildTrailer(message, record.slug) }
2505
+ } catch (error) {
2506
+ await this.store.append(record.slug, {
2507
+ actor: KERNEL,
2508
+ type: 'observation.recorded',
2509
+ payload: {
2510
+ id: this.deps.ids('obs'),
2511
+ kind: 'followup',
2512
+ summary: `Merged commit ${sha} identity inspection failed; inspect its Autobuild-Build trailer manually: ${error instanceof Error ? error.message : String(error)}`,
2513
+ refs: [sha],
2514
+ },
2515
+ })
2516
+ return { sha }
2517
+ }
2518
+ }
2519
+
2096
2520
  /** Post-PR epilogue (§15.7): poll the forge, emit `pr.*` facts (deduped
2097
2521
  * against the reduced `prState`), release/complete, project to the ticket. */
2098
2522
  private async checkPr(
2099
2523
  record: BuildRecord,
2100
2524
  // `workspace` is the open workspace fact; `history` loads the raw log, which
2101
2525
  // only the branches that act on a PR transition need.
2102
- source: { history: () => Promise<AbEvent[]>; workspace: OpenBuildWorkspace | null },
2526
+ source: { history: () => Promise<CurrentBuildFacts>; workspace: OpenBuildWorkspace | null },
2103
2527
  state: BuildState,
2104
2528
  report: TickReport,
2105
2529
  launched: Set<string>,
2106
2530
  executionLeaseLive: boolean,
2531
+ observedPr?: Awaited<ReturnType<Forge['getPrState']>>,
2107
2532
  ): Promise<void> {
2108
2533
  const store = this.store
2109
2534
  const { tickets, forge } = this.deps
@@ -2112,39 +2537,183 @@ export class Dispatcher {
2112
2537
  // Forge calls run from the workspace when it still exists (it does until
2113
2538
  // the build completes); fall back to the repo itself for odd logs.
2114
2539
  const workspacePath = this.forgeWorkspacePathOf(source.workspace)
2115
- const prState = await forge.getPrState(workspacePath, pr.number)
2116
- const autoMerge = prState.state === 'open' ? pendingAutoMerge(state) : undefined
2117
-
2118
- // Revoking consent takes priority even while the PR is conflicted. A live
2119
- // native request could otherwise merge immediately after reconcile pushes
2120
- // and checks pass, before the next janitor poll gets a chance to cancel it.
2121
- if (autoMerge?.enabled === false) {
2122
- const result = await forge.setAutoMerge(workspacePath, pr.number, false)
2123
- if (result.kind !== 'applied') {
2124
- throw new Error(`forge returned ${result.kind} while disabling native auto-merge`)
2540
+ const integration = state.kind === 'node'
2541
+ const nodeTarget = state.target !== undefined
2542
+ const target = nodeTarget ? await store.getBuild(state.target!.build) : null
2543
+ const reservation = target
2544
+ ? (await store.buildFacts(target.slug)).state.nodeRestack?.active
2545
+ : undefined
2546
+ const recoverLanding =
2547
+ reservation?.operation === 'landing' && reservation.source === record.slug
2548
+ let prState: Awaited<ReturnType<typeof forge.getPrState>>
2549
+ try {
2550
+ prState = observedPr ?? (await forge.getPrState(workspacePath, pr.number))
2551
+ } catch (error) {
2552
+ if (!recoverLanding && state.prState !== 'merged') throw error
2553
+ prState = { state: 'open', mergeable: null }
2554
+ }
2555
+ if (state.prState === 'merged' && state.mergedSha)
2556
+ prState = { state: 'merged', sha: state.mergedSha }
2557
+ let nativeCancelled = false
2558
+ if (
2559
+ nodeTarget &&
2560
+ prState.state === 'open' &&
2561
+ !recoverLanding &&
2562
+ prState.nativeAutoMerge !== false
2563
+ ) {
2564
+ const cancelled = await forge.setAutoMerge(workspacePath, pr.number, false)
2565
+ if (cancelled.kind !== 'applied')
2566
+ throw new Error('node-target native auto-merge cancellation unconfirmed')
2567
+ nativeCancelled = true
2568
+ }
2569
+ // Converge native state on every poll, including paused and unready builds.
2570
+ // A replacement publication invalidates readiness, even if a stale enable
2571
+ // finished after the publisher confirmed cancellation.
2572
+ const ready = async (candidate: BuildState): Promise<boolean> => {
2573
+ if (
2574
+ (integration ? executionLeaseLive : candidate.sessions.open.length > 0) ||
2575
+ candidate.status === 'paused' ||
2576
+ candidate.status === 'done' ||
2577
+ candidate.status === 'aborted' ||
2578
+ candidate.openEscalations.length ||
2579
+ candidate.pendingCommands.length
2580
+ )
2581
+ return false
2582
+ if (integration) {
2583
+ const artifact = await store.getArtifact(record.slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
2584
+ const config = artifact
2585
+ ? composeBuildConfig(parseEffectiveBuildConfig(artifact), this.deps.config)
2586
+ : this.deps.config
2587
+ return integrationVerified(candidate, config)
2588
+ }
2589
+ const facts = await store.buildFacts(record.slug)
2590
+ const decision = await this.decideBuild(record.slug, facts.state, facts.log, report)
2591
+ return decision?.kind === 'wait' && decision.reason === 'awaiting-pr'
2592
+ }
2593
+ const candidateOf = async (current: BuildState) =>
2594
+ integration
2595
+ ? current.integration?.cycle && {
2596
+ head: current.integration.cycle.head,
2597
+ parent: current.integration.cycle.parent,
2598
+ cycle: current.integration.cycle.id,
2599
+ }
2600
+ : current.pr && {
2601
+ head: current.pr.headSha,
2602
+ parent:
2603
+ (await store.buildFacts(record.slug)).log.restack.completed?.targetBase ??
2604
+ (await store.buildFacts(record.slug)).log.restack.initialBase ??
2605
+ '',
2606
+ cycle: String(current.finalizeCompletedSeq),
2607
+ }
2608
+ let isReady = prState.state === 'open' && (await ready(state))
2609
+ if (
2610
+ prState.state === 'open' &&
2611
+ !recoverLanding &&
2612
+ (!isReady ||
2613
+ !landingAuthorized(state.landing) ||
2614
+ !sameLandingCandidate(await candidateOf(state), state.landing?.decision?.candidate))
2615
+ ) {
2616
+ const cancellation =
2617
+ nativeCancelled || prState.nativeAutoMerge === false
2618
+ ? { kind: 'applied' as const }
2619
+ : await forge.setAutoMerge(workspacePath, pr.number, false)
2620
+ if (cancellation.kind !== 'applied')
2621
+ throw new Error('Native landing cancellation unconfirmed')
2622
+ nativeCancelled = true
2623
+ }
2624
+ if (isReady) {
2625
+ while (true) {
2626
+ const current = (await store.buildFacts(record.slug)).state
2627
+ const candidate = await candidateOf(current)
2628
+ if (!candidate?.parent || !(await ready(current))) {
2629
+ isReady = false
2630
+ break
2631
+ }
2632
+ if (sameLandingCandidate(candidate, current.landing?.decision?.candidate)) {
2633
+ state = current
2634
+ break
2635
+ }
2636
+ if (!record.ticket) throw new Error('Landing policy requires a readable source ticket')
2637
+ const ticket = await tickets.get(record.ticket.id)
2638
+ if (!ticket)
2639
+ throw new Error(
2640
+ `Landing policy source ticket ${record.ticket.id} is unavailable; retrying on next poll`,
2641
+ )
2642
+ const input = {
2643
+ from: integration ? ('node' as const) : ('leaf' as const),
2644
+ into: current.target
2645
+ ? { kind: 'node' as const, ticket: current.target.ticket.id }
2646
+ : { kind: 'root' as const },
2647
+ labels: ticket.labels,
2648
+ }
2649
+ const decision = evaluateLandingPolicy(this.deps.config.landing, input)
2650
+ if (!(await ready(current))) {
2651
+ isReady = false
2652
+ break
2653
+ }
2654
+ if (
2655
+ await store.appendIfCurrent(record.slug, current.lastSeq, {
2656
+ actor: DISPATCHER,
2657
+ type: 'landing.decided',
2658
+ payload: { candidate, ...input, ...decision },
2659
+ })
2660
+ ) {
2661
+ state = (await store.buildFacts(record.slug)).state
2662
+ break
2663
+ }
2125
2664
  }
2665
+ }
2666
+ if (
2667
+ prState.state === 'open' &&
2668
+ !recoverLanding &&
2669
+ (nodeTarget || !isReady || !landingAuthorized(state.landing))
2670
+ ) {
2671
+ const result =
2672
+ nativeCancelled || prState.nativeAutoMerge === false
2673
+ ? { kind: 'applied' as const }
2674
+ : await forge.setAutoMerge(workspacePath, pr.number, false)
2675
+ if (result.kind !== 'applied')
2676
+ throw new Error('Native landing cancellation unconfirmed; retrying')
2677
+ const current = (await store.buildFacts(record.slug)).state
2678
+ if (current.landing?.native?.enabled !== false)
2679
+ await store.append(record.slug, {
2680
+ actor: DISPATCHER,
2681
+ type: 'landing.native-applied',
2682
+ payload: { enabled: false },
2683
+ })
2684
+ }
2685
+ const command = state.landing?.command
2686
+ if (
2687
+ command &&
2688
+ state.landing?.acknowledgedSeq !== command.seq &&
2689
+ (command.kind === 'land' || prState.state !== 'open' || !recoverLanding)
2690
+ )
2126
2691
  await store.append(record.slug, {
2127
2692
  actor: DISPATCHER,
2128
- type: autoMergeApplicationType(false),
2129
- payload: { commandSeq: autoMerge.commandSeq },
2693
+ type: 'landing.command-acknowledged',
2694
+ payload: { commandSeq: command.seq },
2130
2695
  })
2131
- }
2132
2696
 
2133
2697
  // A positive conflict re-enters reconcile before any enable attempt. In
2134
2698
  // particular, an ungated fallback can never race ahead of the conflict
2135
2699
  // event and its full post-reconcile verification cycle.
2136
- if (prState.state === 'open' && prState.mergeable === false) {
2700
+ if (
2701
+ !integration &&
2702
+ !recoverLanding &&
2703
+ prState.state === 'open' &&
2704
+ prState.mergeable === false
2705
+ ) {
2137
2706
  // Dedupe: a reduced prState of 'conflicted' means reconcile is already
2138
2707
  // pending (a `reconcile.completed` returns it to 'open').
2139
2708
  if (state.prState === 'conflicted') return
2140
2709
  const events = await source.history()
2141
2710
  const baseSha = await this.baseSha(baseBranchOf(events, this.deps.config))
2142
- const conflicted = await store.append(record.slug, {
2711
+ const _conflicted = await store.append(record.slug, {
2143
2712
  actor: DISPATCHER,
2144
2713
  type: 'pr.conflicted',
2145
2714
  payload: { baseSha },
2146
2715
  } satisfies EventWrite<'pr.conflicted'>)
2147
- events.push(conflicted)
2716
+ Object.assign(events, (await readBuildFacts(this.store, record.slug)).value)
2148
2717
  if (openWorkspace(events) === null && this.deps.workspaces.recovery !== undefined) {
2149
2718
  // The reconcile workspace is provisioned by the tracked background
2150
2719
  // continuation, whose tail re-attaches the build-runner; this tick
@@ -2165,55 +2734,388 @@ export class Dispatcher {
2165
2734
  // predicate. Only `applied` acknowledges native state. A direct merge is
2166
2735
  // owned solely by this janitor and only after the engine is parked at
2167
2736
  // awaiting-pr (all verify/finalize work complete).
2168
- if (prState.state === 'open' && autoMerge?.enabled === true) {
2169
- const result = await forge.setAutoMerge(workspacePath, pr.number, true)
2170
- if (result.kind === 'applied') {
2171
- await store.append(record.slug, {
2172
- actor: DISPATCHER,
2173
- type: autoMergeApplicationType(true),
2174
- payload: { commandSeq: autoMerge.commandSeq },
2175
- })
2176
- } else if (result.kind === 'deferred' && result.reason !== undefined) {
2737
+ const commandSeq = state.landing?.command?.seq ?? state.landing?.decision?.seq
2738
+ const canApply = async (): Promise<boolean> => {
2739
+ if (integration ? executionLeaseLive : state.sessions.open.length > 0) return false
2740
+ await store.refreshBuild(record.slug)
2741
+ const latest = await store.buildFacts(record.slug)
2742
+ if (integration) {
2743
+ const artifact = await store.getArtifact(record.slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
2744
+ const config = artifact
2745
+ ? composeBuildConfig(parseEffectiveBuildConfig(artifact), this.deps.config)
2746
+ : this.deps.config
2747
+ const candidate = latest.state
2748
+ if (
2749
+ !landingAuthorized(candidate.landing) ||
2750
+ candidate.landing?.decision?.seq !== state.landing?.decision?.seq ||
2751
+ candidate.status === 'paused' ||
2752
+ candidate.status === 'done' ||
2753
+ candidate.status === 'aborted' ||
2754
+ candidate.openEscalations.length ||
2755
+ candidate.pendingCommands.length ||
2756
+ !integrationVerified(candidate, config)
2757
+ )
2758
+ return false
2759
+ await this.observeIntegration(record.slug, true)
2760
+ if (!record.branch || !latest.state.baseBranch || !forge.compareBranches) return false
2761
+ const exact = await forge.compareBranches(latest.state.baseBranch, record.branch)
2762
+ const current = (await store.buildFacts(record.slug)).state
2763
+ const cycle = current.integration?.cycle
2764
+ return (
2765
+ landingAuthorized(current.landing) &&
2766
+ current.landing?.decision?.seq === state.landing?.decision?.seq &&
2767
+ current.status !== 'paused' &&
2768
+ current.status !== 'aborted' &&
2769
+ current.status !== 'done' &&
2770
+ !current.openEscalations.length &&
2771
+ !current.pendingCommands.length &&
2772
+ integrationVerified(current, config) &&
2773
+ cycle?.head === exact.headSha &&
2774
+ cycle.parent === exact.parentSha
2775
+ )
2776
+ }
2777
+ const decision = await this.decideBuild(record.slug, latest.state, latest.log, report)
2778
+ return (
2779
+ latest.state.pr?.number === pr.number &&
2780
+ latest.state.prState === 'open' &&
2781
+ landingAuthorized(latest.state.landing) &&
2782
+ latest.state.landing?.decision?.seq === state.landing?.decision?.seq &&
2783
+ sameLandingCandidate(await candidateOf(latest.state), state.landing?.decision?.candidate) &&
2784
+ decision?.kind === 'wait' &&
2785
+ decision.reason === 'awaiting-pr'
2786
+ )
2787
+ }
2788
+ const integrationPublicationDue =
2789
+ !integration ||
2790
+ prState.state === 'merged' ||
2791
+ this.integrationPollDue(
2792
+ this.integrationLandingPolls,
2793
+ record.slug,
2794
+ `${state.integration?.cycle?.id ?? ''}:${state.verify.results.at(-1)?.seq ?? ''}:${state.landing?.command?.seq ?? state.landing?.decision?.seq ?? ''}:${state.nodeComparison?.headSha ?? ''}:${state.nodeRestack?.observedParent?.sha ?? ''}`,
2795
+ )
2796
+ if (
2797
+ integrationPublicationDue &&
2798
+ nodeTarget &&
2799
+ (recoverLanding ||
2800
+ (prState.state === 'open' &&
2801
+ ((landingAuthorized(state.landing) && commandSeq !== undefined) ||
2802
+ (integration && state.integration?.intent !== undefined)))) &&
2803
+ !executionLeaseLive &&
2804
+ record.branch
2805
+ ) {
2806
+ if (target?.branch && target.branch === state.baseBranch) {
2807
+ if (!recoverLanding && !(await canApply())) {
2808
+ const intent = state.integration?.intent
2809
+ if (integration && intent)
2810
+ await store.append(record.slug, {
2811
+ actor: KERNEL,
2812
+ type: 'integration.abandoned',
2813
+ payload: {
2814
+ id: intent.id,
2815
+ reason: 'Nested landing eligibility changed before reservation',
2816
+ },
2817
+ })
2818
+ return
2819
+ }
2820
+ const preflight = recoverLanding
2821
+ ? undefined
2822
+ : await preflightNodeLanding(
2823
+ this.kernelForge(),
2824
+ workspacePath,
2825
+ pr.number,
2826
+ record.branch,
2827
+ target.branch,
2828
+ )
2829
+ const reason =
2830
+ preflight ??
2831
+ (await this.withKernelRepository((kernelPath) =>
2832
+ landIntoNode({
2833
+ store,
2834
+ forge: this.kernelForge(),
2835
+ exec: forge.kernelExec ?? this.deps.exec,
2836
+ workspacePath: kernelPath,
2837
+ slug: record.slug,
2838
+ node: target.slug,
2839
+ branch: record.branch!,
2840
+ destination: target.branch!,
2841
+ pr: pr.number,
2842
+ holder: this.deps.ids('node-writer'),
2843
+ id: this.deps.ids('node-landing').replaceAll('_', '-'),
2844
+ ...(integration
2845
+ ? {
2846
+ stack: {
2847
+ head: state.integration!.cycle!.head,
2848
+ parent: state.integration!.cycle!.parent,
2849
+ cycle: state.integration!.cycle!.id,
2850
+ },
2851
+ }
2852
+ : {}),
2853
+ eligible: canApply,
2854
+ }),
2855
+ ))
2856
+ if (reason && commandSeq !== undefined)
2857
+ await recordAutoMergeDeferralObservation(
2858
+ store,
2859
+ record.slug,
2860
+ reason,
2861
+ pr.number,
2862
+ commandSeq,
2863
+ this.deps.ids('obs'),
2864
+ )
2865
+ if ((await store.buildFacts(target.slug)).state.nodeRestack?.active?.source === record.slug)
2866
+ return
2867
+ await store.refreshBuild(record.slug)
2868
+ state = (await store.buildFacts(record.slug)).state
2869
+ if (state.prState === 'merged') {
2870
+ if (state.mergedSha) prState = { state: 'merged', sha: state.mergedSha }
2871
+ }
2872
+ } else if (commandSeq !== undefined) {
2177
2873
  await recordAutoMergeDeferralObservation(
2178
2874
  store,
2179
2875
  record.slug,
2180
- result.reason,
2876
+ {
2877
+ code: 'unproven-gate-state',
2878
+ detail:
2879
+ 'Frozen destination node generation is unavailable or disagrees with its branch. Native landing is withheld; human action required.',
2880
+ },
2181
2881
  pr.number,
2182
- autoMerge.commandSeq,
2882
+ commandSeq,
2183
2883
  this.deps.ids('obs'),
2184
2884
  )
2185
- } else if (result.kind === 'ungated' && prState.mergeable === true) {
2186
- // Re-read at the last possible point. A cancellation, replacement
2187
- // command, newly due pipeline work, or application fact suppresses
2188
- // this attempt; the next tick reclassifies from fresh forge state.
2189
- await store.refreshBuild(record.slug)
2190
- const latest = await store.buildFacts(record.slug)
2191
- const latestState = latest.state
2192
- const latestIntent = pendingAutoMerge(latestState)
2193
- const decision = await this.decideBuild(record.slug, latest.state, latest.log, report)
2194
- if (
2195
- latestState.pr?.number === pr.number &&
2196
- latestIntent?.enabled === true &&
2197
- latestIntent.commandSeq === autoMerge.commandSeq &&
2198
- decision?.kind === 'wait' &&
2199
- decision.reason === 'awaiting-pr'
2200
- ) {
2201
- await forge.squashMerge(workspacePath, pr.number, result.headSha)
2885
+ }
2886
+ }
2887
+ const native = state.landing?.native
2888
+ const retry =
2889
+ native?.retry &&
2890
+ native.decisionSeq === state.landing?.decision?.seq &&
2891
+ native.commandSeq === state.landing?.command?.seq &&
2892
+ sameLandingCandidate(native.candidate, state.landing?.decision?.candidate)
2893
+ ? native.retry
2894
+ : undefined
2895
+ if (
2896
+ !integration &&
2897
+ !nodeTarget &&
2898
+ prState.state === 'open' &&
2899
+ landingAuthorized(state.landing) &&
2900
+ (prState.nativeAutoMerge === false ||
2901
+ !nativeLandingApplied(state.landing) ||
2902
+ !!state.landing?.nativeEnablePending) &&
2903
+ (!retry || Date.parse(retry.after) <= this.deps.clock().getTime()) &&
2904
+ commandSeq !== undefined &&
2905
+ (await canApply())
2906
+ ) {
2907
+ const decision = state.landing!.decision!
2908
+ // The provider checks eligibility immediately before mutating. Inspection
2909
+ // deferrals therefore leave no uncertainty facts on quiet polls.
2910
+ let enableSeq = state.landing?.nativeEnablePending
2911
+ const settleFailedEnable = async () => {
2912
+ if (enableSeq === undefined) return
2913
+ const cancelled = await forge.setAutoMerge(workspacePath, pr.number, false)
2914
+ if (cancelled.kind !== 'applied')
2915
+ throw new Error('Native landing cancellation unconfirmed; retrying')
2916
+ const attempt = (retry?.attempt ?? 0) + 1
2917
+ await store.append(record.slug, {
2918
+ actor: DISPATCHER,
2919
+ type: 'landing.native-applied',
2920
+ payload: {
2921
+ enabled: false,
2922
+ enableSeq,
2923
+ candidate: decision.candidate,
2924
+ decisionSeq: decision.seq,
2925
+ ...(state.landing?.command ? { commandSeq: state.landing.command.seq } : {}),
2926
+ retry: {
2927
+ attempt,
2928
+ after: new Date(
2929
+ this.deps.clock().getTime() +
2930
+ Math.min(300_000, 30_000 * 2 ** Math.min(attempt - 1, 4)),
2931
+ ).toISOString(),
2932
+ },
2933
+ },
2934
+ })
2935
+ }
2936
+ const result =
2937
+ prState.nativeAutoMerge === true && !nativeCancelled
2938
+ ? { kind: 'applied' as const }
2939
+ : await forge
2940
+ .setAutoMerge(workspacePath, pr.number, true, {
2941
+ buildSlug: record.slug,
2942
+ baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
2943
+ canApply: async () => {
2944
+ if (!(await canApply())) return false
2945
+ if (enableSeq === undefined)
2946
+ enableSeq = (
2947
+ await store.append(record.slug, {
2948
+ actor: DISPATCHER,
2949
+ type: 'landing.native-enable-started',
2950
+ payload: {},
2951
+ })
2952
+ ).seq
2953
+ return true
2954
+ },
2955
+ })
2956
+ .catch(async (error: unknown) => {
2957
+ await settleFailedEnable()
2958
+ throw error
2959
+ })
2960
+ // Only an attempt that reached the mutation guard needs cancellation.
2961
+ // Persist retry timing with its receipt so restart cannot reset backoff.
2962
+ if (result.kind !== 'applied') await settleFailedEnable()
2963
+ if (result.kind === 'applied') {
2964
+ const latest = (await store.buildFacts(record.slug)).state
2965
+ if (await canApply()) {
2966
+ if (
2967
+ latest.landing?.nativeEnablePending ||
2968
+ latest.landing?.native?.enabled !== true ||
2969
+ latest.landing.native.decisionSeq !== decision.seq ||
2970
+ latest.landing.native.commandSeq !== latest.landing.command?.seq
2971
+ )
2972
+ await store.append(record.slug, {
2973
+ actor: DISPATCHER,
2974
+ type: 'landing.native-applied',
2975
+ payload: {
2976
+ enabled: true,
2977
+ ...(enableSeq !== undefined ? { enableSeq } : {}),
2978
+ candidate: decision.candidate,
2979
+ decisionSeq: decision.seq,
2980
+ ...(latest.landing?.command ? { commandSeq: latest.landing.command.seq } : {}),
2981
+ },
2982
+ })
2983
+ } else {
2984
+ // Enable may have won after cancellation. Repair immediately, and
2985
+ // again on the next poll if this process dies at this boundary.
2986
+ const cancelled = await forge.setAutoMerge(workspacePath, pr.number, false)
2987
+ if (cancelled.kind === 'applied')
2988
+ await store.append(record.slug, {
2989
+ actor: DISPATCHER,
2990
+ type: 'landing.native-applied',
2991
+ payload: { enabled: false, ...(enableSeq !== undefined ? { enableSeq } : {}) },
2992
+ })
2202
2993
  }
2994
+ } else if (result.kind === 'deferred' && result.reason) {
2995
+ await recordAutoMergeDeferralObservation(
2996
+ store,
2997
+ record.slug,
2998
+ result.reason,
2999
+ pr.number,
3000
+ commandSeq,
3001
+ this.deps.ids('obs'),
3002
+ )
3003
+ } else if (result.kind === 'ungated' && prState.mergeable === true && (await canApply())) {
3004
+ await forge.squashMerge(workspacePath, pr.number, result.headSha, {
3005
+ buildSlug: record.slug,
3006
+ baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
3007
+ })
2203
3008
  }
2204
3009
  }
2205
3010
 
3011
+ if (
3012
+ integration &&
3013
+ integrationPublicationDue &&
3014
+ !nodeTarget &&
3015
+ record.branch &&
3016
+ !executionLeaseLive &&
3017
+ (state.integration?.intent || (commandSeq !== undefined && (await canApply())))
3018
+ ) {
3019
+ const cycle = state.integration?.cycle
3020
+ const intent = state.integration?.intent
3021
+ if (cycle && commandSeq !== undefined)
3022
+ await this.withKernelRepository((path) =>
3023
+ landIntegrationRoot({
3024
+ store,
3025
+ forge: this.kernelForge(),
3026
+ exec: forge.kernelExec ?? this.deps.exec,
3027
+ workspacePath: path,
3028
+ slug: record.slug,
3029
+ branch: record.branch!,
3030
+ destination: state.baseBranch!,
3031
+ pr: pr.number,
3032
+ holder: this.deps.ids('node-writer'),
3033
+ id: this.deps.ids('integration-landing'),
3034
+ ...(intent?.commandSeq !== undefined ? { commandSeq: intent.commandSeq } : {}),
3035
+ decisionSeq: intent?.decisionSeq ?? state.landing?.decision?.seq,
3036
+ head: intent?.head ?? cycle.head,
3037
+ parent: intent?.parent ?? cycle.parent,
3038
+ cycle: intent?.cycle ?? cycle.id,
3039
+ eligible: canApply,
3040
+ }),
3041
+ )
3042
+ state = (await store.buildFacts(record.slug)).state
3043
+ if (state.prState === 'merged' && state.mergedSha)
3044
+ prState = { state: 'merged', sha: state.mergedSha }
3045
+ }
3046
+ if (integration && prState.state === 'merged' && !state.integration?.landing) {
3047
+ const head = prState.headSha
3048
+ await store.append(record.slug, {
3049
+ actor: DISPATCHER,
3050
+ type: 'integration.landed',
3051
+ payload: {
3052
+ head: head ?? 'unknown',
3053
+ landed: prState.sha,
3054
+ provenance: 'human',
3055
+ fenced: false,
3056
+ verified: !!head && integrationHeadVerified(state, head),
3057
+ },
3058
+ })
3059
+ }
3060
+
3061
+ if (
3062
+ integration &&
3063
+ (prState.state === 'merged' || prState.state === 'closed') &&
3064
+ record.branch &&
3065
+ !executionLeaseLive
3066
+ ) {
3067
+ if (
3068
+ !(await this.withKernelRepository((kernelPath) =>
3069
+ settleClosedNode({
3070
+ store,
3071
+ forge: this.kernelForge(),
3072
+ exec: forge.kernelExec ?? this.deps.exec,
3073
+ workspacePath: kernelPath,
3074
+ slug: record.slug,
3075
+ branch: record.branch!,
3076
+ holder: this.deps.ids('node-writer'),
3077
+ }),
3078
+ ))
3079
+ )
3080
+ return
3081
+ }
2206
3082
  switch (prState.state) {
2207
3083
  case 'merged': {
2208
3084
  if (executionLeaseLive) return
2209
3085
  const events = await source.history()
3086
+ if (!landingAuthorized(state.landing) && !state.landing?.forgeMerge) {
3087
+ // Use our durable native-effect evidence, never provider origin.
3088
+ // Absence of a confirmed disabled receipt is indeterminate too.
3089
+ const classification =
3090
+ state.landing?.native?.enabled === false && !state.landing.nativeEnablePending
3091
+ ? ('human' as const)
3092
+ : ('possible-stale-enable' as const)
3093
+ const overrodeHold = state.landing?.command?.kind === 'hold'
3094
+ await store.append(record.slug, {
3095
+ actor: KERNEL,
3096
+ type: 'landing.forge-merged',
3097
+ payload: { classification, overrodeHold },
3098
+ })
3099
+ if (classification === 'possible-stale-enable')
3100
+ await store.append(record.slug, {
3101
+ actor: KERNEL,
3102
+ type: 'observation.recorded',
3103
+ payload: {
3104
+ id: this.deps.ids('obs'),
3105
+ kind: 'followup',
3106
+ summary:
3107
+ 'Landing contrary to policy: native auto-merge was armed or indeterminate when the forge merged without landing authorization. Operator attention required; the target has not been rewritten.',
3108
+ refs: ['landing-contrary-to-policy'],
3109
+ },
3110
+ })
3111
+ }
2210
3112
  // Emit the fact once (a crash between steps re-runs this block; the
2211
3113
  // reduced prState dedupes the event, the log dedupes the release).
2212
3114
  if (state.prState !== 'merged') {
2213
3115
  await store.append(record.slug, {
2214
3116
  actor: DISPATCHER,
2215
3117
  type: 'pr.merged',
2216
- payload: { sha: prState.sha },
3118
+ payload: await this.mergeEvidence(record, workspacePath, prState.sha, state.kind),
2217
3119
  } satisfies EventWrite<'pr.merged'>)
2218
3120
  }
2219
3121
  await this.releaseWorkspace(record.slug, events)
@@ -2270,12 +3172,9 @@ export class Dispatcher {
2270
3172
  * is deliberately post-terminal and best-effort: a provider, timeout, or
2271
3173
  * store failure cannot roll back build.completed/ticket/workspace work.
2272
3174
  * Pending handles remain derivable and are retried on every later tick. */
2273
- private async reclaimPrAttachments(slug: string, events: AbEvent[]): Promise<void> {
2274
- for (const hosted of pendingPrAttachmentReclaims(events)) {
2275
- const priorAttempts = events.filter(
2276
- (event) =>
2277
- event.type === 'pr-attachment.reclaim-failed' && event.payload.hostedSeq === hosted.seq,
2278
- ).length
3175
+ private async reclaimPrAttachments(slug: string, events: CurrentBuildFacts): Promise<void> {
3176
+ for (const hosted of events.pendingAttachments) {
3177
+ const priorAttempts = events.reclaimCounts[String(hosted.seq)] ?? 0
2279
3178
  try {
2280
3179
  const capability = this.deps.forge.prAttachments
2281
3180
  if (capability === undefined) {
@@ -2315,13 +3214,13 @@ export class Dispatcher {
2315
3214
  }
2316
3215
  }
2317
3216
 
2318
- private recoveryCheckpoint(events: AbEvent[]): string | undefined {
2319
- return recoveryCheckpointReducer.reduce(events)
3217
+ private recoveryCheckpoint(events: CurrentBuildFacts): string | undefined {
3218
+ return events.recoveryCheckpoint
2320
3219
  }
2321
3220
 
2322
3221
  private async recordInfrastructureFailure(
2323
3222
  slug: string,
2324
- events: AbEvent[],
3223
+ events: CurrentBuildFacts,
2325
3224
  input: {
2326
3225
  provider: string
2327
3226
  workspaceRef: string
@@ -2330,8 +3229,8 @@ export class Dispatcher {
2330
3229
  cleanupPending: boolean
2331
3230
  },
2332
3231
  ): Promise<void> {
2333
- const execution = [...events].reverse().find((event) => event.type === 'execution.started')
2334
- const appended = await appendInfrastructureFailure(
3232
+ const execution = events.state.executions.at(-1)
3233
+ const _appended = await appendInfrastructureFailure(
2335
3234
  { store: this.store, ids: this.deps.ids },
2336
3235
  {
2337
3236
  slug,
@@ -2339,22 +3238,19 @@ export class Dispatcher {
2339
3238
  maxAttempts: this.deps.config.policy.maxInfrastructureAttempts,
2340
3239
  provider: input.provider,
2341
3240
  workspaceRef: input.workspaceRef,
2342
- instance:
2343
- execution?.type === 'execution.started'
2344
- ? execution.payload.instance
2345
- : 'dispatcher-recovery',
2346
- ...(execution?.type === 'execution.started' && execution.payload.environmentId !== undefined
2347
- ? { environmentId: execution.payload.environmentId }
3241
+ instance: execution !== undefined ? execution.instance : 'dispatcher-recovery',
3242
+ ...(execution !== undefined && execution.environmentId !== undefined
3243
+ ? { environmentId: execution.environmentId }
2348
3244
  : {}),
2349
- ...(execution?.type === 'execution.started' && execution.payload.sessionId !== undefined
2350
- ? { sessionId: execution.payload.sessionId }
3245
+ ...(execution !== undefined && execution.sessionId !== undefined
3246
+ ? { sessionId: execution.sessionId }
2351
3247
  : {}),
2352
3248
  operation: input.operation,
2353
3249
  error: input.error,
2354
3250
  cleanupPending: input.cleanupPending,
2355
3251
  },
2356
3252
  )
2357
- events.push(...appended)
3253
+ Object.assign(events, (await readBuildFacts(this.store, slug)).value)
2358
3254
  }
2359
3255
 
2360
3256
  /** The provider that owns a recorded workspace: the one named on its
@@ -2370,7 +3266,7 @@ export class Dispatcher {
2370
3266
  * only after exact-name cleanup is durably acknowledged. */
2371
3267
  private async reapStaleWorkspace(
2372
3268
  slug: string,
2373
- events: AbEvent[],
3269
+ events: CurrentBuildFacts,
2374
3270
  reason: 'pause' | 'blocked' | 'replacement',
2375
3271
  ): Promise<boolean> {
2376
3272
  const open = openWorkspace(events)
@@ -2381,18 +3277,13 @@ export class Dispatcher {
2381
3277
  // publication's fate BEFORE the destructive reap. The guard's append
2382
3278
  // failure propagates — a stale workspace with an unrecorded pending
2383
3279
  // request is never reaped (the next tick retries).
2384
- events = await settlePublicationBeforeRelease(
3280
+ events = await settlePublicationFactsBeforeRelease(
2385
3281
  { store: this.store, settlePublication: this.settlePublication },
2386
3282
  slug,
2387
3283
  events,
2388
3284
  reason,
2389
3285
  )
2390
- const attempt =
2391
- events.filter(
2392
- (event) =>
2393
- event.type === 'infrastructure.cleanup-attempted' &&
2394
- event.payload.workspaceRef === open.ref,
2395
- ).length + 1
3286
+ const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
2396
3287
  try {
2397
3288
  const outcome = await recovery.reap({
2398
3289
  provider: open.provider,
@@ -2401,7 +3292,7 @@ export class Dispatcher {
2401
3292
  ...(open.localPath !== undefined ? { localPath: open.localPath } : {}),
2402
3293
  branch: open.branch,
2403
3294
  })
2404
- const cleaned = await this.store.append(slug, {
3295
+ const _cleaned = await this.store.append(slug, {
2405
3296
  actor: DISPATCHER,
2406
3297
  type: 'infrastructure.cleanup-attempted',
2407
3298
  payload: {
@@ -2413,17 +3304,17 @@ export class Dispatcher {
2413
3304
  snapshots: outcome.snapshots,
2414
3305
  },
2415
3306
  })
2416
- events.push(cleaned)
2417
- const released = await this.store.append(slug, {
3307
+ Object.assign(events, (await readBuildFacts(this.store, slug)).value)
3308
+ const _released = await this.store.append(slug, {
2418
3309
  actor: DISPATCHER,
2419
3310
  type: 'workspace.released',
2420
3311
  payload: { ref: open.ref, reason },
2421
3312
  })
2422
- events.push(released)
3313
+ Object.assign(events, (await readBuildFacts(this.store, slug)).value)
2423
3314
  return true
2424
3315
  } catch (error) {
2425
3316
  const message = error instanceof Error ? error.message : String(error)
2426
- const failed = await this.store.append(slug, {
3317
+ const _failed = await this.store.append(slug, {
2427
3318
  actor: DISPATCHER,
2428
3319
  type: 'infrastructure.cleanup-attempted',
2429
3320
  payload: {
@@ -2435,7 +3326,7 @@ export class Dispatcher {
2435
3326
  error: message || 'cleanup failed without an error message',
2436
3327
  },
2437
3328
  })
2438
- events.push(failed)
3329
+ Object.assign(events, (await readBuildFacts(this.store, slug)).value)
2439
3330
  await this.recordInfrastructureFailure(slug, events, {
2440
3331
  provider: open.provider,
2441
3332
  workspaceRef: open.ref,
@@ -2451,7 +3342,7 @@ export class Dispatcher {
2451
3342
  * append `workspace.released`. Log-deduped, so re-runs are no-ops. */
2452
3343
  private async releaseWorkspace(
2453
3344
  slug: string,
2454
- events: AbEvent[],
3345
+ events: CurrentBuildFacts,
2455
3346
  reason: 'completion' | 'abort' | 'pause' | 'blocked' | 'replacement' | 'discard' = 'completion',
2456
3347
  ): Promise<AbEvent | undefined> {
2457
3348
  const open = openWorkspace(events)
@@ -2470,7 +3361,7 @@ export class Dispatcher {
2470
3361
  // pending publication BEFORE any provider cleanup call, while the
2471
3362
  // workspace still exists. The guard's append failure propagates — the
2472
3363
  // release never proceeds past an unrecorded pending request.
2473
- events = await settlePublicationBeforeRelease(
3364
+ events = await settlePublicationFactsBeforeRelease(
2474
3365
  { store: this.store, settlePublication: this.settlePublication },
2475
3366
  slug,
2476
3367
  events,
@@ -2478,15 +3369,10 @@ export class Dispatcher {
2478
3369
  )
2479
3370
  const recovery = owner.recovery
2480
3371
  if (recovery !== undefined) {
2481
- const attempt =
2482
- events.filter(
2483
- (event) =>
2484
- event.type === 'infrastructure.cleanup-attempted' &&
2485
- event.payload.workspaceRef === open.ref,
2486
- ).length + 1
3372
+ const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
2487
3373
  try {
2488
3374
  const outcome = await recovery.reap(handle)
2489
- const cleaned = await this.store.append(slug, {
3375
+ const _cleaned = await this.store.append(slug, {
2490
3376
  actor: DISPATCHER,
2491
3377
  type: 'infrastructure.cleanup-attempted',
2492
3378
  payload: {
@@ -2498,10 +3384,10 @@ export class Dispatcher {
2498
3384
  snapshots: outcome.snapshots,
2499
3385
  },
2500
3386
  })
2501
- events.push(cleaned)
3387
+ Object.assign(events, (await readBuildFacts(this.store, slug)).value)
2502
3388
  } catch (error) {
2503
3389
  const message = error instanceof Error ? error.message : String(error)
2504
- const failed = await this.store.append(slug, {
3390
+ const _failed = await this.store.append(slug, {
2505
3391
  actor: DISPATCHER,
2506
3392
  type: 'infrastructure.cleanup-attempted',
2507
3393
  payload: {
@@ -2513,7 +3399,7 @@ export class Dispatcher {
2513
3399
  error: message || 'cleanup failed without an error message',
2514
3400
  },
2515
3401
  })
2516
- events.push(failed)
3402
+ Object.assign(events, (await readBuildFacts(this.store, slug)).value)
2517
3403
  await this.recordInfrastructureFailure(slug, events, {
2518
3404
  provider: open.provider,
2519
3405
  workspaceRef: open.ref,
@@ -2590,14 +3476,23 @@ export class Dispatcher {
2590
3476
  ticket: TicketRef,
2591
3477
  repo: string,
2592
3478
  seed:
2593
- | { autoMergeUser?: string; autoMergeDefaultSeq?: number; assets?: PinnedAsset[] }
3479
+ | {
3480
+ autoMergeUser?: string
3481
+ autoMergeDefaultSeq?: number
3482
+ assets?: PinnedAsset[]
3483
+ kind?: 'work' | 'node'
3484
+ target?: EventPayload<'build.created'>['target']
3485
+ baseBranch?: string
3486
+ }
2594
3487
  | undefined,
2595
3488
  ): EventPayload<'build.created'> {
2596
3489
  const { config } = this.deps
2597
3490
  return {
2598
3491
  ticket,
2599
3492
  repo,
2600
- baseBranch: config.baseBranch,
3493
+ baseBranch: seed?.baseBranch ?? config.baseBranch,
3494
+ ...(seed?.kind !== undefined ? { kind: seed.kind } : {}),
3495
+ ...(seed?.target !== undefined ? { target: seed.target } : {}),
2601
3496
  ...(seed?.autoMergeUser !== undefined ? { autoMergeRequestedBy: seed.autoMergeUser } : {}),
2602
3497
  ...(seed?.autoMergeDefaultSeq !== undefined
2603
3498
  ? { autoMergeDefaultSeq: seed.autoMergeDefaultSeq }
@@ -2639,9 +3534,9 @@ export class Dispatcher {
2639
3534
  if (!(await this.dispatchBudget(record.slug))) return 'parked'
2640
3535
  let stage: EventPayload<'dispatch.failed'>['stage'] = 'create'
2641
3536
  try {
2642
- let events = await store.getEvents(record.slug)
2643
- if (!events.some((event) => event.type === 'build.created')) {
2644
- if (events.length !== 0 || record.ticket === undefined) {
3537
+ let events = (await readBuildFacts(store, record.slug)).value
3538
+ if (events.created === undefined) {
3539
+ if (events.state.lastSeq !== 0 || record.ticket === undefined) {
2645
3540
  throw new Error(
2646
3541
  'build record lacks the immutable ticket facts needed to reconstruct build.created',
2647
3542
  )
@@ -2664,31 +3559,15 @@ export class Dispatcher {
2664
3559
  type: 'build.created',
2665
3560
  payload: this.buildCreatedPayload(record.ticket, record.repo, { ...seed, assets }),
2666
3561
  })
2667
- events = await store.getEvents(record.slug)
2668
- if (!events.some((event) => event.type === 'build.created')) {
3562
+ events = (await readBuildFacts(store, record.slug)).value
3563
+ if (events.created === undefined) {
2669
3564
  throw new Error('build.created reconstruction lost its conditional append race')
2670
3565
  }
2671
3566
  }
2672
3567
 
2673
- const created = events.find((event) => event.type === 'build.created')
2674
- const autoMergeUser = seed?.autoMergeUser ?? created?.payload.autoMergeRequestedBy
2675
- // The claim's sampled default fact, for the request's fan-out provenance:
2676
- // the seed's own value first (this dispatch created the build), else the
2677
- // durable `build.created` fact a recovery pass resumes from.
2678
- const autoMergeDefaultSeq = seed?.autoMergeDefaultSeq ?? created?.payload.autoMergeDefaultSeq
2679
- if (
2680
- autoMergeUser !== undefined &&
2681
- !events.some((event) => event.type === 'build.auto-merge-requested')
2682
- ) {
2683
- await store.append(record.slug, {
2684
- actor: humanActor(autoMergeUser),
2685
- type: 'build.auto-merge-requested',
2686
- payload: {
2687
- ...(autoMergeDefaultSeq !== undefined ? { defaultSeq: autoMergeDefaultSeq } : {}),
2688
- },
2689
- })
2690
- events = await store.getEvents(record.slug)
2691
- }
3568
+ const created = events.created
3569
+ if (created.payload.kind === 'node')
3570
+ return this.completeDispatchBoundaries(record, seed, report, launched)
2692
3571
 
2693
3572
  stage = 'workspace'
2694
3573
  if (openWorkspace(events) === null) {
@@ -2702,9 +3581,7 @@ export class Dispatcher {
2702
3581
  launched.add(record.slug)
2703
3582
  return 'deferred'
2704
3583
  }
2705
- const priorGenerations = events.filter(
2706
- (event) => event.type === 'workspace.provisioned',
2707
- ).length
3584
+ const priorGenerations = events.workspaceGenerations
2708
3585
  const handle = await this.deps.workspaces.provision({
2709
3586
  // Local providers provision FROM the physical checkout; remote
2710
3587
  // providers ignore the value (their host seams are injected).
@@ -2713,7 +3590,7 @@ export class Dispatcher {
2713
3590
  branch: record.branch ?? `ab/${record.slug}`,
2714
3591
  ...(priorGenerations > 0
2715
3592
  ? {
2716
- revision: this.recoveryCheckpoint(events),
3593
+ revision: events.state.integration?.cycle?.head ?? this.recoveryCheckpoint(events),
2717
3594
  generation: priorGenerations,
2718
3595
  }
2719
3596
  : {}),
@@ -2731,10 +3608,10 @@ export class Dispatcher {
2731
3608
  base: handle.base,
2732
3609
  },
2733
3610
  } satisfies EventWrite<'workspace.provisioned'>)
2734
- events = await store.getEvents(record.slug)
3611
+ events = (await readBuildFacts(store, record.slug)).value
2735
3612
  }
2736
3613
  } catch (error) {
2737
- const events = await store.getEvents(record.slug)
3614
+ const events = (await readBuildFacts(store, record.slug)).value
2738
3615
  if (stage === 'workspace' && this.deps.workspaces.recovery !== undefined) {
2739
3616
  const open = openWorkspace(events)
2740
3617
  await this.recordInfrastructureFailure(record.slug, events, {
@@ -2745,7 +3622,7 @@ export class Dispatcher {
2745
3622
  cleanupPending: true,
2746
3623
  })
2747
3624
  }
2748
- const attempt = events.filter((event) => event.type === 'dispatch.failed').length + 1
3625
+ const attempt = events.dispatchFailureCount + 1
2749
3626
  const message = (error instanceof Error ? error.message : String(error)).trim()
2750
3627
  await store.append(record.slug, {
2751
3628
  actor: DISPATCHER,
@@ -2785,12 +3662,10 @@ export class Dispatcher {
2785
3662
  let stage: EventPayload<'dispatch.failed'>['stage'] = 'spec'
2786
3663
  let authored = false
2787
3664
  try {
2788
- const events = await store.getEvents(record.slug)
2789
- const state = reduceBuild(events)
3665
+ const events = (await readBuildFacts(store, record.slug)).value
3666
+ const state = events.state
2790
3667
  if (state.status !== 'queued' || state.discardRequest !== undefined) return 'parked'
2791
- if (
2792
- !events.some((event) => event.type === 'spec.imported' || event.type === 'spec.authored')
2793
- ) {
3668
+ if (!events.specRecorded) {
2794
3669
  let ticket: Ticket
2795
3670
  if (seed?.ticket !== undefined) {
2796
3671
  ticket = seed.ticket
@@ -2848,10 +3723,7 @@ export class Dispatcher {
2848
3723
  }
2849
3724
 
2850
3725
  stage = 'comment'
2851
- if (
2852
- record.ticket !== undefined &&
2853
- !events.some((event) => event.type === 'dispatch.comment-posted')
2854
- ) {
3726
+ if (record.ticket !== undefined && !events.commentPosted) {
2855
3727
  await this.deps.tickets.comment(record.ticket.id, `build ${record.slug} dispatched`)
2856
3728
  await store.append(record.slug, {
2857
3729
  actor: DISPATCHER,
@@ -2860,12 +3732,21 @@ export class Dispatcher {
2860
3732
  })
2861
3733
  }
2862
3734
 
3735
+ if (state.kind === 'node') {
3736
+ stage = 'branch'
3737
+ await store.refreshBuild(record.slug)
3738
+ const current = (await store.buildFacts(record.slug)).state
3739
+ if (current.status !== 'queued' || current.pendingCommands.length > 0) return 'parked'
3740
+ await this.openNode(record, current)
3741
+ return 'completed'
3742
+ }
3743
+
2863
3744
  stage = 'launch'
2864
3745
  // Discard validation and recovery selection happened before several
2865
3746
  // provider awaits. Re-read immediately before launch so a request made
2866
3747
  // during those boundaries parks cleanly for the next janitor pass.
2867
3748
  await store.refreshBuild(record.slug)
2868
- const launchState = reduceBuild(await store.getEvents(record.slug))
3749
+ const launchState = (await readBuildFacts(store, record.slug)).value.state
2869
3750
  if (launchState.status !== 'queued' || launchState.discardRequest !== undefined) {
2870
3751
  return 'parked'
2871
3752
  }
@@ -2874,8 +3755,8 @@ export class Dispatcher {
2874
3755
  if (authored && report !== undefined) report.authored += 1
2875
3756
  return 'completed'
2876
3757
  } catch (error) {
2877
- const events = await store.getEvents(record.slug)
2878
- const attempt = events.filter((event) => event.type === 'dispatch.failed').length + 1
3758
+ const events = (await readBuildFacts(store, record.slug)).value
3759
+ const attempt = events.dispatchFailureCount + 1
2879
3760
  const message = (error instanceof Error ? error.message : String(error)).trim()
2880
3761
  await store.append(record.slug, {
2881
3762
  actor: DISPATCHER,
@@ -3049,10 +3930,16 @@ export class Dispatcher {
3049
3930
  const decision = await this.decideBuild(record.slug, state, facts.log, report)
3050
3931
  if (decision === undefined) continue
3051
3932
  if (state.status === 'done' || state.status === 'aborted') continue
3933
+ if (
3934
+ state.kind === 'node' &&
3935
+ (!integrationCurrent(state) || facts.workspace === null) &&
3936
+ decision.kind !== 'wait'
3937
+ )
3938
+ continue // cascade owns node runner admission
3052
3939
  // Raw history, read at most once and only by a branch that acts on it.
3053
- let loaded: AbEvent[] | undefined
3054
- const history = async (): Promise<AbEvent[]> => {
3055
- loaded ??= await this.store.getEvents(record.slug)
3940
+ let loaded: CurrentBuildFacts | undefined
3941
+ const history = async (): Promise<CurrentBuildFacts> => {
3942
+ loaded ??= (await readBuildFacts(this.store, record.slug)).value
3056
3943
  return loaded
3057
3944
  }
3058
3945
  // Liveness gate (durable supervision): a recorded execution the provider
@@ -3136,7 +4023,7 @@ export class Dispatcher {
3136
4023
  if (
3137
4024
  facts.workspace === null &&
3138
4025
  this.deps.workspaces.recovery !== undefined &&
3139
- (await history()).some((event) => event.type === 'workspace.provisioned')
4026
+ (await history()).workspaceGenerations > 0
3140
4027
  ) {
3141
4028
  const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
3142
4029
  if (kicked === 'kicked') {
@@ -3179,7 +4066,14 @@ export class Dispatcher {
3179
4066
  const activeRefs: TicketRef[] = []
3180
4067
  for (const { record, digest } of await this.repoBuildDigests()) {
3181
4068
  if (digest.terminal === undefined) {
3182
- active += 1
4069
+ if (
4070
+ digest.kind !== 'node' ||
4071
+ (await this.store.buildFacts(record.slug)).state.nodeRestack?.conflict ||
4072
+ (integrationNeedsRunner((await this.store.buildFacts(record.slug)).state) &&
4073
+ (this.hasLiveExecutionLease(record) ||
4074
+ (await this.store.buildFacts(record.slug)).workspace !== null))
4075
+ )
4076
+ active += 1
3183
4077
  if (record.ticket) activeRefs.push(record.ticket)
3184
4078
  }
3185
4079
  }
@@ -3189,17 +4083,18 @@ export class Dispatcher {
3189
4083
  // standing queue-depth report and must stay honest exactly when the
3190
4084
  // dispatcher is saturated. Sources that keep a claimed ticket in the
3191
4085
  // ready state are deduped against the active builds embodying them.
3192
- await this.store.refreshJournal()
3193
- const journalBeforeReady = this.store.recordedJournal()
4086
+ const journalBeforeReady = this.store.repositoryFacts().harvest
3194
4087
  const listing = await this.listReady()
3195
4088
  const activeTicketIds = await this.activeTicketIdentities(activeRefs, listing.tickets)
3196
- await this.store.refreshJournal()
3197
- const journalAfterReady = this.store.recordedJournal()
3198
- if (reduceTicketSourceHealth(journalAfterReady)?.cause === 'ready-scan-failed') {
4089
+ // A provider listing can race reservation and blocker filing. Preserve
4090
+ // the before/after union, refreshing once only when admission is possible.
4091
+ if (listing.tickets.length > 0) await this.store.refreshJournal()
4092
+ const journalAfterReady = this.store.repositoryFacts()
4093
+ if (journalAfterReady.health?.cause === 'ready-scan-failed') {
3199
4094
  await this.sourceCondition(undefined, 'ready-scan')
3200
4095
  }
3201
4096
  const creationHolds = new Map(
3202
- harvestCreationsDuringReadyScan(journalBeforeReady, journalAfterReady).map((creation) => [
4097
+ harvestCreationsFromStates(journalBeforeReady, journalAfterReady.harvest).map((creation) => [
3203
4098
  creation.creationKey.toLowerCase(),
3204
4099
  creation,
3205
4100
  ]),
@@ -3231,7 +4126,7 @@ export class Dispatcher {
3231
4126
  // still runs either way, so the standing queue-depth report stays honest —
3232
4127
  // this only declines to claim a ticket into a build that would immediately
3233
4128
  // sit held.
3234
- if (capacity <= 0 || paused) {
4129
+ if (paused || (capacity <= 0 && !ready.some((ticket) => ticket.kind === 'node'))) {
3235
4130
  await this.sourceCondition(undefined, 'ready-scan')
3236
4131
  if (!this.outOfBudget(opts)) await this.completeScan(checkpoint, report)
3237
4132
  return
@@ -3254,16 +4149,81 @@ export class Dispatcher {
3254
4149
  // failure must leave the entire ready set unclaimed. Publish dependency
3255
4150
  // diagnostics only after the complete preflight succeeds.
3256
4151
  let scanSuccessful = true
4152
+ const treeEntries = await this.repoBuildDigests()
4153
+ const hasNodes =
4154
+ treeEntries.some(({ digest }) => digest.kind === 'node') ||
4155
+ ready.some((ticket) => ticket.kind === 'node')
4156
+ let presence: PresenceInputs | undefined
4157
+ const builtTickets = hasNodes
4158
+ ? new Set(
4159
+ treeEntries.flatMap(({ record }) =>
4160
+ record.ticket ? [JSON.stringify([record.ticket.source, record.ticket.id])] : [],
4161
+ ),
4162
+ )
4163
+ : undefined
4164
+ const needsPresence = (candidate: Ticket) =>
4165
+ (candidate.blockedBy ?? []).some((id) => {
4166
+ const build = blockerBuild(treeEntries, candidate.ref.source, id)
4167
+ return (
4168
+ id !== candidate.ref.id &&
4169
+ build !== undefined &&
4170
+ typeof build !== 'string' &&
4171
+ build.digest.terminal !== 'aborted' &&
4172
+ (build.digest.kind !== 'node' || build.digest.mergedSha !== undefined)
4173
+ )
4174
+ })
4175
+ const destinationHeads = new Map<
4176
+ string,
4177
+ { branch: string; destination: string; head: string; identities: string[] }
4178
+ >()
3257
4179
  const verdicts = new Map<string, DependencyVerdict>()
3258
4180
  const failed = new Set<string>()
4181
+ const targetBlocked = new Set<string>()
4182
+ const preflightTargets = new Map<string, string>()
3259
4183
  for (const ticket of ready) {
3260
4184
  if (this.outOfBudget(opts)) return
3261
4185
  if (withheld.has(ticket.ref.id)) continue
3262
- if (ticket.blockersResolved === true || (ticket.blockedBy ?? []).length === 0) continue
4186
+ const target = await this.resolveNodeTarget(ticket)
4187
+ if (typeof target === 'string') {
4188
+ targetBlocked.add(ticket.ref.id)
4189
+ report.dependencyBlocked += 1
4190
+ report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
4191
+ continue
4192
+ }
4193
+ preflightTargets.set(ticket.ref.id, JSON.stringify(target))
4194
+ if (this.outOfBudget(opts)) return
4195
+ if ((!hasNodes && ticket.blockersResolved === true) || (ticket.blockedBy ?? []).length === 0)
4196
+ continue
3263
4197
  let verdict: DependencyVerdict
3264
4198
  try {
3265
- if (!(await this.loadDependencyGraph(ticket, nodes, opts))) return
3266
- verdict = analyzeDependencies(ticket.ref.id, ticket.blockedBy ?? [], nodes)
4199
+ if (!(await this.loadDependencyGraph(ticket, nodes, opts, builtTickets))) return
4200
+ if (hasNodes) {
4201
+ if (!presence && needsPresence(ticket)) {
4202
+ await this.recoverNodeContributions(treeEntries)
4203
+ const entries = await this.repoBuildDigests()
4204
+ const destinations = ready
4205
+ .filter(
4206
+ (candidate) =>
4207
+ needsPresence(candidate) &&
4208
+ !withheld.has(candidate.ref.id) &&
4209
+ candidate.target !== undefined,
4210
+ )
4211
+ .flatMap((candidate) => {
4212
+ const node = blockerBuild(entries, candidate.ref.source, candidate.target!)
4213
+ return node && typeof node !== 'string' && node.digest.kind === 'node'
4214
+ ? [node.record.slug]
4215
+ : []
4216
+ })
4217
+ presence = await presenceInputs(this.store, entries, destinations)
4218
+ }
4219
+ const inputs = presence ?? {
4220
+ entries: treeEntries,
4221
+ states: new Map(),
4222
+ aliases: new Map(),
4223
+ landings: [],
4224
+ }
4225
+ verdict = await this.presenceVerdict(ticket, target, nodes, inputs, destinationHeads)
4226
+ } else verdict = analyzeDependencies(ticket.ref.id, ticket.blockedBy ?? [], nodes)
3267
4227
  } catch (error) {
3268
4228
  if (error instanceof TicketSourceRateLimitError) {
3269
4229
  await this.sourceFailure(error, 'dependency-check')
@@ -3288,11 +4248,41 @@ export class Dispatcher {
3288
4248
  }
3289
4249
  }
3290
4250
  for (const ticket of ready) {
3291
- if (capacity <= 0 || this.outOfBudget(opts)) break
4251
+ if (this.outOfBudget(opts)) break
4252
+ if (ticket.kind !== 'node' && capacity <= 0) continue
3292
4253
  if (withheld.has(ticket.ref.id)) continue
3293
- if (failed.has(ticket.ref.id)) continue
4254
+ if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
3294
4255
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
3295
4256
 
4257
+ const target = await this.resolveNodeTarget(ticket)
4258
+ if (typeof target === 'string') {
4259
+ report.dependencyBlocked += 1
4260
+ report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
4261
+ continue
4262
+ }
4263
+ if (hasNodes && preflightTargets.get(ticket.ref.id) !== JSON.stringify(target)) {
4264
+ report.dependencyBlocked += 1
4265
+ report.dependencyDiagnostics.push(
4266
+ `ticket ${ticket.ref.id}: target changed after dependency preflight`,
4267
+ )
4268
+ continue
4269
+ }
4270
+ if (hasNodes) {
4271
+ const branch = target?.branch ?? config.baseBranch
4272
+ const destination = target?.target.build ?? `root:${branch}`
4273
+ const observed = destinationHeads.get(destination)
4274
+ if (
4275
+ observed &&
4276
+ (!this.deps.forge.remoteBranchSha ||
4277
+ (await this.deps.forge.remoteBranchSha(branch)) !== observed.head)
4278
+ ) {
4279
+ report.dependencyBlocked += 1
4280
+ report.dependencyDiagnostics.push(
4281
+ `ticket ${ticket.ref.id}: destination ${destination} (${branch}) moved after dependency preflight; waiting for fresh presence evidence`,
4282
+ )
4283
+ continue
4284
+ }
4285
+ }
3296
4286
  // Claim-before-launch (§12): losing the claim means another dispatcher
3297
4287
  // (or an earlier tick) owns this ticket.
3298
4288
  if (!(await tickets.claim(ticket.ref.id))) {
@@ -3329,9 +4319,11 @@ export class Dispatcher {
3329
4319
 
3330
4320
  const baseSlug = await this.chooseSlugBase(ticket.title, body)
3331
4321
  const slug = await this.uniqueSlug(baseSlug)
3332
- const branch = `ab/${slug}`
4322
+ const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
3333
4323
  const repoOrigin = await this.resolveRepoOriginOnce()
3334
4324
  const createdSeed = {
4325
+ ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
4326
+ ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
3335
4327
  ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
3336
4328
  // Claim-time provenance: the newest durable default fact that agrees
3337
4329
  // with the launch sample, recorded on `build.created` so the fan-out's
@@ -3356,7 +4348,7 @@ export class Dispatcher {
3356
4348
  },
3357
4349
  })
3358
4350
  report.queued -= 1
3359
- capacity -= 1
4351
+ if (ticket.kind !== 'node') capacity -= 1
3360
4352
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
3361
4353
  ticket,
3362
4354
  body,
@@ -3374,10 +4366,895 @@ export class Dispatcher {
3374
4366
  * Walk unresolved branches in provider order. Listing facts and dependency
3375
4367
  * reads share a tick-local cache; traversal visits are local to this root.
3376
4368
  */
4369
+ private async resolveNodeTarget(
4370
+ ticket: Ticket,
4371
+ ): Promise<
4372
+ | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
4373
+ | string
4374
+ | undefined
4375
+ > {
4376
+ const forge = this.deps.forge
4377
+ if (
4378
+ ticket.kind === 'node' &&
4379
+ (!forge.createNodeBranch || !forge.compareBranches || !forge.remoteBranchSha)
4380
+ )
4381
+ return `integration requires forge ${forge.name} capabilities createNodeBranch, compareBranches and remoteBranchSha; upgrade the plugin`
4382
+ if (ticket.target === undefined) return undefined
4383
+ const entries = (await this.repoBuildDigests())
4384
+ .filter(
4385
+ ({ record }) =>
4386
+ record.ticket?.source === ticket.ref.source && record.ticket.id === ticket.target,
4387
+ )
4388
+ .sort(
4389
+ (a, b) =>
4390
+ b.record.createdAt.localeCompare(a.record.createdAt) ||
4391
+ b.record.slug.localeCompare(a.record.slug),
4392
+ )
4393
+ const latest = entries[0]
4394
+ if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
4395
+ return `target node ${ticket.target} has ambiguous build generations at ${latest.record.createdAt}`
4396
+ if (!latest) return `target node ${ticket.target} is not yet claimed`
4397
+ const { record, digest } = latest
4398
+ if (digest.kind !== 'node') return `target ${ticket.target} is not a node`
4399
+ if (digest.terminal || digest.prClosed || digest.merged)
4400
+ return `target node ${ticket.target} is ${digest.terminal === 'aborted' ? 'aborted' : digest.merged ? 'landed' : 'closed'}`
4401
+ const state = (await this.store.buildFacts(record.slug)).state
4402
+ if (
4403
+ state.status === 'done' ||
4404
+ state.status === 'aborted' ||
4405
+ state.prState === 'merged' ||
4406
+ state.prState === 'closed'
4407
+ )
4408
+ return `target node ${ticket.target} is ${state.prState === 'merged' ? 'landed' : 'closed'}`
4409
+ if (state.pendingCommands.some((c) => c.command === 'abort'))
4410
+ return `target node ${ticket.target} is closing`
4411
+ if (state.integration?.intent && !state.integration.landing)
4412
+ return `target node ${ticket.target} is landing`
4413
+ if (!digest.nodeOpened || !record.branch) return `target node ${ticket.target} is not yet open`
4414
+ return { target: { ticket: record.ticket!, build: record.slug }, branch: record.branch }
4415
+ }
4416
+
4417
+ private async openNode(record: BuildRecord, state: BuildState): Promise<void> {
4418
+ if (!record.branch || !state.baseBranch)
4419
+ throw new Error('integration lacks frozen branch facts')
4420
+ const forge = this.deps.forge
4421
+ if (!forge.createNodeBranch || !forge.remoteBranchSha)
4422
+ throw new Error('forge lacks node branch capabilities')
4423
+ let intent = state.nodeOpening
4424
+ if (!intent) {
4425
+ intent = {
4426
+ branch: record.branch,
4427
+ parent: state.baseBranch,
4428
+ sha: await forge.remoteBranchSha(state.baseBranch),
4429
+ }
4430
+ const written = await this.store.appendIfCurrent(record.slug, state.lastSeq, {
4431
+ actor: DISPATCHER,
4432
+ type: 'node.opening',
4433
+ payload: intent,
4434
+ })
4435
+ if (!written) return
4436
+ }
4437
+ const sha = await forge.createNodeBranch(intent.branch, intent.sha)
4438
+ await this.store.refreshBuild(record.slug)
4439
+ const latest = (await this.store.buildFacts(record.slug)).state
4440
+ if (latest.status !== 'queued' || latest.pendingCommands.length > 0 || latest.nodeOpened) return
4441
+ await this.store.appendIfCurrent(record.slug, latest.lastSeq, {
4442
+ actor: DISPATCHER,
4443
+ type: 'node.opened',
4444
+ payload: { sha },
4445
+ })
4446
+ }
4447
+
4448
+ private kernelForge(): Forge {
4449
+ const forge = this.deps.forge
4450
+ if (!forge.kernelRewrite) return forge
4451
+ return new Proxy(forge, {
4452
+ get(target, key) {
4453
+ if (key === 'rewrite') return target.kernelRewrite
4454
+ const value = Reflect.get(target, key, target)
4455
+ return typeof value === 'function' ? value.bind(target) : value
4456
+ },
4457
+ })
4458
+ }
4459
+
4460
+ private async kernelRepository(root: string): Promise<string> {
4461
+ const checkout = this.deps.checkout ?? this.deps.repo
4462
+ if (!this.deps.repoOrigin) return checkout
4463
+ // Origin-mode CLI wiring supplies a scratch checkout path too. Only an
4464
+ // actual Git repository can provide the kernel's local object database.
4465
+ if (this.deps.checkout) {
4466
+ const probe = await this.deps.exec(['git', 'rev-parse', '--git-dir'], { cwd: checkout })
4467
+ if (probe.exitCode === 0) return checkout
4468
+ }
4469
+ const path = join(root, 'repository.git')
4470
+ const clone = await (this.deps.forge.kernelExec ?? this.deps.exec)(
4471
+ ['git', 'clone', '--bare', this.deps.repoOrigin, path],
4472
+ {
4473
+ cwd: root,
4474
+ },
4475
+ )
4476
+ if (clone.exitCode !== 0) throw new Error(clone.stderr)
4477
+ return path
4478
+ }
4479
+
4480
+ private async withKernelRepository<T>(run: (path: string) => Promise<T>): Promise<T> {
4481
+ const root = await mkdtemp(join(tmpdir(), 'autobuild-node-transport-'))
4482
+ try {
4483
+ return await run(await this.kernelRepository(root))
4484
+ } finally {
4485
+ await rm(root, { recursive: true, force: true })
4486
+ }
4487
+ }
4488
+
4489
+ private async cascadeNode(
4490
+ record: BuildRecord,
4491
+ state: BuildState,
4492
+ report: TickReport,
4493
+ launched: Set<string>,
4494
+ opts: TickOpts,
4495
+ ): Promise<void> {
4496
+ if (state.nodeRestack?.parentRequest && !state.nodeRestack.active) return
4497
+ if (
4498
+ state.nodeRestack?.parentChange &&
4499
+ state.nodeRestack.parentReplay === state.nodeRestack.parentChange.id
4500
+ )
4501
+ return
4502
+ const forge = this.kernelForge()
4503
+ const settled = (await readBuildFacts(this.store, record.slug)).value
4504
+ if (
4505
+ settled.publication.pending() ||
4506
+ (settled.open !== null &&
4507
+ (settled.open.commandId !== undefined || this.hasLiveExecutionLease(record)))
4508
+ )
4509
+ return
4510
+ if (
4511
+ state.pr &&
4512
+ (await forge.getPrState(this.deps.checkout ?? this.deps.repo, state.pr.number)).state !==
4513
+ 'open'
4514
+ )
4515
+ return
4516
+ if (
4517
+ state.nodeRestack?.active?.operation === 'landing' ||
4518
+ (state.integration?.intent && !state.integration.landing)
4519
+ )
4520
+ return
4521
+ if (
4522
+ !record.branch ||
4523
+ !state.baseBranch ||
4524
+ !forge.rewrite ||
4525
+ (!forge.snapshotBase && !forge.kernelExec)
4526
+ )
4527
+ return
4528
+ // The forge API can prove an unchanged inventory without downloading Git
4529
+ // history. Active work and hand pushes still enter the transaction path.
4530
+ if (
4531
+ !state.nodeRestack?.active &&
4532
+ !state.nodeRestack?.parentChange &&
4533
+ state.sessions.open.length === 0 &&
4534
+ forge.remoteBranchSha
4535
+ ) {
4536
+ const [parent, head] = await Promise.all([
4537
+ forge.remoteBranchSha(state.baseBranch),
4538
+ forge.remoteBranchSha(record.branch),
4539
+ ])
4540
+ if (
4541
+ parent === state.nodeRestack?.contributionBase &&
4542
+ head === state.nodeRestack?.inventory?.head
4543
+ )
4544
+ return
4545
+ }
4546
+ const holder = this.deps.ids('node-writer')
4547
+ const root = await mkdtemp(join(tmpdir(), 'autobuild-node-'))
4548
+ const workspacePath = join(root, 'replay')
4549
+ let checkout = this.deps.checkout ?? this.deps.repo
4550
+ let added = false
4551
+ let claimed = false
4552
+ try {
4553
+ // Repository download is read-only and may exceed the writer lease TTL.
4554
+ // Acquire writer authority only after it completes.
4555
+ checkout = await this.kernelRepository(root)
4556
+ claimed = await this.store.claimNodeWriter(record.slug, holder, 60_000)
4557
+ if (!claimed) return
4558
+ const latest = (await readBuildFacts(this.store, record.slug)).value
4559
+ if (latest.publication.pending()) return
4560
+ if (latest.open !== null) {
4561
+ const refreshed = await this.store.getBuild(record.slug)
4562
+ if (
4563
+ latest.open.commandId !== undefined ||
4564
+ (refreshed && this.hasLiveExecutionLease(refreshed))
4565
+ )
4566
+ return
4567
+ await this.store.append(record.slug, {
4568
+ actor: DISPATCHER,
4569
+ type: 'execution.ended',
4570
+ payload: {
4571
+ instance: latest.open.instance,
4572
+ workspaceRef: latest.open.workspaceRef,
4573
+ outcome: 'lost',
4574
+ },
4575
+ })
4576
+ }
4577
+ state = (await this.store.buildFacts(record.slug)).state
4578
+ // An ended execution may have died between an item's atomic receipt and
4579
+ // its phase/session acknowledgements. Reclaim only after supervision has
4580
+ // settled the complete execution, before any public stack rewrite.
4581
+ for (const session of state.sessions.open) {
4582
+ await this.store.append(record.slug, {
4583
+ actor: KERNEL,
4584
+ type: 'session.ended',
4585
+ payload: {
4586
+ session: session.session,
4587
+ outcome: 'reclaimed',
4588
+ reclaimedBy: { instance: holder, resumedFromSeq: state.lastSeq },
4589
+ },
4590
+ })
4591
+ }
4592
+ if (
4593
+ !state.nodeRestack?.conflict &&
4594
+ state.currentPhase?.phase === 'reconcile' &&
4595
+ state.nodeRestack?.active &&
4596
+ state.nodeRestack.items.length > 0
4597
+ ) {
4598
+ const notes = await this.store.getArtifact(record.slug, 'reconcile-notes')
4599
+ if (!notes) throw new Error('missing source build identity resolution notes')
4600
+ await this.store.append(record.slug, {
4601
+ actor: KERNEL,
4602
+ type: 'reconcile.completed',
4603
+ payload: {
4604
+ headSha: state.nodeRestack.items.at(-1)!.head,
4605
+ rewriteId: state.nodeRestack.active.id,
4606
+ artifact: { kind: notes.meta.kind, rev: notes.meta.revision },
4607
+ },
4608
+ })
4609
+ }
4610
+ const result = await this.deps.exec(
4611
+ ['git', 'worktree', 'add', '--detach', workspacePath, 'HEAD'],
4612
+ { cwd: checkout },
4613
+ )
4614
+ if (result.exitCode !== 0) throw new Error(result.stderr)
4615
+ added = true
4616
+ const parentHead = forge.remoteBranchSha
4617
+ ? await forge.remoteBranchSha(state.baseBranch!)
4618
+ : undefined
4619
+ if (state.nodeRestack?.active || parentHead !== state.nodeRestack?.contributionBase) {
4620
+ // Upgrade recovery: an old dispatcher may have left a native request
4621
+ // armed. Cancel every targeting leaf before admitting a node rewrite.
4622
+ for (const child of await this.repoBuildDigests()) {
4623
+ if (child.digest.terminal || child.digest.kind === 'node') continue
4624
+ const childState = (await this.store.buildFacts(child.record.slug)).state
4625
+ if (
4626
+ childState.target?.build !== record.slug ||
4627
+ !childState.pr ||
4628
+ childState.prState !== 'open'
4629
+ )
4630
+ continue
4631
+ const cancelled = await forge.setAutoMerge(checkout, childState.pr.number, false)
4632
+ if (cancelled.kind !== 'applied')
4633
+ throw new Error(
4634
+ `node restack waits for native auto-merge cancellation on ${child.record.slug}`,
4635
+ )
4636
+ }
4637
+ }
4638
+ const outcome = await runNodeTransaction(
4639
+ {
4640
+ store: this.store,
4641
+ slug: record.slug,
4642
+ forge,
4643
+ exec: forge.kernelExec ?? this.deps.exec,
4644
+ workspacePath,
4645
+ holder,
4646
+ canWrite: async () => {
4647
+ if (this.outOfBudget(opts)) return false
4648
+ if (state.pr && (await forge.getPrState(checkout, state.pr.number)).state !== 'open')
4649
+ return false
4650
+ await this.store.refreshBuild(record.slug)
4651
+ const current = (await this.store.buildFacts(record.slug)).state
4652
+ return (
4653
+ current.status !== 'done' &&
4654
+ current.status !== 'aborted' &&
4655
+ current.status !== 'paused' &&
4656
+ (current.status !== 'blocked' || integrationFailed(current)) &&
4657
+ current.prState !== 'merged' &&
4658
+ current.prState !== 'closed' &&
4659
+ current.pendingCommands.length === 0 &&
4660
+ current.sessions.open.length === 0
4661
+ )
4662
+ },
4663
+ },
4664
+ {
4665
+ branch: record.branch,
4666
+ parentBranch: state.baseBranch!,
4667
+ id: this.deps.ids('node-restack').replaceAll('_', '-'),
4668
+ },
4669
+ )
4670
+ if (outcome === 'completed') {
4671
+ const completed = (await readBuildFacts(this.store, record.slug)).value
4672
+ if (openWorkspace(completed)) await this.releaseWorkspace(record.slug, completed)
4673
+ }
4674
+ if (outcome === 'conflict') {
4675
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4676
+ const node = facts.state.nodeRestack!
4677
+ const conflict = node.conflict!
4678
+ const change = node.active!.changes[conflict.index]!
4679
+ if (change.build) {
4680
+ if (!(await this.store.getBuild(change.build)))
4681
+ throw new Error(`missing source build identity ${change.build}`)
4682
+ const source = (await readBuildFacts(this.store, change.build)).value.state
4683
+ if (
4684
+ source.specRev === undefined ||
4685
+ source.plan.artifactRev === undefined ||
4686
+ !source.plan.approved ||
4687
+ source.implement.artifactRev === undefined
4688
+ )
4689
+ throw new Error(`missing source build identity context for ${change.build}`)
4690
+ for (const [kind, revision] of [
4691
+ ['spec', source.specRev],
4692
+ ['plan', source.plan.artifactRev],
4693
+ ['implement-notes', source.implement.artifactRev],
4694
+ ] as const) {
4695
+ const contextKind = `node-source-${node.active!.id}-${conflict.index}-${kind}`
4696
+ if (await this.store.getArtifact(record.slug, contextKind)) continue
4697
+ const artifact = await this.store.getArtifact(change.build, kind, revision)
4698
+ if (!artifact)
4699
+ throw new Error(`missing source build identity context ${kind} for ${change.build}`)
4700
+ await this.store.putArtifact(record.slug, {
4701
+ kind: contextKind,
4702
+ content: artifact.content,
4703
+ })
4704
+ }
4705
+ }
4706
+
4707
+ let occupied = 0
4708
+ for (const other of await this.repoBuildDigests()) {
4709
+ if (other.record.slug === record.slug || other.digest.terminal) continue
4710
+ if (
4711
+ other.digest.kind !== 'node' ||
4712
+ (await this.store.buildFacts(other.record.slug)).state.nodeRestack?.conflict ||
4713
+ (integrationNeedsRunner((await this.store.buildFacts(other.record.slug)).state) &&
4714
+ (this.hasLiveExecutionLease(other.record) ||
4715
+ (await this.store.buildFacts(other.record.slug)).workspace !== null))
4716
+ )
4717
+ occupied++
4718
+ }
4719
+ if (occupied >= this.deps.config.capacity) return
4720
+ if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
4721
+ const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
4722
+ if (kicked === 'kicked') report.provisioning += 1
4723
+ } else {
4724
+ if (openWorkspace(facts) === null) {
4725
+ const handle = await this.deps.workspaces.provision({
4726
+ repo: checkout,
4727
+ baseBranch: state.baseBranch!,
4728
+ branch: record.branch!,
4729
+ })
4730
+ await this.store.append(record.slug, {
4731
+ actor: DISPATCHER,
4732
+ type: 'workspace.provisioned',
4733
+ payload: {
4734
+ provider: handle.provider,
4735
+ ref: handle.ref,
4736
+ path: handle.path,
4737
+ localPath: handle.localPath,
4738
+ remote: false,
4739
+ branch: handle.branch,
4740
+ base: handle.base,
4741
+ },
4742
+ })
4743
+ }
4744
+ await this.launch(record.slug, launched, report)
4745
+ }
4746
+ }
4747
+ } catch (error) {
4748
+ const message = error instanceof Error ? error.message : String(error)
4749
+ // Safety refusals require human judgment. Infrastructure failures remain
4750
+ // retryable dispatch failures and retain their active reservation.
4751
+ if (
4752
+ message.includes('node restack refused') ||
4753
+ message.includes('contribution base') ||
4754
+ message.includes('build identity')
4755
+ ) {
4756
+ await this.store.refreshBuild(record.slug)
4757
+ const current = (await this.store.buildFacts(record.slug)).state
4758
+ if (!current.openEscalations.length)
4759
+ await this.store.append(record.slug, {
4760
+ actor: KERNEL,
4761
+ type: 'escalation.raised',
4762
+ payload: {
4763
+ id: this.deps.ids('esc'),
4764
+ phase: 'reconcile',
4765
+ source: 'agent',
4766
+ question: message,
4767
+ },
4768
+ })
4769
+ } else throw error
4770
+ } finally {
4771
+ if (added)
4772
+ await this.deps.exec(['git', 'worktree', 'remove', '--force', workspacePath], {
4773
+ cwd: checkout,
4774
+ })
4775
+ await rm(root, { recursive: true, force: true })
4776
+ if (claimed) await this.store.releaseNodeWriter(record.slug, holder)
4777
+ }
4778
+ }
4779
+
4780
+ private async prepareIntegration(
4781
+ record: BuildRecord,
4782
+ state: BuildState,
4783
+ report: TickReport,
4784
+ launched: Set<string>,
4785
+ ): Promise<void> {
4786
+ if (
4787
+ state.status === 'paused' ||
4788
+ state.status === 'done' ||
4789
+ state.status === 'aborted' ||
4790
+ state.pendingCommands.length ||
4791
+ state.openEscalations.length ||
4792
+ state.prState === 'merged' ||
4793
+ state.prState === 'closed' ||
4794
+ state.integration?.intent ||
4795
+ state.nodeRestack?.parentRequest ||
4796
+ state.nodeRestack?.parentChange
4797
+ )
4798
+ return
4799
+ const forge = this.kernelForge()
4800
+ if (!record.branch || !state.baseBranch || !forge.compareBranches) return
4801
+ const comparison = await forge.compareBranches(state.baseBranch!, record.branch!)
4802
+ if (JSON.stringify(comparison) !== JSON.stringify(state.nodeComparison))
4803
+ await this.store.append(record.slug, {
4804
+ actor: DISPATCHER,
4805
+ type: 'node.compared',
4806
+ payload: comparison,
4807
+ })
4808
+ state = (await this.store.buildFacts(record.slug)).state
4809
+ const claims = await this.integrationClaimKey(record.slug)
4810
+ const unchangedFailure = integrationFailed(state)
4811
+ if (
4812
+ !unchangedFailure &&
4813
+ this.integrationPollDue(
4814
+ this.integrationPolls,
4815
+ record.slug,
4816
+ `${comparison.headSha}:${comparison.parentSha}:${state.landing?.command?.seq ?? state.landing?.decision?.seq ?? ''}:${claims}`,
4817
+ )
4818
+ ) {
4819
+ await this.observeIntegration(record.slug)
4820
+ state = (await this.store.buildFacts(record.slug)).state
4821
+ }
4822
+ if (
4823
+ state.integration?.cycle &&
4824
+ !state.nodeRestack?.active &&
4825
+ (!integrationCurrent(state) || integrationFailed(state))
4826
+ ) {
4827
+ const stale = (await readBuildFacts(this.store, record.slug)).value
4828
+ if (openWorkspace(stale)) await this.releaseWorkspace(record.slug, stale)
4829
+ state = (await this.store.buildFacts(record.slug)).state
4830
+ }
4831
+ if (
4832
+ unchangedFailure ||
4833
+ !integrationComplete(state) ||
4834
+ state.nodeRestack?.active ||
4835
+ state.integration?.intent ||
4836
+ state.nodeRestack?.contributionBase !== comparison.parentSha ||
4837
+ state.openEscalations.length ||
4838
+ state.status === 'paused' ||
4839
+ state.status === 'done' ||
4840
+ state.status === 'aborted' ||
4841
+ state.pendingCommands.length ||
4842
+ state.prState === 'merged' ||
4843
+ state.prState === 'closed'
4844
+ )
4845
+ return
4846
+ const artifact = await this.store.getArtifact(record.slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
4847
+ const config = artifact
4848
+ ? composeBuildConfig(parseEffectiveBuildConfig(artifact), this.deps.config)
4849
+ : this.deps.config
4850
+ if (
4851
+ !integrationCurrent(state) ||
4852
+ state.integration?.cycle?.config !== integrationConfig(config)
4853
+ ) {
4854
+ await this.observeIntegration(record.slug)
4855
+ state = (await this.store.buildFacts(record.slug)).state
4856
+ if (!integrationComplete(state)) return
4857
+ const holder = this.deps.ids('node-writer')
4858
+ if (!(await this.store.claimNodeWriter(record.slug, holder, 60_000))) return
4859
+ try {
4860
+ const current = (await this.store.buildFacts(record.slug)).state
4861
+ if (
4862
+ current.nodeRestack?.active ||
4863
+ current.nodeRestack?.parentRequest ||
4864
+ current.nodeRestack?.parentChange ||
4865
+ current.pendingCommands.length
4866
+ )
4867
+ return
4868
+ const exact = await forge.compareBranches(state.baseBranch!, record.branch!)
4869
+ if (exact.parentSha !== comparison.parentSha || exact.headSha !== comparison.headSha) return
4870
+ await this.withKernelRepository(async (path) => {
4871
+ const head = await forge.rewrite!.snapshot({
4872
+ workspacePath: path,
4873
+ branch: record.branch!,
4874
+ destinationRef: `refs/autobuild/reconcile/${record.slug}/verify-head`,
4875
+ })
4876
+ if (head !== exact.headSha)
4877
+ throw new Error('node head moved while preparing verification')
4878
+ await forge.rewrite!.archive({
4879
+ workspacePath: path,
4880
+ ref: `refs/autobuild/archive/${record.slug}/${head}`,
4881
+ sha: head,
4882
+ })
4883
+ })
4884
+ if (!(await this.store.renewNodeWriter(record.slug, holder))) return
4885
+ await this.store.appendIfCurrent(record.slug, current.lastSeq, {
4886
+ actor: DISPATCHER,
4887
+ type: 'integration.prepared',
4888
+ payload: {
4889
+ id: this.deps.ids('integration-cycle'),
4890
+ head: exact.headSha,
4891
+ parent: exact.parentSha,
4892
+ config: integrationConfig(config),
4893
+ },
4894
+ })
4895
+ } finally {
4896
+ await this.store.releaseNodeWriter(record.slug, holder)
4897
+ }
4898
+ state = (await this.store.buildFacts(record.slug)).state
4899
+ }
4900
+ if (integrationFailed(state) || integrationVerified(state, config)) {
4901
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4902
+ if (openWorkspace(facts)) await this.releaseWorkspace(record.slug, facts)
4903
+ return
4904
+ }
4905
+ let occupied = 0
4906
+ for (const other of await this.nonterminalBuilds()) {
4907
+ if (other.slug === record.slug) continue
4908
+ const current = (await this.store.buildFacts(other.slug)).state
4909
+ if (
4910
+ current.kind !== 'node' ||
4911
+ current.nodeRestack?.conflict ||
4912
+ (integrationNeedsRunner(current) &&
4913
+ (this.hasLiveExecutionLease(other) ||
4914
+ (await this.store.buildFacts(other.slug)).workspace !== null))
4915
+ )
4916
+ occupied++
4917
+ }
4918
+ if (occupied >= this.deps.config.capacity) return
4919
+ await this.observeIntegration(record.slug)
4920
+ state = (await this.store.buildFacts(record.slug)).state
4921
+ if (!integrationCurrent(state)) return
4922
+ const facts = (await readBuildFacts(this.store, record.slug)).value
4923
+ if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
4924
+ const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
4925
+ if (kicked === 'kicked') report.provisioning++
4926
+ return
4927
+ }
4928
+ if (openWorkspace(facts) === null) {
4929
+ const handle = await this.deps.workspaces.provision({
4930
+ repo: this.deps.checkout ?? this.deps.repo,
4931
+ baseBranch: record.branch,
4932
+ branch: record.branch,
4933
+ revision: state.integration!.cycle!.head,
4934
+ })
4935
+ await this.store.append(record.slug, {
4936
+ actor: DISPATCHER,
4937
+ type: 'workspace.provisioned',
4938
+ payload: {
4939
+ provider: handle.provider,
4940
+ ref: handle.ref,
4941
+ path: handle.path,
4942
+ localPath: handle.localPath,
4943
+ remote: false,
4944
+ branch: handle.branch,
4945
+ base: handle.base,
4946
+ },
4947
+ })
4948
+ }
4949
+ await this.launch(record.slug, launched, report)
4950
+ }
4951
+
4952
+ private async pollEmptyNode(record: BuildRecord, state: BuildState): Promise<void> {
4953
+ const forge = this.deps.forge
4954
+ if (!forge.compareBranches || !record.branch || !state.baseBranch)
4955
+ throw new Error('integration lacks comparison capability or frozen branch facts')
4956
+ const observe = async () => {
4957
+ const comparison = await forge.compareBranches!(state.baseBranch!, record.branch!)
4958
+ if (
4959
+ comparison.parentSha !== state.nodeComparison?.parentSha ||
4960
+ comparison.headSha !== state.nodeComparison?.headSha ||
4961
+ comparison.ahead !== state.nodeComparison?.ahead
4962
+ ) {
4963
+ await this.store.append(record.slug, {
4964
+ actor: DISPATCHER,
4965
+ type: 'node.compared',
4966
+ payload: comparison,
4967
+ })
4968
+ state.nodeComparison = comparison
4969
+ }
4970
+ return comparison
4971
+ }
4972
+ const comparison = await observe()
4973
+ if (comparison.ahead === 0) return
4974
+ let pr: Awaited<ReturnType<typeof forge.openPr>>
4975
+ try {
4976
+ pr = await forge.openPr({
4977
+ workspacePath: this.deps.checkout ?? this.deps.repo,
4978
+ head: record.branch,
4979
+ base: state.baseBranch,
4980
+ title: `Integration: ${record.ticket?.id ?? record.slug}`,
4981
+ body: `Integration build ${record.slug}. Target: ${state.target?.ticket.id ?? state.baseBranch}. Human landing required.`,
4982
+ })
4983
+ } catch (error) {
4984
+ if (error instanceof NoCommitsBetweenBranchesError && (await observe()).ahead === 0) return
4985
+ throw error
4986
+ }
4987
+ await this.store.append(record.slug, { actor: DISPATCHER, type: 'pr.opened', payload: { pr } })
4988
+ }
4989
+
4990
+ /** Recover manifests after merge-observation crashes as well as before
4991
+ * recording a new merge. Never synthesize an empty historical manifest. */
4992
+ private async recoverNodeContributions(
4993
+ entries: Awaited<ReturnType<Dispatcher['repoBuildDigests']>>,
4994
+ merging?: { slug: string; sha: string },
4995
+ ): Promise<void> {
4996
+ const candidates = entries.filter(
4997
+ ({ record, digest }) =>
4998
+ digest.kind === 'node' && (digest.merged || record.slug === merging?.slug),
4999
+ )
5000
+ if (candidates.length === 0) return
5001
+ const pending = candidates.filter(
5002
+ ({ record, digest }) =>
5003
+ digest.nodeContribution?.landing !==
5004
+ (record.slug === merging?.slug ? merging.sha : digest.mergedSha),
5005
+ )
5006
+ if (pending.length === 0) return
5007
+ const inputs = await presenceInputs(
5008
+ this.store,
5009
+ entries,
5010
+ pending.map(({ record }) => record.slug),
5011
+ )
5012
+ try {
5013
+ await this.withKernelRepository(async (path) => {
5014
+ const forge = this.kernelForge()
5015
+ const git = { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path }
5016
+ const visiting = new Set<string>()
5017
+ const recover = async (slug: string): Promise<void> => {
5018
+ if (visiting.has(slug)) throw new Error('cyclic node contribution evidence')
5019
+ const entry = entries.find(({ record }) => record.slug === slug)!
5020
+ const landing = slug === merging?.slug ? merging.sha : entry.digest.mergedSha
5021
+ if (!landing || entry.digest.nodeContribution?.landing === landing) return
5022
+ const state = inputs.states.get(slug)!
5023
+ if (!state.pr || !forge.inspectLandingPr)
5024
+ throw new Error('cannot establish landed node source head')
5025
+ visiting.add(slug)
5026
+ const pr = await forge.inspectLandingPr(path, state.pr.number)
5027
+ const head = pr.headSha
5028
+ const base =
5029
+ state.nodeRestack?.contributionBoundaries?.[head] ??
5030
+ state.nodeRestack?.contributionBase ??
5031
+ state.nodeOpened?.sha
5032
+ if (!head || !base) throw new Error('missing node contribution source range')
5033
+ // Fetch retained objects when the kernel repository has not seen
5034
+ // this source head (including remote guest publication).
5035
+ for (const sha of [head, base]) {
5036
+ const exists = await git.exec(['git', 'cat-file', '-e', `${sha}^{commit}`], {
5037
+ cwd: path,
5038
+ })
5039
+ if (exists.exitCode !== 0) {
5040
+ const fetched = await git.exec(
5041
+ ['git', 'fetch', '--no-tags', '--no-write-fetch-head', 'origin', sha],
5042
+ { cwd: path },
5043
+ )
5044
+ if (fetched.exitCode !== 0)
5045
+ throw new Error(`retained node source object ${sha} unavailable`)
5046
+ }
5047
+ }
5048
+ // Nested completed nodes must be expanded before their parent is
5049
+ // frozen; a squash can erase every original child SHA.
5050
+ for (const child of candidates) {
5051
+ if (child.record.slug === slug) continue
5052
+ const childState = inputs.states.get(child.record.slug)
5053
+ if (childState?.target?.build === slug && childState.mergedSha)
5054
+ await recover(child.record.slug)
5055
+ }
5056
+ const currentIdentities = await ownedContribution(
5057
+ git,
5058
+ base,
5059
+ head,
5060
+ inputs.landings,
5061
+ inputs.aliases,
5062
+ )
5063
+ const dropped = state.nodeRestack?.droppedIdentities ?? []
5064
+ const transported = inputs.landings
5065
+ .filter(
5066
+ (proof) =>
5067
+ dropped.includes(`build:${proof.slug}`) || dropped.includes(`foreign:${proof.sha}`),
5068
+ )
5069
+ .flatMap((proof) => proof.contribution ?? [])
5070
+ const identities = normalizeIdentities([
5071
+ ...currentIdentities,
5072
+ ...(dropped as ChangeIdentity[]),
5073
+ ...transported,
5074
+ ])
5075
+ const payload = { landing, head, base, identities }
5076
+ await this.store.append(slug, {
5077
+ actor: DISPATCHER,
5078
+ type: 'node.contribution-recorded',
5079
+ payload,
5080
+ })
5081
+ state.nodeRestack ??= { items: [] }
5082
+ state.nodeRestack.contribution = payload
5083
+ entry.digest.nodeContribution = payload
5084
+ inputs.landings.push({ slug, sha: landing, contribution: identities })
5085
+ visiting.delete(slug)
5086
+ }
5087
+ for (const entry of pending) {
5088
+ try {
5089
+ await recover(entry.record.slug)
5090
+ } catch {
5091
+ visiting.clear()
5092
+ }
5093
+ }
5094
+ })
5095
+ } catch {
5096
+ // Admission reports the missing confirmed contribution. Merge facts
5097
+ // and lifecycle cleanup must still progress when Git is unavailable.
5098
+ }
5099
+ }
5100
+
5101
+ private async presenceVerdict(
5102
+ ticket: Ticket,
5103
+ target:
5104
+ | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
5105
+ | undefined,
5106
+ nodes: Map<string, DependencyState>,
5107
+ inputs: PresenceInputs,
5108
+ observations: Map<
5109
+ string,
5110
+ { branch: string; destination: string; head: string; identities: string[] }
5111
+ >,
5112
+ ): Promise<DependencyVerdict> {
5113
+ const branch = target?.branch ?? this.deps.config.baseBranch
5114
+ const destination = target?.target.build ?? `root:${branch}`
5115
+ const unresolved: string[] = []
5116
+ const diagnostics: string[] = []
5117
+ const required = new Map<string, ChangeIdentity[]>()
5118
+ const fallback: string[] = []
5119
+ for (const id of ticket.blockedBy ?? []) {
5120
+ const build = blockerBuild(inputs.entries, ticket.ref.source, id)
5121
+ if (id === ticket.ref.id || !nodes.get(id)?.exists || build === undefined) {
5122
+ fallback.push(id)
5123
+ continue
5124
+ }
5125
+ if (typeof build === 'string') {
5126
+ unresolved.push(id)
5127
+ diagnostics.push(`ticket ${ticket.ref.id}: ${build}`)
5128
+ continue
5129
+ }
5130
+ if (build.digest.terminal === 'aborted') {
5131
+ unresolved.push(id)
5132
+ diagnostics.push(
5133
+ `ticket ${ticket.ref.id}: blocker ${id} latest build ${build.record.slug} is aborted`,
5134
+ )
5135
+ continue
5136
+ }
5137
+ if (build.digest.kind !== 'node') required.set(id, [`build:${build.record.slug}`])
5138
+ else {
5139
+ const contribution = build.digest.nodeContribution
5140
+ if (
5141
+ !build.digest.prClosed &&
5142
+ contribution &&
5143
+ contribution.landing === build.digest.mergedSha
5144
+ )
5145
+ required.set(id, contribution.identities as ChangeIdentity[])
5146
+ else {
5147
+ unresolved.push(id)
5148
+ diagnostics.push(
5149
+ `ticket ${ticket.ref.id}: blocker ${id} has no confirmed completed contribution for destination ${destination} (${branch})`,
5150
+ )
5151
+ }
5152
+ }
5153
+ }
5154
+ const lifecycle = analyzeDependencies(ticket.ref.id, fallback, nodes)
5155
+ unresolved.push(...lifecycle.unresolved)
5156
+ diagnostics.push(...lifecycle.diagnostics)
5157
+ if ([...required.values()].every((ids) => ids.length === 0)) return { unresolved, diagnostics }
5158
+ try {
5159
+ let observed = observations.get(destination)
5160
+ if (!observed) {
5161
+ const forge = this.kernelForge()
5162
+ if (!forge.remoteBranchSha || (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite))
5163
+ throw new Error('forge cannot snapshot destination presence')
5164
+ const head = await forge.remoteBranchSha(branch)
5165
+ const evidence = JSON.stringify({
5166
+ version: 2,
5167
+ revisions: [
5168
+ ...inputs.entries
5169
+ .filter(({ digest }) => digest.mergedSha || digest.nodeContribution)
5170
+ .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq]),
5171
+ ...[...inputs.states].map(([slug, state]) => [slug, state.lastSeq]),
5172
+ ].sort(),
5173
+ })
5174
+ const cached = this.store.repositoryFacts().presence[destination]
5175
+ if (cached?.head === head && cached.branch === branch && cached.evidence === evidence)
5176
+ observed = cached
5177
+ else
5178
+ observed = await this.withKernelRepository(async (path) => {
5179
+ const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
5180
+ let sampled: string
5181
+ if (forge.snapshotBase)
5182
+ sampled = await forge.snapshotBase({
5183
+ workspacePath: path,
5184
+ base: branch,
5185
+ destinationRef,
5186
+ })
5187
+ else if (target && forge.rewrite)
5188
+ sampled = await forge.rewrite.snapshot({
5189
+ workspacePath: path,
5190
+ branch,
5191
+ destinationRef,
5192
+ })
5193
+ else {
5194
+ const exec = forge.kernelExec ?? this.deps.exec
5195
+ const fetch = await exec(
5196
+ [
5197
+ 'git',
5198
+ 'fetch',
5199
+ '--no-tags',
5200
+ '--no-write-fetch-head',
5201
+ '--refmap=',
5202
+ 'origin',
5203
+ `+refs/heads/${branch}:${destinationRef}`,
5204
+ ],
5205
+ { cwd: path },
5206
+ )
5207
+ if (fetch.exitCode !== 0) throw new Error(fetch.stderr)
5208
+ const resolved = await exec(
5209
+ ['git', 'rev-parse', '--verify', `${destinationRef}^{commit}`],
5210
+ { cwd: path },
5211
+ )
5212
+ if (resolved.exitCode !== 0) throw new Error(resolved.stderr)
5213
+ sampled = resolved.stdout.trim()
5214
+ }
5215
+ if (sampled !== head) throw new Error('destination moved while sampling presence')
5216
+ const identities = await observePresence(
5217
+ { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
5218
+ head,
5219
+ inputs.landings,
5220
+ inputs.aliases,
5221
+ )
5222
+ const payload = { branch, destination, head, evidence, identities }
5223
+ await this.store.ensureRepo(this.deps.repo)
5224
+ await this.store.appendRepo(this.deps.repo, {
5225
+ actor: DISPATCHER,
5226
+ type: 'change-presence.observed',
5227
+ payload,
5228
+ })
5229
+ return payload
5230
+ })
5231
+ observations.set(destination, observed)
5232
+ }
5233
+ for (const [id, identities] of required) {
5234
+ const missing = missingChanges(identities, observed.identities)
5235
+ if (missing.length) {
5236
+ unresolved.push(id)
5237
+ diagnostics.push(
5238
+ `ticket ${ticket.ref.id}: blocker ${id} is not present in ${destination} (${branch}) at ${observed.head}; missing ${missing.join(', ')}`,
5239
+ )
5240
+ }
5241
+ }
5242
+ } catch (error) {
5243
+ for (const id of required.keys()) {
5244
+ unresolved.push(id)
5245
+ diagnostics.push(
5246
+ `ticket ${ticket.ref.id}: blocker ${id} presence unavailable in ${destination} (${branch}): ${error instanceof Error ? error.message : String(error)}`,
5247
+ )
5248
+ }
5249
+ }
5250
+ return { unresolved, diagnostics }
5251
+ }
5252
+
3377
5253
  private async loadDependencyGraph(
3378
5254
  ticket: Ticket,
3379
5255
  nodes: Map<string, DependencyState>,
3380
5256
  opts: TickOpts = {},
5257
+ builtTickets?: ReadonlySet<string>,
3381
5258
  ): Promise<boolean> {
3382
5259
  const visited = new Set<string>()
3383
5260
  let frontier = [...new Set(ticket.blockedBy ?? [])]
@@ -3392,7 +5269,12 @@ export class Dispatcher {
3392
5269
  for (const id of frontier) {
3393
5270
  visited.add(id)
3394
5271
  const node = nodes.get(id)
3395
- if (node?.exists && !node.resolved) next.push(...node.blockedBy)
5272
+ if (
5273
+ node?.exists &&
5274
+ !node.resolved &&
5275
+ !builtTickets?.has(JSON.stringify([ticket.ref.source, id]))
5276
+ )
5277
+ next.push(...node.blockedBy)
3396
5278
  }
3397
5279
  frontier = [...new Set(next)].filter((id) => !visited.has(id))
3398
5280
  }