@defrex/autobuild 0.14.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 (172) hide show
  1. package/README.md +4 -2
  2. package/SPEC.md +654 -98
  3. package/docs/architecture.md +226 -5
  4. package/docs/assets/headline-wide.png +0 -0
  5. package/docs/configuration.md +112 -12
  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 +49 -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 +176 -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 -109
  33. package/packages/core/src/cli/dispatch.ts +250 -136
  34. package/packages/core/src/cli/dispatcher-liveness.ts +15 -2
  35. package/packages/core/src/cli/help.ts +49 -32
  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/ports/forge/contract.ts +91 -3
  107. package/packages/core/src/ports/forge/fake.ts +142 -4
  108. package/packages/core/src/ports/forge/git-rewrite.ts +232 -0
  109. package/packages/core/src/ports/forge/github-readiness.ts +421 -0
  110. package/packages/core/src/ports/forge/github.ts +631 -35
  111. package/packages/core/src/ports/forge/local-git.ts +119 -5
  112. package/packages/core/src/ports/forge/readiness.ts +99 -0
  113. package/packages/core/src/ports/tickets/contract.ts +41 -0
  114. package/packages/core/src/ports/tickets/create.ts +8 -1
  115. package/packages/core/src/ports/tickets/fake.ts +32 -1
  116. package/packages/core/src/ports/tickets/file-codec.ts +7 -0
  117. package/packages/core/src/ports/tickets/file.ts +18 -1
  118. package/packages/core/src/ports/tickets/hosted-index.ts +2 -0
  119. package/packages/core/src/ports/tickets/linear.ts +124 -4
  120. package/packages/core/src/ports/tickets/migration.ts +25 -1
  121. package/packages/core/src/ports/tickets/operations.ts +7 -2
  122. package/packages/core/src/ports/tickets/remote-protocol.ts +19 -0
  123. package/packages/core/src/ports/tickets/remote.ts +10 -1
  124. package/packages/core/src/ports/tickets/revision.ts +3 -1
  125. package/packages/core/src/ports/tickets/tree.ts +148 -0
  126. package/packages/core/src/ports/tickets/update.ts +15 -2
  127. package/packages/core/src/ports/types.ts +135 -5
  128. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  129. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -1
  130. package/packages/core/src/ports/workspace/vercel-sandbox.ts +60 -3
  131. package/packages/core/src/processes/build-runner.ts +530 -23
  132. package/packages/core/src/processes/dispatcher-selectors.ts +15 -9
  133. package/packages/core/src/processes/dispatcher.ts +2145 -203
  134. package/packages/core/src/processes/execution-no-progress.ts +46 -1
  135. package/packages/core/src/processes/publication-state.ts +30 -5
  136. package/packages/core/src/processes/repo-view.ts +21 -2
  137. package/packages/core/src/store/build-scope.ts +18 -0
  138. package/packages/core/src/store/contract.ts +658 -0
  139. package/packages/core/src/store/digest.ts +52 -4
  140. package/packages/core/src/store/local/schema.ts +25 -13
  141. package/packages/core/src/store/local/store.ts +117 -1
  142. package/packages/core/src/store/memory.ts +62 -1
  143. package/packages/core/src/store/phase-session.ts +17 -0
  144. package/packages/core/src/store/reduced-reads.ts +2 -1
  145. package/packages/core/src/store/reducer-value-shapes.json +10707 -6440
  146. package/packages/core/src/store/remote/client.ts +44 -0
  147. package/packages/core/src/store/remote/compatibility.ts +19 -9
  148. package/packages/core/src/store/remote/protocol.ts +11 -0
  149. package/packages/core/src/store/repo-state-events.ts +2 -0
  150. package/packages/core/src/store/session-handle.ts +15 -0
  151. package/packages/core/src/store/subscribe.ts +1 -1
  152. package/packages/core/src/store/types.ts +32 -4
  153. package/packages/core/src/testing/index.ts +2 -0
  154. package/packages/core/src/testing/reduced-read-budget.ts +48 -8
  155. package/packages/core/src/testing/refresh-scheduler.ts +32 -0
  156. package/skills/guide/SKILL.md +110 -61
  157. package/skills/guide/references/integration-tree.md +117 -0
  158. package/skills/guide/references/landing-policy.md +150 -0
  159. package/skills/guide/references/migration-1.0.md +68 -0
  160. package/skills/guide/references/operator-api.md +12 -5
  161. package/skills/guide/references/plugin-authoring.md +34 -0
  162. package/skills/guide/references/remote-store-protocol.md +30 -7
  163. package/skills/guide/references/remote-ticket-protocol.md +26 -5
  164. package/skills/guide/references/restacking.md +79 -0
  165. package/skills/guide/references/setup.md +49 -6
  166. package/skills/guide/references/ticket-dependencies.md +69 -0
  167. package/skills/guide/references/ticket-migration.md +8 -0
  168. package/skills/operate/SKILL.md +55 -5
  169. package/skills/reconcile/SKILL.md +55 -48
  170. package/skills/spec/SKILL.md +67 -1
  171. package/skills/tickets/SKILL.md +55 -2
  172. package/templates/autobuild.toml +3 -0
@@ -1,3 +1,17 @@
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'
1
15
  import { readBuildFacts, readBuildSelector, readPhaseFailures } from '../store/reduced-reads'
2
16
  import { delegateCredential } from '../store/remote/credentials'
3
17
  import { refreshSummaryBoundary } from '../cli/pr-summary-publication'
@@ -94,6 +108,8 @@ export { publicationPending } from './publication-state'
94
108
 
95
109
  // ── Seams ────────────────────────────────────────────────────────────────────
96
110
 
111
+ class AutomaticRewriteDeferred extends Error {}
112
+
97
113
  /** Another sandbox owns the build (§7.4): its lease is live, so this runner
98
114
  * must not execute. The dispatcher retries once the lease expires. */
99
115
  export class LeaseHeldError extends Error {
@@ -434,7 +450,7 @@ export const setupStreakReducer = defineReducer<
434
450
  finish: (acc) => acc.failures.filter((seq) => seq > acc.boundary).length,
435
451
  })
436
452
 
437
- export const PUBLISHED_BRANCH_HEAD_REDUCER_VERSION = 1
453
+ export const PUBLISHED_BRANCH_HEAD_REDUCER_VERSION = 4
438
454
 
439
455
  /** Latest event-checkpointed branch head that kernel plumbing published;
440
456
  * undefined while the build has none. */
@@ -449,8 +465,15 @@ export const publishedBranchHeadReducer = defineReducer<
449
465
  for (const event of events) {
450
466
  if (event.type === 'implement.completed') {
451
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)
452
475
  } else if (event.type === 'reconcile.completed') {
453
- acc.head = event.payload.mergeCommit
476
+ acc.head = reconcileHead(event.payload)
454
477
  } else if (
455
478
  event.type === 'finalize.step-completed' &&
456
479
  event.payload.ok &&
@@ -475,7 +498,7 @@ export function selectPublishedBranchHead(events: readonly AbEvent[]): string {
475
498
  return head
476
499
  }
477
500
 
478
- export const VERIFY_DIFF_BASE_REDUCER_VERSION = 1
501
+ export const VERIFY_DIFF_BASE_REDUCER_VERSION = 2
479
502
 
480
503
  /**
481
504
  * The durable tree against which a conditional verifier evaluates the
@@ -495,6 +518,8 @@ export const verifyDiffBaseReducer = defineReducer<
495
518
  for (const event of events) {
496
519
  if (event.type === 'workspace.provisioned') {
497
520
  if (acc.provisioned === undefined) acc.provisioned = event.payload.base.sha
521
+ } else if (event.type === 'restack.completed') {
522
+ acc.promoted = event.payload.targetBase
498
523
  } else if (event.type === 'reconcile.started') {
499
524
  acc.pendingReconcileBase = event.payload.baseSha
500
525
  } else if (event.type === 'reconcile.completed') {
@@ -700,6 +725,13 @@ export class BuildRunner {
700
725
  * setup succeeds; that fact then proves recovery and clears the projection.
701
726
  */
702
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')
703
735
  const config = await this.captureConfig()
704
736
  const { store, slug, instance } = this.deps
705
737
  const claimed = await store.claimLease(slug, instance, this.leaseTtlMs)
@@ -716,6 +748,16 @@ export class BuildRunner {
716
748
  }
717
749
 
718
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
+ }
719
761
  const currentFailure = state.setupFailure
720
762
  const openSetupEscalation = state.openEscalations.some(
721
763
  (escalation) => escalation.phase === 'setup' && escalation.source === 'policy',
@@ -815,9 +857,14 @@ export class BuildRunner {
815
857
  async step(): Promise<Decision> {
816
858
  const config = await this.captureConfig()
817
859
  const { store, slug } = this.deps
860
+ await this.settleLocalReconcile()
861
+ await completeAutomaticReconcile(store, slug)
818
862
  const facts = (await readBuildFacts(store, slug)).value
819
863
  const decision = decideNextFromFacts(facts.state, facts.log, config)
820
864
  switch (decision.kind) {
865
+ case 'restack':
866
+ await this.restack(decision)
867
+ return decision
821
868
  case 'capture-reconcile-policy':
822
869
  await store.append(slug, {
823
870
  actor: KERNEL,
@@ -878,6 +925,9 @@ export class BuildRunner {
878
925
  * already deposited — see module doc).
879
926
  */
880
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
881
931
  if (!this.attached) {
882
932
  const attachment = await this.attach()
883
933
  if (attachment.kind === 'control-acknowledged') {
@@ -885,18 +935,31 @@ export class BuildRunner {
885
935
  }
886
936
  }
887
937
  try {
938
+ await this.settleLocalReconcile()
888
939
  if (await this.refreshSummary())
889
940
  return (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
890
- if ((await readBuildFacts(this.deps.store, this.deps.slug)).value.publication.pending()) {
891
- return (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
892
- }
893
941
  for (;;) {
894
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
+ }
895
960
  const decision = await this.step()
896
961
  if (await this.refreshSummary()) break
897
962
  if (decision.kind === 'wait') break
898
- if ((await readBuildFacts(this.deps.store, this.deps.slug)).value.publication.pending())
899
- break
900
963
  }
901
964
  return (await readBuildFacts(this.deps.store, this.deps.slug)).value.state
902
965
  } finally {
@@ -1025,6 +1088,12 @@ export class BuildRunner {
1025
1088
  const { store, slug } = this.deps
1026
1089
  const { phase, round } = decision
1027
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
+
1028
1097
  // D5 RETRY GUARD first: at the cap, escalate instead of running — a
1029
1098
  // failing phase must never loop forever.
1030
1099
  const failures = await readPhaseFailures(this.deps.store, this.deps.slug, phase, round)
@@ -1044,7 +1113,13 @@ export class BuildRunner {
1044
1113
  let reconcileBaseSha: string | undefined
1045
1114
  if (phase === 'reconcile') {
1046
1115
  try {
1047
- reconcileBaseSha = await this.refreshReconcileBase()
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())
1048
1123
  } catch (error) {
1049
1124
  await this.failPhase(
1050
1125
  phase,
@@ -1056,7 +1131,65 @@ export class BuildRunner {
1056
1131
  }
1057
1132
  }
1058
1133
 
1059
- 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
+ }
1060
1193
 
1061
1194
  const spec = PHASE_SPECS[phase]
1062
1195
  await this.executeSession({
@@ -1070,16 +1203,360 @@ export class BuildRunner {
1070
1203
  priorFailures: failures.count,
1071
1204
  isTerminal: (event) => event.type === spec.terminalEvent && roundMatches(event, round),
1072
1205
  })
1206
+ if (phase === 'reconcile') await this.settleLocalReconcile()
1073
1207
  }
1074
1208
 
1075
- /**
1076
- * Resolve the current remote tip of this build's immutable base branch.
1077
- *
1078
- * The fetch target is build-scoped and internal: concurrent worktrees share
1079
- * one Git common directory, so FETCH_HEAD or a shared remote-tracking ref
1080
- * would let another build overwrite the object this attempt resolves. The
1081
- * explicit ref also makes the fetched remote-only commit available locally.
1082
- */
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. */
1083
1560
  private async refreshReconcileBase(): Promise<string> {
1084
1561
  const baseBranch = await readBuildSelector(this.deps.store, this.deps.slug, 'baseBranch')
1085
1562
  if (baseBranch === undefined) {
@@ -1109,6 +1586,7 @@ export class BuildRunner {
1109
1586
  'fetch',
1110
1587
  '--no-tags',
1111
1588
  '--no-write-fetch-head',
1589
+ '--refmap=',
1112
1590
  'origin',
1113
1591
  `+${sourceRef}:${targetRef}`,
1114
1592
  ]
@@ -1139,7 +1617,11 @@ export class BuildRunner {
1139
1617
  */
1140
1618
  private async evaluateVerify(decision: EvaluateVerifyDecision): Promise<void> {
1141
1619
  const { exec, workspacePath } = this.deps
1142
- const baseSha = await readBuildSelector(this.deps.store, this.deps.slug, 'verifyDiffBase')
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')
1143
1625
  if (baseSha === undefined)
1144
1626
  throw new Error(
1145
1627
  'conditional verify requires a workspace.provisioned base SHA, but this build has none',
@@ -1176,12 +1658,32 @@ export class BuildRunner {
1176
1658
 
1177
1659
  /** Shared writer for every deterministic exclusion mechanism. A skip is a
1178
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
+
1179
1680
  private async skipVerify(decision: SkipVerifyDecision): Promise<void> {
1180
1681
  const { store, slug } = this.deps
1682
+ const evidence = await this.verifyEvidence()
1181
1683
  await store.append(slug, {
1182
1684
  actor: KERNEL,
1183
1685
  type: 'verify.started',
1184
- payload: { step: decision.step, attempt: decision.attempt },
1686
+ payload: { ...evidence, step: decision.step, attempt: decision.attempt },
1185
1687
  } satisfies EventWrite<'verify.started'>)
1186
1688
  await store.append(slug, {
1187
1689
  actor: KERNEL,
@@ -1189,6 +1691,7 @@ export class BuildRunner {
1189
1691
  payload: {
1190
1692
  step: decision.step,
1191
1693
  attempt: decision.attempt,
1694
+ ...evidence,
1192
1695
  outcome: 'skipped',
1193
1696
  reason: decision.reason,
1194
1697
  ...(decision.skipCause !== undefined ? { skipCause: decision.skipCause } : {}),
@@ -1201,10 +1704,11 @@ export class BuildRunner {
1201
1704
  private async runCheck(decision: RunCheckDecision): Promise<void> {
1202
1705
  const { store, slug, exec, workspacePath } = this.deps
1203
1706
  const { step, command, attempt } = decision
1707
+ const evidence = await this.verifyEvidence()
1204
1708
  await store.append(slug, {
1205
1709
  actor: KERNEL,
1206
1710
  type: 'verify.started',
1207
- payload: { step, attempt },
1711
+ payload: { ...evidence, step, attempt },
1208
1712
  } satisfies EventWrite<'verify.started'>)
1209
1713
 
1210
1714
  const result = await exec(['sh', '-c', command], { cwd: workspacePath })
@@ -1212,7 +1716,7 @@ export class BuildRunner {
1212
1716
  await store.append(slug, {
1213
1717
  actor: KERNEL,
1214
1718
  type: 'verify.completed',
1215
- payload: { step, attempt, outcome: 'pass' },
1719
+ payload: { ...evidence, step, attempt, outcome: 'pass' },
1216
1720
  } satisfies EventWrite<'verify.completed'>)
1217
1721
  return
1218
1722
  }
@@ -1239,6 +1743,7 @@ export class BuildRunner {
1239
1743
  payload: {
1240
1744
  step,
1241
1745
  attempt,
1746
+ ...evidence,
1242
1747
  outcome: 'fail',
1243
1748
  report: { kind: meta.kind, rev: meta.revision },
1244
1749
  },
@@ -1251,6 +1756,7 @@ export class BuildRunner {
1251
1756
  private async runAgentVerify(decision: RunAgentVerifyDecision): Promise<void> {
1252
1757
  const { store, slug } = this.deps
1253
1758
  const { step, skill, attempt, feedback } = decision
1759
+ const evidence = await this.verifyEvidence()
1254
1760
  const phase = verifyPhase(step)
1255
1761
 
1256
1762
  // D5 guard, extended to agent-verify (see module doc): keyed by
@@ -1268,7 +1774,7 @@ export class BuildRunner {
1268
1774
  await store.append(slug, {
1269
1775
  actor: KERNEL,
1270
1776
  type: 'verify.started',
1271
- payload: { step, attempt, ...(feedback !== undefined ? { feedback } : {}) },
1777
+ payload: { ...evidence, step, attempt, ...(feedback !== undefined ? { feedback } : {}) },
1272
1778
  } satisfies EventWrite<'verify.started'>)
1273
1779
 
1274
1780
  await this.executeSession({
@@ -1358,6 +1864,7 @@ export class BuildRunner {
1358
1864
  })
1359
1865
  return
1360
1866
  }
1867
+ await suspendNativeLanding(this.deps, `finalize-step:${step}`)
1361
1868
  await this.deps.forge.pushBranch(this.deps.workspacePath, this.deps.branch)
1362
1869
  pushedHead = head
1363
1870
  }