@defrex/autobuild 1.2.0 → 1.4.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 (164) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +416 -36
  3. package/docs/accounts.md +50 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +298 -17
  6. package/docs/build-store.md +18 -0
  7. package/docs/builds.md +7 -1
  8. package/docs/cli.md +1 -1
  9. package/docs/configuration-overview.md +6 -0
  10. package/docs/configuration.md +44 -19
  11. package/docs/dispatcher-hosting.md +42 -0
  12. package/docs/dispatcher.md +41 -0
  13. package/docs/forges.md +5 -0
  14. package/docs/integration-tree.md +24 -5
  15. package/docs/operating.md +11 -3
  16. package/docs/operator-api.md +81 -10
  17. package/docs/operator-surfaces.md +29 -0
  18. package/docs/plugin-authoring.md +51 -2
  19. package/docs/remote-store-protocol.md +321 -46
  20. package/docs/remote-ticket-protocol.md +12 -10
  21. package/docs/restacking.md +105 -3
  22. package/docs/setup.md +37 -8
  23. package/docs/skills.md +1 -1
  24. package/docs/spec-standard.md +41 -5
  25. package/docs/ticket-dependencies.md +8 -0
  26. package/docs/troubleshooting.md +9 -0
  27. package/docs/workspaces.md +1 -1
  28. package/package.json +4 -3
  29. package/packages/core/src/accounts/availability.ts +96 -0
  30. package/packages/core/src/accounts/local-owner.ts +49 -2
  31. package/packages/core/src/cli/attention.ts +2 -0
  32. package/packages/core/src/cli/binary.ts +17 -1
  33. package/packages/core/src/cli/context.ts +62 -0
  34. package/packages/core/src/cli/dashboard/model.ts +12 -3
  35. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  36. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  37. package/packages/core/src/cli/dashboard/render.ts +46 -5
  38. package/packages/core/src/cli/dispatch-args.ts +27 -3
  39. package/packages/core/src/cli/dispatch-frontend.ts +179 -52
  40. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  41. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +150 -33
  43. package/packages/core/src/cli/dispatch.ts +209 -36
  44. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  45. package/packages/core/src/cli/forge-clear.ts +30 -0
  46. package/packages/core/src/cli/harvest.ts +2 -1
  47. package/packages/core/src/cli/help.ts +17 -3
  48. package/packages/core/src/cli/historical-build-state.ts +6 -0
  49. package/packages/core/src/cli/main.ts +43 -2
  50. package/packages/core/src/cli/publication-settlement.ts +17 -0
  51. package/packages/core/src/cli/remote-poll.ts +11 -1
  52. package/packages/core/src/cli/repository-status.ts +11 -0
  53. package/packages/core/src/cli/status.ts +7 -1
  54. package/packages/core/src/cli/wait.ts +9 -2
  55. package/packages/core/src/cli/watch.ts +47 -16
  56. package/packages/core/src/config/roles.ts +16 -1
  57. package/packages/core/src/events/catalog.ts +8 -0
  58. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  59. package/packages/core/src/events/payloads.ts +95 -2
  60. package/packages/core/src/events/policy.ts +19 -0
  61. package/packages/core/src/events/repository.ts +108 -2
  62. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +464 -0
  63. package/packages/core/src/kernel/change-presence.ts +74 -8
  64. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  65. package/packages/core/src/kernel/engine.ts +27 -12
  66. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  67. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  68. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  69. package/packages/core/src/kernel/log-index.ts +1 -1
  70. package/packages/core/src/kernel/node-landing.ts +27 -10
  71. package/packages/core/src/kernel/node-polling.ts +40 -7
  72. package/packages/core/src/kernel/node-restack-demand.ts +75 -0
  73. package/packages/core/src/kernel/node-restack-state.ts +20 -1
  74. package/packages/core/src/kernel/node-restack-transaction.ts +47 -1
  75. package/packages/core/src/kernel/read-facts.ts +120 -9
  76. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  77. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  78. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  79. package/packages/core/src/kernel/reducer.ts +20 -2
  80. package/packages/core/src/kernel/replay-retention.ts +176 -0
  81. package/packages/core/src/kernel/target-lineage.ts +65 -0
  82. package/packages/core/src/kernel/target-observation.ts +117 -0
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +2 -0
  87. package/packages/core/src/operator/registry.ts +25 -13
  88. package/packages/core/src/operator/tickets.ts +8 -2
  89. package/packages/core/src/plugin-sdk/index.ts +1 -0
  90. package/packages/core/src/ports/forge/fake.ts +22 -0
  91. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  92. package/packages/core/src/ports/forge/github.ts +42 -10
  93. package/packages/core/src/ports/forge/local-git.ts +16 -1
  94. package/packages/core/src/ports/runner/account-env.ts +60 -9
  95. package/packages/core/src/ports/runner/claude.ts +49 -45
  96. package/packages/core/src/ports/types.ts +58 -4
  97. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  98. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  99. package/packages/core/src/ports/workspace/create.ts +2 -0
  100. package/packages/core/src/ports/workspace/fake.ts +4 -0
  101. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  102. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  103. package/packages/core/src/processes/build-runner.ts +240 -111
  104. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  105. package/packages/core/src/processes/dispatcher.ts +732 -201
  106. package/packages/core/src/processes/execution-no-progress.ts +8 -0
  107. package/packages/core/src/processes/harvest-runner.ts +6 -7
  108. package/packages/core/src/processes/harvest.ts +11 -16
  109. package/packages/core/src/processes/publication-state.ts +2 -1
  110. package/packages/core/src/processes/repo-view.ts +25 -0
  111. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  112. package/packages/core/src/scenarios/harness.ts +7 -0
  113. package/packages/core/src/store/adapter.ts +9 -0
  114. package/packages/core/src/store/artifact-meta.ts +7 -0
  115. package/packages/core/src/store/build-scope.ts +28 -0
  116. package/packages/core/src/store/contract.ts +182 -0
  117. package/packages/core/src/store/event-reads.ts +156 -0
  118. package/packages/core/src/store/local/schema.ts +11 -0
  119. package/packages/core/src/store/local/store.ts +117 -2
  120. package/packages/core/src/store/memory.ts +241 -0
  121. package/packages/core/src/store/phase-session.ts +47 -0
  122. package/packages/core/src/store/reduced-reads.ts +8 -0
  123. package/packages/core/src/store/reducer-value-shapes.json +10546 -8877
  124. package/packages/core/src/store/reducer-value-validation.ts +109 -6
  125. package/packages/core/src/store/reducer-values.ts +62 -2
  126. package/packages/core/src/store/remote/client.ts +208 -23
  127. package/packages/core/src/store/remote/compatibility.ts +195 -25
  128. package/packages/core/src/store/remote/errors.ts +16 -0
  129. package/packages/core/src/store/remote/index.ts +17 -0
  130. package/packages/core/src/store/remote/protocol.ts +30 -1
  131. package/packages/core/src/store/remote/released-clients.json +37 -0
  132. package/packages/core/src/store/remote/released-clients.ts +88 -0
  133. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  135. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  136. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  137. package/packages/core/src/store/remote/version.ts +8 -1
  138. package/packages/core/src/store/repo-state-events.ts +6 -3
  139. package/packages/core/src/store/scan-cadence.ts +15 -0
  140. package/packages/core/src/store/session-handle.ts +18 -0
  141. package/packages/core/src/store/snapshots.ts +16 -3
  142. package/packages/core/src/store/types.ts +29 -6
  143. package/packages/core/src/testing/dispatch-read-budget.ts +457 -7
  144. package/packages/core/src/testing/index.ts +6 -1
  145. package/packages/core/src/testing/reduced-read-budget.ts +1240 -9
  146. package/skills/guide/SKILL.md +220 -22
  147. package/skills/guide/references/accounts.md +50 -1
  148. package/skills/guide/references/integration-tree.md +24 -5
  149. package/skills/guide/references/operator-api.md +81 -10
  150. package/skills/guide/references/plugin-authoring.md +51 -2
  151. package/skills/guide/references/remote-store-protocol.md +321 -46
  152. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  153. package/skills/guide/references/restacking.md +105 -3
  154. package/skills/guide/references/setup.md +37 -8
  155. package/skills/guide/references/spec-standard.md +41 -5
  156. package/skills/guide/references/ticket-dependencies.md +8 -0
  157. package/skills/implement/SKILL.md +12 -3
  158. package/skills/operate/SKILL.md +85 -12
  159. package/skills/plan/SKILL.md +27 -4
  160. package/skills/plan-review/SKILL.md +22 -2
  161. package/skills/reconcile/SKILL.md +16 -1
  162. package/skills/spec/SKILL.md +7 -4
  163. package/skills/tickets/SKILL.md +7 -3
  164. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { ticketPreparationReducer } from './ticket-preparation'
1
2
  import { ticketMigrationsReducer } from './ticket-migrations'
2
3
  import { dispatchUpgradeReducer } from './dispatch-upgrade'
3
4
  import { forgeHealthReducer } from './forge-health'
@@ -21,6 +22,7 @@ import {
21
22
  } from './service-facts'
22
23
  import { phaseSchema } from '../ontology'
23
24
  import { z } from 'zod'
25
+ import { dispatchPlacementReducer } from './dispatch-placement'
24
26
  import type { ValueCatalogEntry } from '../store/reducer-values'
25
27
  import { dispatchFrontendReducer } from '../cli/dispatch-repository-feed'
26
28
  import { executionNoProgressReducer } from '../processes/execution-no-progress'
@@ -87,6 +89,7 @@ export interface RegisteredReducer {
87
89
  /** Parameterized reducers are registered with representative arguments; the
88
90
  * accumulator shape does not depend on them. */
89
91
  const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
92
+ ticketPreparation: { reducer: ticketPreparationReducer, covers: [] },
90
93
  ticketMigrations: { reducer: ticketMigrationsReducer, covers: [] },
91
94
  nodeRestack: { reducer: nodeRestackReducer, covers: ['advanceNodeRestack'] },
92
95
  leafRestack: { reducer: leafRestackReducer, covers: ['advanceLeafRestack'] },
@@ -189,6 +192,7 @@ const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
189
192
  autoMergeDefault: { reducer: autoMergeDefaultReducer, covers: ['latestAutoMergeDefault'] },
190
193
  pinnedAssets: { reducer: pinnedAssetsReducer, covers: ['findPinnedRevision'] },
191
194
  forgeHealthValue: { reducer: optionalValue(forgeHealthReducer), covers: [] },
195
+ dispatchPlacement: { reducer: dispatchPlacementReducer, covers: [] },
192
196
  }
193
197
 
194
198
  /** Qualification concerns the existing finished contract, including absence. */
@@ -215,6 +219,8 @@ const valueExclusions: Record<string, string> = {
215
219
  ),
216
220
  }
217
221
  const repositoryValues = new Set([
222
+ 'dispatchPlacement',
223
+ 'ticketPreparation',
218
224
  'ticketMigrations',
219
225
  'forgeHealthValue',
220
226
  'repositoryReadFacts',
@@ -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 = 25
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
+ }
@@ -0,0 +1,117 @@
1
+ import type { TargetLineage } from './target-lineage'
2
+ import type { BuildStore } from '../store/types'
3
+ import type { Forge } from '../ports/types'
4
+ import type { EventWrite } from '../events/catalog'
5
+ import { readBuildFacts } from '../store/reduced-reads'
6
+ import { gitOid } from '../events/payloads'
7
+
8
+ export function assertTargetOid(sha: string): void {
9
+ if (!gitOid.safeParse(sha).success) throw new Error('invalid target commit OID')
10
+ }
11
+
12
+ /** Admit only immutable forward destinations. CAS loss requires reclassification
13
+ * against the winning accepted observation, never a blind append. Reads consume
14
+ * reduced values only; idle polls read no event rows. */
15
+ export async function observeTarget(input: {
16
+ store: BuildStore
17
+ forge: Forge
18
+ slug: string
19
+ branch: string
20
+ sha: string
21
+ recordAccepted?: boolean
22
+ enforceUsedBaseline?: boolean
23
+ /** Supplied only by the repository-scoped dispatcher. */
24
+ proveRewrite?: (node: string, from: string) => Promise<TargetLineage | undefined>
25
+ actor: EventWrite['actor']
26
+ }): Promise<'moved' | 'unchanged' | 'rejected' | 'cleared'> {
27
+ const { store, forge, slug, branch, sha, actor } = input
28
+ assertTargetOid(sha)
29
+ for (;;) {
30
+ const facts = await readBuildFacts(store, slug)
31
+ const { state, log } = facts.value
32
+ const restack = log.restack
33
+ const node = state.nodeRestack
34
+ const accepted = restack.target?.branch === branch ? restack.target.sha : undefined
35
+ // Reparent acceptance establishes a new branch scope. Until its replay
36
+ // settles the old parent's contribution boundary is not a baseline here.
37
+ const reconcile = log.lastReconcileCompleted
38
+ const leafBase =
39
+ reconcile && reconcile.completedSeq > (restack.completedAt ?? 0)
40
+ ? reconcile.baseSha
41
+ : (restack.completed?.targetBase ?? restack.initialBase)
42
+ const used =
43
+ state.kind === 'node'
44
+ ? node?.parentChange && node.parentReplay !== node.parentChange.id
45
+ ? undefined
46
+ : node?.contributionBase
47
+ : leafBase
48
+ const baselines = [...new Set([accepted, used].filter((s): s is string => !!s))]
49
+ const rejected = restack.targetRewrite
50
+ if (accepted === sha && !rejected && !input.enforceUsedBaseline) return 'unchanged'
51
+ if (
52
+ !input.proveRewrite &&
53
+ rejected?.branch === branch &&
54
+ rejected.sha === sha &&
55
+ baselines.includes(rejected.previousSha)
56
+ )
57
+ return 'rejected'
58
+ let previousSha: string | undefined
59
+ const lineage: TargetLineage[] = []
60
+ for (const baseline of baselines) {
61
+ assertTargetOid(baseline)
62
+ if (baseline === sha) continue
63
+ if (!forge.isCommitAncestor) throw new Error('forge ancestry proof capability unavailable')
64
+ if (!(await forge.isCommitAncestor(baseline, sha))) {
65
+ // Scoped runners trust only the dispatcher-deposited proof for this
66
+ // exact accepted target, never read a parent's build or receipt index.
67
+ const prior =
68
+ restack.target?.branch === branch
69
+ ? restack.target.lineage?.find((proof) => proof.from === baseline)
70
+ : undefined
71
+ const recorded =
72
+ prior &&
73
+ (accepted === sha ||
74
+ (!input.proveRewrite && accepted && (await forge.isCommitAncestor(accepted, sha))))
75
+ ? prior
76
+ : undefined
77
+ const proof =
78
+ recorded ??
79
+ (state.target?.build && input.proveRewrite
80
+ ? await input.proveRewrite(state.target.build, baseline)
81
+ : undefined)
82
+ if (proof) {
83
+ lineage.push(proof)
84
+ continue
85
+ }
86
+ previousSha = baseline
87
+ break
88
+ }
89
+ }
90
+ if (
91
+ previousSha &&
92
+ rejected?.branch === branch &&
93
+ rejected.previousSha === previousSha &&
94
+ rejected.sha === sha
95
+ )
96
+ return 'rejected'
97
+ if (!previousSha && input.recordAccepted === false && !rejected) return 'unchanged'
98
+ const write: EventWrite | undefined = previousSha
99
+ ? { actor, type: 'target.rewritten', payload: { branch, previousSha, sha } }
100
+ : accepted !== sha
101
+ ? {
102
+ actor,
103
+ type: 'target.moved',
104
+ payload: { branch, sha, ...(lineage.length ? { lineage } : {}) },
105
+ }
106
+ : rejected
107
+ ? {
108
+ actor,
109
+ type: 'target.rewrite-cleared',
110
+ payload: { branch, sha, ...(lineage.length ? { lineage } : {}) },
111
+ }
112
+ : undefined
113
+ if (!write) return 'unchanged'
114
+ if (!(await store.appendIfCurrent(slug, facts.cursor, write))) continue
115
+ return previousSha ? 'rejected' : accepted === sha ? 'cleared' : 'moved'
116
+ }
117
+ }
@@ -0,0 +1,66 @@
1
+ import type { RepositoryEvent } from '../events/repository'
2
+ import type { TicketRef } from '../ontology'
3
+ import { defineReducer } from './incremental'
4
+
5
+ export interface TicketPreparation {
6
+ attempt: string
7
+ ticket: TicketRef
8
+ readyState: string
9
+ claimedState: string
10
+ claimed: boolean
11
+ slug?: string
12
+ handback?: string
13
+ stage?: string
14
+ error?: string
15
+ recoveryError?: string
16
+ retryAt?: string
17
+ }
18
+ /** Completed attempts leave no historical entries in the canonical value. */
19
+ export const ticketPreparationReducer = defineReducer<
20
+ Record<string, TicketPreparation>,
21
+ RepositoryEvent,
22
+ Record<string, TicketPreparation>
23
+ >({
24
+ version: 1,
25
+ initial: () => ({}),
26
+ fold(acc, events) {
27
+ for (const event of events) {
28
+ if (event.type === 'ticket-preparation.intended') {
29
+ acc[event.payload.attempt] = { ...event.payload, claimed: false }
30
+ continue
31
+ }
32
+ if (!event.type.startsWith('ticket-preparation.')) continue
33
+ if (!('attempt' in event.payload)) continue
34
+ const held = acc[event.payload.attempt]
35
+ if (!held) continue
36
+ switch (event.type) {
37
+ case 'ticket-preparation.claimed':
38
+ held.claimed = true
39
+ break
40
+ case 'ticket-preparation.creation-selected':
41
+ held.slug = event.payload.slug
42
+ break
43
+ case 'ticket-preparation.handback-selected':
44
+ held.handback = event.payload.state
45
+ break
46
+ case 'ticket-preparation.failed':
47
+ held.claimed = event.payload.claimed
48
+ held.error ??= event.payload.error
49
+ held.stage = event.payload.stage
50
+ held.handback = event.payload.handback
51
+ break
52
+ case 'ticket-preparation.recovery-failed':
53
+ held.claimed ||= event.payload.claimed ?? false
54
+ if (event.payload.handback) held.handback = event.payload.handback
55
+ if (event.payload.preparationError) held.error ??= event.payload.preparationError
56
+ held.recoveryError = event.payload.error
57
+ held.retryAt = event.payload.retryAt
58
+ break
59
+ case 'ticket-preparation.resolved':
60
+ delete acc[event.payload.attempt]
61
+ break
62
+ }
63
+ }
64
+ },
65
+ finish: (acc) => structuredClone(acc),
66
+ })
@@ -86,6 +86,12 @@ export const OPERATOR_TOOL_ANNOTATIONS = {
86
86
  idempotentHint: false,
87
87
  approval: 'default',
88
88
  },
89
+ 'repository.forge_clear': {
90
+ readOnlyHint: false,
91
+ destructiveHint: false,
92
+ idempotentHint: false,
93
+ approval: 'default',
94
+ },
89
95
  'repository.status': {
90
96
  readOnlyHint: true,
91
97
  destructiveHint: false,
@@ -134,3 +134,23 @@ export async function controlHarvestRun(opts: {
134
134
  })
135
135
  return { action: projected.action, event }
136
136
  }
137
+
138
+ /** Explicit operator override. No history lookup or provider-success claim. */
139
+ export async function clearForgeDegradation(opts: {
140
+ store: BuildStore
141
+ repo: string
142
+ user: string
143
+ via?: Via
144
+ forge: string
145
+ reason: string
146
+ }): Promise<{ event: RepositoryEventEnvelope }> {
147
+ const forge = opts.forge.trim()
148
+ const reason = opts.reason.trim()
149
+ if (!forge || !reason || !opts.user.trim()) throw new Error('forge, reason and user are required')
150
+ const event = await opts.store.appendRepo(opts.repo, {
151
+ actor: humanActor(opts.user, opts.via),
152
+ type: 'dispatcher.forge-recovered',
153
+ payload: { forge, reason },
154
+ })
155
+ return { event }
156
+ }
@@ -141,3 +141,5 @@ export { listOperatorLandings } from './landings'
141
141
  export { readTicketTree, getOperatorTicketTree } from './tickets'
142
142
 
143
143
  export { requestNodeRestack } from './restack'
144
+
145
+ export { clearForgeDegradation } from './control'
@@ -1,3 +1,4 @@
1
+ import { readBuildPage } from '../store/event-reads'
1
2
  import { requestNodeRestack } from './restack'
2
3
  import { listOperatorLandings } from './landings'
3
4
  import { getOperatorTicketTree } from './tickets'
@@ -36,6 +37,7 @@ import { systemClock, type BuildStore, type Clock } from '../store/types'
36
37
  import { TicketOperationError } from '../ports/tickets/operations'
37
38
  import { OPERATOR_NOTES_REPO_KIND } from '../store/retention'
38
39
  import {
40
+ clearForgeDegradation,
39
41
  OperatorControlError,
40
42
  setRepositorySetting,
41
43
  toggleHarvestGate,
@@ -236,8 +238,9 @@ const buildEventsInput = z.strictObject({
236
238
  .number()
237
239
  .int()
238
240
  .min(0)
241
+ .safe()
239
242
  .describe(
240
- 'Event sequence cursor: return build events with seq strictly greater than this (0 = the whole log).',
243
+ 'Event sequence cursor: return build events with seq strictly greater than this (0 = the first page).',
241
244
  ),
242
245
  waitSeconds: z
243
246
  .number()
@@ -550,21 +553,11 @@ export const TOOLS: readonly ToolEntry[] = [
550
553
  'builds.events',
551
554
  'Read one build’s event log after a cursor, optionally waiting (bounded, ≤30s) for new events — the polling companion to builds.get.',
552
555
  buildEventsInput,
553
- '{events, cursor}: the new events in sequence order (each with seq, ts, actor, type, payload) and the cursor to pass next time — the last returned event’s seq, or the requested cursor when the page is empty.',
556
+ '{events, cursor, hasMore}: at most 256 new events in sequence order (each with seq, ts, actor, type, payload) and the cursor to pass next time — the last returned event’s seq, or the requested cursor when the page is empty.',
554
557
  async (raw, ctx) => {
555
558
  const input = raw as z.infer<typeof buildEventsInput>
556
559
  await requireRouteBuild(ctx.store, input.repo, input.slug)
557
- let events = await ctx.store.getEvents(input.slug, input.cursor)
558
- if (events.length === 0 && input.waitSeconds > 0) {
559
- // The store interface offers subscribe but no bounded wait; polling
560
- // keeps the handler finite. The schema caps waitSeconds at 30.
561
- const deadline = Date.now() + input.waitSeconds * 1000
562
- while (events.length === 0 && Date.now() < deadline) {
563
- await new Promise((resolve) => setTimeout(resolve, 500))
564
- events = await ctx.store.getEvents(input.slug, input.cursor)
565
- }
566
- }
567
- return { events, cursor: events.length > 0 ? events.at(-1)!.seq : input.cursor }
560
+ return readBuildPage(ctx.store, input.slug, input.cursor, { waitSeconds: input.waitSeconds })
568
561
  },
569
562
  ),
570
563
  defineTool(
@@ -678,6 +671,25 @@ export const TOOLS: readonly ToolEntry[] = [
678
671
  })
679
672
  },
680
673
  ),
674
+ defineTool(
675
+ 'repository.forge_clear',
676
+ 'Explicitly clear erroneous forge cooldown state with an audited reason; does not prove provider recovery.',
677
+ z.strictObject({
678
+ repo: z.string().min(1).describe('Exact repository identity.'),
679
+ forge: z.string().trim().min(1).describe('Forge adapter name.'),
680
+ reason: z.string().trim().min(1).describe('Reason for the operator override.'),
681
+ }),
682
+ '{event}: the durable human-attributed recovery fact.',
683
+ async (raw, ctx) => {
684
+ const input = raw as { repo: string; forge: string; reason: string }
685
+ return clearForgeDegradation({
686
+ ...input,
687
+ store: ctx.store,
688
+ user: attributed(ctx),
689
+ ...(ctx.via !== undefined ? { via: ctx.via } : {}),
690
+ })
691
+ },
692
+ ),
681
693
  defineTool(
682
694
  'repository.status',
683
695
  'Report one repository’s durable dispatcher settings and journal state.',
@@ -163,9 +163,15 @@ async function matchingBuild(
163
163
  }
164
164
  const matches = normalized.filter(({ ref }) => ref.id === id).map(({ record }) => record)
165
165
  if (!matches.length && source.name === 'hosted') {
166
+ // Readable refs already identify tickets; only legacy local-store refs need aliases.
167
+ const aliases = new Map<string, string | null>()
166
168
  try {
167
- for (const { record, ref } of normalized)
168
- if ((await source.get(ref.id))?.ref.id === id) matches.push(record)
169
+ for (const { record, ref } of normalized) {
170
+ if (!/^ticket-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(ref.id))
171
+ continue
172
+ if (!aliases.has(ref.id)) aliases.set(ref.id, (await source.get(ref.id))?.ref.id ?? null)
173
+ if (aliases.get(ref.id) === id) matches.push(record)
174
+ }
169
175
  } catch {
170
176
  /* optional alias association must not undo a successful mutation */
171
177
  }