@defrex/autobuild 1.11.1 → 1.13.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 (213) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +601 -203
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +32 -2
  5. package/docs/architecture.md +188 -57
  6. package/docs/assets/headline-wide.png +0 -0
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +120 -23
  9. package/docs/dispatcher.md +19 -8
  10. package/docs/integration-overview.md +1 -1
  11. package/docs/integration-tree.md +33 -18
  12. package/docs/merge-policy.md +7 -2
  13. package/docs/operating.md +5 -3
  14. package/docs/operator-api.md +48 -25
  15. package/docs/operator-surfaces.md +39 -3
  16. package/docs/optimization-nodes.md +10 -8
  17. package/docs/plugin-authoring.md +46 -18
  18. package/docs/remote-store-protocol.md +51 -12
  19. package/docs/remote-ticket-protocol.md +85 -38
  20. package/docs/restacking.md +48 -3
  21. package/docs/setup.md +2 -1
  22. package/docs/ticket-migration.md +2 -2
  23. package/docs/ticket-sources.md +23 -8
  24. package/docs/tickets.md +4 -4
  25. package/docs/troubleshooting.md +17 -2
  26. package/docs/verification.md +3 -1
  27. package/package.json +3 -3
  28. package/packages/core/src/cli/ambient-errors.ts +17 -0
  29. package/packages/core/src/cli/bounded-io.ts +174 -0
  30. package/packages/core/src/cli/build-control.ts +72 -6
  31. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  32. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  33. package/packages/core/src/cli/dashboard/model.ts +93 -29
  34. package/packages/core/src/cli/dashboard/poll.ts +231 -34
  35. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  36. package/packages/core/src/cli/dashboard/render.ts +14 -37
  37. package/packages/core/src/cli/dashboard/row-text.ts +26 -8
  38. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  39. package/packages/core/src/cli/dashboard/vocabulary.ts +165 -20
  40. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  41. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  42. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  43. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  44. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  45. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  46. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  47. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  48. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  49. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  50. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  51. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  52. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  53. package/packages/core/src/cli/dispatch.ts +595 -149
  54. package/packages/core/src/cli/env.ts +2 -15
  55. package/packages/core/src/cli/help.ts +43 -28
  56. package/packages/core/src/cli/main.ts +11 -7
  57. package/packages/core/src/cli/production-store.ts +102 -0
  58. package/packages/core/src/cli/publication-settlement.ts +4 -0
  59. package/packages/core/src/cli/remote-poll.ts +22 -5
  60. package/packages/core/src/cli/repo-state.ts +2 -3
  61. package/packages/core/src/cli/repository-status.ts +44 -28
  62. package/packages/core/src/cli/sessionless-store.ts +26 -0
  63. package/packages/core/src/cli/status.ts +188 -47
  64. package/packages/core/src/cli/store-opening.ts +26 -57
  65. package/packages/core/src/cli/store-ref.ts +6 -1
  66. package/packages/core/src/cli/ticket-start.ts +3 -3
  67. package/packages/core/src/cli/ticket.ts +12 -11
  68. package/packages/core/src/cli/wait.ts +8 -28
  69. package/packages/core/src/cli/watch.ts +113 -50
  70. package/packages/core/src/config/reference-metadata.ts +7 -1
  71. package/packages/core/src/config/reference.ts +5 -2
  72. package/packages/core/src/config/schema.ts +51 -16
  73. package/packages/core/src/distribution-packaging.ts +156 -18
  74. package/packages/core/src/events/catalog-identity.ts +28 -0
  75. package/packages/core/src/events/catalog.ts +3 -9
  76. package/packages/core/src/events/compatibility.ts +2 -30
  77. package/packages/core/src/events/payloads.ts +85 -14
  78. package/packages/core/src/events/policy.ts +3 -0
  79. package/packages/core/src/events/repository.ts +15 -4
  80. package/packages/core/src/events/sessions.ts +1 -1
  81. package/packages/core/src/events/validation-error.ts +12 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +36 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  92. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  93. package/packages/core/src/kernel/capacity-build.ts +21 -0
  94. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  95. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +578 -235
  97. package/packages/core/src/kernel/done-escalations.ts +269 -0
  98. package/packages/core/src/kernel/engine.ts +30 -17
  99. package/packages/core/src/kernel/integration-landing.ts +24 -4
  100. package/packages/core/src/kernel/integration-stack.ts +39 -0
  101. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  102. package/packages/core/src/kernel/log-index-value.ts +3 -0
  103. package/packages/core/src/kernel/log-index.ts +41 -2
  104. package/packages/core/src/kernel/measurement.ts +24 -0
  105. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  106. package/packages/core/src/kernel/read-facts.ts +8 -370
  107. package/packages/core/src/kernel/reducer-registry.ts +43 -125
  108. package/packages/core/src/kernel/reducer-revisions.ts +18 -0
  109. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  110. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  111. package/packages/core/src/kernel/reducer.ts +84 -16
  112. package/packages/core/src/kernel/reopen-state.ts +10 -0
  113. package/packages/core/src/kernel/repository-attention.ts +14 -5
  114. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  115. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  116. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  117. package/packages/core/src/kernel/verify-stages.ts +46 -7
  118. package/packages/core/src/operator/attention.ts +28 -3
  119. package/packages/core/src/operator/done-escalations.ts +38 -0
  120. package/packages/core/src/operator/presentation.ts +14 -1
  121. package/packages/core/src/operator/protocol.ts +8 -5
  122. package/packages/core/src/operator/query.ts +72 -57
  123. package/packages/core/src/operator/registry.ts +19 -15
  124. package/packages/core/src/operator/ticket-start.ts +8 -7
  125. package/packages/core/src/operator/tickets.ts +28 -9
  126. package/packages/core/src/plugin-sdk/index.ts +10 -0
  127. package/packages/core/src/plugins/manifest.ts +14 -1
  128. package/packages/core/src/ports/forge/create.ts +8 -0
  129. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  130. package/packages/core/src/ports/forge/github.ts +3 -0
  131. package/packages/core/src/ports/tickets/contract.ts +147 -76
  132. package/packages/core/src/ports/tickets/create.ts +47 -7
  133. package/packages/core/src/ports/tickets/fake.ts +8 -4
  134. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  135. package/packages/core/src/ports/tickets/file.ts +7 -3
  136. package/packages/core/src/ports/tickets/github.ts +1 -0
  137. package/packages/core/src/ports/tickets/grants.ts +11 -3
  138. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  139. package/packages/core/src/ports/tickets/linear.ts +28 -9
  140. package/packages/core/src/ports/tickets/migration.ts +4 -4
  141. package/packages/core/src/ports/tickets/operations.ts +4 -2
  142. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  143. package/packages/core/src/ports/tickets/priority.ts +127 -21
  144. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  145. package/packages/core/src/ports/tickets/remote.ts +104 -11
  146. package/packages/core/src/ports/tickets/revision.ts +5 -3
  147. package/packages/core/src/ports/tickets/search.ts +9 -0
  148. package/packages/core/src/ports/tickets/tree.ts +8 -6
  149. package/packages/core/src/ports/types.ts +30 -15
  150. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  151. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  152. package/packages/core/src/ports/workspace/create.ts +16 -3
  153. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  154. package/packages/core/src/ports/workspace/fake.ts +15 -3
  155. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  156. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  157. package/packages/core/src/processes/build-execution-state.ts +4 -0
  158. package/packages/core/src/processes/build-runner.ts +14 -1
  159. package/packages/core/src/processes/dispatcher.ts +777 -288
  160. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  161. package/packages/core/src/processes/execution-settlement.ts +1 -0
  162. package/packages/core/src/processes/harvest-runner.ts +12 -7
  163. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  164. package/packages/core/src/processes/invocation-budget.ts +176 -0
  165. package/packages/core/src/processes/publication-loss.ts +38 -3
  166. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  167. package/packages/core/src/store/contract.ts +81 -3
  168. package/packages/core/src/store/event-reads.ts +30 -1
  169. package/packages/core/src/store/local/capabilities.ts +115 -0
  170. package/packages/core/src/store/local/store.ts +86 -56
  171. package/packages/core/src/store/reduced-reads.ts +32 -1
  172. package/packages/core/src/store/reducer-value-read.ts +235 -0
  173. package/packages/core/src/store/reducer-value-shapes.json +6722 -6475
  174. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  175. package/packages/core/src/store/reducer-values.ts +36 -204
  176. package/packages/core/src/store/remote/client.ts +169 -29
  177. package/packages/core/src/store/remote/compatibility.ts +113 -56
  178. package/packages/core/src/store/remote/credentials.ts +4 -1
  179. package/packages/core/src/store/remote/protocol.ts +3 -0
  180. package/packages/core/src/store/remote/released-clients.json +22 -0
  181. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  182. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  183. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  184. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  185. package/packages/core/src/store/remote/retry.ts +406 -0
  186. package/packages/core/src/store/rollup-lease.ts +41 -0
  187. package/packages/core/src/store/rollups.ts +7 -38
  188. package/packages/core/src/store/snapshots.ts +1 -1
  189. package/packages/core/src/testing/dispatch-read-budget.ts +409 -14
  190. package/packages/core/src/testing/import-graph.ts +78 -0
  191. package/packages/core/src/testing/index.ts +2 -0
  192. package/packages/core/src/testing/invocation-budget.ts +42 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +602 -40
  194. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  195. package/packages/core/src/testing/slot-agreement.ts +52 -0
  196. package/packages/core/src/web/assets/app.js +5 -5
  197. package/packages/core/src/web/overview-source.ts +19 -6
  198. package/skills/guide/SKILL.md +245 -103
  199. package/skills/guide/references/integration-tree.md +33 -18
  200. package/skills/guide/references/merge-policy.md +7 -2
  201. package/skills/guide/references/operator-api.md +48 -25
  202. package/skills/guide/references/optimization-nodes.md +10 -8
  203. package/skills/guide/references/plugin-authoring.md +46 -18
  204. package/skills/guide/references/remote-store-protocol.md +51 -12
  205. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  206. package/skills/guide/references/restacking.md +48 -3
  207. package/skills/guide/references/setup.md +2 -1
  208. package/skills/guide/references/ticket-migration.md +2 -2
  209. package/skills/operate/SKILL.md +114 -65
  210. package/skills/plan/SKILL.md +4 -3
  211. package/skills/spec/SKILL.md +9 -5
  212. package/skills/tickets/SKILL.md +25 -17
  213. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,14 @@
1
1
  import { StoreWriteTooLargeError } from './errors'
2
+ import {
3
+ RemoteUnavailableError,
4
+ fetchWithRetry,
5
+ isTransientStatus,
6
+ resolveRemoteRetry,
7
+ responseAttempts,
8
+ type RemoteRetryOptions,
9
+ type RemoteRetryPolicy,
10
+ type RetrySafety,
11
+ } from './retry'
2
12
  import {
3
13
  BUILD_CREATION_KEY_CAPABILITY,
4
14
  DISPATCH_PLACEMENT_CAPABILITY,
@@ -6,6 +16,7 @@ import {
6
16
  dispatchPlacementSchema,
7
17
  } from './protocol'
8
18
  import type { DispatchPlacement } from '../../kernel/dispatch-placement'
19
+ import { creationBuildSlug } from '../../kernel/build-creation'
9
20
  import { scanCadenceSchema, type ScanCadence } from '../scan-cadence'
10
21
  import { nodeRewriteWireSchema } from './protocol'
11
22
  import { z } from 'zod'
@@ -234,8 +245,12 @@ export interface RemoteBuildStoreOptions {
234
245
  fetchFn?: typeof fetch
235
246
  /** Test seam for exercising package/protocol skew diagnostics. */
236
247
  identity?: Partial<RemoteStoreIdentity>
248
+ /** Transient-failure retries; `false` makes a single attempt. */
249
+ retry?: RemoteRetryOptions
237
250
  }
238
251
 
252
+ type Safety = RetrySafety | (() => Promise<RetrySafety>)
253
+
239
254
  export class RemoteBuildStore implements BuildStore {
240
255
  readonly catalogIdentity = READ_CATALOG_IDENTITY
241
256
  readonly networkReads = true
@@ -243,9 +258,11 @@ export class RemoteBuildStore implements BuildStore {
243
258
  private readonly token: string | undefined
244
259
  private readonly fetchFn: typeof fetch
245
260
  private readonly identity: RemoteStoreIdentity
261
+ private readonly retry: RemoteRetryPolicy | false
246
262
 
247
263
  constructor(opts: RemoteBuildStoreOptions) {
248
264
  this.base = opts.url.replace(/\/+$/, '')
265
+ this.retry = resolveRemoteRetry(opts.retry)
249
266
  this.token = opts.token
250
267
  this.fetchFn = opts.fetchFn ?? fetch
251
268
  this.identity = {
@@ -347,6 +364,10 @@ export class RemoteBuildStore implements BuildStore {
347
364
  body?: unknown,
348
365
  signal?: AbortSignal,
349
366
  capabilities: Record<string, string> = {},
367
+ safety: Safety = method === 'POST' ? 'unsafe' : 'idempotent',
368
+ /** After a retry ends in a non-transient answer, a `GET` path whose ok
369
+ * answer replaces it, read within the same retry bound. */
370
+ recoverPath?: (final: Response) => string | undefined,
350
371
  ): Promise<Response> {
351
372
  const headers: Record<string, string> = {
352
373
  ...capabilities,
@@ -357,14 +378,39 @@ export class RemoteBuildStore implements BuildStore {
357
378
  if (body !== undefined) headers['content-type'] = 'application/json'
358
379
  const serialized =
359
380
  body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body)
360
- const response = await this.fetchFn(`${this.base}${path}`, {
361
- method,
362
- headers,
363
- // A string body is already serialized JSON (the ticket-asset put sizes
364
- // its exact bytes before sending).
365
- ...(serialized !== undefined ? { body: serialized } : {}),
366
- ...(signal !== undefined ? { signal } : {}),
367
- })
381
+ // Retries (retry.ts): GET/PUT/DELETE and the POSTs a call site marks
382
+ // idempotent retry transient statuses and transport failures; any other
383
+ // POST retries only a 429 or a failure that provably preceded delivery.
384
+ const response = await fetchWithRetry(
385
+ (attemptSignal) =>
386
+ this.fetchFn(`${this.base}${path}`, {
387
+ method,
388
+ headers,
389
+ // A string body is already serialized JSON (the ticket-asset put sizes
390
+ // its exact bytes before sending).
391
+ ...(serialized !== undefined ? { body: serialized } : {}),
392
+ ...(attemptSignal !== undefined ? { signal: attemptSignal } : {}),
393
+ }),
394
+ {
395
+ safety,
396
+ ...(signal !== undefined ? { signal } : {}),
397
+ policy: this.retry,
398
+ ...(recoverPath
399
+ ? {
400
+ recover: (final: Response, bound: AbortSignal) => {
401
+ const target = recoverPath(final)
402
+ if (target === undefined) return undefined
403
+ const { 'content-type': _, ...read } = headers
404
+ return this.fetchFn(`${this.base}${target}`, {
405
+ method: 'GET',
406
+ headers: read,
407
+ signal: bound,
408
+ })
409
+ },
410
+ }
411
+ : {}),
412
+ },
413
+ )
368
414
  if (method !== 'GET' && response.status === 413)
369
415
  throw await this.toError(response, {
370
416
  method,
@@ -423,6 +469,11 @@ export class RemoteBuildStore implements BuildStore {
423
469
  if (response.status === 409 && /^stream ".+" is closed$/.test(message)) {
424
470
  return new StreamClosedError(message)
425
471
  }
472
+ if (isTransientStatus(response.status, body))
473
+ return new RemoteUnavailableError(message, {
474
+ status: response.status,
475
+ attempts: responseAttempts(response),
476
+ })
426
477
  // 404 carries the local adapters' message shape: `unknown build "slug"`.
427
478
  return new Error(message)
428
479
  }
@@ -433,17 +484,41 @@ export class RemoteBuildStore implements BuildStore {
433
484
  schema: { parse: (data: unknown) => T },
434
485
  body?: unknown,
435
486
  signal?: AbortSignal,
487
+ safety?: Safety,
436
488
  ): Promise<T> {
437
- const response = await this.raw(method, path, body, signal)
489
+ const response = await this.raw(method, path, body, signal, {}, safety)
438
490
  if (!response.ok) throw await this.toError(response)
439
491
  return schema.parse(await response.json())
440
492
  }
441
493
 
442
494
  async createBuild(input: NewBuildInput): Promise<BuildRecord> {
443
- return this.requestJson('POST', '/builds', buildRecordWireSchema, {
444
- ...input,
445
- ...(input.created ? { created: validateEventWrite(input.created) } : {}),
446
- })
495
+ const { creationKey } = input
496
+ const response = await this.raw(
497
+ 'POST',
498
+ '/builds',
499
+ {
500
+ ...input,
501
+ ...(input.created ? { created: validateEventWrite(input.created) } : {}),
502
+ },
503
+ undefined,
504
+ {},
505
+ // A keyed creation is retryable only where the server honors the key.
506
+ creationKey !== undefined
507
+ ? async () => ((await this.buildCreationIdentity()) === 'keyed' ? 'idempotent' : 'unsafe')
508
+ : 'unsafe',
509
+ // The server answers a repeated key with a conflict. After a retry that
510
+ // conflict means an earlier attempt landed and lost its response, so the
511
+ // build at the key's own slug, read within the retry bound, is this
512
+ // creation's result.
513
+ creationKey !== undefined
514
+ ? (final) =>
515
+ final.status === 409
516
+ ? this.buildPath(creationBuildSlug(input.repo, input.slug, creationKey))
517
+ : undefined
518
+ : undefined,
519
+ )
520
+ if (!response.ok) throw await this.toError(response)
521
+ return buildRecordWireSchema.parse(await response.json())
447
522
  }
448
523
 
449
524
  async getBuild(slug: string): Promise<BuildRecord | null> {
@@ -523,6 +598,8 @@ export class RemoteBuildStore implements BuildStore {
523
598
  expectedSeq,
524
599
  event: validateEventWrite(event),
525
600
  },
601
+ undefined,
602
+ 'idempotent',
526
603
  )
527
604
  return envelope as EventEnvelope<T> | null
528
605
  }
@@ -624,6 +701,8 @@ export class RemoteBuildStore implements BuildStore {
624
701
  ),
625
702
  },
626
703
  },
704
+ undefined,
705
+ 'idempotent',
627
706
  )
628
707
  if (result === null) return null
629
708
  return {
@@ -762,6 +841,8 @@ export class RemoteBuildStore implements BuildStore {
762
841
  `${this.buildPath(slug)}/node-writer/claim`,
763
842
  okResponseSchema,
764
843
  { holder, ttlMs },
844
+ undefined,
845
+ 'idempotent',
765
846
  )
766
847
  return result.ok
767
848
  }
@@ -772,6 +853,8 @@ export class RemoteBuildStore implements BuildStore {
772
853
  `${this.buildPath(slug)}/node-writer/heartbeat`,
773
854
  okResponseSchema,
774
855
  { holder },
856
+ undefined,
857
+ 'idempotent',
775
858
  )
776
859
  return result.ok
777
860
  }
@@ -784,6 +867,8 @@ export class RemoteBuildStore implements BuildStore {
784
867
  {
785
868
  holder,
786
869
  },
870
+ undefined,
871
+ 'idempotent',
787
872
  )
788
873
  }
789
874
 
@@ -793,6 +878,8 @@ export class RemoteBuildStore implements BuildStore {
793
878
  `${this.buildPath(slug)}/lease/claim`,
794
879
  okResponseSchema,
795
880
  { holder, ttlMs },
881
+ undefined,
882
+ 'idempotent',
796
883
  )
797
884
  return result.ok
798
885
  }
@@ -803,14 +890,23 @@ export class RemoteBuildStore implements BuildStore {
803
890
  `${this.buildPath(slug)}/lease/heartbeat`,
804
891
  okResponseSchema,
805
892
  { holder },
893
+ undefined,
894
+ 'idempotent',
806
895
  )
807
896
  return result.ok
808
897
  }
809
898
 
810
899
  async releaseLease(slug: string, holder: string): Promise<void> {
811
- await this.requestJson('POST', `${this.buildPath(slug)}/lease/release`, okResponseSchema, {
812
- holder,
813
- })
900
+ await this.requestJson(
901
+ 'POST',
902
+ `${this.buildPath(slug)}/lease/release`,
903
+ okResponseSchema,
904
+ {
905
+ holder,
906
+ },
907
+ undefined,
908
+ 'idempotent',
909
+ )
814
910
  }
815
911
 
816
912
  async getScanCadence(repo: string): Promise<ScanCadence | null> {
@@ -825,10 +921,17 @@ export class RemoteBuildStore implements BuildStore {
825
921
  cadence: ScanCadence,
826
922
  allowClockRollback = false,
827
923
  ): Promise<void> {
828
- await this.requestJson('POST', `${this.repoPath(repo)}/scan-cadence`, okResponseSchema, {
829
- cadence: scanCadenceSchema.parse(cadence),
830
- allowClockRollback,
831
- })
924
+ await this.requestJson(
925
+ 'POST',
926
+ `${this.repoPath(repo)}/scan-cadence`,
927
+ okResponseSchema,
928
+ {
929
+ cadence: scanCadenceSchema.parse(cadence),
930
+ allowClockRollback,
931
+ },
932
+ undefined,
933
+ 'idempotent',
934
+ )
832
935
  }
833
936
 
834
937
  async upsertOperatorPresence(
@@ -842,6 +945,7 @@ export class RemoteBuildStore implements BuildStore {
842
945
  operatorPresenceWireSchema,
843
946
  operatorPresenceBodySchema.parse(identity),
844
947
  signal ? AbortSignal.any([signal, AbortSignal.timeout(10_000)]) : AbortSignal.timeout(10_000),
948
+ 'idempotent',
845
949
  )
846
950
  }
847
951
 
@@ -868,7 +972,14 @@ export class RemoteBuildStore implements BuildStore {
868
972
  }
869
973
 
870
974
  async ensureRepo(repo: string): Promise<RepositoryRecord> {
871
- return this.requestJson('POST', '/repos', repositoryRecordWireSchema, { repo })
975
+ return this.requestJson(
976
+ 'POST',
977
+ '/repos',
978
+ repositoryRecordWireSchema,
979
+ { repo },
980
+ undefined,
981
+ 'idempotent',
982
+ )
872
983
  }
873
984
 
874
985
  async getRepo(repo: string): Promise<RepositoryRecord | null> {
@@ -901,6 +1012,8 @@ export class RemoteBuildStore implements BuildStore {
901
1012
  `${this.repoPath(repo)}/events/conditional`,
902
1013
  conditionalRepoEventResponseSchema,
903
1014
  { expectedSeq, event: validateRepositoryEventWrite(event) },
1015
+ undefined,
1016
+ 'idempotent',
904
1017
  )
905
1018
  return envelope as unknown as RepositoryEventEnvelope<T> | null
906
1019
  }
@@ -1057,10 +1170,17 @@ export class RemoteBuildStore implements BuildStore {
1057
1170
  if (scope.kind === 'rollup') return this.getRollupValue(scope, request)
1058
1171
  const { reducer } = resolveReducerValue(scope, request)
1059
1172
  const root = scope.kind === 'build' ? this.buildPath(scope.slug) : this.repoPath(scope.repo)
1060
- const response = await this.raw('POST', `${root}/reducer-values`, request, undefined, {
1061
- [REDUCER_VALUE_PROJECTION_HEADER]: '1',
1062
- [CATALOG_IDENTITY_HEADER]: REDUCER_VALUE_CONTRACT_IDENTITY,
1063
- })
1173
+ const response = await this.raw(
1174
+ 'POST',
1175
+ `${root}/reducer-values`,
1176
+ request,
1177
+ undefined,
1178
+ {
1179
+ [REDUCER_VALUE_PROJECTION_HEADER]: '1',
1180
+ [CATALOG_IDENTITY_HEADER]: REDUCER_VALUE_CONTRACT_IDENTITY,
1181
+ },
1182
+ 'idempotent',
1183
+ )
1064
1184
  if (!response.ok) throw await this.toError(response)
1065
1185
  let body: unknown
1066
1186
  try {
@@ -1120,7 +1240,14 @@ export class RemoteBuildStore implements BuildStore {
1120
1240
  // Reject invalid arguments before the network.
1121
1241
  def.args.parse(parsed.args ?? {})
1122
1242
  def.read.parse(parsed.read ?? {})
1123
- const response = await this.raw('POST', `${this.repoPath(scope.repo)}/rollup-values`, parsed)
1243
+ const response = await this.raw(
1244
+ 'POST',
1245
+ `${this.repoPath(scope.repo)}/rollup-values`,
1246
+ parsed,
1247
+ undefined,
1248
+ {},
1249
+ 'idempotent',
1250
+ )
1124
1251
  const fail = (serverVersion: number | undefined, reason: string): never => {
1125
1252
  throw new ReducerValueIncompatibilityError(
1126
1253
  parsed.reducer,
@@ -1563,6 +1690,8 @@ export class RemoteBuildStore implements BuildStore {
1563
1690
  `${this.repoPath(repo)}/lease/claim`,
1564
1691
  okResponseSchema,
1565
1692
  { holder, ttlMs },
1693
+ undefined,
1694
+ 'idempotent',
1566
1695
  )
1567
1696
  return result.ok
1568
1697
  }
@@ -1573,14 +1702,23 @@ export class RemoteBuildStore implements BuildStore {
1573
1702
  `${this.repoPath(repo)}/lease/heartbeat`,
1574
1703
  okResponseSchema,
1575
1704
  { holder },
1705
+ undefined,
1706
+ 'idempotent',
1576
1707
  )
1577
1708
  return result.ok
1578
1709
  }
1579
1710
 
1580
1711
  async releaseRepoLease(repo: string, holder: string): Promise<void> {
1581
- await this.requestJson('POST', `${this.repoPath(repo)}/lease/release`, okResponseSchema, {
1582
- holder,
1583
- })
1712
+ await this.requestJson(
1713
+ 'POST',
1714
+ `${this.repoPath(repo)}/lease/release`,
1715
+ okResponseSchema,
1716
+ {
1717
+ holder,
1718
+ },
1719
+ undefined,
1720
+ 'idempotent',
1721
+ )
1584
1722
  }
1585
1723
 
1586
1724
  // ── Operator sessions (SPEC §7.1.1) ──────────────────────────────────
@@ -1634,6 +1772,8 @@ export class RemoteBuildStore implements BuildStore {
1634
1772
  expectedSeq,
1635
1773
  event: { actor: event.actor, type: event.type, payload: event.payload },
1636
1774
  },
1775
+ undefined,
1776
+ 'idempotent',
1637
1777
  )
1638
1778
  return envelope as SessionEventEnvelope<T> | null
1639
1779
  }
@@ -1,7 +1,15 @@
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'
4
+ import {
5
+ CURRENT_REDUCER_VALUES,
6
+ projectReducerValue,
7
+ propEntries,
8
+ unionCandidates,
9
+ projectsOnto,
10
+ type ReducerValueCatalog,
11
+ } from '../reducer-value-validation'
12
+ import { RELEASED_VALUE_POLICY_BY_SITE, type ReleasedValuePolicy } from './released-value-policy'
5
13
  import {
6
14
  RELEASED_CLIENTS,
7
15
  releaseLine,
@@ -152,7 +160,8 @@ export function healthIdentity(
152
160
  }
153
161
  }
154
162
 
155
- /** A successful server answer cannot be represented by this client's reducer. */
163
+ /** A successful server answer cannot be represented by this client's reducer.
164
+ * Terminal for every reader: retrying cannot make the value representable. */
156
165
  export class ReducerValueIncompatibilityError extends Error {
157
166
  override readonly name = 'ReducerValueIncompatibilityError'
158
167
  constructor(
@@ -163,15 +172,17 @@ export class ReducerValueIncompatibilityError extends Error {
163
172
  readonly reason: string,
164
173
  ) {
165
174
  super(
166
- `incompatible reducer ${reducer}: client version ${clientVersion}, server version ${serverVersion ?? '(unavailable)'}; ${reason}`,
175
+ `incompatible reducer ${reducer}: client version ${clientVersion}, server version ${serverVersion ?? '(unavailable)'}; ${reason}; Autobuild ${AUTOBUILD_VERSION} cannot represent the server's answer — align this client with the service: upgrade the service first, then this project's @defrex/autobuild, or run the CLI that matches the service`,
167
176
  )
168
177
  }
169
178
  }
170
179
 
171
180
  /** Answer a published client as its release can read: project the canonical
172
- * value onto the release's frozen shape and stamp the version it expects. A value
173
- * the release cannot represent is returned unchanged, so the client raises its
174
- * typed incompatibility error rather than misreading it. */
181
+ * value onto the release's frozen shape and stamp the version it expects.
182
+ * Widened literals at sites declared in the released-value policy are rewritten
183
+ * to an older equivalent or, when optional and descriptive, omitted. Any other
184
+ * value the release cannot represent is returned unchanged, so the client
185
+ * raises its typed incompatibility error rather than misreading it. */
175
186
  export function reducerValueForClient<T extends { version: number; value: unknown }>(
176
187
  client: {
177
188
  version: string | null
@@ -210,89 +221,135 @@ export function reducerValueForClient<T extends { version: number; value: unknow
210
221
  }
211
222
  }
212
223
 
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) {
224
+ const eventTypeIndexes = new WeakMap<ReducerValueCatalog, Map<string, string[]>>()
225
+ /** Object schemas of `catalog` keyed by their required literal `type`. Built
226
+ * once per (static) catalog, so the lookup is bounded. */
227
+ function eventTypeIndex(catalog: ReducerValueCatalog): Map<string, string[]> {
228
+ let index = eventTypeIndexes.get(catalog)
229
+ if (index) return index
230
+ index = new Map()
231
+ for (const [id, shape] of Object.entries(catalog.schemas)) {
232
+ const type = shape.kind === 'object' ? shape.props?.type : undefined
233
+ const literal = type && !type.optional ? catalog.schemas[type.type] : undefined
234
+ if (literal?.kind !== 'literal' || typeof literal.value !== 'string') continue
235
+ index.set(literal.value, [...(index.get(literal.value) ?? []), id])
236
+ }
237
+ eventTypeIndexes.set(catalog, index)
238
+ return index
239
+ }
240
+
241
+ /** The catalog-directed walk covers nested build state without reading history.
242
+ *
243
+ * - Declared policy sites rewrite or omit widened literals (see
244
+ * `released-value-policy.ts`); refuse sites and undeclared values stay as
245
+ * they are, so the answer goes back unchanged.
246
+ * - An optional `lastEvent` the release cannot represent is omitted when its
247
+ * type is unknown to the release, or when it is a well-formed event under the
248
+ * server's own catalog whose payload carries values the release predates. A
249
+ * malformed display event is left in place, so the answer goes back
250
+ * unchanged and the client raises its typed error.
251
+ * - `seenTypes` keeps the members the release knows.
252
+ *
253
+ * Exported for the coverage sweep; servers call `reducerValueForClient`. */
254
+ export function projectReleasedValue(
255
+ name: string,
256
+ value: unknown,
257
+ catalog: ReducerValueCatalog,
258
+ policy: ReadonlyMap<string, ReleasedValuePolicy> = RELEASED_VALUE_POLICY_BY_SITE,
259
+ current: ReducerValueCatalog = CURRENT_REDUCER_VALUES,
260
+ ) {
217
261
  const root = catalog.roots[name]
218
262
  if (!root) return { path: '$', expected: 'known reducer' }
219
- function adapt(id: string, input: unknown): unknown {
220
- const shape = catalog.schemas[id]!
263
+ const schemas = catalog.schemas
264
+ const OMIT = Symbol('omit')
265
+ /** A declared older equivalent for a string the release cannot represent. */
266
+ function downgrade(path: string, input: unknown, type: string, optional: boolean): unknown {
267
+ if (typeof input !== 'string') return input
268
+ const entry = policy.get(`${name}:${path}`)
269
+ if (!entry || entry.kind === 'refuse' || projectsOnto(catalog, type, input)) return input
270
+ if (entry.kind === 'map') {
271
+ const target = entry.map[input]
272
+ return target !== undefined && projectsOnto(catalog, type, target) ? target : input
273
+ }
274
+ return optional && entry.values.includes(input) ? OMIT : input
275
+ }
276
+ function adapt(id: string, input: unknown, path: string): unknown {
277
+ const shape = schemas[id]!
221
278
  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
279
+ const members = unionCandidates(schemas, shape, input)
280
+ // Sole possible member: the root projection decides, exactly as a
281
+ // failed per-member check would have left the input unchanged.
282
+ if (members.length === 1) return adapt(members[0]!, input, path)
283
+ for (const member of members) {
284
+ const candidate = adapt(member, input, path)
285
+ if (projectsOnto(catalog, member, candidate)) return candidate
229
286
  }
230
287
  return input
231
288
  }
232
- if (shape.kind === 'array' && Array.isArray(input))
233
- return input.map((item) => adapt(shape.items as string, item))
289
+ if (shape.kind === 'array' && Array.isArray(input)) {
290
+ const items = shape.items as string
291
+ const out: unknown[] = []
292
+ for (const item of input) {
293
+ const next = downgrade(`${path}[]`, item, items, true)
294
+ if (next !== OMIT) out.push(adapt(items, next, `${path}[]`))
295
+ }
296
+ return out
297
+ }
234
298
  if (shape.kind !== 'object' || !input || typeof input !== 'object' || Array.isArray(input))
235
299
  return input
236
300
  const out = { ...input } as Record<string, unknown>
237
- for (const [key, prop] of Object.entries(shape.props ?? {})) {
301
+ for (const [key, prop] of propEntries(shape)) {
238
302
  if (!(key in out)) continue
303
+ const at = `${path}.${key}`
239
304
  if (key === 'lastEvent' && prop.optional) {
240
- const result = projectReducerValue('event', out[key], {
241
- ...catalog,
242
- roots: { event: { value: prop.type } },
243
- })
244
305
  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
- }
306
+ const adapted = adapt(prop.type, event, at)
258
307
  if (
259
- 'path' in result &&
308
+ !projectsOnto(catalog, prop.type, adapted) &&
260
309
  event &&
261
310
  typeof event === 'object' &&
262
311
  'type' in event &&
263
312
  typeof event.type === 'string' &&
264
- !knowsType(prop.type)
265
- ) {
313
+ (!knowsType(prop.type, event.type) || wellFormed(event.type, event))
314
+ )
266
315
  delete out[key]
267
- continue
268
- }
316
+ else out[key] = adapted
317
+ continue
269
318
  }
270
319
  // seenTypes is the set of event types this reader can act on, rather
271
320
  // than an event history. Retain its known members; compatibility facts
272
321
  // and sequence/progress remain the server's canonical answer.
273
322
  if (key === 'seenTypes' && Array.isArray(out[key])) {
274
- const array = catalog.schemas[prop.type]!
323
+ const array = schemas[prop.type]!
275
324
  if (array.kind === 'array') {
276
325
  out[key] = (out[key] as unknown[]).filter(
277
326
  (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
- ),
327
+ typeof type !== 'string' || projectsOnto(catalog, array.items as string, type),
286
328
  )
287
329
  continue
288
330
  }
289
331
  }
290
- out[key] = adapt(prop.type, out[key])
332
+ const next = downgrade(at, out[key], prop.type, prop.optional)
333
+ if (next === OMIT) delete out[key]
334
+ else out[key] = adapt(prop.type, next, at)
291
335
  }
292
336
  if (shape.index)
293
337
  for (const key of Object.keys(out))
294
- if (!Object.hasOwn(shape.props ?? {}, key)) out[key] = adapt(shape.index, out[key])
338
+ if (!Object.hasOwn(shape.props ?? {}, key))
339
+ out[key] = adapt(shape.index, out[key], `${path}[*]`)
295
340
  return out
296
341
  }
297
- return projectReducerValue(name, adapt(root.value, value), catalog)
342
+ /** Whether some variant of the release's slot declares this event type. */
343
+ function knowsType(id: string, type: string): boolean {
344
+ const variant = schemas[id]!
345
+ if (variant.kind === 'union')
346
+ return (variant.items as string[]).some((item) => knowsType(item, type))
347
+ const discriminant = variant.props?.type
348
+ return discriminant !== undefined && projectsOnto(catalog, discriminant.type, type)
349
+ }
350
+ /** Well formed under the server's own catalog as a variant of its type. */
351
+ function wellFormed(type: string, event: object): boolean {
352
+ return (eventTypeIndex(current).get(type) ?? []).some((id) => projectsOnto(current, id, event))
353
+ }
354
+ return projectReducerValue(name, adapt(root.value, value, '$'), catalog)
298
355
  }
@@ -11,9 +11,12 @@ export async function delegateCredential(
11
11
  storeRef: string,
12
12
  token: string | undefined,
13
13
  target: DelegateCredentialTarget,
14
+ /** Host fetch; a bounded dispatcher invocation passes one that cancels at
15
+ * its deadline. Absent ⇒ global `fetch`. */
16
+ fetchFn: typeof fetch = fetch,
14
17
  ): Promise<string> {
15
18
  if (!token) throw new Error('credential delegation requires parent authority')
16
- const response = await fetch(`${storeRef.replace(/\/$/, '')}/credentials/delegate`, {
19
+ const response = await fetchFn(`${storeRef.replace(/\/$/, '')}/credentials/delegate`, {
17
20
  method: 'POST',
18
21
  headers: {
19
22
  authorization: `Bearer ${token}`,
@@ -52,6 +52,9 @@ export const errorKindSchema = z.enum([
52
52
  'cursor-too-old',
53
53
  'checkpoint-integrity',
54
54
  'retired-seed-generation',
55
+ // The backing database is saturated (connection slots or pool acquisition)
56
+ // or the service is shutting down; retry after the `Retry-After` header.
57
+ 'unavailable',
55
58
  ])
56
59
  export type ErrorKind = z.infer<typeof errorKindSchema>
57
60
 
@@ -154,5 +154,27 @@
154
154
  "provenance": {
155
155
  "tag": "v1.11.1"
156
156
  }
157
+ },
158
+ {
159
+ "version": "1.12.0",
160
+ "publishedAt": "2026-11-30T20:20:02.645Z",
161
+ "protocol": "7",
162
+ "contract": "1.12.0.json",
163
+ "projects": true,
164
+ "catalogIdentity": "a381f7bfe8eb04827869e5b05fb19901c2d52867081de419f44f2e00005ef306",
165
+ "provenance": {
166
+ "tag": "v1.12.0"
167
+ }
168
+ },
169
+ {
170
+ "version": "1.13.0",
171
+ "publishedAt": "2026-12-01T15:42:48.303Z",
172
+ "protocol": "7",
173
+ "contract": "1.13.0.json",
174
+ "projects": true,
175
+ "catalogIdentity": "296b376e8c50e65257285bf62e107b70f6d888553fe96bc9cfad2f18bf29a25f",
176
+ "provenance": {
177
+ "tag": "v1.13.0"
178
+ }
157
179
  }
158
180
  ]