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

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 (172) hide show
  1. package/SPEC.md +310 -56
  2. package/bin/ab-build-runner.ts +10 -8
  3. package/docs/architecture.md +177 -23
  4. package/docs/configuration.md +35 -4
  5. package/docs/hosted-service.md +35 -0
  6. package/docs/integration-tree.md +83 -4
  7. package/docs/landing-policy.md +11 -0
  8. package/docs/migration-1.0.md +9 -0
  9. package/docs/operator-api.md +18 -0
  10. package/docs/remote-store-protocol.md +16 -0
  11. package/docs/remote-ticket-protocol.md +5 -0
  12. package/docs/restacking.md +42 -7
  13. package/docs/setup.md +25 -0
  14. package/docs/spec-standard.md +71 -0
  15. package/docs/ticket-dependencies.md +6 -45
  16. package/docs/ticket-migration.md +50 -4
  17. package/package.json +3 -3
  18. package/packages/core/src/cli/attention.ts +4 -1
  19. package/packages/core/src/cli/binary.ts +17 -1
  20. package/packages/core/src/cli/build-control.ts +3 -3
  21. package/packages/core/src/cli/context.ts +53 -1
  22. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  23. package/packages/core/src/cli/dashboard/detail.ts +45 -1
  24. package/packages/core/src/cli/dashboard/facts.ts +7 -2
  25. package/packages/core/src/cli/dashboard/integration-detail.ts +144 -0
  26. package/packages/core/src/cli/dashboard/integration-row.ts +255 -0
  27. package/packages/core/src/cli/dashboard/landing-display.ts +64 -0
  28. package/packages/core/src/cli/dashboard/model.ts +147 -16
  29. package/packages/core/src/cli/dashboard/poll.ts +40 -4
  30. package/packages/core/src/cli/dashboard/render.ts +106 -5
  31. package/packages/core/src/cli/dashboard/transcript.ts +2 -1
  32. package/packages/core/src/cli/dispatch-frontend.ts +11 -0
  33. package/packages/core/src/cli/dispatch-repository-feed.ts +2 -1
  34. package/packages/core/src/cli/dispatch.ts +49 -14
  35. package/packages/core/src/cli/help.ts +17 -1
  36. package/packages/core/src/cli/main.ts +48 -8
  37. package/packages/core/src/cli/publication-settlement.ts +49 -5
  38. package/packages/core/src/cli/repository-status.ts +103 -2
  39. package/packages/core/src/cli/status.ts +24 -1
  40. package/packages/core/src/cli/terminals.ts +94 -93
  41. package/packages/core/src/cli/ticket.ts +35 -11
  42. package/packages/core/src/cli/wait.ts +11 -2
  43. package/packages/core/src/cli/watch.ts +12 -0
  44. package/packages/core/src/config/schema.ts +3 -0
  45. package/packages/core/src/events/catalog.ts +38 -0
  46. package/packages/core/src/events/compatibility.ts +183 -0
  47. package/packages/core/src/events/native-session.ts +13 -0
  48. package/packages/core/src/events/payloads.ts +150 -2
  49. package/packages/core/src/events/policy.ts +210 -0
  50. package/packages/core/src/events/repository.ts +69 -0
  51. package/packages/core/src/integration/harness.ts +4 -4
  52. package/packages/core/src/kernel/__snapshots__/{reducer-registry.test.ts.snap → reducer-accumulator-shapes.json} +4286 -4006
  53. package/packages/core/src/kernel/change-presence.ts +11 -3
  54. package/packages/core/src/kernel/dispatch-capacity.ts +127 -0
  55. package/packages/core/src/kernel/dispatcher-liveness.ts +5 -1
  56. package/packages/core/src/kernel/engine.ts +25 -5
  57. package/packages/core/src/kernel/forge-health.ts +19 -0
  58. package/packages/core/src/kernel/generators/build-log.ts +18 -0
  59. package/packages/core/src/kernel/generators/node-restack-log.ts +1 -1
  60. package/packages/core/src/kernel/generators/repository-journals.ts +10 -0
  61. package/packages/core/src/kernel/guarded-forge.ts +159 -0
  62. package/packages/core/src/kernel/incremental.ts +4 -2
  63. package/packages/core/src/kernel/integration-completeness.ts +108 -9
  64. package/packages/core/src/kernel/integration-landing.ts +5 -4
  65. package/packages/core/src/kernel/janitor-failure.ts +36 -0
  66. package/packages/core/src/kernel/landing-publication.ts +35 -15
  67. package/packages/core/src/kernel/landing-state.ts +7 -0
  68. package/packages/core/src/kernel/leaf-restack-state.ts +1 -1
  69. package/packages/core/src/kernel/log-index.ts +12 -1
  70. package/packages/core/src/kernel/mixed-version.ts +52 -0
  71. package/packages/core/src/kernel/node-landing.ts +14 -11
  72. package/packages/core/src/kernel/node-parent.ts +35 -10
  73. package/packages/core/src/kernel/node-restack-demand.ts +29 -0
  74. package/packages/core/src/kernel/node-restack-state.ts +46 -16
  75. package/packages/core/src/kernel/node-restack-transaction.ts +151 -8
  76. package/packages/core/src/kernel/node-restack.ts +34 -10
  77. package/packages/core/src/kernel/publication.ts +22 -0
  78. package/packages/core/src/kernel/read-deferrals.ts +111 -0
  79. package/packages/core/src/kernel/read-facts.ts +34 -6
  80. package/packages/core/src/kernel/reconcile-restack.ts +23 -2
  81. package/packages/core/src/kernel/reducer-registry.ts +18 -2
  82. package/packages/core/src/kernel/reducer.ts +196 -10
  83. package/packages/core/src/kernel/repository-attention.ts +38 -1
  84. package/packages/core/src/kernel/terminal-guard.ts +11 -4
  85. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  86. package/packages/core/src/operator/annotations.ts +6 -0
  87. package/packages/core/src/operator/index.ts +2 -0
  88. package/packages/core/src/operator/presentation.ts +5 -0
  89. package/packages/core/src/operator/query.ts +51 -11
  90. package/packages/core/src/operator/registry.ts +17 -1
  91. package/packages/core/src/operator/restack.ts +51 -0
  92. package/packages/core/src/operator/tickets.ts +30 -26
  93. package/packages/core/src/plugin-sdk/index.ts +10 -0
  94. package/packages/core/src/plugins/manifest.ts +1 -1
  95. package/packages/core/src/ports/forge/contract.ts +23 -0
  96. package/packages/core/src/ports/forge/fake.ts +6 -2
  97. package/packages/core/src/ports/forge/git-rewrite.ts +92 -64
  98. package/packages/core/src/ports/forge/github-transport.ts +45 -2
  99. package/packages/core/src/ports/forge/github.ts +56 -17
  100. package/packages/core/src/ports/forge/local-git.ts +7 -2
  101. package/packages/core/src/ports/forge-failure.ts +40 -0
  102. package/packages/core/src/ports/forge-request-context.ts +35 -0
  103. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  104. package/packages/core/src/ports/runner/claude.ts +136 -9
  105. package/packages/core/src/ports/runner/codex.ts +112 -7
  106. package/packages/core/src/ports/runner/contract.ts +78 -0
  107. package/packages/core/src/ports/runner/fake.ts +59 -1
  108. package/packages/core/src/ports/runner/native-cli-fixture.ts +86 -0
  109. package/packages/core/src/ports/runner/native-process-fixture.ts +38 -0
  110. package/packages/core/src/ports/runner/native-session.ts +110 -0
  111. package/packages/core/src/ports/runner/pi-rpc.ts +7 -1
  112. package/packages/core/src/ports/runner/pi.ts +162 -2
  113. package/packages/core/src/ports/tickets/linear.ts +180 -12
  114. package/packages/core/src/ports/tickets/migration.ts +92 -9
  115. package/packages/core/src/ports/types.ts +60 -5
  116. package/packages/core/src/ports/workspace/git-worktree.ts +45 -51
  117. package/packages/core/src/ports/workspace/vercel-sandbox.ts +28 -12
  118. package/packages/core/src/processes/build-child-exit.ts +50 -2
  119. package/packages/core/src/processes/build-child.ts +15 -7
  120. package/packages/core/src/processes/build-runner.ts +909 -213
  121. package/packages/core/src/processes/dispatcher.ts +815 -369
  122. package/packages/core/src/processes/execution-no-progress.ts +15 -0
  123. package/packages/core/src/processes/pause-execution-fixture.ts +37 -0
  124. package/packages/core/src/processes/phase-failure-budget.ts +2 -1
  125. package/packages/core/src/processes/publication-loss.ts +7 -3
  126. package/packages/core/src/processes/repo-view.ts +53 -6
  127. package/packages/core/src/processes/tick-publication.ts +6 -2
  128. package/packages/core/src/runtime-identity.ts +37 -0
  129. package/packages/core/src/store/adapter.ts +4 -2
  130. package/packages/core/src/store/build-scope.ts +9 -0
  131. package/packages/core/src/store/contract.ts +233 -16
  132. package/packages/core/src/store/digest.ts +20 -2
  133. package/packages/core/src/store/local/schema.ts +6 -0
  134. package/packages/core/src/store/local/store.ts +57 -4
  135. package/packages/core/src/store/memory.ts +83 -2
  136. package/packages/core/src/store/new-build.ts +2 -2
  137. package/packages/core/src/store/phase-session.ts +13 -0
  138. package/packages/core/src/store/reduced-reads.ts +43 -4
  139. package/packages/core/src/store/reducer-value-shapes.json +8911 -6344
  140. package/packages/core/src/store/reducer-value-validation.ts +103 -3
  141. package/packages/core/src/store/reducer-values.ts +21 -6
  142. package/packages/core/src/store/remote/client.ts +145 -20
  143. package/packages/core/src/store/remote/index.ts +2 -0
  144. package/packages/core/src/store/remote/protocol.ts +19 -0
  145. package/packages/core/src/store/remote/version.ts +2 -0
  146. package/packages/core/src/store/repo-state-events.ts +5 -2
  147. package/packages/core/src/store/repo-tick.ts +6 -1
  148. package/packages/core/src/store/session-handle.ts +8 -0
  149. package/packages/core/src/store/snapshots.ts +21 -5
  150. package/packages/core/src/store/types.ts +17 -1
  151. package/packages/core/src/testing/dispatch-read-budget.ts +18 -2
  152. package/packages/core/src/testing/index.ts +7 -0
  153. package/packages/core/src/testing/newer-writer.ts +37 -0
  154. package/packages/core/src/testing/reduced-read-budget.ts +3 -0
  155. package/skills/guide/SKILL.md +140 -25
  156. package/skills/guide/references/integration-tree.md +83 -4
  157. package/skills/guide/references/landing-policy.md +11 -0
  158. package/skills/guide/references/migration-1.0.md +9 -0
  159. package/skills/guide/references/operator-api.md +18 -0
  160. package/skills/guide/references/plugin-authoring.md +47 -4
  161. package/skills/guide/references/remote-store-protocol.md +16 -0
  162. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  163. package/skills/guide/references/restacking.md +42 -7
  164. package/skills/guide/references/setup.md +25 -0
  165. package/skills/guide/references/spec-standard.md +71 -0
  166. package/skills/guide/references/ticket-dependencies.md +6 -45
  167. package/skills/guide/references/ticket-migration.md +50 -4
  168. package/skills/implement/SKILL.md +4 -2
  169. package/skills/operate/SKILL.md +63 -6
  170. package/skills/reconcile/SKILL.md +3 -1
  171. package/skills/spec/SKILL.md +62 -40
  172. package/skills/tickets/SKILL.md +15 -43
@@ -1,3 +1,9 @@
1
+ import { migrationIdentity } from '../kernel/ticket-migrations'
2
+ import { formatDispatcherError } from '../runtime-identity'
3
+
4
+ import { isDeepStrictEqual } from 'node:util'
5
+ import { guardForge } from '../kernel/guarded-forge'
6
+ import { dispatchCapacity } from '../kernel/dispatch-capacity'
1
7
  import { openTicketSource } from './ticket'
2
8
  import {
3
9
  inspectForgeReadiness,
@@ -824,6 +830,12 @@ class DispatchLoop {
824
830
  repo: this.repoIdentity,
825
831
  resident: opts.once !== true,
826
832
  })
833
+ wiring.forge = guardForge(wiring.forge, {
834
+ store: this.repoView,
835
+ repo: this.repoIdentity,
836
+ name: config.forge,
837
+ now: wiring.clock,
838
+ })
827
839
  this.dispatcher = new Dispatcher({
828
840
  store: this.repoView,
829
841
  tickets: wiring.tickets,
@@ -2930,7 +2942,14 @@ class DispatchLoop {
2930
2942
  events: RepositoryEventWrite[],
2931
2943
  ): Promise<RepoTickFinish | null> {
2932
2944
  try {
2933
- return await this.repoView.finishRepoTick(this.repoIdentity, this.runId, completion, events)
2945
+ // Closing a durable boundary must not depend on a subsequent view read.
2946
+ // The next operational tick refreshes the view before any decisions.
2947
+ return await this.wiring.store.finishRepoTick(
2948
+ this.repoIdentity,
2949
+ this.runId,
2950
+ completion,
2951
+ events,
2952
+ )
2934
2953
  } catch (error) {
2935
2954
  const observation = (await this.wiring.store.getRepo(this.repoIdentity).catch(() => null))
2936
2955
  ?.tick
@@ -2947,13 +2966,13 @@ class DispatchLoop {
2947
2966
  (finished.outcome === 'completed' &&
2948
2967
  completion.outcome === 'completed' &&
2949
2968
  Object.entries(completion.counters).some(
2950
- ([key, value]) => finished.counters[key as keyof typeof finished.counters] !== value,
2969
+ ([key, value]) =>
2970
+ !isDeepStrictEqual(finished.counters[key as keyof typeof finished.counters], value),
2951
2971
  ))
2952
2972
  )
2953
2973
  throw error
2954
- // The failed response bypassed the view's own-write fold. Refresh its
2955
- // cursor from the journal, including any committed boundary pair.
2956
- await this.repoView.refresh()
2974
+ // Metadata confirms the exact committed boundary. The next operational
2975
+ // tick refreshes facts before making decisions.
2957
2976
  return { observation, events: [] }
2958
2977
  }
2959
2978
  }
@@ -2962,20 +2981,27 @@ class DispatchLoop {
2962
2981
  const failed = {
2963
2982
  actor: DISPATCHER,
2964
2983
  type: 'dispatcher.tick-failed' as const,
2965
- payload: { run: this.runId, error: error instanceof Error ? error.message : String(error) },
2984
+ payload: { run: this.runId, error: formatDispatcherError(error) },
2966
2985
  }
2967
2986
  if (this.tickStartedAt === undefined) {
2968
- await this.appendStatus(failed)
2987
+ await this.wiring.store.appendRepo(this.repoIdentity, failed)
2969
2988
  return
2970
2989
  }
2971
- const result = await this.finishTick({ outcome: 'failed', error: failed.payload.error }, [
2990
+ const result = await this.finishTick(
2972
2991
  {
2973
- actor: DISPATCHER,
2974
- type: 'dispatcher.tick-started',
2975
- payload: { run: this.runId, startedAt: this.tickStartedAt },
2992
+ outcome: 'failed',
2993
+ error: failed.payload.error,
2994
+ forgeRequests: this.dispatcher.lastForgeRequests,
2976
2995
  },
2977
- failed,
2978
- ])
2996
+ [
2997
+ {
2998
+ actor: DISPATCHER,
2999
+ type: 'dispatcher.tick-started',
3000
+ payload: { run: this.runId, startedAt: this.tickStartedAt },
3001
+ },
3002
+ failed,
3003
+ ],
3004
+ )
2979
3005
  if (result === null) {
2980
3006
  this.superseded = true
2981
3007
  return
@@ -3638,6 +3664,15 @@ class DispatchLoop {
3638
3664
  (state) => state.kind !== 'node' && state.status !== 'done' && state.status !== 'aborted',
3639
3665
  ).length,
3640
3666
  capacity: configSnapshot.config.capacity,
3667
+ capacityProjection: dispatchCapacity(
3668
+ buildSnapshot.capacityBuilds ?? [],
3669
+ configSnapshot.config.capacity,
3670
+ this.wiring.clock(),
3671
+ migrationIdentity(
3672
+ repositoryEvents.ticketMigrations,
3673
+ configSnapshot.config.tickets.source,
3674
+ ),
3675
+ ),
3641
3676
  observationCount: this.observationCount,
3642
3677
  observationLimit: configSnapshot.config.policy.harvestThreshold,
3643
3678
  },
@@ -4040,7 +4075,7 @@ class DispatchLoop {
4040
4075
  startup = false
4041
4076
  } catch (error) {
4042
4077
  if (this.forgePublicationFailed) throw error
4043
- const message = error instanceof Error ? error.message : String(error)
4078
+ const message = formatDispatcherError(error)
4044
4079
  await this.publishTickFailure(error)
4045
4080
  this.warn(`tick failed: ${message}`)
4046
4081
  }
@@ -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]',
@@ -346,7 +347,7 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
346
347
  ' flushed as soon as it is written.',
347
348
  ' --store <ref> Override the BuildStore path or URL.',
348
349
  '',
349
- 'Default filter — actionable attention only. Builds: escalation.raised, integration.landed,',
350
+ 'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
350
351
  'node.item-conflicted, conflicted restack.replayed, derived build.consent-ready and',
351
352
  'build.merge-decision (a current actionable merge-gate deferral or unsafe forge outcome).',
352
353
  'Consent and held ready landings use only build.consent-ready, once per readiness episode.',
@@ -504,6 +505,9 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
504
505
  ' ab pause <slug> [--store <ref>]',
505
506
  ' ab pause --all [--store <ref>] [--json]',
506
507
  '',
508
+ 'Pause immediately suspends a live agent session after its bounded stop delay.',
509
+ 'Resume continues where it stopped when supported; remote and unsupported',
510
+ 'sessions rerun fresh. Without a live agent, pause waits for the next boundary.',
507
511
  'Durably request that an active build pause. --store overrides the BuildStore',
508
512
  'path or URL. This command is sessionless; a phase may not control its own build.',
509
513
  '',
@@ -600,6 +604,18 @@ These fields describe intent; dispatch and landing behavior are unchanged.`,
600
604
  'may not control its own build.',
601
605
  ]),
602
606
  },
607
+ {
608
+ name: 'restack',
609
+ audience: 'human',
610
+ summary: 'Request a node restack onto its current parent.',
611
+ detail: page([
612
+ 'Usage: ab restack <node> [--store <ref>]',
613
+ '',
614
+ 'Records durable demand, coalescing repeated pending requests.',
615
+ 'Paused or blocked nodes wait for normal safety gates. Leaves, terminal nodes',
616
+ 'and nodes without an open branch are refused. This command is sessionless.',
617
+ ]),
618
+ },
603
619
  ...(['hold', 'land'] as const).map((name) => ({
604
620
  name,
605
621
  audience: 'human' as const,
@@ -1,3 +1,6 @@
1
+ import { currentTicketRef } from '../kernel/ticket-migrations'
2
+ import { requestNodeRestack } from '../operator/restack'
3
+ import { withSessionlessStore } from './store-opening'
1
4
  import { abLandings } from './landings'
2
5
  import { readBuildFacts } from '../store/reduced-reads'
3
6
  import { preparePinnedAssets } from '../store/ticket-assets'
@@ -112,6 +115,7 @@ export const SESSIONLESS_COMMANDS = new Set([
112
115
  'wait',
113
116
  'mcp',
114
117
  'repository',
118
+ 'restack',
115
119
  'pause',
116
120
  'resume',
117
121
  'hold',
@@ -315,7 +319,7 @@ async function runBuildControl(
315
319
  slug: string,
316
320
  action: BuildControlAction,
317
321
  storeRef?: string,
318
- readTicketBody?: (ref: TicketRef) => Promise<string>,
322
+ readTicketBody?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<string>,
319
323
  prepareTicketAssets?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<PinnedAsset[]>,
320
324
  ): Promise<void> {
321
325
  if (deps.exec === undefined) {
@@ -667,6 +671,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
667
671
  throw new Error("'ab ticket' needs an exec seam — this is a wiring bug in the ab binary")
668
672
  }
669
673
  await abTicket(rest, {
674
+ signal: deps.signal,
670
675
  targetRepo: deps.workspacePath,
671
676
  env: deps.processEnv ?? {},
672
677
  exec: deps.exec,
@@ -1045,6 +1050,40 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1045
1050
  })
1046
1051
  }
1047
1052
 
1053
+ case 'restack': {
1054
+ const usage = 'usage: ab restack <node> [--store <ref>]'
1055
+ const parsed = parseArgs(rest, { store: 'value' }, usage)
1056
+ if (parsed.positionals.length !== 1) throw new Error(usage)
1057
+ if (
1058
+ deps.processEnv?.AB_SESSION?.trim() &&
1059
+ deps.processEnv?.AB_BUILD?.trim() === parsed.positionals[0]
1060
+ )
1061
+ throw new Error(
1062
+ 'cannot restack a node from its own phase session (AB_SESSION/AB_BUILD conflict)',
1063
+ )
1064
+ if (!deps.exec) throw new Error('restack requires an exec seam')
1065
+ const result = await withSessionlessStore(
1066
+ {
1067
+ targetRepo: deps.workspacePath,
1068
+ env: deps.processEnv ?? {},
1069
+ exec: deps.exec,
1070
+ ...(stringFlag(parsed, 'store') ? { storeRef: stringFlag(parsed, 'store') } : {}),
1071
+ ...(deps.openStore ? { openStore: deps.openStore } : {}),
1072
+ },
1073
+ ({ store, repo }) =>
1074
+ requestNodeRestack({
1075
+ store,
1076
+ repo,
1077
+ slug: parsed.positionals[0]!,
1078
+ user: deps.processEnv?.USER?.trim() || deps.processEnv?.USERNAME?.trim() || 'operator',
1079
+ }),
1080
+ )
1081
+ deps.stdout(
1082
+ `restack requested for ${result.slug}${result.waiting ? '; waiting for normal safety gates' : ''}`,
1083
+ )
1084
+ return 0
1085
+ }
1086
+
1048
1087
  case 'abort': {
1049
1088
  const usage = 'usage: ab abort <slug> [--store <ref>]'
1050
1089
  const parsed = parseArgs(rest, { store: 'value' }, usage)
@@ -1170,7 +1209,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1170
1209
  let revisionTicketSource: import('../ports/types').TicketSource | undefined
1171
1210
  const readTicketBody =
1172
1211
  resolve?.kind === 'revise-spec' && resolve.body.kind === 'ticket'
1173
- ? async (ref: TicketRef): Promise<string> => {
1212
+ ? async (original: TicketRef, store: BuildStore, repo: string): Promise<string> => {
1174
1213
  const { source } = await openTicketSource(
1175
1214
  {
1176
1215
  targetRepo: deps.workspacePath,
@@ -1182,11 +1221,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1182
1221
  'ab answer --revise-spec-from-ticket',
1183
1222
  )
1184
1223
  revisionTicketSource = source
1185
- if (source.name !== ref.source) {
1186
- throw new Error(
1187
- `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`,
1188
- )
1189
- }
1224
+ const ref = await currentTicketRef(store, repo, source.name, original, slug)
1190
1225
  const ticket = await source.get(ref.id)
1191
1226
  if (ticket === null) {
1192
1227
  throw new Error(
@@ -1219,7 +1254,12 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1219
1254
  ? async (ref, store, repo) => {
1220
1255
  if (!revisionTicketSource)
1221
1256
  throw new Error('ticket body must be read before preparing assets')
1222
- return preparePinnedAssets(revisionTicketSource, store, repo, ref.id)
1257
+ return preparePinnedAssets(
1258
+ revisionTicketSource,
1259
+ store,
1260
+ repo,
1261
+ (await currentTicketRef(store, repo, revisionTicketSource.name, ref, slug)).id,
1262
+ )
1223
1263
  }
1224
1264
  : undefined,
1225
1265
  )
@@ -1,3 +1,6 @@
1
+ import { ForgeRequestDeferred } from '../ports/forge-request-context'
2
+ import { stat } from 'node:fs/promises'
3
+ import { deferMixedVersion, MixedVersionDeferral } from '../kernel/mixed-version'
1
4
  import { suspendNativeLanding } from '../kernel/landing-publication'
2
5
  import { completeAutomaticReconcile } from '../kernel/leaf-restack-completion'
3
6
  import { readBuildFacts, readPhaseFailures } from '../store/reduced-reads'
@@ -23,6 +26,26 @@ export interface PublicationSettlementDeps {
23
26
  clock?: Clock
24
27
  }
25
28
 
29
+ /** Hosted guests have a separate ref database. Refresh a real dispatcher cache
30
+ * too, when this deployment retains one; origin-only dispatchers have none. */
31
+ async function confirmDispatcherCache(
32
+ deps: PublicationSettlementDeps,
33
+ branch: string,
34
+ sha: string,
35
+ ) {
36
+ if (!deps.forge.confirmPublication) return
37
+ try {
38
+ if (!(await stat(deps.workspacePath)).isDirectory()) return
39
+ } catch (error) {
40
+ if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return
41
+ throw error
42
+ }
43
+ const repository = await deps.exec(['git', 'rev-parse', '--git-dir'], { cwd: deps.workspacePath })
44
+ if (repository.exitCode !== 0 || !repository.stdout.trim()) return
45
+ if (!(await deps.forge.confirmPublication(deps.workspacePath, branch, sha)))
46
+ throw new Error(`dispatcher publication readback did not confirm ${sha}`)
47
+ }
48
+
26
49
  /** Settle one durable request after the caller has observed environment
27
50
  * completion and released its exact execution lease. External effects precede
28
51
  * completion facts, making every crash gap safely retryable.
@@ -37,6 +60,7 @@ export async function settlePendingPublication(
37
60
  ): Promise<void> {
38
61
  const publication = deps.publication
39
62
  if (publication === undefined) return
63
+ if (await deferMixedVersion(deps.store, slug)) return
40
64
  await completeAutomaticReconcile(deps.store, slug)
41
65
  let events = (await readBuildFacts(deps.store, slug)).value
42
66
  const request = events.publication.latestUncompletedRequest()
@@ -82,6 +106,8 @@ export async function settlePendingPublication(
82
106
  localExpected: transaction.localBranchHead,
83
107
  archives,
84
108
  })
109
+ if (result.kind === 'published')
110
+ await confirmDispatcherCache(deps, request.payload.branch, request.payload.sha)
85
111
  const latest = (await readBuildFacts(deps.store, slug)).value
86
112
  if (
87
113
  (result.kind === 'published' || result.rewritten === true) &&
@@ -155,6 +181,8 @@ export async function settlePendingPublication(
155
181
  localExpected: transaction.localBranchHead,
156
182
  archives,
157
183
  })
184
+ if (result.kind === 'published')
185
+ await confirmDispatcherCache(deps, request.payload.branch, request.payload.sha)
158
186
  const history = (await readBuildFacts(deps.store, slug)).value.reconcileHistory
159
187
  if (
160
188
  (result.kind === 'published' || result.rewritten === true) &&
@@ -208,10 +236,17 @@ export async function settlePendingPublication(
208
236
  // Consulted for every uncompleted request, not only abandoned ones: a guest
209
237
  // that pushed its branch before dying is owed its completion fact, not a
210
238
  // re-push or a loss record.
211
- const alreadyPublished =
212
- publication.isPublished !== undefined
213
- ? await publication.isPublished({ sha: request.payload.sha, branch: request.payload.branch })
214
- : false
239
+ if (!publication.isPublished)
240
+ throw new Error(
241
+ 'workspace provider lacks authoritative publication inspection; upgrade the provider',
242
+ )
243
+ const probe = () =>
244
+ publication.isPublished!({
245
+ ref: events.workspace?.ref,
246
+ sha: request.payload.sha,
247
+ branch: request.payload.branch,
248
+ })
249
+ const alreadyPublished = await probe()
215
250
  if (abandoned && !alreadyPublished) {
216
251
  // Last-chance backstop (AUT-328): the workspace is gone with this request
217
252
  // uncompleted. Record the loss durably (deduped per request) instead of
@@ -249,9 +284,17 @@ export async function settlePendingPublication(
249
284
  if (ref === undefined)
250
285
  throw new Error(`build ${slug} has a publication request but no open workspace`)
251
286
  await suspendNativeLanding({ ...deps, slug }, `publication:${request.seq}`)
252
- await publication.publish({ ref, sha: request.payload.sha, branch: request.payload.branch })
287
+ try {
288
+ await publication.publish({ ref, sha: request.payload.sha, branch: request.payload.branch })
289
+ } catch (error) {
290
+ if (!(await probe())) throw error
291
+ }
292
+ if (!(await probe()))
293
+ throw new Error(`publication readback did not confirm ${request.payload.sha}`)
253
294
  }
254
295
  } catch (error) {
296
+ if (error instanceof ForgeRequestDeferred) throw error
297
+ if (error instanceof MixedVersionDeferral) return
255
298
  if (request.payload.operation !== 'finalize-step') throw error
256
299
  const detail = error instanceof Error ? error.message : String(error)
257
300
  const note = `finalize publication failed: ${detail}`
@@ -271,6 +314,7 @@ export async function settlePendingPublication(
271
314
  })
272
315
  return
273
316
  }
317
+ await confirmDispatcherCache(deps, request.payload.branch, request.payload.sha)
274
318
  events = (await readBuildFacts(deps.store, slug)).value
275
319
  if (events.publication.requestCompleted(request)) return
276
320
 
@@ -1,3 +1,14 @@
1
+ import { migrationIdentity } from '../kernel/ticket-migrations'
2
+ import {
3
+ dispatchCapacity,
4
+ type DispatchCapacity,
5
+ type CapacityBuild,
6
+ } from '../kernel/dispatch-capacity'
7
+ import { forgeHealthReducer, type ForgeDegradation } from '../kernel/forge-health'
8
+ import { forgeHotspot, type ForgeRequestCounts } from '../ports/forge-telemetry'
9
+ import { configSchema } from '../config/schema'
10
+ import type { BuildStore } from '../store/types'
11
+ import { readBuildFacts } from '../store/reduced-reads'
1
12
  import { forgeReadinessWarnings, reduceDispatchStatus } from '../kernel/dispatch-status'
2
13
  import { readRepositoryFacts, type RepositoryReadFacts } from '../store/reduced-reads'
3
14
  import {
@@ -19,8 +30,12 @@ import { withSessionlessStore, type StoreOpener } from './store-opening'
19
30
  /** Script-facing projection returned by `ab repository status`. */
20
31
  export interface RepositoryStatus extends DispatchSettings {
21
32
  repo: string
33
+ capacity?: DispatchCapacity
22
34
  warningLines?: string[]
23
35
  dispatcher: DispatcherLiveness
36
+ forgeRequests?: ForgeRequestCounts
37
+ forgeRequestHotspot?: string
38
+ forgeDegradation?: ForgeDegradation
24
39
  ticketSourceDegradation?: TicketSourceDegradation
25
40
  /** Live operator sandboxes (AUT-340); released environments are omitted. */
26
41
  sandboxes: Array<{
@@ -90,10 +105,21 @@ export function projectRepositoryStatus(
90
105
  ? forgeReadinessWarnings(reduceDispatchStatus(events, latestRun.payload.run))
91
106
  : []
92
107
  return {
108
+ ...(forgeHealthReducer.reduce(events)
109
+ ? { forgeDegradation: forgeHealthReducer.reduce(events) }
110
+ : {}),
93
111
  ...(active === undefined ? {} : { ticketSourceDegradation: active }),
94
112
  repo,
95
113
  ...(warningLines.length ? { warningLines } : {}),
96
114
  dispatcher,
115
+ ...(() => {
116
+ const tick = (dispatcher.holder ?? dispatcher.expiredHolder ?? dispatcher.latestRun)?.lastTick
117
+ const forgeRequests =
118
+ tick?.outcome === 'completed' ? tick.counters.forgeRequests : tick?.forgeRequests
119
+ return forgeRequests
120
+ ? { forgeRequests, forgeRequestHotspot: forgeHotspot(forgeRequests) }
121
+ : {}
122
+ })(),
97
123
  ...reduceDispatchSettings(events),
98
124
  sandboxes: sandboxStates(events)
99
125
  .filter((state) => state.state !== 'released')
@@ -118,7 +144,16 @@ export function repositoryStatusFromFacts(
118
144
  repo,
119
145
  ...(warningLines.length ? { warningLines } : {}),
120
146
  dispatcher,
147
+ ...(() => {
148
+ const tick = (dispatcher.holder ?? dispatcher.expiredHolder ?? dispatcher.latestRun)?.lastTick
149
+ const forgeRequests =
150
+ tick?.outcome === 'completed' ? tick.counters.forgeRequests : tick?.forgeRequests
151
+ return forgeRequests
152
+ ? { forgeRequests, forgeRequestHotspot: forgeHotspot(forgeRequests) }
153
+ : {}
154
+ })(),
121
155
  ...facts.settings,
156
+ ...(facts.forgeHealth ? { forgeDegradation: facts.forgeHealth } : {}),
122
157
  ...(facts.health === undefined ? {} : { ticketSourceDegradation: facts.health }),
123
158
  sandboxes: facts.sandboxes
124
159
  .filter((state) => state.state !== 'released')
@@ -142,15 +177,35 @@ export function repositoryStatusFromFacts(
142
177
  }
143
178
 
144
179
  export function renderRepositoryStatus(status: RepositoryStatus): string[] {
180
+ const tick = (
181
+ status.dispatcher.holder ??
182
+ status.dispatcher.expiredHolder ??
183
+ status.dispatcher.latestRun
184
+ )?.lastTick
185
+ const requests = tick?.outcome === 'completed' ? tick.counters.forgeRequests : tick?.forgeRequests
186
+ const hotspot = forgeHotspot(requests)
145
187
  const setting = (enabled: boolean): string => (enabled ? 'ON' : 'OFF')
146
188
  const active = status.ticketSourceDegradation
147
189
  return [
190
+ requests
191
+ ? `forge requests: ${requests.total} (${requests.unattributed} unattributed)${hotspot ? `; hotspot ${hotspot}` : ''}`
192
+ : 'forge requests: unavailable',
193
+ ...(status.forgeDegradation
194
+ ? [
195
+ `forge ${status.forgeDegradation.forge}: degraded — ${status.forgeDegradation.message}; reset ${status.forgeDegradation.resetAt}`,
196
+ ]
197
+ : []),
148
198
  ...(active === undefined
149
199
  ? []
150
200
  : [
151
201
  `ticket source ${active.source}: ${active.cause} (${active.operation}) — ${active.message}${'resetAt' in active ? `; reset ${active.resetAt}` : ''}`,
152
202
  ]),
153
203
  `repository: ${status.repo}`,
204
+ ...(status.capacity
205
+ ? [
206
+ `capacity: ${status.capacity.occupied}/${status.capacity.effective} effective; ${status.capacity.configured} configured; ${status.capacity.borrowingNodes.length} node${status.capacity.borrowingNodes.length === 1 ? '' : 's'} using descendant-held slots${status.capacity.borrowingNodes.length ? `: ${status.capacity.borrowingNodes.join(', ')}` : ''}`,
207
+ ]
208
+ : []),
154
209
  ...(status.warningLines ?? []),
155
210
  `dispatcher: ${status.dispatcher.state}${status.dispatcher.holder ? ` — ${formatDispatcherIdentity(status.dispatcher.holder)}` : ' — no dispatcher holds the repository'}`,
156
211
  ...(status.dispatcher.expiredHolder
@@ -182,6 +237,47 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
182
237
  ]
183
238
  }
184
239
 
240
+ /** Capacity is optional when no held dispatcher has a retrievable configuration. */
241
+ export async function readRepositoryCapacity(
242
+ store: BuildStore,
243
+ repo: string,
244
+ facts: RepositoryReadFacts,
245
+ dispatcher: DispatcherLiveness,
246
+ now: Date,
247
+ ): Promise<DispatchCapacity | undefined> {
248
+ if (
249
+ dispatcher.state === 'held' &&
250
+ facts.status?.effectiveConfig &&
251
+ facts.status.run === dispatcher.holder?.run
252
+ ) {
253
+ const ref = facts.status.effectiveConfig
254
+ const artifact = await store.getRepoArtifact(repo, ref.kind, ref.rev)
255
+ if (artifact) {
256
+ const config = configSchema.parse(JSON.parse(new TextDecoder().decode(artifact.content)))
257
+ const builds: CapacityBuild[] = []
258
+ const records = await store.listBuildsForRepo(repo)
259
+ const digests = await store.getRepoBuildDigests(repo)
260
+ for (const record of records) {
261
+ if (digests.get(record.slug)?.terminal) continue
262
+ const build = (await readBuildFacts(store, record.slug)).value
263
+ builds.push({
264
+ record,
265
+ state: build.state,
266
+ workspace: build.workspace !== null,
267
+ provisioning: build.provisionMarker !== undefined,
268
+ })
269
+ }
270
+ return dispatchCapacity(
271
+ builds,
272
+ config.capacity,
273
+ now,
274
+ migrationIdentity(facts.ticketMigrations, config.tickets.source),
275
+ )
276
+ }
277
+ }
278
+ return undefined
279
+ }
280
+
185
281
  /**
186
282
  * `ab repository status` — read the durable dispatcher controls without
187
283
  * creating a repository stream or starting any dispatcher work.
@@ -191,11 +287,16 @@ export async function abRepositoryStatus(opts: RepositoryStatusOpts): Promise<vo
191
287
  // A fresh store has no repository row. Do not call ensureRepo: this query's
192
288
  // empty-stream defaults must remain a genuinely read-only operation.
193
289
  const { dispatcher } = await readDispatcherLiveness(store, repo, opts.now?.())
194
- const status = repositoryStatusFromFacts(
290
+ const facts = (await readRepositoryFacts(store, repo)).value
291
+ const status = repositoryStatusFromFacts(repo, facts, dispatcher)
292
+ const capacity = await readRepositoryCapacity(
293
+ store,
195
294
  repo,
196
- (await readRepositoryFacts(store, repo)).value,
295
+ facts,
197
296
  dispatcher,
297
+ opts.now?.() ?? new Date(),
198
298
  )
299
+ if (capacity) status.capacity = capacity
199
300
  if (opts.json === true) {
200
301
  opts.stdout(JSON.stringify(status, null, 2))
201
302
  return
@@ -1,3 +1,4 @@
1
+ import { compatibilityDiagnostic } from '../kernel/mixed-version'
1
2
  import { indexLog } from '../kernel/log-index'
2
3
  import { projectTree, type TreeProjection } from './dashboard/tree'
3
4
  import { buildVocabulary } from './dashboard/model'
@@ -97,6 +98,8 @@ export interface LeaseInfo {
97
98
  }
98
99
 
99
100
  export interface BuildSummary {
101
+ compatibility?: BuildState['compatibility']
102
+ compatibilityDiagnostic?: string
100
103
  kind?: 'integration' | 'work'
101
104
  target?: string
102
105
  integration?: ReturnType<typeof buildVocabulary>['integration']
@@ -160,6 +163,8 @@ export interface BuildDetail extends BuildSummary {
160
163
  openEscalations: OpenEscalation[]
161
164
  /** Per-loop review overrides for the current spec; omitted when none are set. */
162
165
  reviewRoundCeilings?: { plan?: number; code?: number }
166
+ suspendedSessions: OpenSession[]
167
+ sessionTotals: BuildState['sessions']['totals']
163
168
  openSessions: StatusOpenSession[]
164
169
  observations: BuildObservation[]
165
170
  /** Current setup failure only; a later successful attachment clears it. */
@@ -245,6 +250,12 @@ export function summarizeFrom(record: BuildRecord, state: BuildState, now: Date)
245
250
  // record.ticket is a TicketRef already carrying id/title/url — no artifact
246
251
  // read and no ticket-provider call (live ticket state is out of scope).
247
252
  ...(record.ticket !== undefined ? { ticket: record.ticket } : {}),
253
+ ...(state.compatibility.unknownFacts
254
+ ? {
255
+ compatibility: state.compatibility,
256
+ compatibilityDiagnostic: compatibilityDiagnostic(state.compatibility),
257
+ }
258
+ : {}),
248
259
  status: state.status,
249
260
  ...(active?.phase !== undefined ? { phase: active.phase } : {}),
250
261
  ...(round !== undefined ? { round } : {}),
@@ -351,6 +362,8 @@ export function detailFromFacts(
351
362
  ...(state.reviewRoundCeilings.plan !== undefined || state.reviewRoundCeilings.code !== undefined
352
363
  ? { reviewRoundCeilings: { ...state.reviewRoundCeilings } }
353
364
  : {}),
365
+ suspendedSessions: state.sessions.suspended,
366
+ sessionTotals: state.sessions.totals,
354
367
  openSessions: state.sessions.open.map((session) => {
355
368
  const record = streamStatus.get(`session:${session.session}`)
356
369
  return {
@@ -537,6 +550,11 @@ export function renderSummaries(summaries: BuildSummary[], now: Date, emptyNote:
537
550
  /** Labeled sections, each omitted when absent ("when each is available"). */
538
551
  export function renderDetail(d: BuildDetail, now: Date): string[] {
539
552
  const lines: string[] = [`build ${d.slug}`]
553
+ if (d.compatibility)
554
+ lines.push(
555
+ ` newer facts: ${d.compatibility.unknownFacts} (${d.compatibility.decisiveFacts} decisive)`,
556
+ )
557
+ if (d.compatibilityDiagnostic) lines.push(` ${safeStatusText(d.compatibilityDiagnostic)}`)
540
558
  if (d.ticket !== undefined) {
541
559
  const title = d.ticket.title !== undefined ? ` — ${d.ticket.title}` : ''
542
560
  lines.push(` ticket: ${d.ticket.id}${title}`)
@@ -713,6 +731,11 @@ export function renderDetail(d: BuildDetail, now: Date): string[] {
713
731
  }
714
732
  }
715
733
 
734
+ if (d.suspendedSessions.length > 0) {
735
+ lines.push(` suspended sessions (${d.suspendedSessions.length}):`)
736
+ for (const session of d.suspendedSessions)
737
+ lines.push(` ${session.session} — suspended (shutdown) on ${session.phase}`)
738
+ }
716
739
  if (d.openSessions.length > 0) {
717
740
  lines.push(` open sessions (${d.openSessions.length}):`)
718
741
  for (const session of d.openSessions) {
@@ -721,7 +744,7 @@ export function renderDetail(d: BuildDetail, now: Date): string[] {
721
744
  ? ` — stream ${session.stream} (${session.streamStatus ?? 'open'})`
722
745
  : ''
723
746
  lines.push(
724
- ` ${session.session} — ${session.role} on ${session.phase} (runner ${session.runner})${stream}`,
747
+ ` ${session.session} — ${session.role} on ${session.phase} (runner ${session.runner})${session.resumed ? ' — resumed' : ''}${stream}`,
725
748
  )
726
749
  }
727
750
  }