@defrex/autobuild 0.13.0 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/README.md +5 -3
  2. package/SPEC.md +673 -99
  3. package/bin/ab-dispatch-kernel.ts +4 -6
  4. package/docs/architecture.md +322 -75
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +112 -12
  7. package/docs/hosted-service.md +20 -2
  8. package/docs/integration-tree.md +117 -0
  9. package/docs/landing-policy.md +150 -0
  10. package/docs/mcp.md +24 -0
  11. package/docs/migration-1.0.md +68 -0
  12. package/docs/operator-api.md +20 -9
  13. package/docs/remote-store-protocol.md +114 -9
  14. package/docs/remote-ticket-protocol.md +26 -5
  15. package/docs/restacking.md +79 -0
  16. package/docs/setup.md +49 -6
  17. package/docs/ticket-dependencies.md +69 -0
  18. package/docs/ticket-migration.md +8 -0
  19. package/package.json +4 -3
  20. package/packages/core/src/cli/attention.ts +40 -163
  21. package/packages/core/src/cli/build-control.ts +75 -55
  22. package/packages/core/src/cli/bulk-control.ts +3 -2
  23. package/packages/core/src/cli/context.ts +68 -78
  24. package/packages/core/src/cli/dashboard/actions.ts +6 -3
  25. package/packages/core/src/cli/dashboard/landing-display.ts +6 -0
  26. package/packages/core/src/cli/dashboard/live.ts +5 -0
  27. package/packages/core/src/cli/dashboard/model.ts +178 -40
  28. package/packages/core/src/cli/dashboard/poll.ts +15 -9
  29. package/packages/core/src/cli/dashboard/refresh.ts +176 -0
  30. package/packages/core/src/cli/dashboard/render.ts +78 -28
  31. package/packages/core/src/cli/dashboard/repository-poll.ts +57 -0
  32. package/packages/core/src/cli/dashboard/selection.ts +7 -1
  33. package/packages/core/src/cli/dashboard/tree.ts +107 -0
  34. package/packages/core/src/cli/dispatch-frontend.ts +173 -169
  35. package/packages/core/src/cli/dispatch-process.ts +14 -7
  36. package/packages/core/src/cli/dispatch-repository-feed.ts +196 -0
  37. package/packages/core/src/cli/dispatch.ts +397 -214
  38. package/packages/core/src/cli/dispatcher-liveness.ts +41 -21
  39. package/packages/core/src/cli/harvest.ts +71 -39
  40. package/packages/core/src/cli/help.ts +49 -32
  41. package/packages/core/src/cli/historical-build-state.ts +27 -0
  42. package/packages/core/src/cli/init-validation.ts +43 -2
  43. package/packages/core/src/cli/keyboard.ts +6 -0
  44. package/packages/core/src/cli/landings.ts +18 -0
  45. package/packages/core/src/cli/main.ts +52 -18
  46. package/packages/core/src/cli/mcp.ts +9 -0
  47. package/packages/core/src/cli/pr-attachments.ts +10 -13
  48. package/packages/core/src/cli/pr-summary-publication.ts +27 -60
  49. package/packages/core/src/cli/pr-summary.ts +43 -13
  50. package/packages/core/src/cli/publication-settlement.ts +177 -21
  51. package/packages/core/src/cli/repository-status.ts +49 -2
  52. package/packages/core/src/cli/status.ts +133 -36
  53. package/packages/core/src/cli/terminal-restore.ts +54 -0
  54. package/packages/core/src/cli/terminal.ts +16 -2
  55. package/packages/core/src/cli/terminals.ts +121 -219
  56. package/packages/core/src/cli/ticket-editor.ts +10 -3
  57. package/packages/core/src/cli/ticket.ts +115 -20
  58. package/packages/core/src/cli/upgrade-commit.ts +4 -0
  59. package/packages/core/src/cli/upgrade-compatibility.ts +2 -2
  60. package/packages/core/src/cli/upgrade-landing.ts +69 -0
  61. package/packages/core/src/cli/upgrade.ts +16 -0
  62. package/packages/core/src/cli/wait.ts +194 -91
  63. package/packages/core/src/cli/watch.ts +111 -109
  64. package/packages/core/src/config/landing.ts +22 -0
  65. package/packages/core/src/config/live.ts +1 -0
  66. package/packages/core/src/config/pipeline-source.ts +4 -3
  67. package/packages/core/src/config/schema.ts +3 -0
  68. package/packages/core/src/events/catalog.ts +48 -3
  69. package/packages/core/src/events/payloads.ts +295 -6
  70. package/packages/core/src/events/repository.ts +38 -3
  71. package/packages/core/src/integration/harness.ts +11 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-registry.test.ts.snap +3330 -119
  73. package/packages/core/src/kernel/auto-merge-default.ts +1 -0
  74. package/packages/core/src/kernel/auto-merge.ts +29 -4
  75. package/packages/core/src/kernel/build-identity.ts +94 -0
  76. package/packages/core/src/kernel/change-presence.ts +179 -0
  77. package/packages/core/src/kernel/dispatch-status.ts +17 -1
  78. package/packages/core/src/kernel/dispatcher-liveness.ts +10 -4
  79. package/packages/core/src/kernel/engine.ts +89 -2
  80. package/packages/core/src/kernel/generators/build-log.ts +23 -0
  81. package/packages/core/src/kernel/generators/leaf-restack-log.ts +110 -0
  82. package/packages/core/src/kernel/generators/node-restack-log.ts +94 -0
  83. package/packages/core/src/kernel/generators/repository-journals.ts +25 -3
  84. package/packages/core/src/kernel/harvest.ts +25 -23
  85. package/packages/core/src/kernel/integration-completeness.ts +81 -0
  86. package/packages/core/src/kernel/integration-landing.ts +263 -0
  87. package/packages/core/src/kernel/integration-stack.ts +36 -0
  88. package/packages/core/src/kernel/integration-state.ts +135 -0
  89. package/packages/core/src/kernel/landing-policy.ts +47 -0
  90. package/packages/core/src/kernel/landing-publication.ts +41 -0
  91. package/packages/core/src/kernel/landing-readiness.ts +67 -0
  92. package/packages/core/src/kernel/landing-state.ts +96 -0
  93. package/packages/core/src/kernel/leaf-restack-completion.ts +24 -0
  94. package/packages/core/src/kernel/leaf-restack-state.ts +73 -0
  95. package/packages/core/src/kernel/log-index-value.ts +38 -0
  96. package/packages/core/src/kernel/log-index.ts +35 -5
  97. package/packages/core/src/kernel/node-landing.ts +439 -0
  98. package/packages/core/src/kernel/node-parent.ts +184 -0
  99. package/packages/core/src/kernel/node-restack-state.ts +191 -0
  100. package/packages/core/src/kernel/node-restack-transaction.ts +210 -0
  101. package/packages/core/src/kernel/node-restack.ts +274 -0
  102. package/packages/core/src/kernel/read-facts.ts +704 -0
  103. package/packages/core/src/kernel/reconcile-head.ts +51 -0
  104. package/packages/core/src/kernel/reconcile-restack.ts +560 -0
  105. package/packages/core/src/kernel/reducer-registry.ts +153 -3
  106. package/packages/core/src/kernel/reducer.ts +121 -6
  107. package/packages/core/src/kernel/repository-attention.ts +179 -0
  108. package/packages/core/src/kernel/service-facts.ts +135 -0
  109. package/packages/core/src/kernel/snapshot-parent.ts +33 -0
  110. package/packages/core/src/kernel/terminal-guard.ts +133 -0
  111. package/packages/core/src/ontology.ts +9 -1
  112. package/packages/core/src/operator/annotations.ts +12 -0
  113. package/packages/core/src/operator/control.ts +11 -6
  114. package/packages/core/src/operator/index.ts +6 -0
  115. package/packages/core/src/operator/landings.ts +35 -0
  116. package/packages/core/src/operator/presentation.ts +1 -0
  117. package/packages/core/src/operator/protocol.ts +12 -3
  118. package/packages/core/src/operator/query.ts +40 -21
  119. package/packages/core/src/operator/read-view.ts +4 -13
  120. package/packages/core/src/operator/registry.ts +48 -19
  121. package/packages/core/src/operator/requests.ts +3 -22
  122. package/packages/core/src/operator/sandbox.ts +10 -9
  123. package/packages/core/src/operator/tickets.ts +57 -11
  124. package/packages/core/src/plugin-sdk/index.ts +13 -0
  125. package/packages/core/src/ports/forge/contract.ts +91 -3
  126. package/packages/core/src/ports/forge/fake.ts +142 -4
  127. package/packages/core/src/ports/forge/git-rewrite.ts +232 -0
  128. package/packages/core/src/ports/forge/github-readiness.ts +421 -0
  129. package/packages/core/src/ports/forge/github.ts +631 -35
  130. package/packages/core/src/ports/forge/local-git.ts +119 -5
  131. package/packages/core/src/ports/forge/readiness.ts +99 -0
  132. package/packages/core/src/ports/tickets/contract.ts +41 -0
  133. package/packages/core/src/ports/tickets/create.ts +8 -1
  134. package/packages/core/src/ports/tickets/fake.ts +32 -1
  135. package/packages/core/src/ports/tickets/file-codec.ts +7 -0
  136. package/packages/core/src/ports/tickets/file.ts +18 -1
  137. package/packages/core/src/ports/tickets/hosted-index.ts +2 -0
  138. package/packages/core/src/ports/tickets/linear.ts +124 -4
  139. package/packages/core/src/ports/tickets/migration.ts +25 -1
  140. package/packages/core/src/ports/tickets/operations.ts +7 -2
  141. package/packages/core/src/ports/tickets/remote-protocol.ts +19 -0
  142. package/packages/core/src/ports/tickets/remote.ts +10 -1
  143. package/packages/core/src/ports/tickets/revision.ts +3 -1
  144. package/packages/core/src/ports/tickets/tree.ts +148 -0
  145. package/packages/core/src/ports/tickets/update.ts +15 -2
  146. package/packages/core/src/ports/types.ts +135 -5
  147. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  148. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -1
  149. package/packages/core/src/ports/workspace/vercel-sandbox.ts +60 -3
  150. package/packages/core/src/processes/build-child.ts +6 -6
  151. package/packages/core/src/processes/build-runner.ts +586 -87
  152. package/packages/core/src/processes/dispatch-failure-budget.ts +5 -4
  153. package/packages/core/src/processes/dispatcher-selectors.ts +15 -9
  154. package/packages/core/src/processes/dispatcher.ts +2239 -357
  155. package/packages/core/src/processes/execution-no-progress.ts +46 -1
  156. package/packages/core/src/processes/harvest-execution-state.ts +15 -9
  157. package/packages/core/src/processes/harvest-runner.ts +34 -70
  158. package/packages/core/src/processes/harvest.ts +38 -15
  159. package/packages/core/src/processes/infrastructure-failure-budget.ts +13 -15
  160. package/packages/core/src/processes/orchestrator-tick.ts +2 -2
  161. package/packages/core/src/processes/publication-loss.ts +35 -21
  162. package/packages/core/src/processes/publication-state.ts +30 -5
  163. package/packages/core/src/processes/repo-view.ts +244 -1130
  164. package/packages/core/src/processes/tick-publication.ts +110 -0
  165. package/packages/core/src/store/adapter.ts +23 -0
  166. package/packages/core/src/store/build-scope.ts +35 -0
  167. package/packages/core/src/store/contract.ts +909 -0
  168. package/packages/core/src/store/digest.ts +52 -4
  169. package/packages/core/src/store/local/schema.ts +26 -13
  170. package/packages/core/src/store/local/store.ts +296 -55
  171. package/packages/core/src/store/memory.ts +181 -30
  172. package/packages/core/src/store/phase-session.ts +34 -0
  173. package/packages/core/src/store/reduced-reads.ts +240 -0
  174. package/packages/core/src/store/reducer-value-shapes.json +18323 -0
  175. package/packages/core/src/store/reducer-value-validation.ts +96 -0
  176. package/packages/core/src/store/reducer-values.ts +145 -0
  177. package/packages/core/src/store/remote/client.ts +85 -0
  178. package/packages/core/src/store/remote/compatibility.ts +21 -9
  179. package/packages/core/src/store/remote/index.ts +19 -0
  180. package/packages/core/src/store/remote/protocol.ts +27 -0
  181. package/packages/core/src/store/remote/version.ts +3 -1
  182. package/packages/core/src/store/repo-state-events.ts +3 -1
  183. package/packages/core/src/store/repo-tick.ts +72 -0
  184. package/packages/core/src/store/session-handle.ts +34 -0
  185. package/packages/core/src/store/snapshots.ts +10 -0
  186. package/packages/core/src/store/subscribe.ts +1 -1
  187. package/packages/core/src/store/ticket-assets.ts +4 -4
  188. package/packages/core/src/store/types.ts +71 -6
  189. package/packages/core/src/testing/dispatch-read-budget.ts +215 -0
  190. package/packages/core/src/testing/index.ts +10 -0
  191. package/packages/core/src/testing/reduced-read-budget.ts +502 -0
  192. package/packages/core/src/testing/refresh-scheduler.ts +32 -0
  193. package/skills/guide/SKILL.md +116 -62
  194. package/skills/guide/references/integration-tree.md +117 -0
  195. package/skills/guide/references/landing-policy.md +150 -0
  196. package/skills/guide/references/migration-1.0.md +68 -0
  197. package/skills/guide/references/operator-api.md +13 -6
  198. package/skills/guide/references/plugin-authoring.md +34 -0
  199. package/skills/guide/references/remote-store-protocol.md +114 -9
  200. package/skills/guide/references/remote-ticket-protocol.md +26 -5
  201. package/skills/guide/references/restacking.md +79 -0
  202. package/skills/guide/references/setup.md +49 -6
  203. package/skills/guide/references/ticket-dependencies.md +69 -0
  204. package/skills/guide/references/ticket-migration.md +8 -0
  205. package/skills/operate/SKILL.md +55 -5
  206. package/skills/reconcile/SKILL.md +55 -48
  207. package/skills/spec/SKILL.md +67 -1
  208. package/skills/tickets/SKILL.md +55 -2
  209. package/templates/autobuild.toml +3 -0
  210. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,18 @@
1
+ import { suspendNativeLanding } from '../kernel/landing-publication'
2
+ import { integrationCurrent } from '../kernel/integration-state'
3
+ import { replayNodeChange } from '../kernel/node-restack'
4
+ import { restoreReplay } from '../kernel/reconcile-restack'
5
+ import { completeAutomaticReconcile } from '../kernel/leaf-restack-completion'
6
+ import { isRemoteWorkspace } from '../events/workspace-remote'
7
+ import { withBuildTrailer } from '../kernel/build-identity'
8
+ import {
9
+ prepareRestack,
10
+ publishRestack,
11
+ retainReplay,
12
+ requireRewrite,
13
+ } from '../kernel/reconcile-restack'
14
+ import { reconcileHead, reconcileRewriteHead } from '../kernel/reconcile-head'
15
+ import { readBuildFacts, readBuildSelector, readPhaseFailures } from '../store/reduced-reads'
1
16
  import { delegateCredential } from '../store/remote/credentials'
2
17
  import { refreshSummaryBoundary } from '../cli/pr-summary-publication'
3
18
  /**
@@ -50,12 +65,11 @@ import type { Config } from '../config/schema'
50
65
  import type { AbEvent, EventWrite } from '../events/catalog'
51
66
  import type { EventPayload } from '../events/payloads'
52
67
  import { KERNEL, agentActor, type Actor } from '../events/envelope'
53
- import { isRemoteWorkspace } from '../events/workspace-remote'
54
68
  import type { IdSource } from '../ids'
55
- import { decideNext, type Decision } from '../kernel/engine'
69
+ import { decideNextFromFacts, type Decision } from '../kernel/engine'
56
70
  import { defineReducer } from '../kernel/incremental'
57
71
  import { PHASE_SPECS } from '../kernel/phases'
58
- import { reduceBuild, type BuildState } from '../kernel/reducer'
72
+ import type { BuildState } from '../kernel/reducer'
59
73
  import { evaluateVerifyApplicability } from '../kernel/verify-applicability'
60
74
  import {
61
75
  verifyPhase,
@@ -89,12 +103,13 @@ import { phaseScratchRejection, scratchPathsTouchedInRange } from '../ports/work
89
103
  import type { Exec } from '../ports/workspace/git-worktree'
90
104
  import type { BuildScopedStore, Clock } from '../store/types'
91
105
  import { resetsPhaseFailureBudget, type PhaseFailureResetEscalation } from './phase-failure-budget'
92
- import { publicationPending } from './publication-state'
93
106
 
94
107
  export { publicationPending } from './publication-state'
95
108
 
96
109
  // ── Seams ────────────────────────────────────────────────────────────────────
97
110
 
111
+ class AutomaticRewriteDeferred extends Error {}
112
+
98
113
  /** Another sandbox owns the build (§7.4): its lease is live, so this runner
99
114
  * must not execute. The dispatcher retries once the lease expires. */
100
115
  export class LeaseHeldError extends Error {
@@ -435,7 +450,7 @@ export const setupStreakReducer = defineReducer<
435
450
  finish: (acc) => acc.failures.filter((seq) => seq > acc.boundary).length,
436
451
  })
437
452
 
438
- export const PUBLISHED_BRANCH_HEAD_REDUCER_VERSION = 1
453
+ export const PUBLISHED_BRANCH_HEAD_REDUCER_VERSION = 4
439
454
 
440
455
  /** Latest event-checkpointed branch head that kernel plumbing published;
441
456
  * undefined while the build has none. */
@@ -450,8 +465,15 @@ export const publishedBranchHeadReducer = defineReducer<
450
465
  for (const event of events) {
451
466
  if (event.type === 'implement.completed') {
452
467
  acc.head = event.payload.commits.head
468
+ } else if (event.type === 'restack.rewritten' || event.type === 'restack.completed') {
469
+ acc.head =
470
+ event.type === 'restack.rewritten'
471
+ ? (event.payload.observedHead ?? event.payload.headSha)
472
+ : event.payload.headSha
473
+ } else if (event.type === 'reconcile.rewritten') {
474
+ acc.head = reconcileRewriteHead(event.payload)
453
475
  } else if (event.type === 'reconcile.completed') {
454
- acc.head = event.payload.mergeCommit
476
+ acc.head = reconcileHead(event.payload)
455
477
  } else if (
456
478
  event.type === 'finalize.step-completed' &&
457
479
  event.payload.ok &&
@@ -476,7 +498,7 @@ export function selectPublishedBranchHead(events: readonly AbEvent[]): string {
476
498
  return head
477
499
  }
478
500
 
479
- export const VERIFY_DIFF_BASE_REDUCER_VERSION = 1
501
+ export const VERIFY_DIFF_BASE_REDUCER_VERSION = 2
480
502
 
481
503
  /**
482
504
  * The durable tree against which a conditional verifier evaluates the
@@ -496,6 +518,8 @@ export const verifyDiffBaseReducer = defineReducer<
496
518
  for (const event of events) {
497
519
  if (event.type === 'workspace.provisioned') {
498
520
  if (acc.provisioned === undefined) acc.provisioned = event.payload.base.sha
521
+ } else if (event.type === 'restack.completed') {
522
+ acc.promoted = event.payload.targetBase
499
523
  } else if (event.type === 'reconcile.started') {
500
524
  acc.pendingReconcileBase = event.payload.baseSha
501
525
  } else if (event.type === 'reconcile.completed') {
@@ -639,9 +663,6 @@ export class BuildRunner {
639
663
  /** Consecutive durable setup failures since the latest successful attachment
640
664
  * or explicit human answer. The answer re-arms the budget but deliberately
641
665
  * does not erase the current diagnostic while recovery is still running. */
642
- private setupStreak(events: readonly AbEvent[]): number {
643
- return setupStreakReducer.reduce(events)
644
- }
645
666
 
646
667
  private setupQuestion(failure: EventPayload<'runner.setup-failed'>): string {
647
668
  const status =
@@ -671,10 +692,10 @@ export class BuildRunner {
671
692
  * announce takeover against that same boundary. If a write is interrupted,
672
693
  * no attachment lands; the next runner reduces the newer prefix and closes
673
694
  * only sessions that remain open. */
674
- private async reclaimSessionsAndAttach(events: readonly AbEvent[]): Promise<void> {
695
+ private async reclaimSessionsAndAttach(state: BuildState): Promise<void> {
675
696
  const { store, slug, instance, host } = this.deps
676
- const resumedFromSeq = events.at(-1)?.seq ?? 0
677
- for (const session of reduceBuild([...events]).sessions.open) {
697
+ const resumedFromSeq = state.lastSeq
698
+ for (const session of state.sessions.open) {
678
699
  await store.append(slug, {
679
700
  actor: KERNEL,
680
701
  type: 'session.ended',
@@ -704,13 +725,20 @@ export class BuildRunner {
704
725
  * setup succeeds; that fact then proves recovery and clears the projection.
705
726
  */
706
727
  async attach(): Promise<AttachmentResult> {
728
+ const attaching = (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
729
+ if (
730
+ attaching.kind === 'node' &&
731
+ !attaching.nodeRestack?.conflict &&
732
+ !integrationCurrent(attaching)
733
+ )
734
+ throw new Error('integration runners require a reserved node conflict')
707
735
  const config = await this.captureConfig()
708
736
  const { store, slug, instance } = this.deps
709
737
  const claimed = await store.claimLease(slug, instance, this.leaseTtlMs)
710
738
  if (!claimed) throw new LeaseHeldError(slug, instance)
711
739
 
712
- let events = await store.getEvents(slug)
713
- const decision = decideNext(events, config)
740
+ let facts = (await readBuildFacts(store, slug)).value
741
+ const decision = decideNextFromFacts(facts.state, facts.log, config)
714
742
  if (
715
743
  decision.kind === 'acknowledge' &&
716
744
  (decision.command === 'pause' || decision.command === 'abort')
@@ -719,12 +747,22 @@ export class BuildRunner {
719
747
  return { kind: 'control-acknowledged', command: decision.command }
720
748
  }
721
749
 
722
- const state = reduceBuild(events)
750
+ const state = facts.state
751
+ if (state.kind === 'node' && state.integration?.cycle && !state.nodeRestack?.conflict) {
752
+ // Local worktree provisioning may create a new branch at its parent;
753
+ // verification consumes the archived cycle commit, never that mutable tip.
754
+ const checkout = await this.deps.exec(
755
+ ['git', 'checkout', '--detach', state.integration.cycle.head],
756
+ { cwd: this.deps.workspacePath },
757
+ )
758
+ if (checkout.exitCode !== 0)
759
+ throw new Error(`cannot check out prepared integration head: ${checkout.stderr}`)
760
+ }
723
761
  const currentFailure = state.setupFailure
724
762
  const openSetupEscalation = state.openEscalations.some(
725
763
  (escalation) => escalation.phase === 'setup' && escalation.source === 'policy',
726
764
  )
727
- const streak = this.setupStreak(events)
765
+ const streak = await readBuildSelector(store, slug, 'setupStreak')
728
766
 
729
767
  // Crash-safe exhaustion: the final failure and escalation are separate
730
768
  // appends. If only the failure landed, raise the blocker before another
@@ -738,7 +776,7 @@ export class BuildRunner {
738
776
  }
739
777
 
740
778
  const recovering = currentFailure !== undefined
741
- if (!recovering) await this.reclaimSessionsAndAttach(events)
779
+ if (!recovering) await this.reclaimSessionsAndAttach(facts.state)
742
780
 
743
781
  // First beat immediately (liveness visible without waiting an interval),
744
782
  // then keep-alive. Setup runs under this heartbeat so a slow install cannot
@@ -800,8 +838,8 @@ export class BuildRunner {
800
838
 
801
839
  if (recovering) {
802
840
  try {
803
- events = await store.getEvents(slug)
804
- await this.reclaimSessionsAndAttach(events)
841
+ facts = (await readBuildFacts(store, slug)).value
842
+ await this.reclaimSessionsAndAttach(facts.state)
805
843
  } catch (error) {
806
844
  this.stopHeartbeat()
807
845
  this.attached = false
@@ -819,9 +857,14 @@ export class BuildRunner {
819
857
  async step(): Promise<Decision> {
820
858
  const config = await this.captureConfig()
821
859
  const { store, slug } = this.deps
822
- const events = await store.getEvents(slug)
823
- const decision = decideNext(events, config)
860
+ await this.settleLocalReconcile()
861
+ await completeAutomaticReconcile(store, slug)
862
+ const facts = (await readBuildFacts(store, slug)).value
863
+ const decision = decideNextFromFacts(facts.state, facts.log, config)
824
864
  switch (decision.kind) {
865
+ case 'restack':
866
+ await this.restack(decision)
867
+ return decision
825
868
  case 'capture-reconcile-policy':
826
869
  await store.append(slug, {
827
870
  actor: KERNEL,
@@ -851,25 +894,25 @@ export class BuildRunner {
851
894
  await this.raiseEscalation(decision)
852
895
  return decision
853
896
  case 'run-phase':
854
- await this.runPhase(decision, events)
897
+ await this.runPhase(decision)
855
898
  return decision
856
899
  case 'run-check':
857
900
  await this.runCheck(decision)
858
901
  return decision
859
902
  case 'run-agent-verify':
860
- await this.runAgentVerify(decision, events)
903
+ await this.runAgentVerify(decision)
861
904
  return decision
862
905
  case 'evaluate-verify':
863
- await this.evaluateVerify(decision, events)
906
+ await this.evaluateVerify(decision)
864
907
  return decision
865
908
  case 'skip-verify':
866
909
  await this.skipVerify(decision)
867
910
  return decision
868
911
  case 'run-finalize-step':
869
- await this.runFinalizeStep(decision, events)
912
+ await this.runFinalizeStep(decision)
870
913
  return decision
871
914
  case 'check-reconcile-progress':
872
- await this.checkReconcileProgress(decision, events)
915
+ await this.checkReconcileProgress(decision)
873
916
  return decision
874
917
  }
875
918
  }
@@ -882,26 +925,43 @@ export class BuildRunner {
882
925
  * already deposited — see module doc).
883
926
  */
884
927
  async run(): Promise<BuildState> {
928
+ const initial = (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
929
+ if (initial.kind === 'node' && !initial.nodeRestack?.conflict && !integrationCurrent(initial))
930
+ return initial
885
931
  if (!this.attached) {
886
932
  const attachment = await this.attach()
887
933
  if (attachment.kind === 'control-acknowledged') {
888
- return reduceBuild(await this.deps.store.getEvents(this.deps.slug))
934
+ return (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
889
935
  }
890
936
  }
891
937
  try {
938
+ await this.settleLocalReconcile()
892
939
  if (await this.refreshSummary())
893
- return reduceBuild(await this.deps.store.getEvents(this.deps.slug))
894
- if (publicationPending(await this.deps.store.getEvents(this.deps.slug))) {
895
- return reduceBuild(await this.deps.store.getEvents(this.deps.slug))
896
- }
940
+ return (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
897
941
  for (;;) {
898
942
  await this.ensureLease()
943
+ await this.settleLocalReconcile()
944
+ const facts = (await readBuildFacts(this.deps.store, this.deps.slug)).value
945
+ if (facts.publication.pending()) {
946
+ const next = decideNextFromFacts(facts.state, facts.log, await this.captureConfig())
947
+ // Inert controls cannot start more work under unsettled publication.
948
+ // A local paused resolver needs resume acknowledged before this
949
+ // runner can settle its publication; remote guests still park.
950
+ const localResume =
951
+ next.kind === 'acknowledge' &&
952
+ next.command === 'resume' &&
953
+ (facts.workspace === null || !isRemoteWorkspace(facts.workspace))
954
+ if (
955
+ next.kind !== 'acknowledge' ||
956
+ (next.command !== 'pause' && next.command !== 'abort' && !localResume)
957
+ )
958
+ break
959
+ }
899
960
  const decision = await this.step()
900
961
  if (await this.refreshSummary()) break
901
962
  if (decision.kind === 'wait') break
902
- if (publicationPending(await this.deps.store.getEvents(this.deps.slug))) break
903
963
  }
904
- return reduceBuild(await this.deps.store.getEvents(this.deps.slug))
964
+ return (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
905
965
  } finally {
906
966
  this.stopHeartbeat()
907
967
  await this.closeProducerSessions()
@@ -982,12 +1042,14 @@ export class BuildRunner {
982
1042
  * reuse the snapshot as the merge target: actual phase startup refreshes
983
1043
  * again, preserving the execution-boundary freshness guarantee.
984
1044
  */
985
- private async checkReconcileProgress(
986
- decision: CheckReconcileProgressDecision,
987
- events: AbEvent[],
988
- ): Promise<void> {
1045
+ private async checkReconcileProgress(decision: CheckReconcileProgressDecision): Promise<void> {
989
1046
  const { nextAttempt } = decision
990
- const failures = this.phaseFailures(events, 'reconcile', nextAttempt)
1047
+ const failures = await readPhaseFailures(
1048
+ this.deps.store,
1049
+ this.deps.slug,
1050
+ 'reconcile',
1051
+ nextAttempt,
1052
+ )
991
1053
  if (failures.count >= this.maxPhaseAttempts) {
992
1054
  await this.raisePolicyExhausted('reconcile', nextAttempt, failures)
993
1055
  return
@@ -999,7 +1061,7 @@ export class BuildRunner {
999
1061
 
1000
1062
  let baseSha: string
1001
1063
  try {
1002
- baseSha = await this.refreshReconcileBase(events)
1064
+ baseSha = await this.refreshReconcileBase()
1003
1065
  } catch (error) {
1004
1066
  await this.failPhase(
1005
1067
  'reconcile',
@@ -1022,13 +1084,19 @@ export class BuildRunner {
1022
1084
  }
1023
1085
 
1024
1086
  /** A core-phase run: retry guard (D5), started event (§15.3), session. */
1025
- private async runPhase(decision: RunPhaseDecision, events: AbEvent[]): Promise<void> {
1087
+ private async runPhase(decision: RunPhaseDecision): Promise<void> {
1026
1088
  const { store, slug } = this.deps
1027
1089
  const { phase, round } = decision
1028
1090
 
1091
+ const node = (await readBuildFacts(store, slug)).value.state.nodeRestack
1092
+ if (node?.conflict && node.active && phase === 'reconcile') {
1093
+ await this.runNodeConflict(round)
1094
+ return
1095
+ }
1096
+
1029
1097
  // D5 RETRY GUARD first: at the cap, escalate instead of running — a
1030
1098
  // failing phase must never loop forever.
1031
- const failures = this.phaseFailures(events, phase, round)
1099
+ const failures = await readPhaseFailures(this.deps.store, this.deps.slug, phase, round)
1032
1100
  if (failures.count >= this.maxPhaseAttempts) {
1033
1101
  await this.raisePolicyExhausted(phase, round, failures)
1034
1102
  return
@@ -1045,7 +1113,13 @@ export class BuildRunner {
1045
1113
  let reconcileBaseSha: string | undefined
1046
1114
  if (phase === 'reconcile') {
1047
1115
  try {
1048
- reconcileBaseSha = await this.refreshReconcileBase(events)
1116
+ requireRewrite(this.deps.forge)
1117
+ const facts = (await readBuildFacts(store, slug)).value
1118
+ reconcileBaseSha =
1119
+ facts.log.restack.active?.targetBase ??
1120
+ (facts.reconcileTransaction?.attempt === round
1121
+ ? facts.reconcileTransaction.targetBase
1122
+ : await this.refreshReconcileBase())
1049
1123
  } catch (error) {
1050
1124
  await this.failPhase(
1051
1125
  phase,
@@ -1057,7 +1131,65 @@ export class BuildRunner {
1057
1131
  }
1058
1132
  }
1059
1133
 
1060
- await store.append(slug, this.startedWrite(decision, reconcileBaseSha))
1134
+ if (phase === 'reconcile') {
1135
+ const facts = (await readBuildFacts(store, slug)).value
1136
+ const active = facts.log.restack.active
1137
+ if (active !== undefined && facts.reconcileTransaction?.restackId !== active.id) {
1138
+ await store.append(slug, {
1139
+ actor: KERNEL,
1140
+ type: 'reconcile.started',
1141
+ payload: { attempt: round, baseSha: active.targetBase, restackId: active.id },
1142
+ })
1143
+ const {
1144
+ trigger: _trigger,
1145
+ cycle: _cycle,
1146
+ observation: _observation,
1147
+ message: _message,
1148
+ ...transaction
1149
+ } = active
1150
+ await store.append(slug, {
1151
+ actor: KERNEL,
1152
+ type: 'reconcile.prepared',
1153
+ payload: { ...transaction, attempt: round, restackId: active.id },
1154
+ })
1155
+ await store.append(slug, {
1156
+ actor: KERNEL,
1157
+ type: 'reconcile.replayed',
1158
+ payload: { id: active.id, conflicted: true },
1159
+ })
1160
+ }
1161
+ }
1162
+ if (
1163
+ phase !== 'reconcile' ||
1164
+ (await readBuildFacts(store, slug)).value.reconcileTransaction?.attempt !== round
1165
+ )
1166
+ await store.append(slug, this.startedWrite(decision, reconcileBaseSha))
1167
+ if (phase === 'reconcile') {
1168
+ try {
1169
+ const oldBase = await readBuildSelector(store, slug, 'verifyDiffBase')
1170
+ if (oldBase === undefined || reconcileBaseSha === undefined)
1171
+ throw new Error('missing reconcile contribution base')
1172
+ await prepareRestack(
1173
+ { ...this.deps },
1174
+ {
1175
+ attempt: round,
1176
+ restackId: (await readBuildFacts(store, slug)).value.log.restack.active?.id,
1177
+ branch: this.deps.branch,
1178
+ oldBase,
1179
+ targetBase: reconcileBaseSha,
1180
+ id: this.deps.ids('rewrite').replaceAll('_', '-'),
1181
+ },
1182
+ )
1183
+ } catch (error) {
1184
+ await this.failPhase(
1185
+ phase,
1186
+ round,
1187
+ failures.count,
1188
+ `failed to prepare reconcile replay: ${errorMessage(error)}`,
1189
+ )
1190
+ return
1191
+ }
1192
+ }
1061
1193
 
1062
1194
  const spec = PHASE_SPECS[phase]
1063
1195
  await this.executeSession({
@@ -1071,30 +1203,374 @@ export class BuildRunner {
1071
1203
  priorFailures: failures.count,
1072
1204
  isTerminal: (event) => event.type === spec.terminalEvent && roundMatches(event, round),
1073
1205
  })
1206
+ if (phase === 'reconcile') await this.settleLocalReconcile()
1074
1207
  }
1075
1208
 
1076
- /**
1077
- * Resolve the current remote tip of this build's immutable base branch.
1078
- *
1079
- * The fetch target is build-scoped and internal: concurrent worktrees share
1080
- * one Git common directory, so FETCH_HEAD or a shared remote-tracking ref
1081
- * would let another build overwrite the object this attempt resolves. The
1082
- * explicit ref also makes the fetched remote-only commit available locally.
1083
- */
1084
- private async refreshReconcileBase(events: AbEvent[]): Promise<string> {
1085
- const created = events.find((event) => event.type === 'build.created')
1086
- if (created === undefined || created.type !== 'build.created') {
1209
+ private async runNodeConflict(round: number): Promise<void> {
1210
+ const { store, slug } = this.deps
1211
+ const state = (await readBuildFacts(store, slug)).value.state
1212
+ const node = state.nodeRestack!
1213
+ const active = node.active!
1214
+ const conflict = node.conflict!
1215
+ const change = active.changes[conflict.index]!
1216
+ try {
1217
+ for (const sha of [active.expected, active.parent]) {
1218
+ const exists = await this.deps.exec(['git', 'cat-file', '-e', `${sha}^{commit}`], {
1219
+ cwd: this.deps.workspacePath,
1220
+ })
1221
+ if (exists.exitCode !== 0) {
1222
+ const fetched = await this.deps.exec(
1223
+ ['git', 'fetch', '--no-tags', 'origin', `refs/autobuild/archive/${slug}/${sha}`],
1224
+ { cwd: this.deps.workspacePath },
1225
+ )
1226
+ if (fetched.exitCode !== 0) throw new Error(`missing archived node input ${sha}`)
1227
+ }
1228
+ }
1229
+ if (change.build) {
1230
+ for (const kind of ['spec', 'plan', 'implement-notes']) {
1231
+ if (
1232
+ !(await store.getArtifact(slug, `node-source-${active.id}-${conflict.index}-${kind}`))
1233
+ )
1234
+ throw new Error(`missing ${kind} for source build ${change.build}`)
1235
+ }
1236
+ } else {
1237
+ const result = await this.deps.exec(
1238
+ [
1239
+ 'git',
1240
+ 'show',
1241
+ '--format=fuller',
1242
+ ...(change.mainline ? ['-m', '--first-parent'] : []),
1243
+ change.sha,
1244
+ ],
1245
+ {
1246
+ cwd: this.deps.workspacePath,
1247
+ },
1248
+ )
1249
+ if (result.exitCode !== 0) throw new Error(`missing foreign commit ${change.sha}`)
1250
+ await store.putArtifact(slug, {
1251
+ kind: `node-source-${active.id}-${conflict.index}-foreign`,
1252
+ content: result.stdout,
1253
+ })
1254
+ }
1255
+ for (const item of node.items) if (!item.dropped) await restoreReplay(this.deps, item.head)
1256
+ await this.deps.exec(['git', 'cherry-pick', '--abort'], { cwd: this.deps.workspacePath })
1257
+ const reset = await this.deps.exec(['git', 'checkout', '--detach', conflict.base], {
1258
+ cwd: this.deps.workspacePath,
1259
+ })
1260
+ if (reset.exitCode !== 0) throw new Error(reset.stderr)
1261
+ const result = await replayNodeChange(
1262
+ this.deps,
1263
+ { ...active, oldHead: active.expected },
1264
+ conflict.index,
1265
+ conflict.base,
1266
+ )
1267
+ if (result.kind !== 'conflict')
1268
+ throw new Error('reserved conflict no longer reproduces from frozen inputs')
1269
+ } catch (error) {
1270
+ await store.append(slug, {
1271
+ actor: KERNEL,
1272
+ type: 'escalation.raised',
1273
+ payload: {
1274
+ id: this.deps.ids('esc'),
1275
+ phase: 'reconcile',
1276
+ source: 'agent',
1277
+ question: `Cannot prepare node change ${change.sha}: ${errorMessage(error)}`,
1278
+ },
1279
+ })
1280
+ return
1281
+ }
1282
+ await store.append(slug, {
1283
+ actor: KERNEL,
1284
+ type: 'reconcile.started',
1285
+ payload: { attempt: round, baseSha: conflict.base },
1286
+ })
1287
+ const failures = await readPhaseFailures(store, slug, 'reconcile', round)
1288
+ if (failures.count >= this.maxPhaseAttempts) {
1289
+ await this.raisePolicyExhausted('reconcile', round, failures)
1290
+ return
1291
+ }
1292
+ await this.executeSession({
1293
+ phase: 'reconcile',
1294
+ round,
1295
+ role: 'reconcile',
1296
+ skill: PHASE_SPECS.reconcile.skill,
1297
+ abPhase: `reconcile@${round}`,
1298
+ producerPhase: 'reconcile',
1299
+ priorFailures: failures.count,
1300
+ isTerminal: (event) => event.type === 'reconcile.completed',
1301
+ })
1302
+ }
1303
+
1304
+ /** Re-read durable ownership and controls at the actual rewrite boundary. */
1305
+ private async assertAutomaticRewriteOwnership(allowPublication = false) {
1306
+ const { store, slug, instance, clock } = this.deps
1307
+ const record = await store.getBuild(slug)
1308
+ if (record?.lease?.holder !== instance) throw new LeaseHeldError(slug, instance)
1309
+ if (
1310
+ new Date(record.lease.expiresAt).getTime() <= clock().getTime() &&
1311
+ !(await store.claimLease(slug, instance, this.leaseTtlMs))
1312
+ )
1313
+ throw new LeaseHeldError(slug, instance)
1314
+ const facts = (await readBuildFacts(store, slug)).value
1315
+ if (facts.open !== null && facts.open.instance !== instance)
1316
+ throw new LeaseHeldError(slug, instance)
1317
+ if (
1318
+ facts.state.sessions.open.length > 0 ||
1319
+ facts.state.status === 'paused' ||
1320
+ facts.state.status === 'blocked' ||
1321
+ facts.state.status === 'done' ||
1322
+ facts.state.status === 'aborted' ||
1323
+ facts.state.pendingCommands.some(
1324
+ (command) =>
1325
+ (!allowPublication && command.command === 'pause') || command.command === 'abort',
1326
+ ) ||
1327
+ (!allowPublication && facts.publication.pending())
1328
+ )
1329
+ throw new AutomaticRewriteDeferred(
1330
+ 'automatic rewrite deferred until execution, control and publication settlement',
1331
+ )
1332
+ }
1333
+
1334
+ /** A resolver deposits intent while its turn is live. Publish after it ends. */
1335
+ private async settleLocalReconcile() {
1336
+ const { store, slug } = this.deps
1337
+ const facts = (await readBuildFacts(store, slug)).value
1338
+ if (facts.workspace !== null && isRemoteWorkspace(facts.workspace)) return
1339
+ const request = facts.publication.latestUncompletedRequest()
1340
+ if (
1341
+ request?.payload.operation !== 'reconcile' ||
1342
+ request.payload.rewrite === undefined ||
1343
+ facts.publication.requestSettled(request)
1344
+ )
1345
+ return
1346
+ if (
1347
+ facts.state.sessions.open.length > 0 ||
1348
+ facts.state.status === 'paused' ||
1349
+ facts.state.status === 'blocked' ||
1350
+ facts.state.status === 'aborted' ||
1351
+ facts.state.status === 'done' ||
1352
+ facts.state.pendingCommands.some((command) => command.command === 'abort')
1353
+ )
1354
+ return
1355
+ await this.closeProducerSessions()
1356
+ const rewriteId = request.payload.rewrite.id
1357
+ const intent = facts.reconcileHistory.findLast(
1358
+ (e) => e.type === 'reconcile.publish-intended' && e.payload.id === rewriteId,
1359
+ )
1360
+ if (
1361
+ intent?.type !== 'reconcile.publish-intended' ||
1362
+ intent.payload.headSha !== request.payload.sha
1363
+ )
1364
+ throw new Error('local reconcile request does not match durable intent')
1365
+ const publicationDeps = {
1366
+ ...this.deps,
1367
+ beforeRewrite: () => this.assertAutomaticRewriteOwnership(true),
1368
+ }
1369
+ // A replacement workspace may still be checked out at the old branch tip.
1370
+ // Restore the frozen resolved intent before the guarded branch update.
1371
+ await prepareRestack(publicationDeps, {
1372
+ attempt: intent.payload.attempt,
1373
+ branch: intent.payload.branch,
1374
+ oldBase: intent.payload.oldBase,
1375
+ targetBase: intent.payload.targetBase,
1376
+ id: intent.payload.id,
1377
+ restackId: intent.payload.restackId,
1378
+ })
1379
+ const result = await publishRestack(publicationDeps, intent.payload)
1380
+ if (result.kind === 'lease-mismatch') {
1381
+ await store.append(slug, {
1382
+ actor: KERNEL,
1383
+ type: 'reconcile.contended',
1384
+ payload: { id: intent.payload.id, request: request.seq, actual: result.actual },
1385
+ })
1386
+ return
1387
+ }
1388
+ await store.append(slug, {
1389
+ actor: KERNEL,
1390
+ type: 'reconcile.completed',
1391
+ payload: {
1392
+ headSha: request.payload.sha,
1393
+ rewriteId: intent.payload.id,
1394
+ artifact: request.payload.artifact,
1395
+ },
1396
+ })
1397
+ await completeAutomaticReconcile(store, slug)
1398
+ }
1399
+
1400
+ private async restack(decision: Extract<Decision, { kind: 'restack' }>): Promise<void> {
1401
+ const { store, slug } = this.deps
1402
+ let facts = (await readBuildFacts(store, slug)).value
1403
+ if (facts.state.sessions.open.length > 0 || facts.publication.pending())
1404
+ throw new Error('automatic restack deferred until session and publication settlement')
1405
+ await this.closeProducerSessions()
1406
+ const round = facts.state.reconcileAttempts + 1
1407
+ const failures = await readPhaseFailures(store, slug, 'reconcile', round)
1408
+ if (failures.count >= this.maxPhaseAttempts) {
1409
+ await this.raisePolicyExhausted('reconcile', round, failures)
1410
+ return
1411
+ }
1412
+ try {
1413
+ await this.assertAutomaticRewriteOwnership()
1414
+ let transaction = facts.log.restack.active
1415
+ let automatic: Pick<
1416
+ EventPayload<'restack.prepared'>,
1417
+ 'trigger' | 'cycle' | 'observation' | 'message'
1418
+ >
1419
+ let id: string
1420
+ let targetBase: string
1421
+ if (transaction === undefined) {
1422
+ targetBase = await this.refreshReconcileBase()
1423
+ const branch = facts.lastCreated?.payload.baseBranch
1424
+ if (branch === undefined) throw new Error('missing frozen target')
1425
+ if (facts.log.restack.target?.sha !== targetBase) {
1426
+ await store.append(slug, {
1427
+ actor: KERNEL,
1428
+ type: 'target.moved',
1429
+ payload: { branch, sha: targetBase },
1430
+ })
1431
+ facts = (await readBuildFacts(store, slug)).value
1432
+ }
1433
+ const description = await store.getArtifact(slug, 'pr-description')
1434
+ const title =
1435
+ facts.lastCreated?.payload.ticket.title ?? facts.lastCreated?.payload.ticket.id ?? slug
1436
+ const message = withBuildTrailer(
1437
+ description === null ? title : new TextDecoder().decode(description.content),
1438
+ slug,
1439
+ { includesSubject: true },
1440
+ )
1441
+ automatic = {
1442
+ trigger: decision.trigger,
1443
+ cycle: decision.cycle,
1444
+ observation: facts.log.restack.target!.seq,
1445
+ message,
1446
+ }
1447
+ id = this.deps.ids('restack').replaceAll('_', '-')
1448
+ } else {
1449
+ automatic = {
1450
+ trigger: transaction.trigger,
1451
+ cycle: transaction.cycle,
1452
+ observation: transaction.observation,
1453
+ message: transaction.message,
1454
+ }
1455
+ targetBase = transaction.targetBase
1456
+ id = transaction.id
1457
+ }
1458
+ const oldBase = await readBuildSelector(store, slug, 'verifyDiffBase')
1459
+ if (oldBase === undefined) throw new Error('missing contribution base')
1460
+ // A resolver already published one canonical change on this exact base.
1461
+ // Reuse it only while no later finalize publication has extended it.
1462
+ const canonical = facts.reconcileTransaction
1463
+ const completed = facts.log.lastReconcileCompleted
1464
+ if (
1465
+ transaction === undefined &&
1466
+ canonical !== undefined &&
1467
+ completed?.completedSeq === decision.cycle &&
1468
+ (facts.log.restack.postStepAt ?? 0) <= completed.completedSeq &&
1469
+ canonical.targetBase === targetBase
1470
+ ) {
1471
+ const { attempt: _attempt, restackId: _restackId, ...replay } = canonical
1472
+ const headSha = await readBuildSelector(store, slug, 'publishedBranchHead')
1473
+ if (headSha === undefined) throw new Error('missing canonical reconcile head')
1474
+ await store.append(slug, {
1475
+ actor: KERNEL,
1476
+ type: 'restack.completed',
1477
+ payload: { ...replay, ...automatic, headSha },
1478
+ })
1479
+ return
1480
+ }
1481
+ await this.assertAutomaticRewriteOwnership()
1482
+ const deps = {
1483
+ ...this.deps,
1484
+ automatic,
1485
+ beforeRewrite: () => this.assertAutomaticRewriteOwnership(),
1486
+ }
1487
+ const prepared = await prepareRestack(deps, {
1488
+ attempt: 1,
1489
+ branch: this.deps.branch,
1490
+ oldBase,
1491
+ targetBase,
1492
+ id,
1493
+ })
1494
+ facts = (await readBuildFacts(store, slug)).value
1495
+ transaction = facts.log.restack.active
1496
+ if (transaction === undefined) throw new Error('missing prepared automatic restack')
1497
+ if (facts.log.restack.replay?.conflicted) return
1498
+ const result = await this.deps.exec(['git', 'rev-parse', 'HEAD'], {
1499
+ cwd: this.deps.workspacePath,
1500
+ })
1501
+ if (result.exitCode !== 0) throw new Error(result.stderr)
1502
+ const headSha = result.stdout.trim()
1503
+ if (facts.log.restack.intent !== undefined && facts.log.restack.intent.headSha !== headSha)
1504
+ throw new Error('recovered automatic replay differs from its frozen publication intent')
1505
+ await retainReplay(deps, headSha, transaction.targetBase)
1506
+ const intent = { ...transaction, headSha }
1507
+ if (facts.log.restack.intent === undefined)
1508
+ await store.append(slug, {
1509
+ actor: KERNEL,
1510
+ type: 'restack.publish-intended',
1511
+ payload: intent,
1512
+ })
1513
+ if (facts.workspace !== null && isRemoteWorkspace(facts.workspace)) {
1514
+ await store.append(slug, {
1515
+ actor: KERNEL,
1516
+ type: 'publication.requested',
1517
+ payload: {
1518
+ operation: 'restack',
1519
+ branch: transaction.branch,
1520
+ sha: headSha,
1521
+ rewrite: intent,
1522
+ },
1523
+ })
1524
+ return
1525
+ }
1526
+ const published = await publishRestack(deps, {
1527
+ ...prepared,
1528
+ headSha,
1529
+ conflicted: false,
1530
+ artifact: { kind: 'restack', rev: 0 },
1531
+ })
1532
+ if (published.kind === 'lease-mismatch') {
1533
+ await store.append(slug, {
1534
+ actor: KERNEL,
1535
+ type: 'restack.contended',
1536
+ payload: {
1537
+ id: transaction.id,
1538
+ request: facts.restackHistory.at(-1)!.seq,
1539
+ actual: published.actual,
1540
+ },
1541
+ })
1542
+ throw new Error(
1543
+ `automatic restack publication contended at ${published.actual ?? '(deleted)'}`,
1544
+ )
1545
+ }
1546
+ await store.append(slug, { actor: KERNEL, type: 'restack.completed', payload: intent })
1547
+ } catch (error) {
1548
+ if (error instanceof LeaseHeldError) throw error
1549
+ if (error instanceof AutomaticRewriteDeferred) return
1550
+ await this.failPhase(
1551
+ 'reconcile',
1552
+ round,
1553
+ failures.count,
1554
+ `automatic restack failed: ${errorMessage(error)}`,
1555
+ )
1556
+ }
1557
+ }
1558
+
1559
+ /** Snapshot the frozen target in a build-private ref without tracking-ref updates. */
1560
+ private async refreshReconcileBase(): Promise<string> {
1561
+ const baseBranch = await readBuildSelector(this.deps.store, this.deps.slug, 'baseBranch')
1562
+ if (baseBranch === undefined) {
1087
1563
  throw new Error(
1088
1564
  'this build has no build.created event — cannot resolve its frozen baseBranch (§15.3)',
1089
1565
  )
1090
1566
  }
1091
1567
 
1092
- const sourceRef = `refs/heads/${created.payload.baseBranch}`
1568
+ const sourceRef = `refs/heads/${baseBranch}`
1093
1569
  const targetRef = `refs/autobuild/reconcile/${this.deps.slug}/base`
1094
1570
  if (this.deps.forge.snapshotBase !== undefined) {
1095
1571
  const sha = await this.deps.forge.snapshotBase({
1096
1572
  workspacePath: this.deps.workspacePath,
1097
- base: created.payload.baseBranch,
1573
+ base: baseBranch,
1098
1574
  destinationRef: targetRef,
1099
1575
  })
1100
1576
  if (!GIT_OBJECT_ID.test(sha)) {
@@ -1110,6 +1586,7 @@ export class BuildRunner {
1110
1586
  'fetch',
1111
1587
  '--no-tags',
1112
1588
  '--no-write-fetch-head',
1589
+ '--refmap=',
1113
1590
  'origin',
1114
1591
  `+${sourceRef}:${targetRef}`,
1115
1592
  ]
@@ -1138,9 +1615,17 @@ export class BuildRunner {
1138
1615
  * a canonical kernel-authored skip and launches no command or session.
1139
1616
  * Inclusion delegates to the existing verifier path unchanged.
1140
1617
  */
1141
- private async evaluateVerify(decision: EvaluateVerifyDecision, events: AbEvent[]): Promise<void> {
1618
+ private async evaluateVerify(decision: EvaluateVerifyDecision): Promise<void> {
1142
1619
  const { exec, workspacePath } = this.deps
1143
- const baseSha = selectVerifyDiffBase(events)
1620
+ const state = (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
1621
+ const baseSha =
1622
+ state.kind === 'node'
1623
+ ? state.integration?.cycle?.parent
1624
+ : await readBuildSelector(this.deps.store, this.deps.slug, 'verifyDiffBase')
1625
+ if (baseSha === undefined)
1626
+ throw new Error(
1627
+ 'conditional verify requires a workspace.provisioned base SHA, but this build has none',
1628
+ )
1144
1629
  const args = ['git', 'diff', '--no-renames', '--name-only', '-z', baseSha, 'HEAD', '--']
1145
1630
  const result = await exec(args, { cwd: workspacePath })
1146
1631
  if (result.exitCode !== 0) {
@@ -1154,7 +1639,7 @@ export class BuildRunner {
1154
1639
  { kind: 'paths', step: decision.step, paths: decision.paths },
1155
1640
  changedPaths,
1156
1641
  )
1157
- if (!applicability.applies) {
1642
+ if (applicability.applies === false) {
1158
1643
  await this.skipVerify({
1159
1644
  kind: 'skip-verify',
1160
1645
  step: decision.step,
@@ -1167,18 +1652,38 @@ export class BuildRunner {
1167
1652
  if (decision.action.kind === 'run-check') {
1168
1653
  await this.runCheck(decision.action)
1169
1654
  } else {
1170
- await this.runAgentVerify(decision.action, events)
1655
+ await this.runAgentVerify(decision.action)
1171
1656
  }
1172
1657
  }
1173
1658
 
1174
1659
  /** Shared writer for every deterministic exclusion mechanism. A skip is a
1175
1660
  * queryable two-fact phase occurrence and launches no command or session. */
1661
+ private async verifyEvidence() {
1662
+ const facts = (await readBuildFacts(this.deps.store, this.deps.slug)).value
1663
+ if (facts.state.kind === 'node') {
1664
+ const cycle = facts.state.integration?.cycle
1665
+ if (!cycle) throw new Error('missing prepared integration verification')
1666
+ const head = await this.deps.exec(['git', 'rev-parse', 'HEAD'], {
1667
+ cwd: this.deps.workspacePath,
1668
+ })
1669
+ if (head.exitCode !== 0 || head.stdout.trim() !== cycle.head)
1670
+ throw new Error('integration checkout differs from prepared head')
1671
+ return { baseSha: cycle.parent, headSha: cycle.head, restackId: cycle.id }
1672
+ }
1673
+ const cycle = Math.max(facts.log.code.latestApproveSeq, facts.log.lastReconcileCompletedSeq)
1674
+ const gate = facts.log.restack.gates[String(cycle)]
1675
+ if (gate !== undefined)
1676
+ return { baseSha: gate.targetBase, headSha: gate.headSha, restackId: gate.id }
1677
+ return {}
1678
+ }
1679
+
1176
1680
  private async skipVerify(decision: SkipVerifyDecision): Promise<void> {
1177
1681
  const { store, slug } = this.deps
1682
+ const evidence = await this.verifyEvidence()
1178
1683
  await store.append(slug, {
1179
1684
  actor: KERNEL,
1180
1685
  type: 'verify.started',
1181
- payload: { step: decision.step, attempt: decision.attempt },
1686
+ payload: { ...evidence, step: decision.step, attempt: decision.attempt },
1182
1687
  } satisfies EventWrite<'verify.started'>)
1183
1688
  await store.append(slug, {
1184
1689
  actor: KERNEL,
@@ -1186,6 +1691,7 @@ export class BuildRunner {
1186
1691
  payload: {
1187
1692
  step: decision.step,
1188
1693
  attempt: decision.attempt,
1694
+ ...evidence,
1189
1695
  outcome: 'skipped',
1190
1696
  reason: decision.reason,
1191
1697
  ...(decision.skipCause !== undefined ? { skipCause: decision.skipCause } : {}),
@@ -1198,10 +1704,11 @@ export class BuildRunner {
1198
1704
  private async runCheck(decision: RunCheckDecision): Promise<void> {
1199
1705
  const { store, slug, exec, workspacePath } = this.deps
1200
1706
  const { step, command, attempt } = decision
1707
+ const evidence = await this.verifyEvidence()
1201
1708
  await store.append(slug, {
1202
1709
  actor: KERNEL,
1203
1710
  type: 'verify.started',
1204
- payload: { step, attempt },
1711
+ payload: { ...evidence, step, attempt },
1205
1712
  } satisfies EventWrite<'verify.started'>)
1206
1713
 
1207
1714
  const result = await exec(['sh', '-c', command], { cwd: workspacePath })
@@ -1209,7 +1716,7 @@ export class BuildRunner {
1209
1716
  await store.append(slug, {
1210
1717
  actor: KERNEL,
1211
1718
  type: 'verify.completed',
1212
- payload: { step, attempt, outcome: 'pass' },
1719
+ payload: { ...evidence, step, attempt, outcome: 'pass' },
1213
1720
  } satisfies EventWrite<'verify.completed'>)
1214
1721
  return
1215
1722
  }
@@ -1236,6 +1743,7 @@ export class BuildRunner {
1236
1743
  payload: {
1237
1744
  step,
1238
1745
  attempt,
1746
+ ...evidence,
1239
1747
  outcome: 'fail',
1240
1748
  report: { kind: meta.kind, rev: meta.revision },
1241
1749
  },
@@ -1245,14 +1753,15 @@ export class BuildRunner {
1245
1753
  }
1246
1754
 
1247
1755
  /** Agent-verify step (§5): a session with a pass/fail/skip verdict. */
1248
- private async runAgentVerify(decision: RunAgentVerifyDecision, events: AbEvent[]): Promise<void> {
1756
+ private async runAgentVerify(decision: RunAgentVerifyDecision): Promise<void> {
1249
1757
  const { store, slug } = this.deps
1250
1758
  const { step, skill, attempt, feedback } = decision
1759
+ const evidence = await this.verifyEvidence()
1251
1760
  const phase = verifyPhase(step)
1252
1761
 
1253
1762
  // D5 guard, extended to agent-verify (see module doc): keyed by
1254
1763
  // verify:<step> with the verify attempt as the round.
1255
- const failures = this.phaseFailures(events, phase, attempt)
1764
+ const failures = await readPhaseFailures(this.deps.store, this.deps.slug, phase, attempt)
1256
1765
  if (failures.count >= this.maxPhaseAttempts) {
1257
1766
  await this.raisePolicyExhausted(phase, attempt, failures)
1258
1767
  return
@@ -1265,7 +1774,7 @@ export class BuildRunner {
1265
1774
  await store.append(slug, {
1266
1775
  actor: KERNEL,
1267
1776
  type: 'verify.started',
1268
- payload: { step, attempt, ...(feedback !== undefined ? { feedback } : {}) },
1777
+ payload: { ...evidence, step, attempt, ...(feedback !== undefined ? { feedback } : {}) },
1269
1778
  } satisfies EventWrite<'verify.started'>)
1270
1779
 
1271
1780
  await this.executeSession({
@@ -1292,10 +1801,7 @@ export class BuildRunner {
1292
1801
  * Step, Git, and Forge failures become the ordinary failed outcome plus an
1293
1802
  * observation and never route a green build backward.
1294
1803
  */
1295
- private async runFinalizeStep(
1296
- decision: RunFinalizeStepDecision,
1297
- events: AbEvent[],
1298
- ): Promise<void> {
1804
+ private async runFinalizeStep(decision: RunFinalizeStepDecision): Promise<void> {
1299
1805
  const { step, action } = decision
1300
1806
  await this.deps.store.append(this.deps.slug, {
1301
1807
  actor: KERNEL,
@@ -1308,7 +1814,12 @@ export class BuildRunner {
1308
1814
 
1309
1815
  try {
1310
1816
  await this.requireFinalizeWorktreeClean('before the post-step starts')
1311
- durableHead = selectPublishedBranchHead(events)
1817
+ durableHead = await readBuildSelector(this.deps.store, this.deps.slug, 'publishedBranchHead')
1818
+ if (durableHead === undefined)
1819
+ throw new Error(
1820
+ 'finalize publication requires a prior implement.completed, reconcile.completed, ' +
1821
+ 'or successful finalize publication head, but this build has none',
1822
+ )
1312
1823
  } catch (error) {
1313
1824
  failureNote = `finalize publication preflight failed: ${errorMessage(error)}`
1314
1825
  }
@@ -1338,9 +1849,8 @@ export class BuildRunner {
1338
1849
  head,
1339
1850
  )
1340
1851
  if (scratchPaths.length > 0) throw phaseScratchRejection(scratchPaths)
1341
- const remote = events.some(
1342
- (event) => event.type === 'workspace.provisioned' && isRemoteWorkspace(event.payload),
1343
- )
1852
+ const remote = (await readBuildFacts(this.deps.store, this.deps.slug)).value
1853
+ .remoteWorkspace
1344
1854
  if (remote) {
1345
1855
  await this.deps.store.append(this.deps.slug, {
1346
1856
  actor,
@@ -1354,6 +1864,7 @@ export class BuildRunner {
1354
1864
  })
1355
1865
  return
1356
1866
  }
1867
+ await suspendNativeLanding(this.deps, `finalize-step:${step}`)
1357
1868
  await this.deps.forge.pushBranch(this.deps.workspacePath, this.deps.branch)
1358
1869
  pushedHead = head
1359
1870
  }
@@ -2642,18 +3153,6 @@ export class BuildRunner {
2642
3153
  * an applicable answer count again, so a still-failing phase re-escalates on
2643
3154
  * new evidence instead of deadlocking before its recovery session starts.
2644
3155
  */
2645
- private phaseFailures(
2646
- events: AbEvent[],
2647
- phase: Phase,
2648
- round: number,
2649
- ): {
2650
- count: number
2651
- lastError?: string
2652
- lastWillRetry?: boolean
2653
- lastProviderAttempts?: readonly ProviderAttempt[]
2654
- } {
2655
- return phaseFailuresReducer(phase, round).reduce(events)
2656
- }
2657
3156
 
2658
3157
  private async failPhase(
2659
3158
  phase: Phase,