@defrex/autobuild 1.11.0 → 1.12.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 (110) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +186 -57
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +76 -10
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +13 -11
  8. package/docs/dispatcher.md +5 -4
  9. package/docs/integration-tree.md +28 -16
  10. package/docs/operator-api.md +4 -4
  11. package/docs/operator-surfaces.md +38 -3
  12. package/docs/optimization-nodes.md +3 -2
  13. package/docs/tickets.md +1 -1
  14. package/docs/troubleshooting.md +1 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/ambient-errors.ts +17 -0
  17. package/packages/core/src/cli/bounded-io.ts +174 -0
  18. package/packages/core/src/cli/dashboard/header.ts +10 -0
  19. package/packages/core/src/cli/dashboard/model.ts +81 -23
  20. package/packages/core/src/cli/dashboard/poll.ts +24 -34
  21. package/packages/core/src/cli/dashboard/render.ts +44 -37
  22. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  23. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  24. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  25. package/packages/core/src/cli/dispatch-frontend.ts +12 -3
  26. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  27. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  28. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  29. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  30. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  31. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  32. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  33. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  34. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  35. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  36. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  37. package/packages/core/src/cli/dispatch.ts +70 -9
  38. package/packages/core/src/cli/env.ts +2 -15
  39. package/packages/core/src/cli/help.ts +5 -4
  40. package/packages/core/src/cli/main.ts +4 -2
  41. package/packages/core/src/cli/production-store.ts +102 -0
  42. package/packages/core/src/cli/repo-state.ts +2 -3
  43. package/packages/core/src/cli/repository-status.ts +36 -28
  44. package/packages/core/src/cli/sessionless-store.ts +26 -0
  45. package/packages/core/src/cli/status.ts +169 -40
  46. package/packages/core/src/cli/store-opening.ts +15 -58
  47. package/packages/core/src/cli/store-ref.ts +6 -1
  48. package/packages/core/src/config/schema.ts +1 -1
  49. package/packages/core/src/distribution-packaging.ts +156 -18
  50. package/packages/core/src/events/catalog-identity.ts +28 -0
  51. package/packages/core/src/events/catalog.ts +3 -9
  52. package/packages/core/src/events/compatibility.ts +2 -30
  53. package/packages/core/src/events/payloads.ts +11 -0
  54. package/packages/core/src/events/policy.ts +3 -0
  55. package/packages/core/src/events/repository.ts +1 -1
  56. package/packages/core/src/events/sessions.ts +1 -1
  57. package/packages/core/src/events/validation-error.ts +12 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +74 -30
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  63. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  64. package/packages/core/src/kernel/capacity-build.ts +21 -0
  65. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  67. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  68. package/packages/core/src/kernel/engine.ts +2 -8
  69. package/packages/core/src/kernel/measurement.ts +24 -0
  70. package/packages/core/src/kernel/read-facts.ts +9 -369
  71. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  72. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  73. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  74. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  75. package/packages/core/src/kernel/reducer.ts +57 -9
  76. package/packages/core/src/kernel/reopen-state.ts +10 -0
  77. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  78. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  79. package/packages/core/src/operator/presentation.ts +13 -0
  80. package/packages/core/src/operator/query.ts +47 -41
  81. package/packages/core/src/operator/registry.ts +3 -3
  82. package/packages/core/src/ports/workspace/fake.ts +15 -3
  83. package/packages/core/src/processes/dispatcher.ts +232 -75
  84. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  85. package/packages/core/src/store/local/capabilities.ts +115 -0
  86. package/packages/core/src/store/local/store.ts +86 -56
  87. package/packages/core/src/store/reduced-reads.ts +9 -1
  88. package/packages/core/src/store/reducer-value-read.ts +235 -0
  89. package/packages/core/src/store/reducer-value-shapes.json +3796 -3670
  90. package/packages/core/src/store/reducer-values.ts +36 -204
  91. package/packages/core/src/store/remote/released-clients.json +22 -0
  92. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  93. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  94. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  95. package/packages/core/src/store/rollup-lease.ts +41 -0
  96. package/packages/core/src/store/rollups.ts +7 -38
  97. package/packages/core/src/store/snapshots.ts +1 -1
  98. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  99. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  100. package/packages/core/src/testing/import-graph.ts +78 -0
  101. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  102. package/packages/core/src/testing/slot-agreement.ts +52 -0
  103. package/packages/core/src/web/assets/app.js +5 -5
  104. package/packages/core/src/web/repository-source.ts +6 -2
  105. package/skills/guide/SKILL.md +126 -47
  106. package/skills/guide/references/integration-tree.md +28 -16
  107. package/skills/guide/references/operator-api.md +4 -4
  108. package/skills/guide/references/optimization-nodes.md +3 -2
  109. package/skills/operate/SKILL.md +38 -20
  110. package/templates/hosted-service/package.json +2 -2
@@ -6,16 +6,9 @@ import {
6
6
  type OperatorIdentity,
7
7
  type OperatorPresence,
8
8
  } from '../operator-presence'
9
- import { READ_CATALOG_IDENTITY } from '../../events/compatibility'
10
- import { readPersistedBuildDigests } from '../reduced-reads'
9
+ import { READ_CATALOG_IDENTITY } from '../../events/catalog-identity'
11
10
  import { assertPublicSnapshotReducer } from '../snapshots'
12
- import {
13
- readReducerValue,
14
- resolveReducerValue,
15
- type ReducerValueRequest,
16
- type ReducerValue,
17
- } from '../reducer-values'
18
- import { validateTickFinish } from '../repo-tick'
11
+ import type { ReducerValueRequest, ReducerValue } from '../reducer-value-read'
19
12
  import {
20
13
  buildPageOrder,
21
14
  decodeBuildPageCursor,
@@ -37,7 +30,8 @@ import type { RepoTickCompletion, RepoTickFinish, RepoTickObservation } from '..
37
30
  * explicitly resolved local state root. Repository/default selection belongs
38
31
  * to the CLI; this adapter only opens the path it is given.
39
32
  *
40
- * Every write goes through `validateEventWrite` (§8 — the enforced ontology).
33
+ * Every write goes through `validateEventWrite` (§8 — the enforced ontology),
34
+ * loaded on first use (`./capabilities`) before the write's transaction.
41
35
  * Seq assignment and `appendWithArtifacts` are transactional: bun:sqlite
42
36
  * transactions are synchronous, so the atomic path (D6) runs inside one
43
37
  * `db.transaction` while blob writes happen *before* it — a rolled-back
@@ -52,26 +46,19 @@ import { access, copyFile, mkdtemp, rm } from 'node:fs/promises'
52
46
  import { tmpdir } from 'node:os'
53
47
  import { join } from 'node:path'
54
48
  import { humanActor } from '../../events/envelope'
55
- import {
56
- prepareEventWrite as validateEventWrite,
57
- type AbEvent,
58
- type EventEnvelope,
59
- type EventWrite,
60
- } from '../../events/catalog'
61
- import { eventPayloadSchemas, type EventType } from '../../events/payloads'
62
- import {
63
- prepareRepositoryEventWrite as validateRepositoryEventWrite,
64
- type RepositoryEvent,
65
- type RepositoryEventEnvelope,
66
- type RepositoryEventType,
67
- type RepositoryEventWrite,
49
+ import type { AbEvent, EventEnvelope, EventWrite } from '../../events/catalog'
50
+ import type { EventType } from '../../events/payloads'
51
+ import type {
52
+ RepositoryEvent,
53
+ RepositoryEventEnvelope,
54
+ RepositoryEventType,
55
+ RepositoryEventWrite,
68
56
  } from '../../events/repository'
69
- import {
70
- validateSessionEventWrite,
71
- type SessionEvent,
72
- type SessionEventEnvelope,
73
- type SessionEventType,
74
- type SessionEventWrite,
57
+ import type {
58
+ SessionEvent,
59
+ SessionEventEnvelope,
60
+ SessionEventType,
61
+ SessionEventWrite,
75
62
  } from '../../events/sessions'
76
63
  import { createBuildScopedStore } from '../build-scope'
77
64
  import type { ReducerSnapshot, ReducerValueScope, RollupScope, SnapshotScope } from '../snapshots'
@@ -81,17 +68,9 @@ import {
81
68
  ROLLUP_LEASE_WAIT_MS,
82
69
  RollupLeaseLostError,
83
70
  RollupLeaseTimeoutError,
84
- readRollupValue,
85
- type RollupAdvance,
86
- type RollupStorage,
87
- } from '../rollups'
88
- import { validateCreatedEvent } from '../new-build'
71
+ } from '../rollup-lease'
72
+ import type { RollupAdvance, RollupStorage } from '../rollups'
89
73
  import { createSessionScopedStore } from '../session-handle'
90
- import {
91
- REPOSITORY_STATE_EVENT_TYPES,
92
- REPOSITORY_LATEST_EVENT_TYPES,
93
- readRepoStateEventsWithAnchorRecheck,
94
- } from '../repo-state-events'
95
74
  import {
96
75
  DEFAULT_ARTIFACT_RETENTION_MAX_REVISIONS,
97
76
  isRetentionManagedKind,
@@ -99,7 +78,6 @@ import {
99
78
  } from '../retention'
100
79
  import { pollingSubscribe } from '../subscribe'
101
80
  import { StreamLocks } from '../streams/lock'
102
- import { assembleUIMessageDocument } from '../streams/assemble'
103
81
  import { EVENT_WAIT_POLL_MS, readEventsWithWait, readStreamWithWait } from '../streams/wait'
104
82
  import {
105
83
  serializedBatchSize,
@@ -150,19 +128,23 @@ import {
150
128
  HEAD as ASSET_HEAD,
151
129
  NEXT_NAME_SAME_KIND as ASSET_NEXT_NAME_SAME_KIND,
152
130
  } from './ticket-asset-heads'
153
- import {
154
- DEFAULT_TICKET_ASSET_LIMITS,
155
- loadTicketAsset,
156
- storeTicketAssetBlobs,
157
- resolvePinnedAsset,
158
- summarizeTicketAsset,
159
- validateTicketAssetInput,
160
- type TicketAsset,
161
- type TicketAssetInput,
162
- type TicketAssetLimits,
163
- type TicketAssetMeta,
164
- type TicketAssetSummary,
131
+ import type {
132
+ TicketAsset,
133
+ TicketAssetInput,
134
+ TicketAssetLimits,
135
+ TicketAssetMeta,
136
+ TicketAssetSummary,
165
137
  } from '../ticket-assets'
138
+ import {
139
+ buildDigests,
140
+ payloadSchemas,
141
+ reducedValues,
142
+ repositoryStateEvents,
143
+ rollups,
144
+ streamAssembly,
145
+ ticketAssetCapability,
146
+ writeValidation,
147
+ } from './capabilities'
166
148
  import { DirBlobStore } from './blobs'
167
149
  import {
168
150
  artifacts,
@@ -966,6 +948,7 @@ export class SqliteBuildStore implements BuildStore {
966
948
  }
967
949
 
968
950
  async createBuild(input: NewBuildInput): Promise<BuildRecord> {
951
+ const { validateCreatedEvent } = writeValidation.value ?? (await writeValidation.load())
969
952
  const created = validateCreatedEvent(input)
970
953
  const ts = this.now()
971
954
  return this.writeTx(() => {
@@ -1074,6 +1057,7 @@ export class SqliteBuildStore implements BuildStore {
1074
1057
  }
1075
1058
 
1076
1059
  async getNodeRewrite(slug: string, previous?: string, beforePrevious?: string) {
1060
+ const { eventPayloadSchemas } = payloadSchemas.value ?? (await payloadSchemas.load())
1077
1061
  this.requireBuild(slug)
1078
1062
  const row = (
1079
1063
  beforePrevious !== undefined
@@ -1100,6 +1084,7 @@ export class SqliteBuildStore implements BuildStore {
1100
1084
  }
1101
1085
 
1102
1086
  async listOpenBuilds(repo: string): Promise<OpenBuild[]> {
1087
+ const { readPersistedBuildDigests } = buildDigests.value ?? (await buildDigests.load())
1103
1088
  const records = this.db
1104
1089
  .select({ build: builds })
1105
1090
  .from(openBuilds)
@@ -1113,6 +1098,7 @@ export class SqliteBuildStore implements BuildStore {
1113
1098
  }
1114
1099
 
1115
1100
  async getRepoBuildDigests(repo: string): Promise<Map<string, BuildDigest>> {
1101
+ const { readPersistedBuildDigests } = buildDigests.value ?? (await buildDigests.load())
1116
1102
  return readPersistedBuildDigests(
1117
1103
  this,
1118
1104
  repo,
@@ -1169,6 +1155,7 @@ export class SqliteBuildStore implements BuildStore {
1169
1155
  }
1170
1156
 
1171
1157
  async append<T extends EventType>(slug: string, event: EventWrite<T>): Promise<EventEnvelope<T>> {
1158
+ const { validateEventWrite } = writeValidation.value ?? (await writeValidation.load())
1172
1159
  const validated = validateEventWrite(event)
1173
1160
  return this.writeTx(() => this.appendInTx(slug, validated)) as EventEnvelope<T>
1174
1161
  }
@@ -1178,6 +1165,7 @@ export class SqliteBuildStore implements BuildStore {
1178
1165
  expectedSeq: number,
1179
1166
  event: EventWrite<T>,
1180
1167
  ): Promise<EventEnvelope<T> | null> {
1168
+ const { validateEventWrite } = writeValidation.value ?? (await writeValidation.load())
1181
1169
  validateExpectedSeq(expectedSeq)
1182
1170
  const validated = validateEventWrite(event)
1183
1171
  return this.writeTx(() => {
@@ -1306,6 +1294,7 @@ export class SqliteBuildStore implements BuildStore {
1306
1294
  artifactInputs: ArtifactInput[],
1307
1295
  makeEvent: (deposited: ArtifactMeta[]) => EventWrite<T>,
1308
1296
  ): Promise<{ event: EventEnvelope<T>; artifacts: ArtifactMeta[] }> {
1297
+ const { validateEventWrite } = writeValidation.value ?? (await writeValidation.load())
1309
1298
  const prepared: PreparedArtifact[] = []
1310
1299
  for (const input of artifactInputs) {
1311
1300
  prepared.push(await this.prepareArtifact(input))
@@ -1339,6 +1328,7 @@ export class SqliteBuildStore implements BuildStore {
1339
1328
  artifactInputs: ArtifactInput[],
1340
1329
  makeEvent: (deposited: ArtifactMeta[]) => EventWrite<T>,
1341
1330
  ): Promise<{ event: EventEnvelope<T>; artifacts: ArtifactMeta[] } | null> {
1331
+ const { validateEventWrite } = writeValidation.value ?? (await writeValidation.load())
1342
1332
  validateExpectedSeq(expectedSeq)
1343
1333
  const prepared: PreparedArtifact[] = []
1344
1334
  for (const input of artifactInputs) {
@@ -1707,6 +1697,7 @@ export class SqliteBuildStore implements BuildStore {
1707
1697
  repo: string,
1708
1698
  event: RepositoryEventWrite<T>,
1709
1699
  ): Promise<RepositoryEventEnvelope<T>> {
1700
+ const { validateRepositoryEventWrite } = writeValidation.value ?? (await writeValidation.load())
1710
1701
  const validated = validateRepositoryEventWrite(event)
1711
1702
  return this.writeTx(() => this.appendRepoInTx(repo, validated)) as RepositoryEventEnvelope<T>
1712
1703
  }
@@ -1716,6 +1707,7 @@ export class SqliteBuildStore implements BuildStore {
1716
1707
  expectedSeq: number,
1717
1708
  event: RepositoryEventWrite<T>,
1718
1709
  ): Promise<RepositoryEventEnvelope<T> | null> {
1710
+ const { validateRepositoryEventWrite } = writeValidation.value ?? (await writeValidation.load())
1719
1711
  validateExpectedSeq(expectedSeq)
1720
1712
  const validated = validateRepositoryEventWrite(event)
1721
1713
  return this.writeTx(() => {
@@ -1781,6 +1773,7 @@ export class SqliteBuildStore implements BuildStore {
1781
1773
  event: RepositoryEventEnvelope<T>
1782
1774
  artifacts: RepositoryArtifactMeta[]
1783
1775
  }> {
1776
+ const { validateRepositoryEventWrite } = writeValidation.value ?? (await writeValidation.load())
1784
1777
  const prepared: PreparedArtifact[] = []
1785
1778
  for (const input of artifactInputs) {
1786
1779
  prepared.push(await this.prepareArtifact(input))
@@ -1911,10 +1904,27 @@ export class SqliteBuildStore implements BuildStore {
1911
1904
  scope: ReducerValueScope,
1912
1905
  request: ReducerValueRequest,
1913
1906
  ): Promise<ReducerValue> {
1914
- if (scope.kind === 'rollup') return readRollupValue(scope, request, this.rollupStorage(scope))
1915
- // Reject invalid requests before touching storage.
1916
- resolveReducerValue(scope, request)
1917
- return readReducerValue(scope, request, {
1907
+ if (scope.kind === 'rollup') {
1908
+ const { readRollupValue } = rollups.value ?? (await rollups.load())
1909
+ return readRollupValue(scope, request, this.rollupStorage(scope))
1910
+ }
1911
+ const {
1912
+ parseValueRequest,
1913
+ resolveRegisteredValue,
1914
+ readResolvedReducerValue,
1915
+ loadValueRegistration,
1916
+ loadedValueRegistration,
1917
+ } = reducedValues.value ?? (await reducedValues.load())
1918
+ // Reject invalid requests before touching storage. Only the requested
1919
+ // reducer's registration initializes; a loaded one adds no await.
1920
+ const parsed = parseValueRequest(request)
1921
+ const loaded = loadedValueRegistration(parsed.reducer)
1922
+ const resolved = resolveRegisteredValue(
1923
+ scope,
1924
+ parsed,
1925
+ loaded !== null ? loaded : await loadValueRegistration(parsed.reducer),
1926
+ )
1927
+ return readResolvedReducerValue(resolved, {
1918
1928
  highWater: async () => {
1919
1929
  const tail = this.snapshotTail(scope)
1920
1930
  if (tail === undefined) throw new Error('unknown reducer scope')
@@ -2231,6 +2241,11 @@ export class SqliteBuildStore implements BuildStore {
2231
2241
  }
2232
2242
 
2233
2243
  async getRepoStateEvents(repo: string): Promise<RepositoryEvent[]> {
2244
+ const {
2245
+ REPOSITORY_STATE_EVENT_TYPES,
2246
+ REPOSITORY_LATEST_EVENT_TYPES,
2247
+ readRepoStateEventsWithAnchorRecheck,
2248
+ } = repositoryStateEvents.value ?? (await repositoryStateEvents.load())
2234
2249
  this.requireRepo(repo)
2235
2250
  // Two queries, mirroring the oracle's derivation: the latest
2236
2251
  // run-started anchor, then one select of durable types plus the tail
@@ -2368,6 +2383,8 @@ export class SqliteBuildStore implements BuildStore {
2368
2383
  }
2369
2384
 
2370
2385
  async ticketAssetLimits(_repo: string): Promise<TicketAssetLimits> {
2386
+ const { DEFAULT_TICKET_ASSET_LIMITS } =
2387
+ ticketAssetCapability.value ?? (await ticketAssetCapability.load())
2371
2388
  return { ...DEFAULT_TICKET_ASSET_LIMITS }
2372
2389
  }
2373
2390
 
@@ -2390,6 +2407,8 @@ export class SqliteBuildStore implements BuildStore {
2390
2407
  ticketId: string,
2391
2408
  asset: TicketAssetInput,
2392
2409
  ): Promise<TicketAssetMeta> {
2410
+ const { validateTicketAssetInput, storeTicketAssetBlobs } =
2411
+ ticketAssetCapability.value ?? (await ticketAssetCapability.load())
2393
2412
  const size = validateTicketAssetInput(asset)
2394
2413
  const entries = await storeTicketAssetBlobs(this.blobs, asset.entries)
2395
2414
  return this.writeTx(() => {
@@ -2424,6 +2443,7 @@ export class SqliteBuildStore implements BuildStore {
2424
2443
  name: string,
2425
2444
  rev?: number,
2426
2445
  ): Promise<TicketAsset | null> {
2446
+ const { loadTicketAsset } = ticketAssetCapability.value ?? (await ticketAssetCapability.load())
2427
2447
  const scoped = ticketAssetKey(repo, ticketId, kind, name)
2428
2448
  const row =
2429
2449
  rev === undefined
@@ -2449,6 +2469,8 @@ export class SqliteBuildStore implements BuildStore {
2449
2469
  name: string,
2450
2470
  rev?: number,
2451
2471
  ): Promise<TicketAsset | null> {
2472
+ const { resolvePinnedAsset } =
2473
+ ticketAssetCapability.value ?? (await ticketAssetCapability.load())
2452
2474
  return resolvePinnedAsset(this, slug, kind, name, rev)
2453
2475
  }
2454
2476
 
@@ -2457,6 +2479,8 @@ export class SqliteBuildStore implements BuildStore {
2457
2479
  ticketId: string,
2458
2480
  opts?: { revisions?: boolean },
2459
2481
  ): Promise<TicketAssetSummary[]> {
2482
+ const { summarizeTicketAsset } =
2483
+ ticketAssetCapability.value ?? (await ticketAssetCapability.load())
2460
2484
  if (opts?.revisions) {
2461
2485
  return this.db
2462
2486
  .select()
@@ -2571,6 +2595,7 @@ export class SqliteBuildStore implements BuildStore {
2571
2595
  completion: RepoTickCompletion,
2572
2596
  events: RepositoryEventWrite[],
2573
2597
  ): Promise<RepoTickFinish | null> {
2598
+ const { validateTickFinish } = writeValidation.value ?? (await writeValidation.load())
2574
2599
  const validated = validateTickFinish(holder, completion, events)
2575
2600
  return this.writeTx(() => {
2576
2601
  const row = this.requireRepo(repo)
@@ -2718,6 +2743,7 @@ export class SqliteBuildStore implements BuildStore {
2718
2743
  }
2719
2744
 
2720
2745
  async createSession(input: NewSessionInput): Promise<SessionRecord> {
2746
+ const { validateSessionEventWrite } = writeValidation.value ?? (await writeValidation.load())
2721
2747
  const operator = normalizeOperator(input.operator)
2722
2748
  if (!input.repo) throw new Error('repo is required')
2723
2749
  const ts = this.now()
@@ -2789,6 +2815,7 @@ export class SqliteBuildStore implements BuildStore {
2789
2815
  id: string,
2790
2816
  event: SessionEventWrite<T>,
2791
2817
  ): Promise<SessionEventEnvelope<T>> {
2818
+ const { validateSessionEventWrite } = writeValidation.value ?? (await writeValidation.load())
2792
2819
  const validated = validateSessionEventWrite(event)
2793
2820
  return this.writeTx(() => this.appendSessionInTx(id, validated) as SessionEventEnvelope<T>)
2794
2821
  }
@@ -2798,6 +2825,7 @@ export class SqliteBuildStore implements BuildStore {
2798
2825
  expectedSeq: number,
2799
2826
  event: SessionEventWrite<T>,
2800
2827
  ): Promise<SessionEventEnvelope<T> | null> {
2828
+ const { validateSessionEventWrite } = writeValidation.value ?? (await writeValidation.load())
2801
2829
  validateExpectedSeq(expectedSeq)
2802
2830
  const validated = validateSessionEventWrite(event)
2803
2831
  return this.writeTx(() => {
@@ -2886,6 +2914,7 @@ export class SqliteBuildStore implements BuildStore {
2886
2914
  artifactInputs: ArtifactInput[],
2887
2915
  makeEvent: (deposited: SessionArtifactMeta[]) => SessionEventWrite<T>,
2888
2916
  ): Promise<{ event: SessionEventEnvelope<T>; artifacts: SessionArtifactMeta[] }> {
2917
+ const { validateSessionEventWrite } = writeValidation.value ?? (await writeValidation.load())
2889
2918
  const prepared: PreparedArtifact[] = []
2890
2919
  for (const input of artifactInputs) {
2891
2920
  prepared.push(await this.prepareArtifact(input))
@@ -3136,6 +3165,7 @@ export class SqliteBuildStore implements BuildStore {
3136
3165
  }
3137
3166
 
3138
3167
  async closeStream(streamId: string, outcome: StreamOutcome): Promise<StreamRecord> {
3168
+ const { assembleUIMessageDocument } = streamAssembly.value ?? (await streamAssembly.load())
3139
3169
  // The per-stream mutex holds across the entire prepare→commit loop
3140
3170
  // (AUT-348): a same-process append issued during this close waits for it
3141
3171
  // to finish and then rejects on the closed check with StreamClosedError.
@@ -11,7 +11,6 @@ import type {
11
11
  buildStreamSeedReducer,
12
12
  repositoryReadFactsReducer,
13
13
  } from '../kernel/read-facts'
14
- import { publicationStateReducer } from '../processes/publication-state'
15
14
  import type { SnapshotScope } from './snapshots'
16
15
 
17
16
  export class ReducerValueValidationError extends Error {
@@ -43,6 +42,9 @@ export async function readBuildFacts(store: Reader, slug: string) {
43
42
  'buildReadFacts',
44
43
  )
45
44
  const value = result.value
45
+ // A build reducer: repository readers of this module never initialize it.
46
+ // Once loaded, the read adds no await.
47
+ if (!publicationStateReducer) publicationStateReducer = await loadPublicationStateReducer()
46
48
  return {
47
49
  cursor: result.cursor,
48
50
  value: {
@@ -52,6 +54,12 @@ export async function readBuildFacts(store: Reader, slug: string) {
52
54
  },
53
55
  }
54
56
  }
57
+ let publicationStateReducer:
58
+ | typeof import('../processes/publication-state').publicationStateReducer
59
+ | undefined
60
+ async function loadPublicationStateReducer() {
61
+ return (await import('../processes/publication-state')).publicationStateReducer
62
+ }
55
63
  async function readValue<T>(
56
64
  store: Reader,
57
65
  scope: SnapshotScope,
@@ -0,0 +1,235 @@
1
+ import { CheckpointIntegrityError, REPOSITORY_TAIL_WINDOW } from './event-reads'
2
+ import { projectStoredEvents } from '../events/compatibility'
3
+ import { READ_CATALOG_IDENTITY } from '../events/catalog-identity'
4
+ /** Named JSON answers over persisted incremental state. The event log remains authoritative.
5
+ * This core never names the complete catalog: callers resolve a registration
6
+ * (`reducer-values.ts` over the registry, the local store through the selective
7
+ * index) and hand it to `resolveRegisteredValue`. */
8
+ import { z } from 'zod'
9
+ import type { AbEvent } from '../events/catalog'
10
+ import type { RepositoryEvent } from '../events/repository'
11
+ import type { RegisteredReducer } from '../kernel/reducer-value-entry'
12
+ import type { IncrementalReducer } from '../kernel/incremental'
13
+ import {
14
+ REDUCER_VALUE_SNAPSHOT_PREFIX,
15
+ type ReducerSnapshot,
16
+ type SnapshotScope,
17
+ } from './snapshots'
18
+
19
+ export const reducerValueRequestSchema = z
20
+ .object({
21
+ reducer: z.string().min(1).max(64),
22
+ args: z.record(z.string(), z.json()).optional(),
23
+ /** Read-time arguments: they shape a rollup's finished value without
24
+ * creating a key (SPEC §7.7). Named reducers reject them. */
25
+ read: z.record(z.string(), z.json()).optional(),
26
+ })
27
+ .strict()
28
+ export type ReducerValueRequest = z.infer<typeof reducerValueRequestSchema>
29
+ export type JsonValue = z.infer<ReturnType<typeof z.json>>
30
+ export interface ReducerValue {
31
+ catalogIdentity?: string
32
+ version: number
33
+ cursor: number
34
+ value: JsonValue
35
+ }
36
+ export const reducerValueSchema = z
37
+ .object({
38
+ version: z.number().int().positive(),
39
+ cursor: z.number().int().nonnegative(),
40
+ value: z.json(),
41
+ })
42
+ .strict()
43
+
44
+ export interface ValueCatalogEntry {
45
+ scope: SnapshotScope['kind']
46
+ args: z.ZodType
47
+ validate(state: unknown): boolean
48
+ adapt(events: readonly (AbEvent | RepositoryEvent)[]): readonly unknown[]
49
+ value(state: unknown): JsonValue
50
+ // biome-ignore lint/suspicious/noExplicitAny: heterogeneous executable catalog
51
+ create(args: any): IncrementalReducer<any, any, any>
52
+ }
53
+
54
+ export function canonical(value: unknown): string {
55
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
56
+ if (value !== null && typeof value === 'object')
57
+ return `{${Object.entries(value)
58
+ .sort(([a], [b]) => a.localeCompare(b))
59
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
60
+ .join(',')}}`
61
+ return JSON.stringify(value)
62
+ }
63
+
64
+ /** Parse a value request; named reducers take no read-time arguments. */
65
+ export function parseValueRequest(input: ReducerValueRequest): ReducerValueRequest {
66
+ const request = reducerValueRequestSchema.parse(input)
67
+ if (request.read !== undefined)
68
+ throw new Error(`reducer "${request.reducer}" takes no read-time arguments`)
69
+ return request
70
+ }
71
+
72
+ /** Validate a parsed request against its registration and derive its key. */
73
+ export function resolveRegisteredValue(
74
+ scope: SnapshotScope,
75
+ request: ReducerValueRequest,
76
+ registration: RegisteredReducer | undefined,
77
+ catalogIdentity = READ_CATALOG_IDENTITY,
78
+ ) {
79
+ if (!registration) throw new Error(`unknown reducer "${request.reducer}"`)
80
+ const entry = registration.valueRead
81
+ if ('excluded' in entry)
82
+ throw new Error(`excluded reducer "${request.reducer}": ${entry.excluded}`)
83
+ if (entry.scope !== scope.kind) throw new Error(`wrong scope for reducer "${request.reducer}"`)
84
+ const args = entry.args.parse(request.args ?? {})
85
+ const reducer = entry.create(args)
86
+ const identity = canonical({
87
+ scope,
88
+ reducer: request.reducer,
89
+ version: reducer.version,
90
+ catalogIdentity,
91
+ args,
92
+ })
93
+ // v2 ignores checkpoints from the former client-writable key format.
94
+ const key = `${REDUCER_VALUE_SNAPSHOT_PREFIX}v2.${new Bun.CryptoHasher('sha256').update(identity).digest('hex').slice(0, 54)}`
95
+ return { name: request.reducer, reducer, identity, key, entry }
96
+ }
97
+ export type ResolvedReducerValue = ReturnType<typeof resolveRegisteredValue>
98
+
99
+ /** Raw cache reads and conditional repairs are private adapter operations: clients
100
+ * cannot submit a new accumulator through the value API. `token` identifies the
101
+ * exact row read, including malformed bytes that could not be decoded. */
102
+ export interface ValueCacheRow {
103
+ snapshot: ReducerSnapshot
104
+ token: string
105
+ }
106
+ export interface ReducerValueStorage {
107
+ checkpoints?: {
108
+ publish(key: string, snapshot: ReducerSnapshot, checkpoints: ReducerSnapshot[]): Promise<void>
109
+ coverage(key: string, cursor: number): Promise<boolean>
110
+ latest(key: string, through: number): Promise<ReducerSnapshot | null>
111
+ }
112
+ highWater(): Promise<number>
113
+ read(key: string): Promise<ValueCacheRow | null>
114
+ events(since: number, through: number): Promise<(AbEvent | RepositoryEvent)[]>
115
+ put(key: string, snapshot: ReducerSnapshot): Promise<boolean>
116
+ repair(key: string, observed: ValueCacheRow, snapshot: ReducerSnapshot): Promise<boolean>
117
+ }
118
+
119
+ /** Serve one resolved value: load its saved row, advance it over the delta
120
+ * since its cursor, and save the result. */
121
+ export async function readResolvedReducerValue(
122
+ resolved: ResolvedReducerValue,
123
+ storage: ReducerValueStorage,
124
+ ): Promise<ReducerValue> {
125
+ const { reducer, identity, key, entry } = resolved
126
+ let boundary = await storage.highWater()
127
+ let row: ValueCacheRow | null = null
128
+ try {
129
+ row = await storage.read(key)
130
+ } catch {
131
+ if (storage.checkpoints) throw new CheckpointIntegrityError('unreadable canonical stream seed')
132
+ /* unreadable cache is a miss */
133
+ }
134
+ // A concurrent reader may have persisted beyond our first boundary. Only a
135
+ // fresh authoritative boundary can establish ahead-of-log poison.
136
+ if (row && row.snapshot.cursor > boundary) boundary = await storage.highWater()
137
+ let acc = reducer.initial()
138
+ let cursor = 0
139
+ let valid = false
140
+ if (row) {
141
+ const { snapshot } = row
142
+ const state = snapshot.state as { identity?: unknown; acc?: unknown } | null
143
+ try {
144
+ valid =
145
+ snapshot.version === reducer.version &&
146
+ Number.isSafeInteger(snapshot.cursor) &&
147
+ snapshot.cursor >= 0 &&
148
+ snapshot.cursor <= boundary &&
149
+ state !== null &&
150
+ typeof state === 'object' &&
151
+ state.identity === identity &&
152
+ entry.validate(state.acc)
153
+ } catch {
154
+ valid = false // malformed nested cache data must never prevent replay
155
+ }
156
+ if (valid) {
157
+ acc = structuredClone(state!.acc)
158
+ cursor = snapshot.cursor
159
+ }
160
+ }
161
+ if (storage.checkpoints && row && !valid)
162
+ throw new CheckpointIntegrityError('corrupt canonical stream seed')
163
+ let recovering = false
164
+ if (storage.checkpoints && valid && !(await storage.checkpoints.coverage(key, cursor))) {
165
+ // A pre-checkpoint server may advance the shared canonical row during a
166
+ // rolling deploy or rollback. Its accumulator cannot supply the missing
167
+ // intermediate seeds. Refold only the uncovered suffix under the seed lock.
168
+ const checkpoint = await storage.checkpoints.latest(key, cursor)
169
+ if (checkpoint) {
170
+ const state = checkpoint.state as { identity?: unknown; acc?: unknown } | null
171
+ if (
172
+ checkpoint.version !== reducer.version ||
173
+ !Number.isSafeInteger(checkpoint.cursor) ||
174
+ checkpoint.cursor < 0 ||
175
+ checkpoint.cursor > cursor ||
176
+ state?.identity !== identity ||
177
+ !entry.validate(state.acc)
178
+ )
179
+ throw new CheckpointIntegrityError('corrupt recovery stream-seed checkpoint')
180
+ acc = structuredClone(state.acc)
181
+ cursor = checkpoint.cursor
182
+ } else {
183
+ // Initial legacy adoption with no checkpoint to resume from.
184
+ acc = reducer.initial()
185
+ cursor = 0
186
+ }
187
+ recovering = true
188
+ }
189
+ const start = cursor
190
+ const delta = (await storage.events(cursor, boundary)).filter((event) => event.seq <= boundary)
191
+ for (const event of delta) {
192
+ if (event.seq !== cursor + 1) throw new Error('noncontiguous reducer log')
193
+ cursor = event.seq
194
+ }
195
+ if (cursor !== boundary) throw new Error('incomplete reducer log')
196
+ const checkpoints: ReducerSnapshot[] = []
197
+ if (storage.checkpoints) {
198
+ const oldest = Math.max(0, boundary - REPOSITORY_TAIL_WINDOW)
199
+ const prefix = delta.filter((event) => event.seq <= oldest)
200
+ acc = reducer.advance(acc, entry.adapt(projectStoredEvents(prefix)))
201
+ if (start <= oldest)
202
+ checkpoints.push({
203
+ version: reducer.version,
204
+ cursor: oldest,
205
+ state: { identity, acc: structuredClone(acc) },
206
+ })
207
+ for (const event of delta) {
208
+ if (event.seq <= oldest) continue
209
+ acc = reducer.advance(acc, entry.adapt(projectStoredEvents([event])))
210
+ checkpoints.push({
211
+ version: reducer.version,
212
+ cursor: event.seq,
213
+ state: { identity, acc: structuredClone(acc) },
214
+ })
215
+ }
216
+ } else acc = reducer.advance(acc, entry.adapt(projectStoredEvents(delta)))
217
+ const value = entry.value(reducer.finish(acc))
218
+ if (!valid || recovering || delta.length > 0) {
219
+ const next = { version: reducer.version, cursor, state: { identity, acc } }
220
+ if (storage.checkpoints) {
221
+ await storage.checkpoints.publish(key, next, checkpoints)
222
+ return { version: reducer.version, cursor, value, catalogIdentity: READ_CATALOG_IDENTITY }
223
+ }
224
+ try {
225
+ if (row && !valid && row.snapshot.version === reducer.version)
226
+ await storage.repair(key, row, next)
227
+ else if (row && !valid && row.snapshot.version !== reducer.version) {
228
+ /* foreign cache is read-only */
229
+ } else await storage.put(key, next)
230
+ } catch {
231
+ /* best-effort cache; log and reduction errors propagate */
232
+ }
233
+ }
234
+ return { version: reducer.version, cursor, value, catalogIdentity: READ_CATALOG_IDENTITY }
235
+ }