@defrex/autobuild 1.0.0-beta.3 → 1.0.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 (168) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +362 -56
  3. package/bin/ab-dispatch-generation.ts +93 -0
  4. package/docs/agent-runtimes.md +157 -0
  5. package/docs/answering-blocked-builds.md +21 -3
  6. package/docs/architecture.md +166 -7
  7. package/docs/build-store.md +123 -0
  8. package/docs/builds.md +82 -0
  9. package/docs/cli.md +48 -0
  10. package/docs/configuration-overview.md +93 -0
  11. package/docs/configuration.md +1778 -188
  12. package/docs/dispatcher-hosting.md +115 -0
  13. package/docs/dispatcher.md +59 -0
  14. package/docs/forges.md +121 -0
  15. package/docs/getting-started.md +60 -0
  16. package/docs/glossary.md +60 -0
  17. package/docs/hosted-service.md +2 -2
  18. package/docs/intake.md +48 -0
  19. package/docs/integration-overview.md +81 -0
  20. package/docs/integration-tree.md +87 -2
  21. package/docs/integration.md +54 -0
  22. package/docs/operating.md +114 -0
  23. package/docs/operator-api.md +64 -11
  24. package/docs/operator-surfaces.md +90 -0
  25. package/docs/overview.md +49 -0
  26. package/docs/plugin-authoring.md +426 -0
  27. package/docs/remote-store-protocol.md +12 -9
  28. package/docs/restacking.md +4 -1
  29. package/docs/seams.md +66 -0
  30. package/docs/setup.md +28 -6
  31. package/docs/skills.md +119 -0
  32. package/docs/spec-standard.md +23 -5
  33. package/docs/ticket-sources.md +132 -0
  34. package/docs/tickets.md +69 -0
  35. package/docs/troubleshooting.md +111 -0
  36. package/docs/upgrading.md +50 -0
  37. package/docs/verification.md +146 -0
  38. package/docs/website.md +47 -5
  39. package/docs/workspaces.md +152 -0
  40. package/package.json +5 -4
  41. package/packages/core/src/cli/artifact.ts +5 -4
  42. package/packages/core/src/cli/attention.ts +2 -0
  43. package/packages/core/src/cli/binary-direct.ts +190 -0
  44. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  45. package/packages/core/src/cli/binary.ts +24 -210
  46. package/packages/core/src/cli/build-control.ts +105 -2
  47. package/packages/core/src/cli/context.ts +41 -1
  48. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  49. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  50. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  51. package/packages/core/src/cli/dashboard/model.ts +34 -10
  52. package/packages/core/src/cli/dashboard/render.ts +24 -2
  53. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  54. package/packages/core/src/cli/dispatch-args.ts +53 -0
  55. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  56. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  57. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  58. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  59. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  60. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  61. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  62. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  63. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  64. package/packages/core/src/cli/dispatch-process.ts +22 -90
  65. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  66. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  67. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  68. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  69. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  70. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  71. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  72. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  73. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  74. package/packages/core/src/cli/dispatch.ts +604 -60
  75. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  76. package/packages/core/src/cli/env.ts +1 -1
  77. package/packages/core/src/cli/harvest.ts +28 -11
  78. package/packages/core/src/cli/help.ts +10 -5
  79. package/packages/core/src/cli/installation.ts +5 -3
  80. package/packages/core/src/cli/main-checkout.ts +59 -0
  81. package/packages/core/src/cli/main.ts +15 -45
  82. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  83. package/packages/core/src/cli/repo-state.ts +3 -58
  84. package/packages/core/src/cli/repository-status.ts +67 -3
  85. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  86. package/packages/core/src/cli/status.ts +57 -3
  87. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  88. package/packages/core/src/cli/wait.ts +3 -0
  89. package/packages/core/src/cli/watch.ts +7 -0
  90. package/packages/core/src/config/landing.ts +8 -0
  91. package/packages/core/src/config/live.ts +1 -0
  92. package/packages/core/src/config/reference-metadata.ts +31 -0
  93. package/packages/core/src/config/reference.ts +342 -0
  94. package/packages/core/src/config/roles.ts +1 -1
  95. package/packages/core/src/config/schema.ts +352 -10
  96. package/packages/core/src/distribution-packaging.ts +116 -0
  97. package/packages/core/src/events/catalog.ts +6 -0
  98. package/packages/core/src/events/payloads.ts +53 -9
  99. package/packages/core/src/events/policy.ts +25 -0
  100. package/packages/core/src/events/repository.ts +184 -4
  101. package/packages/core/src/events/runtime.ts +16 -0
  102. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  103. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  104. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  105. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  106. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  107. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  108. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  109. package/packages/core/src/kernel/harvest.ts +98 -4
  110. package/packages/core/src/kernel/integration-attention.ts +20 -0
  111. package/packages/core/src/kernel/integration-state.ts +80 -11
  112. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  113. package/packages/core/src/kernel/mixed-version.ts +34 -0
  114. package/packages/core/src/kernel/node-polling.ts +160 -0
  115. package/packages/core/src/kernel/read-facts.ts +40 -5
  116. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  117. package/packages/core/src/kernel/reducer.ts +75 -14
  118. package/packages/core/src/kernel/service-facts.ts +11 -4
  119. package/packages/core/src/ontology.ts +2 -2
  120. package/packages/core/src/open-map.ts +3 -1
  121. package/packages/core/src/operator/presentation.ts +7 -0
  122. package/packages/core/src/operator/query.ts +6 -2
  123. package/packages/core/src/operator/registry.ts +1 -1
  124. package/packages/core/src/plugins/load.ts +4 -1
  125. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  126. package/packages/core/src/ports/forge/contract.ts +29 -0
  127. package/packages/core/src/ports/forge/github.ts +189 -61
  128. package/packages/core/src/ports/forge-failure.ts +1 -0
  129. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  130. package/packages/core/src/ports/runner/session-env.ts +1 -0
  131. package/packages/core/src/ports/types.ts +10 -0
  132. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  133. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  134. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  135. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  136. package/packages/core/src/processes/build-child-exit.ts +5 -26
  137. package/packages/core/src/processes/build-runner.ts +81 -11
  138. package/packages/core/src/processes/dispatcher.ts +254 -23
  139. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  140. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  141. package/packages/core/src/processes/execution-settlement.ts +16 -7
  142. package/packages/core/src/processes/harvest-runner.ts +328 -292
  143. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  144. package/packages/core/src/runtime-identity.ts +22 -3
  145. package/packages/core/src/store/contract.ts +153 -0
  146. package/packages/core/src/store/local/store.ts +197 -72
  147. package/packages/core/src/store/reduced-reads.ts +8 -0
  148. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  149. package/packages/core/src/store/remote/client.ts +43 -0
  150. package/packages/core/src/store/repo-state-events.ts +20 -3
  151. package/packages/core/src/store/types.ts +7 -0
  152. package/skills/finalize/SKILL.md +3 -1
  153. package/skills/guide/SKILL.md +273 -48
  154. package/skills/guide/references/integration-tree.md +87 -2
  155. package/skills/guide/references/operator-api.md +71 -14
  156. package/skills/guide/references/plugin-authoring.md +231 -266
  157. package/skills/guide/references/remote-store-protocol.md +12 -9
  158. package/skills/guide/references/restacking.md +4 -1
  159. package/skills/guide/references/setup.md +28 -6
  160. package/skills/guide/references/spec-standard.md +23 -5
  161. package/skills/harvest/SKILL.md +4 -0
  162. package/skills/harvest-review/SKILL.md +4 -0
  163. package/skills/implement/SKILL.md +4 -2
  164. package/skills/operate/SKILL.md +104 -35
  165. package/skills/plan/SKILL.md +12 -4
  166. package/skills/spec/SKILL.md +20 -2
  167. package/skills/tickets/SKILL.md +20 -1
  168. package/templates/hosted-service/package.json +2 -2
@@ -21,7 +21,7 @@ export async function readDispatcherLiveness(
21
21
  [...runs].map(async (run) => (await readDispatcherRunFacts(store, repo, run)).value),
22
22
  )
23
23
  const events = correlations.flatMap((run) =>
24
- [run.start, run.latestStart, run.stop, run.tick].filter(
24
+ [run.start, run.latestStart, run.stop, run.tick, run.runtime].filter(
25
25
  (event): event is RepositoryEvent => event !== undefined,
26
26
  ),
27
27
  )
@@ -37,7 +37,7 @@ export interface CliEnv {
37
37
 
38
38
  export type AmbientReadSession = CliEnv | HarvestCliEnv
39
39
 
40
- const PHASE_FORMAT = "'<phase>[@<round>]' (e.g. 'implement@2', 'verify:e2e@1')"
40
+ const PHASE_FORMAT = "'<phase>[@<round>]' (e.g. 'implement@2', 'verify:acceptance@1')"
41
41
  const BUILD_AMBIENT_TUPLE = 'AB_STORE/AB_BUILD/AB_PHASE/AB_SESSION'
42
42
  const HARVEST_AMBIENT_TUPLE = 'AB_STORE/AB_REPO/AB_HARVEST/AB_PHASE/AB_SESSION'
43
43
 
@@ -24,6 +24,7 @@ import {
24
24
  parkedHarvestRuns,
25
25
  proposalArtifactForRound,
26
26
  reduceHarvest,
27
+ suspendedHarvestSession,
27
28
  unresolvedHarvestAttentionRuns,
28
29
  type HarvestPendingCommand,
29
30
  type HarvestRunState,
@@ -437,12 +438,14 @@ export interface HarvestSessionStatusView {
437
438
  /** Open until the session's `harvest.session.ended` lands; the store's
438
439
  * records refine this to the stream's authoritative status when available. */
439
440
  streamStatus: 'open' | 'closed'
440
- status: 'open' | 'ended'
441
+ status: 'open' | 'ended' | 'suspended'
442
+ transcript?: import('../ontology').ArtifactRef
443
+ continuation?: import('../events/repository').HarvestEventPayload<'harvest.session.started'>['continuation']
441
444
  }
442
445
 
443
446
  export interface HarvestRunStatusView {
444
447
  run: string
445
- status: HarvestRunState['status']
448
+ status: HarvestRunState['status'] | 'suspended'
446
449
  startedSeq: number
447
450
  startedAt: string
448
451
  observations: number
@@ -461,8 +464,8 @@ export interface HarvestStatusView {
461
464
  run?: string
462
465
  /** Repository control takes display precedence while paused; runStatus keeps
463
466
  * the primary run lifecycle queryable without making pause terminal. */
464
- status: 'idle' | 'paused' | HarvestRunState['status']
465
- runStatus?: HarvestRunState['status']
467
+ status: 'idle' | 'paused' | 'suspended' | HarvestRunState['status']
468
+ runStatus?: HarvestRunState['status'] | 'suspended'
466
469
  paused: boolean
467
470
  pausedSeq?: number
468
471
  pausedAt?: string
@@ -557,6 +560,7 @@ function projectHarvestSessions(
557
560
  step: event.payload.step,
558
561
  round: event.payload.round,
559
562
  status: 'open',
563
+ ...(event.payload.continuation ? { continuation: event.payload.continuation } : {}),
560
564
  // The store's records are authoritative when available; without them
561
565
  // the pairing degrades gracefully (open until `harvest.session.ended`).
562
566
  ...(record !== undefined
@@ -566,22 +570,30 @@ function projectHarvestSessions(
566
570
  streamStatus: event.payload.stream !== undefined ? 'open' : 'closed',
567
571
  }),
568
572
  }
573
+ if (event.payload.continuation) {
574
+ const prior = byRun
575
+ .get(event.payload.run)
576
+ ?.find((s) => s.session === event.payload.continuation!.predecessor)
577
+ if (prior) prior.status = 'ended'
578
+ }
569
579
  const list = byRun.get(event.payload.run) ?? []
570
580
  list.push(view)
571
581
  byRun.set(event.payload.run, list)
572
582
  open.set(view.session, view)
573
583
  continue
574
584
  }
575
- if (event.type !== 'harvest.session.ended') continue
585
+ if (event.type !== 'harvest.session.ended' && event.type !== 'harvest.session.suspended')
586
+ continue
576
587
  const started = open.get(event.payload.session)
577
588
  if (started === undefined) continue
578
- started.status = 'ended'
589
+ started.status = event.type === 'harvest.session.suspended' ? 'suspended' : 'ended'
590
+ started.transcript = event.payload.transcript
579
591
  // A session bracket has ended: without an authoritative record its
580
592
  // stream reads closed.
581
593
  const record = recordsByLabel.get(`session:${started.session}`)
582
594
  if (record !== undefined) {
583
595
  started.stream = record.id
584
- started.streamStatus = record.status
596
+ started.streamStatus = started.status === 'suspended' ? 'closed' : record.status
585
597
  } else {
586
598
  started.streamStatus = 'closed'
587
599
  }
@@ -593,7 +605,7 @@ function projectHarvestSessions(
593
605
  function projectHarvestRunStatus(run: HarvestRunState): Omit<HarvestRunStatusView, 'sessions'> {
594
606
  return {
595
607
  run: run.run,
596
- status: run.status,
608
+ status: suspendedHarvestSession(run) ? 'suspended' : run.status,
597
609
  startedSeq: run.startedSeq,
598
610
  startedAt: run.startedAt,
599
611
  observations: run.observations.length,
@@ -638,7 +650,12 @@ export function projectHarvestStatus(
638
650
  const list = sessionsByRun.get(run) ?? []
639
651
  list.push({
640
652
  ...session,
641
- ...(record ? { stream: record.id, streamStatus: record.status } : {}),
653
+ ...(record
654
+ ? {
655
+ stream: record.id,
656
+ streamStatus: session.status === 'suspended' ? ('closed' as const) : record.status,
657
+ }
658
+ : {}),
642
659
  })
643
660
  sessionsByRun.set(run, list)
644
661
  }
@@ -651,7 +668,7 @@ export function projectHarvestStatus(
651
668
  const unresolvedIds = new Set(unresolved.map((run) => run.run))
652
669
  const primary =
653
670
  runs.find((run) => unresolvedIds.has(run.run)) ??
654
- runs.find((run) => run.status === 'running') ??
671
+ runs.find((run) => run.status === 'running' || run.status === 'suspended') ??
655
672
  runs.at(-1)
656
673
 
657
674
  const control = {
@@ -704,7 +721,7 @@ function renderHarvestRunStatus(run: HarvestRunStatusView, paused: boolean): str
704
721
  const stream =
705
722
  session.stream !== undefined ? ` stream ${session.stream} (${session.streamStatus})` : ''
706
723
  lines.push(
707
- ` session ${session.session} (${session.role}, ${session.step}@${session.round})${stream}`,
724
+ ` session ${session.session} (${session.role}, ${session.step}@${session.round}, ${session.status})${stream}`,
708
725
  )
709
726
  }
710
727
  if (run.recovery.stopped !== undefined) {
@@ -51,7 +51,9 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
51
51
  'On an interactive terminal, init selects a usable shipped runtime in a fixed product',
52
52
  'preference order and starts a conversational setup agent. The agent inspects the',
53
53
  'repository, asks for team-specific choices, configures commands, verification, roles,',
54
- 'and tickets, and leaves one groomed ticket. Its exit status becomes init’s exit status.',
54
+ 'and tickets, then validates with bun ab init --validate. Its exit status becomes init’s exit status.',
55
+ 'After validation, you start bun ab dispatch, then open your operator agent with',
56
+ 'ab-operate to create, groom, and shepherd the first ticket.',
55
57
  'Without a usable runtime or interactive terminal, init completes installation, prints',
56
58
  'every probe result, and emits the identical setup prompt for use in a coding agent.',
57
59
  '',
@@ -348,6 +350,7 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
348
350
  ' --store <ref> Override the BuildStore path or URL.',
349
351
  '',
350
352
  'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
353
+ 'integration.verification-failed (failed node verification), build.janitor-failing, build.compatibility-deferred,',
351
354
  'node.item-conflicted, conflicted restack.replayed, derived build.consent-ready and',
352
355
  'build.merge-decision (a current actionable merge-gate deferral or unsafe forge outcome).',
353
356
  'Consent and held ready landings use only build.consent-ready, once per readiness episode.',
@@ -413,7 +416,7 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
413
416
  'Conditions (--for, repeatable): blocked, paused, running, done, aborted, terminal (done',
414
417
  'or aborted), pr=open, pr=merged, pr=closed, consent, node-landed, restack-conflicted, pr=conflicted, phase=<phase> (a core phase —',
415
418
  'plan, plan-review, implement, code-review, finalize, reconcile — or verify:<step>), and',
416
- 'attention (an open escalation, consent readiness, a node landing or restack conflict,',
419
+ 'attention (an open escalation, failed node verification, consent readiness, a node landing or restack conflict,',
417
420
  'or a build waiting for a merge decision). Merge attention',
418
421
  'requires a current actionable gate deferral or an unsafe forge outcome;',
419
422
  'armed pending consent, routine outcomes and self-healing failures stay silent.',
@@ -578,8 +581,10 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
578
581
  '',
579
582
  '--revise-spec reads a replacement body from a file; --revise-spec-from-ticket',
580
583
  're-imports the build ticket after it was amended. A conforming replacement becomes',
581
- 'the next spec revision and restarts from plan while keeping an open PR. Revision',
582
- 'requires an open escalation. Non-conforming bodies are refused before anything is',
584
+ 'the next spec revision. Leaves require an open escalation and restart from plan.',
585
+ 'Idle collecting or verification-failed nodes need no escalation: they recollect',
586
+ 'and verify again, even on the same head. Active work, pause, pending controls and',
587
+ 'landing intent refuse node revision. Non-conforming bodies are refused before anything is',
583
588
  'recorded. Retrying an interrupted revision completes the exact body authorized by',
584
589
  'the earlier recorded answer, not a newly supplied body.',
585
590
  '',
@@ -805,7 +810,7 @@ export function renderTopLevelHelp(): string {
805
810
  const lines = [
806
811
  'ab — agent-driven software delivery from groomed ticket to merged PR',
807
812
  '',
808
- '`ab` is Autobuild’s human/operator CLI and the agent↔store channel (SPEC §8.2).',
813
+ '`ab` serves the operator role (normally an operator agent, or you directly) and the agent↔store channel (SPEC §8.2).',
809
814
  '',
810
815
  'Primary human workflow:',
811
816
  ' Install in your repository: bun add -d --exact @defrex/autobuild',
@@ -206,7 +206,9 @@ async function readMetadata(path: string): Promise<string> {
206
206
  }
207
207
  }
208
208
 
209
- function githubDependency(value: unknown): { owner: string; repository: string } | undefined {
209
+ export function githubDependency(
210
+ value: unknown,
211
+ ): { owner: string; repository: string } | undefined {
210
212
  if (typeof value !== 'string') return undefined
211
213
  const match = /^github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:#([^\s]+))?$/.exec(value)
212
214
  if (match?.[1] === undefined || match[2] === undefined) return undefined
@@ -245,7 +247,7 @@ async function parseJsonc(path: string): Promise<Record<string, unknown>> {
245
247
  }
246
248
  }
247
249
 
248
- function lockDependency(
250
+ export function lockDependency(
249
251
  lock: Record<string, unknown>,
250
252
  packageName: string,
251
253
  section: DependencySection,
@@ -268,7 +270,7 @@ function declaredSection(
268
270
  return first === undefined ? undefined : { ...first, dual: declared.length > 1 }
269
271
  }
270
272
 
271
- function lockPackageRecord(
273
+ export function lockPackageRecord(
272
274
  lock: Record<string, unknown>,
273
275
  packageName: string,
274
276
  ): unknown[] | undefined {
@@ -0,0 +1,59 @@
1
+ import { basename, dirname, isAbsolute, resolve } from 'node:path'
2
+ import type { Exec } from '../ports/workspace/git-worktree'
3
+ function absoluteGitPath(path: string, target: string): string {
4
+ return isAbsolute(path) ? resolve(path) : resolve(target, path)
5
+ }
6
+
7
+ /**
8
+ * Resolve the main checkout from Git's repository/worktree topology.
9
+ *
10
+ * A normal checkout (including a submodule or `--separate-git-dir` checkout)
11
+ * has equal Git and common directories, so `--show-toplevel` is authoritative.
12
+ * A linked worktree has a per-worktree Git directory and a shared common
13
+ * directory; Git's worktree registry lists the main checkout first. This avoids
14
+ * assuming the common directory is `<checkout>/.git`, which is false for
15
+ * submodules and separately stored Git directories.
16
+ *
17
+ * Outside Git (or when Git cannot be executed), the resolved target directory
18
+ * is the deterministic fallback.
19
+ */
20
+ export async function resolveMainRepo(targetRepo: string, exec: Exec): Promise<string> {
21
+ const target = resolve(targetRepo)
22
+ try {
23
+ const result = await exec(
24
+ [
25
+ 'git',
26
+ 'rev-parse',
27
+ '--path-format=absolute',
28
+ '--git-dir',
29
+ '--git-common-dir',
30
+ '--show-toplevel',
31
+ ],
32
+ { cwd: target },
33
+ )
34
+ if (result.exitCode !== 0) return target
35
+ const [gitDirRaw, commonDirRaw, topLevelRaw] = result.stdout.trimEnd().split('\n')
36
+ if (!gitDirRaw || !commonDirRaw || !topLevelRaw) return target
37
+
38
+ const gitDir = absoluteGitPath(gitDirRaw, target)
39
+ const commonDir = absoluteGitPath(commonDirRaw, target)
40
+ const topLevel = absoluteGitPath(topLevelRaw, target)
41
+ if (gitDir === commonDir) return topLevel
42
+
43
+ const worktrees = await exec(['git', 'worktree', 'list', '--porcelain', '-z'], { cwd: target })
44
+ if (worktrees.exitCode === 0) {
45
+ const main = worktrees.stdout
46
+ .split('\0')
47
+ .find((entry) => entry.startsWith('worktree '))
48
+ ?.slice('worktree '.length)
49
+ if (main) return absoluteGitPath(main, target)
50
+ }
51
+
52
+ // Old Git versions without porcelain -z still have the ordinary linked
53
+ // layout. Only derive from dirname when the common dir is literally .git;
54
+ // otherwise the current worktree is safer than writing inside Git metadata.
55
+ return basename(commonDir) === '.git' ? dirname(commonDir) : topLevel
56
+ } catch {
57
+ return target
58
+ }
59
+ }
@@ -1,4 +1,6 @@
1
1
  import { currentTicketRef } from '../kernel/ticket-migrations'
2
+ import { upgradeFollowup } from './upgrade-followup'
3
+ import { parseDispatchArgs } from './dispatch-args'
2
4
  import { requestNodeRestack } from '../operator/restack'
3
5
  import { withSessionlessStore } from './store-opening'
4
6
  import { abLandings } from './landings'
@@ -290,6 +292,8 @@ export function buildControlConfirmation(result: BuildControlResult): string {
290
292
  }
291
293
  if (result.resolution === 'revise-spec') {
292
294
  const revision = result.specRev === undefined ? '' : ` (spec rev ${result.specRev})`
295
+ if (result.nodeRevision)
296
+ return `build ${result.slug}: revised node spec${revision}; collecting for a new verification cycle`
293
297
  if (result.authorizedEarlier === true) {
294
298
  return `build ${result.slug}: completed the spec revision recorded earlier${revision}; the body supplied now was not used${
295
299
  result.resumed ? '; resume requested' : ''
@@ -658,6 +662,15 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
658
662
  if (commitContext !== undefined) {
659
663
  await finishUpgradeCommit(commitContext, report, { stdout, stderr })
660
664
  }
665
+ if (report.exitCode === 0) {
666
+ try {
667
+ stdout(await upgradeFollowup(targetRepo))
668
+ } catch {
669
+ stderr(
670
+ 'Could not determine automatic dispatcher upgrade policy; inspect autobuild.toml.',
671
+ )
672
+ }
673
+ }
661
674
  return report.exitCode
662
675
  } finally {
663
676
  if (commitContext !== undefined) await cleanupUpgradeCommitContext(commitContext)
@@ -685,51 +698,8 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
685
698
  // a build, so it routes before any store/env requirement and does its own
686
699
  // heavy wiring (like ticket create). One dispatcher per repo (§12).
687
700
  case 'dispatch': {
688
- const usage =
689
- 'usage: ab dispatch [--once] [--interval <seconds>] [--store <ref>] [--repository <origin>] [--plain] [--intake | --no-intake] [--auto-merge | --no-auto-merge] (§3.3)'
690
- const parsed = parseArgs(
691
- rest,
692
- {
693
- once: 'boolean',
694
- interval: 'value',
695
- store: 'value',
696
- repository: 'value',
697
- plain: 'boolean',
698
- intake: 'boolean',
699
- 'no-intake': 'boolean',
700
- 'auto-merge': 'boolean',
701
- 'no-auto-merge': 'boolean',
702
- },
703
- usage,
704
- )
705
- if (parsed.positionals.length > 0) throw new Error(usage)
706
-
707
- const once = parsed.flags.has('once')
708
- const plain = parsed.flags.has('plain')
709
- const sawIntake = parsed.flags.has('intake')
710
- const sawNoIntake = parsed.flags.has('no-intake')
711
- const sawAutoMerge = parsed.flags.has('auto-merge')
712
- const sawNoAutoMerge = parsed.flags.has('no-auto-merge')
713
- if (sawIntake && sawNoIntake) {
714
- throw new Error(`--intake and --no-intake cannot be combined — ${usage}`)
715
- }
716
- if (sawAutoMerge || sawNoAutoMerge) {
717
- throw new Error(`Auto-merge flags are retired; configure [[landing]] policy — ${usage}`)
718
- }
719
-
720
- const interval = stringFlag(parsed, 'interval')
721
- let intervalMs: number | undefined
722
- if (interval !== undefined) {
723
- const seconds = Number(interval)
724
- if (!Number.isFinite(seconds) || seconds <= 0) {
725
- throw new Error(`--interval requires a positive number of seconds — ${usage}`)
726
- }
727
- intervalMs = Math.round(seconds * 1000)
728
- }
729
- const storeRef = stringFlag(parsed, 'store')
730
- const repository = stringFlag(parsed, 'repository') ?? deps.processEnv?.AB_REPOSITORY
731
- const intake = sawIntake ? true : sawNoIntake ? false : undefined
732
- const defaultAutoMerge = sawAutoMerge ? true : sawNoAutoMerge ? false : undefined
701
+ const { once, plain, intake, defaultAutoMerge, intervalMs, storeRef, repository } =
702
+ parseDispatchArgs(rest, deps.processEnv ?? {})
733
703
  if (deps.exec === undefined) {
734
704
  throw new Error("'ab dispatch' needs an exec seam — this is a wiring bug in the ab binary")
735
705
  }
@@ -0,0 +1,97 @@
1
+ import { buildTrailers, validateBuildSlug } from '../kernel/build-identity'
2
+ import { originalForeign } from '../kernel/change-presence'
3
+ import { history, nodeInventory, type NodeGit } from '../kernel/node-restack'
4
+ import type { CommitRange, TicketRef } from '../ontology'
5
+ import { readBuildFacts } from '../store/reduced-reads'
6
+ import type { BuildStore } from '../store/types'
7
+
8
+ export interface NodeContribution {
9
+ build: string
10
+ ticket: TicketRef
11
+ spec: { kind: 'spec'; rev: number }
12
+ specPath: string
13
+ commits: string[]
14
+ }
15
+ export interface NodeVerificationIndex {
16
+ range: CommitRange
17
+ handPushedCommits: { sha: string; originalSha: string; message: string }[]
18
+ contributions: NodeContribution[]
19
+ unattributedCommits: string[]
20
+ commits: { sha: string; build?: string }[]
21
+ }
22
+
23
+ /** Reachability, rather than the current child inventory, establishes membership. */
24
+ export async function collectNodeVerificationProvenance(
25
+ store: BuildStore,
26
+ repo: string,
27
+ range: CommitRange,
28
+ git: NodeGit,
29
+ ownership: { contributionBase: string; foreignAliases?: Record<string, string> },
30
+ ): Promise<{ index: NodeVerificationIndex; specs: Map<string, string> }> {
31
+ const index: NodeVerificationIndex = {
32
+ range,
33
+ handPushedCommits: [],
34
+ contributions: [],
35
+ unattributedCommits: [],
36
+ commits: [],
37
+ }
38
+ const owned = new Set((await nodeInventory(git, range.head, ownership.contributionBase)).foreign)
39
+ const aliases = new Map(Object.entries(ownership.foreignAliases ?? {}))
40
+ const specs = new Map<string, string>()
41
+ const byBuild = new Map<string, NodeContribution>()
42
+ for (const commit of await history(
43
+ git,
44
+ [`${range.base}..${range.head}`],
45
+ ['--reverse', '--topo-order'],
46
+ )) {
47
+ if (owned.has(commit.sha))
48
+ index.handPushedCommits.push({
49
+ sha: commit.sha,
50
+ originalSha: originalForeign(commit.sha, aliases),
51
+ message: commit.message,
52
+ })
53
+ const trailers = buildTrailers(commit.message)
54
+ if (trailers.length > 1) throw new Error(`ambiguous build identity on ${commit.sha}`)
55
+ const build = trailers[0]
56
+ if (build === undefined) {
57
+ index.commits.push({ sha: commit.sha })
58
+ index.unattributedCommits.push(commit.sha)
59
+ continue
60
+ }
61
+ try {
62
+ validateBuildSlug(build)
63
+ } catch {
64
+ throw new Error(`invalid build identity on ${commit.sha}: ${JSON.stringify(build)}`)
65
+ }
66
+ let contribution = byBuild.get(build)
67
+ if (contribution === undefined) {
68
+ try {
69
+ const record = await store.getBuild(build)
70
+ if (!record) throw new Error('unknown build')
71
+ if (record.repo !== repo) throw new Error('build belongs to a different repository')
72
+ if (!record.ticket) throw new Error('missing ticket identity')
73
+ const { state } = (await readBuildFacts(store, build)).value
74
+ if (state.specRev === undefined) throw new Error('missing authoritative spec revision')
75
+ const artifact = await store.getArtifact(build, 'spec', state.specRev)
76
+ if (!artifact) throw new Error(`missing spec@${state.specRev}`)
77
+ contribution = {
78
+ build,
79
+ ticket: record.ticket,
80
+ spec: { kind: 'spec', rev: state.specRev },
81
+ specPath: '',
82
+ commits: [],
83
+ }
84
+ byBuild.set(build, contribution)
85
+ index.contributions.push(contribution)
86
+ specs.set(build, new TextDecoder().decode(artifact.content))
87
+ } catch (error) {
88
+ throw new Error(
89
+ `node verification contribution ${build} at ${commit.sha}: ${error instanceof Error ? error.message : String(error)}`,
90
+ )
91
+ }
92
+ }
93
+ contribution.commits.push(commit.sha)
94
+ index.commits.push({ sha: commit.sha, build })
95
+ }
96
+ return { index, specs }
97
+ }
@@ -21,7 +21,7 @@
21
21
  * interpret a relative path from different working directories.
22
22
  */
23
23
  import { configuredStore } from './configured-store'
24
- import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
24
+ import { join, resolve } from 'node:path'
25
25
  import type { Exec } from '../ports/workspace/git-worktree'
26
26
  import type { BuildRecord } from '../store/types'
27
27
  import { normalizeGitRemoteUrl } from '../kernel/origin'
@@ -34,63 +34,8 @@ export function isRemoteStoreRef(ref: string): boolean {
34
34
  return /^https?:\/\//i.test(ref)
35
35
  }
36
36
 
37
- function absoluteGitPath(path: string, target: string): string {
38
- return isAbsolute(path) ? resolve(path) : resolve(target, path)
39
- }
40
-
41
- /**
42
- * Resolve the main checkout from Git's repository/worktree topology.
43
- *
44
- * A normal checkout (including a submodule or `--separate-git-dir` checkout)
45
- * has equal Git and common directories, so `--show-toplevel` is authoritative.
46
- * A linked worktree has a per-worktree Git directory and a shared common
47
- * directory; Git's worktree registry lists the main checkout first. This avoids
48
- * assuming the common directory is `<checkout>/.git`, which is false for
49
- * submodules and separately stored Git directories.
50
- *
51
- * Outside Git (or when Git cannot be executed), the resolved target directory
52
- * is the deterministic fallback.
53
- */
54
- export async function resolveMainRepo(targetRepo: string, exec: Exec): Promise<string> {
55
- const target = resolve(targetRepo)
56
- try {
57
- const result = await exec(
58
- [
59
- 'git',
60
- 'rev-parse',
61
- '--path-format=absolute',
62
- '--git-dir',
63
- '--git-common-dir',
64
- '--show-toplevel',
65
- ],
66
- { cwd: target },
67
- )
68
- if (result.exitCode !== 0) return target
69
- const [gitDirRaw, commonDirRaw, topLevelRaw] = result.stdout.trimEnd().split('\n')
70
- if (!gitDirRaw || !commonDirRaw || !topLevelRaw) return target
71
-
72
- const gitDir = absoluteGitPath(gitDirRaw, target)
73
- const commonDir = absoluteGitPath(commonDirRaw, target)
74
- const topLevel = absoluteGitPath(topLevelRaw, target)
75
- if (gitDir === commonDir) return topLevel
76
-
77
- const worktrees = await exec(['git', 'worktree', 'list', '--porcelain', '-z'], { cwd: target })
78
- if (worktrees.exitCode === 0) {
79
- const main = worktrees.stdout
80
- .split('\0')
81
- .find((entry) => entry.startsWith('worktree '))
82
- ?.slice('worktree '.length)
83
- if (main) return absoluteGitPath(main, target)
84
- }
85
-
86
- // Old Git versions without porcelain -z still have the ordinary linked
87
- // layout. Only derive from dirname when the common dir is literally .git;
88
- // otherwise the current worktree is safer than writing inside Git metadata.
89
- return basename(commonDir) === '.git' ? dirname(commonDir) : topLevel
90
- } catch {
91
- return target
92
- }
93
- }
37
+ export { resolveMainRepo } from './main-checkout'
38
+ import { resolveMainRepo } from './main-checkout'
94
39
 
95
40
  export interface RepoStatePaths {
96
41
  /** Validated repository setting used for this selection, when present. */
@@ -1,4 +1,6 @@
1
1
  import { migrationIdentity } from '../kernel/ticket-migrations'
2
+ import { dispatchUpgradeReducer, type DispatchUpgradeState } from '../kernel/dispatch-upgrade'
3
+ import { formatRuntimeIdentity } from '../events/runtime'
2
4
  import {
3
5
  dispatchCapacity,
4
6
  type DispatchCapacity,
@@ -30,6 +32,8 @@ import { withSessionlessStore, type StoreOpener } from './store-opening'
30
32
  /** Script-facing projection returned by `ab repository status`. */
31
33
  export interface RepositoryStatus extends DispatchSettings {
32
34
  repo: string
35
+ upgrades: DispatchUpgradeState
36
+ rollbackHold?: DispatchUpgradeState['lastRollback']
33
37
  capacity?: DispatchCapacity
34
38
  warningLines?: string[]
35
39
  dispatcher: DispatcherLiveness
@@ -110,6 +114,8 @@ export function projectRepositoryStatus(
110
114
  : {}),
111
115
  ...(active === undefined ? {} : { ticketSourceDegradation: active }),
112
116
  repo,
117
+ upgrades: dispatchUpgradeReducer.reduce(events),
118
+ rollbackHold: effectiveRollbackHold(dispatchUpgradeReducer.reduce(events), dispatcher),
113
119
  ...(warningLines.length ? { warningLines } : {}),
114
120
  dispatcher,
115
121
  ...(() => {
@@ -142,6 +148,8 @@ export function repositoryStatusFromFacts(
142
148
  const warningLines = facts.status ? forgeReadinessWarnings(facts.status) : []
143
149
  return {
144
150
  repo,
151
+ upgrades: facts.upgrades,
152
+ rollbackHold: effectiveRollbackHold(facts.upgrades, dispatcher),
145
153
  ...(warningLines.length ? { warningLines } : {}),
146
154
  dispatcher,
147
155
  ...(() => {
@@ -176,6 +184,18 @@ export function repositoryStatusFromFacts(
176
184
  }
177
185
  }
178
186
 
187
+ function effectiveRollbackHold(upgrades: DispatchUpgradeState, dispatcher: DispatcherLiveness) {
188
+ const run = dispatcher.holder ?? dispatcher.expiredHolder ?? dispatcher.latestRun
189
+ const lineage = run && upgrades.lineages[run.run]
190
+ return lineage ? upgrades.holds[lineage] : undefined
191
+ }
192
+
193
+ function formatRepositoryDispatcherIdentity(
194
+ run: NonNullable<DispatcherLiveness['latestRun']>,
195
+ ): string {
196
+ return `${formatDispatcherIdentity(run)}; ${formatRuntimeIdentity(run.runtime)}`
197
+ }
198
+
179
199
  export function renderRepositoryStatus(status: RepositoryStatus): string[] {
180
200
  const tick = (
181
201
  status.dispatcher.holder ??
@@ -187,8 +207,50 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
187
207
  const setting = (enabled: boolean): string => (enabled ? 'ON' : 'OFF')
188
208
  const active = status.ticketSourceDegradation
189
209
  return [
210
+ ...(status.upgrades.lastRollback
211
+ ? [
212
+ `runtime rollback: ${status.upgrades.lastRollback.payload.failed.version} → ${status.upgrades.lastRollback.payload.restored.version}; ${status.upgrades.lastRollback.payload.reason}`,
213
+ ]
214
+ : []),
215
+ ...(status.rollbackHold
216
+ ? [
217
+ `held runtime: ${status.rollbackHold.payload.failed.version}; target ${status.rollbackHold.payload.target.key}`,
218
+ ]
219
+ : []),
220
+ ...Object.entries(status.upgrades.runs).flatMap(([run, state]) => {
221
+ const event =
222
+ state.completed ??
223
+ state.failure ??
224
+ state.handoff ??
225
+ state.request ??
226
+ state.prepared ??
227
+ state.detected
228
+ const resolved = state.resolved?.payload.target
229
+ const lines = resolved
230
+ ? [
231
+ `resolved target ${run}: ${resolved.mode}; base ${resolved.base ?? '-'}; source ${resolved.source}${resolved.sha ? ` at ${resolved.sha}` : ''}`,
232
+ ]
233
+ : []
234
+ if (!event) return lines
235
+ const target = event.payload.target
236
+ const overlap =
237
+ state.handoff && state.request && !state.completed
238
+ ? [
239
+ `handoff ${run} (${state.handoff.payload.from.version}) → ${state.request.payload.successor} (${state.handoff.payload.to.version}): ${state.request.payload.mode}; ${state.takeover ? 'taken over' : 'awaiting takeover'}; draining ${
240
+ Object.entries(state.outstanding)
241
+ .map(([slug, instance]) => `${slug} (${instance})`)
242
+ .join(', ') || 'none'
243
+ }; deadline ${state.deadline ?? 'unknown'}`,
244
+ ]
245
+ : []
246
+ return [
247
+ ...lines,
248
+ ...overlap,
249
+ `upgrade ${run}: ${event.type.slice('dispatcher.'.length)}; ${target.mode} ${target.version ?? target.source}; source ${target.source}${target.sha ? ` at ${target.sha}` : ''}${event.type === 'dispatcher.upgrade-failed' ? `; ${event.payload.reason}` : ''}`,
250
+ ]
251
+ }),
190
252
  requests
191
- ? `forge requests: ${requests.total} (${requests.unattributed} unattributed)${hotspot ? `; hotspot ${hotspot}` : ''}`
253
+ ? `forge requests: ${requests.total}${requests.restPrimary === undefined ? '' : `; REST primary ${requests.restPrimary}`}${requests.restNotModified === undefined ? '' : `; REST 304 ${requests.restNotModified}`}${requests.graphql === undefined ? '' : `; GraphQL ${requests.graphql}`} (${requests.unattributed} unattributed)${hotspot ? `; hotspot ${hotspot}` : ''}`
192
254
  : 'forge requests: unavailable',
193
255
  ...(status.forgeDegradation
194
256
  ? [
@@ -207,9 +269,11 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
207
269
  ]
208
270
  : []),
209
271
  ...(status.warningLines ?? []),
210
- `dispatcher: ${status.dispatcher.state}${status.dispatcher.holder ? ` — ${formatDispatcherIdentity(status.dispatcher.holder)}` : ' — no dispatcher holds the repository'}`,
272
+ `dispatcher: ${status.dispatcher.state}${status.dispatcher.holder ? ` — ${formatRepositoryDispatcherIdentity(status.dispatcher.holder)}` : ' — no dispatcher holds the repository'}`,
211
273
  ...(status.dispatcher.expiredHolder
212
- ? [`expired dispatcher: ${formatDispatcherIdentity(status.dispatcher.expiredHolder)}`]
274
+ ? [
275
+ `expired dispatcher: ${formatRepositoryDispatcherIdentity(status.dispatcher.expiredHolder)}`,
276
+ ]
213
277
  : []),
214
278
  ...[status.dispatcher.holder ?? status.dispatcher.expiredHolder].flatMap((run) =>
215
279
  run
@@ -0,0 +1,16 @@
1
+ import { distributionRoot } from '../distribution'
2
+ import { ownCachedRuntime } from './dispatch-runtime-use'
3
+ /** Every cached Bun entry pins compiler resolution before evaluating any JS. */
4
+ export function bunRuntimeArguments(entry: string, args: string[] = []): string[] {
5
+ const root = distributionRoot()
6
+ return ownCachedRuntime(root)
7
+ ? [
8
+ process.execPath,
9
+ '--no-install',
10
+ '--tsconfig-override',
11
+ `${root}/tsconfig.json`,
12
+ entry,
13
+ ...args,
14
+ ]
15
+ : [process.execPath, entry, ...args]
16
+ }