@defrex/autobuild 1.0.0-beta.3 → 1.0.0-beta.4

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 (130) hide show
  1. package/SPEC.md +317 -20
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +166 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +87 -2
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +4 -1
  10. package/docs/restacking.md +4 -1
  11. package/docs/setup.md +20 -0
  12. package/docs/spec-standard.md +23 -5
  13. package/package.json +3 -3
  14. package/packages/core/src/cli/artifact.ts +5 -4
  15. package/packages/core/src/cli/attention.ts +2 -0
  16. package/packages/core/src/cli/binary-direct.ts +190 -0
  17. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  18. package/packages/core/src/cli/binary.ts +24 -210
  19. package/packages/core/src/cli/build-control.ts +105 -2
  20. package/packages/core/src/cli/context.ts +41 -1
  21. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  22. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  23. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  24. package/packages/core/src/cli/dashboard/model.ts +34 -10
  25. package/packages/core/src/cli/dashboard/render.ts +24 -2
  26. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  27. package/packages/core/src/cli/dispatch-args.ts +53 -0
  28. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  29. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  30. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  31. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  32. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  33. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  34. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  35. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  36. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  37. package/packages/core/src/cli/dispatch-process.ts +22 -90
  38. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  39. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  40. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  41. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  42. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  43. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  44. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  45. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  46. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  47. package/packages/core/src/cli/dispatch.ts +604 -60
  48. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  49. package/packages/core/src/cli/harvest.ts +28 -11
  50. package/packages/core/src/cli/help.ts +6 -3
  51. package/packages/core/src/cli/installation.ts +5 -3
  52. package/packages/core/src/cli/main-checkout.ts +59 -0
  53. package/packages/core/src/cli/main.ts +15 -45
  54. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  55. package/packages/core/src/cli/repo-state.ts +3 -58
  56. package/packages/core/src/cli/repository-status.ts +67 -3
  57. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  58. package/packages/core/src/cli/status.ts +57 -3
  59. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  60. package/packages/core/src/cli/wait.ts +3 -0
  61. package/packages/core/src/cli/watch.ts +7 -0
  62. package/packages/core/src/config/live.ts +1 -0
  63. package/packages/core/src/config/schema.ts +8 -4
  64. package/packages/core/src/distribution-packaging.ts +116 -0
  65. package/packages/core/src/events/catalog.ts +6 -0
  66. package/packages/core/src/events/payloads.ts +53 -9
  67. package/packages/core/src/events/policy.ts +25 -0
  68. package/packages/core/src/events/repository.ts +184 -4
  69. package/packages/core/src/events/runtime.ts +16 -0
  70. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  71. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  72. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  73. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  74. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  75. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  76. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  77. package/packages/core/src/kernel/harvest.ts +98 -4
  78. package/packages/core/src/kernel/integration-attention.ts +20 -0
  79. package/packages/core/src/kernel/integration-state.ts +80 -11
  80. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  81. package/packages/core/src/kernel/mixed-version.ts +34 -0
  82. package/packages/core/src/kernel/node-polling.ts +160 -0
  83. package/packages/core/src/kernel/read-facts.ts +40 -5
  84. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  85. package/packages/core/src/kernel/reducer.ts +75 -14
  86. package/packages/core/src/kernel/service-facts.ts +11 -4
  87. package/packages/core/src/operator/presentation.ts +7 -0
  88. package/packages/core/src/operator/query.ts +6 -2
  89. package/packages/core/src/operator/registry.ts +1 -1
  90. package/packages/core/src/plugins/load.ts +4 -1
  91. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  92. package/packages/core/src/ports/forge/contract.ts +29 -0
  93. package/packages/core/src/ports/forge/github.ts +189 -61
  94. package/packages/core/src/ports/forge-failure.ts +1 -0
  95. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  96. package/packages/core/src/ports/runner/session-env.ts +1 -0
  97. package/packages/core/src/ports/types.ts +10 -0
  98. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  99. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  100. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  101. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  102. package/packages/core/src/processes/build-child-exit.ts +5 -26
  103. package/packages/core/src/processes/build-runner.ts +81 -11
  104. package/packages/core/src/processes/dispatcher.ts +254 -23
  105. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  106. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  107. package/packages/core/src/processes/execution-settlement.ts +16 -7
  108. package/packages/core/src/processes/harvest-runner.ts +328 -292
  109. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  110. package/packages/core/src/runtime-identity.ts +22 -3
  111. package/packages/core/src/store/contract.ts +153 -0
  112. package/packages/core/src/store/local/store.ts +197 -72
  113. package/packages/core/src/store/reduced-reads.ts +8 -0
  114. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  115. package/packages/core/src/store/remote/client.ts +43 -0
  116. package/packages/core/src/store/repo-state-events.ts +20 -3
  117. package/packages/core/src/store/types.ts +7 -0
  118. package/skills/guide/SKILL.md +231 -23
  119. package/skills/guide/references/integration-tree.md +87 -2
  120. package/skills/guide/references/operator-api.md +53 -4
  121. package/skills/guide/references/plugin-authoring.md +45 -4
  122. package/skills/guide/references/remote-store-protocol.md +4 -1
  123. package/skills/guide/references/restacking.md +4 -1
  124. package/skills/guide/references/setup.md +20 -0
  125. package/skills/guide/references/spec-standard.md +23 -5
  126. package/skills/harvest/SKILL.md +4 -0
  127. package/skills/harvest-review/SKILL.md +4 -0
  128. package/skills/operate/SKILL.md +78 -8
  129. package/skills/spec/SKILL.md +19 -1
  130. package/skills/tickets/SKILL.md +19 -0
@@ -1,3 +1,6 @@
1
+ import { bunRuntimeArguments } from '../cli/runtime-spawn'
2
+ import { spawnUsingRuntime } from '../cli/dispatch-runtime-use'
3
+ import { distributionRoot } from '../distribution'
1
4
  import { distributionPath } from '../distribution'
2
5
  import { DEFAULT_PROCESS_GROUP_STOP_TIMEOUT_MS } from './process-group'
3
6
 
@@ -20,16 +23,20 @@ export function launchProcessGroupReaper(
20
23
  options: ProcessGroupReaperOptions,
21
24
  spawn: typeof Bun.spawn = Bun.spawn,
22
25
  ): number {
23
- const child = spawn([process.execPath, distributionPath('bin', 'ab-process-group-reaper.ts')], {
24
- env: {
25
- ...process.env,
26
- [PROCESS_GROUP_REAPER_OPTIONS_ENV]: JSON.stringify(options),
27
- },
28
- stdin: 'ignore',
29
- stdout: 'ignore',
30
- stderr: 'ignore',
31
- detached: true,
32
- })
26
+ const { child, release } = spawnUsingRuntime(distributionRoot(), () =>
27
+ spawn(bunRuntimeArguments(distributionPath('bin', 'ab-process-group-reaper.ts')), {
28
+ env: {
29
+ ...process.env,
30
+ AB_DISPATCH_GENERATION: undefined,
31
+ [PROCESS_GROUP_REAPER_OPTIONS_ENV]: JSON.stringify(options),
32
+ },
33
+ stdin: 'ignore',
34
+ stdout: 'ignore',
35
+ stderr: 'ignore',
36
+ detached: true,
37
+ }),
38
+ )
39
+ void child.exited.finally(release)
33
40
  child.unref()
34
41
  return child.pid
35
42
  }
@@ -1,5 +1,6 @@
1
1
  import { readFileSync, realpathSync } from 'node:fs'
2
- import { join } from 'node:path'
2
+ import { join, resolve } from 'node:path'
3
+ import type { RuntimeIdentity } from './events/runtime'
3
4
  import { execFileSync } from 'node:child_process'
4
5
  import { distributionRoot } from './distribution'
5
6
  import { AUTOBUILD_VERSION } from './store/remote/version'
@@ -7,12 +8,23 @@ import { AUTOBUILD_VERSION } from './store/remote/version'
7
8
  /** Capture the distribution's source identity, never the target checkout. */
8
9
  export function captureRuntimeIdentity(root = distributionRoot()) {
9
10
  let commit = 'unknown'
11
+ let version = AUTOBUILD_VERSION
12
+ try {
13
+ const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
14
+ if (typeof manifest.version === 'string') version = manifest.version
15
+ } catch {}
16
+ let location = resolve(root)
17
+ try {
18
+ location = realpathSync(location)
19
+ } catch {}
20
+ let kind: 'source' | 'package' = 'package'
10
21
  try {
11
22
  const top = execFileSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], {
12
23
  encoding: 'utf8',
13
24
  stdio: ['ignore', 'pipe', 'ignore'],
14
25
  }).trim()
15
26
  if (realpathSync(top) !== realpathSync(root)) throw new Error('not distribution Git metadata')
27
+ kind = 'source'
16
28
  commit =
17
29
  execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], {
18
30
  encoding: 'utf8',
@@ -22,13 +34,20 @@ export function captureRuntimeIdentity(root = distributionRoot()) {
22
34
  // npm records the source commit in published manifests when available.
23
35
  try {
24
36
  const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
25
- if (typeof manifest.gitHead === 'string' && /^[a-f0-9]{40,64}$/.test(manifest.gitHead))
37
+ if (
38
+ typeof manifest.gitHead === 'string' &&
39
+ /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(manifest.gitHead)
40
+ )
26
41
  commit = manifest.gitHead
27
42
  } catch {
28
43
  /* Identity is diagnostic and must never block dispatch. */
29
44
  }
30
45
  }
31
- return Object.freeze({ version: AUTOBUILD_VERSION, commit })
46
+ return Object.freeze({
47
+ version,
48
+ commit,
49
+ source: Object.freeze({ kind, location }),
50
+ }) satisfies RuntimeIdentity
32
51
  }
33
52
  export const RUNTIME_IDENTITY = captureRuntimeIdentity()
34
53
  export function formatDispatcherError(error: unknown): string {
@@ -690,6 +690,49 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
690
690
  })
691
691
  })
692
692
 
693
+ test('accepted targets and relaunch requests survive validated reductions and neutral settlement', async () => {
694
+ await withStore(factory, undefined, async (store) => {
695
+ const slug = 'relaunch-contract'
696
+ await store.createBuild(sampleBuildInput(slug))
697
+ await store.append(slug, buildCreatedWrite())
698
+ const runtime = {
699
+ version: '1',
700
+ commit: 'unknown',
701
+ source: { kind: 'package' as const, location: '/old' },
702
+ }
703
+ const targetRuntime = { ...runtime, source: { ...runtime.source, location: '/new' } }
704
+ await store.append(slug, {
705
+ actor: DISPATCHER,
706
+ type: 'execution.started',
707
+ payload: { provider: 'local', workspaceRef: 'w', instance: 'i' },
708
+ })
709
+ await store.append(slug, {
710
+ actor: DISPATCHER,
711
+ type: 'execution.drain-authorized',
712
+ payload: { instance: 'i', correlation: 'h', run: 'old', runtime, targetRuntime },
713
+ })
714
+ const request = { instance: 'i', correlation: 'h', from: runtime, to: targetRuntime }
715
+ await store.append(slug, {
716
+ actor: KERNEL,
717
+ type: 'execution.relaunch-requested',
718
+ payload: request,
719
+ })
720
+ expect(
721
+ (await readBuildFacts(store, slug)).value.state.drainingExecutions?.i?.relaunch,
722
+ ).toEqual(request)
723
+ await store.append(slug, {
724
+ actor: DISPATCHER,
725
+ type: 'execution.ended',
726
+ payload: { instance: 'i', workspaceRef: 'w', outcome: 'relaunch', exitCode: 0 },
727
+ })
728
+ const facts = (await readBuildFacts(store, slug)).value
729
+ expect(facts.lastExecution).toBe('relaunch')
730
+ expect(facts.executionNoProgress.count).toBe(0)
731
+ expect(facts.state.drainingExecutions?.i?.relaunch).toEqual(request)
732
+ expect(facts.state.drainingExecutions?.i?.authorization).toBeUndefined()
733
+ })
734
+ })
735
+
693
736
  test('executionOpen and reclaimPending follow the openExecution and pendingPrAttachmentReclaims rules', async () => {
694
737
  await withStore(factory, undefined, async (store) => {
695
738
  const repo = 'acme/dg-work'
@@ -1123,6 +1166,9 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
1123
1166
  ...counters,
1124
1167
  forgeRequests: {
1125
1168
  total: i,
1169
+ restPrimary: i,
1170
+ restNotModified: 0,
1171
+ graphql: 0,
1126
1172
  unattributed: 0,
1127
1173
  builds: i ? [{ build: 'active', requests: i }] : [],
1128
1174
  complete: true,
@@ -1135,6 +1181,8 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
1135
1181
  expect(finished.outcome === 'completed' && finished.counters.forgeRequests?.total).toBe(
1136
1182
  i,
1137
1183
  )
1184
+ if (finished.outcome === 'completed')
1185
+ expect(finished.counters.forgeRequests?.restPrimary).toBe(i)
1138
1186
  expect(result!.events).toEqual([])
1139
1187
  expect((await store.getRepo(repo))!.tick!.finished!.completedAt).toBe(
1140
1188
  clock().toISOString(),
@@ -2198,6 +2246,111 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
2198
2246
  }
2199
2247
  }
2200
2248
 
2249
+ test('upgrade handoffs and failures remain run-scoped through reduced reads', async () => {
2250
+ await withStore(factory, undefined, async (store) => {
2251
+ const repo = 'acme/upgrades'
2252
+ await store.ensureRepo(repo)
2253
+ const identity = {
2254
+ correlation: 'upgrade',
2255
+ run: 'old',
2256
+ lineage: 'launcher',
2257
+ from: {
2258
+ version: '1.0.0',
2259
+ commit: 'unknown',
2260
+ source: { kind: 'package' as const, location: '/old' },
2261
+ },
2262
+ target: {
2263
+ mode: 'pinned' as const,
2264
+ key: 'two',
2265
+ version: '2.0.0',
2266
+ source: 'main',
2267
+ base: 'main',
2268
+ sha: 'a'.repeat(40),
2269
+ },
2270
+ }
2271
+ const handoff = {
2272
+ ...identity,
2273
+ to: { ...identity.from, version: '2.0.0' },
2274
+ root: '/cache',
2275
+ cacheId: 'candidate',
2276
+ }
2277
+ await store.appendRepo(repo, {
2278
+ actor: DISPATCHER,
2279
+ type: 'dispatcher.upgrade-detected',
2280
+ payload: identity,
2281
+ })
2282
+ await store.appendRepo(repo, {
2283
+ actor: DISPATCHER,
2284
+ type: 'dispatcher.handoff-started',
2285
+ payload: handoff,
2286
+ })
2287
+ await store.appendRepo(repo, {
2288
+ actor: DISPATCHER,
2289
+ type: 'dispatcher.upgrade-failed',
2290
+ payload: { ...identity, run: 'foreign', reason: 'registry unavailable' },
2291
+ })
2292
+ await store.appendRepo(repo, {
2293
+ actor: DISPATCHER,
2294
+ type: 'dispatcher.upgrade-target-resolved',
2295
+ payload: {
2296
+ run: 'foreign',
2297
+ lineage: identity.lineage,
2298
+ target: { ...identity.target, mode: 'source', sha: 'b'.repeat(40) },
2299
+ },
2300
+ })
2301
+ const first = (await readRepositoryFacts(store, repo)).value.upgrades
2302
+ expect(first.runs.old?.handoff?.payload).toEqual(handoff)
2303
+ expect(first.runs.old?.completed).toBeUndefined()
2304
+ expect(first.runs.foreign?.failure?.payload.reason).toBe('registry unavailable')
2305
+ expect(first.runs.foreign?.resolved?.payload.target.sha).toBe('b'.repeat(40))
2306
+ await store.appendRepo(repo, {
2307
+ actor: DISPATCHER,
2308
+ type: 'dispatcher.handoff-completed',
2309
+ payload: { ...handoff, successor: 'new' },
2310
+ })
2311
+ await store.appendRepo(repo, {
2312
+ actor: DISPATCHER,
2313
+ type: 'dispatcher.runtime-rolled-back',
2314
+ payload: {
2315
+ correlation: 'rollback',
2316
+ run: 'restored',
2317
+ lineage: identity.lineage,
2318
+ predecessor: 'old',
2319
+ successor: 'new',
2320
+ handoff: identity.correlation,
2321
+ takeoverAt: '2026-01-01T00:00:00.000Z',
2322
+ failures: 3,
2323
+ failed: handoff.to,
2324
+ restored: handoff.from,
2325
+ failedRoot: '/cache/new',
2326
+ restoredRoot: '/cache/old',
2327
+ target: identity.target,
2328
+ reason: 'three failed exits',
2329
+ },
2330
+ })
2331
+ expect(
2332
+ (await readRepositoryFacts(store, repo)).value.upgrades.holds[identity.lineage]?.payload
2333
+ .failed.version,
2334
+ ).toBe('2.0.0')
2335
+ await store.appendRepo(repo, {
2336
+ actor: DISPATCHER,
2337
+ type: 'dispatcher.rollback-hold-cleared',
2338
+ payload: {
2339
+ correlation: 'rollback',
2340
+ run: 'restored',
2341
+ lineage: identity.lineage,
2342
+ target: { ...identity.target, key: 'changed' },
2343
+ },
2344
+ })
2345
+ const rollbackState = (await readRepositoryFacts(store, repo)).value.upgrades
2346
+ expect(rollbackState.holds[identity.lineage]).toBeUndefined()
2347
+ expect(rollbackState.lastRollback?.payload.restored.version).toBe(handoff.from.version)
2348
+ const next = (await readRepositoryFacts(store, repo)).value.upgrades
2349
+ expect(next.runs.old?.completed?.payload.successor).toBe('new')
2350
+ expect(next.runs.foreign?.failure).toBeDefined()
2351
+ })
2352
+ })
2353
+
2201
2354
  test('latest-only scans stay bounded across scans, runs and repositories', async () => {
2202
2355
  await withStore(factory, undefined, async (store) => {
2203
2356
  for (const repo of ['acme/scans', 'acme/foreign-scans']) await store.ensureRepo(repo)
@@ -329,6 +329,8 @@ interface PreparedArtifact {
329
329
  }
330
330
 
331
331
  export interface SqliteBuildStoreOptions {
332
+ /** Preflight opens the existing schema without running initialization DDL. */
333
+ bootstrap?: boolean
332
334
  database: Database
333
335
  blobs: BlobStore
334
336
  clock?: Clock
@@ -368,79 +370,198 @@ export class SqliteBuildStore implements BuildStore {
368
370
  // each other's writes (§7.2.1). Cross-process write serialization comes
369
371
  // from `writeTx` (BEGIN IMMEDIATE), not from this timeout alone.
370
372
  this.sqlite.exec('PRAGMA busy_timeout = 5000')
371
- this.sqlite.exec('PRAGMA journal_mode = WAL')
372
- for (const ddl of BOOTSTRAP_DDL) this.sqlite.exec(ddl)
373
- for (const table of ['events', 'repo_events']) {
374
- const columns = this.sqlite.query(`PRAGMA table_info('${table}')`).all() as { name: string }[]
375
- if (!columns.some((column) => column.name === 'compatibility'))
376
- this.sqlite.exec(`ALTER TABLE ${table} ADD COLUMN compatibility TEXT`)
377
- }
378
- // Stores created before `repo_origin` existed keep working: add the column
379
- // idempotently when a pre-existing table lacks it (the bootstrap DDL above
380
- // covers fresh stores). No migration framework — one guarded ALTER at open.
381
- const repoColumns = this.sqlite.query("PRAGMA table_info('repo_streams')").all() as {
382
- name: string
383
- }[]
384
- if (!repoColumns.some((column) => column.name === 'tick'))
385
- this.sqlite.exec('ALTER TABLE repo_streams ADD COLUMN tick TEXT')
386
- const columns = this.sqlite.query("PRAGMA table_info('builds')").all() as Array<{
387
- name: string
388
- }>
389
- if (!columns.some((column) => column.name === 'repo_origin')) {
390
- this.sqlite.exec('ALTER TABLE builds ADD COLUMN repo_origin TEXT')
391
- }
392
- for (const [name, type] of [
393
- ['node_writer_holder', 'TEXT'],
394
- ['node_writer_expires_at', 'TEXT'],
395
- ['node_writer_ttl_ms', 'INTEGER'],
396
- ]) {
397
- if (!columns.some((column) => column.name === name))
398
- this.sqlite.exec(`ALTER TABLE builds ADD COLUMN ${name} ${type}`)
399
- }
400
- // Stores created before session-scoped streams existed keep working: add
401
- // the streams.session column idempotently when a pre-existing table lacks
402
- // it (the repo_origin precedent). A pre-existing local database also keeps
403
- // its old `scope_kind` CHECK, so it cannot host session-scoped streams —
404
- // unreachable in product terms because sessions are hosted-only and
405
- // nothing local creates one; fresh stores (and every contract-suite
406
- // database) get the widened DDL above. Rebuilding the table to widen a
407
- // CHECK would risk local data for an unreachable path and is deliberately
408
- // not attempted.
409
- const streamColumns = this.sqlite.query("PRAGMA table_info('streams')").all() as Array<{
410
- name: string
411
- }>
412
- if (!streamColumns.some((column) => column.name === 'session')) {
413
- this.sqlite.exec('ALTER TABLE streams ADD COLUMN session TEXT')
414
- }
415
- // Stores created before the listStreams creation-order tiebreak existed
416
- // keep working: add the streams.creation_seq column idempotently when a
417
- // pre-existing table lacks it (the sessions.creation_seq precedent), then
418
- // backfill by rowid — rowid equals insertion order because streams are
419
- // never deleted (retention prunes stream_chunks only), so the backfill is
420
- // consistent with the pinned creation-order contract. Legacy
421
- // same-millisecond ties are genuinely unorderable; the pinned guarantee
422
- // applies from the migrated store onward.
423
- if (!streamColumns.some((column) => column.name === 'creation_seq')) {
424
- this.sqlite.exec('ALTER TABLE streams ADD COLUMN creation_seq INTEGER NOT NULL DEFAULT 0')
425
- this.sqlite.exec('UPDATE streams SET creation_seq = rowid')
426
- }
427
- // Stores created before the listSessions creation-order tiebreak existed
428
- // keep working: add the sessions.creation_seq column idempotently when a
429
- // pre-existing table lacks it (the repo_origin precedent), then backfill
430
- // by rowid — rowid equals insertion order because sessions are never
431
- // deleted, so the backfill is consistent with the pinned creation-order
432
- // contract. Legacy same-millisecond ties are genuinely unorderable; the
433
- // pinned guarantee applies from the migrated store onward.
434
- const sessionColumns = this.sqlite.query("PRAGMA table_info('sessions')").all() as Array<{
435
- name: string
436
- }>
437
- if (!sessionColumns.some((column) => column.name === 'creation_seq')) {
438
- this.sqlite.exec('ALTER TABLE sessions ADD COLUMN creation_seq INTEGER NOT NULL DEFAULT 0')
439
- this.sqlite.exec('UPDATE sessions SET creation_seq = rowid')
373
+ if (opts.bootstrap !== false) {
374
+ this.sqlite.exec('PRAGMA journal_mode = WAL')
375
+ for (const ddl of BOOTSTRAP_DDL) this.sqlite.exec(ddl)
376
+ for (const table of ['events', 'repo_events']) {
377
+ const columns = this.sqlite.query(`PRAGMA table_info('${table}')`).all() as {
378
+ name: string
379
+ }[]
380
+ if (!columns.some((column) => column.name === 'compatibility'))
381
+ this.sqlite.exec(`ALTER TABLE ${table} ADD COLUMN compatibility TEXT`)
382
+ }
383
+ // Stores created before `repo_origin` existed keep working: add the column
384
+ // idempotently when a pre-existing table lacks it (the bootstrap DDL above
385
+ // covers fresh stores). No migration framework — one guarded ALTER at open.
386
+ const repoColumns = this.sqlite.query("PRAGMA table_info('repo_streams')").all() as {
387
+ name: string
388
+ }[]
389
+ if (!repoColumns.some((column) => column.name === 'tick'))
390
+ this.sqlite.exec('ALTER TABLE repo_streams ADD COLUMN tick TEXT')
391
+ const columns = this.sqlite.query("PRAGMA table_info('builds')").all() as Array<{
392
+ name: string
393
+ }>
394
+ if (!columns.some((column) => column.name === 'repo_origin')) {
395
+ this.sqlite.exec('ALTER TABLE builds ADD COLUMN repo_origin TEXT')
396
+ }
397
+ for (const [name, type] of [
398
+ ['node_writer_holder', 'TEXT'],
399
+ ['node_writer_expires_at', 'TEXT'],
400
+ ['node_writer_ttl_ms', 'INTEGER'],
401
+ ]) {
402
+ if (!columns.some((column) => column.name === name))
403
+ this.sqlite.exec(`ALTER TABLE builds ADD COLUMN ${name} ${type}`)
404
+ }
405
+ // Stores created before session-scoped streams existed keep working: add
406
+ // the streams.session column idempotently when a pre-existing table lacks
407
+ // it (the repo_origin precedent). A pre-existing local database also keeps
408
+ // its old `scope_kind` CHECK, so it cannot host session-scoped streams —
409
+ // unreachable in product terms because sessions are hosted-only and
410
+ // nothing local creates one; fresh stores (and every contract-suite
411
+ // database) get the widened DDL above. Rebuilding the table to widen a
412
+ // CHECK would risk local data for an unreachable path and is deliberately
413
+ // not attempted.
414
+ const streamColumns = this.sqlite.query("PRAGMA table_info('streams')").all() as Array<{
415
+ name: string
416
+ }>
417
+ if (!streamColumns.some((column) => column.name === 'session')) {
418
+ this.sqlite.exec('ALTER TABLE streams ADD COLUMN session TEXT')
419
+ }
420
+ // Stores created before the listStreams creation-order tiebreak existed
421
+ // keep working: add the streams.creation_seq column idempotently when a
422
+ // pre-existing table lacks it (the sessions.creation_seq precedent), then
423
+ // backfill by rowid — rowid equals insertion order because streams are
424
+ // never deleted (retention prunes stream_chunks only), so the backfill is
425
+ // consistent with the pinned creation-order contract. Legacy
426
+ // same-millisecond ties are genuinely unorderable; the pinned guarantee
427
+ // applies from the migrated store onward.
428
+ if (!streamColumns.some((column) => column.name === 'creation_seq')) {
429
+ this.sqlite.exec('ALTER TABLE streams ADD COLUMN creation_seq INTEGER NOT NULL DEFAULT 0')
430
+ this.sqlite.exec('UPDATE streams SET creation_seq = rowid')
431
+ }
432
+ // Stores created before the listSessions creation-order tiebreak existed
433
+ // keep working: add the sessions.creation_seq column idempotently when a
434
+ // pre-existing table lacks it (the repo_origin precedent), then backfill
435
+ // by rowid — rowid equals insertion order because sessions are never
436
+ // deleted, so the backfill is consistent with the pinned creation-order
437
+ // contract. Legacy same-millisecond ties are genuinely unorderable; the
438
+ // pinned guarantee applies from the migrated store onward.
439
+ const sessionColumns = this.sqlite.query("PRAGMA table_info('sessions')").all() as Array<{
440
+ name: string
441
+ }>
442
+ if (!sessionColumns.some((column) => column.name === 'creation_seq')) {
443
+ this.sqlite.exec('ALTER TABLE sessions ADD COLUMN creation_seq INTEGER NOT NULL DEFAULT 0')
444
+ this.sqlite.exec('UPDATE sessions SET creation_seq = rowid')
445
+ }
440
446
  }
441
447
  this.db = drizzle(this.sqlite)
442
448
  }
443
449
 
450
+ async inspectDispatcherOverlap(signal: AbortSignal) {
451
+ signal.throwIfAborted()
452
+ // Compare the actual, untouched catalog with this provider's requirements.
453
+ // No migrations are run against the live database during preflight.
454
+ const expected = new Database(':memory:')
455
+ try {
456
+ for (const ddl of BOOTSTRAP_DDL) expected.exec(ddl)
457
+ // ALTER appends columns, and legacy creation-order columns have a DEFAULT
458
+ // used only for backfill. Neither changes the target's runtime requirements.
459
+ const catalog = (database: Database) => {
460
+ const quote = (name: string) => `'${name.replaceAll("'", "''")}'`
461
+ const objects = database
462
+ .query(
463
+ "SELECT type, name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name",
464
+ )
465
+ .all() as Array<{ type: string; name: string; sql: string }>
466
+ return objects.map((object) => {
467
+ if (object.type !== 'table') return object
468
+ const columns = database
469
+ .query(`PRAGMA table_xinfo(${quote(object.name)})`)
470
+ .all() as Array<{
471
+ cid: number
472
+ name: string
473
+ type: string
474
+ notnull: number
475
+ dflt_value: string | null
476
+ pk: number
477
+ hidden: number
478
+ }>
479
+ const indexes = database
480
+ .query(`PRAGMA index_list(${quote(object.name)})`)
481
+ .all() as Array<{
482
+ name: string
483
+ unique: number
484
+ origin: string
485
+ partial: number
486
+ }>
487
+ // Keep key order, collation and uniqueness, but ignore physical column
488
+ // offsets and the automatically assigned index sequence number.
489
+ const indexShapes = indexes
490
+ .map((index) => ({
491
+ name: index.name,
492
+ unique: index.unique,
493
+ origin: index.origin,
494
+ partial: index.partial,
495
+ columns: (
496
+ database.query(`PRAGMA index_xinfo(${quote(index.name)})`).all() as Array<
497
+ Record<string, unknown>
498
+ >
499
+ ).map(({ cid: _cid, ...column }) => column),
500
+ }))
501
+ .sort((a, b) => a.name.localeCompare(b.name))
502
+ // PRAGMAs expose keys and foreign keys, but not CHECK constraints.
503
+ // Retain balanced CHECK expressions so an older, narrower streams
504
+ // constraint still requires cutover rather than being called equivalent.
505
+ const checks: string[] = []
506
+ const matcher = /\bCHECK\s*\(/gi
507
+ for (const match of object.sql.matchAll(matcher)) {
508
+ const begin = match.index + match[0].length
509
+ let depth = 1,
510
+ quoted = false,
511
+ end = begin
512
+ for (; end < object.sql.length && depth; end++) {
513
+ const char = object.sql[end]
514
+ if (char === "'") {
515
+ if (quoted && object.sql[end + 1] === "'") {
516
+ end++
517
+ continue
518
+ }
519
+ quoted = !quoted
520
+ }
521
+ if (!quoted) {
522
+ if (char === '(') depth++
523
+ if (char === ')') depth--
524
+ }
525
+ }
526
+ checks.push(
527
+ object.sql
528
+ .slice(begin, end - 1)
529
+ .replace(/\s+/g, ' ')
530
+ .trim(),
531
+ )
532
+ }
533
+ return {
534
+ type: object.type,
535
+ name: object.name,
536
+ columns: columns
537
+ .map(({ cid: _cid, ...column }) => ({
538
+ ...column,
539
+ dflt_value:
540
+ column.name === 'creation_seq' &&
541
+ (object.name === 'sessions' || object.name === 'streams') &&
542
+ column.dflt_value === '0'
543
+ ? null
544
+ : column.dflt_value,
545
+ }))
546
+ .sort((a, b) => a.name.localeCompare(b.name)),
547
+ indexes: indexShapes,
548
+ foreignKeys: database.query(`PRAGMA foreign_key_list(${quote(object.name)})`).all(),
549
+ checks,
550
+ }
551
+ })
552
+ }
553
+ const compatible = JSON.stringify(catalog(this.sqlite)) === JSON.stringify(catalog(expected))
554
+ return {
555
+ compatible,
556
+ evidence: compatible
557
+ ? 'SQLite catalog matches target provider requirements without migration'
558
+ : 'SQLite catalog differs from target provider requirements; cutover required before initialization',
559
+ }
560
+ } finally {
561
+ expected.close()
562
+ }
563
+ }
564
+
444
565
  scopeBuild(slug: string): BuildScopedStore {
445
566
  return createBuildScopedStore(this, slug)
446
567
  }
@@ -2447,14 +2568,18 @@ export async function inspectLocalStoreSnapshot(rootDir: string): Promise<LocalS
2447
2568
  */
2448
2569
  export function openLocalStore(
2449
2570
  rootDir: string,
2450
- opts: { clock?: Clock; retention?: { maxRevisions?: number } } = {},
2571
+ opts: { clock?: Clock; retention?: { maxRevisions?: number }; bootstrap?: boolean } = {},
2451
2572
  ): SqliteBuildStore {
2452
- mkdirSync(rootDir, { recursive: true })
2453
- const database = new Database(join(rootDir, 'autobuild.sqlite'), { create: true })
2573
+ if (opts.bootstrap !== false) mkdirSync(rootDir, { recursive: true })
2574
+ const database = new Database(join(rootDir, 'autobuild.sqlite'), {
2575
+ readwrite: true,
2576
+ create: opts.bootstrap !== false,
2577
+ })
2454
2578
  const blobs = new DirBlobStore(join(rootDir, 'blobs'))
2455
2579
  return new SqliteBuildStore({
2456
2580
  database,
2457
2581
  blobs,
2582
+ bootstrap: opts.bootstrap,
2458
2583
  ...(opts.clock ? { clock: opts.clock } : {}),
2459
2584
  ...(opts.retention ? { retention: opts.retention } : {}),
2460
2585
  })
@@ -277,3 +277,11 @@ export async function readForgeHealth(store: Reader & Pick<BuildStore, 'getRepo'
277
277
  )
278
278
  return result.value.value
279
279
  }
280
+
281
+ export async function readDispatchUpgrade(store: Reader, repo: string) {
282
+ return readValue<import('../kernel/dispatch-upgrade').DispatchUpgradeState>(
283
+ store,
284
+ { kind: 'repo', repo },
285
+ 'dispatchUpgrade',
286
+ )
287
+ }