@defrex/autobuild 1.11.0 → 1.12.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 (110) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +186 -57
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +76 -10
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +13 -11
  8. package/docs/dispatcher.md +5 -4
  9. package/docs/integration-tree.md +28 -16
  10. package/docs/operator-api.md +4 -4
  11. package/docs/operator-surfaces.md +38 -3
  12. package/docs/optimization-nodes.md +3 -2
  13. package/docs/tickets.md +1 -1
  14. package/docs/troubleshooting.md +1 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/ambient-errors.ts +17 -0
  17. package/packages/core/src/cli/bounded-io.ts +174 -0
  18. package/packages/core/src/cli/dashboard/header.ts +10 -0
  19. package/packages/core/src/cli/dashboard/model.ts +81 -23
  20. package/packages/core/src/cli/dashboard/poll.ts +24 -34
  21. package/packages/core/src/cli/dashboard/render.ts +44 -37
  22. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  23. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  24. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  25. package/packages/core/src/cli/dispatch-frontend.ts +12 -3
  26. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  27. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  28. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  29. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  30. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  31. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  32. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  33. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  34. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  35. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  36. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  37. package/packages/core/src/cli/dispatch.ts +70 -9
  38. package/packages/core/src/cli/env.ts +2 -15
  39. package/packages/core/src/cli/help.ts +5 -4
  40. package/packages/core/src/cli/main.ts +4 -2
  41. package/packages/core/src/cli/production-store.ts +102 -0
  42. package/packages/core/src/cli/repo-state.ts +2 -3
  43. package/packages/core/src/cli/repository-status.ts +36 -28
  44. package/packages/core/src/cli/sessionless-store.ts +26 -0
  45. package/packages/core/src/cli/status.ts +169 -40
  46. package/packages/core/src/cli/store-opening.ts +15 -58
  47. package/packages/core/src/cli/store-ref.ts +6 -1
  48. package/packages/core/src/config/schema.ts +1 -1
  49. package/packages/core/src/distribution-packaging.ts +156 -18
  50. package/packages/core/src/events/catalog-identity.ts +28 -0
  51. package/packages/core/src/events/catalog.ts +3 -9
  52. package/packages/core/src/events/compatibility.ts +2 -30
  53. package/packages/core/src/events/payloads.ts +11 -0
  54. package/packages/core/src/events/policy.ts +3 -0
  55. package/packages/core/src/events/repository.ts +1 -1
  56. package/packages/core/src/events/sessions.ts +1 -1
  57. package/packages/core/src/events/validation-error.ts +12 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +74 -30
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  63. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  64. package/packages/core/src/kernel/capacity-build.ts +21 -0
  65. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  67. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  68. package/packages/core/src/kernel/engine.ts +2 -8
  69. package/packages/core/src/kernel/measurement.ts +24 -0
  70. package/packages/core/src/kernel/read-facts.ts +9 -369
  71. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  72. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  73. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  74. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  75. package/packages/core/src/kernel/reducer.ts +57 -9
  76. package/packages/core/src/kernel/reopen-state.ts +10 -0
  77. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  78. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  79. package/packages/core/src/operator/presentation.ts +13 -0
  80. package/packages/core/src/operator/query.ts +47 -41
  81. package/packages/core/src/operator/registry.ts +3 -3
  82. package/packages/core/src/ports/workspace/fake.ts +15 -3
  83. package/packages/core/src/processes/dispatcher.ts +232 -75
  84. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  85. package/packages/core/src/store/local/capabilities.ts +115 -0
  86. package/packages/core/src/store/local/store.ts +86 -56
  87. package/packages/core/src/store/reduced-reads.ts +9 -1
  88. package/packages/core/src/store/reducer-value-read.ts +235 -0
  89. package/packages/core/src/store/reducer-value-shapes.json +3796 -3670
  90. package/packages/core/src/store/reducer-values.ts +36 -204
  91. package/packages/core/src/store/remote/released-clients.json +22 -0
  92. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  93. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  94. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  95. package/packages/core/src/store/rollup-lease.ts +41 -0
  96. package/packages/core/src/store/rollups.ts +7 -38
  97. package/packages/core/src/store/snapshots.ts +1 -1
  98. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  99. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  100. package/packages/core/src/testing/import-graph.ts +78 -0
  101. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  102. package/packages/core/src/testing/slot-agreement.ts +52 -0
  103. package/packages/core/src/web/assets/app.js +5 -5
  104. package/packages/core/src/web/repository-source.ts +6 -2
  105. package/skills/guide/SKILL.md +126 -47
  106. package/skills/guide/references/integration-tree.md +28 -16
  107. package/skills/guide/references/operator-api.md +4 -4
  108. package/skills/guide/references/optimization-nodes.md +3 -2
  109. package/skills/operate/SKILL.md +38 -20
  110. package/templates/hosted-service/package.json +2 -2
@@ -18,7 +18,6 @@ import { LocalAccountOwner, renewLocalAccounts } from '../accounts/local-owner'
18
18
  import { accountRedactor, redactAccountStore } from '../store/account-redaction'
19
19
  import { capturedBuildConfig } from '../processes/verify-cycle-config'
20
20
  import { ForgeRequestDeferred } from '../ports/forge-request-context'
21
- import { migrationIdentity } from '../kernel/ticket-migrations'
22
21
  import { recordRuntimeRollback } from './dispatch-handoff'
23
22
  import { syncRollbackRetention } from './dispatch-runtime-use'
24
23
  import { dirname as runtimeDirname } from 'node:path'
@@ -32,6 +31,7 @@ import { authorizeRemoteHandoffs, recoverDispatchDrain } from '../kernel/dispatc
32
31
  import { distributionRoot } from '../distribution'
33
32
  import { readDistributionIdentity } from './installation'
34
33
  import { launchContext } from './dispatch-launch-contract'
34
+ import { observeYield, watchForYieldRequest } from './dispatch-yield-observer'
35
35
  import { DispatchUpgradeController } from './dispatch-upgrade-controller'
36
36
  import { resolveUpgradeTarget } from './dispatch-upgrade-target'
37
37
  import { prepareUpgrade } from './dispatch-upgrade-install'
@@ -159,6 +159,7 @@ import {
159
159
  type DashboardView,
160
160
  } from './dashboard/model'
161
161
  import { DashboardBuildPollCache } from './dashboard/poll'
162
+ import { repositoryQueueDepth } from './dashboard/header'
162
163
  import {
163
164
  dashboardContentWidth,
164
165
  detailScrollLimit,
@@ -958,8 +959,6 @@ class DispatchLoop {
958
959
  private configWarnings: readonly string[] = []
959
960
  /** Deprecation notices of an autobuild.toml change that is not adopted. */
960
961
  private candidateWarnings: readonly string[] = []
961
- /** Last intake-enabled tick's standing queue depth, for the dashboard header. */
962
- private queuedCount = 0
963
962
  /** Display-only triage count, sampled between ticks at most once per
964
963
  * `TRIAGE_COUNT_REFRESH_MS`. Present only for interactive dashboards and
965
964
  * frontend-status kernels; its value is undefined until a read succeeds. */
@@ -1511,6 +1510,8 @@ class DispatchLoop {
1511
1510
 
1512
1511
  private dispatcherTick(resumeCurrent: boolean): Promise<Awaited<ReturnType<Dispatcher['tick']>>> {
1513
1512
  return this.serialize(async () => {
1513
+ // The yield observer may have accepted while this tick was queued.
1514
+ if (this.retirement !== undefined) return emptyTickReport()
1514
1515
  // Refresh before every watch decision. The owner publishes atomically;
1515
1516
  // everything below captures the resulting one snapshot for this tick.
1516
1517
  await this.flushPendingTickFailure()
@@ -1576,7 +1577,6 @@ class DispatchLoop {
1576
1577
  invalidTickets: readyObservation?.invalidTickets ?? report.invalidTickets,
1577
1578
  ticketDiagnostics: readyObservation?.ticketDiagnostics ?? report.ticketDiagnostics,
1578
1579
  }
1579
- this.queuedCount = publishedReport.queued
1580
1580
  const triage = this.triageSampler?.value
1581
1581
  this.lastTickStatus = {
1582
1582
  queued: publishedReport.queued,
@@ -4308,7 +4308,7 @@ class DispatchLoop {
4308
4308
  buildSnapshot.builds,
4309
4309
  {
4310
4310
  repo: this.repoIdentity,
4311
- queued: this.queuedCount,
4311
+ queued: repositoryQueueDepth(repositoryEvents),
4312
4312
  activeCount: [...buildSnapshot.states.values()].filter(
4313
4313
  (state) => state.kind !== 'node' && state.status !== 'done' && state.status !== 'aborted',
4314
4314
  ).length,
@@ -4317,10 +4317,6 @@ class DispatchLoop {
4317
4317
  buildSnapshot.capacityBuilds ?? [],
4318
4318
  configSnapshot.config.capacity,
4319
4319
  this.wiring.clock(),
4320
- migrationIdentity(
4321
- repositoryEvents.ticketMigrations,
4322
- configSnapshot.config.tickets.source,
4323
- ),
4324
4320
  {
4325
4321
  urgentClaims: urgentClaimDemand(repositoryEvents),
4326
4322
  openPrs: {
@@ -4831,6 +4827,16 @@ class DispatchLoop {
4831
4827
  request.lineage !== launch.lineage ||
4832
4828
  !this.currentConfig().config.upgrade.automatic
4833
4829
  ) {
4830
+ // A prepared target still awaiting its request: observe for it between
4831
+ // ticks. Arming reuses the read above and never accepts by itself.
4832
+ if (
4833
+ state?.prepared &&
4834
+ state.prepared.payload.lineage === launch.lineage &&
4835
+ !state.failure &&
4836
+ !state.handoff &&
4837
+ !state.request
4838
+ )
4839
+ this.armYieldObservation(state.prepared.payload.correlation, launch.lineage)
4834
4840
  this.abandonUpgradeYield()
4835
4841
  return false
4836
4842
  }
@@ -4940,6 +4946,59 @@ class DispatchLoop {
4940
4946
  return this.adoptUpgradeYield(accepted)
4941
4947
  }
4942
4948
 
4949
+ private yieldObservation?: { correlation: string; stop: AbortController }
4950
+ /** A preparation observed to its step limit is left to ordinary ticks, so
4951
+ * re-arming from a tick cannot extend the observation indefinitely. */
4952
+ private exhaustedYieldObservation?: string
4953
+
4954
+ /** While this run has a prepared target outstanding, observe durable state
4955
+ * for its yield request between ticks at a bounded cadence, and attempt
4956
+ * acceptance through the same serialization as ticks. The observation only
4957
+ * decides when to call `acceptUpgradeYield()`, which re-reads and validates
4958
+ * durable state; ordinary tick cadence is unchanged. */
4959
+ private armYieldObservation(correlation: string, lineage: string): void {
4960
+ if (
4961
+ this.opts.once === true ||
4962
+ this.watchStopped ||
4963
+ this.superseded ||
4964
+ this.retirement !== undefined
4965
+ )
4966
+ return
4967
+ if (
4968
+ this.yieldObservation?.correlation === correlation ||
4969
+ this.exhaustedYieldObservation === correlation
4970
+ )
4971
+ return
4972
+ this.yieldObservation?.stop.abort()
4973
+ const stop = new AbortController()
4974
+ const observation = { correlation, stop }
4975
+ this.yieldObservation = observation
4976
+ // The sleep and the cancellation listen to the same stop sources, so an
4977
+ // interrupted sleep never becomes a back-to-back read.
4978
+ const signals = [stop.signal, this.opts.signal, this.inputStop.signal].filter(
4979
+ (signal): signal is AbortSignal => signal !== undefined,
4980
+ )
4981
+ void watchForYieldRequest({
4982
+ observe: () =>
4983
+ observeYield(this.wiring.store, this.repoIdentity, this.runId, correlation, lineage),
4984
+ accept: () =>
4985
+ this.serialize(async () => {
4986
+ if (this.retirement !== undefined || this.watchStopped || this.superseded) return
4987
+ await this.refreshConfig()
4988
+ await this.acceptUpgradeYield()
4989
+ }),
4990
+ sleep: (ms) => interruptibleSleep(ms, signals),
4991
+ signal: AbortSignal.any(signals),
4992
+ })
4993
+ .then((outcome) => {
4994
+ if (outcome === 'exhausted') this.exhaustedYieldObservation = correlation
4995
+ })
4996
+ .catch(() => {})
4997
+ .finally(() => {
4998
+ if (this.yieldObservation === observation) this.yieldObservation = undefined
4999
+ })
5000
+ }
5001
+
4943
5002
  /** Repository authority may transfer only from a current holder. A record
4944
5003
  * naming another run, or no record, means a peer replaced us. An expired
4945
5004
  * lease that still names us is resolved like any other lapse. */
@@ -5247,6 +5306,7 @@ class DispatchLoop {
5247
5306
  type: 'dispatcher.target-prepared',
5248
5307
  payload: handoff,
5249
5308
  })
5309
+ this.armYieldObservation(handoff.correlation, launch.lineage!)
5250
5310
  return true
5251
5311
  }),
5252
5312
  })
@@ -5385,6 +5445,7 @@ class DispatchLoop {
5385
5445
  }
5386
5446
  } finally {
5387
5447
  this.localHarvestShutdown.abort()
5448
+ this.yieldObservation?.stop.abort()
5388
5449
  await this.upgradeController?.stop()
5389
5450
  await this.stopHooks()
5390
5451
  if (this.retirement) {
@@ -55,21 +55,8 @@ export interface JudgeCliEnv {
55
55
  export type AmbientReadSession = CliEnv | HarvestCliEnv
56
56
 
57
57
  const PHASE_FORMAT = "'<phase>[@<round>]' (e.g. 'implement@2', 'verify:acceptance@1')"
58
- const BUILD_AMBIENT_TUPLE = 'AB_STORE/AB_BUILD/AB_PHASE/AB_SESSION'
59
- const HARVEST_AMBIENT_TUPLE = 'AB_STORE/AB_REPO/AB_HARVEST/AB_PHASE/AB_SESSION'
60
-
61
- /** Optional ambient identity is present but cannot safely select one scope. */
62
- export class InvalidAmbientContextError extends Error {
63
- override readonly name = 'InvalidAmbientContextError'
64
-
65
- constructor(detail: string) {
66
- super(
67
- `invalid ambient context: ${detail}. Expected no agent identity markers, ` +
68
- `a complete build tuple (${BUILD_AMBIENT_TUPLE}), or a complete Harvest tuple ` +
69
- `(${HARVEST_AMBIENT_TUPLE})`,
70
- )
71
- }
72
- }
58
+ export { InvalidAmbientContextError } from './ambient-errors'
59
+ import { InvalidAmbientContextError } from './ambient-errors'
73
60
 
74
61
  /** A required runner-provided session value is absent or empty. Callers that
75
62
  * resolve ambient auth directly still receive the variable-specific message;
@@ -707,10 +707,11 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
707
707
  'dashboard’s global-row r: it durably releases the queued-build hold, then',
708
708
  'turns ticket intake back on, then requests a resume on every cleanly paused',
709
709
  'build that does not already have one. A released queued build becomes',
710
- 'launchable on the next ordinary tick with no further action. Running, resuming,',
711
- 'blocked, and finished builds are skipped without error, and a build still',
712
- 'holding an open escalation is left to ab answer. Output names every build that',
713
- 'received a request, the hold, and the intake value written; --json emits that',
710
+ 'launchable on the next ordinary tick with no further action. Running builds,',
711
+ 'builds with a resume already pending, and blocked and finished builds are',
712
+ 'skipped without error, and a build still holding an open escalation is',
713
+ 'left to ab answer. Output names every build that received a request, the',
714
+ 'hold, and the intake value written; --json emits that',
714
715
  'summary as JSON. Re-running it changes nothing further. A phase session may not',
715
716
  'use --all. A failure exits nonzero and reports which of the two repository',
716
717
  'facts landed and which builds were requested.',
@@ -1000,7 +1000,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1000
1000
  }
1001
1001
 
1002
1002
  case 'builds': {
1003
- const { abBuilds } = await import('./status')
1003
+ const { abBuilds, statusColor } = await import('./status')
1004
1004
  const usage = 'usage: ab builds [--queued] [--all] [--json] [--store <ref>] (§8.2)'
1005
1005
  const parsed = parseArgs(
1006
1006
  rest,
@@ -1020,6 +1020,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1020
1020
  queued: parsed.flags.has('queued'),
1021
1021
  all: parsed.flags.has('all'),
1022
1022
  json: parsed.flags.has('json'),
1023
+ color: statusColor(deps.terminal, parsed.flags.has('json')),
1023
1024
  ...(storeRef !== undefined ? { storeRef } : {}),
1024
1025
  ...(deps.openStore !== undefined ? { openStore: deps.openStore } : {}),
1025
1026
  ...(deps.clock !== undefined ? { now: deps.clock } : {}),
@@ -1050,7 +1051,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1050
1051
  }
1051
1052
 
1052
1053
  case 'build': {
1053
- const { abBuildAssetGet, abBuildStatus } = await import('./status')
1054
+ const { abBuildAssetGet, abBuildStatus, statusColor } = await import('./status')
1054
1055
  const usage =
1055
1056
  'usage: ab build status <slug> [--events <n>] [--json] [--store <ref>] (§8.2)\n' +
1056
1057
  ' ab build asset get <slug> <kind> <name> <dest> [--rev <n>] [--json] [--store <ref>] (§8.8)'
@@ -1117,6 +1118,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1117
1118
  stdout,
1118
1119
  slug,
1119
1120
  json: parsed.flags.has('json'),
1121
+ color: statusColor(deps.terminal, parsed.flags.has('json')),
1120
1122
  ...(events !== undefined ? { events } : {}),
1121
1123
  ...(storeRef !== undefined ? { storeRef } : {}),
1122
1124
  ...(deps.openStore !== undefined ? { openStore: deps.openStore } : {}),
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The adapter-free half of production store composition. A local reference
3
+ * never evaluates the remote HTTP adapter or repository configuration: the
4
+ * remote client loads only when `openProductionStoreAsync` opens an http(s)
5
+ * reference, and repository-state resolution lives in `store-opening.ts` and
6
+ * `sessionless-store.ts`. `store-opening.ts` re-exposes all of this with its
7
+ * eager remote factory, so its exports and behavior are unchanged.
8
+ */
9
+ import { AccountRedactor, redactAccountStore } from '../store/account-redaction'
10
+ import type { BuildStore } from '../store/types'
11
+ import { InvalidAmbientContextError } from './ambient-errors'
12
+ import { projectToken } from './project-credentials'
13
+ import type { RepoStatePaths } from './repo-state'
14
+ import { isRemoteStoreRef, resolveStore, type ResolveStoreOpts } from './store-ref'
15
+
16
+ /** Shared injection seam used by every command that opens a BuildStore. */
17
+ export type StoreOpener = (ref: string, token?: string) => BuildStore
18
+
19
+ export function optionalToken(value: string | undefined): string | undefined {
20
+ // Bearer credentials are opaque. Only absence and the exact empty value mean
21
+ // "no token"; nonempty values are forwarded byte-for-byte.
22
+ return value !== undefined && value !== '' ? value : undefined
23
+ }
24
+
25
+ /** Production local/remote composition over a supplied remote factory. */
26
+ export function composeProductionStore(
27
+ ref: string,
28
+ token: string | undefined,
29
+ remoteFactory?: ResolveStoreOpts['remoteFactory'],
30
+ ): BuildStore {
31
+ const forwardedToken = optionalToken(token)
32
+ const store = resolveStore(ref, {
33
+ ...(remoteFactory ? { remoteFactory } : {}),
34
+ ...(forwardedToken !== undefined ? { token: forwardedToken } : {}),
35
+ })
36
+ const raw = process.env.AB_ACCOUNT_CREDENTIAL_ENVS
37
+ if (!raw) return store
38
+ const names: unknown = JSON.parse(raw)
39
+ if (!Array.isArray(names) || !names.every((name) => typeof name === 'string'))
40
+ throw new Error('Invalid account credential variable inventory')
41
+ return redactAccountStore(
42
+ store,
43
+ new AccountRedactor(() => names.map((name) => process.env[name])),
44
+ )
45
+ }
46
+
47
+ /** The production remote factory, loaded with the remote adapter. */
48
+ export async function loadRemoteFactory(): Promise<NonNullable<ResolveStoreOpts['remoteFactory']>> {
49
+ const { RemoteBuildStore } = await import('../store/remote/client')
50
+ return (url, remoteToken) => new RemoteBuildStore({ url, token: remoteToken })
51
+ }
52
+
53
+ /** The production opener for `ref`: the remote adapter loads only for an
54
+ * http(s) reference. */
55
+ export async function productionOpenerFor(ref: string): Promise<StoreOpener> {
56
+ const remoteFactory = isRemoteStoreRef(ref) ? await loadRemoteFactory() : undefined
57
+ return (selected, token) => composeProductionStore(selected, token, remoteFactory)
58
+ }
59
+
60
+ /** `openProductionStore` without loading the remote adapter for a local ref. */
61
+ export async function openProductionStoreAsync(ref: string, token?: string): Promise<BuildStore> {
62
+ return (await productionOpenerFor(ref))(ref, token)
63
+ }
64
+
65
+ export interface OpenStoreForRepoStateOpts {
66
+ env: Record<string, string | undefined>
67
+ openStore?: StoreOpener
68
+ useProjectCredential?: boolean
69
+ }
70
+
71
+ export interface OpenedStoreContext extends RepoStatePaths {
72
+ store: BuildStore
73
+ token?: string
74
+ /** The validated ambient phase/Harvest identity this invocation carries, if
75
+ * any — the same value that scoped `store`. Exposed for commands whose
76
+ * repository selection also depends on ambient own-build authority. */
77
+ ambient?: import('./env').AmbientReadSession
78
+ }
79
+
80
+ /** Open from an already canonicalized state selection with `opener`. */
81
+ export function openStoreForRepoStateWith(
82
+ state: RepoStatePaths,
83
+ opts: OpenStoreForRepoStateOpts,
84
+ opener: StoreOpener,
85
+ ): OpenedStoreContext {
86
+ // A judge session's only store authority is its one preference.
87
+ if (opts.env.AB_JUDGE !== undefined)
88
+ throw new InvalidAmbientContextError('a judge session has no read authority')
89
+ const token =
90
+ opts.useProjectCredential !== false && isRemoteStoreRef(state.storeRef)
91
+ ? projectToken(state.storeRef, state.repo, opts.env)
92
+ : optionalToken(opts.env.AB_TOKEN)
93
+ if (!token && isRemoteStoreRef(state.storeRef) && state.configStore === state.storeRef) {
94
+ throw new Error('No project credential for this service; run ab connect')
95
+ }
96
+ const store = opener(state.storeRef, token)
97
+ return {
98
+ ...state,
99
+ store,
100
+ ...(token !== undefined ? { token } : {}),
101
+ }
102
+ }
@@ -32,9 +32,8 @@ export { normalizeGitRemoteUrl } from '../kernel/origin'
32
32
 
33
33
  export const LOCAL_STATE_DIR = '.autobuild'
34
34
 
35
- export function isRemoteStoreRef(ref: string): boolean {
36
- return /^https?:\/\//i.test(ref)
37
- }
35
+ export { isRemoteStoreRef } from './store-ref'
36
+ import { isRemoteStoreRef } from './store-ref'
38
37
 
39
38
  export { resolveMainRepo } from './main-checkout'
40
39
  import { resolveMainRepo } from './main-checkout'
@@ -7,7 +7,6 @@ import {
7
7
  } from '../kernel/ticket-starts'
8
8
  import { normalizeEffectiveConfigArtifact } from '../config/effective-artifact'
9
9
  import { OPERATOR_PRESENCE_TTL_MS, type OperatorPresence } from '../store/operator-presence'
10
- import { migrationIdentity } from '../kernel/ticket-migrations'
11
10
  import {
12
11
  dispatchUpgradeReducer,
13
12
  upgradeRunRecency,
@@ -15,7 +14,7 @@ import {
15
14
  type UpgradeRun,
16
15
  } from '../kernel/dispatch-upgrade'
17
16
  import { formatRuntimeIdentity } from '../events/runtime'
18
- import { landingRestackDue } from '../kernel/engine'
17
+ import { capacityBuildFromFacts } from '../kernel/capacity-build'
19
18
  import {
20
19
  dispatchCapacity,
21
20
  startClaimDemand,
@@ -23,6 +22,7 @@ import {
23
22
  waitingExplanation,
24
23
  type DispatchCapacity,
25
24
  type CapacityBuild,
25
+ type SlotState,
26
26
  } from '../kernel/dispatch-capacity'
27
27
  import { backpressureStatusLine } from '../kernel/open-pr-backpressure'
28
28
  import {
@@ -42,7 +42,11 @@ import { readHookProgress } from '../processes/hooks'
42
42
  import type { BuildStore, RepositoryArtifact } from '../store/types'
43
43
  import type { LocalOverrideRecord } from '../config/local'
44
44
  import { readBuildFacts } from '../store/reduced-reads'
45
- import { forgeReadinessWarnings, reduceDispatchStatus } from '../kernel/dispatch-status'
45
+ import {
46
+ foldReportedDispatch,
47
+ forgeReadinessWarnings,
48
+ initialReportedDispatch,
49
+ } from '../kernel/dispatch-status'
46
50
  import { readRepositoryFacts, type RepositoryReadFacts } from '../store/reduced-reads'
47
51
  import {
48
52
  formatDispatcherIdentity,
@@ -360,11 +364,9 @@ export function projectRepositoryStatus(
360
364
  }
361
365
  publications.reverse()
362
366
  const active = reduceTicketSourceHealth(events)
363
- const latestRun = events.findLast((event) => event.type === 'dispatcher.run-started')
364
- const runStatus =
365
- latestRun?.type === 'dispatcher.run-started'
366
- ? reduceDispatchStatus(events, latestRun.payload.run)
367
- : undefined
367
+ const reported = initialReportedDispatch()
368
+ for (const event of events) foldReportedDispatch(reported, event)
369
+ const runStatus = reported.run ? reported.status : undefined
368
370
  const warningLines = runStatus
369
371
  ? [...runStatus.roleWarnings, ...forgeReadinessWarnings(runStatus)]
370
372
  : []
@@ -572,9 +574,10 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
572
574
  `repository: ${status.repo}`,
573
575
  ...(status.capacity
574
576
  ? [
575
- `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(', ')}` : ''}${status.capacity.waitingNodes?.length || status.capacity.waitingBuilds?.length || status.capacity.urgentClaims || status.capacity.startRequests ? `; ${waitingExplanation(status.capacity, { requests: true })}` : ''}`,
577
+ `capacity: ${status.capacity.occupied}/${status.capacity.configured}${status.capacity.waitingNodes?.length || status.capacity.waitingBuilds?.length || status.capacity.urgentClaims || status.capacity.startRequests ? `; ${waitingExplanation(status.capacity, { requests: true })}` : ''}`,
576
578
  ]
577
579
  : []),
580
+ ...(status.capacity?.slots ? [slotsStatusLine(status.capacity.slots)] : []),
578
581
  ...(status.capacity?.backpressure
579
582
  ? [backpressureStatusLine(status.capacity.backpressure)]
580
583
  : []),
@@ -721,6 +724,24 @@ export function localOverridesFromArtifact(
721
724
 
722
725
  /** Capacity is optional when no held dispatcher has a retrievable configuration
723
726
  * (`artifact` comes from `readHeldEffectiveConfig`). */
727
+ /** Every reported build's slot state, grouped held, requested and none,
728
+ * each group sorted by slug; `none` when no build is reported. Builds whose
729
+ * state is unknown are not listed. */
730
+ function slotsStatusLine(slots: Record<string, SlotState>): string {
731
+ const entries = Object.entries(slots).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
732
+ const label = (slug: string, slot: SlotState) =>
733
+ slot.state === 'requested'
734
+ ? `${slug} (${slot.request}${slot.priority === 'urgent' ? ', urgent' : ''})`
735
+ : slug
736
+ const clauses = (['held', 'requested', 'none'] as const).flatMap((state) => {
737
+ const members = entries.filter(([, slot]) => slot.state === state)
738
+ return members.length
739
+ ? [`${state} ${members.map(([slug, slot]) => label(slug, slot)).join(', ')}`]
740
+ : []
741
+ })
742
+ return `slots: ${clauses.length ? clauses.join('; ') : 'none'}`
743
+ }
744
+
724
745
  export async function readRepositoryCapacity(
725
746
  store: BuildStore,
726
747
  repo: string,
@@ -737,26 +758,13 @@ export async function readRepositoryCapacity(
737
758
  // settled build, so this read stays flat as history accumulates.
738
759
  for (const { record, digest } of await store.listOpenBuilds(repo)) {
739
760
  if (digest.terminal) continue
740
- const build = (await readBuildFacts(store, record.slug)).value
741
- builds.push({
742
- record,
743
- state: build.state,
744
- workspace: build.workspace !== null,
745
- provisioning: build.provisionMarker !== undefined,
746
- restackDue: landingRestackDue(build.state, build.log),
747
- })
761
+ builds.push(capacityBuildFromFacts(record, (await readBuildFacts(store, record.slug)).value))
748
762
  }
749
- return dispatchCapacity(
750
- builds,
751
- config.capacity,
752
- now,
753
- migrationIdentity(facts.ticketMigrations, config.tickets.source),
754
- {
755
- urgentClaims: urgentClaimDemand(facts),
756
- startRequests: startClaimDemand(facts),
757
- openPrs: { policy: config.policy, engaged: facts.openPrBackpressure !== undefined },
758
- },
759
- )
763
+ return dispatchCapacity(builds, config.capacity, now, {
764
+ urgentClaims: urgentClaimDemand(facts),
765
+ startRequests: startClaimDemand(facts),
766
+ openPrs: { policy: config.policy, engaged: facts.openPrBackpressure !== undefined },
767
+ })
760
768
  }
761
769
 
762
770
  /**
@@ -0,0 +1,26 @@
1
+ /**
2
+ * `openSessionlessStore` for callers that must not evaluate the remote adapter
3
+ * for a local reference. This is the only light-path module that resolves
4
+ * repository state (and with it configuration), so readers that already know
5
+ * their journal never load it.
6
+ */
7
+ import { resolveRepoState } from './repo-state'
8
+ import {
9
+ openStoreForRepoStateWith,
10
+ productionOpenerFor,
11
+ type OpenedStoreContext,
12
+ } from './production-store'
13
+ import type { SessionlessStoreOpts } from './store-opening'
14
+
15
+ export async function openSessionlessStoreLazily(
16
+ opts: SessionlessStoreOpts,
17
+ ): Promise<OpenedStoreContext> {
18
+ const state = await resolveRepoState({
19
+ targetRepo: opts.targetRepo,
20
+ exec: opts.exec,
21
+ ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
22
+ ...(opts.env.AB_STORE !== undefined ? { envStore: opts.env.AB_STORE } : {}),
23
+ })
24
+ const opener = opts.openStore ?? (await productionOpenerFor(state.storeRef))
25
+ return openStoreForRepoStateWith(state, opts, opener)
26
+ }