@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,6 @@
1
+ import { readinessChecks, type ForgeReadinessCheck } from './readiness'
2
+ import { hasBuildTrailer, withBuildTrailer } from '../../kernel/build-identity'
3
+ import type { BuildLandingOptions } from '../types'
1
4
  import { findSummaryMarker } from './summary-marker'
2
5
  /**
3
6
  * FakeForge (SPEC §3.2): in-memory Forge for seam tests. Gate existence and
@@ -56,6 +59,7 @@ export interface AutoMergeRecord {
56
59
  }
57
60
 
58
61
  export interface SquashMergeRecord {
62
+ buildSlug?: string
59
63
  workspacePath: string
60
64
  number: number
61
65
  expectedHeadSha: string
@@ -81,7 +85,80 @@ export type MergeSha = string | ((number: number) => string)
81
85
  type FakeGateState = MergeGatePresence | AutoMergeDeferralReason
82
86
 
83
87
  export class FakeForge implements Forge {
88
+ readiness: ForgeReadinessCheck[] = readinessChecks(
89
+ 'pass',
90
+ 'Fake forge permits repository operations.',
91
+ )
92
+ async inspectReadiness() {
93
+ return this.readiness
94
+ }
95
+ readonly linearStackMerges: { number: number; head: string }[] = []
96
+ async inspectMergeFreshness(_branch: string) {
97
+ return { fenced: false, evidence: ['Fake freshness enforcement is not configured'] }
98
+ }
99
+ async mergeLinearStack(_workspacePath: string, number: number, head: string): Promise<string> {
100
+ this.assertPr(number)
101
+ const pr = this.prs.get(number)!
102
+ if (pr.state !== 'open' || pr.mergeable !== true || this.headShas.get(number) !== head)
103
+ throw new Error('Fake stack merge requires an open mergeable exact head')
104
+ const gate = this.gates.get(number) ?? this.defaultGatePresence
105
+ if (gate !== 'absent') throw new Error('Fake stack merge is gated')
106
+ const sha = this.resolveMergeSha(number)
107
+ this.linearStackMerges.push({ number, head })
108
+ this.prs.set(number, { state: 'merged', sha, headSha: head })
109
+ return sha
110
+ }
111
+ readonly retargeted: { number: number; base: string }[] = []
112
+ async retargetPr(workspacePath: string, number: number, base: string): Promise<void> {
113
+ const pr = await this.inspectLandingPr(workspacePath, number)
114
+ if (!pr.open) throw new Error(`PR #${number} is no longer open`)
115
+ this.opened[number - 1]!.base = base
116
+ this.retargeted.push({ number, base })
117
+ }
118
+ async inspectLandingPr(_workspacePath: string, number: number) {
119
+ const pr = this.opened[number - 1]
120
+ if (!pr) throw new Error(`FakeForge: missing PR refs #${number}`)
121
+ return {
122
+ base: pr.base,
123
+ head: pr.head,
124
+ headSha: this.headShas.get(number) ?? this.resolveHeadSha(number),
125
+ open: this.prs.get(number)?.state === 'open',
126
+ }
127
+ }
128
+ async inspectLandingGate(branch: string): Promise<import('../types').LandingGateInspection> {
129
+ const index = this.opened.findIndex((pr) => pr.base === branch)
130
+ const gate =
131
+ index === -1
132
+ ? this.defaultGatePresence
133
+ : (this.gates.get(index + 1) ?? this.defaultGatePresence)
134
+ if (typeof gate !== 'string') return { kind: 'unproven', reason: gate.detail }
135
+ return gate === 'absent'
136
+ ? { kind: 'proved-ungated' }
137
+ : { kind: 'gated', reason: 'Fake destination requires merge gates' }
138
+ }
84
139
  readonly name = 'fake'
140
+ readonly archives = new Map<string, string>()
141
+ readonly rewrites: { branch: string; expected: string; sha: string }[] = []
142
+ rewrite: import('../types').ForgeRewrite = {
143
+ snapshot: async ({ branch }) => {
144
+ const sha = this.remoteBranches.get(branch)
145
+ if (sha === undefined) throw new Error(`fake: unknown build branch ${branch}`)
146
+ return sha
147
+ },
148
+ archive: async ({ ref, sha }) => {
149
+ const prior = this.archives.get(ref)
150
+ if (prior !== undefined && prior !== sha) throw new Error(`immutable archive ${ref} differs`)
151
+ this.archives.set(ref, sha)
152
+ },
153
+ replace: async ({ branch, expected, sha }) => {
154
+ const actual = this.remoteBranches.get(branch) ?? null
155
+ if (actual === sha) return { kind: 'published' }
156
+ if (actual !== expected) return { kind: 'lease-mismatch', actual }
157
+ this.rewrites.push({ branch, expected, sha })
158
+ this.remoteBranches.set(branch, sha)
159
+ return { kind: 'published' }
160
+ },
161
+ }
85
162
  readonly prAttachments?: PrAttachmentHosting
86
163
 
87
164
  /** Optional checkout-less read seam (SPEC §16.1 pipeline pinning): seeded
@@ -90,6 +167,8 @@ export class FakeForge implements Forge {
90
167
  * not-found contract as the production adapters. */
91
168
  readonly remoteBranches = new Map<string, string>()
92
169
  readonly files = new Map<string, string>()
170
+ readonly commitMessages = new Map<string, string>()
171
+ readonly buildSlugs = new Map<number, string>()
93
172
 
94
173
  /** Journals — public so tests assert directly on call order and args. */
95
174
  readonly pushes: PushRecord[] = []
@@ -122,6 +201,29 @@ export class FakeForge implements Forge {
122
201
  private readonly deleteBranchErrors: string[] = []
123
202
  private readonly publishedBranches = new Set<string>()
124
203
 
204
+ readonly nodeOpenings: { branch: string; sha: string }[] = []
205
+ readonly nodeComparisons = new Map<string, number>()
206
+ readonly nodeAncestors = new Map<string, Set<string>>()
207
+ async createNodeBranch(branch: string, sha: string): Promise<string> {
208
+ this.nodeOpenings.push({ branch, sha })
209
+ const existing = this.remoteBranches.get(branch)
210
+ if (existing !== undefined) {
211
+ if (existing !== sha && !this.nodeAncestors.get(existing)?.has(sha))
212
+ throw new Error(`node branch collision: ${branch}`)
213
+ return existing
214
+ }
215
+ this.remoteBranches.set(branch, sha)
216
+ return sha
217
+ }
218
+ async compareBranches(parent: string, head: string) {
219
+ const parentSha = await this.remoteBranchSha(parent)
220
+ const headSha = await this.remoteBranchSha(head)
221
+ const ahead = this.nodeComparisons.get(`${parent}...${head}`)
222
+ if (ahead === undefined && parentSha !== headSha)
223
+ throw new Error('seed fake node comparison for differing heads')
224
+ return { parentSha, headSha, ahead: ahead ?? 0 }
225
+ }
226
+
125
227
  constructor(
126
228
  opts: {
127
229
  headSha?: HeadSha
@@ -365,6 +467,10 @@ export class FakeForge implements Forge {
365
467
  async pushBranch(workspacePath: string, branch: string): Promise<void> {
366
468
  this.pushes.push({ workspacePath, branch })
367
469
  this.publishedBranches.add(branch)
470
+ this.remoteBranches.set(
471
+ branch,
472
+ typeof this.headSha === 'string' ? this.headSha : this.headSha(this.nextNumber),
473
+ )
368
474
  }
369
475
 
370
476
  async closePr(workspacePath: string, number: number): Promise<ClosePrResult> {
@@ -383,6 +489,7 @@ export class FakeForge implements Forge {
383
489
  const error = this.deleteBranchErrors.shift()
384
490
  if (error !== undefined) throw new Error(error)
385
491
  this.publishedBranches.delete(branch)
492
+ this.remoteBranches.delete(branch)
386
493
  }
387
494
 
388
495
  async openPr(opts: {
@@ -396,7 +503,7 @@ export class FakeForge implements Forge {
396
503
  // Idempotent by head branch, mirroring GitHubForge (SPEC §8.7).
397
504
  for (let i = this.opened.length - 1; i >= 0; i -= 1) {
398
505
  const number = i + 1
399
- if (this.opened[i]!.head !== opts.head) continue
506
+ if (this.opened[i]!.head !== opts.head || this.opened[i]!.base !== opts.base) continue
400
507
  if (this.prs.get(number)?.state !== 'open') continue
401
508
  return {
402
509
  number,
@@ -418,14 +525,18 @@ export class FakeForge implements Forge {
418
525
  this.getPrStateCalls.push({ workspacePath, number })
419
526
  const state = this.prs.get(number)
420
527
  if (!state) throw new Error(`FakeForge: unknown PR #${number}`)
421
- return state
528
+ return state.state === 'open'
529
+ ? { ...state, nativeAutoMerge: state.nativeAutoMerge ?? this.isAutoMergeEnabled(number) }
530
+ : state
422
531
  }
423
532
 
424
533
  async setAutoMerge(
425
534
  workspacePath: string,
426
535
  number: number,
427
536
  enabled: boolean,
537
+ options?: BuildLandingOptions,
428
538
  ): Promise<AutoMergeResult> {
539
+ if (enabled && options !== undefined) this.buildSlugs.set(number, options.buildSlug)
429
540
  this.assertPr(number)
430
541
  const currentlyEnabled = this.autoMerge.get(number) ?? false
431
542
 
@@ -450,6 +561,8 @@ export class FakeForge implements Forge {
450
561
  this.autoMergeCalls.push({ workspacePath, number, enabled: true, changed: false })
451
562
  return { kind: 'deferred', reason }
452
563
  }
564
+ if (options?.canApply !== undefined && !(await options.canApply()))
565
+ return { kind: 'deferred' }
453
566
  this.autoMerge.set(number, true)
454
567
  this.autoMergeCalls.push({
455
568
  workspacePath,
@@ -484,7 +597,12 @@ export class FakeForge implements Forge {
484
597
  }
485
598
  }
486
599
 
487
- async squashMerge(workspacePath: string, number: number, expectedHeadSha: string): Promise<void> {
600
+ async squashMerge(
601
+ workspacePath: string,
602
+ number: number,
603
+ expectedHeadSha: string,
604
+ options?: BuildLandingOptions,
605
+ ): Promise<void> {
488
606
  this.assertPr(number)
489
607
  const error = this.squashErrors.get(number)
490
608
  if (error !== undefined) throw new Error(error)
@@ -509,10 +627,30 @@ export class FakeForge implements Forge {
509
627
  throw new Error(`FakeForge: PR #${number} is no longer direct-merge eligible`)
510
628
  }
511
629
 
512
- this.squashMergeCalls.push({ workspacePath, number, expectedHeadSha })
630
+ this.squashMergeCalls.push({
631
+ workspacePath,
632
+ number,
633
+ expectedHeadSha,
634
+ ...(options === undefined ? {} : { buildSlug: options.buildSlug }),
635
+ })
636
+ const message = this.opened[number - 1]?.mergeMessage ?? this.opened[number - 1]?.body ?? ''
637
+ this.commitMessages.set(
638
+ this.resolveMergeSha(number),
639
+ options === undefined ? message : withBuildTrailer(message, options.buildSlug),
640
+ )
513
641
  this.prs.set(number, { state: 'merged', sha: this.resolveMergeSha(number) })
514
642
  }
515
643
 
644
+ async readCommitMessage(_workspacePath: string, sha: string): Promise<string> {
645
+ return this.commitMessages.get(sha) ?? ''
646
+ }
647
+
648
+ async containsBuild(_workspacePath: string, branch: string, buildSlug: string): Promise<boolean> {
649
+ const sha = this.remoteBranches.get(branch)
650
+ if (sha === undefined) throw new Error(`FakeForge: unknown branch ${branch}`)
651
+ return hasBuildTrailer(await this.readCommitMessage(_workspacePath, sha), buildSlug)
652
+ }
653
+
516
654
  async commentOnPr(workspacePath: string, number: number, body: string): Promise<void> {
517
655
  this.assertPr(number)
518
656
  const marker = findSummaryMarker(body)
@@ -0,0 +1,232 @@
1
+ import type { ForgeRewrite, RewriteResult } from '../types'
2
+ import type { Exec } from '../workspace/git-worktree'
3
+ import { isValidGitBranchName } from '../../kernel/origin'
4
+
5
+ const oid = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/
6
+ function object(value: string): void {
7
+ if (!oid.test(value)) throw new Error(`rewrite requires an exact object id: ${value}`)
8
+ }
9
+ function branchRef(branch: string): string {
10
+ if (!isValidGitBranchName(branch) || !/^(?:ab|ab-node)\/[a-z0-9]+(?:-[a-z0-9]+)*$/.test(branch))
11
+ throw new Error(`rewrite requires a build branch: ${branch}`)
12
+ return `refs/heads/${branch}`
13
+ }
14
+
15
+ /** Git transport and shared-database implementations share validation, but local-git
16
+ * never consults a remote, even when the repository happens to have one. */
17
+ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
18
+ async function git(cwd: string, args: string[], allowFailure = false) {
19
+ const result = await exec(['git', ...args], { cwd })
20
+ if (!allowFailure && result.exitCode !== 0)
21
+ throw new Error(
22
+ `reconcile git ${args.join(' ')} failed: ${result.stderr || result.stdout}; enable refs/autobuild/archive/ publication and guarded build-branch rewrites`,
23
+ )
24
+ return result
25
+ }
26
+ async function read(cwd: string, ref: string): Promise<string | null> {
27
+ const result = await git(
28
+ cwd,
29
+ local ? ['rev-parse', '--verify', '--quiet', ref] : ['ls-remote', '--refs', 'origin', ref],
30
+ true,
31
+ )
32
+ if (local && result.exitCode === 1) return null
33
+ if (result.exitCode !== 0) throw new Error(`cannot read ${ref}: ${result.stderr}`)
34
+ const sha = result.stdout.trim().split(/\s+/)[0]
35
+ if (!sha) return null
36
+ object(sha)
37
+ return sha
38
+ }
39
+ return {
40
+ async fastForward(input) {
41
+ object(input.expected)
42
+ object(input.sha)
43
+ if (!isValidGitBranchName(input.branch)) throw new Error('invalid fast-forward destination')
44
+ const ancestry = await git(
45
+ input.workspacePath,
46
+ ['merge-base', '--is-ancestor', input.expected, input.sha],
47
+ true,
48
+ )
49
+ if (ancestry.exitCode !== 0) throw new Error('publication is not a fast-forward')
50
+ const ref = `refs/heads/${input.branch}`
51
+ const actual = await read(input.workspacePath, ref)
52
+ if (actual !== input.expected) return { kind: 'lease-mismatch', actual }
53
+ const result = await git(
54
+ input.workspacePath,
55
+ local
56
+ ? ['update-ref', ref, input.sha, input.expected]
57
+ : [
58
+ 'push',
59
+ '--porcelain',
60
+ `--force-with-lease=${ref}:${input.expected}`,
61
+ 'origin',
62
+ `${input.sha}:${ref}`,
63
+ ],
64
+ true,
65
+ )
66
+ if (result.exitCode !== 0)
67
+ return { kind: 'lease-mismatch', actual: await read(input.workspacePath, ref) }
68
+ return { kind: 'published' }
69
+ },
70
+ async snapshot(input) {
71
+ const ref = branchRef(input.branch)
72
+ if (!/^refs\/autobuild\/reconcile\/[a-z0-9-]+\/[a-z0-9/-]+$/.test(input.destinationRef))
73
+ throw new Error('snapshot requires a build-private reconcile ref')
74
+ if (local) {
75
+ const sha = await read(input.workspacePath, ref)
76
+ if (sha === null)
77
+ throw new Error(`build branch ${ref} was deleted; restore it before reconciling`)
78
+ await git(input.workspacePath, ['update-ref', input.destinationRef, sha])
79
+ return sha
80
+ }
81
+ await git(input.workspacePath, [
82
+ 'fetch',
83
+ '--no-tags',
84
+ '--no-write-fetch-head',
85
+ '--refmap=',
86
+ 'origin',
87
+ `+${ref}:${input.destinationRef}`,
88
+ ])
89
+ const result = await git(input.workspacePath, [
90
+ 'rev-parse',
91
+ '--verify',
92
+ `${input.destinationRef}^{commit}`,
93
+ ])
94
+ const sha = result.stdout.trim()
95
+ object(sha)
96
+ return sha
97
+ },
98
+ async archive(input) {
99
+ object(input.sha)
100
+ if (
101
+ !/^refs\/autobuild\/archive\/[a-z0-9]+(?:-[a-z0-9]+)*\/[0-9a-f]+$/.test(input.ref) ||
102
+ !input.ref.endsWith(`/${input.sha}`)
103
+ )
104
+ throw new Error(`invalid immutable archive ref: ${input.ref}`)
105
+ const existing = await read(input.workspacePath, input.ref)
106
+ if (existing !== null && existing !== input.sha)
107
+ throw new Error(`immutable archive ${input.ref} names ${existing}, expected ${input.sha}`)
108
+ if (existing === null) {
109
+ const result = await git(
110
+ input.workspacePath,
111
+ local
112
+ ? ['update-ref', input.ref, input.sha, '0'.repeat(input.sha.length)]
113
+ : ['push', `--force-with-lease=${input.ref}:`, 'origin', `${input.sha}:${input.ref}`],
114
+ true,
115
+ )
116
+ // An uncertain acknowledgement is adopted only after an exact readback.
117
+ if ((await read(input.workspacePath, input.ref)) !== input.sha)
118
+ throw new Error(
119
+ `archive publication rejected for ${input.ref}: ${result.stderr}; enable refs/autobuild/archive/ publication before branch rewrites`,
120
+ )
121
+ }
122
+ if (!local) {
123
+ // Fetch by the exact archive ref, never by an unadvertised object id.
124
+ await git(input.workspacePath, [
125
+ 'fetch',
126
+ '--no-tags',
127
+ '--no-write-fetch-head',
128
+ 'origin',
129
+ input.ref,
130
+ ])
131
+ }
132
+ await git(input.workspacePath, ['cat-file', '-e', `${input.sha}^{commit}`])
133
+ },
134
+ async replace(input): Promise<RewriteResult> {
135
+ object(input.expected)
136
+ object(input.sha)
137
+ const ref = branchRef(input.branch)
138
+ const actual = await read(input.workspacePath, ref)
139
+ async function acknowledge(): Promise<RewriteResult> {
140
+ if (!local) {
141
+ const localHead = await git(
142
+ input.workspacePath,
143
+ ['rev-parse', '--verify', '--quiet', ref],
144
+ true,
145
+ )
146
+ if (localHead.exitCode === 0 && localHead.stdout.trim() !== input.sha)
147
+ await git(input.workspacePath, [
148
+ 'update-ref',
149
+ ref,
150
+ input.sha,
151
+ input.localExpected ?? input.expected,
152
+ ])
153
+ }
154
+ // Replay stays detached until the guarded branch update is confirmed.
155
+ // Reattach only its exact workspace result; explicit-source callers may
156
+ // legitimately publish an object other than their checked-out HEAD.
157
+ const workspaceHead = await git(input.workspacePath, ['rev-parse', 'HEAD'])
158
+ if (!input.branch.startsWith('ab-node/') && workspaceHead.stdout.trim() === input.sha)
159
+ await git(input.workspacePath, ['checkout', '--no-guess', input.branch])
160
+ return { kind: 'published' }
161
+ }
162
+ async function mismatch(observed: string | null): Promise<RewriteResult> {
163
+ // Recover the effect-before-receipt window from immutable intent inputs
164
+ // and branch ancestry. The candidate must be newly introduced, not an
165
+ // ancestor already present in the expected old history.
166
+ if (
167
+ observed !== null &&
168
+ input.sha !== input.expected &&
169
+ (await git(input.workspacePath, ['cat-file', '-e', `${input.sha}^{commit}`], true))
170
+ .exitCode === 0 &&
171
+ (await git(input.workspacePath, ['cat-file', '-e', `${input.expected}^{commit}`], true))
172
+ .exitCode === 0
173
+ ) {
174
+ if (
175
+ !local &&
176
+ (await git(input.workspacePath, ['cat-file', '-e', `${observed}^{commit}`], true))
177
+ .exitCode !== 0
178
+ ) {
179
+ const fetchedRef = `refs/autobuild/reconcile/${input.branch.replace(/^(?:ab|ab-node)\//, '')}/rewrite-observed`
180
+ await git(input.workspacePath, [
181
+ 'fetch',
182
+ '--no-tags',
183
+ '--no-write-fetch-head',
184
+ 'origin',
185
+ `+${ref}:${fetchedRef}`,
186
+ ])
187
+ observed = (
188
+ await git(input.workspacePath, ['rev-parse', '--verify', `${fetchedRef}^{commit}`])
189
+ ).stdout.trim()
190
+ object(observed)
191
+ }
192
+ const introduced = await git(
193
+ input.workspacePath,
194
+ ['merge-base', '--is-ancestor', input.sha, input.expected],
195
+ true,
196
+ )
197
+ const retained = await git(
198
+ input.workspacePath,
199
+ ['merge-base', '--is-ancestor', input.sha, observed],
200
+ true,
201
+ )
202
+ if (introduced.exitCode === 1 && retained.exitCode === 0)
203
+ return { kind: 'lease-mismatch', actual: observed, rewritten: true }
204
+ }
205
+ return { kind: 'lease-mismatch', actual: observed }
206
+ }
207
+ if (actual === input.sha) return acknowledge()
208
+ if (actual !== input.expected) return mismatch(actual)
209
+ const result = await git(
210
+ input.workspacePath,
211
+ local
212
+ ? ['update-ref', ref, input.sha, input.expected]
213
+ : [
214
+ 'push',
215
+ `--force-with-lease=${ref}:${input.expected}`,
216
+ 'origin',
217
+ `${input.sha}:${ref}`,
218
+ ],
219
+ true,
220
+ )
221
+ const after = await read(input.workspacePath, ref)
222
+ if (after === input.sha) return acknowledge()
223
+ // A successful CAS is a fact even if its candidate is overtaken before
224
+ // readback. Callers record that rewrite, then replay the observed head.
225
+ if (result.exitCode === 0) return { kind: 'lease-mismatch', actual: after, rewritten: true }
226
+ if (after !== input.expected) return mismatch(after)
227
+ throw new Error(
228
+ `guarded rewrite rejected for ${ref}: ${result.stderr}; enable guarded build-branch rewrites`,
229
+ )
230
+ },
231
+ }
232
+ }