@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
@@ -8,8 +8,18 @@ type Shape = {
8
8
  props?: Record<string, { type: string; optional: boolean }>
9
9
  index?: string
10
10
  }
11
+ export const REDUCER_VALUE_CONTRACT_IDENTITY = new Bun.CryptoHasher('sha256')
12
+ .update(JSON.stringify(shapes))
13
+ .digest('hex')
11
14
  const schemas: Record<string, Shape> = shapes.schemas
12
15
 
16
+ /** A finished-value shape catalog: this build's generated one, or a frozen
17
+ * catalog from a published release line. */
18
+ export interface ReducerValueCatalog {
19
+ roots: Record<string, { value: string }>
20
+ schemas: Record<string, Shape>
21
+ }
22
+
13
23
  /** Generated structural shapes include nested event payload unions, records,
14
24
  * optional fields and literal discriminants. No accumulator is trusted merely
15
25
  * because finish() happens to accept it. */
@@ -37,8 +47,8 @@ function json(value: unknown, seen = new Set<object>()): boolean {
37
47
  Object.values(value).every((item) => json(item, new Set(seen)))
38
48
  )
39
49
  }
40
- function matches(id: string, value: unknown): boolean {
41
- const shape = schemas[id]!
50
+ function matches(id: string, value: unknown, table = schemas): boolean {
51
+ const shape = table[id]!
42
52
  switch (shape.kind) {
43
53
  case 'json':
44
54
  return json(value)
@@ -53,9 +63,11 @@ function matches(id: string, value: unknown): boolean {
53
63
  case 'boolean':
54
64
  return typeof value === 'boolean'
55
65
  case 'union':
56
- return (shape.items as string[]).some((item) => matches(item, value))
66
+ return (shape.items as string[]).some((item) => matches(item, value, table))
57
67
  case 'array':
58
- return Array.isArray(value) && value.every((item) => matches(shape.items as string, item))
68
+ return (
69
+ Array.isArray(value) && value.every((item) => matches(shape.items as string, item, table))
70
+ )
59
71
  case 'object': {
60
72
  if (
61
73
  value === null ||
@@ -67,12 +79,12 @@ function matches(id: string, value: unknown): boolean {
67
79
  const record = value as Record<string, unknown>
68
80
  for (const [key, prop] of Object.entries(shape.props!)) {
69
81
  if (!(key in record) && prop.optional) continue
70
- if (!matches(prop.type, record[key])) return false
82
+ if (!matches(prop.type, record[key], table)) return false
71
83
  }
72
84
  return Object.keys(record).every(
73
85
  (key) =>
74
86
  Object.hasOwn(shape.props!, key) ||
75
- (shape.index !== undefined && matches(shape.index, record[key])),
87
+ (shape.index !== undefined && matches(shape.index, record[key], table)),
76
88
  )
77
89
  }
78
90
  default:
@@ -174,6 +186,97 @@ function diagnose(id: string, value: unknown, path: string, depth: number): Diag
174
186
  return failure
175
187
  }
176
188
 
189
+ type Projected = { value: unknown; dropped: number }
190
+ type Unprojectable = Diagnostic
191
+ type Projection = Projected | Unprojectable
192
+ // Plugin consumers may compile without strict narrowing; `in` guards narrow everywhere.
193
+ const failed = (result: Projection): result is Unprojectable => 'path' in result
194
+
195
+ /** Project a value onto a catalog's shape, dropping object properties the shape
196
+ * does not know. Additive server fields then reach older readers as the value
197
+ * they were built for, while a missing field or unknown variant still fails.
198
+ * Among union members, the one dropping the fewest properties wins. */
199
+ function project(
200
+ table: Record<string, Shape>,
201
+ id: string,
202
+ value: unknown,
203
+ path: string,
204
+ depth: number,
205
+ ): Projection {
206
+ if (matches(id, value, table)) return { value, dropped: 0 }
207
+ const shape = table[id]!
208
+ const failure: Unprojectable = {
209
+ path,
210
+ depth,
211
+ expected: shape.kind === 'literal' ? JSON.stringify(shape.value) : shape.kind,
212
+ }
213
+ if (shape.kind === 'union') {
214
+ let best: Projection | undefined
215
+ for (const item of shape.items as string[]) {
216
+ const next = project(table, item, value, path, depth)
217
+ if (!failed(next)) {
218
+ if (!best || failed(best) || next.dropped < best.dropped) best = next
219
+ } else if (!best || (failed(best) && next.depth > best.depth)) best = next
220
+ }
221
+ return best ?? failure
222
+ }
223
+ if (shape.kind === 'array' && Array.isArray(value)) {
224
+ const items: unknown[] = []
225
+ let dropped = 0
226
+ for (let i = 0; i < value.length; i++) {
227
+ const next = project(table, shape.items as string, value[i], `${path}[${i}]`, depth + 1)
228
+ if (failed(next)) return next
229
+ items.push(next.value)
230
+ dropped += next.dropped
231
+ }
232
+ return { value: items, dropped }
233
+ }
234
+ if (
235
+ shape.kind === 'object' &&
236
+ value !== null &&
237
+ typeof value === 'object' &&
238
+ Object.getPrototypeOf(value) === Object.prototype
239
+ ) {
240
+ const record = value as Record<string, unknown>
241
+ const out: Record<string, unknown> = {}
242
+ let dropped = 0
243
+ for (const [key, prop] of Object.entries(shape.props!)) {
244
+ if (!(key in record) && prop.optional) continue
245
+ const next = project(table, prop.type, record[key], property(path, key), depth + 1)
246
+ if (failed(next)) return next
247
+ if (key in record) out[key] = next.value
248
+ dropped += next.dropped
249
+ }
250
+ for (const key of Object.keys(record).sort()) {
251
+ if (Object.hasOwn(shape.props!, key)) continue
252
+ if (!shape.index) {
253
+ dropped += 1
254
+ continue
255
+ }
256
+ const next = project(table, shape.index, record[key], property(path, key), depth + 1)
257
+ if (failed(next)) return next
258
+ out[key] = next.value
259
+ dropped += next.dropped
260
+ }
261
+ return { value: out, dropped }
262
+ }
263
+ return failure
264
+ }
265
+
266
+ /** The reader-side contract for a server's canonical answer: the value as this
267
+ * reader's shape can represent it, or a structural diagnostic. Reducer versions
268
+ * are cache identities, not compatibility gates. */
269
+ export function projectReducerValue(
270
+ name: string,
271
+ value: unknown,
272
+ catalog: ReducerValueCatalog = shapes,
273
+ ): { value: unknown } | ValidationFailure {
274
+ const root = Object.hasOwn(catalog.roots, name) ? catalog.roots[name] : undefined
275
+ if (!root) return { path: '$', expected: 'known reducer' }
276
+ const result = project(catalog.schemas, root.value, value, '$', 0)
277
+ return failed(result) ? { path: result.path, expected: result.expected } : { value: result.value }
278
+ }
279
+
177
280
  /** Existing optional object fields keep their ordinary JSON omission semantics.
178
281
  * Collections, functions, nonfinite numbers and undefined array entries cannot
179
282
  * silently become a different public contract during JSON serialization. */
@@ -1,3 +1,4 @@
1
+ import { CheckpointIntegrityError, REPOSITORY_TAIL_WINDOW } from './event-reads'
1
2
  import { READ_CATALOG_IDENTITY, projectStoredEvents } from '../events/compatibility'
2
3
  /** Named JSON answers over persisted incremental state. The event log remains authoritative. */
3
4
  import { z } from 'zod'
@@ -89,6 +90,11 @@ export interface ValueCacheRow {
89
90
  token: string
90
91
  }
91
92
  export interface ReducerValueStorage {
93
+ checkpoints?: {
94
+ publish(key: string, snapshot: ReducerSnapshot, checkpoints: ReducerSnapshot[]): Promise<void>
95
+ coverage(key: string, cursor: number): Promise<boolean>
96
+ latest(key: string, through: number): Promise<ReducerSnapshot | null>
97
+ }
92
98
  highWater(): Promise<number>
93
99
  read(key: string): Promise<ValueCacheRow | null>
94
100
  events(since: number, through: number): Promise<(AbEvent | RepositoryEvent)[]>
@@ -107,6 +113,7 @@ export async function readReducerValue(
107
113
  try {
108
114
  row = await storage.read(key)
109
115
  } catch {
116
+ if (storage.checkpoints) throw new CheckpointIntegrityError('unreadable canonical stream seed')
110
117
  /* unreadable cache is a miss */
111
118
  }
112
119
  // A concurrent reader may have persisted beyond our first boundary. Only a
@@ -136,16 +143,69 @@ export async function readReducerValue(
136
143
  cursor = snapshot.cursor
137
144
  }
138
145
  }
146
+ if (storage.checkpoints && row && !valid)
147
+ throw new CheckpointIntegrityError('corrupt canonical stream seed')
148
+ let recovering = false
149
+ if (storage.checkpoints && valid && !(await storage.checkpoints.coverage(key, cursor))) {
150
+ // A pre-checkpoint server may advance the shared canonical row during a
151
+ // rolling deploy or rollback. Its accumulator cannot supply the missing
152
+ // intermediate seeds. Refold only the uncovered suffix under the seed lock.
153
+ const checkpoint = await storage.checkpoints.latest(key, cursor)
154
+ if (checkpoint) {
155
+ const state = checkpoint.state as { identity?: unknown; acc?: unknown } | null
156
+ if (
157
+ checkpoint.version !== reducer.version ||
158
+ !Number.isSafeInteger(checkpoint.cursor) ||
159
+ checkpoint.cursor < 0 ||
160
+ checkpoint.cursor > cursor ||
161
+ state?.identity !== identity ||
162
+ !entry.validate(state.acc)
163
+ )
164
+ throw new CheckpointIntegrityError('corrupt recovery stream-seed checkpoint')
165
+ acc = structuredClone(state.acc)
166
+ cursor = checkpoint.cursor
167
+ } else {
168
+ // Initial legacy adoption with no checkpoint to resume from.
169
+ acc = reducer.initial()
170
+ cursor = 0
171
+ }
172
+ recovering = true
173
+ }
174
+ const start = cursor
139
175
  const delta = (await storage.events(cursor, boundary)).filter((event) => event.seq <= boundary)
140
176
  for (const event of delta) {
141
177
  if (event.seq !== cursor + 1) throw new Error('noncontiguous reducer log')
142
178
  cursor = event.seq
143
179
  }
144
180
  if (cursor !== boundary) throw new Error('incomplete reducer log')
145
- acc = reducer.advance(acc, entry.adapt(projectStoredEvents(delta)))
181
+ const checkpoints: ReducerSnapshot[] = []
182
+ if (storage.checkpoints) {
183
+ const oldest = Math.max(0, boundary - REPOSITORY_TAIL_WINDOW)
184
+ const prefix = delta.filter((event) => event.seq <= oldest)
185
+ acc = reducer.advance(acc, entry.adapt(projectStoredEvents(prefix)))
186
+ if (start <= oldest)
187
+ checkpoints.push({
188
+ version: reducer.version,
189
+ cursor: oldest,
190
+ state: { identity, acc: structuredClone(acc) },
191
+ })
192
+ for (const event of delta) {
193
+ if (event.seq <= oldest) continue
194
+ acc = reducer.advance(acc, entry.adapt(projectStoredEvents([event])))
195
+ checkpoints.push({
196
+ version: reducer.version,
197
+ cursor: event.seq,
198
+ state: { identity, acc: structuredClone(acc) },
199
+ })
200
+ }
201
+ } else acc = reducer.advance(acc, entry.adapt(projectStoredEvents(delta)))
146
202
  const value = entry.value(reducer.finish(acc))
147
- if (!valid || delta.length > 0) {
203
+ if (!valid || recovering || delta.length > 0) {
148
204
  const next = { version: reducer.version, cursor, state: { identity, acc } }
205
+ if (storage.checkpoints) {
206
+ await storage.checkpoints.publish(key, next, checkpoints)
207
+ return { version: reducer.version, cursor, value, catalogIdentity: READ_CATALOG_IDENTITY }
208
+ }
149
209
  try {
150
210
  if (row && !valid && row.snapshot.version === reducer.version)
151
211
  await storage.repair(key, row, next)
@@ -1,3 +1,23 @@
1
+ import { StoreWriteTooLargeError } from './errors'
2
+ import {
3
+ DISPATCH_PLACEMENT_CAPABILITY,
4
+ placementCapabilitiesSchema,
5
+ dispatchPlacementSchema,
6
+ } from './protocol'
7
+ import type { DispatchPlacement } from '../../kernel/dispatch-placement'
8
+ import { scanCadenceSchema, type ScanCadence } from '../scan-cadence'
9
+ import { nodeRewriteWireSchema } from './protocol'
10
+ import { z } from 'zod'
11
+ import {
12
+ CursorTooOldError,
13
+ CheckpointIntegrityError,
14
+ RetiredSeedGenerationError,
15
+ IncompleteEventReadError,
16
+ validateEventCursor,
17
+ type EventReadOptions,
18
+ type EventPage,
19
+ } from '../event-reads'
20
+ import { ArtifactMetaUnsupportedError } from '../artifact-meta'
1
21
  import {
2
22
  operatorPresenceBodySchema,
3
23
  operatorPresenceWireSchema,
@@ -16,9 +36,10 @@ import {
16
36
  supportedClientRangeSchema,
17
37
  } from './compatibility'
18
38
  import { stampCompatibility, buildEventPolicy, repositoryEventPolicy } from '../../events/policy'
39
+ import { REDUCER_VALUE_CONTRACT_IDENTITY } from '../reducer-value-validation'
19
40
  import { READ_CATALOG_IDENTITY } from '../../events/compatibility'
20
- import { CATALOG_IDENTITY_HEADER } from './version'
21
- import { diagnoseReducerValue } from '../reducer-value-validation'
41
+ import { CATALOG_IDENTITY_HEADER, REDUCER_VALUE_PROJECTION_HEADER } from './version'
42
+ import { diagnoseReducerValue, projectReducerValue } from '../reducer-value-validation'
22
43
  import { prepareEventWrite as validateEventWrite } from '../../events/catalog'
23
44
  import { prepareRepositoryEventWrite as validateRepositoryEventWrite } from '../../events/repository'
24
45
  import {
@@ -211,6 +232,24 @@ export class RemoteBuildStore implements BuildStore {
211
232
  }
212
233
  }
213
234
 
235
+ private placementCapability: Promise<boolean> | undefined
236
+
237
+ async getDispatchPlacement(repo: string): Promise<DispatchPlacement> {
238
+ this.placementCapability ??= (async () => {
239
+ const response = await this.raw('GET', '/health')
240
+ if (response.status === 404 || response.status === 405) return false
241
+ if (!response.ok) throw await this.toError(response)
242
+ const health = placementCapabilitiesSchema.parse(await response.json())
243
+ return health.capabilities?.includes(DISPATCH_PLACEMENT_CAPABILITY) ?? false
244
+ })().catch((error) => {
245
+ this.placementCapability = undefined
246
+ throw error
247
+ })
248
+ if (!(await this.placementCapability))
249
+ return { status: 'unknown', reason: 'unsupported-capability' }
250
+ return this.requestJson('GET', `${this.repoPath(repo)}/placement`, dispatchPlacementSchema)
251
+ }
252
+
214
253
  async inspectDispatcherOverlap(signal: AbortSignal) {
215
254
  const response = await this.raw('GET', '/health', undefined, signal)
216
255
  if (response.status === 404 || response.status === 405)
@@ -273,32 +312,53 @@ export class RemoteBuildStore implements BuildStore {
273
312
  path: string,
274
313
  body?: unknown,
275
314
  signal?: AbortSignal,
315
+ capabilities: Record<string, string> = {},
276
316
  ): Promise<Response> {
277
317
  const headers: Record<string, string> = {
318
+ ...capabilities,
278
319
  [AUTOBUILD_VERSION_HEADER]: this.identity.autobuildVersion,
279
320
  [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: this.identity.protocolVersion,
280
321
  }
281
322
  if (this.token !== undefined) headers.authorization = `Bearer ${this.token}`
282
323
  if (body !== undefined) headers['content-type'] = 'application/json'
283
- return this.fetchFn(`${this.base}${path}`, {
324
+ const serialized =
325
+ body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body)
326
+ const response = await this.fetchFn(`${this.base}${path}`, {
284
327
  method,
285
328
  headers,
286
329
  // A string body is already serialized JSON (the ticket-asset put sizes
287
330
  // its exact bytes before sending).
288
- ...(body !== undefined
289
- ? { body: typeof body === 'string' ? body : JSON.stringify(body) }
290
- : {}),
331
+ ...(serialized !== undefined ? { body: serialized } : {}),
291
332
  ...(signal !== undefined ? { signal } : {}),
292
333
  })
334
+ if (method !== 'GET' && response.status === 413)
335
+ throw await this.toError(response, {
336
+ method,
337
+ route: path,
338
+ requestBytes: Buffer.byteLength(serialized ?? '', 'utf8'),
339
+ })
340
+ return response
293
341
  }
294
342
 
295
- private async toError(response: Response): Promise<Error> {
296
- let body: { error: string; kind: string } | undefined
343
+ private async toError(
344
+ response: Response,
345
+ request?: { method: string; route: string; requestBytes: number },
346
+ ): Promise<Error> {
347
+ let body: import('./protocol').ErrorBody | undefined
297
348
  try {
298
349
  body = errorBodySchema.parse(await response.json())
299
350
  } catch {
300
351
  // Not a protocol error body — fall back to the status line.
301
352
  }
353
+ if (
354
+ body?.kind === 'cursor-too-old' &&
355
+ body.scope &&
356
+ body.requestedCursor !== undefined &&
357
+ body.head !== undefined
358
+ )
359
+ return new CursorTooOldError(body.scope, body.requestedCursor, body.head)
360
+ if (body?.kind === 'checkpoint-integrity') return new CheckpointIntegrityError(body.error)
361
+ if (body?.kind === 'retired-seed-generation') return new RetiredSeedGenerationError()
302
362
  const message = body?.error ?? `store server responded ${response.status}`
303
363
  if (response.status === 401 || response.status === 403) {
304
364
  return new AuthError(message)
@@ -311,13 +371,21 @@ export class RemoteBuildStore implements BuildStore {
311
371
  ) {
312
372
  return new TicketAssetValidationError(message)
313
373
  }
314
- if (response.status === 422) return new EventValidationError(message)
374
+ if (response.status === 422 || (response.status === 400 && body?.kind === 'validation'))
375
+ return new EventValidationError(message)
315
376
  // Typed stream rejections rehydrate by the server's message shape: the
316
377
  // ceiling names its bytes, the closed-append names its stream (a 409 is
317
378
  // otherwise the generic already-exists conflict).
318
379
  if (response.status === 413 && message.startsWith('stream batch of ')) {
319
380
  return new StreamBatchTooLargeError(undefined, undefined, message)
320
381
  }
382
+ if (response.status === 413 && request !== undefined)
383
+ return new StoreWriteTooLargeError(
384
+ request.method,
385
+ request.route,
386
+ request.requestBytes,
387
+ body?.error,
388
+ )
321
389
  if (response.status === 409 && /^stream ".+" is closed$/.test(message)) {
322
390
  return new StreamClosedError(message)
323
391
  }
@@ -517,24 +585,39 @@ export class RemoteBuildStore implements BuildStore {
517
585
  }
518
586
  }
519
587
 
520
- async getEvents(
588
+ async getEvents(slug: string, sinceSeq = 0, opts?: EventReadOptions): Promise<AbEvent[]> {
589
+ const page = await this.getBuildEventPage(slug, sinceSeq, opts)
590
+ if (page.hasMore) throw new IncompleteEventReadError(sinceSeq, page.cursor)
591
+ return page.events
592
+ }
593
+
594
+ async getBuildEventPage(
521
595
  slug: string,
522
- sinceSeq = 0,
523
- opts?: { waitSeconds?: number; signal?: AbortSignal },
524
- ): Promise<AbEvent[]> {
525
- const params = new URLSearchParams({ since: String(sinceSeq) })
596
+ since = 0,
597
+ opts?: EventReadOptions,
598
+ ): Promise<EventPage<AbEvent>> {
599
+ validateEventCursor(since)
600
+ const params = new URLSearchParams({ since: String(since) })
601
+ if (opts?.through !== undefined) {
602
+ validateEventCursor(opts.through)
603
+ params.set('through', String(opts.through))
604
+ }
526
605
  if (opts?.waitSeconds !== undefined) params.set('wait', String(opts.waitSeconds))
527
606
  return this.heldRequest(
528
607
  opts?.signal,
529
- (): AbEvent[] => [],
608
+ (): EventPage<AbEvent> => ({ events: [], cursor: since, hasMore: false }),
530
609
  () =>
531
610
  this.requestJson(
532
611
  'GET',
533
612
  `${this.buildPath(slug)}/events?${params}`,
534
- eventListSchema,
613
+ z.object({
614
+ events: eventListSchema,
615
+ cursor: z.number().int().nonnegative().safe(),
616
+ hasMore: z.boolean(),
617
+ }),
535
618
  undefined,
536
619
  opts?.signal,
537
- ) as Promise<AbEvent[]>,
620
+ ) as Promise<EventPage<AbEvent>>,
538
621
  )
539
622
  }
540
623
 
@@ -558,6 +641,46 @@ export class RemoteBuildStore implements BuildStore {
558
641
  return { meta: result.meta, content: decodeBase64(result.contentBase64) }
559
642
  }
560
643
 
644
+ private artifactMetaUnsupported = false
645
+
646
+ async getNodeRewrite(slug: string, previous?: string, beforePrevious?: string) {
647
+ return this.requestJson(
648
+ 'GET',
649
+ `${this.buildPath(slug)}/node-rewrite?${new URLSearchParams({ ...(previous === undefined ? {} : { previous }), ...(beforePrevious === undefined ? {} : { beforePrevious }) })}`,
650
+ nodeRewriteWireSchema,
651
+ )
652
+ }
653
+
654
+ async getLatestArtifactMeta(slug: string, kind: string): Promise<ArtifactMeta | null> {
655
+ if (this.artifactMetaUnsupported) throw new ArtifactMetaUnsupportedError()
656
+ const response = await this.raw(
657
+ 'GET',
658
+ `${this.buildPath(slug)}/artifact-meta?${new URLSearchParams({ kind })}`,
659
+ )
660
+ if (!response.ok) {
661
+ const body = errorBodySchema.safeParse(
662
+ await response
663
+ .clone()
664
+ .json()
665
+ .catch(() => null),
666
+ )
667
+ if (
668
+ body.success &&
669
+ ((response.status === 501 && body.data.kind === 'unsupported-operation') ||
670
+ (response.status === 404 &&
671
+ body.data.kind === 'not-found' &&
672
+ (body.data.error === 'no route: GET /builds/:slug/artifact-meta' ||
673
+ body.data.error ===
674
+ `no route: GET ${new URL(`${this.base}${this.buildPath(slug)}/artifact-meta`).pathname}`)))
675
+ ) {
676
+ this.artifactMetaUnsupported = true
677
+ throw new ArtifactMetaUnsupportedError()
678
+ }
679
+ throw await this.toError(response)
680
+ }
681
+ return artifactMetaWireSchema.nullable().parse(await response.json())
682
+ }
683
+
561
684
  async listArtifacts(slug: string, kind?: string): Promise<ArtifactMeta[]> {
562
685
  const query = kind !== undefined ? `?kind=${encodeURIComponent(kind)}` : ''
563
686
  return this.requestJson(
@@ -624,6 +747,24 @@ export class RemoteBuildStore implements BuildStore {
624
747
  })
625
748
  }
626
749
 
750
+ async getScanCadence(repo: string): Promise<ScanCadence | null> {
751
+ return this.requestJson(
752
+ 'GET',
753
+ `${this.repoPath(repo)}/scan-cadence`,
754
+ scanCadenceSchema.nullable(),
755
+ )
756
+ }
757
+ async putScanCadence(
758
+ repo: string,
759
+ cadence: ScanCadence,
760
+ allowClockRollback = false,
761
+ ): Promise<void> {
762
+ await this.requestJson('POST', `${this.repoPath(repo)}/scan-cadence`, okResponseSchema, {
763
+ cadence: scanCadenceSchema.parse(cadence),
764
+ allowClockRollback,
765
+ })
766
+ }
767
+
627
768
  async upsertOperatorPresence(
628
769
  repo: string,
629
770
  identity: OperatorIdentity,
@@ -754,10 +895,52 @@ export class RemoteBuildStore implements BuildStore {
754
895
  )
755
896
  }
756
897
 
898
+ async getStreamSeed(scope: SnapshotScope, cursor: number): Promise<ReducerValue> {
899
+ validateEventCursor(cursor)
900
+ const root = scope.kind === 'build' ? this.buildPath(scope.slug) : this.repoPath(scope.repo)
901
+ const value = await this.requestJson(
902
+ 'GET',
903
+ `${root}/stream-seed?cursor=${cursor}`,
904
+ reducerValueSchema,
905
+ )
906
+ const request = { reducer: scope.kind === 'build' ? 'buildStreamSeed' : 'repositoryAttention' }
907
+ const { reducer } = resolveReducerValue(scope, request)
908
+ if (value.version !== reducer.version || diagnoseReducerValue(request.reducer, value.value))
909
+ throw new ReducerValueIncompatibilityError(
910
+ request.reducer,
911
+ scope,
912
+ reducer.version,
913
+ value.version,
914
+ 'invalid historical seed',
915
+ )
916
+ return value as ReducerValue
917
+ }
918
+ getRepositoryTail(repo: string, since = 0, opts?: EventReadOptions): Promise<RepositoryEvent[]> {
919
+ return this.getRepoEvents(repo, since, opts)
920
+ }
921
+ getHarvestHistoryPage(
922
+ repo: string,
923
+ before = Number.MAX_SAFE_INTEGER,
924
+ ): Promise<EventPage<RepositoryEvent>> {
925
+ validateEventCursor(before)
926
+ return this.requestJson(
927
+ 'GET',
928
+ `${this.repoPath(repo)}/harvest-history?before=${before}`,
929
+ z.object({
930
+ events: repositoryEventListSchema,
931
+ cursor: z.number().int().nonnegative().safe(),
932
+ hasMore: z.boolean(),
933
+ }),
934
+ ) as Promise<EventPage<RepositoryEvent>>
935
+ }
936
+
757
937
  async getReducerValue(scope: SnapshotScope, request: ReducerValueRequest): Promise<ReducerValue> {
758
938
  const { reducer } = resolveReducerValue(scope, request)
759
939
  const root = scope.kind === 'build' ? this.buildPath(scope.slug) : this.repoPath(scope.repo)
760
- const response = await this.raw('POST', `${root}/reducer-values`, request)
940
+ const response = await this.raw('POST', `${root}/reducer-values`, request, undefined, {
941
+ [REDUCER_VALUE_PROJECTION_HEADER]: '1',
942
+ [CATALOG_IDENTITY_HEADER]: REDUCER_VALUE_CONTRACT_IDENTITY,
943
+ })
761
944
  if (!response.ok) throw await this.toError(response)
762
945
  let body: unknown
763
946
  try {
@@ -788,14 +971,16 @@ export class RemoteBuildStore implements BuildStore {
788
971
  }
789
972
  if (!parsed.success) fail(`invalid reducer envelope: ${parsed.error.message}`)
790
973
  const result = parsed.data!
791
- if (result.version !== reducer.version) fail('reducer version mismatch')
792
- const failure = diagnoseReducerValue(request.reducer, result.value)
793
- if (failure) fail(`invalid finished value at ${failure.path}: expected ${failure.expected}`)
974
+ // The shape this reader can represent is the contract. A different reducer
975
+ // version is the server's cache identity, so release lines may skew freely.
976
+ const projected = projectReducerValue(request.reducer, result.value)
977
+ if ('path' in projected)
978
+ fail(`invalid finished value at ${projected.path}: expected ${projected.expected}`)
794
979
  const identity = response.headers.get(CATALOG_IDENTITY_HEADER)
795
980
  return {
796
981
  version: result.version,
797
982
  cursor: result.cursor,
798
- value: result.value as ReducerValue['value'],
983
+ value: (projected as { value: unknown }).value as ReducerValue['value'],
799
984
  ...(identity === null ? {} : { catalogIdentity: identity }),
800
985
  }
801
986
  }
@@ -1299,7 +1484,7 @@ export class RemoteBuildStore implements BuildStore {
1299
1484
  // answers immediately and the cadence degrades to the old request rate.
1300
1485
  const { waitSeconds = REMOTE_EVENT_WAIT_SECONDS, ...rest } = opts
1301
1486
  return pollingSubscribe(
1302
- (since, pollOpts) => this.getEvents(slug, since, pollOpts),
1487
+ async (since, pollOpts) => (await this.getBuildEventPage(slug, since, pollOpts)).events,
1303
1488
  { ...rest, waitSeconds: waitSeconds > 0 ? waitSeconds : undefined },
1304
1489
  onEvent,
1305
1490
  )