@defrex/autobuild 1.0.0-beta.2 → 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 (145) hide show
  1. package/SPEC.md +342 -23
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +170 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +91 -4
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +9 -1
  10. package/docs/remote-ticket-protocol.md +5 -0
  11. package/docs/restacking.md +4 -1
  12. package/docs/setup.md +24 -0
  13. package/docs/spec-standard.md +94 -5
  14. package/docs/ticket-migration.md +50 -4
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/artifact.ts +5 -4
  17. package/packages/core/src/cli/attention.ts +2 -0
  18. package/packages/core/src/cli/binary-direct.ts +190 -0
  19. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  20. package/packages/core/src/cli/binary.ts +24 -210
  21. package/packages/core/src/cli/build-control.ts +108 -5
  22. package/packages/core/src/cli/context.ts +41 -1
  23. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  24. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  25. package/packages/core/src/cli/dashboard/integration-detail.ts +11 -6
  26. package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
  27. package/packages/core/src/cli/dashboard/model.ts +41 -10
  28. package/packages/core/src/cli/dashboard/render.ts +24 -2
  29. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  30. package/packages/core/src/cli/dispatch-args.ts +53 -0
  31. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +57 -5
  33. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  34. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  35. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  36. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  38. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  39. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  40. package/packages/core/src/cli/dispatch-process.ts +22 -90
  41. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +6 -1
  43. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  44. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  45. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  46. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  47. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  48. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  49. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  50. package/packages/core/src/cli/dispatch.ts +609 -60
  51. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  52. package/packages/core/src/cli/harvest.ts +28 -11
  53. package/packages/core/src/cli/help.ts +7 -3
  54. package/packages/core/src/cli/installation.ts +5 -3
  55. package/packages/core/src/cli/main-checkout.ts +59 -0
  56. package/packages/core/src/cli/main.ts +26 -53
  57. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  58. package/packages/core/src/cli/repo-state.ts +3 -58
  59. package/packages/core/src/cli/repository-status.ts +74 -4
  60. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  61. package/packages/core/src/cli/status.ts +57 -3
  62. package/packages/core/src/cli/ticket.ts +35 -11
  63. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  64. package/packages/core/src/cli/wait.ts +3 -0
  65. package/packages/core/src/cli/watch.ts +7 -0
  66. package/packages/core/src/config/live.ts +1 -0
  67. package/packages/core/src/config/schema.ts +8 -4
  68. package/packages/core/src/distribution-packaging.ts +116 -0
  69. package/packages/core/src/events/catalog.ts +6 -0
  70. package/packages/core/src/events/payloads.ts +55 -9
  71. package/packages/core/src/events/policy.ts +26 -0
  72. package/packages/core/src/events/repository.ts +205 -4
  73. package/packages/core/src/events/runtime.ts +16 -0
  74. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +6537 -4053
  75. package/packages/core/src/kernel/change-presence.ts +7 -1
  76. package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
  77. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  78. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  79. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  80. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  81. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  82. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  83. package/packages/core/src/kernel/harvest.ts +98 -4
  84. package/packages/core/src/kernel/integration-attention.ts +20 -0
  85. package/packages/core/src/kernel/integration-completeness.ts +54 -16
  86. package/packages/core/src/kernel/integration-state.ts +80 -11
  87. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  88. package/packages/core/src/kernel/mixed-version.ts +34 -0
  89. package/packages/core/src/kernel/node-parent.ts +35 -10
  90. package/packages/core/src/kernel/node-polling.ts +160 -0
  91. package/packages/core/src/kernel/read-facts.ts +47 -5
  92. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  93. package/packages/core/src/kernel/reducer.ts +75 -14
  94. package/packages/core/src/kernel/service-facts.ts +11 -4
  95. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  96. package/packages/core/src/operator/presentation.ts +7 -0
  97. package/packages/core/src/operator/query.ts +13 -3
  98. package/packages/core/src/operator/registry.ts +1 -1
  99. package/packages/core/src/operator/tickets.ts +30 -26
  100. package/packages/core/src/plugins/load.ts +4 -1
  101. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  102. package/packages/core/src/ports/forge/contract.ts +29 -0
  103. package/packages/core/src/ports/forge/github.ts +189 -61
  104. package/packages/core/src/ports/forge-failure.ts +1 -0
  105. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  106. package/packages/core/src/ports/runner/session-env.ts +1 -0
  107. package/packages/core/src/ports/tickets/linear.ts +180 -12
  108. package/packages/core/src/ports/tickets/migration.ts +92 -9
  109. package/packages/core/src/ports/types.ts +17 -0
  110. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  111. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  112. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  113. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  114. package/packages/core/src/processes/build-child-exit.ts +5 -26
  115. package/packages/core/src/processes/build-runner.ts +81 -11
  116. package/packages/core/src/processes/dispatcher.ts +418 -59
  117. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  118. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  119. package/packages/core/src/processes/execution-settlement.ts +16 -7
  120. package/packages/core/src/processes/harvest-runner.ts +328 -292
  121. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  122. package/packages/core/src/runtime-identity.ts +22 -3
  123. package/packages/core/src/store/contract.ts +183 -0
  124. package/packages/core/src/store/local/store.ts +197 -72
  125. package/packages/core/src/store/reduced-reads.ts +8 -0
  126. package/packages/core/src/store/reducer-value-shapes.json +8915 -6344
  127. package/packages/core/src/store/remote/client.ts +43 -0
  128. package/packages/core/src/store/repo-state-events.ts +21 -3
  129. package/packages/core/src/store/types.ts +7 -0
  130. package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
  131. package/skills/guide/SKILL.md +234 -24
  132. package/skills/guide/references/integration-tree.md +91 -4
  133. package/skills/guide/references/operator-api.md +53 -4
  134. package/skills/guide/references/plugin-authoring.md +45 -4
  135. package/skills/guide/references/remote-store-protocol.md +9 -1
  136. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  137. package/skills/guide/references/restacking.md +4 -1
  138. package/skills/guide/references/setup.md +24 -0
  139. package/skills/guide/references/spec-standard.md +94 -5
  140. package/skills/guide/references/ticket-migration.md +50 -4
  141. package/skills/harvest/SKILL.md +4 -0
  142. package/skills/harvest-review/SKILL.md +4 -0
  143. package/skills/operate/SKILL.md +78 -8
  144. package/skills/spec/SKILL.md +35 -5
  145. package/skills/tickets/SKILL.md +19 -0
@@ -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
  )
@@ -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) {
@@ -174,6 +174,7 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
174
174
  ' ab ticket edit <id>',
175
175
  ' ab ticket export <dir> [--store <ref>]',
176
176
  ' ab ticket import <dir> [--store <ref>]',
177
+ ' ab ticket migration record <dir> [--store <ref>]',
177
178
  ' ab ticket update <id> [--kind work|node] [--target <id> | --no-target] [--title <title>] [--body <file>] [--labels a,b] [--expected-revision <opaque>] [--json]',
178
179
  ' ab ticket block <id> <blocker-id[,blocker-id...]> [--expected-revision <opaque>] [--json]',
179
180
  ' ab ticket unblock <id> <blocker-id[,blocker-id...]> [--expected-revision <opaque>] [--json]',
@@ -347,6 +348,7 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
347
348
  ' --store <ref> Override the BuildStore path or URL.',
348
349
  '',
349
350
  'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
351
+ 'integration.verification-failed (failed node verification), build.janitor-failing, build.compatibility-deferred,',
350
352
  'node.item-conflicted, conflicted restack.replayed, derived build.consent-ready and',
351
353
  'build.merge-decision (a current actionable merge-gate deferral or unsafe forge outcome).',
352
354
  'Consent and held ready landings use only build.consent-ready, once per readiness episode.',
@@ -412,7 +414,7 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
412
414
  'Conditions (--for, repeatable): blocked, paused, running, done, aborted, terminal (done',
413
415
  'or aborted), pr=open, pr=merged, pr=closed, consent, node-landed, restack-conflicted, pr=conflicted, phase=<phase> (a core phase —',
414
416
  'plan, plan-review, implement, code-review, finalize, reconcile — or verify:<step>), and',
415
- 'attention (an open escalation, consent readiness, a node landing or restack conflict,',
417
+ 'attention (an open escalation, failed node verification, consent readiness, a node landing or restack conflict,',
416
418
  'or a build waiting for a merge decision). Merge attention',
417
419
  'requires a current actionable gate deferral or an unsafe forge outcome;',
418
420
  'armed pending consent, routine outcomes and self-healing failures stay silent.',
@@ -577,8 +579,10 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
577
579
  '',
578
580
  '--revise-spec reads a replacement body from a file; --revise-spec-from-ticket',
579
581
  're-imports the build ticket after it was amended. A conforming replacement becomes',
580
- 'the next spec revision and restarts from plan while keeping an open PR. Revision',
581
- 'requires an open escalation. Non-conforming bodies are refused before anything is',
582
+ 'the next spec revision. Leaves require an open escalation and restart from plan.',
583
+ 'Idle collecting or verification-failed nodes need no escalation: they recollect',
584
+ 'and verify again, even on the same head. Active work, pause, pending controls and',
585
+ 'landing intent refuse node revision. Non-conforming bodies are refused before anything is',
582
586
  'recorded. Retrying an interrupted revision completes the exact body authorized by',
583
587
  'the earlier recorded answer, not a newly supplied body.',
584
588
  '',
@@ -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,3 +1,6 @@
1
+ import { currentTicketRef } from '../kernel/ticket-migrations'
2
+ import { upgradeFollowup } from './upgrade-followup'
3
+ import { parseDispatchArgs } from './dispatch-args'
1
4
  import { requestNodeRestack } from '../operator/restack'
2
5
  import { withSessionlessStore } from './store-opening'
3
6
  import { abLandings } from './landings'
@@ -289,6 +292,8 @@ export function buildControlConfirmation(result: BuildControlResult): string {
289
292
  }
290
293
  if (result.resolution === 'revise-spec') {
291
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`
292
297
  if (result.authorizedEarlier === true) {
293
298
  return `build ${result.slug}: completed the spec revision recorded earlier${revision}; the body supplied now was not used${
294
299
  result.resumed ? '; resume requested' : ''
@@ -318,7 +323,7 @@ async function runBuildControl(
318
323
  slug: string,
319
324
  action: BuildControlAction,
320
325
  storeRef?: string,
321
- readTicketBody?: (ref: TicketRef) => Promise<string>,
326
+ readTicketBody?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<string>,
322
327
  prepareTicketAssets?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<PinnedAsset[]>,
323
328
  ): Promise<void> {
324
329
  if (deps.exec === undefined) {
@@ -657,6 +662,15 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
657
662
  if (commitContext !== undefined) {
658
663
  await finishUpgradeCommit(commitContext, report, { stdout, stderr })
659
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
+ }
660
674
  return report.exitCode
661
675
  } finally {
662
676
  if (commitContext !== undefined) await cleanupUpgradeCommitContext(commitContext)
@@ -670,6 +684,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
670
684
  throw new Error("'ab ticket' needs an exec seam — this is a wiring bug in the ab binary")
671
685
  }
672
686
  await abTicket(rest, {
687
+ signal: deps.signal,
673
688
  targetRepo: deps.workspacePath,
674
689
  env: deps.processEnv ?? {},
675
690
  exec: deps.exec,
@@ -683,51 +698,8 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
683
698
  // a build, so it routes before any store/env requirement and does its own
684
699
  // heavy wiring (like ticket create). One dispatcher per repo (§12).
685
700
  case 'dispatch': {
686
- const usage =
687
- 'usage: ab dispatch [--once] [--interval <seconds>] [--store <ref>] [--repository <origin>] [--plain] [--intake | --no-intake] [--auto-merge | --no-auto-merge] (§3.3)'
688
- const parsed = parseArgs(
689
- rest,
690
- {
691
- once: 'boolean',
692
- interval: 'value',
693
- store: 'value',
694
- repository: 'value',
695
- plain: 'boolean',
696
- intake: 'boolean',
697
- 'no-intake': 'boolean',
698
- 'auto-merge': 'boolean',
699
- 'no-auto-merge': 'boolean',
700
- },
701
- usage,
702
- )
703
- if (parsed.positionals.length > 0) throw new Error(usage)
704
-
705
- const once = parsed.flags.has('once')
706
- const plain = parsed.flags.has('plain')
707
- const sawIntake = parsed.flags.has('intake')
708
- const sawNoIntake = parsed.flags.has('no-intake')
709
- const sawAutoMerge = parsed.flags.has('auto-merge')
710
- const sawNoAutoMerge = parsed.flags.has('no-auto-merge')
711
- if (sawIntake && sawNoIntake) {
712
- throw new Error(`--intake and --no-intake cannot be combined — ${usage}`)
713
- }
714
- if (sawAutoMerge || sawNoAutoMerge) {
715
- throw new Error(`Auto-merge flags are retired; configure [[landing]] policy — ${usage}`)
716
- }
717
-
718
- const interval = stringFlag(parsed, 'interval')
719
- let intervalMs: number | undefined
720
- if (interval !== undefined) {
721
- const seconds = Number(interval)
722
- if (!Number.isFinite(seconds) || seconds <= 0) {
723
- throw new Error(`--interval requires a positive number of seconds — ${usage}`)
724
- }
725
- intervalMs = Math.round(seconds * 1000)
726
- }
727
- const storeRef = stringFlag(parsed, 'store')
728
- const repository = stringFlag(parsed, 'repository') ?? deps.processEnv?.AB_REPOSITORY
729
- const intake = sawIntake ? true : sawNoIntake ? false : undefined
730
- const defaultAutoMerge = sawAutoMerge ? true : sawNoAutoMerge ? false : undefined
701
+ const { once, plain, intake, defaultAutoMerge, intervalMs, storeRef, repository } =
702
+ parseDispatchArgs(rest, deps.processEnv ?? {})
731
703
  if (deps.exec === undefined) {
732
704
  throw new Error("'ab dispatch' needs an exec seam — this is a wiring bug in the ab binary")
733
705
  }
@@ -1207,7 +1179,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1207
1179
  let revisionTicketSource: import('../ports/types').TicketSource | undefined
1208
1180
  const readTicketBody =
1209
1181
  resolve?.kind === 'revise-spec' && resolve.body.kind === 'ticket'
1210
- ? async (ref: TicketRef): Promise<string> => {
1182
+ ? async (original: TicketRef, store: BuildStore, repo: string): Promise<string> => {
1211
1183
  const { source } = await openTicketSource(
1212
1184
  {
1213
1185
  targetRepo: deps.workspacePath,
@@ -1219,11 +1191,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1219
1191
  'ab answer --revise-spec-from-ticket',
1220
1192
  )
1221
1193
  revisionTicketSource = source
1222
- if (source.name !== ref.source) {
1223
- throw new Error(
1224
- `build ticket source is "${ref.source}", but this repository is configured for "${source.name}"; refusing to read a same-id ticket from a different source`,
1225
- )
1226
- }
1194
+ const ref = await currentTicketRef(store, repo, source.name, original, slug)
1227
1195
  const ticket = await source.get(ref.id)
1228
1196
  if (ticket === null) {
1229
1197
  throw new Error(
@@ -1256,7 +1224,12 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1256
1224
  ? async (ref, store, repo) => {
1257
1225
  if (!revisionTicketSource)
1258
1226
  throw new Error('ticket body must be read before preparing assets')
1259
- return preparePinnedAssets(revisionTicketSource, store, repo, ref.id)
1227
+ return preparePinnedAssets(
1228
+ revisionTicketSource,
1229
+ store,
1230
+ repo,
1231
+ (await currentTicketRef(store, repo, revisionTicketSource.name, ref, slug)).id,
1232
+ )
1260
1233
  }
1261
1234
  : undefined,
1262
1235
  )
@@ -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. */