@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,6 +1,7 @@
1
1
  import type { JsonValue } from './reducer-values'
2
2
  import shapes from './reducer-value-shapes.json'
3
3
 
4
+ export type ReducerValueShape = Shape
4
5
  type Shape = {
5
6
  kind: string
6
7
  value?: unknown
@@ -13,6 +14,9 @@ export const REDUCER_VALUE_CONTRACT_IDENTITY = new Bun.CryptoHasher('sha256')
13
14
  .digest('hex')
14
15
  const schemas: Record<string, Shape> = shapes.schemas
15
16
 
17
+ /** This build's own generated catalog: the canonical shape the server serves. */
18
+ export const CURRENT_REDUCER_VALUES: ReducerValueCatalog = shapes
19
+
16
20
  /** A finished-value shape catalog: this build's generated one, or a frozen
17
21
  * catalog from a published release line. */
18
22
  export interface ReducerValueCatalog {
@@ -63,7 +67,7 @@ function matches(id: string, value: unknown, table = schemas): boolean {
63
67
  case 'boolean':
64
68
  return typeof value === 'boolean'
65
69
  case 'union':
66
- return (shape.items as string[]).some((item) => matches(item, value, table))
70
+ return unionCandidates(table, shape, value).some((item) => matches(item, value, table))
67
71
  case 'array':
68
72
  return (
69
73
  Array.isArray(value) && value.every((item) => matches(shape.items as string, item, table))
@@ -77,7 +81,7 @@ function matches(id: string, value: unknown, table = schemas): boolean {
77
81
  )
78
82
  return false
79
83
  const record = value as Record<string, unknown>
80
- for (const [key, prop] of Object.entries(shape.props!)) {
84
+ for (const [key, prop] of propEntries(shape)) {
81
85
  if (!(key in record) && prop.optional) continue
82
86
  if (!matches(prop.type, record[key], table)) return false
83
87
  }
@@ -92,6 +96,109 @@ function matches(id: string, value: unknown, table = schemas): boolean {
92
96
  }
93
97
  }
94
98
 
99
+ /** True only when union member `id` provably cannot accept `value`: a differing
100
+ * literal, `undefined` against a defined value, a non-object against an object,
101
+ * or an object whose required literal `type`/`t` discriminant the value lacks or
102
+ * contradicts. A cheap filter before the full structural trial; it never
103
+ * excludes a member that could succeed. */
104
+ export function discriminantMismatch(
105
+ table: Record<string, Shape>,
106
+ id: string,
107
+ value: unknown,
108
+ ): boolean {
109
+ const shape = table[id]!
110
+ switch (shape.kind) {
111
+ case 'literal':
112
+ return value !== shape.value
113
+ case 'undefined':
114
+ return value !== undefined
115
+ case 'object': {
116
+ if (
117
+ value === null ||
118
+ typeof value !== 'object' ||
119
+ Array.isArray(value) ||
120
+ Object.getPrototypeOf(value) !== Object.prototype
121
+ )
122
+ return true
123
+ for (const [key, literal] of discriminants(table, shape))
124
+ if (!(key in value) || (value as Record<string, unknown>)[key] !== literal) return true
125
+ return false
126
+ }
127
+ default:
128
+ return false
129
+ }
130
+ }
131
+
132
+ /** What `discriminantMismatch` can observe about a value, as a cache key. */
133
+ function discriminantKey(value: unknown): string | undefined {
134
+ if (value === null || typeof value !== 'object')
135
+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
136
+ ? `${typeof value}:${value}`
137
+ : typeof value === 'undefined'
138
+ ? 'undefined'
139
+ : undefined
140
+ if (Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) return 'other'
141
+ const record = value as Record<string, unknown>
142
+ const part = (key: string) => {
143
+ if (!(key in record)) return '-'
144
+ const item = record[key]
145
+ return typeof item === 'string' ? JSON.stringify(item) : undefined
146
+ }
147
+ const type = part('type')
148
+ const t = part('t')
149
+ return type === undefined || t === undefined ? undefined : `object:${type}:${t}`
150
+ }
151
+ const unionCandidateCache = new WeakMap<Shape, Map<string, string[]>>()
152
+ /** Union members not excluded by `discriminantMismatch`, in declaration order,
153
+ * cached per union shape and discriminant key. */
154
+ export function unionCandidates(
155
+ table: Record<string, Shape>,
156
+ shape: Shape,
157
+ value: unknown,
158
+ ): readonly string[] {
159
+ const items = shape.items as string[]
160
+ const key = discriminantKey(value)
161
+ if (key === undefined) return items.filter((item) => !discriminantMismatch(table, item, value))
162
+ let cache = unionCandidateCache.get(shape)
163
+ if (!cache) {
164
+ cache = new Map()
165
+ unionCandidateCache.set(shape, cache)
166
+ }
167
+ let found = cache.get(key)
168
+ if (!found) {
169
+ found = items.filter((item) => !discriminantMismatch(table, item, value))
170
+ if (cache.size < 256) cache.set(key, found)
171
+ }
172
+ return found
173
+ }
174
+
175
+ const discriminantCache = new WeakMap<Shape, readonly (readonly [string, unknown])[]>()
176
+ /** An object shape's required literal `type`/`t` props, computed once per shape. */
177
+ function discriminants(table: Record<string, Shape>, shape: Shape) {
178
+ let found = discriminantCache.get(shape)
179
+ if (found) return found
180
+ found = (['type', 't'] as const).flatMap((key) => {
181
+ const prop = shape.props?.[key]
182
+ const literal = prop && !prop.optional ? table[prop.type] : undefined
183
+ return literal?.kind === 'literal' ? [[key, literal.value] as const] : []
184
+ })
185
+ discriminantCache.set(shape, found)
186
+ return found
187
+ }
188
+ const propEntryCache = new WeakMap<
189
+ Shape,
190
+ readonly [string, { type: string; optional: boolean }][]
191
+ >()
192
+ /** Declared properties of an object shape, computed once per (immutable) shape. */
193
+ export function propEntries(shape: Shape) {
194
+ let entries = propEntryCache.get(shape)
195
+ if (!entries) {
196
+ entries = Object.entries(shape.props ?? {})
197
+ propEntryCache.set(shape, entries)
198
+ }
199
+ return entries
200
+ }
201
+
95
202
  export interface ValidationFailure {
96
203
  path: string
97
204
  expected: string
@@ -170,7 +277,7 @@ function diagnose(id: string, value: unknown, path: string, depth: number): Diag
170
277
  Object.getPrototypeOf(value) === Object.prototype
171
278
  ) {
172
279
  const record = value as Record<string, unknown>
173
- for (const [key, prop] of Object.entries(shape.props!)) {
280
+ for (const [key, prop] of propEntries(shape)) {
174
281
  if (!(key in record) && prop.optional) continue
175
282
  const found = diagnose(prop.type, record[key], property(path, key), depth + 1)
176
283
  if (found) return found
@@ -178,7 +285,11 @@ function diagnose(id: string, value: unknown, path: string, depth: number): Diag
178
285
  for (const key of Object.keys(record).sort()) {
179
286
  if (Object.hasOwn(shape.props!, key)) continue
180
287
  if (!shape.index)
181
- return { path: property(path, key), expected: 'no additional property', depth: depth + 1 }
288
+ return {
289
+ path: property(path, key),
290
+ expected: 'no additional property',
291
+ depth: depth + 1,
292
+ }
182
293
  const found = diagnose(shape.index, record[key], property(path, key), depth + 1)
183
294
  if (found) return found
184
295
  }
@@ -187,49 +298,61 @@ function diagnose(id: string, value: unknown, path: string, depth: number): Diag
187
298
  }
188
299
 
189
300
  type Projected = { value: unknown; dropped: number }
190
- type Unprojectable = Diagnostic
301
+ /** A diagnostic location, rendered only when a projection fails. */
302
+ type At = { up: At; key: string | number } | null
303
+ function render(at: At): string {
304
+ return at === null
305
+ ? '$'
306
+ : typeof at.key === 'number'
307
+ ? `${render(at.up)}[${at.key}]`
308
+ : property(render(at.up), at.key)
309
+ }
310
+ /** `shape` names the expected kind; it is rendered only for the reported failure. */
311
+ type Unprojectable = { at: At; depth: number; shape: Shape }
312
+ const expected = (shape: Shape) =>
313
+ shape.kind === 'literal' ? JSON.stringify(shape.value) : shape.kind
191
314
  type Projection = Projected | Unprojectable
192
315
  // Plugin consumers may compile without strict narrowing; `in` guards narrow everywhere.
193
- const failed = (result: Projection): result is Unprojectable => 'path' in result
316
+ const failed = (result: Projection): result is Unprojectable => 'at' in result
194
317
 
195
318
  /** Project a value onto a catalog's shape, dropping object properties the shape
196
319
  * does not know. Additive server fields then reach older readers as the value
197
320
  * they were built for, while a missing field or unknown variant still fails.
198
- * Among union members, the one dropping the fewest properties wins. */
321
+ * Among union members, the one dropping the fewest properties wins.
322
+ *
323
+ * A projection that drops nothing is exactly a match, and returns the input
324
+ * itself; composites recurse once instead of revalidating every subtree at each
325
+ * level, so the cost stays linear in the value's size. */
199
326
  function project(
200
327
  table: Record<string, Shape>,
201
328
  id: string,
202
329
  value: unknown,
203
- path: string,
330
+ at: At,
204
331
  depth: number,
205
332
  ): Projection {
206
- if (matches(id, value, table)) return { value, dropped: 0 }
207
333
  const shape = table[id]!
208
- const failure: Unprojectable = {
209
- path,
210
- depth,
211
- expected: shape.kind === 'literal' ? JSON.stringify(shape.value) : shape.kind,
212
- }
334
+ const composite = shape.kind === 'union' || shape.kind === 'array' || shape.kind === 'object'
335
+ if (!composite && matches(id, value, table)) return { value, dropped: 0 }
336
+ const failure = (): Unprojectable => ({ at, depth, shape })
213
337
  if (shape.kind === 'union') {
214
- let best: Projection | undefined
215
- for (const item of shape.items as string[]) {
216
- const next = project(table, item, value, path, depth)
217
- if (!failed(next)) {
218
- if (!best || failed(best) || next.dropped < best.dropped) best = next
219
- } else if (!best || (failed(best) && next.depth > best.depth)) best = next
220
- }
221
- return best ?? failure
338
+ // Members that provably cannot succeed are skipped; when nothing succeeds,
339
+ // the unfiltered trial reproduces the deepest-failure diagnostic exactly.
340
+ const items = shape.items as string[]
341
+ const candidates = unionCandidates(table, shape, value)
342
+ const best = projectUnion(table, candidates, value, at, depth)
343
+ if (best && !failed(best)) return best
344
+ return projectUnion(table, items, value, at, depth) ?? failure()
222
345
  }
223
346
  if (shape.kind === 'array' && Array.isArray(value)) {
224
347
  const items: unknown[] = []
225
348
  let dropped = 0
226
349
  for (let i = 0; i < value.length; i++) {
227
- const next = project(table, shape.items as string, value[i], `${path}[${i}]`, depth + 1)
350
+ const next = project(table, shape.items as string, value[i], { up: at, key: i }, depth + 1)
228
351
  if (failed(next)) return next
229
352
  items.push(next.value)
230
353
  dropped += next.dropped
231
354
  }
232
- return { value: items, dropped }
355
+ return { value: dropped ? items : value, dropped }
233
356
  }
234
357
  if (
235
358
  shape.kind === 'object' &&
@@ -240,27 +363,50 @@ function project(
240
363
  const record = value as Record<string, unknown>
241
364
  const out: Record<string, unknown> = {}
242
365
  let dropped = 0
243
- for (const [key, prop] of Object.entries(shape.props!)) {
366
+ for (const [key, prop] of propEntries(shape)) {
244
367
  if (!(key in record) && prop.optional) continue
245
- const next = project(table, prop.type, record[key], property(path, key), depth + 1)
368
+ const next = project(table, prop.type, record[key], { up: at, key }, depth + 1)
246
369
  if (failed(next)) return next
247
370
  if (key in record) out[key] = next.value
248
371
  dropped += next.dropped
249
372
  }
250
- for (const key of Object.keys(record).sort()) {
251
- if (Object.hasOwn(shape.props!, key)) continue
373
+ const extra = Object.keys(record).filter((key) => !Object.hasOwn(shape.props!, key))
374
+ if (extra.length > 1) extra.sort()
375
+ for (const key of extra) {
252
376
  if (!shape.index) {
253
377
  dropped += 1
254
378
  continue
255
379
  }
256
- const next = project(table, shape.index, record[key], property(path, key), depth + 1)
380
+ const next = project(table, shape.index, record[key], { up: at, key }, depth + 1)
257
381
  if (failed(next)) return next
258
382
  out[key] = next.value
259
383
  dropped += next.dropped
260
384
  }
261
- return { value: out, dropped }
385
+ return { value: dropped ? out : value, dropped }
262
386
  }
263
- return failure
387
+ return failure()
388
+ }
389
+
390
+ function projectUnion(
391
+ table: Record<string, Shape>,
392
+ items: readonly string[],
393
+ value: unknown,
394
+ at: At,
395
+ depth: number,
396
+ ): Projection | undefined {
397
+ let best: Projection | undefined
398
+ for (const item of items) {
399
+ const next = project(table, item, value, at, depth)
400
+ if (!failed(next)) {
401
+ if (!best || failed(best) || next.dropped < best.dropped) best = next
402
+ } else if (!best || (failed(best) && next.depth > best.depth)) best = next
403
+ }
404
+ return best
405
+ }
406
+
407
+ /** Whether schema `id` of `catalog` can represent `value` after projection. */
408
+ export function projectsOnto(catalog: ReducerValueCatalog, id: string, value: unknown): boolean {
409
+ return !failed(project(catalog.schemas, id, value, null, 0))
264
410
  }
265
411
 
266
412
  /** The reader-side contract for a server's canonical answer: the value as this
@@ -273,8 +419,10 @@ export function projectReducerValue(
273
419
  ): { value: unknown } | ValidationFailure {
274
420
  const root = Object.hasOwn(catalog.roots, name) ? catalog.roots[name] : undefined
275
421
  if (!root) return { path: '$', expected: 'known reducer' }
276
- const result = project(catalog.schemas, root.value, value, '$', 0)
277
- return failed(result) ? { path: result.path, expected: result.expected } : { value: result.value }
422
+ const result = project(catalog.schemas, root.value, value, null, 0)
423
+ return failed(result)
424
+ ? { path: render(result.at), expected: expected(result.shape) }
425
+ : { value: result.value }
278
426
  }
279
427
 
280
428
  /** Existing optional object fields keep their ordinary JSON omission semantics.
@@ -1,225 +1,57 @@
1
- import { CheckpointIntegrityError, REPOSITORY_TAIL_WINDOW } from './event-reads'
2
- import { READ_CATALOG_IDENTITY, projectStoredEvents } from '../events/compatibility'
3
- /** Named JSON answers over persisted incremental state. The event log remains authoritative. */
4
- import { z } from 'zod'
5
- import type { AbEvent } from '../events/catalog'
6
- import type { RepositoryEvent } from '../events/repository'
1
+ /** Named JSON answers over persisted incremental state, resolved against the
2
+ * complete catalog. The event log remains authoritative. */
3
+ import { READ_CATALOG_IDENTITY } from '../events/catalog-identity'
7
4
  import { REDUCERS } from '../kernel/reducer-registry'
8
- import type { IncrementalReducer } from '../kernel/incremental'
5
+ import type { SnapshotScope } from './snapshots'
9
6
  import {
10
- REDUCER_VALUE_SNAPSHOT_PREFIX,
11
- type ReducerSnapshot,
12
- type SnapshotScope,
13
- } from './snapshots'
7
+ parseValueRequest,
8
+ readResolvedReducerValue,
9
+ resolveRegisteredValue,
10
+ type ReducerValue,
11
+ type ReducerValueRequest,
12
+ type ReducerValueStorage,
13
+ } from './reducer-value-read'
14
14
 
15
- export const reducerValueRequestSchema = z
16
- .object({
17
- reducer: z.string().min(1).max(64),
18
- args: z.record(z.string(), z.json()).optional(),
19
- /** Read-time arguments: they shape a rollup's finished value without
20
- * creating a key (SPEC §7.7). Named reducers reject them. */
21
- read: z.record(z.string(), z.json()).optional(),
22
- })
23
- .strict()
24
- export type ReducerValueRequest = z.infer<typeof reducerValueRequestSchema>
25
- export type JsonValue = z.infer<ReturnType<typeof z.json>>
26
- export interface ReducerValue {
27
- catalogIdentity?: string
28
- version: number
29
- cursor: number
30
- value: JsonValue
31
- }
32
- export const reducerValueSchema = z
33
- .object({
34
- version: z.number().int().positive(),
35
- cursor: z.number().int().nonnegative(),
36
- value: z.json(),
37
- })
38
- .strict()
39
-
40
- export interface ValueCatalogEntry {
41
- scope: SnapshotScope['kind']
42
- args: z.ZodType
43
- validate(state: unknown): boolean
44
- adapt(events: readonly (AbEvent | RepositoryEvent)[]): readonly unknown[]
45
- value(state: unknown): JsonValue
46
- // biome-ignore lint/suspicious/noExplicitAny: heterogeneous executable catalog
47
- create(args: any): IncrementalReducer<any, any, any>
48
- }
49
-
50
- export function canonical(value: unknown): string {
51
- if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
52
- if (value !== null && typeof value === 'object')
53
- return `{${Object.entries(value)
54
- .sort(([a], [b]) => a.localeCompare(b))
55
- .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
56
- .join(',')}}`
57
- return JSON.stringify(value)
58
- }
15
+ export {
16
+ canonical,
17
+ parseValueRequest,
18
+ readResolvedReducerValue,
19
+ reducerValueRequestSchema,
20
+ reducerValueSchema,
21
+ resolveRegisteredValue,
22
+ type JsonValue,
23
+ type ReducerValue,
24
+ type ReducerValueRequest,
25
+ type ReducerValueStorage,
26
+ type ResolvedReducerValue,
27
+ type ValueCacheRow,
28
+ type ValueCatalogEntry,
29
+ } from './reducer-value-read'
59
30
 
60
31
  export function resolveReducerValue(
61
32
  scope: SnapshotScope,
62
33
  input: ReducerValueRequest,
63
34
  catalogIdentity = READ_CATALOG_IDENTITY,
64
35
  ) {
65
- const request = reducerValueRequestSchema.parse(input)
66
- if (request.read !== undefined)
67
- throw new Error(`reducer "${request.reducer}" takes no read-time arguments`)
36
+ const request = parseValueRequest(input)
68
37
  const registration = Object.hasOwn(REDUCERS, request.reducer)
69
38
  ? REDUCERS[request.reducer]
70
39
  : undefined
71
- if (!registration) throw new Error(`unknown reducer "${request.reducer}"`)
72
- const entry = registration.valueRead
73
- if ('excluded' in entry)
74
- throw new Error(`excluded reducer "${request.reducer}": ${entry.excluded}`)
75
- if (entry.scope !== scope.kind) throw new Error(`wrong scope for reducer "${request.reducer}"`)
76
- const args = entry.args.parse(request.args ?? {})
77
- const reducer = entry.create(args)
78
- const identity = canonical({
79
- scope,
80
- reducer: request.reducer,
81
- version: reducer.version,
82
- catalogIdentity,
83
- args,
84
- })
85
- // v2 ignores checkpoints from the former client-writable key format.
86
- const key = `${REDUCER_VALUE_SNAPSHOT_PREFIX}v2.${new Bun.CryptoHasher('sha256').update(identity).digest('hex').slice(0, 54)}`
87
- return { name: request.reducer, reducer, identity, key, entry }
40
+ return resolveRegisteredValue(scope, request, registration, catalogIdentity)
88
41
  }
89
42
 
90
- /** Raw cache reads and conditional repairs are private adapter operations: clients
91
- * cannot submit a new accumulator through the value API. `token` identifies the
92
- * exact row read, including malformed bytes that could not be decoded. */
93
- export interface ValueCacheRow {
94
- snapshot: ReducerSnapshot
95
- token: string
96
- }
97
- export interface ReducerValueStorage {
98
- checkpoints?: {
99
- publish(key: string, snapshot: ReducerSnapshot, checkpoints: ReducerSnapshot[]): Promise<void>
100
- coverage(key: string, cursor: number): Promise<boolean>
101
- latest(key: string, through: number): Promise<ReducerSnapshot | null>
102
- }
103
- highWater(): Promise<number>
104
- read(key: string): Promise<ValueCacheRow | null>
105
- events(since: number, through: number): Promise<(AbEvent | RepositoryEvent)[]>
106
- put(key: string, snapshot: ReducerSnapshot): Promise<boolean>
107
- repair(key: string, observed: ValueCacheRow, snapshot: ReducerSnapshot): Promise<boolean>
108
- }
109
-
110
- export async function readReducerValue(
43
+ export function readReducerValue(
111
44
  scope: SnapshotScope,
112
45
  request: ReducerValueRequest,
113
46
  storage: ReducerValueStorage,
114
47
  ): Promise<ReducerValue> {
115
- const { reducer, identity, key, entry } = resolveReducerValue(scope, request)
116
- let boundary = await storage.highWater()
117
- let row: ValueCacheRow | null = null
48
+ // Not `async`: returning the inner promise directly keeps the read's
49
+ // microtask timing identical to the single-function body it replaced.
50
+ let resolved: ReturnType<typeof resolveReducerValue>
118
51
  try {
119
- row = await storage.read(key)
120
- } catch {
121
- if (storage.checkpoints) throw new CheckpointIntegrityError('unreadable canonical stream seed')
122
- /* unreadable cache is a miss */
123
- }
124
- // A concurrent reader may have persisted beyond our first boundary. Only a
125
- // fresh authoritative boundary can establish ahead-of-log poison.
126
- if (row && row.snapshot.cursor > boundary) boundary = await storage.highWater()
127
- let acc = reducer.initial()
128
- let cursor = 0
129
- let valid = false
130
- if (row) {
131
- const { snapshot } = row
132
- const state = snapshot.state as { identity?: unknown; acc?: unknown } | null
133
- try {
134
- valid =
135
- snapshot.version === reducer.version &&
136
- Number.isSafeInteger(snapshot.cursor) &&
137
- snapshot.cursor >= 0 &&
138
- snapshot.cursor <= boundary &&
139
- state !== null &&
140
- typeof state === 'object' &&
141
- state.identity === identity &&
142
- entry.validate(state.acc)
143
- } catch {
144
- valid = false // malformed nested cache data must never prevent replay
145
- }
146
- if (valid) {
147
- acc = structuredClone(state!.acc)
148
- cursor = snapshot.cursor
149
- }
150
- }
151
- if (storage.checkpoints && row && !valid)
152
- throw new CheckpointIntegrityError('corrupt canonical stream seed')
153
- let recovering = false
154
- if (storage.checkpoints && valid && !(await storage.checkpoints.coverage(key, cursor))) {
155
- // A pre-checkpoint server may advance the shared canonical row during a
156
- // rolling deploy or rollback. Its accumulator cannot supply the missing
157
- // intermediate seeds. Refold only the uncovered suffix under the seed lock.
158
- const checkpoint = await storage.checkpoints.latest(key, cursor)
159
- if (checkpoint) {
160
- const state = checkpoint.state as { identity?: unknown; acc?: unknown } | null
161
- if (
162
- checkpoint.version !== reducer.version ||
163
- !Number.isSafeInteger(checkpoint.cursor) ||
164
- checkpoint.cursor < 0 ||
165
- checkpoint.cursor > cursor ||
166
- state?.identity !== identity ||
167
- !entry.validate(state.acc)
168
- )
169
- throw new CheckpointIntegrityError('corrupt recovery stream-seed checkpoint')
170
- acc = structuredClone(state.acc)
171
- cursor = checkpoint.cursor
172
- } else {
173
- // Initial legacy adoption with no checkpoint to resume from.
174
- acc = reducer.initial()
175
- cursor = 0
176
- }
177
- recovering = true
178
- }
179
- const start = cursor
180
- const delta = (await storage.events(cursor, boundary)).filter((event) => event.seq <= boundary)
181
- for (const event of delta) {
182
- if (event.seq !== cursor + 1) throw new Error('noncontiguous reducer log')
183
- cursor = event.seq
184
- }
185
- if (cursor !== boundary) throw new Error('incomplete reducer log')
186
- const checkpoints: ReducerSnapshot[] = []
187
- if (storage.checkpoints) {
188
- const oldest = Math.max(0, boundary - REPOSITORY_TAIL_WINDOW)
189
- const prefix = delta.filter((event) => event.seq <= oldest)
190
- acc = reducer.advance(acc, entry.adapt(projectStoredEvents(prefix)))
191
- if (start <= oldest)
192
- checkpoints.push({
193
- version: reducer.version,
194
- cursor: oldest,
195
- state: { identity, acc: structuredClone(acc) },
196
- })
197
- for (const event of delta) {
198
- if (event.seq <= oldest) continue
199
- acc = reducer.advance(acc, entry.adapt(projectStoredEvents([event])))
200
- checkpoints.push({
201
- version: reducer.version,
202
- cursor: event.seq,
203
- state: { identity, acc: structuredClone(acc) },
204
- })
205
- }
206
- } else acc = reducer.advance(acc, entry.adapt(projectStoredEvents(delta)))
207
- const value = entry.value(reducer.finish(acc))
208
- if (!valid || recovering || delta.length > 0) {
209
- const next = { version: reducer.version, cursor, state: { identity, acc } }
210
- if (storage.checkpoints) {
211
- await storage.checkpoints.publish(key, next, checkpoints)
212
- return { version: reducer.version, cursor, value, catalogIdentity: READ_CATALOG_IDENTITY }
213
- }
214
- try {
215
- if (row && !valid && row.snapshot.version === reducer.version)
216
- await storage.repair(key, row, next)
217
- else if (row && !valid && row.snapshot.version !== reducer.version) {
218
- /* foreign cache is read-only */
219
- } else await storage.put(key, next)
220
- } catch {
221
- /* best-effort cache; log and reduction errors propagate */
222
- }
52
+ resolved = resolveReducerValue(scope, request)
53
+ } catch (error) {
54
+ return Promise.reject(error)
223
55
  }
224
- return { version: reducer.version, cursor, value, catalogIdentity: READ_CATALOG_IDENTITY }
56
+ return readResolvedReducerValue(resolved, storage)
225
57
  }