@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
@@ -17,6 +17,12 @@ import type { BuildDigest } from './types'
17
17
  * rows to exactly these, so a per-build type-filtered index keeps the scan's
18
18
  * cost growing with the actual signal, not with total history. */
19
19
  export const DIGEST_EVENT_TYPES = [
20
+ 'build.created',
21
+ 'integration.landed',
22
+ 'integration.audited',
23
+ 'node.opened',
24
+ 'node.contribution-recorded',
25
+ 'pr.closed',
20
26
  'build.completed',
21
27
  'build.aborted',
22
28
  'observation.recorded',
@@ -31,6 +37,10 @@ export const DIGEST_EVENT_TYPES = [
31
37
  * `pr-attachment.reclaimed` rows and `instance` for `execution.started` /
32
38
  * `execution.ended` rows instead of whole payloads. */
33
39
  export type DigestEventRow = Pick<AbEvent, 'type' | 'seq' | 'ts'> & {
40
+ auditRequested?: boolean
41
+ mergedSha?: string
42
+ nodeContribution?: BuildDigest['nodeContribution']
43
+ kind?: 'work' | 'node'
34
44
  hostedSeq?: number
35
45
  instance?: string
36
46
  }
@@ -45,6 +55,12 @@ export type DigestEvent = DigestEventRow
45
55
 
46
56
  /** The carried accumulator for `reduceBuildDigest`. */
47
57
  export interface DigestAcc {
58
+ integrationAuditPending?: true
59
+ mergedSha?: string
60
+ nodeContribution?: BuildDigest['nodeContribution']
61
+ kind?: 'work' | 'node'
62
+ nodeOpened?: true
63
+ prClosed?: true
48
64
  readinessChangeSeq?: number
49
65
  terminal?: BuildDigest['terminal']
50
66
  merged?: string
@@ -58,7 +74,7 @@ export interface DigestAcc {
58
74
  }
59
75
 
60
76
  /** Bump when `DigestAcc`'s shape or fold semantics change. */
61
- export const BUILD_DIGEST_REDUCER_VERSION = 3
77
+ export const BUILD_DIGEST_REDUCER_VERSION = 7
62
78
 
63
79
  export const buildDigestReducer: IncrementalReducer<
64
80
  DigestAcc,
@@ -69,12 +85,30 @@ export const buildDigestReducer: IncrementalReducer<
69
85
  initial: (): DigestAcc => ({ observations: [], hosted: [], reclaimed: [], openInstance: null }),
70
86
  fold(acc, events) {
71
87
  for (const event of events) {
72
- if (['pr.merged', 'build.completed', 'build.aborted'].includes(event.type))
88
+ if (
89
+ [
90
+ 'node.opened',
91
+ 'node.contribution-recorded',
92
+ 'pr.closed',
93
+ 'pr.merged',
94
+ 'build.completed',
95
+ 'build.aborted',
96
+ ].includes(event.type)
97
+ )
73
98
  acc.readinessChangeSeq = event.seq
99
+ if (event.type === 'integration.landed')
100
+ acc.integrationAuditPending = event.auditRequested ? true : undefined
101
+ if (event.type === 'integration.audited') acc.integrationAuditPending = undefined
102
+ if (event.type === 'build.created') acc.kind = event.kind
103
+ if (event.type === 'node.contribution-recorded') acc.nodeContribution = event.nodeContribution
104
+ if (event.type === 'node.opened') acc.nodeOpened = true
105
+ if (event.type === 'pr.closed') acc.prClosed = true
74
106
  if (event.type === 'build.completed') acc.terminal = 'done'
75
107
  else if (event.type === 'build.aborted') acc.terminal = 'aborted'
76
- else if (event.type === 'pr.merged') acc.merged = event.ts
77
- else if (event.type === 'observation.recorded')
108
+ else if (event.type === 'pr.merged') {
109
+ acc.merged = event.ts
110
+ acc.mergedSha = event.mergedSha
111
+ } else if (event.type === 'observation.recorded')
78
112
  acc.observations.push({ seq: event.seq, ts: event.ts })
79
113
  else if (event.type === 'pr-attachment.hosted') acc.hosted.push(event.seq)
80
114
  else if (event.type === 'pr-attachment.reclaimed') {
@@ -88,6 +122,12 @@ export const buildDigestReducer: IncrementalReducer<
88
122
  }
89
123
  },
90
124
  finish: ({
125
+ integrationAuditPending,
126
+ mergedSha,
127
+ nodeContribution,
128
+ kind,
129
+ nodeOpened,
130
+ prClosed,
91
131
  readinessChangeSeq,
92
132
  terminal,
93
133
  merged,
@@ -99,6 +139,14 @@ export const buildDigestReducer: IncrementalReducer<
99
139
  const reclaimedSet = new Set(reclaimed)
100
140
  const reclaimPending = hosted.some((seq) => !reclaimedSet.has(seq))
101
141
  return {
142
+ ...(integrationAuditPending ? { integrationAuditPending } : {}),
143
+ ...(mergedSha !== undefined ? { mergedSha } : {}),
144
+ ...(nodeContribution !== undefined
145
+ ? { nodeContribution: structuredClone(nodeContribution) }
146
+ : {}),
147
+ ...(kind !== undefined ? { kind } : {}),
148
+ ...(nodeOpened ? { nodeOpened } : {}),
149
+ ...(prClosed ? { prClosed } : {}),
102
150
  observations: [...observations],
103
151
  ...(readinessChangeSeq !== undefined ? { readinessChangeSeq } : {}),
104
152
  ...(merged !== undefined ? { merged } : {}),
@@ -15,19 +15,26 @@ import type { TicketRef } from '../../ontology'
15
15
  import type { TicketAssetEntry } from '../ticket-assets'
16
16
  import type { StreamPart } from '../streams/types'
17
17
 
18
- export const builds = sqliteTable('builds', {
19
- slug: text('slug').primaryKey(),
20
- repo: text('repo').notNull(),
21
- repoOrigin: text('repo_origin'),
22
- ticket: text('ticket', { mode: 'json' }).$type<TicketRef>(),
23
- branch: text('branch'),
24
- createdAt: text('created_at').notNull(),
25
- updatedAt: text('updated_at').notNull(),
26
- leaseHolder: text('lease_holder'),
27
- leaseExpiresAt: text('lease_expires_at'),
28
- leaseTtlMs: integer('lease_ttl_ms'),
29
- heartbeatAt: text('heartbeat_at'),
30
- })
18
+ export const builds = sqliteTable(
19
+ 'builds',
20
+ {
21
+ slug: text('slug').primaryKey(),
22
+ repo: text('repo').notNull(),
23
+ repoOrigin: text('repo_origin'),
24
+ ticket: text('ticket', { mode: 'json' }).$type<TicketRef>(),
25
+ branch: text('branch'),
26
+ createdAt: text('created_at').notNull(),
27
+ updatedAt: text('updated_at').notNull(),
28
+ leaseHolder: text('lease_holder'),
29
+ leaseExpiresAt: text('lease_expires_at'),
30
+ leaseTtlMs: integer('lease_ttl_ms'),
31
+ nodeWriterHolder: text('node_writer_holder'),
32
+ nodeWriterExpiresAt: text('node_writer_expires_at'),
33
+ nodeWriterTtlMs: integer('node_writer_ttl_ms'),
34
+ heartbeatAt: text('heartbeat_at'),
35
+ },
36
+ (t) => [index('builds_repo_created_slug').on(t.repo, t.createdAt, t.slug)],
37
+ )
31
38
 
32
39
  export const events = sqliteTable(
33
40
  'events',
@@ -56,6 +63,7 @@ export const repoStreams = sqliteTable('repo_streams', {
56
63
  leaseExpiresAt: text('lease_expires_at'),
57
64
  leaseTtlMs: integer('lease_ttl_ms'),
58
65
  heartbeatAt: text('heartbeat_at'),
66
+ tick: text('tick', { mode: 'json' }).$type<import('../types').RepoTickObservation>(),
59
67
  })
60
68
 
61
69
  export const repoEvents = sqliteTable(
@@ -222,3 +230,8 @@ export const streamChunks = sqliteTable(
222
230
  },
223
231
  (t) => [primaryKey({ columns: [t.stream, t.seq] })],
224
232
  )
233
+
234
+ export const repoChangePositions = sqliteTable('repo_change_positions', {
235
+ repo: text('repo').primaryKey(),
236
+ position: integer('position').notNull(),
237
+ })
@@ -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 local BuildStore (SPEC §7.2.1): SQLite + blob directory beneath an
3
13
  * explicitly resolved local state root. Repository/default selection belongs
@@ -43,7 +53,6 @@ import { createBuildScopedStore } from '../build-scope'
43
53
  import type { ReducerSnapshot, SnapshotScope } from '../snapshots'
44
54
  import { validateCreatedEvent } from '../new-build'
45
55
  import { createSessionScopedStore } from '../session-handle'
46
- import { DIGEST_EVENT_TYPES, type DigestEventRow, reduceBuildDigest } from '../digest'
47
56
  import {
48
57
  REPOSITORY_STATE_EVENT_TYPES,
49
58
  REPOSITORY_LATEST_EVENT_TYPES,
@@ -136,6 +145,24 @@ import {
136
145
  */
137
146
  // Exported for the schema-parity test, which pins this DDL against the
138
147
  // drizzle schema; schema.ts stays the source of truth, this is its inlined form.
148
+ export const REPO_CHANGE_DDL = `
149
+ CREATE TABLE IF NOT EXISTS repo_change_positions (repo TEXT PRIMARY KEY, position INTEGER NOT NULL);
150
+ CREATE INDEX IF NOT EXISTS builds_repo_created_slug ON builds(repo, created_at, slug);
151
+ CREATE TRIGGER IF NOT EXISTS builds_repo_change AFTER INSERT ON builds
152
+ BEGIN INSERT INTO repo_change_positions(repo, position) VALUES (NEW.repo, 1)
153
+ ON CONFLICT(repo) DO UPDATE SET position = position + 1; END;
154
+ CREATE TRIGGER IF NOT EXISTS repo_events_repo_change AFTER INSERT ON repo_events
155
+ BEGIN INSERT INTO repo_change_positions(repo, position) VALUES (NEW.repo, 1)
156
+ ON CONFLICT(repo) DO UPDATE SET position = position + 1; END;
157
+ CREATE TRIGGER IF NOT EXISTS events_repo_change AFTER INSERT ON events
158
+ BEGIN INSERT INTO repo_change_positions(repo, position) VALUES ((SELECT repo FROM builds WHERE slug = NEW.build), 1)
159
+ ON CONFLICT(repo) DO UPDATE SET position = position + 1; END;
160
+ CREATE TRIGGER IF NOT EXISTS repo_holder_change AFTER UPDATE OF lease_holder ON repo_streams
161
+ WHEN OLD.lease_holder IS NOT NEW.lease_holder
162
+ BEGIN INSERT INTO repo_change_positions(repo, position) VALUES (NEW.repo, 1)
163
+ ON CONFLICT(repo) DO UPDATE SET position = position + 1; END;
164
+ `
165
+
139
166
  export const BOOTSTRAP_DDL = [
140
167
  // Reducer snapshots: additive and idempotent, so databases that predate the
141
168
  // table gain it on open.
@@ -160,6 +187,9 @@ export const BOOTSTRAP_DDL = [
160
187
  lease_holder TEXT,
161
188
  lease_expires_at TEXT,
162
189
  lease_ttl_ms INTEGER,
190
+ node_writer_holder TEXT,
191
+ node_writer_expires_at TEXT,
192
+ node_writer_ttl_ms INTEGER,
163
193
  heartbeat_at TEXT
164
194
  )`,
165
195
  `CREATE TABLE IF NOT EXISTS events (
@@ -191,7 +221,8 @@ export const BOOTSTRAP_DDL = [
191
221
  lease_holder TEXT,
192
222
  lease_expires_at TEXT,
193
223
  lease_ttl_ms INTEGER,
194
- heartbeat_at TEXT
224
+ heartbeat_at TEXT,
225
+ tick TEXT
195
226
  )`,
196
227
  `CREATE TABLE IF NOT EXISTS repo_events (
197
228
  repo TEXT NOT NULL,
@@ -282,6 +313,7 @@ export const BOOTSTRAP_DDL = [
282
313
  parts TEXT NOT NULL,
283
314
  PRIMARY KEY (stream, seq)
284
315
  )`,
316
+ REPO_CHANGE_DDL,
285
317
  ] as const
286
318
 
287
319
  type BuildRow = typeof builds.$inferSelect
@@ -337,12 +369,25 @@ export class SqliteBuildStore implements BuildStore {
337
369
  // Stores created before `repo_origin` existed keep working: add the column
338
370
  // idempotently when a pre-existing table lacks it (the bootstrap DDL above
339
371
  // covers fresh stores). No migration framework — one guarded ALTER at open.
372
+ const repoColumns = this.sqlite.query("PRAGMA table_info('repo_streams')").all() as {
373
+ name: string
374
+ }[]
375
+ if (!repoColumns.some((column) => column.name === 'tick'))
376
+ this.sqlite.exec('ALTER TABLE repo_streams ADD COLUMN tick TEXT')
340
377
  const columns = this.sqlite.query("PRAGMA table_info('builds')").all() as Array<{
341
378
  name: string
342
379
  }>
343
380
  if (!columns.some((column) => column.name === 'repo_origin')) {
344
381
  this.sqlite.exec('ALTER TABLE builds ADD COLUMN repo_origin TEXT')
345
382
  }
383
+ for (const [name, type] of [
384
+ ['node_writer_holder', 'TEXT'],
385
+ ['node_writer_expires_at', 'TEXT'],
386
+ ['node_writer_ttl_ms', 'INTEGER'],
387
+ ]) {
388
+ if (!columns.some((column) => column.name === name))
389
+ this.sqlite.exec(`ALTER TABLE builds ADD COLUMN ${name} ${type}`)
390
+ }
346
391
  // Stores created before session-scoped streams existed keep working: add
347
392
  // the streams.session column idempotently when a pre-existing table lacks
348
393
  // it (the repo_origin precedent). A pre-existing local database also keeps
@@ -435,6 +480,7 @@ export class SqliteBuildStore implements BuildStore {
435
480
 
436
481
  private toRepoRecord(row: RepoRow): RepositoryRecord {
437
482
  return {
483
+ ...(row.tick ? { tick: structuredClone(row.tick) } : {}),
438
484
  repo: row.repo,
439
485
  createdAt: row.createdAt,
440
486
  updatedAt: row.updatedAt,
@@ -490,62 +536,45 @@ export class SqliteBuildStore implements BuildStore {
490
536
  return row ? this.toRecord(row) : null
491
537
  }
492
538
 
539
+ async getRepoChangePosition(repo: string): Promise<string> {
540
+ const row = this.sqlite
541
+ .query<{ position: string }, [string]>(
542
+ 'SELECT CAST(position AS TEXT) AS position FROM repo_change_positions WHERE repo = ?',
543
+ )
544
+ .get(repo)
545
+ return row?.position ?? '0'
546
+ }
547
+
548
+ async listBuildsForRepo(repo: string): Promise<BuildRecord[]> {
549
+ return this.db
550
+ .select()
551
+ .from(builds)
552
+ .where(eq(builds.repo, repo))
553
+ .orderBy(asc(builds.createdAt), asc(builds.slug))
554
+ .all()
555
+ .map((row) => this.toRecord(row))
556
+ }
557
+
493
558
  async listBuilds(): Promise<BuildRecord[]> {
494
- const rows = this.db.select().from(builds).orderBy(asc(builds.createdAt)).all()
559
+ const rows = this.db
560
+ .select()
561
+ .from(builds)
562
+ .orderBy(asc(builds.createdAt), asc(builds.slug))
563
+ .all()
495
564
  return rows.map((row) => this.toRecord(row))
496
565
  }
497
566
 
498
567
  async getRepoBuildDigests(repo: string): Promise<Map<string, BuildDigest>> {
499
- // From the builds side (AUT-487): the type filter lives in the ON clause
500
- // so a build whose log holds none of the digest-relevant event
501
- // types still yields its row — a join that starts from `events` would
502
- // silently drop such builds and break the operation's completeness
503
- // contract. Only the digest-relevant types are fetched, then one shared
504
- // derivation
505
- // per build, so the answer cannot drift from `reduceBuild`.
506
- const rows = this.sqlite
507
- .query(
508
- `SELECT b.slug AS slug, e.seq AS seq, e.ts AS ts, e.type AS type,
509
- CASE WHEN e.type = 'pr-attachment.reclaimed'
510
- THEN json_extract(e.payload, '$.hostedSeq') END AS hostedSeq,
511
- CASE WHEN e.type IN ('execution.started', 'execution.ended')
512
- THEN json_extract(e.payload, '$.instance') END AS instance
513
- FROM builds b
514
- LEFT JOIN events e
515
- ON e.build = b.slug AND e.type IN (${DIGEST_EVENT_TYPES.map(() => '?').join(', ')})
516
- WHERE b.repo = ?
517
- ORDER BY b.slug, e.seq`,
518
- )
519
- .all(...DIGEST_EVENT_TYPES, repo) as {
520
- slug: string
521
- seq: number | null
522
- ts: string | null
523
- type: string | null
524
- hostedSeq: number | null
525
- instance: string | null
526
- }[]
527
- const eventsByBuild = new Map<string, DigestEventRow[]>()
528
- for (const row of rows) {
529
- if (row.seq === null || row.ts === null || row.type === null) continue
530
- const events = eventsByBuild.get(row.slug) ?? []
531
- events.push({
532
- type: row.type as AbEvent['type'],
533
- seq: row.seq,
534
- ts: row.ts,
535
- ...(row.hostedSeq !== null ? { hostedSeq: row.hostedSeq } : {}),
536
- ...(row.instance !== null ? { instance: row.instance } : {}),
537
- })
538
- eventsByBuild.set(row.slug, events)
539
- }
540
- const digests = new Map<string, BuildDigest>()
541
- for (const row of rows) {
542
- if (digests.has(row.slug)) continue
543
- digests.set(row.slug, {
544
- slug: row.slug,
545
- ...reduceBuildDigest(eventsByBuild.get(row.slug) ?? []),
546
- })
547
- }
548
- return digests
568
+ return readPersistedBuildDigests(
569
+ this,
570
+ repo,
571
+ this.db
572
+ .select()
573
+ .from(builds)
574
+ .where(eq(builds.repo, repo))
575
+ .all()
576
+ .map((row) => this.toRecord(row)),
577
+ )
549
578
  }
550
579
 
551
580
  /** Current build-stream tail inside an open transaction. */
@@ -842,6 +871,69 @@ export class SqliteBuildStore implements BuildStore {
842
871
  return rows.map((row) => this.toMeta(row))
843
872
  }
844
873
 
874
+ async claimNodeWriter(slug: string, holder: string, ttlMs: number): Promise<boolean> {
875
+ return this.writeTx(() => {
876
+ const row = this.requireBuild(slug)
877
+ const now = this.clock().getTime()
878
+ const heldByOther =
879
+ row.nodeWriterHolder !== null &&
880
+ row.nodeWriterHolder !== holder &&
881
+ row.nodeWriterExpiresAt !== null &&
882
+ Date.parse(row.nodeWriterExpiresAt) > now
883
+ if (heldByOther) return false
884
+ this.db
885
+ .update(builds)
886
+ .set({
887
+ nodeWriterHolder: holder,
888
+ nodeWriterExpiresAt: new Date(now + ttlMs).toISOString(),
889
+ nodeWriterTtlMs: ttlMs,
890
+ updatedAt: new Date(now).toISOString(),
891
+ })
892
+ .where(eq(builds.slug, slug))
893
+ .run()
894
+ return true
895
+ })
896
+ }
897
+
898
+ async renewNodeWriter(slug: string, holder: string): Promise<boolean> {
899
+ return this.writeTx(() => {
900
+ const row = this.requireBuild(slug)
901
+ const now = this.clock().getTime()
902
+ const holds =
903
+ row.nodeWriterHolder === holder &&
904
+ row.nodeWriterExpiresAt !== null &&
905
+ Date.parse(row.nodeWriterExpiresAt) > now
906
+ if (!holds) return false
907
+ const nowIso = new Date(now).toISOString()
908
+ this.db
909
+ .update(builds)
910
+ .set({
911
+ nodeWriterExpiresAt: new Date(now + (row.nodeWriterTtlMs ?? 0)).toISOString(),
912
+ updatedAt: nowIso,
913
+ })
914
+ .where(eq(builds.slug, slug))
915
+ .run()
916
+ return true
917
+ })
918
+ }
919
+
920
+ async releaseNodeWriter(slug: string, holder: string): Promise<void> {
921
+ this.writeTx(() => {
922
+ const row = this.requireBuild(slug)
923
+ if (row.nodeWriterHolder !== holder) return
924
+ this.db
925
+ .update(builds)
926
+ .set({
927
+ nodeWriterHolder: null,
928
+ nodeWriterExpiresAt: null,
929
+ nodeWriterTtlMs: null,
930
+ updatedAt: this.now(),
931
+ })
932
+ .where(eq(builds.slug, slug))
933
+ .run()
934
+ })
935
+ }
936
+
845
937
  async claimLease(slug: string, holder: string, ttlMs: number): Promise<boolean> {
846
938
  return this.writeTx(() => {
847
939
  const row = this.requireBuild(slug)
@@ -922,9 +1014,12 @@ export class SqliteBuildStore implements BuildStore {
922
1014
  return row ? this.toRepoRecord(row) : null
923
1015
  }
924
1016
 
925
- private appendRepoInTx(repo: string, validated: RepositoryEventWrite): RepositoryEventEnvelope {
1017
+ private appendRepoInTx(
1018
+ repo: string,
1019
+ validated: RepositoryEventWrite,
1020
+ ts = this.now(),
1021
+ ): RepositoryEventEnvelope {
926
1022
  this.requireRepo(repo)
927
- const ts = this.now()
928
1023
  const row = this.db
929
1024
  .select({ max: sql<number | null>`max(${repoEvents.seq})` })
930
1025
  .from(repoEvents)
@@ -1092,11 +1187,91 @@ export class SqliteBuildStore implements BuildStore {
1092
1187
  return row?.tail
1093
1188
  }
1094
1189
 
1190
+ async getReducerValue(scope: SnapshotScope, request: ReducerValueRequest): Promise<ReducerValue> {
1191
+ // Reject invalid requests before touching storage.
1192
+ resolveReducerValue(scope, request)
1193
+ return readReducerValue(scope, request, {
1194
+ highWater: async () => {
1195
+ const tail = this.snapshotTail(scope)
1196
+ if (tail === undefined) throw new Error('unknown reducer scope')
1197
+ return tail
1198
+ },
1199
+ events: async (since, through) => {
1200
+ const key = scope.kind === 'build' ? scope.slug : scope.repo
1201
+ const rows = this.sqlite
1202
+ .query(
1203
+ scope.kind === 'build'
1204
+ ? 'SELECT * FROM events WHERE build=?1 AND seq>?2 AND seq<=?3 ORDER BY seq'
1205
+ : 'SELECT * FROM repo_events WHERE repo=?1 AND seq>?2 AND seq<=?3 ORDER BY seq',
1206
+ )
1207
+ .all(key, since, through) as {
1208
+ build?: string
1209
+ repo?: string
1210
+ seq: number
1211
+ ts: string
1212
+ actor: string
1213
+ type: string
1214
+ payload: string
1215
+ }[]
1216
+ return rows.map((row) => ({
1217
+ ...row,
1218
+ actor: JSON.parse(row.actor),
1219
+ payload: JSON.parse(row.payload),
1220
+ })) as (AbEvent | RepositoryEvent)[]
1221
+ },
1222
+ put: (key, snapshot) => this.putSnapshot(scope, key, snapshot),
1223
+ read: async (key) => {
1224
+ const row = this.sqlite
1225
+ .query(
1226
+ 'SELECT version, cursor, state FROM reducer_snapshots WHERE scope_kind=?1 AND scope_key=?2 AND reducer=?3',
1227
+ )
1228
+ .get(scope.kind, scope.kind === 'build' ? scope.slug : scope.repo, key) as {
1229
+ version: number
1230
+ cursor: number
1231
+ state: string
1232
+ } | null
1233
+ if (!row) return null
1234
+ let state: unknown = null
1235
+ try {
1236
+ state = JSON.parse(row.state)
1237
+ } catch {
1238
+ /* malformed cache */
1239
+ }
1240
+ return { snapshot: { version: row.version, cursor: row.cursor, state }, token: row.state }
1241
+ },
1242
+ repair: async (key, observed, snapshot) => {
1243
+ return this.sqlite.transaction(() => {
1244
+ const tail = this.snapshotTail(scope)
1245
+ if (tail === undefined || snapshot.cursor > tail) return false
1246
+ return (
1247
+ this.sqlite
1248
+ .query(
1249
+ `UPDATE reducer_snapshots SET version=?1, cursor=?2, state=?3, updated_at=?4 WHERE scope_kind=?5 AND scope_key=?6 AND reducer=?7 AND version=?8 AND cursor=?9 AND state=?10`,
1250
+ )
1251
+ .run(
1252
+ snapshot.version,
1253
+ snapshot.cursor,
1254
+ JSON.stringify(snapshot.state),
1255
+ this.clock().toISOString(),
1256
+ scope.kind,
1257
+ scope.kind === 'build' ? scope.slug : scope.repo,
1258
+ key,
1259
+ observed.snapshot.version,
1260
+ observed.snapshot.cursor,
1261
+ observed.token,
1262
+ ).changes > 0
1263
+ )
1264
+ })()
1265
+ },
1266
+ })
1267
+ }
1268
+
1095
1269
  async getReducerSnapshot(
1096
1270
  scope: SnapshotScope,
1097
1271
  reducer: string,
1098
1272
  version: number,
1099
1273
  ): Promise<ReducerSnapshot | null> {
1274
+ assertPublicSnapshotReducer(reducer)
1100
1275
  const tail = this.snapshotTail(scope)
1101
1276
  if (tail === undefined) return null
1102
1277
  const row = this.sqlite
@@ -1120,6 +1295,15 @@ export class SqliteBuildStore implements BuildStore {
1120
1295
  scope: SnapshotScope,
1121
1296
  reducer: string,
1122
1297
  snapshot: ReducerSnapshot,
1298
+ ): Promise<boolean> {
1299
+ assertPublicSnapshotReducer(reducer)
1300
+ return this.putSnapshot(scope, reducer, snapshot)
1301
+ }
1302
+
1303
+ private async putSnapshot(
1304
+ scope: SnapshotScope,
1305
+ reducer: string,
1306
+ snapshot: ReducerSnapshot,
1123
1307
  ): Promise<boolean> {
1124
1308
  const tail = this.snapshotTail(scope)
1125
1309
  if (tail === undefined || snapshot.cursor > tail) return false
@@ -1420,6 +1604,63 @@ export class SqliteBuildStore implements BuildStore {
1420
1604
  })
1421
1605
  }
1422
1606
 
1607
+ async beginRepoTick(repo: string, holder: string): Promise<string | null> {
1608
+ return this.writeTx(() => {
1609
+ const row = this.requireRepo(repo)
1610
+ if (
1611
+ row.leaseHolder !== holder ||
1612
+ !row.leaseExpiresAt ||
1613
+ Date.parse(row.leaseExpiresAt) <= this.clock().getTime()
1614
+ )
1615
+ return null
1616
+ const startedAt = this.now()
1617
+ const tick: RepoTickObservation = {
1618
+ run: holder,
1619
+ open: { startedAt },
1620
+ ...(row.tick?.finished ? { finished: row.tick.finished } : {}),
1621
+ }
1622
+ this.db
1623
+ .update(repoStreams)
1624
+ .set({ tick, updatedAt: startedAt })
1625
+ .where(eq(repoStreams.repo, repo))
1626
+ .run()
1627
+ return startedAt
1628
+ })
1629
+ }
1630
+
1631
+ async finishRepoTick(
1632
+ repo: string,
1633
+ holder: string,
1634
+ completion: RepoTickCompletion,
1635
+ events: RepositoryEventWrite[],
1636
+ ): Promise<RepoTickFinish | null> {
1637
+ const validated = validateTickFinish(holder, completion, events)
1638
+ return this.writeTx(() => {
1639
+ const row = this.requireRepo(repo)
1640
+ if (
1641
+ row.leaseHolder !== holder ||
1642
+ !row.leaseExpiresAt ||
1643
+ Date.parse(row.leaseExpiresAt) <= this.clock().getTime()
1644
+ )
1645
+ return null
1646
+ if (row.tick?.run !== holder || !row.tick.open) throw new Error('no open repository tick')
1647
+ const completedAt = this.now()
1648
+ const envelopes = validated.map((event) =>
1649
+ this.appendRepoInTx(repo, event, completedAt),
1650
+ ) as RepositoryEvent[]
1651
+ const observation: RepoTickObservation = {
1652
+ run: holder,
1653
+ finished: { ...completion, run: holder, startedAt: row.tick.open.startedAt, completedAt },
1654
+ }
1655
+ this.db
1656
+ .update(repoStreams)
1657
+ .set({ tick: observation, updatedAt: completedAt })
1658
+ .where(eq(repoStreams.repo, repo))
1659
+ .run()
1660
+ return { observation, events: envelopes }
1661
+ })
1662
+ }
1663
+
1423
1664
  async claimRepoLease(repo: string, holder: string, ttlMs: number): Promise<boolean> {
1424
1665
  return this.writeTx(() => {
1425
1666
  const row = this.requireRepo(repo)