@defrex/autobuild 1.5.0 → 1.6.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 (74) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +85 -14
  3. package/docs/answering-blocked-builds.md +7 -4
  4. package/docs/architecture.md +38 -10
  5. package/docs/configuration.md +55 -5
  6. package/docs/dispatcher.md +2 -2
  7. package/docs/glossary.md +1 -1
  8. package/docs/operating.md +1 -1
  9. package/docs/operator-api.md +14 -2
  10. package/docs/plugin-authoring.md +4 -0
  11. package/docs/remote-store-protocol.md +14 -4
  12. package/docs/restacking.md +4 -0
  13. package/docs/tickets.md +1 -1
  14. package/docs/troubleshooting.md +1 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/attention.ts +2 -0
  17. package/packages/core/src/cli/dashboard/model.ts +14 -4
  18. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  19. package/packages/core/src/cli/dashboard/render.ts +3 -0
  20. package/packages/core/src/cli/dispatch-preflight.ts +4 -1
  21. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  22. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  23. package/packages/core/src/cli/dispatch.ts +368 -98
  24. package/packages/core/src/cli/help.ts +4 -2
  25. package/packages/core/src/cli/repo-lease.ts +225 -0
  26. package/packages/core/src/cli/repository-status.ts +3 -1
  27. package/packages/core/src/cli/status.ts +13 -13
  28. package/packages/core/src/cli/wait.ts +4 -1
  29. package/packages/core/src/cli/watch.ts +15 -4
  30. package/packages/core/src/config/schema.ts +38 -2
  31. package/packages/core/src/events/catalog.ts +2 -0
  32. package/packages/core/src/events/payloads.ts +15 -0
  33. package/packages/core/src/events/policy.ts +2 -0
  34. package/packages/core/src/events/repository.ts +2 -0
  35. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +196 -230
  36. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  37. package/packages/core/src/kernel/engine.ts +13 -6
  38. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  39. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  40. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  41. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  42. package/packages/core/src/kernel/log-index.ts +1 -1
  43. package/packages/core/src/kernel/node-landing.ts +2 -1
  44. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  45. package/packages/core/src/kernel/reducer.ts +58 -4
  46. package/packages/core/src/kernel/ticket-preparation.ts +11 -7
  47. package/packages/core/src/operator/query.ts +15 -12
  48. package/packages/core/src/ports/tickets/create.ts +19 -5
  49. package/packages/core/src/ports/types.ts +4 -0
  50. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  51. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  52. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  53. package/packages/core/src/ports/workspace/vercel-sandbox.ts +3 -0
  54. package/packages/core/src/processes/build-runner.ts +2 -1
  55. package/packages/core/src/processes/dispatcher.ts +231 -41
  56. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  57. package/packages/core/src/processes/harvest-child.ts +4 -2
  58. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  59. package/packages/core/src/processes/harvest-runner.ts +246 -17
  60. package/packages/core/src/scenarios/harness.ts +145 -35
  61. package/packages/core/src/store/reduced-reads.ts +10 -0
  62. package/packages/core/src/store/reducer-value-shapes.json +1463 -1215
  63. package/packages/core/src/store/remote/released-clients.json +11 -0
  64. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  65. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  66. package/packages/core/src/testing/reduced-read-budget.ts +339 -2
  67. package/skills/guide/SKILL.md +53 -17
  68. package/skills/guide/references/operator-api.md +14 -2
  69. package/skills/guide/references/plugin-authoring.md +4 -0
  70. package/skills/guide/references/remote-store-protocol.md +14 -4
  71. package/skills/guide/references/restacking.md +4 -0
  72. package/skills/operate/SKILL.md +50 -11
  73. package/skills/tickets/SKILL.md +4 -2
  74. package/templates/hosted-service/package.json +2 -2
@@ -24,6 +24,7 @@ import { gitRewrite } from '../ports/forge/git-rewrite'
24
24
  * agents never touch the remote, so a journal IS the remote) and
25
25
  * FakeTicketSource (§13 — projections flow outward only).
26
26
  */
27
+ import type { afterEach as BunAfterEach, test as BunTest } from 'bun:test'
27
28
  import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
28
29
  import { tmpdir } from 'node:os'
29
30
  import { dirname, join } from 'node:path'
@@ -56,7 +57,7 @@ import type {
56
57
  TicketSource,
57
58
  WorkspaceProvider,
58
59
  } from '../ports/types'
59
- import { GitWorktreeProvider, spawnExec } from '../ports/workspace/git-worktree'
60
+ import { GitWorktreeProvider, spawnExec, type Exec } from '../ports/workspace/git-worktree'
60
61
  import { InProcessBuildExecution } from '../ports/workspace/in-process-build-execution'
61
62
  import { BuildRunner, LeaseHeldError, SetupFailureError } from '../processes/build-runner'
62
63
  import {
@@ -151,8 +152,11 @@ export const GIT_ID = [
151
152
  'commit.gpgsign=false',
152
153
  ]
153
154
 
154
- export async function git(args: string[], cwd: string): Promise<string> {
155
- const result = await spawnExec(['git', ...args], { cwd })
155
+ export async function git(args: string[], cwd: string, signal?: AbortSignal): Promise<string> {
156
+ const result = await spawnExec(['git', ...args], {
157
+ cwd,
158
+ ...(signal === undefined ? {} : { signal }),
159
+ })
156
160
  if (result.exitCode !== 0) {
157
161
  throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`)
158
162
  }
@@ -176,25 +180,30 @@ export async function writeFileIn(dir: string, rel: string, content: string): Pr
176
180
  return path
177
181
  }
178
182
 
179
- async function initOrigin(dir: string, configToml: string, noRemote = false): Promise<string> {
183
+ async function initOrigin(
184
+ dir: string,
185
+ configToml: string,
186
+ noRemote = false,
187
+ signal?: AbortSignal,
188
+ ): Promise<string> {
180
189
  // Reconcile fetches the current base from the conventional `origin` remote
181
190
  // at phase startup. Keep that seam real in every integration scenario: the
182
191
  // dispatcher works from `dir`, while a separate bare repo is its remote.
183
192
  const remote = join(dirname(dir), 'remote.git')
184
193
  if (!noRemote) {
185
194
  await mkdir(remote, { recursive: true })
186
- await git(['init', '--bare', '-q', '-b', 'main'], remote)
195
+ await git(['init', '--bare', '-q', '-b', 'main'], remote, signal)
187
196
  }
188
197
 
189
198
  await mkdir(dir, { recursive: true })
190
- await git(['init', '-q', '-b', 'main'], dir)
191
- if (!noRemote) await git(['remote', 'add', 'origin', remote], dir)
199
+ await git(['init', '-q', '-b', 'main'], dir, signal)
200
+ if (!noRemote) await git(['remote', 'add', 'origin', remote], dir, signal)
192
201
  // No `.ab/` ignore here — see commitAll: the product establishes it.
193
202
  await writeFile(join(dir, 'autobuild.toml'), configToml)
194
203
  await writeFile(join(dir, 'README.md'), 'e2e origin\n')
195
- await git(['add', '-A'], dir)
196
- await git([...GIT_ID, 'commit', '-q', '-m', 'initial'], dir)
197
- if (!noRemote) await git(['push', '-q', '-u', 'origin', 'main'], dir)
204
+ await git(['add', '-A'], dir, signal)
205
+ await git([...GIT_ID, 'commit', '-q', '-m', 'initial'], dir, signal)
206
+ if (!noRemote) await git(['push', '-q', '-u', 'origin', 'main'], dir, signal)
198
207
  return remote
199
208
  }
200
209
 
@@ -294,6 +303,8 @@ export interface E2eHarness {
294
303
  /** Run the most recently launched BuildRunner to its park point (§11). */
295
304
  runLatest(): Promise<BuildState>
296
305
  events(slug: string): Promise<AbEvent[]>
306
+ /** Idempotent: every call after the first returns the first call's promise,
307
+ * so a scenario's own `finally` and scenarioScope can both invoke it. */
297
308
  cleanup(): Promise<void>
298
309
  }
299
310
 
@@ -446,17 +457,30 @@ export async function makeHarness(opts: {
446
457
  /** Execute scripted phase commands through the private `ab` launcher on
447
458
  * PATH, forcing production ambient-env parsing and Store reopening. */
448
459
  processCli?: boolean
460
+ /** Owned by scenarioScope: aborting kills harness-routed subprocesses and
461
+ * stops harness entry points. */
462
+ signal?: AbortSignal
449
463
  }): Promise<E2eHarness> {
464
+ const signal = opts.signal
465
+ const exec: Exec =
466
+ signal === undefined
467
+ ? spawnExec
468
+ : (cmd, o) =>
469
+ spawnExec(cmd, {
470
+ ...o,
471
+ signal: o.signal === undefined ? signal : AbortSignal.any([o.signal, signal]),
472
+ })
450
473
  const tmp = await mkdtemp(join(tmpdir(), 'ab-e2e-'))
451
474
  try {
475
+ signal?.throwIfAborted()
452
476
  const originPath = join(tmp, 'origin')
453
477
  const configToml = opts.configToml ?? CONFIG_TOML
454
- const remote = await initOrigin(originPath, configToml, opts.localGitForge === true)
478
+ const remote = await initOrigin(originPath, configToml, opts.localGitForge === true, signal)
455
479
  // Git canonicalizes temporary paths on macOS (`/var` → `/private/var`).
456
480
  // Records and every dispatch caller must use that same repository identity.
457
481
  const origin = await realpath(originPath)
458
482
  const remoteUpdater = join(tmp, 'remote-updater')
459
- if (opts.localGitForge !== true) await git(['clone', '-q', remote, remoteUpdater], tmp)
483
+ if (opts.localGitForge !== true) await git(['clone', '-q', remote, remoteUpdater], tmp, signal)
460
484
 
461
485
  const clock = steppingClock()
462
486
  const ids = sequentialIds()
@@ -472,9 +496,9 @@ export async function makeHarness(opts: {
472
496
  // Ad-hoc scenario configs predating mandatory runtime defaults stay explicit
473
497
  // at the harness boundary rather than relying on production wiring.
474
498
  config.roles.default ??= { runtime: 'scripted' }
475
- await git(['config', 'user.name', 'ab-e2e'], origin)
476
- await git(['config', 'user.email', 'ab-e2e@example.invalid'], origin)
477
- await git(['config', 'commit.gpgsign', 'false'], origin)
499
+ await git(['config', 'user.name', 'ab-e2e'], origin, signal)
500
+ await git(['config', 'user.email', 'ab-e2e@example.invalid'], origin, signal)
501
+ await git(['config', 'commit.gpgsign', 'false'], origin, signal)
478
502
  const forge = new FakeForge({
479
503
  gatePresence: opts.gatePresence ?? 'present',
480
504
  ...(opts.pluginForge?.prAttachments === true ? { prAttachments: true } : {}),
@@ -482,7 +506,10 @@ export async function makeHarness(opts: {
482
506
  })
483
507
  // This fixture's served bare repository is the authoritative forge, even
484
508
  // when FakeForge supplies the scripted PR surface.
485
- const served = new LocalGitForge({ repoRoot: opts.localGitForge === true ? origin : remote })
509
+ const served = new LocalGitForge({
510
+ repoRoot: opts.localGitForge === true ? origin : remote,
511
+ exec,
512
+ })
486
513
  const scriptedBranch = forge.remoteBranchSha.bind(forge)
487
514
  forge.remoteBranchSha = async (branch) =>
488
515
  forge.remoteBranches.has(branch) ? scriptedBranch(branch) : served.remoteBranchSha(branch)
@@ -490,11 +517,11 @@ export async function makeHarness(opts: {
490
517
  const recordPush = forge.pushBranch.bind(forge)
491
518
  forge.pushBranch = async (cwd, branch, sha) => {
492
519
  await recordPush(cwd, branch, sha)
493
- await git(['push', '-q', 'origin', `HEAD:refs/heads/${branch}`], cwd)
520
+ await git(['push', '-q', 'origin', `HEAD:refs/heads/${branch}`], cwd, signal)
494
521
  }
495
- forge.rewrite = gitRewrite(spawnExec, false)
522
+ forge.rewrite = gitRewrite(exec, false)
496
523
  let selectedForge: Forge =
497
- opts.localGitForge === true ? new LocalGitForge({ repoRoot: origin }) : forge
524
+ opts.localGitForge === true ? new LocalGitForge({ repoRoot: origin, exec }) : forge
498
525
  let plugins: PluginRegistry | undefined
499
526
  if (opts.pluginForge !== undefined) {
500
527
  plugins = createPluginRegistry()
@@ -515,7 +542,7 @@ export async function makeHarness(opts: {
515
542
  const worktreeRoot = join(tmp, 'worktrees')
516
543
  const workspaces =
517
544
  opts.createWorkspaceProvider === undefined
518
- ? new GitWorktreeProvider({ root: worktreeRoot })
545
+ ? new GitWorktreeProvider({ root: worktreeRoot, exec })
519
546
  : await opts.createWorkspaceProvider({ config, repoRoot: origin, worktreeRoot })
520
547
 
521
548
  const launched: Array<{ slug: string; runner: BuildRunner; instance: string }> = []
@@ -571,7 +598,7 @@ export async function makeHarness(opts: {
571
598
  env,
572
599
  workspacePath: ws,
573
600
  forge: selectedForge,
574
- exec: spawnExec,
601
+ exec,
575
602
  ids,
576
603
  clock,
577
604
  stdout: (line) => out.push(line),
@@ -637,7 +664,7 @@ export async function makeHarness(opts: {
637
664
  store: activeStore.scopeBuild(slug),
638
665
  config,
639
666
  ...(opts.verifyCycleConfig
640
- ? { readVerifyPipeline: () => readVerifyPipeline(workspacePath, spawnExec) }
667
+ ? { readVerifyPipeline: () => readVerifyPipeline(workspacePath, exec) }
641
668
  : {}),
642
669
  ...(opts.pinnedConfig
643
670
  ? {
@@ -662,7 +689,7 @@ export async function makeHarness(opts: {
662
689
  workspacePath,
663
690
  branch: record.branch ?? `ab/${slug}`,
664
691
  slug,
665
- exec: spawnExec,
692
+ exec,
666
693
  forge: selectedForge,
667
694
  ids,
668
695
  clock,
@@ -700,12 +727,19 @@ export async function makeHarness(opts: {
700
727
  forge: selectedForge,
701
728
  config: opts.dispatcherConfig?.(structuredClone(config)) ?? config,
702
729
  repo: origin,
703
- exec: spawnExec,
730
+ exec,
704
731
  launchRunner,
705
732
  ...(opts.getConfig ? { getConfig: opts.getConfig } : {}),
706
733
  ids,
707
734
  clock,
708
735
  })
736
+ if (signal !== undefined) {
737
+ const tick = dispatcher.tick.bind(dispatcher)
738
+ dispatcher.tick = (...args) => {
739
+ signal.throwIfAborted()
740
+ return tick(...args)
741
+ }
742
+ }
709
743
  const wiring: DispatchWiring = {
710
744
  store: activeStore,
711
745
  tickets: ticketSource,
@@ -744,6 +778,7 @@ export async function makeHarness(opts: {
744
778
  ...(plugins !== undefined ? { plugins } : {}),
745
779
  }
746
780
 
781
+ let cleaned: Promise<void> | undefined
747
782
  return {
748
783
  tmp,
749
784
  origin,
@@ -765,14 +800,16 @@ export async function makeHarness(opts: {
765
800
  if (opts.localGitForge === true) {
766
801
  throw new Error('advanceRemote is unavailable for a no-remote local-git harness')
767
802
  }
803
+ signal?.throwIfAborted()
768
804
  for (const [path, content] of Object.entries(changes)) {
769
805
  await writeFileIn(remoteUpdater, path, content)
770
806
  }
771
807
  const sha = await commitAll(remoteUpdater, message)
772
- await git(['push', '-q', 'origin', 'main'], remoteUpdater)
808
+ await git(['push', '-q', 'origin', 'main'], remoteUpdater, signal)
773
809
  return sha
774
810
  },
775
811
  async runLatest(): Promise<BuildState> {
812
+ signal?.throwIfAborted()
776
813
  const entry = launched.at(-1)
777
814
  if (entry === undefined) throw new Error('runLatest: nothing launched')
778
815
  try {
@@ -784,16 +821,17 @@ export async function makeHarness(opts: {
784
821
  }
785
822
  },
786
823
  events: (slug) => store.getEvents(slug),
787
- cleanup: async () => {
788
- try {
789
- if (!snapshotsOff) await assertSnapshotEquivalence(store, origin)
790
- await activeStore.close()
791
- if (activeStore !== store) await store.close()
792
- await adapted?.cleanup?.()
793
- } finally {
794
- await rm(tmp, { recursive: true, force: true })
795
- }
796
- },
824
+ cleanup: () =>
825
+ (cleaned ??= (async () => {
826
+ try {
827
+ if (!snapshotsOff) await assertSnapshotEquivalence(store, origin)
828
+ await activeStore.close()
829
+ if (activeStore !== store) await store.close()
830
+ await adapted?.cleanup?.()
831
+ } finally {
832
+ await rm(tmp, { recursive: true, force: true })
833
+ }
834
+ })()),
797
835
  }
798
836
  } catch (error) {
799
837
  await rm(tmp, { recursive: true, force: true })
@@ -801,6 +839,78 @@ export async function makeHarness(opts: {
801
839
  }
802
840
  }
803
841
 
842
+ // ── Scenario lifetime scope ──────────────────────────────────────────────────
843
+
844
+ /** A harness maker bound to one scenario's lifetime. */
845
+ export type Make = (opts: Parameters<typeof makeHarness>[0]) => Promise<E2eHarness>
846
+
847
+ /**
848
+ * Own every harness a scenario creates from the moment creation starts. Bun
849
+ * runs `afterEach` after a timed-out test but never the abandoned body's
850
+ * `finally`, so the scope's hook aborts the case's signal (killing
851
+ * harness-routed subprocesses and stopping the next harness entry point),
852
+ * drains the body, and disposes every harness before the next case starts.
853
+ * A timed-out case's late rejection and cleanup errors are swallowed; it is
854
+ * already reported as timed out. A case that settled keeps its own outcome,
855
+ * and its cleanup errors fail the hook.
856
+ *
857
+ * Bun's `test` and `afterEach` are passed in so the harness itself never
858
+ * imports `bun:test`.
859
+ */
860
+ export function scenarioScope(bun: { test: typeof BunTest; afterEach: typeof BunAfterEach }) {
861
+ interface Case {
862
+ controller: AbortController
863
+ abandoned: boolean
864
+ settled: boolean
865
+ run: Promise<void>
866
+ created: Promise<E2eHarness>[]
867
+ }
868
+ let current: Case | undefined
869
+ bun.afterEach(async () => {
870
+ const c = current
871
+ current = undefined
872
+ if (c === undefined) return
873
+ const timedOut = !c.settled
874
+ // Set before any await: a late rejection from the drained body is swallowed.
875
+ c.abandoned = true
876
+ c.controller.abort(new Error('scenario ended'))
877
+ await c.run.catch(() => {})
878
+ const errors: unknown[] = []
879
+ for (const created of c.created) {
880
+ // A failed creation already removed its own temporary directory.
881
+ const h = await created.catch(() => undefined)
882
+ await h?.cleanup().catch((error: unknown) => errors.push(error))
883
+ }
884
+ if (errors.length > 0 && !timedOut) throw errors[0]
885
+ }, 30_000)
886
+ return (name: string, body: (makeHarness: Make) => Promise<void>, timeout?: number): void =>
887
+ bun.test(
888
+ name,
889
+ () => {
890
+ const c: Case = {
891
+ controller: new AbortController(),
892
+ abandoned: false,
893
+ settled: false,
894
+ run: Promise.resolve(),
895
+ created: [],
896
+ }
897
+ const make: Make = (opts) => {
898
+ const created = makeHarness({ ...opts, signal: c.controller.signal })
899
+ c.created.push(created)
900
+ return created
901
+ }
902
+ current = c
903
+ c.run = body(make).finally(() => {
904
+ c.settled = true
905
+ })
906
+ return c.run.catch((error: unknown) => {
907
+ if (!c.abandoned) throw error
908
+ })
909
+ },
910
+ timeout,
911
+ )
912
+ }
913
+
804
914
  // ── Default (§15.6 happy-path) handlers over the REAL CLI ────────────────────
805
915
 
806
916
  /**
@@ -64,6 +64,16 @@ async function readValue<T>(
64
64
  return { cursor: result.cursor, value: result.value as T }
65
65
  }
66
66
 
67
+ /** One served constant-size value naming the current hosted harvest
68
+ * authority; no `getRepo` call, no event download. */
69
+ export async function readHostedHarvestAuthority(store: Reader, repo: string) {
70
+ return readValue<
71
+ ReturnType<
72
+ typeof import('../processes/harvest-execution-state').hostedHarvestAuthorityReducer.finish
73
+ >
74
+ >(store, { kind: 'repo', repo }, 'hostedHarvestAuthority')
75
+ }
76
+
67
77
  export type RepositoryReadFacts = ReturnType<typeof repositoryReadFactsReducer.finish>
68
78
  export async function readRepositoryFacts(
69
79
  store: Reader & Pick<BuildStore, 'getRepo'>,