@defrex/autobuild 1.1.0 → 1.3.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 (157) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +249 -15
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +130 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +4 -1
  7. package/docs/architecture.md +224 -12
  8. package/docs/build-store.md +3 -41
  9. package/docs/builds.md +2 -0
  10. package/docs/cli.md +14 -0
  11. package/docs/configuration-overview.md +117 -0
  12. package/docs/configuration.md +266 -141
  13. package/docs/dispatcher-hosting.md +18 -33
  14. package/docs/intake.md +2 -0
  15. package/docs/integration-tree.md +16 -5
  16. package/docs/merge-policy.md +1 -3
  17. package/docs/operating.md +1 -2
  18. package/docs/operator-api.md +144 -53
  19. package/docs/operator-surfaces.md +32 -20
  20. package/docs/overview.md +1 -1
  21. package/docs/plugin-authoring.md +27 -1
  22. package/docs/remote-store-protocol.md +259 -91
  23. package/docs/remote-ticket-protocol.md +29 -49
  24. package/docs/restacking.md +45 -0
  25. package/docs/seams.md +8 -8
  26. package/docs/setup.md +34 -129
  27. package/docs/spec-standard.md +4 -2
  28. package/docs/ticket-dependencies.md +8 -0
  29. package/docs/ticket-sources.md +18 -0
  30. package/docs/troubleshooting.md +7 -11
  31. package/docs/upgrading.md +1 -1
  32. package/docs/workspaces.md +4 -4
  33. package/package.json +14 -5
  34. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  35. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  36. package/packages/core/src/accounts/local-credentials.ts +194 -0
  37. package/packages/core/src/accounts/local-inference.ts +106 -0
  38. package/packages/core/src/accounts/local-owner.ts +123 -0
  39. package/packages/core/src/accounts/sensitive.ts +2 -0
  40. package/packages/core/src/cli/accounts.ts +147 -0
  41. package/packages/core/src/cli/binary.ts +3 -1
  42. package/packages/core/src/cli/connect.ts +3 -3
  43. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  44. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  45. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  46. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  47. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  48. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  49. package/packages/core/src/cli/dispatch.ts +135 -27
  50. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  51. package/packages/core/src/cli/forge-clear.ts +30 -0
  52. package/packages/core/src/cli/help.ts +17 -0
  53. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  54. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  55. package/packages/core/src/cli/init-validation.ts +160 -18
  56. package/packages/core/src/cli/main.ts +72 -0
  57. package/packages/core/src/cli/publication-settlement.ts +4 -1
  58. package/packages/core/src/cli/secrets.ts +173 -0
  59. package/packages/core/src/cli/store-opening.ts +11 -1
  60. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  61. package/packages/core/src/cli/watch.ts +12 -14
  62. package/packages/core/src/config/accounts.ts +101 -0
  63. package/packages/core/src/config/live.ts +14 -1
  64. package/packages/core/src/config/roles.ts +54 -3
  65. package/packages/core/src/config/schema.ts +60 -0
  66. package/packages/core/src/events/catalog.ts +1 -0
  67. package/packages/core/src/events/compatibility.ts +2 -1
  68. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  69. package/packages/core/src/events/payloads.ts +13 -0
  70. package/packages/core/src/events/policy.ts +9 -0
  71. package/packages/core/src/events/repository.ts +75 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +278 -0
  73. package/packages/core/src/kernel/change-presence.ts +74 -8
  74. package/packages/core/src/kernel/engine.ts +8 -0
  75. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  76. package/packages/core/src/kernel/node-polling.ts +40 -7
  77. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  78. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  79. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  80. package/packages/core/src/kernel/read-facts.ts +6 -0
  81. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  82. package/packages/core/src/kernel/reducer.ts +4 -1
  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 +4 -0
  87. package/packages/core/src/operator/protocol.ts +6 -0
  88. package/packages/core/src/operator/registry.ts +42 -1
  89. package/packages/core/src/operator/tickets.ts +25 -4
  90. package/packages/core/src/plugins/manifest.ts +2 -1
  91. package/packages/core/src/ports/runner/account-env.ts +139 -0
  92. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  93. package/packages/core/src/ports/runner/claude.ts +70 -42
  94. package/packages/core/src/ports/runner/codex.ts +63 -31
  95. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  96. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  97. package/packages/core/src/ports/runner/routing.ts +35 -4
  98. package/packages/core/src/ports/tickets/contract.ts +58 -0
  99. package/packages/core/src/ports/tickets/tree.ts +1 -1
  100. package/packages/core/src/ports/types.ts +28 -7
  101. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  102. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  103. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  104. package/packages/core/src/ports/workspace/create.ts +2 -0
  105. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  106. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  107. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  108. package/packages/core/src/processes/build-runner.ts +32 -1
  109. package/packages/core/src/processes/dispatcher.ts +493 -121
  110. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  111. package/packages/core/src/processes/execution-settlement.ts +21 -3
  112. package/packages/core/src/processes/harvest-runner.ts +68 -8
  113. package/packages/core/src/processes/harvest.ts +11 -16
  114. package/packages/core/src/processes/repo-view.ts +3 -0
  115. package/packages/core/src/project-secrets.ts +105 -0
  116. package/packages/core/src/secret-name.ts +41 -0
  117. package/packages/core/src/store/account-redaction.ts +156 -0
  118. package/packages/core/src/store/artifact-meta.ts +7 -0
  119. package/packages/core/src/store/contract.ts +60 -1
  120. package/packages/core/src/store/memory.ts +4 -0
  121. package/packages/core/src/store/reducer-value-shapes.json +7389 -6647
  122. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  123. package/packages/core/src/store/remote/client.ts +85 -50
  124. package/packages/core/src/store/remote/compatibility.ts +57 -0
  125. package/packages/core/src/store/remote/index.ts +6 -0
  126. package/packages/core/src/store/remote/protocol.ts +8 -1
  127. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  128. package/packages/core/src/store/remote/version.ts +4 -0
  129. package/packages/core/src/store/repo-state-events.ts +4 -2
  130. package/packages/core/src/store/snapshots.ts +16 -3
  131. package/packages/core/src/store/types.ts +2 -0
  132. package/packages/core/src/testing/dispatch-read-budget.ts +266 -5
  133. package/packages/core/src/testing/index.ts +2 -1
  134. package/packages/core/src/testing/reduced-read-budget.ts +560 -5
  135. package/skills/guide/SKILL.md +164 -37
  136. package/skills/guide/references/accounts.md +130 -0
  137. package/skills/guide/references/integration-tree.md +16 -5
  138. package/skills/guide/references/merge-policy.md +1 -3
  139. package/skills/guide/references/operator-api.md +144 -53
  140. package/skills/guide/references/plugin-authoring.md +27 -1
  141. package/skills/guide/references/remote-store-protocol.md +259 -91
  142. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  143. package/skills/guide/references/restacking.md +45 -0
  144. package/skills/guide/references/setup.md +34 -129
  145. package/skills/guide/references/spec-standard.md +4 -2
  146. package/skills/guide/references/ticket-dependencies.md +8 -0
  147. package/skills/harvest/SKILL.md +3 -1
  148. package/skills/harvest-review/SKILL.md +3 -1
  149. package/skills/operate/SKILL.md +26 -11
  150. package/skills/reconcile/SKILL.md +6 -0
  151. package/skills/spec/SKILL.md +1 -1
  152. package/skills/tickets/SKILL.md +10 -5
  153. package/templates/hosted-service/package.json +2 -2
  154. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  155. package/docs/hosted-dispatcher.md +0 -278
  156. package/docs/hosted-service.md +0 -304
  157. package/docs/mcp.md +0 -150
@@ -10,6 +10,13 @@ type Shape = {
10
10
  }
11
11
  const schemas: Record<string, Shape> = shapes.schemas
12
12
 
13
+ /** A finished-value shape catalog: this build's generated one, or a frozen
14
+ * catalog from a published release line. */
15
+ export interface ReducerValueCatalog {
16
+ roots: Record<string, { value: string }>
17
+ schemas: Record<string, Shape>
18
+ }
19
+
13
20
  /** Generated structural shapes include nested event payload unions, records,
14
21
  * optional fields and literal discriminants. No accumulator is trusted merely
15
22
  * because finish() happens to accept it. */
@@ -37,8 +44,8 @@ function json(value: unknown, seen = new Set<object>()): boolean {
37
44
  Object.values(value).every((item) => json(item, new Set(seen)))
38
45
  )
39
46
  }
40
- function matches(id: string, value: unknown): boolean {
41
- const shape = schemas[id]!
47
+ function matches(id: string, value: unknown, table = schemas): boolean {
48
+ const shape = table[id]!
42
49
  switch (shape.kind) {
43
50
  case 'json':
44
51
  return json(value)
@@ -53,9 +60,11 @@ function matches(id: string, value: unknown): boolean {
53
60
  case 'boolean':
54
61
  return typeof value === 'boolean'
55
62
  case 'union':
56
- return (shape.items as string[]).some((item) => matches(item, value))
63
+ return (shape.items as string[]).some((item) => matches(item, value, table))
57
64
  case 'array':
58
- return Array.isArray(value) && value.every((item) => matches(shape.items as string, item))
65
+ return (
66
+ Array.isArray(value) && value.every((item) => matches(shape.items as string, item, table))
67
+ )
59
68
  case 'object': {
60
69
  if (
61
70
  value === null ||
@@ -67,12 +76,12 @@ function matches(id: string, value: unknown): boolean {
67
76
  const record = value as Record<string, unknown>
68
77
  for (const [key, prop] of Object.entries(shape.props!)) {
69
78
  if (!(key in record) && prop.optional) continue
70
- if (!matches(prop.type, record[key])) return false
79
+ if (!matches(prop.type, record[key], table)) return false
71
80
  }
72
81
  return Object.keys(record).every(
73
82
  (key) =>
74
83
  Object.hasOwn(shape.props!, key) ||
75
- (shape.index !== undefined && matches(shape.index, record[key])),
84
+ (shape.index !== undefined && matches(shape.index, record[key], table)),
76
85
  )
77
86
  }
78
87
  default:
@@ -174,6 +183,97 @@ function diagnose(id: string, value: unknown, path: string, depth: number): Diag
174
183
  return failure
175
184
  }
176
185
 
186
+ type Projected = { value: unknown; dropped: number }
187
+ type Unprojectable = Diagnostic
188
+ type Projection = Projected | Unprojectable
189
+ // Plugin consumers may compile without strict narrowing; `in` guards narrow everywhere.
190
+ const failed = (result: Projection): result is Unprojectable => 'path' in result
191
+
192
+ /** Project a value onto a catalog's shape, dropping object properties the shape
193
+ * does not know. Additive server fields then reach older readers as the value
194
+ * they were built for, while a missing field or unknown variant still fails.
195
+ * Among union members, the one dropping the fewest properties wins. */
196
+ function project(
197
+ table: Record<string, Shape>,
198
+ id: string,
199
+ value: unknown,
200
+ path: string,
201
+ depth: number,
202
+ ): Projection {
203
+ if (matches(id, value, table)) return { value, dropped: 0 }
204
+ const shape = table[id]!
205
+ const failure: Unprojectable = {
206
+ path,
207
+ depth,
208
+ expected: shape.kind === 'literal' ? JSON.stringify(shape.value) : shape.kind,
209
+ }
210
+ if (shape.kind === 'union') {
211
+ let best: Projection | undefined
212
+ for (const item of shape.items as string[]) {
213
+ const next = project(table, item, value, path, depth)
214
+ if (!failed(next)) {
215
+ if (!best || failed(best) || next.dropped < best.dropped) best = next
216
+ } else if (!best || (failed(best) && next.depth > best.depth)) best = next
217
+ }
218
+ return best ?? failure
219
+ }
220
+ if (shape.kind === 'array' && Array.isArray(value)) {
221
+ const items: unknown[] = []
222
+ let dropped = 0
223
+ for (let i = 0; i < value.length; i++) {
224
+ const next = project(table, shape.items as string, value[i], `${path}[${i}]`, depth + 1)
225
+ if (failed(next)) return next
226
+ items.push(next.value)
227
+ dropped += next.dropped
228
+ }
229
+ return { value: items, dropped }
230
+ }
231
+ if (
232
+ shape.kind === 'object' &&
233
+ value !== null &&
234
+ typeof value === 'object' &&
235
+ Object.getPrototypeOf(value) === Object.prototype
236
+ ) {
237
+ const record = value as Record<string, unknown>
238
+ const out: Record<string, unknown> = {}
239
+ let dropped = 0
240
+ for (const [key, prop] of Object.entries(shape.props!)) {
241
+ if (!(key in record) && prop.optional) continue
242
+ const next = project(table, prop.type, record[key], property(path, key), depth + 1)
243
+ if (failed(next)) return next
244
+ if (key in record) out[key] = next.value
245
+ dropped += next.dropped
246
+ }
247
+ for (const key of Object.keys(record).sort()) {
248
+ if (Object.hasOwn(shape.props!, key)) continue
249
+ if (!shape.index) {
250
+ dropped += 1
251
+ continue
252
+ }
253
+ const next = project(table, shape.index, record[key], property(path, key), depth + 1)
254
+ if (failed(next)) return next
255
+ out[key] = next.value
256
+ dropped += next.dropped
257
+ }
258
+ return { value: out, dropped }
259
+ }
260
+ return failure
261
+ }
262
+
263
+ /** The reader-side contract for a server's canonical answer: the value as this
264
+ * reader's shape can represent it, or a structural diagnostic. Reducer versions
265
+ * are cache identities, not compatibility gates. */
266
+ export function projectReducerValue(
267
+ name: string,
268
+ value: unknown,
269
+ catalog: ReducerValueCatalog = shapes,
270
+ ): { value: unknown } | ValidationFailure {
271
+ const root = Object.hasOwn(catalog.roots, name) ? catalog.roots[name] : undefined
272
+ if (!root) return { path: '$', expected: 'known reducer' }
273
+ const result = project(catalog.schemas, root.value, value, '$', 0)
274
+ return failed(result) ? { path: result.path, expected: result.expected } : { value: result.value }
275
+ }
276
+
177
277
  /** Existing optional object fields keep their ordinary JSON omission semantics.
178
278
  * Collections, functions, nonfinite numbers and undefined array entries cannot
179
279
  * silently become a different public contract during JSON serialization. */
@@ -1,3 +1,4 @@
1
+ import { ArtifactMetaUnsupportedError } from '../artifact-meta'
1
2
  import {
2
3
  operatorPresenceBodySchema,
3
4
  operatorPresenceWireSchema,
@@ -9,15 +10,16 @@ import {
9
10
  type OperatorPresence,
10
11
  } from '../operator-presence'
11
12
  import {
13
+ ReducerValueIncompatibilityError,
12
14
  clientIdentityError,
13
15
  classifyClient,
14
16
  releaseVersion,
15
17
  supportedClientRangeSchema,
16
18
  } from './compatibility'
17
19
  import { stampCompatibility, buildEventPolicy, repositoryEventPolicy } from '../../events/policy'
18
- import { READ_CATALOG_IDENTITY, projectStoredEvents } from '../../events/compatibility'
19
- import { CATALOG_IDENTITY_HEADER } from './version'
20
- import { validateReducerValue } from '../reducer-value-validation'
20
+ import { READ_CATALOG_IDENTITY } from '../../events/compatibility'
21
+ import { CATALOG_IDENTITY_HEADER, REDUCER_VALUE_PROJECTION_HEADER } from './version'
22
+ import { projectReducerValue } from '../reducer-value-validation'
21
23
  import { prepareEventWrite as validateEventWrite } from '../../events/catalog'
22
24
  import { prepareRepositoryEventWrite as validateRepositoryEventWrite } from '../../events/repository'
23
25
  import {
@@ -195,9 +197,6 @@ export interface RemoteBuildStoreOptions {
195
197
  export class RemoteBuildStore implements BuildStore {
196
198
  readonly catalogIdentity = READ_CATALOG_IDENTITY
197
199
  readonly networkReads = true
198
- // Reader-local accumulators for this client instance. Never publish these into the service's
199
- // cache: its catalog may interpret the same journal differently.
200
- private readonly replayStates = new Map<string, { cursor: number; acc: unknown }>()
201
200
  private readonly base: string
202
201
  private readonly token: string | undefined
203
202
  private readonly fetchFn: typeof fetch
@@ -275,8 +274,10 @@ export class RemoteBuildStore implements BuildStore {
275
274
  path: string,
276
275
  body?: unknown,
277
276
  signal?: AbortSignal,
277
+ capabilities: Record<string, string> = {},
278
278
  ): Promise<Response> {
279
279
  const headers: Record<string, string> = {
280
+ ...capabilities,
280
281
  [AUTOBUILD_VERSION_HEADER]: this.identity.autobuildVersion,
281
282
  [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: this.identity.protocolVersion,
282
283
  }
@@ -313,7 +314,8 @@ export class RemoteBuildStore implements BuildStore {
313
314
  ) {
314
315
  return new TicketAssetValidationError(message)
315
316
  }
316
- if (response.status === 422) return new EventValidationError(message)
317
+ if (response.status === 422 || (response.status === 400 && body?.kind === 'validation'))
318
+ return new EventValidationError(message)
317
319
  // Typed stream rejections rehydrate by the server's message shape: the
318
320
  // ceiling names its bytes, the closed-append names its stream (a 409 is
319
321
  // otherwise the generic already-exists conflict).
@@ -365,10 +367,7 @@ export class RemoteBuildStore implements BuildStore {
365
367
  const response = await this.raw('GET', `${this.repoPath(repo)}/build-digests`)
366
368
  if (!response.ok) throw await this.toError(response)
367
369
  const digests = buildDigestListSchema.parse(await response.json())
368
- if (response.headers.get(CATALOG_IDENTITY_HEADER) === READ_CATALOG_IDENTITY)
369
- return new Map(digests.map((digest) => [digest.slug, digest]))
370
- const { readPersistedBuildDigests } = await import('../reduced-reads')
371
- return readPersistedBuildDigests(this, repo)
370
+ return new Map(digests.map((digest) => [digest.slug, digest]))
372
371
  }
373
372
 
374
373
  async append<T extends EventType>(slug: string, event: EventWrite<T>): Promise<EventEnvelope<T>> {
@@ -563,6 +562,38 @@ export class RemoteBuildStore implements BuildStore {
563
562
  return { meta: result.meta, content: decodeBase64(result.contentBase64) }
564
563
  }
565
564
 
565
+ private artifactMetaUnsupported = false
566
+
567
+ async getLatestArtifactMeta(slug: string, kind: string): Promise<ArtifactMeta | null> {
568
+ if (this.artifactMetaUnsupported) throw new ArtifactMetaUnsupportedError()
569
+ const response = await this.raw(
570
+ 'GET',
571
+ `${this.buildPath(slug)}/artifact-meta?${new URLSearchParams({ kind })}`,
572
+ )
573
+ if (!response.ok) {
574
+ const body = errorBodySchema.safeParse(
575
+ await response
576
+ .clone()
577
+ .json()
578
+ .catch(() => null),
579
+ )
580
+ if (
581
+ body.success &&
582
+ ((response.status === 501 && body.data.kind === 'unsupported-operation') ||
583
+ (response.status === 404 &&
584
+ body.data.kind === 'not-found' &&
585
+ (body.data.error === 'no route: GET /builds/:slug/artifact-meta' ||
586
+ body.data.error ===
587
+ `no route: GET ${new URL(`${this.base}${this.buildPath(slug)}/artifact-meta`).pathname}`)))
588
+ ) {
589
+ this.artifactMetaUnsupported = true
590
+ throw new ArtifactMetaUnsupportedError()
591
+ }
592
+ throw await this.toError(response)
593
+ }
594
+ return artifactMetaWireSchema.nullable().parse(await response.json())
595
+ }
596
+
566
597
  async listArtifacts(slug: string, kind?: string): Promise<ArtifactMeta[]> {
567
598
  const query = kind !== undefined ? `?kind=${encodeURIComponent(kind)}` : ''
568
599
  return this.requestJson(
@@ -760,49 +791,53 @@ export class RemoteBuildStore implements BuildStore {
760
791
  }
761
792
 
762
793
  async getReducerValue(scope: SnapshotScope, request: ReducerValueRequest): Promise<ReducerValue> {
763
- const { reducer, entry, identity: replayIdentity } = resolveReducerValue(scope, request)
794
+ const { reducer } = resolveReducerValue(scope, request)
764
795
  const root = scope.kind === 'build' ? this.buildPath(scope.slug) : this.repoPath(scope.repo)
765
- const response = await this.raw('POST', `${root}/reducer-values`, request)
796
+ const response = await this.raw('POST', `${root}/reducer-values`, request, undefined, {
797
+ [REDUCER_VALUE_PROJECTION_HEADER]: '1',
798
+ })
766
799
  if (!response.ok) throw await this.toError(response)
767
- const result = reducerValueSchema.parse(await response.json())
768
- const identity = response.headers.get(CATALOG_IDENTITY_HEADER)
769
- if (
770
- identity === READ_CATALOG_IDENTITY &&
771
- result.version === reducer.version &&
772
- validateReducerValue(request.reducer, result.value)
773
- )
774
- return {
775
- version: result.version,
776
- cursor: result.cursor,
777
- value: result.value as ReducerValue['value'],
778
- catalogIdentity: identity,
779
- }
780
- // Freeze at this response's cursor, including when concurrent reads finish
781
- // out of order. Clone before folding: reducers may mutate their accumulator.
782
- const cached = this.replayStates.get(replayIdentity)
783
- const reusable = cached !== undefined && cached.cursor <= result.cursor ? cached : undefined
784
- let cursor = reusable?.cursor ?? 0
785
- let acc = reusable === undefined ? reducer.initial() : structuredClone(reusable.acc)
786
- if (cursor < result.cursor) {
787
- const events =
788
- scope.kind === 'build'
789
- ? await this.getEvents(scope.slug, cursor)
790
- : await this.getRepoEvents(scope.repo, cursor)
791
- const bounded = events.filter((event) => event.seq <= result.cursor)
792
- for (const event of bounded) {
793
- if (event.seq !== cursor + 1) throw new Error('noncontiguous reducer log')
794
- cursor = event.seq
795
- }
796
- if (cursor !== result.cursor) throw new Error('incomplete reducer log')
797
- acc = reducer.advance(acc, entry.adapt(projectStoredEvents(bounded)))
800
+ let body: unknown
801
+ try {
802
+ body = await response.json()
803
+ } catch (error) {
804
+ if (!(error instanceof SyntaxError)) throw error
805
+ throw new ReducerValueIncompatibilityError(
806
+ request.reducer,
807
+ scope,
808
+ reducer.version,
809
+ undefined,
810
+ 'invalid reducer envelope: expected JSON',
811
+ )
812
+ }
813
+ const parsed = reducerValueSchema.safeParse(body)
814
+ const serverVersion =
815
+ body && typeof body === 'object' && 'version' in body && typeof body.version === 'number'
816
+ ? body.version
817
+ : undefined
818
+ const fail = (reason: string): never => {
819
+ throw new ReducerValueIncompatibilityError(
820
+ request.reducer,
821
+ scope,
822
+ reducer.version,
823
+ serverVersion,
824
+ reason,
825
+ )
798
826
  }
799
- const value = entry.value(reducer.finish(structuredClone(acc)))
800
- // Commit only successful folds, and never regress a concurrent accumulator.
801
- if ((this.replayStates.get(replayIdentity)?.cursor ?? -1) <= cursor) {
802
- this.replayStates.delete(replayIdentity)
803
- this.replayStates.set(replayIdentity, { cursor, acc })
827
+ if (!parsed.success) fail(`invalid reducer envelope: ${parsed.error.message}`)
828
+ const result = parsed.data!
829
+ // The shape this reader can represent is the contract. A different reducer
830
+ // version is the server's cache identity, so release lines may skew freely.
831
+ const projected = projectReducerValue(request.reducer, result.value)
832
+ if ('path' in projected)
833
+ fail(`invalid finished value at ${projected.path}: expected ${projected.expected}`)
834
+ const identity = response.headers.get(CATALOG_IDENTITY_HEADER)
835
+ return {
836
+ version: result.version,
837
+ cursor: result.cursor,
838
+ value: (projected as { value: unknown }).value as ReducerValue['value'],
839
+ ...(identity === null ? {} : { catalogIdentity: identity }),
804
840
  }
805
- return { version: reducer.version, cursor, value, catalogIdentity: READ_CATALOG_IDENTITY }
806
841
  }
807
842
 
808
843
  private snapshotPath(scope: SnapshotScope, reducer: string): string {
@@ -1,6 +1,8 @@
1
1
  import semver from 'semver'
2
2
  import { z } from 'zod'
3
3
  import { AUTOBUILD_VERSION, REMOTE_STORE_PROTOCOL_VERSION } from './version'
4
+ import { projectReducerValue, type ReducerValueCatalog } from '../reducer-value-validation'
5
+ import released120 from './released-reducer-values/1.2.0.json'
4
6
 
5
7
  /** Stable releases only: prefixes, whitespace, prereleases and build suffixes are not identities. */
6
8
  export function stableVersion(value: unknown): semver.SemVer | undefined {
@@ -80,6 +82,10 @@ export function compatibilityAdvice(
80
82
  export const RELEASE_LINE_PROTOCOLS: Readonly<Record<string, string>> = {
81
83
  // v1.0.x shipped protocol 4; protocol 5+ requires the next minor line.
82
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',
83
89
  '0.9': '3',
84
90
  '0.10': '3',
85
91
  '0.11': '3',
@@ -108,3 +114,54 @@ export function clientIdentityError(
108
114
  if (!advice && expected !== undefined && protocol === expected) return undefined
109
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`}`
110
116
  }
117
+
118
+ /** A successful server answer cannot be represented by this client's reducer. */
119
+ export class ReducerValueIncompatibilityError extends Error {
120
+ override readonly name = 'ReducerValueIncompatibilityError'
121
+ constructor(
122
+ readonly reducer: string,
123
+ readonly scope: import('../snapshots').SnapshotScope,
124
+ readonly clientVersion: number,
125
+ readonly serverVersion: number | undefined,
126
+ readonly reason: string,
127
+ ) {
128
+ super(
129
+ `incompatible reducer ${reducer}: client version ${clientVersion}, server version ${serverVersion ?? '(unavailable)'}; ${reason}`,
130
+ )
131
+ }
132
+ }
133
+
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
147
+ * value onto the release's frozen shape and stamp the version it expects. A value
148
+ * the release cannot represent is returned unchanged, so the client raises its
149
+ * typed incompatibility error rather than misreading it. */
150
+ export function reducerValueForClient<T extends { version: number; value: unknown }>(
151
+ client: { version: string | null; projects: boolean },
152
+ reducer: string,
153
+ answer: T,
154
+ ): T {
155
+ 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]!
159
+ if (!Object.hasOwn(catalog.versions, reducer)) return answer
160
+ const projected = projectReducerValue(reducer, answer.value, catalog)
161
+ if ('path' in projected) return answer
162
+ return {
163
+ ...answer,
164
+ version: catalog.versions[reducer]!,
165
+ value: (projected as { value: unknown }).value,
166
+ }
167
+ }
@@ -14,6 +14,7 @@ export type {
14
14
  } from './token'
15
15
  export {
16
16
  CATALOG_IDENTITY_HEADER,
17
+ REDUCER_VALUE_PROJECTION_HEADER,
17
18
  AUTOBUILD_VERSION,
18
19
  AUTOBUILD_VERSION_HEADER,
19
20
  REMOTE_STORE_PROTOCOL_VERSION,
@@ -56,3 +57,8 @@ export type { BuildDelegationFacts, HarvestDelegationFacts } from '../../kernel/
56
57
  export { delegationFactKey } from '../../kernel/service-facts'
57
58
 
58
59
  export { assertPublicSnapshotReducer } from '../snapshots'
60
+
61
+ export {
62
+ validateForgeDegradation,
63
+ MAX_FORGE_DEGRADATION_MS,
64
+ } from '../../events/forge-degradation-policy'
@@ -39,7 +39,14 @@ import type { ArtifactMeta, RepositoryArtifactMeta, SessionArtifactMeta } from '
39
39
 
40
40
  // ── Errors (D6: errors as feedback over the wire) ────────────────────────────
41
41
 
42
- export const errorKindSchema = z.enum(['validation', 'not-found', 'auth', 'conflict', 'internal'])
42
+ export const errorKindSchema = z.enum([
43
+ 'validation',
44
+ 'not-found',
45
+ 'auth',
46
+ 'conflict',
47
+ 'internal',
48
+ 'unsupported-operation',
49
+ ])
43
50
  export type ErrorKind = z.infer<typeof errorKindSchema>
44
51
 
45
52
  export const errorBodySchema = z.object({