@defrex/autobuild 0.14.0 → 1.0.0-beta.1

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 (173) hide show
  1. package/README.md +13 -6
  2. package/SPEC.md +657 -100
  3. package/docs/architecture.md +230 -5
  4. package/docs/assets/headline-wide.png +0 -0
  5. package/docs/configuration.md +118 -14
  6. package/docs/hosted-service.md +18 -0
  7. package/docs/integration-tree.md +117 -0
  8. package/docs/landing-policy.md +150 -0
  9. package/docs/mcp.md +24 -0
  10. package/docs/migration-1.0.md +68 -0
  11. package/docs/operator-api.md +19 -8
  12. package/docs/remote-store-protocol.md +30 -7
  13. package/docs/remote-ticket-protocol.md +26 -5
  14. package/docs/restacking.md +79 -0
  15. package/docs/setup.md +53 -6
  16. package/docs/ticket-dependencies.md +69 -0
  17. package/docs/ticket-migration.md +8 -0
  18. package/package.json +3 -3
  19. package/packages/core/src/cli/attention.ts +25 -2
  20. package/packages/core/src/cli/build-control.ts +65 -41
  21. package/packages/core/src/cli/context.ts +54 -2
  22. package/packages/core/src/cli/dashboard/actions.ts +6 -3
  23. package/packages/core/src/cli/dashboard/landing-display.ts +6 -0
  24. package/packages/core/src/cli/dashboard/live.ts +5 -0
  25. package/packages/core/src/cli/dashboard/model.ts +142 -18
  26. package/packages/core/src/cli/dashboard/poll.ts +15 -9
  27. package/packages/core/src/cli/dashboard/refresh.ts +183 -0
  28. package/packages/core/src/cli/dashboard/render.ts +78 -28
  29. package/packages/core/src/cli/dashboard/repository-poll.ts +57 -0
  30. package/packages/core/src/cli/dashboard/selection.ts +7 -1
  31. package/packages/core/src/cli/dashboard/tree.ts +107 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +156 -105
  33. package/packages/core/src/cli/dispatch.ts +257 -139
  34. package/packages/core/src/cli/dispatcher-liveness.ts +15 -2
  35. package/packages/core/src/cli/help.ts +52 -33
  36. package/packages/core/src/cli/init-validation.ts +43 -2
  37. package/packages/core/src/cli/keyboard.ts +6 -0
  38. package/packages/core/src/cli/landings.ts +18 -0
  39. package/packages/core/src/cli/main.ts +49 -15
  40. package/packages/core/src/cli/mcp.ts +9 -0
  41. package/packages/core/src/cli/publication-settlement.ts +168 -2
  42. package/packages/core/src/cli/repository-status.ts +11 -0
  43. package/packages/core/src/cli/status.ts +72 -5
  44. package/packages/core/src/cli/terminal-restore.ts +54 -0
  45. package/packages/core/src/cli/terminal.ts +16 -2
  46. package/packages/core/src/cli/terminals.ts +98 -79
  47. package/packages/core/src/cli/ticket-editor.ts +10 -3
  48. package/packages/core/src/cli/ticket.ts +113 -18
  49. package/packages/core/src/cli/upgrade-commit.ts +4 -0
  50. package/packages/core/src/cli/upgrade-compatibility.ts +2 -2
  51. package/packages/core/src/cli/upgrade-landing.ts +69 -0
  52. package/packages/core/src/cli/upgrade.ts +16 -0
  53. package/packages/core/src/cli/wait.ts +115 -19
  54. package/packages/core/src/cli/watch.ts +51 -12
  55. package/packages/core/src/config/landing.ts +22 -0
  56. package/packages/core/src/config/live.ts +1 -0
  57. package/packages/core/src/config/schema.ts +3 -0
  58. package/packages/core/src/events/catalog.ts +48 -3
  59. package/packages/core/src/events/payloads.ts +295 -6
  60. package/packages/core/src/events/repository.ts +31 -0
  61. package/packages/core/src/integration/harness.ts +10 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-registry.test.ts.snap +1030 -239
  63. package/packages/core/src/kernel/auto-merge-default.ts +1 -0
  64. package/packages/core/src/kernel/auto-merge.ts +12 -3
  65. package/packages/core/src/kernel/build-identity.ts +94 -0
  66. package/packages/core/src/kernel/change-presence.ts +179 -0
  67. package/packages/core/src/kernel/dispatch-status.ts +17 -1
  68. package/packages/core/src/kernel/engine.ts +89 -2
  69. package/packages/core/src/kernel/generators/build-log.ts +23 -0
  70. package/packages/core/src/kernel/generators/leaf-restack-log.ts +110 -0
  71. package/packages/core/src/kernel/generators/node-restack-log.ts +94 -0
  72. package/packages/core/src/kernel/generators/repository-journals.ts +11 -0
  73. package/packages/core/src/kernel/integration-completeness.ts +81 -0
  74. package/packages/core/src/kernel/integration-landing.ts +263 -0
  75. package/packages/core/src/kernel/integration-stack.ts +36 -0
  76. package/packages/core/src/kernel/integration-state.ts +135 -0
  77. package/packages/core/src/kernel/landing-policy.ts +47 -0
  78. package/packages/core/src/kernel/landing-publication.ts +41 -0
  79. package/packages/core/src/kernel/landing-readiness.ts +67 -0
  80. package/packages/core/src/kernel/landing-state.ts +96 -0
  81. package/packages/core/src/kernel/leaf-restack-completion.ts +24 -0
  82. package/packages/core/src/kernel/leaf-restack-state.ts +73 -0
  83. package/packages/core/src/kernel/log-index.ts +35 -5
  84. package/packages/core/src/kernel/node-landing.ts +439 -0
  85. package/packages/core/src/kernel/node-parent.ts +184 -0
  86. package/packages/core/src/kernel/node-restack-state.ts +191 -0
  87. package/packages/core/src/kernel/node-restack-transaction.ts +210 -0
  88. package/packages/core/src/kernel/node-restack.ts +274 -0
  89. package/packages/core/src/kernel/read-facts.ts +70 -3
  90. package/packages/core/src/kernel/reconcile-head.ts +51 -0
  91. package/packages/core/src/kernel/reconcile-restack.ts +560 -0
  92. package/packages/core/src/kernel/reducer-registry.ts +16 -0
  93. package/packages/core/src/kernel/reducer.ts +121 -6
  94. package/packages/core/src/kernel/snapshot-parent.ts +33 -0
  95. package/packages/core/src/ontology.ts +9 -1
  96. package/packages/core/src/operator/annotations.ts +12 -0
  97. package/packages/core/src/operator/control.ts +6 -0
  98. package/packages/core/src/operator/index.ts +4 -0
  99. package/packages/core/src/operator/landings.ts +35 -0
  100. package/packages/core/src/operator/presentation.ts +1 -0
  101. package/packages/core/src/operator/protocol.ts +12 -3
  102. package/packages/core/src/operator/query.ts +3 -1
  103. package/packages/core/src/operator/registry.ts +48 -19
  104. package/packages/core/src/operator/requests.ts +1 -8
  105. package/packages/core/src/operator/tickets.ts +55 -9
  106. package/packages/core/src/plugins/load.ts +3 -4
  107. package/packages/core/src/ports/forge/contract.ts +91 -3
  108. package/packages/core/src/ports/forge/fake.ts +142 -4
  109. package/packages/core/src/ports/forge/git-rewrite.ts +232 -0
  110. package/packages/core/src/ports/forge/github-readiness.ts +421 -0
  111. package/packages/core/src/ports/forge/github.ts +631 -35
  112. package/packages/core/src/ports/forge/local-git.ts +119 -5
  113. package/packages/core/src/ports/forge/readiness.ts +99 -0
  114. package/packages/core/src/ports/tickets/contract.ts +41 -0
  115. package/packages/core/src/ports/tickets/create.ts +8 -1
  116. package/packages/core/src/ports/tickets/fake.ts +32 -1
  117. package/packages/core/src/ports/tickets/file-codec.ts +7 -0
  118. package/packages/core/src/ports/tickets/file.ts +18 -1
  119. package/packages/core/src/ports/tickets/hosted-index.ts +2 -0
  120. package/packages/core/src/ports/tickets/linear.ts +124 -4
  121. package/packages/core/src/ports/tickets/migration.ts +25 -1
  122. package/packages/core/src/ports/tickets/operations.ts +7 -2
  123. package/packages/core/src/ports/tickets/remote-protocol.ts +19 -0
  124. package/packages/core/src/ports/tickets/remote.ts +10 -1
  125. package/packages/core/src/ports/tickets/revision.ts +3 -1
  126. package/packages/core/src/ports/tickets/tree.ts +148 -0
  127. package/packages/core/src/ports/tickets/update.ts +15 -2
  128. package/packages/core/src/ports/types.ts +135 -5
  129. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  130. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -1
  131. package/packages/core/src/ports/workspace/vercel-sandbox.ts +60 -3
  132. package/packages/core/src/processes/build-runner.ts +530 -23
  133. package/packages/core/src/processes/dispatcher-selectors.ts +15 -9
  134. package/packages/core/src/processes/dispatcher.ts +2145 -203
  135. package/packages/core/src/processes/execution-no-progress.ts +46 -1
  136. package/packages/core/src/processes/publication-state.ts +30 -5
  137. package/packages/core/src/processes/repo-view.ts +21 -2
  138. package/packages/core/src/store/build-scope.ts +18 -0
  139. package/packages/core/src/store/contract.ts +658 -0
  140. package/packages/core/src/store/digest.ts +52 -4
  141. package/packages/core/src/store/local/schema.ts +25 -13
  142. package/packages/core/src/store/local/store.ts +117 -1
  143. package/packages/core/src/store/memory.ts +62 -1
  144. package/packages/core/src/store/phase-session.ts +17 -0
  145. package/packages/core/src/store/reduced-reads.ts +2 -1
  146. package/packages/core/src/store/reducer-value-shapes.json +10707 -6440
  147. package/packages/core/src/store/remote/client.ts +45 -0
  148. package/packages/core/src/store/remote/compatibility.ts +25 -9
  149. package/packages/core/src/store/remote/protocol.ts +11 -0
  150. package/packages/core/src/store/repo-state-events.ts +2 -0
  151. package/packages/core/src/store/session-handle.ts +15 -0
  152. package/packages/core/src/store/subscribe.ts +1 -1
  153. package/packages/core/src/store/types.ts +34 -4
  154. package/packages/core/src/testing/index.ts +2 -0
  155. package/packages/core/src/testing/reduced-read-budget.ts +48 -8
  156. package/packages/core/src/testing/refresh-scheduler.ts +32 -0
  157. package/skills/guide/SKILL.md +117 -64
  158. package/skills/guide/references/integration-tree.md +117 -0
  159. package/skills/guide/references/landing-policy.md +150 -0
  160. package/skills/guide/references/migration-1.0.md +68 -0
  161. package/skills/guide/references/operator-api.md +12 -5
  162. package/skills/guide/references/plugin-authoring.md +42 -3
  163. package/skills/guide/references/remote-store-protocol.md +30 -7
  164. package/skills/guide/references/remote-ticket-protocol.md +26 -5
  165. package/skills/guide/references/restacking.md +79 -0
  166. package/skills/guide/references/setup.md +53 -6
  167. package/skills/guide/references/ticket-dependencies.md +69 -0
  168. package/skills/guide/references/ticket-migration.md +8 -0
  169. package/skills/operate/SKILL.md +55 -5
  170. package/skills/reconcile/SKILL.md +55 -48
  171. package/skills/spec/SKILL.md +67 -1
  172. package/skills/tickets/SKILL.md +55 -2
  173. package/templates/autobuild.toml +3 -0
@@ -1,5 +1,44 @@
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'
1
40
  import { readBuildDigests } from '../store/reduced-reads'
2
- import { readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
41
+ import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
3
42
  import { ensureExecutionProgress } from './execution-no-progress'
4
43
  import { ticketIdentity } from '../ports/tickets/identity'
5
44
  import { ticketLifecycle } from '../ports/tickets/lifecycle'
@@ -47,21 +86,13 @@ import { createHash } from 'node:crypto'
47
86
  import type { Config } from '../config/schema'
48
87
  import type { LanguageModel } from 'ai'
49
88
  import { runOrchestratorTickStep } from './orchestrator-tick'
50
- import { DISPATCHER, agentActor, humanActor } from '../events/envelope'
89
+ import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
51
90
  import { isRemoteWorkspace } from '../events/workspace-remote'
52
91
  import type { AbEvent, EventWrite } from '../events/catalog'
53
92
  import type { EventPayload, PinnedAsset } from '../events/payloads'
54
93
  import type { IdSource } from '../ids'
55
- import {
56
- autoMergeApplicationType,
57
- pendingAutoMerge,
58
- recordAutoMergeDeferralObservation,
59
- } from '../kernel/auto-merge'
60
- import {
61
- autoMergeDefaultTarget,
62
- pickAutoMergeDefault,
63
- type AutoMergeDefaultFact,
64
- } from '../kernel/auto-merge-default'
94
+ import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
95
+ import type { AutoMergeDefaultFact } from '../kernel/auto-merge-default'
65
96
  import { decideNextFromFacts } from '../kernel/engine'
66
97
  import { composeBuildConfig } from '../config/live'
67
98
  import { BUILD_EFFECTIVE_CONFIG_ARTIFACT, parseEffectiveBuildConfig } from './build-execution-state'
@@ -81,7 +112,7 @@ import type {
81
112
  TicketSource,
82
113
  WorkspaceProvider,
83
114
  } from '../ports/types'
84
- import { TicketSourceRateLimitError } from '../ports/types'
115
+ import { NoCommitsBetweenBranchesError, TicketSourceRateLimitError } from '../ports/types'
85
116
  import type { Exec } from '../ports/workspace/git-worktree'
86
117
  import type { ArtifactMeta, BuildDigest, BuildRecord, BuildStore, Clock } from '../store/types'
87
118
  import { preparePinnedAssets } from '../store/ticket-assets'
@@ -635,6 +666,59 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
635
666
  }
636
667
 
637
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
+
638
722
  /** Read at each decision boundary: artifact revisions are independent of events. */
639
723
  private async decideBuild(
640
724
  slug: string,
@@ -749,17 +833,13 @@ export class Dispatcher {
749
833
  }
750
834
 
751
835
  private async runTick(opts: TickOpts): Promise<TickReport> {
836
+ this.integrationInputs = undefined
837
+ this.integrationPublicationInputs = undefined
752
838
  // One immutable config for this complete decision pass. A reload racing the
753
839
  // tick is observed by the next tick, never half-way through this one.
754
840
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
755
841
  if (opts.viewRefreshed !== true) await this.store.refresh()
756
- let autoMergeUser: string | undefined
757
- if (opts.defaultAutoMerge === true) {
758
- autoMergeUser = opts.autoMergeUser?.trim()
759
- if (autoMergeUser === undefined || autoMergeUser === '') {
760
- throw new Error('defaultAutoMerge requires nonempty human attribution in autoMergeUser')
761
- }
762
- }
842
+ const autoMergeUser = undefined
763
843
  const report = emptyTickReport()
764
844
  this.restoreScan(report)
765
845
  /** Builds already launched this tick — a janitor/startup re-attach must
@@ -772,16 +852,7 @@ export class Dispatcher {
772
852
  // pretends to a serialization the store does not offer.
773
853
  const repoFacts = this.store.repositoryFacts()
774
854
  const paused = repoFacts.settings.paused
775
- const autoMergeDefault = pickAutoMergeDefault(repoFacts.autoMerge)
776
- // The claim-time seed cites the newest fact whose enabled state matches
777
- // the launch sample, not blindly the newest fact: the CLI samples
778
- // `defaultAutoMerge` from its own earlier read, so an interleaved toggle
779
- // can make this tick's read newer-and-opposite. Citing the matching fact
780
- // keeps the newer opposite fact strictly ahead of the seed's provenance,
781
- // so the fan-out reconciles the build on the next tick instead of the
782
- // stale sample out-voting the durable default forever (f_b851c0e8).
783
- const autoMergeSeedFact =
784
- opts.defaultAutoMerge === true ? pickAutoMergeDefault(repoFacts.autoMerge, true) : undefined
855
+ const autoMergeSeedFact = undefined
785
856
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
786
857
  // provider liveness and settle their completion, lease, and publication.
787
858
  // Runs before the janitor so its executionLeaseLive checks see freshly
@@ -801,7 +872,6 @@ export class Dispatcher {
801
872
  // inside `checkPr`). Independent of intake and `acceptNewWork` — the
802
873
  // durable fact drives it, so a second dispatcher polling the same
803
874
  // repository converges the same state.
804
- await this.applyAutoMergeDefault(autoMergeDefault)
805
875
  if (this.outOfBudget(opts)) return report
806
876
  await this.janitor(report, launched, opts)
807
877
  if (this.outOfBudget(opts)) return report
@@ -922,7 +992,7 @@ export class Dispatcher {
922
992
  * end. A terminal, settled build costs no event reads. */
923
993
  private async workBuilds(): Promise<BuildRecord[]> {
924
994
  return (await this.repoBuildDigests())
925
- .filter(({ digest }) => isWorkDigest(digest))
995
+ .filter(({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true)
926
996
  .map(({ record }) => record)
927
997
  }
928
998
 
@@ -930,7 +1000,6 @@ export class Dispatcher {
930
1000
  next?: TicketSourceDegradation,
931
1001
  successfulOperation?: 'ready-scan' | 'dependency-check',
932
1002
  ): Promise<void> {
933
- await this.store.refreshJournal()
934
1003
  const current = this.store.repositoryFacts().health
935
1004
  if (next !== undefined && current?.cause === next.cause && current.source === next.source) {
936
1005
  if (
@@ -1022,25 +1091,23 @@ export class Dispatcher {
1022
1091
  * disabled. It shares the active-ticket exclusion with dispatch but performs
1023
1092
  * no dependency fetch, claim, bounce, build, workspace, or launch side
1024
1093
  * effect, and deliberately does not alter TickReport compatibility. */
1025
- async observeReady(): Promise<{
1094
+ async observeReady(opts: Pick<TickOpts, 'viewRefreshed'> = {}): Promise<{
1026
1095
  queued: number
1027
1096
  invalidTickets: number
1028
1097
  ticketDiagnostics: string[]
1029
1098
  }> {
1030
1099
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1031
- await this.store.refresh()
1100
+ if (opts.viewRefreshed !== true) await this.store.refresh()
1032
1101
  const report = emptyTickReport()
1033
1102
  this.restoreScan(report)
1034
1103
  const checkpoint = await this.scanCheckpoint('observation')
1035
1104
  if (checkpoint.due) {
1036
- await this.store.refreshJournal()
1037
1105
  const listing = await this.listReady()
1038
1106
  const refs: TicketRef[] = []
1039
1107
  for (const { record, digest } of await this.repoBuildDigests()) {
1040
1108
  if (record.ticket && digest.terminal === undefined) refs.push(record.ticket)
1041
1109
  }
1042
1110
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
1043
- await this.store.refreshJournal()
1044
1111
  report.queued = listing.tickets.filter(
1045
1112
  (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
1046
1113
  ).length
@@ -1134,60 +1201,10 @@ export class Dispatcher {
1134
1201
  })
1135
1202
  }
1136
1203
 
1137
- /** Apply the newest durable `dispatcher.auto-merge-default-set` fact to every
1138
- * current non-terminal build of this repository: on — request consent; off —
1139
- * cancel it. Attribution is the toggling human's own actor, exactly as if
1140
- * they had pressed `m` on each row; each command carries the fact's seq so
1141
- * the fan-out is idempotent (a settled build fails `autoMergeDefaultTarget`)
1142
- * and a per-build override stands until the default is toggled again. A fact
1143
- * whose value already matches the build's state writes a provenance-only
1144
- * `build.auto-merge-default-observed` marker instead of a duplicate command,
1145
- * so the matching fact is recorded as answered (f_28b3fba1).
1146
- *
1147
- * Per build, a compare-and-set loop (the `requestOne` shape from
1148
- * `bulk-control.ts`): the read/reduce/evaluate lives inside the loop, so a
1149
- * competing write loses at most one attempt and the next re-reads fresh
1150
- * state. No TickReport counter: the evidence is the build events, and the
1151
- * report shape stays compatible. */
1152
- private async applyAutoMergeDefault(fact: AutoMergeDefaultFact | undefined): Promise<void> {
1153
- if (fact === undefined) return
1154
- const store = this.store
1155
-
1156
- // Terminal builds are never eligible (`autoMergeDefaultEligible`).
1157
- for (const record of (await this.nonterminalBuilds()).sort((a, b) =>
1158
- a.slug.localeCompare(b.slug),
1159
- )) {
1160
- while (true) {
1161
- const { state } = await store.buildFacts(record.slug)
1162
- const target = autoMergeDefaultTarget(state, fact)
1163
- if (target === undefined) break
1164
- if (target === 'observed') {
1165
- const observed = await store.appendIfCurrent(record.slug, state.lastSeq, {
1166
- actor: DISPATCHER,
1167
- type: 'build.auto-merge-default-observed',
1168
- payload: { defaultSeq: fact.seq },
1169
- })
1170
- if (observed !== null) break
1171
- continue
1172
- }
1173
- const type =
1174
- target === 'request' ? 'build.auto-merge-requested' : 'build.auto-merge-cancelled'
1175
- const appended = await store.appendIfCurrent(record.slug, state.lastSeq, {
1176
- actor: fact.actor,
1177
- type,
1178
- payload: { defaultSeq: fact.seq },
1179
- })
1180
- if (appended !== null) break
1181
- }
1182
- }
1183
- }
1184
-
1185
1204
  private async triggerHarvest(): Promise<void> {
1186
1205
  const start = this.deps.startHarvest
1187
1206
  if (start === undefined) return
1188
- // The journal moves under foreign harvest writers while the stages run, so
1189
- // take the delta before deciding.
1190
- await this.store.refreshJournal()
1207
+ // Use the tick sample, advanced by any local repository append.
1191
1208
  if (!this.store.journalRecorded()) {
1192
1209
  start()
1193
1210
  return
@@ -1204,8 +1221,20 @@ export class Dispatcher {
1204
1221
  launched: Set<string>,
1205
1222
  report: TickReport = emptyTickReport(),
1206
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'
1207
1231
  if (launched.has(slug)) return 'already-active'
1208
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
+ }
1209
1238
  if (
1210
1239
  !(await ensureExecutionProgress(
1211
1240
  this.store,
@@ -1279,20 +1308,7 @@ export class Dispatcher {
1279
1308
  * repository lease. */
1280
1309
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
1281
1310
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
1282
- let facts: ReturnType<RepoViewStore['repositoryFacts']>
1283
- try {
1284
- // The earlier stages awaited providers; take the journal delta so a
1285
- // foreign append (operator activity, harvest facts) made meanwhile is
1286
- // seen before any destructive decision below.
1287
- await this.store.refreshJournal()
1288
- facts = this.store.repositoryFacts()
1289
- } catch {
1290
- // The read itself failed (a transient store error — a missing record
1291
- // answers `[]` inside the helper, so it never reaches this arm):
1292
- // skipping this settlement stage for this tick while the rest of the
1293
- // tick proceeds, and the next tick retries what remains.
1294
- return
1295
- }
1311
+ const facts = this.store.repositoryFacts()
1296
1312
  for (const execution of facts.openHarvest) {
1297
1313
  if (active.has(execution.execution)) continue
1298
1314
  // Budget gate: once spent, stop settling further harvest executions;
@@ -1382,22 +1398,9 @@ export class Dispatcher {
1382
1398
  const capability = this.deps.workspaces.orchestratorSandbox
1383
1399
  if (capability === undefined) return
1384
1400
  const providerName = this.deps.workspaces.name
1385
- let facts: ReturnType<RepoViewStore['repositoryFacts']>
1386
- try {
1387
- // The earlier stages awaited providers; take the journal delta so a
1388
- // foreign append (operator activity, harvest facts) made meanwhile is
1389
- // seen before any destructive decision below.
1390
- await this.store.refreshJournal()
1391
- facts = this.store.repositoryFacts()
1392
- } catch {
1393
- // The read itself failed (a transient store error — a missing record
1394
- // answers `[]` inside the helper, so it never reaches this arm):
1395
- // skipping this settlement stage for this tick while the rest of the
1396
- // tick proceeds, and the next tick retries what remains.
1397
- return
1398
- }
1401
+ const facts = this.store.repositoryFacts()
1399
1402
  const idleMs = config.orchestrator.sandbox.idleMinutes * 60_000
1400
- for (const environment of facts.sandboxes) {
1403
+ for (let environment of facts.sandboxes) {
1401
1404
  if (environment.state !== 'live') continue
1402
1405
  // Budget gate: once spent, stop settling further environments; the
1403
1406
  // next tick retries what remains.
@@ -1407,6 +1410,25 @@ export class Dispatcher {
1407
1410
  continue
1408
1411
  }
1409
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
1410
1432
  if (environment.provider !== providerName) {
1411
1433
  // Provider-mismatch disposition (AUT-377): the journaled provider no
1412
1434
  // longer matches the wired provider, so environmentIds are out of this
@@ -1618,11 +1640,14 @@ export class Dispatcher {
1618
1640
  // Local providers provision FROM the physical checkout; remote
1619
1641
  // providers ignore the value (their host seams are injected).
1620
1642
  repo: this.deps.checkout ?? this.deps.repo,
1621
- baseBranch: baseBranchOf(events, config),
1643
+ baseBranch:
1644
+ events.state.kind === 'node' && events.state.integration?.cycle
1645
+ ? input.branch
1646
+ : baseBranchOf(events, config),
1622
1647
  branch: input.branch,
1623
1648
  ...(priorGenerations > 0 || input.generation > 0
1624
1649
  ? {
1625
- revision: this.recoveryCheckpoint(events),
1650
+ revision: events.state.integration?.cycle?.head ?? this.recoveryCheckpoint(events),
1626
1651
  generation: Math.max(priorGenerations, input.generation),
1627
1652
  }
1628
1653
  : {}),
@@ -1768,7 +1793,9 @@ export class Dispatcher {
1768
1793
  // Only this repo's builds that still have work (§12: another repo's
1769
1794
  // builds are another dispatcher's duty; settled terminal builds cost no
1770
1795
  // event reads).
1771
- const entries = (await this.repoBuildDigests()).filter(({ digest }) => isWorkDigest(digest))
1796
+ const entries = (await this.repoBuildDigests()).filter(
1797
+ ({ digest }) => isWorkDigest(digest) || digest.integrationAuditPending === true,
1798
+ )
1772
1799
  for (const { record, digest } of entries) {
1773
1800
  // Budget gate: the janitor's per-build path issues forge/store transport
1774
1801
  // calls (PR probes, closePr, deleteBranch); once the budget is spent,
@@ -1779,7 +1806,7 @@ export class Dispatcher {
1779
1806
  // Once a record is known, contain its complete janitor path: loading
1780
1807
  // and reducing facts, cleanup, forge/ticket calls, and store writes.
1781
1808
  // Existing partial facts leave the same work due on the next tick.
1782
- const { state, workspace } = await this.store.buildFacts(record.slug)
1809
+ let { state, workspace, log } = await this.store.buildFacts(record.slug)
1783
1810
  const executionLeaseLive = this.hasLiveExecutionLease(record)
1784
1811
  // Raw history, read at most once and only by a branch that acts on it:
1785
1812
  // the facts above answer every quiet-path question without it.
@@ -1788,15 +1815,123 @@ export class Dispatcher {
1788
1815
  loaded ??= (await readBuildFacts(this.store, record.slug)).value
1789
1816
  return loaded
1790
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
+ }
1791
1851
  // Pipeline/ticket/workspace state is settled, but release-asset cleanup
1792
1852
  // has its own crash window after build.completed. Revisit only pending
1793
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
+ }
1794
1870
  if (state.status === 'done') {
1795
1871
  if (digest.reclaimPending === true) {
1796
1872
  await this.reclaimPrAttachments(record.slug, await history())
1797
1873
  }
1798
1874
  continue
1799
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
+ }
1800
1935
  // Abort is destructive human judgment and therefore outranks a queued
1801
1936
  // discard when both requests raced into the same stream.
1802
1937
  if (
@@ -1830,6 +1965,17 @@ export class Dispatcher {
1830
1965
  await this.cleanupAborted(record, await history(), report)
1831
1966
  continue
1832
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
+ }
1833
1979
  if (state.pr) {
1834
1980
  await this.checkPr(
1835
1981
  record,
@@ -1838,6 +1984,7 @@ export class Dispatcher {
1838
1984
  report,
1839
1985
  launched,
1840
1986
  executionLeaseLive,
1987
+ observedPr,
1841
1988
  )
1842
1989
  }
1843
1990
  } catch (error) {
@@ -1848,6 +1995,234 @@ export class Dispatcher {
1848
1995
  }
1849
1996
  }
1850
1997
 
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
+
1851
2226
  private forgeWorkspacePath(events: CurrentBuildFacts): string {
1852
2227
  return this.forgeWorkspacePathOf(openWorkspace(events))
1853
2228
  }
@@ -1878,6 +2253,51 @@ export class Dispatcher {
1878
2253
  const store = this.store
1879
2254
  const { tickets, forge } = this.deps
1880
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
1881
2301
  // Whether this build ever owned a local checkout workspace, judged on the
1882
2302
  // provisioned facts (not the open one, which is null when the build never
1883
2303
  // provisioned or already released — only the former must skip the
@@ -1927,7 +2347,16 @@ export class Dispatcher {
1927
2347
  )
1928
2348
  await append(
1929
2349
  result.state === 'merged'
1930
- ? { 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
+ }
1931
2360
  : { actor: DISPATCHER, type: 'pr.closed', payload: {} },
1932
2361
  )
1933
2362
  } catch (error) {
@@ -2059,6 +2488,35 @@ export class Dispatcher {
2059
2488
  report.discarded += 1
2060
2489
  }
2061
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
+
2062
2520
  /** Post-PR epilogue (§15.7): poll the forge, emit `pr.*` facts (deduped
2063
2521
  * against the reduced `prState`), release/complete, project to the ticket. */
2064
2522
  private async checkPr(
@@ -2070,6 +2528,7 @@ export class Dispatcher {
2070
2528
  report: TickReport,
2071
2529
  launched: Set<string>,
2072
2530
  executionLeaseLive: boolean,
2531
+ observedPr?: Awaited<ReturnType<Forge['getPrState']>>,
2073
2532
  ): Promise<void> {
2074
2533
  const store = this.store
2075
2534
  const { tickets, forge } = this.deps
@@ -2078,28 +2537,172 @@ export class Dispatcher {
2078
2537
  // Forge calls run from the workspace when it still exists (it does until
2079
2538
  // the build completes); fall back to the repo itself for odd logs.
2080
2539
  const workspacePath = this.forgeWorkspacePathOf(source.workspace)
2081
- const prState = await forge.getPrState(workspacePath, pr.number)
2082
- const autoMerge = prState.state === 'open' ? pendingAutoMerge(state) : undefined
2083
-
2084
- // Revoking consent takes priority even while the PR is conflicted. A live
2085
- // native request could otherwise merge immediately after reconcile pushes
2086
- // and checks pass, before the next janitor poll gets a chance to cancel it.
2087
- if (autoMerge?.enabled === false) {
2088
- const result = await forge.setAutoMerge(workspacePath, pr.number, false)
2089
- if (result.kind !== 'applied') {
2090
- 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
+ }
2091
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
+ )
2092
2691
  await store.append(record.slug, {
2093
2692
  actor: DISPATCHER,
2094
- type: autoMergeApplicationType(false),
2095
- payload: { commandSeq: autoMerge.commandSeq },
2693
+ type: 'landing.command-acknowledged',
2694
+ payload: { commandSeq: command.seq },
2096
2695
  })
2097
- }
2098
2696
 
2099
2697
  // A positive conflict re-enters reconcile before any enable attempt. In
2100
2698
  // particular, an ungated fallback can never race ahead of the conflict
2101
2699
  // event and its full post-reconcile verification cycle.
2102
- if (prState.state === 'open' && prState.mergeable === false) {
2700
+ if (
2701
+ !integration &&
2702
+ !recoverLanding &&
2703
+ prState.state === 'open' &&
2704
+ prState.mergeable === false
2705
+ ) {
2103
2706
  // Dedupe: a reduced prState of 'conflicted' means reconcile is already
2104
2707
  // pending (a `reconcile.completed` returns it to 'open').
2105
2708
  if (state.prState === 'conflicted') return
@@ -2131,55 +2734,388 @@ export class Dispatcher {
2131
2734
  // predicate. Only `applied` acknowledges native state. A direct merge is
2132
2735
  // owned solely by this janitor and only after the engine is parked at
2133
2736
  // awaiting-pr (all verify/finalize work complete).
2134
- if (prState.state === 'open' && autoMerge?.enabled === true) {
2135
- const result = await forge.setAutoMerge(workspacePath, pr.number, true)
2136
- if (result.kind === 'applied') {
2137
- await store.append(record.slug, {
2138
- actor: DISPATCHER,
2139
- type: autoMergeApplicationType(true),
2140
- payload: { commandSeq: autoMerge.commandSeq },
2141
- })
2142
- } 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) {
2143
2873
  await recordAutoMergeDeferralObservation(
2144
2874
  store,
2145
2875
  record.slug,
2146
- 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
+ },
2147
2881
  pr.number,
2148
- autoMerge.commandSeq,
2882
+ commandSeq,
2149
2883
  this.deps.ids('obs'),
2150
2884
  )
2151
- } else if (result.kind === 'ungated' && prState.mergeable === true) {
2152
- // Re-read at the last possible point. A cancellation, replacement
2153
- // command, newly due pipeline work, or application fact suppresses
2154
- // this attempt; the next tick reclassifies from fresh forge state.
2155
- await store.refreshBuild(record.slug)
2156
- const latest = await store.buildFacts(record.slug)
2157
- const latestState = latest.state
2158
- const latestIntent = pendingAutoMerge(latestState)
2159
- const decision = await this.decideBuild(record.slug, latest.state, latest.log, report)
2160
- if (
2161
- latestState.pr?.number === pr.number &&
2162
- latestIntent?.enabled === true &&
2163
- latestIntent.commandSeq === autoMerge.commandSeq &&
2164
- decision?.kind === 'wait' &&
2165
- decision.reason === 'awaiting-pr'
2166
- ) {
2167
- await forge.squashMerge(workspacePath, pr.number, result.headSha)
2168
- }
2169
2885
  }
2170
2886
  }
2171
-
2172
- switch (prState.state) {
2173
- case 'merged': {
2174
- if (executionLeaseLive) return
2175
- const events = await source.history()
2176
- // Emit the fact once (a crash between steps re-runs this block; the
2177
- // reduced prState dedupes the event, the log dedupes the release).
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
+ })
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
+ })
3008
+ }
3009
+ }
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
+ }
3082
+ switch (prState.state) {
3083
+ case 'merged': {
3084
+ if (executionLeaseLive) return
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
+ }
3112
+ // Emit the fact once (a crash between steps re-runs this block; the
3113
+ // reduced prState dedupes the event, the log dedupes the release).
2178
3114
  if (state.prState !== 'merged') {
2179
3115
  await store.append(record.slug, {
2180
3116
  actor: DISPATCHER,
2181
3117
  type: 'pr.merged',
2182
- payload: { sha: prState.sha },
3118
+ payload: await this.mergeEvidence(record, workspacePath, prState.sha, state.kind),
2183
3119
  } satisfies EventWrite<'pr.merged'>)
2184
3120
  }
2185
3121
  await this.releaseWorkspace(record.slug, events)
@@ -2540,14 +3476,23 @@ export class Dispatcher {
2540
3476
  ticket: TicketRef,
2541
3477
  repo: string,
2542
3478
  seed:
2543
- | { 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
+ }
2544
3487
  | undefined,
2545
3488
  ): EventPayload<'build.created'> {
2546
3489
  const { config } = this.deps
2547
3490
  return {
2548
3491
  ticket,
2549
3492
  repo,
2550
- baseBranch: config.baseBranch,
3493
+ baseBranch: seed?.baseBranch ?? config.baseBranch,
3494
+ ...(seed?.kind !== undefined ? { kind: seed.kind } : {}),
3495
+ ...(seed?.target !== undefined ? { target: seed.target } : {}),
2551
3496
  ...(seed?.autoMergeUser !== undefined ? { autoMergeRequestedBy: seed.autoMergeUser } : {}),
2552
3497
  ...(seed?.autoMergeDefaultSeq !== undefined
2553
3498
  ? { autoMergeDefaultSeq: seed.autoMergeDefaultSeq }
@@ -2621,21 +3566,8 @@ export class Dispatcher {
2621
3566
  }
2622
3567
 
2623
3568
  const created = events.created
2624
- const autoMergeUser = seed?.autoMergeUser ?? created?.payload.autoMergeRequestedBy
2625
- // The claim's sampled default fact, for the request's fan-out provenance:
2626
- // the seed's own value first (this dispatch created the build), else the
2627
- // durable `build.created` fact a recovery pass resumes from.
2628
- const autoMergeDefaultSeq = seed?.autoMergeDefaultSeq ?? created?.payload.autoMergeDefaultSeq
2629
- if (autoMergeUser !== undefined && !events.autoMergeEverRequested) {
2630
- await store.append(record.slug, {
2631
- actor: humanActor(autoMergeUser),
2632
- type: 'build.auto-merge-requested',
2633
- payload: {
2634
- ...(autoMergeDefaultSeq !== undefined ? { defaultSeq: autoMergeDefaultSeq } : {}),
2635
- },
2636
- })
2637
- events = (await readBuildFacts(store, record.slug)).value
2638
- }
3569
+ if (created.payload.kind === 'node')
3570
+ return this.completeDispatchBoundaries(record, seed, report, launched)
2639
3571
 
2640
3572
  stage = 'workspace'
2641
3573
  if (openWorkspace(events) === null) {
@@ -2658,7 +3590,7 @@ export class Dispatcher {
2658
3590
  branch: record.branch ?? `ab/${record.slug}`,
2659
3591
  ...(priorGenerations > 0
2660
3592
  ? {
2661
- revision: this.recoveryCheckpoint(events),
3593
+ revision: events.state.integration?.cycle?.head ?? this.recoveryCheckpoint(events),
2662
3594
  generation: priorGenerations,
2663
3595
  }
2664
3596
  : {}),
@@ -2800,6 +3732,15 @@ export class Dispatcher {
2800
3732
  })
2801
3733
  }
2802
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
+
2803
3744
  stage = 'launch'
2804
3745
  // Discard validation and recovery selection happened before several
2805
3746
  // provider awaits. Re-read immediately before launch so a request made
@@ -2989,6 +3930,12 @@ export class Dispatcher {
2989
3930
  const decision = await this.decideBuild(record.slug, state, facts.log, report)
2990
3931
  if (decision === undefined) continue
2991
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
2992
3939
  // Raw history, read at most once and only by a branch that acts on it.
2993
3940
  let loaded: CurrentBuildFacts | undefined
2994
3941
  const history = async (): Promise<CurrentBuildFacts> => {
@@ -3119,7 +4066,14 @@ export class Dispatcher {
3119
4066
  const activeRefs: TicketRef[] = []
3120
4067
  for (const { record, digest } of await this.repoBuildDigests()) {
3121
4068
  if (digest.terminal === undefined) {
3122
- 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
3123
4077
  if (record.ticket) activeRefs.push(record.ticket)
3124
4078
  }
3125
4079
  }
@@ -3129,11 +4083,12 @@ export class Dispatcher {
3129
4083
  // standing queue-depth report and must stay honest exactly when the
3130
4084
  // dispatcher is saturated. Sources that keep a claimed ticket in the
3131
4085
  // ready state are deduped against the active builds embodying them.
3132
- await this.store.refreshJournal()
3133
4086
  const journalBeforeReady = this.store.repositoryFacts().harvest
3134
4087
  const listing = await this.listReady()
3135
4088
  const activeTicketIds = await this.activeTicketIdentities(activeRefs, listing.tickets)
3136
- await this.store.refreshJournal()
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()
3137
4092
  const journalAfterReady = this.store.repositoryFacts()
3138
4093
  if (journalAfterReady.health?.cause === 'ready-scan-failed') {
3139
4094
  await this.sourceCondition(undefined, 'ready-scan')
@@ -3171,7 +4126,7 @@ export class Dispatcher {
3171
4126
  // still runs either way, so the standing queue-depth report stays honest —
3172
4127
  // this only declines to claim a ticket into a build that would immediately
3173
4128
  // sit held.
3174
- if (capacity <= 0 || paused) {
4129
+ if (paused || (capacity <= 0 && !ready.some((ticket) => ticket.kind === 'node'))) {
3175
4130
  await this.sourceCondition(undefined, 'ready-scan')
3176
4131
  if (!this.outOfBudget(opts)) await this.completeScan(checkpoint, report)
3177
4132
  return
@@ -3194,16 +4149,81 @@ export class Dispatcher {
3194
4149
  // failure must leave the entire ready set unclaimed. Publish dependency
3195
4150
  // diagnostics only after the complete preflight succeeds.
3196
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
+ >()
3197
4179
  const verdicts = new Map<string, DependencyVerdict>()
3198
4180
  const failed = new Set<string>()
4181
+ const targetBlocked = new Set<string>()
4182
+ const preflightTargets = new Map<string, string>()
3199
4183
  for (const ticket of ready) {
3200
4184
  if (this.outOfBudget(opts)) return
3201
4185
  if (withheld.has(ticket.ref.id)) continue
3202
- 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
3203
4197
  let verdict: DependencyVerdict
3204
4198
  try {
3205
- if (!(await this.loadDependencyGraph(ticket, nodes, opts))) return
3206
- 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)
3207
4227
  } catch (error) {
3208
4228
  if (error instanceof TicketSourceRateLimitError) {
3209
4229
  await this.sourceFailure(error, 'dependency-check')
@@ -3228,11 +4248,41 @@ export class Dispatcher {
3228
4248
  }
3229
4249
  }
3230
4250
  for (const ticket of ready) {
3231
- if (capacity <= 0 || this.outOfBudget(opts)) break
4251
+ if (this.outOfBudget(opts)) break
4252
+ if (ticket.kind !== 'node' && capacity <= 0) continue
3232
4253
  if (withheld.has(ticket.ref.id)) continue
3233
- if (failed.has(ticket.ref.id)) continue
4254
+ if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
3234
4255
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
3235
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
+ }
3236
4286
  // Claim-before-launch (§12): losing the claim means another dispatcher
3237
4287
  // (or an earlier tick) owns this ticket.
3238
4288
  if (!(await tickets.claim(ticket.ref.id))) {
@@ -3269,9 +4319,11 @@ export class Dispatcher {
3269
4319
 
3270
4320
  const baseSlug = await this.chooseSlugBase(ticket.title, body)
3271
4321
  const slug = await this.uniqueSlug(baseSlug)
3272
- const branch = `ab/${slug}`
4322
+ const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
3273
4323
  const repoOrigin = await this.resolveRepoOriginOnce()
3274
4324
  const createdSeed = {
4325
+ ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
4326
+ ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
3275
4327
  ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
3276
4328
  // Claim-time provenance: the newest durable default fact that agrees
3277
4329
  // with the launch sample, recorded on `build.created` so the fan-out's
@@ -3296,7 +4348,7 @@ export class Dispatcher {
3296
4348
  },
3297
4349
  })
3298
4350
  report.queued -= 1
3299
- capacity -= 1
4351
+ if (ticket.kind !== 'node') capacity -= 1
3300
4352
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
3301
4353
  ticket,
3302
4354
  body,
@@ -3314,10 +4366,895 @@ export class Dispatcher {
3314
4366
  * Walk unresolved branches in provider order. Listing facts and dependency
3315
4367
  * reads share a tick-local cache; traversal visits are local to this root.
3316
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
+
3317
5253
  private async loadDependencyGraph(
3318
5254
  ticket: Ticket,
3319
5255
  nodes: Map<string, DependencyState>,
3320
5256
  opts: TickOpts = {},
5257
+ builtTickets?: ReadonlySet<string>,
3321
5258
  ): Promise<boolean> {
3322
5259
  const visited = new Set<string>()
3323
5260
  let frontier = [...new Set(ticket.blockedBy ?? [])]
@@ -3332,7 +5269,12 @@ export class Dispatcher {
3332
5269
  for (const id of frontier) {
3333
5270
  visited.add(id)
3334
5271
  const node = nodes.get(id)
3335
- 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)
3336
5278
  }
3337
5279
  frontier = [...new Set(next)].filter((id) => !visited.has(id))
3338
5280
  }