@defrex/autobuild 1.3.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 (142) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +302 -26
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +187 -19
  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 +258 -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 +178 -52
  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/fake.ts +4 -0
  85. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  86. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  87. package/packages/core/src/processes/build-runner.ts +240 -111
  88. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  89. package/packages/core/src/processes/dispatcher.ts +262 -80
  90. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  91. package/packages/core/src/processes/harvest-runner.ts +6 -7
  92. package/packages/core/src/processes/publication-state.ts +2 -1
  93. package/packages/core/src/processes/repo-view.ts +22 -0
  94. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  95. package/packages/core/src/scenarios/harness.ts +7 -0
  96. package/packages/core/src/store/adapter.ts +9 -0
  97. package/packages/core/src/store/build-scope.ts +28 -0
  98. package/packages/core/src/store/contract.ts +125 -0
  99. package/packages/core/src/store/event-reads.ts +156 -0
  100. package/packages/core/src/store/local/schema.ts +11 -0
  101. package/packages/core/src/store/local/store.ts +117 -2
  102. package/packages/core/src/store/memory.ts +237 -0
  103. package/packages/core/src/store/phase-session.ts +47 -0
  104. package/packages/core/src/store/reduced-reads.ts +8 -0
  105. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  106. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  107. package/packages/core/src/store/reducer-values.ts +62 -2
  108. package/packages/core/src/store/remote/client.ts +161 -16
  109. package/packages/core/src/store/remote/compatibility.ts +177 -46
  110. package/packages/core/src/store/remote/errors.ts +16 -0
  111. package/packages/core/src/store/remote/index.ts +11 -0
  112. package/packages/core/src/store/remote/protocol.ts +22 -0
  113. package/packages/core/src/store/remote/released-clients.json +37 -0
  114. package/packages/core/src/store/remote/released-clients.ts +88 -0
  115. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  116. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  117. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  118. package/packages/core/src/store/remote/version.ts +5 -2
  119. package/packages/core/src/store/repo-state-events.ts +4 -3
  120. package/packages/core/src/store/scan-cadence.ts +15 -0
  121. package/packages/core/src/store/session-handle.ts +18 -0
  122. package/packages/core/src/store/types.ts +27 -6
  123. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  124. package/packages/core/src/testing/index.ts +5 -0
  125. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  126. package/skills/guide/SKILL.md +177 -16
  127. package/skills/guide/references/accounts.md +38 -0
  128. package/skills/guide/references/integration-tree.md +8 -0
  129. package/skills/guide/references/operator-api.md +37 -4
  130. package/skills/guide/references/plugin-authoring.md +45 -1
  131. package/skills/guide/references/remote-store-protocol.md +258 -42
  132. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  133. package/skills/guide/references/restacking.md +60 -3
  134. package/skills/guide/references/setup.md +37 -8
  135. package/skills/guide/references/spec-standard.md +37 -3
  136. package/skills/implement/SKILL.md +12 -3
  137. package/skills/operate/SKILL.md +64 -7
  138. package/skills/plan/SKILL.md +27 -4
  139. package/skills/plan-review/SKILL.md +22 -2
  140. package/skills/reconcile/SKILL.md +10 -1
  141. package/skills/spec/SKILL.md +7 -4
  142. package/templates/hosted-service/package.json +2 -2
@@ -8,6 +8,9 @@ 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
 
13
16
  /** A finished-value shape catalog: this build's generated one, or a frozen
@@ -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,22 @@
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'
1
20
  import { ArtifactMetaUnsupportedError } from '../artifact-meta'
2
21
  import {
3
22
  operatorPresenceBodySchema,
@@ -17,9 +36,10 @@ import {
17
36
  supportedClientRangeSchema,
18
37
  } from './compatibility'
19
38
  import { stampCompatibility, buildEventPolicy, repositoryEventPolicy } from '../../events/policy'
39
+ import { REDUCER_VALUE_CONTRACT_IDENTITY } from '../reducer-value-validation'
20
40
  import { READ_CATALOG_IDENTITY } from '../../events/compatibility'
21
41
  import { CATALOG_IDENTITY_HEADER, REDUCER_VALUE_PROJECTION_HEADER } from './version'
22
- import { projectReducerValue } from '../reducer-value-validation'
42
+ import { diagnoseReducerValue, projectReducerValue } from '../reducer-value-validation'
23
43
  import { prepareEventWrite as validateEventWrite } from '../../events/catalog'
24
44
  import { prepareRepositoryEventWrite as validateRepositoryEventWrite } from '../../events/repository'
25
45
  import {
@@ -212,6 +232,24 @@ export class RemoteBuildStore implements BuildStore {
212
232
  }
213
233
  }
214
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
+
215
253
  async inspectDispatcherOverlap(signal: AbortSignal) {
216
254
  const response = await this.raw('GET', '/health', undefined, signal)
217
255
  if (response.status === 404 || response.status === 405)
@@ -283,25 +321,44 @@ export class RemoteBuildStore implements BuildStore {
283
321
  }
284
322
  if (this.token !== undefined) headers.authorization = `Bearer ${this.token}`
285
323
  if (body !== undefined) headers['content-type'] = 'application/json'
286
- 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}`, {
287
327
  method,
288
328
  headers,
289
329
  // A string body is already serialized JSON (the ticket-asset put sizes
290
330
  // its exact bytes before sending).
291
- ...(body !== undefined
292
- ? { body: typeof body === 'string' ? body : JSON.stringify(body) }
293
- : {}),
331
+ ...(serialized !== undefined ? { body: serialized } : {}),
294
332
  ...(signal !== undefined ? { signal } : {}),
295
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
296
341
  }
297
342
 
298
- private async toError(response: Response): Promise<Error> {
299
- 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
300
348
  try {
301
349
  body = errorBodySchema.parse(await response.json())
302
350
  } catch {
303
351
  // Not a protocol error body — fall back to the status line.
304
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()
305
362
  const message = body?.error ?? `store server responded ${response.status}`
306
363
  if (response.status === 401 || response.status === 403) {
307
364
  return new AuthError(message)
@@ -322,6 +379,13 @@ export class RemoteBuildStore implements BuildStore {
322
379
  if (response.status === 413 && message.startsWith('stream batch of ')) {
323
380
  return new StreamBatchTooLargeError(undefined, undefined, message)
324
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
+ )
325
389
  if (response.status === 409 && /^stream ".+" is closed$/.test(message)) {
326
390
  return new StreamClosedError(message)
327
391
  }
@@ -521,24 +585,39 @@ export class RemoteBuildStore implements BuildStore {
521
585
  }
522
586
  }
523
587
 
524
- 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(
525
595
  slug: string,
526
- sinceSeq = 0,
527
- opts?: { waitSeconds?: number; signal?: AbortSignal },
528
- ): Promise<AbEvent[]> {
529
- 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
+ }
530
605
  if (opts?.waitSeconds !== undefined) params.set('wait', String(opts.waitSeconds))
531
606
  return this.heldRequest(
532
607
  opts?.signal,
533
- (): AbEvent[] => [],
608
+ (): EventPage<AbEvent> => ({ events: [], cursor: since, hasMore: false }),
534
609
  () =>
535
610
  this.requestJson(
536
611
  'GET',
537
612
  `${this.buildPath(slug)}/events?${params}`,
538
- eventListSchema,
613
+ z.object({
614
+ events: eventListSchema,
615
+ cursor: z.number().int().nonnegative().safe(),
616
+ hasMore: z.boolean(),
617
+ }),
539
618
  undefined,
540
619
  opts?.signal,
541
- ) as Promise<AbEvent[]>,
620
+ ) as Promise<EventPage<AbEvent>>,
542
621
  )
543
622
  }
544
623
 
@@ -564,6 +643,14 @@ export class RemoteBuildStore implements BuildStore {
564
643
 
565
644
  private artifactMetaUnsupported = false
566
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
+
567
654
  async getLatestArtifactMeta(slug: string, kind: string): Promise<ArtifactMeta | null> {
568
655
  if (this.artifactMetaUnsupported) throw new ArtifactMetaUnsupportedError()
569
656
  const response = await this.raw(
@@ -660,6 +747,24 @@ export class RemoteBuildStore implements BuildStore {
660
747
  })
661
748
  }
662
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
+
663
768
  async upsertOperatorPresence(
664
769
  repo: string,
665
770
  identity: OperatorIdentity,
@@ -790,11 +895,51 @@ export class RemoteBuildStore implements BuildStore {
790
895
  )
791
896
  }
792
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
+
793
937
  async getReducerValue(scope: SnapshotScope, request: ReducerValueRequest): Promise<ReducerValue> {
794
938
  const { reducer } = resolveReducerValue(scope, request)
795
939
  const root = scope.kind === 'build' ? this.buildPath(scope.slug) : this.repoPath(scope.repo)
796
940
  const response = await this.raw('POST', `${root}/reducer-values`, request, undefined, {
797
941
  [REDUCER_VALUE_PROJECTION_HEADER]: '1',
942
+ [CATALOG_IDENTITY_HEADER]: REDUCER_VALUE_CONTRACT_IDENTITY,
798
943
  })
799
944
  if (!response.ok) throw await this.toError(response)
800
945
  let body: unknown
@@ -1339,7 +1484,7 @@ export class RemoteBuildStore implements BuildStore {
1339
1484
  // answers immediately and the cadence degrades to the old request rate.
1340
1485
  const { waitSeconds = REMOTE_EVENT_WAIT_SECONDS, ...rest } = opts
1341
1486
  return pollingSubscribe(
1342
- (since, pollOpts) => this.getEvents(slug, since, pollOpts),
1487
+ async (since, pollOpts) => (await this.getBuildEventPage(slug, since, pollOpts)).events,
1343
1488
  { ...rest, waitSeconds: waitSeconds > 0 ? waitSeconds : undefined },
1344
1489
  onEvent,
1345
1490
  )
@@ -2,7 +2,15 @@ import semver from 'semver'
2
2
  import { z } from 'zod'
3
3
  import { AUTOBUILD_VERSION, REMOTE_STORE_PROTOCOL_VERSION } from './version'
4
4
  import { projectReducerValue, type ReducerValueCatalog } from '../reducer-value-validation'
5
- import released120 from './released-reducer-values/1.2.0.json'
5
+ import {
6
+ RELEASED_CLIENTS,
7
+ releaseLine,
8
+ supportedPublishedLines,
9
+ CLIENT_POLICY_FLOOR,
10
+ CLIENT_SUPPORT_POLICY,
11
+ type ReleasedClient,
12
+ } from './released-clients'
13
+ import { RELEASED_REDUCER_VALUES } from './released-reducer-values'
6
14
 
7
15
  /** Stable releases only: prefixes, whitespace, prereleases and build suffixes are not identities. */
8
16
  export function stableVersion(value: unknown): semver.SemVer | undefined {
@@ -34,12 +42,21 @@ export const supportedClientRangeSchema = z
34
42
  .refine((range) => semver.lt(range.minVersion, range.maxVersionExclusive))
35
43
  export type SupportedClientRange = z.infer<typeof supportedClientRangeSchema>
36
44
 
37
- /** A major starts a new family: X.0 has one line, X.1 two, X.2+ three. */
38
- export function supportedClientRange(serviceVersion = AUTOBUILD_VERSION): SupportedClientRange {
45
+ /** Capture time per decision, so retirement takes effect without a redeploy. */
46
+ export function supportedClientRange(
47
+ serviceVersion = AUTOBUILD_VERSION,
48
+ now = Date.now(),
49
+ releases: readonly ReleasedClient[] = RELEASED_CLIENTS,
50
+ ): SupportedClientRange {
39
51
  const version = releaseVersion(serviceVersion)
40
52
  if (!version) throw new Error('service must have a canonical release version')
53
+ const lines = supportedPublishedLines(serviceVersion, now, releases)
41
54
  return {
42
- minVersion: `${version.major}.${Math.max(0, version.minor - 2)}.0`,
55
+ minVersion:
56
+ lines[0] ??
57
+ (semver.lt(releaseLine(serviceVersion), CLIENT_POLICY_FLOOR)
58
+ ? CLIENT_POLICY_FLOOR
59
+ : releaseLine(serviceVersion)),
43
60
  maxVersionExclusive: `${version.major}.${version.minor + 1}.0`,
44
61
  }
45
62
  }
@@ -78,41 +95,61 @@ export function compatibilityAdvice(
78
95
 
79
96
  /** Retain these wire identities and handlers until their lines leave the window.
80
97
  * Historical lines require explicit entries; the service's own line uses its
81
- * current protocol identity. Unknown historical protocols fail closed. */
82
- export const RELEASE_LINE_PROTOCOLS: Readonly<Record<string, string>> = {
83
- // v1.0.x shipped protocol 4; protocol 5+ requires the next minor line.
84
- '1.0': '4',
85
- // v1.1.x shipped protocol 6; retain it when this line becomes historical.
86
- '1.1': '6',
87
- // v1.2.x shipped protocol 6; retain it when this line becomes historical.
88
- '1.2': '6',
89
- '0.9': '3',
90
- '0.10': '3',
91
- '0.11': '3',
92
- '0.12': '3',
93
- // v0.13.0 shipped protocol 3. Protocol 4 requires the next minor line.
94
- '0.13': '3',
95
- // v0.14.0 introduced protocol 4; retain it when this line becomes historical.
96
- '0.14': '4',
97
- }
98
+ * runtime and published protocol identities. Unknown historical protocols fail closed. */
99
+ export const RELEASE_LINE_PROTOCOLS: Readonly<Record<string, string>> = Object.fromEntries(
100
+ RELEASED_CLIENTS.filter(
101
+ (entry) => entry.protocol && semver.gte(releaseLine(entry.version), CLIENT_POLICY_FLOOR),
102
+ ).map((entry) => [releaseLine(entry.version).split('.').slice(0, 2).join('.'), entry.protocol!]),
103
+ )
98
104
 
99
105
  export function clientIdentityError(
100
106
  client: string | null,
101
107
  protocol: string | null,
102
108
  serviceVersion = AUTOBUILD_VERSION,
103
109
  serviceProtocol = REMOTE_STORE_PROTOCOL_VERSION,
110
+ now = Date.now(),
111
+ releases: readonly ReleasedClient[] = RELEASED_CLIENTS,
104
112
  ): string | undefined {
105
- const range = supportedClientRange(serviceVersion)
113
+ const range = supportedClientRange(serviceVersion, now, releases)
106
114
  const service = releaseVersion(serviceVersion)!
107
115
  const advice = compatibilityAdvice(client, serviceVersion, range)
108
116
  const parsed = releaseVersion(client)
109
- const expected =
117
+ const publishedProtocol =
118
+ parsed &&
119
+ releases.find((entry) => releaseLine(entry.version) === releaseLine(parsed.version))?.protocol
120
+ const sameLine = parsed && parsed.major === service.major && parsed.minor === service.minor
121
+ const admittedProtocol =
122
+ protocol !== null &&
123
+ (protocol === publishedProtocol || (sameLine && protocol === serviceProtocol))
124
+ if (
110
125
  parsed &&
111
- (parsed.major === service.major && parsed.minor === service.minor
112
- ? serviceProtocol
113
- : RELEASE_LINE_PROTOCOLS[`${parsed.major}.${parsed.minor}`])
114
- if (!advice && expected !== undefined && protocol === expected) return undefined
115
- return `remote store version mismatch: client Autobuild ${client ?? '(missing)'} protocol ${protocol ?? '(missing)'}; server Autobuild ${serviceVersion} protocol ${serviceProtocol}; ${advice ?? `supported clients ${formatClientRange(range)}; unsupported protocol identity`}`
126
+ semver.gte(releaseLine(parsed.version), CLIENT_POLICY_FLOOR) &&
127
+ !advice &&
128
+ admittedProtocol
129
+ )
130
+ return undefined
131
+ return `remote store version mismatch: client Autobuild ${client ?? '(missing)'} protocol ${protocol ?? '(missing)'}; server Autobuild ${serviceVersion} protocol ${serviceProtocol}; ${advice ?? `supported clients ${formatClientRange(range)}; unsupported protocol identity`}; ${CLIENT_SUPPORT_POLICY}`
132
+ }
133
+
134
+ /** Public health never echoes an identity that admission would reject. */
135
+ export function healthIdentity(
136
+ client: string | null,
137
+ protocol: string | null,
138
+ serviceVersion = AUTOBUILD_VERSION,
139
+ serviceProtocol = REMOTE_STORE_PROTOCOL_VERSION,
140
+ ) {
141
+ const sameLine = releaseVersion(client) && releaseLine(client!) === releaseLine(serviceVersion)
142
+ const published = RELEASED_CLIENTS.find(
143
+ (entry) => releaseLine(entry.version) === releaseLine(serviceVersion),
144
+ )?.protocol
145
+ return {
146
+ autobuildVersion: serviceVersion,
147
+ protocolVersion:
148
+ sameLine && !clientIdentityError(client, protocol, serviceVersion, serviceProtocol)
149
+ ? protocol!
150
+ : (published ?? serviceProtocol),
151
+ supportedClientRange: supportedClientRange(serviceVersion),
152
+ }
116
153
  }
117
154
 
118
155
  /** A successful server answer cannot be represented by this client's reducer. */
@@ -131,33 +168,40 @@ export class ReducerValueIncompatibilityError extends Error {
131
168
  }
132
169
  }
133
170
 
134
- interface ReleasedReducerValues extends ReducerValueCatalog {
135
- versions: Record<string, number>
136
- }
137
-
138
- /** Published releases whose clients accept only their own reducer version and
139
- * finished shape. Each catalog is frozen from its release and retained while
140
- * that release is in the supported window, like `RELEASE_LINE_PROTOCOLS`. Later
141
- * clients send `REDUCER_VALUE_PROJECTION_HEADER` and project for themselves. */
142
- const EXACT_REDUCER_VALUE_RELEASES: Readonly<Record<string, ReleasedReducerValues>> = {
143
- '1.2.0': released120 as ReleasedReducerValues,
144
- }
145
-
146
- /** Answer an exact-version client as its release can read: project the canonical
171
+ /** Answer a published client as its release can read: project the canonical
147
172
  * value onto the release's frozen shape and stamp the version it expects. A value
148
173
  * the release cannot represent is returned unchanged, so the client raises its
149
174
  * typed incompatibility error rather than misreading it. */
150
175
  export function reducerValueForClient<T extends { version: number; value: unknown }>(
151
- client: { version: string | null; projects: boolean },
176
+ client: {
177
+ version: string | null
178
+ projects: boolean
179
+ catalogIdentity?: string | null
180
+ },
152
181
  reducer: string,
153
182
  answer: T,
183
+ releases = RELEASED_CLIENTS,
154
184
  ): T {
185
+ // Source clients retain the package version between releases. Their catalog
186
+ // can require fields absent from that version's published contract.
187
+ if (
188
+ client.projects &&
189
+ client.catalogIdentity &&
190
+ !releases.some((entry) => entry.catalogIdentity === client.catalogIdentity)
191
+ )
192
+ return answer
155
193
  const { version: release } = client
156
- if (client.projects || release === null) return answer
157
- if (!Object.hasOwn(EXACT_REDUCER_VALUE_RELEASES, release)) return answer
158
- const catalog = EXACT_REDUCER_VALUE_RELEASES[release]!
194
+ if (release === null) return answer
195
+ const published = releases.find((entry) =>
196
+ client.catalogIdentity
197
+ ? entry.catalogIdentity === client.catalogIdentity
198
+ : entry.version === release,
199
+ )
200
+ if (!published?.contract) return answer
201
+ const catalog = RELEASED_REDUCER_VALUES[published.contract]
202
+ if (!catalog) return answer
159
203
  if (!Object.hasOwn(catalog.versions, reducer)) return answer
160
- const projected = projectReducerValue(reducer, answer.value, catalog)
204
+ const projected = projectReleasedValue(reducer, answer.value, catalog)
161
205
  if ('path' in projected) return answer
162
206
  return {
163
207
  ...answer,
@@ -165,3 +209,90 @@ export function reducerValueForClient<T extends { version: number; value: unknow
165
209
  value: (projected as { value: unknown }).value,
166
210
  }
167
211
  }
212
+
213
+ /** Only the optional display event may be omitted when a release predates its
214
+ * discriminant. Progress, sequence and required compatibility facts stay intact.
215
+ * The catalog-directed walk covers nested build state without reading history. */
216
+ function projectReleasedValue(name: string, value: unknown, catalog: ReducerValueCatalog) {
217
+ const root = catalog.roots[name]
218
+ if (!root) return { path: '$', expected: 'known reducer' }
219
+ function adapt(id: string, input: unknown): unknown {
220
+ const shape = catalog.schemas[id]!
221
+ if (shape.kind === 'union') {
222
+ for (const member of shape.items as string[]) {
223
+ const candidate = adapt(member, input)
224
+ const result = projectReducerValue('candidate', candidate, {
225
+ ...catalog,
226
+ roots: { candidate: { value: member } },
227
+ })
228
+ if (!('path' in result)) return candidate
229
+ }
230
+ return input
231
+ }
232
+ if (shape.kind === 'array' && Array.isArray(input))
233
+ return input.map((item) => adapt(shape.items as string, item))
234
+ if (shape.kind !== 'object' || !input || typeof input !== 'object' || Array.isArray(input))
235
+ return input
236
+ const out = { ...input } as Record<string, unknown>
237
+ for (const [key, prop] of Object.entries(shape.props ?? {})) {
238
+ if (!(key in out)) continue
239
+ if (key === 'lastEvent' && prop.optional) {
240
+ const result = projectReducerValue('event', out[key], {
241
+ ...catalog,
242
+ roots: { event: { value: prop.type } },
243
+ })
244
+ const event = out[key]
245
+ function knowsType(id: string): boolean {
246
+ const variant = catalog.schemas[id]!
247
+ if (variant.kind === 'union') return (variant.items as string[]).some(knowsType)
248
+ const type = variant.props?.type
249
+ if (!type || !event || typeof event !== 'object' || !('type' in event)) return false
250
+ return !(
251
+ 'path' in
252
+ projectReducerValue('type', event.type, {
253
+ ...catalog,
254
+ roots: { type: { value: type.type } },
255
+ })
256
+ )
257
+ }
258
+ if (
259
+ 'path' in result &&
260
+ event &&
261
+ typeof event === 'object' &&
262
+ 'type' in event &&
263
+ typeof event.type === 'string' &&
264
+ !knowsType(prop.type)
265
+ ) {
266
+ delete out[key]
267
+ continue
268
+ }
269
+ }
270
+ // seenTypes is the set of event types this reader can act on, rather
271
+ // than an event history. Retain its known members; compatibility facts
272
+ // and sequence/progress remain the server's canonical answer.
273
+ if (key === 'seenTypes' && Array.isArray(out[key])) {
274
+ const array = catalog.schemas[prop.type]!
275
+ if (array.kind === 'array') {
276
+ out[key] = (out[key] as unknown[]).filter(
277
+ (type) =>
278
+ typeof type !== 'string' ||
279
+ !(
280
+ 'path' in
281
+ projectReducerValue('type', type, {
282
+ ...catalog,
283
+ roots: { type: { value: array.items as string } },
284
+ })
285
+ ),
286
+ )
287
+ continue
288
+ }
289
+ }
290
+ out[key] = adapt(prop.type, out[key])
291
+ }
292
+ if (shape.index)
293
+ for (const key of Object.keys(out))
294
+ if (!Object.hasOwn(shape.props ?? {}, key)) out[key] = adapt(shape.index, out[key])
295
+ return out
296
+ }
297
+ return projectReducerValue(name, adapt(root.value, value), catalog)
298
+ }
@@ -0,0 +1,16 @@
1
+ /** A permanent rejection of an outgoing store write's request size. */
2
+ export class StoreWriteTooLargeError extends Error {
3
+ override readonly name = 'StoreWriteTooLargeError'
4
+
5
+ constructor(
6
+ readonly method: string,
7
+ readonly route: string,
8
+ readonly requestBytes: number,
9
+ serverMessage?: string,
10
+ ) {
11
+ super(
12
+ `oversized store write: ${method} ${route} (${requestBytes} request bytes)` +
13
+ (serverMessage === undefined ? '' : `: ${serverMessage}`),
14
+ )
15
+ }
16
+ }