@defrex/autobuild 0.13.0 → 1.0.0-beta.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 (210) hide show
  1. package/README.md +5 -3
  2. package/SPEC.md +673 -99
  3. package/bin/ab-dispatch-kernel.ts +4 -6
  4. package/docs/architecture.md +322 -75
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +112 -12
  7. package/docs/hosted-service.md +20 -2
  8. package/docs/integration-tree.md +117 -0
  9. package/docs/landing-policy.md +150 -0
  10. package/docs/mcp.md +24 -0
  11. package/docs/migration-1.0.md +68 -0
  12. package/docs/operator-api.md +20 -9
  13. package/docs/remote-store-protocol.md +114 -9
  14. package/docs/remote-ticket-protocol.md +26 -5
  15. package/docs/restacking.md +79 -0
  16. package/docs/setup.md +49 -6
  17. package/docs/ticket-dependencies.md +69 -0
  18. package/docs/ticket-migration.md +8 -0
  19. package/package.json +4 -3
  20. package/packages/core/src/cli/attention.ts +40 -163
  21. package/packages/core/src/cli/build-control.ts +75 -55
  22. package/packages/core/src/cli/bulk-control.ts +3 -2
  23. package/packages/core/src/cli/context.ts +68 -78
  24. package/packages/core/src/cli/dashboard/actions.ts +6 -3
  25. package/packages/core/src/cli/dashboard/landing-display.ts +6 -0
  26. package/packages/core/src/cli/dashboard/live.ts +5 -0
  27. package/packages/core/src/cli/dashboard/model.ts +178 -40
  28. package/packages/core/src/cli/dashboard/poll.ts +15 -9
  29. package/packages/core/src/cli/dashboard/refresh.ts +176 -0
  30. package/packages/core/src/cli/dashboard/render.ts +78 -28
  31. package/packages/core/src/cli/dashboard/repository-poll.ts +57 -0
  32. package/packages/core/src/cli/dashboard/selection.ts +7 -1
  33. package/packages/core/src/cli/dashboard/tree.ts +107 -0
  34. package/packages/core/src/cli/dispatch-frontend.ts +173 -169
  35. package/packages/core/src/cli/dispatch-process.ts +14 -7
  36. package/packages/core/src/cli/dispatch-repository-feed.ts +196 -0
  37. package/packages/core/src/cli/dispatch.ts +397 -214
  38. package/packages/core/src/cli/dispatcher-liveness.ts +41 -21
  39. package/packages/core/src/cli/harvest.ts +71 -39
  40. package/packages/core/src/cli/help.ts +49 -32
  41. package/packages/core/src/cli/historical-build-state.ts +27 -0
  42. package/packages/core/src/cli/init-validation.ts +43 -2
  43. package/packages/core/src/cli/keyboard.ts +6 -0
  44. package/packages/core/src/cli/landings.ts +18 -0
  45. package/packages/core/src/cli/main.ts +52 -18
  46. package/packages/core/src/cli/mcp.ts +9 -0
  47. package/packages/core/src/cli/pr-attachments.ts +10 -13
  48. package/packages/core/src/cli/pr-summary-publication.ts +27 -60
  49. package/packages/core/src/cli/pr-summary.ts +43 -13
  50. package/packages/core/src/cli/publication-settlement.ts +177 -21
  51. package/packages/core/src/cli/repository-status.ts +49 -2
  52. package/packages/core/src/cli/status.ts +133 -36
  53. package/packages/core/src/cli/terminal-restore.ts +54 -0
  54. package/packages/core/src/cli/terminal.ts +16 -2
  55. package/packages/core/src/cli/terminals.ts +121 -219
  56. package/packages/core/src/cli/ticket-editor.ts +10 -3
  57. package/packages/core/src/cli/ticket.ts +115 -20
  58. package/packages/core/src/cli/upgrade-commit.ts +4 -0
  59. package/packages/core/src/cli/upgrade-compatibility.ts +2 -2
  60. package/packages/core/src/cli/upgrade-landing.ts +69 -0
  61. package/packages/core/src/cli/upgrade.ts +16 -0
  62. package/packages/core/src/cli/wait.ts +194 -91
  63. package/packages/core/src/cli/watch.ts +111 -109
  64. package/packages/core/src/config/landing.ts +22 -0
  65. package/packages/core/src/config/live.ts +1 -0
  66. package/packages/core/src/config/pipeline-source.ts +4 -3
  67. package/packages/core/src/config/schema.ts +3 -0
  68. package/packages/core/src/events/catalog.ts +48 -3
  69. package/packages/core/src/events/payloads.ts +295 -6
  70. package/packages/core/src/events/repository.ts +38 -3
  71. package/packages/core/src/integration/harness.ts +11 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-registry.test.ts.snap +3330 -119
  73. package/packages/core/src/kernel/auto-merge-default.ts +1 -0
  74. package/packages/core/src/kernel/auto-merge.ts +29 -4
  75. package/packages/core/src/kernel/build-identity.ts +94 -0
  76. package/packages/core/src/kernel/change-presence.ts +179 -0
  77. package/packages/core/src/kernel/dispatch-status.ts +17 -1
  78. package/packages/core/src/kernel/dispatcher-liveness.ts +10 -4
  79. package/packages/core/src/kernel/engine.ts +89 -2
  80. package/packages/core/src/kernel/generators/build-log.ts +23 -0
  81. package/packages/core/src/kernel/generators/leaf-restack-log.ts +110 -0
  82. package/packages/core/src/kernel/generators/node-restack-log.ts +94 -0
  83. package/packages/core/src/kernel/generators/repository-journals.ts +25 -3
  84. package/packages/core/src/kernel/harvest.ts +25 -23
  85. package/packages/core/src/kernel/integration-completeness.ts +81 -0
  86. package/packages/core/src/kernel/integration-landing.ts +263 -0
  87. package/packages/core/src/kernel/integration-stack.ts +36 -0
  88. package/packages/core/src/kernel/integration-state.ts +135 -0
  89. package/packages/core/src/kernel/landing-policy.ts +47 -0
  90. package/packages/core/src/kernel/landing-publication.ts +41 -0
  91. package/packages/core/src/kernel/landing-readiness.ts +67 -0
  92. package/packages/core/src/kernel/landing-state.ts +96 -0
  93. package/packages/core/src/kernel/leaf-restack-completion.ts +24 -0
  94. package/packages/core/src/kernel/leaf-restack-state.ts +73 -0
  95. package/packages/core/src/kernel/log-index-value.ts +38 -0
  96. package/packages/core/src/kernel/log-index.ts +35 -5
  97. package/packages/core/src/kernel/node-landing.ts +439 -0
  98. package/packages/core/src/kernel/node-parent.ts +184 -0
  99. package/packages/core/src/kernel/node-restack-state.ts +191 -0
  100. package/packages/core/src/kernel/node-restack-transaction.ts +210 -0
  101. package/packages/core/src/kernel/node-restack.ts +274 -0
  102. package/packages/core/src/kernel/read-facts.ts +704 -0
  103. package/packages/core/src/kernel/reconcile-head.ts +51 -0
  104. package/packages/core/src/kernel/reconcile-restack.ts +560 -0
  105. package/packages/core/src/kernel/reducer-registry.ts +153 -3
  106. package/packages/core/src/kernel/reducer.ts +121 -6
  107. package/packages/core/src/kernel/repository-attention.ts +179 -0
  108. package/packages/core/src/kernel/service-facts.ts +135 -0
  109. package/packages/core/src/kernel/snapshot-parent.ts +33 -0
  110. package/packages/core/src/kernel/terminal-guard.ts +133 -0
  111. package/packages/core/src/ontology.ts +9 -1
  112. package/packages/core/src/operator/annotations.ts +12 -0
  113. package/packages/core/src/operator/control.ts +11 -6
  114. package/packages/core/src/operator/index.ts +6 -0
  115. package/packages/core/src/operator/landings.ts +35 -0
  116. package/packages/core/src/operator/presentation.ts +1 -0
  117. package/packages/core/src/operator/protocol.ts +12 -3
  118. package/packages/core/src/operator/query.ts +40 -21
  119. package/packages/core/src/operator/read-view.ts +4 -13
  120. package/packages/core/src/operator/registry.ts +48 -19
  121. package/packages/core/src/operator/requests.ts +3 -22
  122. package/packages/core/src/operator/sandbox.ts +10 -9
  123. package/packages/core/src/operator/tickets.ts +57 -11
  124. package/packages/core/src/plugin-sdk/index.ts +13 -0
  125. package/packages/core/src/ports/forge/contract.ts +91 -3
  126. package/packages/core/src/ports/forge/fake.ts +142 -4
  127. package/packages/core/src/ports/forge/git-rewrite.ts +232 -0
  128. package/packages/core/src/ports/forge/github-readiness.ts +421 -0
  129. package/packages/core/src/ports/forge/github.ts +631 -35
  130. package/packages/core/src/ports/forge/local-git.ts +119 -5
  131. package/packages/core/src/ports/forge/readiness.ts +99 -0
  132. package/packages/core/src/ports/tickets/contract.ts +41 -0
  133. package/packages/core/src/ports/tickets/create.ts +8 -1
  134. package/packages/core/src/ports/tickets/fake.ts +32 -1
  135. package/packages/core/src/ports/tickets/file-codec.ts +7 -0
  136. package/packages/core/src/ports/tickets/file.ts +18 -1
  137. package/packages/core/src/ports/tickets/hosted-index.ts +2 -0
  138. package/packages/core/src/ports/tickets/linear.ts +124 -4
  139. package/packages/core/src/ports/tickets/migration.ts +25 -1
  140. package/packages/core/src/ports/tickets/operations.ts +7 -2
  141. package/packages/core/src/ports/tickets/remote-protocol.ts +19 -0
  142. package/packages/core/src/ports/tickets/remote.ts +10 -1
  143. package/packages/core/src/ports/tickets/revision.ts +3 -1
  144. package/packages/core/src/ports/tickets/tree.ts +148 -0
  145. package/packages/core/src/ports/tickets/update.ts +15 -2
  146. package/packages/core/src/ports/types.ts +135 -5
  147. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  148. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -1
  149. package/packages/core/src/ports/workspace/vercel-sandbox.ts +60 -3
  150. package/packages/core/src/processes/build-child.ts +6 -6
  151. package/packages/core/src/processes/build-runner.ts +586 -87
  152. package/packages/core/src/processes/dispatch-failure-budget.ts +5 -4
  153. package/packages/core/src/processes/dispatcher-selectors.ts +15 -9
  154. package/packages/core/src/processes/dispatcher.ts +2239 -357
  155. package/packages/core/src/processes/execution-no-progress.ts +46 -1
  156. package/packages/core/src/processes/harvest-execution-state.ts +15 -9
  157. package/packages/core/src/processes/harvest-runner.ts +34 -70
  158. package/packages/core/src/processes/harvest.ts +38 -15
  159. package/packages/core/src/processes/infrastructure-failure-budget.ts +13 -15
  160. package/packages/core/src/processes/orchestrator-tick.ts +2 -2
  161. package/packages/core/src/processes/publication-loss.ts +35 -21
  162. package/packages/core/src/processes/publication-state.ts +30 -5
  163. package/packages/core/src/processes/repo-view.ts +244 -1130
  164. package/packages/core/src/processes/tick-publication.ts +110 -0
  165. package/packages/core/src/store/adapter.ts +23 -0
  166. package/packages/core/src/store/build-scope.ts +35 -0
  167. package/packages/core/src/store/contract.ts +909 -0
  168. package/packages/core/src/store/digest.ts +52 -4
  169. package/packages/core/src/store/local/schema.ts +26 -13
  170. package/packages/core/src/store/local/store.ts +296 -55
  171. package/packages/core/src/store/memory.ts +181 -30
  172. package/packages/core/src/store/phase-session.ts +34 -0
  173. package/packages/core/src/store/reduced-reads.ts +240 -0
  174. package/packages/core/src/store/reducer-value-shapes.json +18323 -0
  175. package/packages/core/src/store/reducer-value-validation.ts +96 -0
  176. package/packages/core/src/store/reducer-values.ts +145 -0
  177. package/packages/core/src/store/remote/client.ts +85 -0
  178. package/packages/core/src/store/remote/compatibility.ts +21 -9
  179. package/packages/core/src/store/remote/index.ts +19 -0
  180. package/packages/core/src/store/remote/protocol.ts +27 -0
  181. package/packages/core/src/store/remote/version.ts +3 -1
  182. package/packages/core/src/store/repo-state-events.ts +3 -1
  183. package/packages/core/src/store/repo-tick.ts +72 -0
  184. package/packages/core/src/store/session-handle.ts +34 -0
  185. package/packages/core/src/store/snapshots.ts +10 -0
  186. package/packages/core/src/store/subscribe.ts +1 -1
  187. package/packages/core/src/store/ticket-assets.ts +4 -4
  188. package/packages/core/src/store/types.ts +71 -6
  189. package/packages/core/src/testing/dispatch-read-budget.ts +215 -0
  190. package/packages/core/src/testing/index.ts +10 -0
  191. package/packages/core/src/testing/reduced-read-budget.ts +502 -0
  192. package/packages/core/src/testing/refresh-scheduler.ts +32 -0
  193. package/skills/guide/SKILL.md +116 -62
  194. package/skills/guide/references/integration-tree.md +117 -0
  195. package/skills/guide/references/landing-policy.md +150 -0
  196. package/skills/guide/references/migration-1.0.md +68 -0
  197. package/skills/guide/references/operator-api.md +13 -6
  198. package/skills/guide/references/plugin-authoring.md +34 -0
  199. package/skills/guide/references/remote-store-protocol.md +114 -9
  200. package/skills/guide/references/remote-ticket-protocol.md +26 -5
  201. package/skills/guide/references/restacking.md +79 -0
  202. package/skills/guide/references/setup.md +49 -6
  203. package/skills/guide/references/ticket-dependencies.md +69 -0
  204. package/skills/guide/references/ticket-migration.md +8 -0
  205. package/skills/operate/SKILL.md +55 -5
  206. package/skills/reconcile/SKILL.md +55 -48
  207. package/skills/spec/SKILL.md +67 -1
  208. package/skills/tickets/SKILL.md +55 -2
  209. package/templates/autobuild.toml +3 -0
  210. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,13 @@
1
+ import { readPersistedBuildDigests } from './reduced-reads'
2
+ import { assertPublicSnapshotReducer } from './snapshots'
3
+ import {
4
+ readReducerValue,
5
+ resolveReducerValue,
6
+ type ReducerValueRequest,
7
+ type ReducerValue,
8
+ } from './reducer-values'
9
+ import { validateTickFinish } from './repo-tick'
10
+ import type { RepoTickCompletion, RepoTickFinish, RepoTickObservation } from './types'
1
11
  /**
2
12
  * The in-memory BuildStore — the reference adapter. Its behavior *is* the
3
13
  * contract: the suite in `store/contract.ts` is written against this and
@@ -34,7 +44,6 @@ import {
34
44
  } from './snapshots'
35
45
  import { validateCreatedEvent } from './new-build'
36
46
  import { createSessionScopedStore } from './session-handle'
37
- import { reduceBuildDigest } from './digest'
38
47
  import { projectRepositoryStateEvents } from './repo-state-events'
39
48
  import {
40
49
  DEFAULT_ARTIFACT_RETENTION_MAX_REVISIONS,
@@ -121,6 +130,7 @@ interface Lease {
121
130
  }
122
131
 
123
132
  interface RepoState {
133
+ tick?: RepoTickObservation
124
134
  record: {
125
135
  repo: string
126
136
  createdAt: string
@@ -133,6 +143,7 @@ interface RepoState {
133
143
  }
134
144
 
135
145
  interface BuildState {
146
+ nodeWriter?: Lease
136
147
  record: {
137
148
  slug: string
138
149
  repo: string
@@ -303,6 +314,7 @@ export class MemoryBuildStore implements BuildStore {
303
314
  )
304
315
  }
305
316
  this.builds.set(input.slug, state)
317
+ this.advanceRepo(input.repo)
306
318
  return this.snapshot(state)
307
319
  }
308
320
 
@@ -311,39 +323,31 @@ export class MemoryBuildStore implements BuildStore {
311
323
  return state ? this.snapshot(state) : null
312
324
  }
313
325
 
326
+ private readonly repoPositions = new Map<string, bigint>()
327
+
328
+ private advanceRepo(repo: string): void {
329
+ this.repoPositions.set(repo, (this.repoPositions.get(repo) ?? 0n) + 1n)
330
+ }
331
+
332
+ async getRepoChangePosition(repo: string): Promise<string> {
333
+ return (this.repoPositions.get(repo) ?? 0n).toString()
334
+ }
335
+
336
+ async listBuildsForRepo(repo: string): Promise<BuildRecord[]> {
337
+ return [...this.builds.values()]
338
+ .filter((state) => state.record.repo === repo)
339
+ .map((state) => this.snapshot(state))
340
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.slug.localeCompare(b.slug))
341
+ }
342
+
314
343
  async listBuilds(): Promise<BuildRecord[]> {
315
- return [...this.builds.values()].map((state) => this.snapshot(state))
344
+ return [...this.builds.values()]
345
+ .map((state) => this.snapshot(state))
346
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.slug.localeCompare(b.slug))
316
347
  }
317
348
 
318
349
  async getRepoBuildDigests(repo: string): Promise<Map<string, BuildDigest>> {
319
- // Insertion order is creation order (the listSessions tiebreak note); the
320
- // digest map is returned in slug order so every adapter answers the same
321
- // shape for the same store contents.
322
- const slugs = [...this.builds.entries()]
323
- .filter(([, state]) => state.record.repo === repo)
324
- .map(([slug]) => slug)
325
- .sort()
326
- const digests = new Map<string, BuildDigest>()
327
- for (const slug of slugs) {
328
- const state = this.builds.get(slug)!
329
- digests.set(slug, {
330
- slug,
331
- ...reduceBuildDigest(
332
- state.events.map((event) => ({
333
- type: event.type,
334
- seq: event.seq,
335
- ts: event.ts,
336
- ...(event.type === 'pr-attachment.reclaimed'
337
- ? { hostedSeq: event.payload.hostedSeq }
338
- : {}),
339
- ...(event.type === 'execution.started' || event.type === 'execution.ended'
340
- ? { instance: event.payload.instance }
341
- : {}),
342
- })),
343
- ),
344
- })
345
- }
346
- return digests
350
+ return readPersistedBuildDigests(this, repo)
347
351
  }
348
352
 
349
353
  async append<T extends EventType>(slug: string, event: EventWrite<T>): Promise<EventEnvelope<T>> {
@@ -358,6 +362,7 @@ export class MemoryBuildStore implements BuildStore {
358
362
  payload: validated.payload,
359
363
  } as EventEnvelope<T>
360
364
  state.events.push(structuredClone(envelope) as AbEvent)
365
+ this.advanceRepo(state.record.repo)
361
366
  state.record.updatedAt = envelope.ts
362
367
  return envelope
363
368
  }
@@ -384,6 +389,7 @@ export class MemoryBuildStore implements BuildStore {
384
389
  payload: validated.payload,
385
390
  } as EventEnvelope<T>
386
391
  state.events.push(structuredClone(envelope) as AbEvent)
392
+ this.advanceRepo(state.record.repo)
387
393
  state.record.updatedAt = envelope.ts
388
394
  return envelope
389
395
  }
@@ -452,6 +458,7 @@ export class MemoryBuildStore implements BuildStore {
452
458
  payload: validated.payload,
453
459
  } as EventEnvelope<T>
454
460
  state.events.push(structuredClone(envelope) as AbEvent)
461
+ this.advanceRepo(state.record.repo)
455
462
  state.record.updatedAt = ts
456
463
  return { event: envelope, artifacts: structuredClone(deposited) }
457
464
  }
@@ -518,6 +525,38 @@ export class MemoryBuildStore implements BuildStore {
518
525
  )
519
526
  }
520
527
 
528
+ async claimNodeWriter(slug: string, holder: string, ttlMs: number): Promise<boolean> {
529
+ const state = this.state(slug)
530
+ const now = this.clock().getTime()
531
+ const lease = state.nodeWriter
532
+ if (lease && lease.holder !== holder && lease.expiresAt > now) {
533
+ return false
534
+ }
535
+ state.nodeWriter = { holder, expiresAt: now + ttlMs, ttlMs }
536
+ state.record.updatedAt = new Date(now).toISOString()
537
+ return true
538
+ }
539
+
540
+ async renewNodeWriter(slug: string, holder: string): Promise<boolean> {
541
+ const state = this.state(slug)
542
+ const now = this.clock().getTime()
543
+ const lease = state.nodeWriter
544
+ if (!lease || lease.holder !== holder || lease.expiresAt <= now) {
545
+ return false
546
+ }
547
+ lease.expiresAt = now + lease.ttlMs
548
+ state.record.updatedAt = new Date(now).toISOString()
549
+ return true
550
+ }
551
+
552
+ async releaseNodeWriter(slug: string, holder: string): Promise<void> {
553
+ const state = this.state(slug)
554
+ if (state.nodeWriter?.holder === holder) {
555
+ state.nodeWriter = undefined
556
+ state.record.updatedAt = this.now()
557
+ }
558
+ }
559
+
521
560
  async claimLease(slug: string, holder: string, ttlMs: number): Promise<boolean> {
522
561
  const state = this.state(slug)
523
562
  const now = this.clock().getTime()
@@ -563,6 +602,7 @@ export class MemoryBuildStore implements BuildStore {
563
602
 
564
603
  private repoSnapshot(state: RepoState): RepositoryRecord {
565
604
  return {
605
+ ...(state.tick ? { tick: structuredClone(state.tick) } : {}),
566
606
  repo: state.record.repo,
567
607
  createdAt: state.record.createdAt,
568
608
  updatedAt: state.record.updatedAt,
@@ -613,6 +653,7 @@ export class MemoryBuildStore implements BuildStore {
613
653
  payload: validated.payload,
614
654
  } as RepositoryEventEnvelope<T>
615
655
  state.events.push(structuredClone(envelope) as RepositoryEvent)
656
+ this.advanceRepo(repo)
616
657
  state.record.updatedAt = envelope.ts
617
658
  return envelope
618
659
  }
@@ -677,6 +718,7 @@ export class MemoryBuildStore implements BuildStore {
677
718
  payload: validated.payload,
678
719
  } as RepositoryEventEnvelope<T>
679
720
  state.events.push(structuredClone(envelope) as RepositoryEvent)
721
+ this.advanceRepo(repo)
680
722
  state.record.updatedAt = ts
681
723
  return { event: envelope, artifacts: structuredClone(deposited) }
682
724
  }
@@ -714,11 +756,54 @@ export class MemoryBuildStore implements BuildStore {
714
756
  return events === undefined ? undefined : (events.at(-1)?.seq ?? 0)
715
757
  }
716
758
 
759
+ async getReducerValue(scope: SnapshotScope, request: ReducerValueRequest): Promise<ReducerValue> {
760
+ // Reject invalid requests before touching storage.
761
+ resolveReducerValue(scope, request)
762
+ return readReducerValue(scope, request, {
763
+ highWater: async () => {
764
+ const tail = this.snapshotTail(scope)
765
+ if (tail === undefined) throw new Error('unknown reducer scope')
766
+ return tail
767
+ },
768
+ events: async (since, through) =>
769
+ structuredClone(
770
+ (scope.kind === 'build'
771
+ ? this.state(scope.slug).events
772
+ : this.repoState(scope.repo).events
773
+ ).slice(since, through),
774
+ ) as (AbEvent | RepositoryEvent)[],
775
+ put: (key, snapshot) => this.putSnapshot(scope, key, snapshot),
776
+ read: async (key) => {
777
+ const snapshot = this.snapshots.get(`${snapshotScopeKey(scope)}\u0000${key}`)
778
+ return snapshot === undefined
779
+ ? null
780
+ : { snapshot: structuredClone(snapshot), token: JSON.stringify(snapshot) }
781
+ },
782
+ repair: async (key, observed, snapshot) => {
783
+ const cacheKey = `${snapshotScopeKey(scope)}\u0000${key}`
784
+ const current = this.snapshots.get(cacheKey)
785
+ const tail = this.snapshotTail(scope)
786
+ if (
787
+ !current ||
788
+ JSON.stringify(current) !== observed.token ||
789
+ tail === undefined ||
790
+ snapshot.cursor > tail
791
+ )
792
+ return false
793
+ if (observed.snapshot.cursor > snapshot.cursor && tail >= observed.snapshot.cursor)
794
+ return false
795
+ this.snapshots.set(cacheKey, JSON.parse(JSON.stringify(snapshot)))
796
+ return true
797
+ },
798
+ })
799
+ }
800
+
717
801
  async getReducerSnapshot(
718
802
  scope: SnapshotScope,
719
803
  reducer: string,
720
804
  version: number,
721
805
  ): Promise<ReducerSnapshot | null> {
806
+ assertPublicSnapshotReducer(reducer)
722
807
  const tail = this.snapshotTail(scope)
723
808
  if (tail === undefined) return null
724
809
  const stored = this.snapshots.get(`${snapshotScopeKey(scope)}\u0000${reducer}`)
@@ -730,6 +815,15 @@ export class MemoryBuildStore implements BuildStore {
730
815
  scope: SnapshotScope,
731
816
  reducer: string,
732
817
  snapshot: ReducerSnapshot,
818
+ ): Promise<boolean> {
819
+ assertPublicSnapshotReducer(reducer)
820
+ return this.putSnapshot(scope, reducer, snapshot)
821
+ }
822
+
823
+ private async putSnapshot(
824
+ scope: SnapshotScope,
825
+ reducer: string,
826
+ snapshot: ReducerSnapshot,
733
827
  ): Promise<boolean> {
734
828
  const tail = this.snapshotTail(scope)
735
829
  if (tail === undefined || snapshot.cursor > tail) return false
@@ -896,12 +990,68 @@ export class MemoryBuildStore implements BuildStore {
896
990
  return structuredClone(latest.meta)
897
991
  }
898
992
 
993
+ async beginRepoTick(repo: string, holder: string): Promise<string | null> {
994
+ const state = this.repoState(repo)
995
+ if (
996
+ !state.lease ||
997
+ state.lease.holder !== holder ||
998
+ state.lease.expiresAt <= this.clock().getTime()
999
+ )
1000
+ return null
1001
+ const startedAt = this.now()
1002
+ state.tick = {
1003
+ run: holder,
1004
+ open: { startedAt },
1005
+ ...(state.tick?.finished ? { finished: state.tick.finished } : {}),
1006
+ }
1007
+ state.record.updatedAt = startedAt
1008
+ return startedAt
1009
+ }
1010
+
1011
+ async finishRepoTick(
1012
+ repo: string,
1013
+ holder: string,
1014
+ completion: RepoTickCompletion,
1015
+ events: RepositoryEventWrite[],
1016
+ ): Promise<RepoTickFinish | null> {
1017
+ const validated = validateTickFinish(holder, completion, events)
1018
+ const state = this.repoState(repo)
1019
+ if (
1020
+ !state.lease ||
1021
+ state.lease.holder !== holder ||
1022
+ state.lease.expiresAt <= this.clock().getTime()
1023
+ )
1024
+ return null
1025
+ if (state.tick?.run !== holder || !state.tick.open) throw new Error('no open repository tick')
1026
+ const completedAt = this.now()
1027
+ const envelopes = validated.map((event, index) => ({
1028
+ ...event,
1029
+ repo,
1030
+ seq: state.events.length + index + 1,
1031
+ ts: completedAt,
1032
+ })) as RepositoryEvent[]
1033
+ state.tick = {
1034
+ run: holder,
1035
+ finished: {
1036
+ ...structuredClone(completion),
1037
+ run: holder,
1038
+ startedAt: state.tick.open.startedAt,
1039
+ completedAt,
1040
+ },
1041
+ }
1042
+ state.events.push(...structuredClone(envelopes))
1043
+ for (const _event of envelopes) this.advanceRepo(repo)
1044
+ state.record.updatedAt = completedAt
1045
+ return structuredClone({ observation: state.tick, events: envelopes })
1046
+ }
1047
+
899
1048
  async claimRepoLease(repo: string, holder: string, ttlMs: number): Promise<boolean> {
900
1049
  const state = this.repoState(repo)
901
1050
  const now = this.clock().getTime()
902
1051
  if (state.lease && state.lease.holder !== holder && state.lease.expiresAt > now) {
903
1052
  return false
904
1053
  }
1054
+ if (state.lease?.holder !== holder) this.advanceRepo(repo)
905
1055
  state.lease = { holder, expiresAt: now + ttlMs, ttlMs }
906
1056
  state.record.updatedAt = new Date(now).toISOString()
907
1057
  return true
@@ -921,6 +1071,7 @@ export class MemoryBuildStore implements BuildStore {
921
1071
  async releaseRepoLease(repo: string, holder: string): Promise<void> {
922
1072
  const state = this.repoState(repo)
923
1073
  if (state.lease?.holder === holder) {
1074
+ this.advanceRepo(repo)
924
1075
  state.lease = undefined
925
1076
  state.record.updatedAt = this.now()
926
1077
  }
@@ -1,3 +1,4 @@
1
+ import type { ReducerValueRequest, ReducerValue } from './reducer-values'
1
2
  /**
2
3
  * Local ambient phase-session wrapper for a BuildStore.
3
4
  *
@@ -214,6 +215,14 @@ export function scopeLocalStoreToPhaseSession(
214
215
  own('getBuild', 'build', slug)
215
216
  return store.getBuild(slug)
216
217
  },
218
+ async listBuildsForRepo(repo: string): Promise<BuildRecord[]> {
219
+ own('listBuildsForRepo', 'repo', repo)
220
+ return store.listBuildsForRepo(repo)
221
+ },
222
+ async getRepoChangePosition(repo: string): Promise<string> {
223
+ own('getRepoChangePosition', 'repo', repo)
224
+ return store.getRepoChangePosition(repo)
225
+ },
217
226
  async listBuilds(): Promise<BuildRecord[]> {
218
227
  return admin('listBuilds')
219
228
  },
@@ -266,6 +275,15 @@ export function scopeLocalStoreToPhaseSession(
266
275
  own('listArtifacts', 'build', slug)
267
276
  return store.listArtifacts(slug, kind)
268
277
  },
278
+ async claimNodeWriter(_slug: string, _holder: string, _ttlMs: number): Promise<boolean> {
279
+ throw new Error('phase sessions cannot mutate node writer leases')
280
+ },
281
+ async renewNodeWriter(_slug: string, _holder: string): Promise<boolean> {
282
+ throw new Error('phase sessions cannot mutate node writer leases')
283
+ },
284
+ async releaseNodeWriter(_slug: string, _holder: string): Promise<void> {
285
+ throw new Error('phase sessions cannot mutate node writer leases')
286
+ },
269
287
  async claimLease(slug: string, holder: string, ttlMs: number): Promise<boolean> {
270
288
  own('claimLease', 'build', slug)
271
289
  return store.claimLease(slug, holder, ttlMs)
@@ -333,6 +351,14 @@ export function scopeLocalStoreToPhaseSession(
333
351
  own('getRepoHighWater', 'repo', repo)
334
352
  return store.getRepoHighWater(repo)
335
353
  },
354
+ async getReducerValue(
355
+ target: SnapshotScope,
356
+ request: ReducerValueRequest,
357
+ ): Promise<ReducerValue> {
358
+ if (target.kind === 'build') own('getReducerValue', 'build', target.slug)
359
+ else own('getReducerValue', 'repo', target.repo)
360
+ return store.getReducerValue(target, request)
361
+ },
336
362
  async getReducerSnapshot(
337
363
  target: SnapshotScope,
338
364
  reducer: string,
@@ -423,6 +449,14 @@ export function scopeLocalStoreToPhaseSession(
423
449
  own('claimRepoLease', 'repo', repo)
424
450
  return store.claimRepoLease(repo, holder, ttlMs)
425
451
  },
452
+ async beginRepoTick(repo: string) {
453
+ own('beginRepoTick', 'repo', repo)
454
+ throw new Error('phase sessions cannot begin repository ticks')
455
+ },
456
+ async finishRepoTick(repo: string) {
457
+ own('finishRepoTick', 'repo', repo)
458
+ throw new Error('phase sessions cannot finish repository ticks')
459
+ },
426
460
  async heartbeatRepo(repo: string, holder: string): Promise<boolean> {
427
461
  own('heartbeatRepo', 'repo', repo)
428
462
  return store.heartbeatRepo(repo, holder)
@@ -0,0 +1,240 @@
1
+ import { decodeLog } from '../kernel/log-index-value'
2
+ /** The consumer boundary for current reductions. Raw event reads are for event output. */
3
+ import type { BuildStore } from './types'
4
+ import { validateReducerValue } from './reducer-value-validation'
5
+ import type {
6
+ buildReadFactsReducer,
7
+ buildStreamSeedReducer,
8
+ repositoryReadFactsReducer,
9
+ } from '../kernel/read-facts'
10
+ import { publicationStateReducer } from '../processes/publication-state'
11
+ import type { SnapshotScope } from './snapshots'
12
+
13
+ type Reader = Pick<BuildStore, 'getReducerValue'>
14
+ export async function readBuildStreamSeed(store: Reader, slug: string) {
15
+ return readValue<ReturnType<typeof buildStreamSeedReducer.finish>>(
16
+ store,
17
+ { kind: 'build', slug },
18
+ 'buildStreamSeed',
19
+ )
20
+ }
21
+ export async function readBuildFacts(store: Reader, slug: string) {
22
+ const result = await readValue<ReturnType<typeof buildReadFactsReducer.finish>>(
23
+ store,
24
+ { kind: 'build', slug },
25
+ 'buildReadFacts',
26
+ )
27
+ const value = result.value
28
+ return {
29
+ cursor: result.cursor,
30
+ value: {
31
+ ...value,
32
+ log: decodeLog(value.log),
33
+ publication: publicationStateReducer.finish(value.publication),
34
+ },
35
+ }
36
+ }
37
+ async function readValue<T>(
38
+ store: Reader,
39
+ scope: SnapshotScope,
40
+ reducer: string,
41
+ ): Promise<{ cursor: number; value: T }> {
42
+ const result = await store.getReducerValue(scope, { reducer })
43
+ if (!validateReducerValue(reducer, result.value))
44
+ throw new Error(`invalid persisted value for ${reducer}`)
45
+ // The generated validator checks the complete finished contract before decoding.
46
+ return { cursor: result.cursor, value: result.value as T }
47
+ }
48
+
49
+ export type RepositoryReadFacts = ReturnType<typeof repositoryReadFactsReducer.finish>
50
+ export async function readRepositoryFacts(
51
+ store: Reader & Pick<BuildStore, 'getRepo'>,
52
+ repo: string,
53
+ knownPresence?: boolean,
54
+ ) {
55
+ let absent = false
56
+ try {
57
+ absent = knownPresence === undefined ? (await store.getRepo(repo)) === null : !knownPresence
58
+ } catch {
59
+ // Lease/record metadata can be unavailable while durable values remain readable.
60
+ return readValue<RepositoryReadFacts>(store, { kind: 'repo', repo }, 'repositoryReadFacts')
61
+ }
62
+ if (!absent)
63
+ return readValue<RepositoryReadFacts>(store, { kind: 'repo', repo }, 'repositoryReadFacts')
64
+ const { repositoryReadFactsReducer } = await import('../kernel/read-facts')
65
+ return {
66
+ cursor: 0,
67
+ value: repositoryReadFactsReducer.finish(repositoryReadFactsReducer.initial()),
68
+ }
69
+ }
70
+
71
+ type Selectors = {
72
+ setupStreak: ReturnType<typeof import('../processes/build-runner').setupStreakReducer.finish>
73
+ baseBranch: ReturnType<
74
+ typeof import('../processes/dispatcher-selectors').baseBranchReducer.finish
75
+ >
76
+ publishedBranchHead: ReturnType<
77
+ typeof import('../processes/build-runner').publishedBranchHeadReducer.finish
78
+ >
79
+ verifyDiffBase: ReturnType<
80
+ typeof import('../processes/build-runner').verifyDiffBaseReducer.finish
81
+ >
82
+ recordedBaseSha: ReturnType<
83
+ typeof import('../config/pipeline-source').recordedBaseShaReducer.finish
84
+ >
85
+ }
86
+ export async function readBuildSelector<N extends keyof Selectors>(
87
+ store: Reader,
88
+ slug: string,
89
+ name: N,
90
+ ): Promise<Selectors[N]> {
91
+ if (name === 'setupStreak')
92
+ return (await readValue<Selectors[N]>(store, { kind: 'build', slug }, name)).value
93
+ return (await readValue<{ value?: Selectors[N] }>(store, { kind: 'build', slug }, `${name}Value`))
94
+ .value.value as Selectors[N]
95
+ }
96
+
97
+ export async function readPhaseFailures(
98
+ store: Reader,
99
+ slug: string,
100
+ phase: import('../ontology').Phase,
101
+ round: number,
102
+ ) {
103
+ const result = await store.getReducerValue(
104
+ { kind: 'build', slug },
105
+ { reducer: 'phaseFailures', args: { phase, round } },
106
+ )
107
+ if (!validateReducerValue('phaseFailures', result.value))
108
+ throw new Error('invalid phaseFailures value')
109
+ return result.value as unknown as ReturnType<
110
+ ReturnType<typeof import('../processes/build-runner').phaseFailuresReducer>['finish']
111
+ >
112
+ }
113
+
114
+ export async function readDispatchBudget(
115
+ store: Reader,
116
+ slug: string,
117
+ infrastructureOwnsWorkspace: boolean,
118
+ ) {
119
+ const result = await store.getReducerValue(
120
+ { kind: 'build', slug },
121
+ { reducer: 'dispatchFailureBudget', args: { infrastructureOwnsWorkspace } },
122
+ )
123
+ if (!validateReducerValue('dispatchFailureBudget', result.value))
124
+ throw new Error('invalid dispatchFailureBudget value')
125
+ return {
126
+ cursor: result.cursor,
127
+ value: result.value as unknown as ReturnType<
128
+ ReturnType<
129
+ typeof import('../processes/dispatch-failure-budget').dispatchFailureBudgetReducer
130
+ >['finish']
131
+ >,
132
+ }
133
+ }
134
+
135
+ export async function readDeferralLedger(store: Reader, slug: string) {
136
+ return readValue<import('../kernel/auto-merge').DeferralLedger>(
137
+ store,
138
+ { kind: 'build', slug },
139
+ 'currentDeferralObservation',
140
+ )
141
+ }
142
+
143
+ export async function readRepositoryAttention(store: Reader, repo: string) {
144
+ return readValue<import('../kernel/repository-attention').RepositoryAttentionState>(
145
+ store,
146
+ { kind: 'repo', repo },
147
+ 'repositoryAttention',
148
+ )
149
+ }
150
+
151
+ export type CurrentBuildFacts = Awaited<ReturnType<typeof readBuildFacts>>['value']
152
+
153
+ export async function readTerminalGuard(
154
+ store: Reader,
155
+ slug: string,
156
+ phase: import('../ontology').Phase,
157
+ round: number,
158
+ session: string,
159
+ ) {
160
+ const result = await store.getReducerValue(
161
+ { kind: 'build', slug },
162
+ { reducer: 'terminalGuard', args: { phase, round, session } },
163
+ )
164
+ if (!validateReducerValue('terminalGuard', result.value))
165
+ throw new Error('invalid terminalGuard value')
166
+ return result.value as { diagnostic?: string }
167
+ }
168
+
169
+ export async function readOpenTick(store: Reader, repo: string, run: string, historical = true) {
170
+ return (
171
+ (await readDispatcherRunFacts(store, repo, run, historical)).value.boundary ===
172
+ 'dispatcher.tick-started'
173
+ )
174
+ }
175
+ export async function readPinnedAssets(store: Reader, slug: string) {
176
+ return readValue<ReturnType<typeof import('./ticket-assets').pinnedAssetsReducer.finish>>(
177
+ store,
178
+ { kind: 'build', slug },
179
+ 'pinnedAssets',
180
+ )
181
+ }
182
+
183
+ /** Digests are reductions too. Read persisted per-build digests so repeated
184
+ * discovery never transfers all historical digest-relevant event rows. */
185
+ export async function readPersistedBuildDigests(
186
+ store: Reader & Pick<BuildStore, 'listBuilds'>,
187
+ repo: string,
188
+ records?: import('./types').BuildRecord[],
189
+ ) {
190
+ const entries = await Promise.all(
191
+ (records ?? (await store.listBuilds()))
192
+ .filter((record) => record.repo === repo)
193
+ .map(async (record) => {
194
+ const result = await readValue<
195
+ ReturnType<typeof import('./digest').buildDigestReducer.finish>
196
+ >(store, { kind: 'build', slug: record.slug }, 'buildDigest')
197
+ return [record.slug, { slug: record.slug, ...result.value }] as const
198
+ }),
199
+ )
200
+ return new Map(entries)
201
+ }
202
+
203
+ /** Keep the batch boundary for hosted callers; adapter implementations use
204
+ * readPersistedBuildDigests so each digest still comes from a persisted value. */
205
+ export function readBuildDigests(store: Pick<BuildStore, 'getRepoBuildDigests'>, repo: string) {
206
+ return store.getRepoBuildDigests(repo)
207
+ }
208
+
209
+ /** Current/recent runs use the shared cache. Set historical=false only when
210
+ * checking this process's fresh invocation, whose missing start means no prior
211
+ * lifecycle facts; arbitrary older holder IDs must retain historical recovery. */
212
+ export async function readDispatcherRunFacts(
213
+ store: Reader,
214
+ repo: string,
215
+ run: string,
216
+ historical = true,
217
+ ) {
218
+ const repository = await readValue<RepositoryReadFacts>(
219
+ store,
220
+ { kind: 'repo', repo },
221
+ 'repositoryReadFacts',
222
+ )
223
+ const recent = repository.value.recentRuns.find(([id]) => id === run)
224
+ if ((recent && recent[1].start !== undefined) || !historical)
225
+ return {
226
+ cursor: repository.cursor,
227
+ value: recent?.[1] ?? ({} as import('../kernel/read-facts').DispatcherRunFacts),
228
+ }
229
+
230
+ const result = await store.getReducerValue(
231
+ { kind: 'repo', repo },
232
+ { reducer: 'dispatcherRunFacts', args: { run } },
233
+ )
234
+ if (!validateReducerValue('dispatcherRunFacts', result.value))
235
+ throw new Error('invalid dispatcherRunFacts value')
236
+ return {
237
+ cursor: result.cursor,
238
+ value: result.value as import('../kernel/read-facts').DispatcherRunFacts,
239
+ }
240
+ }