@defrex/autobuild 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +307 -27
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +198 -25
  5. package/docs/build-store.md +18 -0
  6. package/docs/builds.md +5 -1
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +38 -19
  9. package/docs/dispatcher-hosting.md +42 -0
  10. package/docs/dispatcher.md +41 -0
  11. package/docs/forges.md +5 -0
  12. package/docs/integration-tree.md +8 -0
  13. package/docs/operating.md +11 -3
  14. package/docs/operator-api.md +37 -4
  15. package/docs/plugin-authoring.md +45 -1
  16. package/docs/remote-store-protocol.md +262 -42
  17. package/docs/remote-ticket-protocol.md +12 -10
  18. package/docs/restacking.md +60 -3
  19. package/docs/setup.md +37 -8
  20. package/docs/skills.md +1 -1
  21. package/docs/spec-standard.md +37 -3
  22. package/docs/troubleshooting.md +9 -0
  23. package/docs/workspaces.md +1 -1
  24. package/package.json +4 -3
  25. package/packages/core/src/accounts/availability.ts +96 -0
  26. package/packages/core/src/accounts/local-owner.ts +49 -2
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary.ts +17 -1
  29. package/packages/core/src/cli/context.ts +62 -0
  30. package/packages/core/src/cli/dashboard/model.ts +12 -3
  31. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  32. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  33. package/packages/core/src/cli/dashboard/render.ts +46 -5
  34. package/packages/core/src/cli/dispatch-args.ts +27 -3
  35. package/packages/core/src/cli/dispatch-frontend.ts +187 -53
  36. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +45 -9
  39. package/packages/core/src/cli/dispatch.ts +145 -11
  40. package/packages/core/src/cli/harvest.ts +2 -1
  41. package/packages/core/src/cli/help.ts +16 -3
  42. package/packages/core/src/cli/historical-build-state.ts +6 -0
  43. package/packages/core/src/cli/main.ts +15 -2
  44. package/packages/core/src/cli/publication-settlement.ts +17 -0
  45. package/packages/core/src/cli/remote-poll.ts +11 -1
  46. package/packages/core/src/cli/repository-status.ts +11 -0
  47. package/packages/core/src/cli/status.ts +7 -1
  48. package/packages/core/src/cli/wait.ts +9 -2
  49. package/packages/core/src/cli/watch.ts +38 -3
  50. package/packages/core/src/config/roles.ts +16 -1
  51. package/packages/core/src/events/catalog.ts +7 -0
  52. package/packages/core/src/events/payloads.ts +85 -2
  53. package/packages/core/src/events/policy.ts +10 -0
  54. package/packages/core/src/events/repository.ts +35 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +189 -0
  56. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  57. package/packages/core/src/kernel/engine.ts +19 -12
  58. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  59. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  60. package/packages/core/src/kernel/log-index.ts +1 -1
  61. package/packages/core/src/kernel/node-landing.ts +27 -10
  62. package/packages/core/src/kernel/node-restack-demand.ts +1 -0
  63. package/packages/core/src/kernel/node-restack-state.ts +16 -1
  64. package/packages/core/src/kernel/node-restack-transaction.ts +14 -0
  65. package/packages/core/src/kernel/read-facts.ts +114 -9
  66. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  67. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  68. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  69. package/packages/core/src/kernel/reducer.ts +20 -2
  70. package/packages/core/src/kernel/replay-retention.ts +176 -0
  71. package/packages/core/src/kernel/target-lineage.ts +65 -0
  72. package/packages/core/src/kernel/target-observation.ts +117 -0
  73. package/packages/core/src/operator/registry.ts +5 -13
  74. package/packages/core/src/operator/tickets.ts +8 -2
  75. package/packages/core/src/plugin-sdk/index.ts +1 -0
  76. package/packages/core/src/ports/forge/fake.ts +22 -0
  77. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  78. package/packages/core/src/ports/forge/github.ts +42 -10
  79. package/packages/core/src/ports/forge/local-git.ts +16 -1
  80. package/packages/core/src/ports/types.ts +58 -4
  81. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  82. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  83. package/packages/core/src/ports/workspace/create.ts +2 -0
  84. package/packages/core/src/ports/workspace/distribution-archive.ts +14 -4
  85. package/packages/core/src/ports/workspace/fake.ts +4 -0
  86. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  87. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  88. package/packages/core/src/processes/build-runner.ts +240 -111
  89. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  90. package/packages/core/src/processes/dispatcher.ts +262 -80
  91. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  92. package/packages/core/src/processes/harvest-runner.ts +6 -7
  93. package/packages/core/src/processes/publication-state.ts +2 -1
  94. package/packages/core/src/processes/repo-view.ts +22 -0
  95. package/packages/core/src/processes/tick-publication.ts +35 -47
  96. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  97. package/packages/core/src/scenarios/harness.ts +7 -0
  98. package/packages/core/src/store/adapter.ts +9 -0
  99. package/packages/core/src/store/build-scope.ts +28 -0
  100. package/packages/core/src/store/contract.ts +125 -0
  101. package/packages/core/src/store/event-reads.ts +156 -0
  102. package/packages/core/src/store/local/schema.ts +11 -0
  103. package/packages/core/src/store/local/store.ts +117 -2
  104. package/packages/core/src/store/memory.ts +237 -0
  105. package/packages/core/src/store/phase-session.ts +47 -0
  106. package/packages/core/src/store/reduced-reads.ts +8 -0
  107. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  108. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  109. package/packages/core/src/store/reducer-values.ts +62 -2
  110. package/packages/core/src/store/remote/client.ts +161 -16
  111. package/packages/core/src/store/remote/compatibility.ts +177 -46
  112. package/packages/core/src/store/remote/errors.ts +16 -0
  113. package/packages/core/src/store/remote/index.ts +11 -0
  114. package/packages/core/src/store/remote/protocol.ts +22 -0
  115. package/packages/core/src/store/remote/released-clients.json +48 -0
  116. package/packages/core/src/store/remote/released-clients.ts +88 -0
  117. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  118. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  119. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  120. package/packages/core/src/store/remote/version.ts +5 -2
  121. package/packages/core/src/store/repo-state-events.ts +4 -3
  122. package/packages/core/src/store/scan-cadence.ts +15 -0
  123. package/packages/core/src/store/session-handle.ts +18 -0
  124. package/packages/core/src/store/types.ts +27 -6
  125. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  126. package/packages/core/src/testing/index.ts +5 -0
  127. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  128. package/skills/guide/SKILL.md +201 -18
  129. package/skills/guide/references/accounts.md +38 -0
  130. package/skills/guide/references/integration-tree.md +8 -0
  131. package/skills/guide/references/operator-api.md +37 -4
  132. package/skills/guide/references/plugin-authoring.md +45 -1
  133. package/skills/guide/references/remote-store-protocol.md +262 -42
  134. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  135. package/skills/guide/references/restacking.md +60 -3
  136. package/skills/guide/references/setup.md +37 -8
  137. package/skills/guide/references/spec-standard.md +37 -3
  138. package/skills/implement/SKILL.md +12 -3
  139. package/skills/operate/SKILL.md +87 -15
  140. package/skills/plan/SKILL.md +27 -4
  141. package/skills/plan-review/SKILL.md +22 -2
  142. package/skills/reconcile/SKILL.md +10 -1
  143. package/skills/spec/SKILL.md +7 -4
  144. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { inspectGitCandidate } from '../ports/workspace/commit-preservation'
1
2
  import { createHash } from 'node:crypto'
2
3
  import { deferMixedVersion, MixedVersionDeferral } from './mixed-version'
3
4
  import { suspendNativeLanding } from './landing-publication'
@@ -19,7 +20,16 @@ export interface RestackDeps {
19
20
  workspacePath: string
20
21
  forge: Forge
21
22
  exec: Exec
23
+ instance?: string
24
+ clock?: import('../store/types').Clock
22
25
  beforeRewrite?: () => Promise<void>
26
+ probeCandidate?: (input: {
27
+ ref: string
28
+ slug: string
29
+ branch: string
30
+ sha: string
31
+ replayPack?: string
32
+ }) => Promise<boolean>
23
33
  automatic?: Pick<
24
34
  EventPayload<'restack.prepared'>,
25
35
  'trigger' | 'cycle' | 'observation' | 'message'
@@ -29,11 +39,16 @@ export interface RestackDeps {
29
39
  * transactions have their own durable vocabulary and never fabricate a phase. */
30
40
  async function replayHistory(deps: RestackDeps): Promise<readonly AbEvent[]> {
31
41
  const facts = (await readBuildFacts(deps.store, deps.slug)).value
32
- if (deps.automatic === undefined) return facts.reconcileHistory
42
+ const recovery = facts.candidateRecoveries[deps.automatic ? 'restack' : 'reconcile']
43
+ if (deps.automatic === undefined)
44
+ return facts.reconcileHistory.filter(
45
+ (event) => !('id' in event.payload && event.payload.id === recovery?.id),
46
+ )
33
47
  const mapped: AbEvent[] = [
34
48
  ...facts.reconcileHistory.filter((e) => e.type === 'workspace.provisioned'),
35
49
  ]
36
50
  for (const event of facts.restackHistory) {
51
+ if ('id' in event.payload && event.payload.id === recovery?.id) continue
37
52
  const type = event.type.replace('restack.', 'reconcile.')
38
53
  const payload = { ...event.payload, attempt: 1 }
39
54
  // Only replay mechanics consume these records; external writes below are
@@ -96,75 +111,8 @@ export function requireRewrite(forge: Forge) {
96
111
  return forge.rewrite
97
112
  }
98
113
 
99
- /** Retain the resolved commit and its new trees/blobs before durable intent.
100
- * Commit bytes alone cannot reconstruct a cherry-pick's combined tree after a
101
- * disposable guest disappears. Base history remains in the authoritative Git
102
- * repository; this pack retains only objects introduced above that base. */
103
- export async function retainReplay(deps: RestackDeps, head: string, base: string) {
104
- const result = await deps.exec(
105
- [
106
- 'bash',
107
- '-o',
108
- 'pipefail',
109
- '-c',
110
- 'printf "%s\\n" "$1" "^$2" | git pack-objects --stdout --revs | base64 -w0',
111
- 'retain-replay',
112
- head,
113
- base,
114
- ],
115
- { cwd: deps.workspacePath },
116
- )
117
- if (result.exitCode !== 0 || result.stdout.trim() === '')
118
- throw new Error(`cannot retain replay objects: ${result.stderr}`)
119
- await deps.store.putArtifact(deps.slug, {
120
- kind: `replay-objects-${head}`,
121
- content: result.stdout.trim(),
122
- })
123
- }
124
- export async function restoreReplay(deps: RestackDeps, sha: string): Promise<boolean> {
125
- const artifact = await deps.store.getArtifact(deps.slug, `replay-objects-${sha}`)
126
- if (artifact === null) return false
127
- const content = new TextDecoder().decode(artifact.content)
128
- if (!/^[A-Za-z0-9+/=]+$/.test(content)) throw new Error('invalid retained replay pack')
129
- const temporary = (await deps.exec(['mktemp'], { cwd: deps.workspacePath })).stdout.trim()
130
- if (temporary === '') throw new Error('cannot create retained replay input')
131
- try {
132
- for (let offset = 0; offset < content.length; offset += 16_384) {
133
- const written = await deps.exec(
134
- [
135
- 'sh',
136
- '-c',
137
- 'printf %s "$1" >> "$2"',
138
- 'replay-chunk',
139
- content.slice(offset, offset + 16_384),
140
- temporary,
141
- ],
142
- { cwd: deps.workspacePath },
143
- )
144
- if (written.exitCode !== 0) throw new Error('cannot stage retained replay input')
145
- }
146
- const result = await deps.exec(
147
- [
148
- 'bash',
149
- '-o',
150
- 'pipefail',
151
- '-c',
152
- 'base64 -d "$1" | git unpack-objects -q',
153
- 'restore-replay',
154
- temporary,
155
- ],
156
- { cwd: deps.workspacePath },
157
- )
158
- if (
159
- result.exitCode !== 0 ||
160
- (await git(deps, ['cat-file', '-e', `${sha}^{commit}`], true)).exitCode !== 0
161
- )
162
- throw new Error(`cannot restore replay objects ${sha}`)
163
- } finally {
164
- await deps.exec(['rm', '-f', temporary], { cwd: deps.workspacePath })
165
- }
166
- return true
167
- }
114
+ export { retainReplay, restoreReplay } from './replay-retention'
115
+ import { restoreReplay } from './replay-retention'
168
116
 
169
117
  /** Restore a sandbox-only change from durable bytes without remote write access. */
170
118
  async function restoreChange(deps: RestackDeps, sha: string): Promise<boolean> {
@@ -181,6 +129,81 @@ async function restoreChange(deps: RestackDeps, sha: string): Promise<boolean> {
181
129
  return true
182
130
  }
183
131
 
132
+ /** Exact availability probes only. Transport/auth errors defer recovery;
133
+ * successful empty ref reads plus absent replay bytes prove candidate loss. */
134
+ export async function recoverLostCandidate(
135
+ deps: RestackDeps,
136
+ ): Promise<'none' | 'available' | 'retired'> {
137
+ const current = await readBuildFacts(deps.store, deps.slug)
138
+ const request = current.value.publication.latestUncompletedRequest()
139
+ if (!request || !current.value.publication.lostRecorded(request)) return 'none'
140
+ const payload = request.payload
141
+ if ((payload.operation !== 'reconcile' && payload.operation !== 'restack') || !payload.rewrite)
142
+ return 'none'
143
+ if (
144
+ current.value.state.sessions.open.length ||
145
+ current.value.state.status === 'paused' ||
146
+ current.value.state.status === 'blocked' ||
147
+ current.value.state.pendingCommands.length
148
+ )
149
+ return 'none'
150
+ const record = await deps.store.getBuild(deps.slug)
151
+ if (
152
+ current.value.open &&
153
+ record?.lease &&
154
+ new Date(record.lease.expiresAt).getTime() > (deps.clock?.() ?? new Date()).getTime() &&
155
+ (deps.instance === undefined ||
156
+ current.value.open.instance !== deps.instance ||
157
+ record.lease.holder !== deps.instance)
158
+ )
159
+ return 'none'
160
+ const sha = payload.sha
161
+ const artifact = await deps.store.getArtifact(deps.slug, `replay-objects-${sha}`)
162
+ const replayPack = artifact ? new TextDecoder().decode(artifact.content) : undefined
163
+ const available = deps.probeCandidate
164
+ ? await deps.probeCandidate({
165
+ ref: current.value.workspace?.ref ?? '',
166
+ slug: deps.slug,
167
+ branch: payload.branch,
168
+ sha,
169
+ replayPack,
170
+ })
171
+ : await inspectGitCandidate({
172
+ exec: deps.forge.kernelExec ?? deps.exec,
173
+ workspacePath: deps.workspacePath,
174
+ branch: payload.branch,
175
+ sha,
176
+ archiveRef: `refs/autobuild/archive/${deps.slug}/${sha}`,
177
+ local: deps.forge.name === 'local-git',
178
+ replayPack,
179
+ })
180
+ if (available) {
181
+ if (!current.value.workspace || !isRemoteWorkspace(current.value.workspace))
182
+ await (deps.forge.kernelRewrite ?? requireRewrite(deps.forge)).archive({
183
+ workspacePath: deps.workspacePath,
184
+ ref: `refs/autobuild/archive/${deps.slug}/${sha}`,
185
+ sha,
186
+ })
187
+ return 'available'
188
+ }
189
+ if (await deferMixedVersion(deps.store, deps.slug, KERNEL)) throw new MixedVersionDeferral()
190
+ if (
191
+ !(await deps.store.appendIfCurrent(deps.slug, current.cursor, {
192
+ actor: KERNEL,
193
+ type: 'publication.candidate-retired',
194
+ payload: {
195
+ request: request.seq,
196
+ operation: payload.operation,
197
+ id: payload.rewrite.id,
198
+ sha,
199
+ replacementId: `${payload.rewrite.id}-recovery-${request.seq}`,
200
+ },
201
+ }))
202
+ )
203
+ throw new Error('publication changed during candidate recovery; retry')
204
+ return 'retired'
205
+ }
206
+
184
207
  export async function archiveTips(deps: RestackDeps, extra: string[] = []) {
185
208
  const capability = requireRewrite(deps.forge)
186
209
  const facts = (await readBuildFacts(deps.store, deps.slug)).value
@@ -188,14 +211,13 @@ export async function archiveTips(deps: RestackDeps, extra: string[] = []) {
188
211
  const archives: { ref: string; sha: string }[] = []
189
212
  for (const sha of tips) {
190
213
  const ref = `refs/autobuild/archive/${deps.slug}/${sha}`
191
- // Recovery can obtain evidence from an already published exact archive.
214
+ // Restore durable local changes first; the remote capability recovers other objects.
192
215
  if (
193
216
  (await git(deps, ['cat-file', '-e', `${sha}^{commit}`], true)).exitCode !== 0 &&
194
217
  !(await restoreChange(deps, sha))
195
218
  ) {
196
219
  if (deps.forge.name === 'local-git')
197
220
  throw new Error(`missing recorded Git object ${sha}; restore it before reconcile`)
198
- await git(deps, ['fetch', '--no-tags', '--no-write-fetch-head', 'origin', ref])
199
221
  }
200
222
  await capability.archive({ workspacePath: deps.workspacePath, ref, sha })
201
223
  archives.push({ ref, sha })
@@ -219,6 +241,18 @@ export async function prepareRestack(
219
241
  ): Promise<ReconcileTransaction> {
220
242
  if (await deferMixedVersion(deps.store, deps.slug, KERNEL)) throw new MixedVersionDeferral()
221
243
  const capability = requireRewrite(deps.forge)
244
+ await recoverLostCandidate(deps)
245
+ const recovery = (await readBuildFacts(deps.store, deps.slug)).value.candidateRecoveries[
246
+ deps.automatic ? 'restack' : 'reconcile'
247
+ ]
248
+ if (
249
+ recovery &&
250
+ (input.id === recovery.id ||
251
+ (deps.automatic === undefined &&
252
+ (await readBuildFacts(deps.store, deps.slug)).value.reconcileTransaction?.id ===
253
+ recovery.id))
254
+ )
255
+ input = { ...input, id: recovery.replacementId }
222
256
  const events = await replayHistory(deps)
223
257
  const prior = events.findLast(
224
258
  (e) =>
@@ -22,6 +22,7 @@ import {
22
22
  } from './service-facts'
23
23
  import { phaseSchema } from '../ontology'
24
24
  import { z } from 'zod'
25
+ import { dispatchPlacementReducer } from './dispatch-placement'
25
26
  import type { ValueCatalogEntry } from '../store/reducer-values'
26
27
  import { dispatchFrontendReducer } from '../cli/dispatch-repository-feed'
27
28
  import { executionNoProgressReducer } from '../processes/execution-no-progress'
@@ -191,6 +192,7 @@ const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
191
192
  autoMergeDefault: { reducer: autoMergeDefaultReducer, covers: ['latestAutoMergeDefault'] },
192
193
  pinnedAssets: { reducer: pinnedAssetsReducer, covers: ['findPinnedRevision'] },
193
194
  forgeHealthValue: { reducer: optionalValue(forgeHealthReducer), covers: [] },
195
+ dispatchPlacement: { reducer: dispatchPlacementReducer, covers: [] },
194
196
  }
195
197
 
196
198
  /** Qualification concerns the existing finished contract, including absence. */
@@ -217,6 +219,7 @@ const valueExclusions: Record<string, string> = {
217
219
  ),
218
220
  }
219
221
  const repositoryValues = new Set([
222
+ 'dispatchPlacement',
220
223
  'ticketPreparation',
221
224
  'ticketMigrations',
222
225
  'forgeHealthValue',
@@ -256,6 +256,7 @@ export interface BuildState {
256
256
  pr?: { number: number; url: string; headSha: string }
257
257
  prState?: PrLifecycle
258
258
  /** Readiness provenance, landing-bound consent and native application receipts. */
259
+ targetRewrite?: Extract<AbEvent, { type: 'target.rewritten' }>
259
260
  janitor?: {
260
261
  firstFailureAt: string
261
262
  attempt: number
@@ -423,6 +424,7 @@ export interface BuildAcc {
423
424
  reviewRoundCeilings: BuildState['reviewRoundCeilings']
424
425
  pr: BuildState['pr']
425
426
  prState?: PrLifecycle
427
+ targetRewrite?: Extract<AbEvent, { type: 'target.rewritten' }>
426
428
  janitor?: {
427
429
  firstFailureAt: string
428
430
  attempt: number
@@ -465,7 +467,7 @@ export interface BuildAcc {
465
467
  }
466
468
 
467
469
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
468
- export const BUILD_REDUCER_VERSION = 26
470
+ export const BUILD_REDUCER_VERSION = 27
469
471
 
470
472
  function initialBuildAcc(): BuildAcc {
471
473
  return {
@@ -629,12 +631,22 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
629
631
  }
630
632
  if (event.type === 'build.janitor-failing' && acc.janitor) acc.janitor.attention = true
631
633
  if (event.type === 'build.janitor-recovered') delete acc.janitor
634
+ if (event.type === 'target.rewritten') acc.targetRewrite = event
635
+ if (
636
+ event.type === 'target.moved' ||
637
+ event.type === 'target.rewrite-cleared' ||
638
+ event.type === 'node.parent-accepted'
639
+ )
640
+ delete acc.targetRewrite
632
641
  advanceLanding(acc.landing, event)
633
642
  if (event.type.startsWith('integration.')) {
634
643
  acc.integration ??= {}
635
644
  advanceIntegration(acc.integration, event)
636
645
  }
637
- if (event.type.startsWith('node.') || (acc.kind === 'node' && event.type === 'target.moved')) {
646
+ if (
647
+ event.type.startsWith('node.') ||
648
+ (acc.kind === 'node' && event.type.startsWith('target.'))
649
+ ) {
638
650
  acc.nodeRestack ??= { items: [] }
639
651
  advanceNodeRestack(acc.nodeRestack, [event])
640
652
  }
@@ -700,6 +712,10 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
700
712
  pinnedAssets = event.payload.assets ?? []
701
713
  break
702
714
  case 'workspace.provisioned':
715
+ case 'workspace.cleanup-required':
716
+ case 'workspace.fenced':
717
+ case 'workspace.commits-preserved':
718
+ case 'workspace.commits-lost':
703
719
  case 'workspace.released':
704
720
  case 'pr-summary.requested':
705
721
  case 'pr-summary.attempted':
@@ -713,6 +729,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
713
729
  // the phase — the reducer needs no state from it.
714
730
  case 'publication.retry-scheduled':
715
731
  case 'publication.retry-exhausted':
732
+ case 'publication.candidate-retired':
716
733
  case 'publication.lost':
717
734
  case 'dispatch.comment-posted':
718
735
  case 'pr-attachment.designated':
@@ -1321,6 +1338,7 @@ function finishBuild(acc: BuildAcc): BuildState {
1321
1338
  reviewRoundCeilings: acc.reviewRoundCeilings,
1322
1339
  pr: acc.pr,
1323
1340
  prState: acc.prState,
1341
+ targetRewrite: acc.targetRewrite,
1324
1342
  janitor: acc.janitor,
1325
1343
  landing: acc.landing,
1326
1344
  autoMerge: acc.autoMerge,
@@ -0,0 +1,176 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { RestackDeps } from './reconcile-restack'
3
+
4
+ export const REPLAY_CHUNK_BYTES = 1024 * 1024
5
+ const shaPattern = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/
6
+ interface Manifest {
7
+ version: 1
8
+ head: string
9
+ base: string
10
+ digest: string
11
+ bytes: number
12
+ chunkBytes: number
13
+ chunks: number
14
+ }
15
+ function parse(content: Uint8Array): Manifest | string {
16
+ const text = new TextDecoder().decode(content)
17
+ if (
18
+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text) &&
19
+ text.length > 0
20
+ )
21
+ return text
22
+ const m = JSON.parse(text) as Manifest
23
+ if (
24
+ text.length > 1024 ||
25
+ m === null ||
26
+ typeof m !== 'object' ||
27
+ Object.keys(m).sort().join(',') !== 'base,bytes,chunkBytes,chunks,digest,head,version' ||
28
+ m.version !== 1 ||
29
+ !shaPattern.test(m.head) ||
30
+ !shaPattern.test(m.base) ||
31
+ !/^[a-f0-9]{64}$/.test(m.digest) ||
32
+ !Number.isSafeInteger(m.bytes) ||
33
+ m.bytes <= 0 ||
34
+ m.chunkBytes !== REPLAY_CHUNK_BYTES ||
35
+ !Number.isSafeInteger(m.chunks) ||
36
+ m.chunks !== Math.ceil(m.bytes / REPLAY_CHUNK_BYTES)
37
+ )
38
+ throw new Error('invalid retained replay manifest')
39
+ return m
40
+ }
41
+ const kind = (head: string) => `replay-objects-${head}`
42
+ const chunkKind = (m: Manifest, i: number) => `replay-v1-${m.digest}-${i}`
43
+ async function run(deps: RestackDeps, args: string[]) {
44
+ const r = await deps.exec(args, { cwd: deps.workspacePath })
45
+ if (r.exitCode !== 0) throw new Error(`replay command failed: ${r.stderr}`)
46
+ return r.stdout.trim()
47
+ }
48
+ async function present(deps: RestackDeps, head: string) {
49
+ return (
50
+ (await deps.exec(['git', 'cat-file', '-e', `${head}^{commit}`], { cwd: deps.workspacePath }))
51
+ .exitCode === 0
52
+ )
53
+ }
54
+ async function scratch(deps: RestackDeps) {
55
+ return run(deps, ['sh', '-c', 'mkdir -p .ab/replay && mktemp .ab/replay/pack.XXXXXXXX'])
56
+ }
57
+ async function stage(deps: RestackDeps, path: string, bytes: Uint8Array) {
58
+ // Keep Exec arguments bounded as well as store requests.
59
+ for (let offset = 0; offset < bytes.length; offset += 12288)
60
+ await run(deps, [
61
+ 'bash',
62
+ '-o',
63
+ 'pipefail',
64
+ '-c',
65
+ 'printf %s "$1" | base64 -d >> "$2"',
66
+ 'stage-replay',
67
+ Buffer.from(bytes.subarray(offset, offset + 12288)).toString('base64'),
68
+ path,
69
+ ])
70
+ }
71
+ function validateIdentity(m: Manifest | string, head: string, base?: string) {
72
+ if (typeof m !== 'string' && (m.head !== head || (base !== undefined && m.base !== base)))
73
+ throw new Error('retained replay identity mismatch')
74
+ }
75
+ /** Completion is published last; incomplete digest-keyed chunks are never a replay. */
76
+ export async function retainReplay(deps: RestackDeps, head: string, base: string) {
77
+ if (!shaPattern.test(head) || !shaPattern.test(base)) throw new Error('invalid replay identity')
78
+ const completed = await deps.store.getArtifact(deps.slug, kind(head))
79
+ if (completed !== null) {
80
+ validateIdentity(parse(completed.content), head, base)
81
+ return
82
+ }
83
+ const path = await scratch(deps)
84
+ try {
85
+ await run(deps, [
86
+ 'bash',
87
+ '-o',
88
+ 'pipefail',
89
+ '-c',
90
+ 'printf "%s\\n" "$1" "^$2" | git -c core.bigFileThreshold=2g pack-objects --stdout --revs --thin --window=50 --depth=50 --threads=1 --no-reuse-delta --no-reuse-object > "$3"',
91
+ 'retain-replay',
92
+ head,
93
+ base,
94
+ path,
95
+ ])
96
+ const bytes = Number(await run(deps, ['sh', '-c', 'wc -c < "$1"', 'pack-size', path]))
97
+ const digest = (await run(deps, ['sha256sum', path])).split(' ')[0]!
98
+ const m: Manifest = {
99
+ version: 1,
100
+ head,
101
+ base,
102
+ digest,
103
+ bytes,
104
+ chunkBytes: REPLAY_CHUNK_BYTES,
105
+ chunks: Math.ceil(bytes / REPLAY_CHUNK_BYTES),
106
+ }
107
+ parse(new TextEncoder().encode(JSON.stringify(m)))
108
+ for (let i = 0; i < m.chunks; i++) {
109
+ const encoded = await run(deps, [
110
+ 'bash',
111
+ '-o',
112
+ 'pipefail',
113
+ '-c',
114
+ 'dd if="$1" bs=1048576 skip="$2" count=1 status=none | base64 -w0',
115
+ 'read-replay',
116
+ path,
117
+ String(i),
118
+ ])
119
+ const content = Buffer.from(encoded, 'base64')
120
+ const prior = await deps.store.getArtifact(deps.slug, chunkKind(m, i))
121
+ if (prior !== null) {
122
+ if (!Buffer.from(prior.content).equals(content))
123
+ throw new Error('conflicting retained replay chunk')
124
+ } else await deps.store.putArtifact(deps.slug, { kind: chunkKind(m, i), content })
125
+ }
126
+ const prior = await deps.store.getArtifact(deps.slug, kind(head))
127
+ if (prior !== null) validateIdentity(parse(prior.content), head, base)
128
+ else await deps.store.putArtifact(deps.slug, { kind: kind(head), content: JSON.stringify(m) })
129
+ } finally {
130
+ await run(deps, ['rm', '-f', path])
131
+ }
132
+ }
133
+
134
+ export async function restoreReplay(deps: RestackDeps, head: string): Promise<boolean> {
135
+ if (!shaPattern.test(head)) throw new Error('invalid replay identity')
136
+ if (await present(deps, head)) return true
137
+ const artifact = await deps.store.getArtifact(deps.slug, kind(head))
138
+ if (artifact === null) return false
139
+ const m = parse(artifact.content)
140
+ validateIdentity(m, head)
141
+ const path = await scratch(deps)
142
+ try {
143
+ if (typeof m === 'string') {
144
+ await stage(deps, path, Buffer.from(m, 'base64'))
145
+ } else {
146
+ const hash = createHash('sha256')
147
+ for (let i = 0; i < m.chunks; i++) {
148
+ const chunk = await deps.store.getArtifact(deps.slug, chunkKind(m, i))
149
+ const expected = Math.min(m.chunkBytes, m.bytes - i * m.chunkBytes)
150
+ if (chunk === null || chunk.content.length !== expected)
151
+ throw new Error('missing or truncated retained replay chunk')
152
+ hash.update(chunk.content)
153
+ await stage(deps, path, chunk.content)
154
+ }
155
+ if (hash.digest('hex') !== m.digest) throw new Error('retained replay digest mismatch')
156
+ }
157
+ await run(deps, [
158
+ 'sh',
159
+ '-c',
160
+ typeof m === 'string'
161
+ ? 'git unpack-objects -q < "$1"'
162
+ : 'git index-pack --stdin --fix-thin < "$1"',
163
+ 'restore-replay',
164
+ path,
165
+ ])
166
+ if (!(await present(deps, head))) throw new Error('retained replay commit missing')
167
+ if (
168
+ typeof m !== 'string' &&
169
+ (await run(deps, ['git', 'show', '-s', '--format=%P', head])) !== m.base
170
+ )
171
+ throw new Error('retained replay parent mismatch')
172
+ return true
173
+ } finally {
174
+ await run(deps, ['rm', '-f', path])
175
+ }
176
+ }
@@ -0,0 +1,65 @@
1
+ import { gitOid } from '../events/payloads'
2
+ import type { EventPayload } from '../events/payloads'
3
+ import type { Forge } from '../ports/types'
4
+ import type { BuildStore } from '../store/types'
5
+
6
+ export const MAX_TARGET_LINEAGE_HOPS = 64
7
+ export type TargetLineage = NonNullable<EventPayload<'target.moved'>['lineage']>[number]
8
+
9
+ /** Repository-scoped dispatcher proof. Neither branch ownership nor inventory
10
+ * is rewrite authority: every discontinuity needs a guarded publication receipt.
11
+ * Point reads cost O(gap), capped independently of total history. */
12
+ export async function proveTargetLineage(input: {
13
+ store: BuildStore
14
+ forge: Forge
15
+ node: string
16
+ branch: string
17
+ from: string
18
+ sha: string
19
+ }): Promise<TargetLineage | undefined> {
20
+ const { store, forge, node, branch, from, sha } = input
21
+ gitOid.parse(from)
22
+ gitOid.parse(sha)
23
+ if (!store.getNodeRewrite || !forge.isCommitAncestor) return undefined
24
+ const record = await store.getBuild(node)
25
+ if (record?.branch !== branch) return undefined
26
+ // Exact chains remain a cheap point-lookup path, including when a newer
27
+ // publication raced this observation. Share the read cap with gap recovery.
28
+ let reads = 0
29
+ let forward = from
30
+ const exact: TargetLineage['receipts'] = []
31
+ while (reads < MAX_TARGET_LINEAGE_HOPS) {
32
+ reads++
33
+ const receipt = await store.getNodeRewrite(node, forward)
34
+ if (!receipt || receipt.previous !== forward || receipt.head === forward) break
35
+ gitOid.parse(receipt.previous)
36
+ gitOid.parse(receipt.head)
37
+ exact.push(receipt)
38
+ forward = receipt.head
39
+ if (forward === sha || (await forge.isCommitAncestor(forward, sha)))
40
+ return { node, from, receipts: exact }
41
+ }
42
+ // Walk backwards from the latest guarded publication. Between receipts a
43
+ // sibling may land forward commits; prove each such immutable gap rather than
44
+ // requiring exact previous-head equality. Never infer a rewrite from ownership.
45
+ const receipts: TargetLineage['receipts'] = []
46
+ let head = sha
47
+ let beforePrevious: string | undefined
48
+ const seen = new Set<string>()
49
+ while (reads < MAX_TARGET_LINEAGE_HOPS) {
50
+ reads++
51
+ const receipt = await store.getNodeRewrite(node, undefined, beforePrevious)
52
+ if (!receipt || seen.has(receipt.id)) return undefined
53
+ seen.add(receipt.id)
54
+ gitOid.parse(receipt.previous)
55
+ gitOid.parse(receipt.head)
56
+ if (receipt.previous === receipt.head) return undefined
57
+ if (head !== receipt.head && !(await forge.isCommitAncestor(receipt.head, head)))
58
+ return undefined
59
+ receipts.unshift(receipt)
60
+ head = receipt.previous
61
+ if (from === head || (await forge.isCommitAncestor(from, head))) return { node, from, receipts }
62
+ beforePrevious = receipt.previous
63
+ }
64
+ return undefined
65
+ }