@defrex/autobuild 1.2.0 → 1.4.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 (164) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +416 -36
  3. package/docs/accounts.md +50 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +298 -17
  6. package/docs/build-store.md +18 -0
  7. package/docs/builds.md +7 -1
  8. package/docs/cli.md +1 -1
  9. package/docs/configuration-overview.md +6 -0
  10. package/docs/configuration.md +44 -19
  11. package/docs/dispatcher-hosting.md +42 -0
  12. package/docs/dispatcher.md +41 -0
  13. package/docs/forges.md +5 -0
  14. package/docs/integration-tree.md +24 -5
  15. package/docs/operating.md +11 -3
  16. package/docs/operator-api.md +81 -10
  17. package/docs/operator-surfaces.md +29 -0
  18. package/docs/plugin-authoring.md +51 -2
  19. package/docs/remote-store-protocol.md +321 -46
  20. package/docs/remote-ticket-protocol.md +12 -10
  21. package/docs/restacking.md +105 -3
  22. package/docs/setup.md +37 -8
  23. package/docs/skills.md +1 -1
  24. package/docs/spec-standard.md +41 -5
  25. package/docs/ticket-dependencies.md +8 -0
  26. package/docs/troubleshooting.md +9 -0
  27. package/docs/workspaces.md +1 -1
  28. package/package.json +4 -3
  29. package/packages/core/src/accounts/availability.ts +96 -0
  30. package/packages/core/src/accounts/local-owner.ts +49 -2
  31. package/packages/core/src/cli/attention.ts +2 -0
  32. package/packages/core/src/cli/binary.ts +17 -1
  33. package/packages/core/src/cli/context.ts +62 -0
  34. package/packages/core/src/cli/dashboard/model.ts +12 -3
  35. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  36. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  37. package/packages/core/src/cli/dashboard/render.ts +46 -5
  38. package/packages/core/src/cli/dispatch-args.ts +27 -3
  39. package/packages/core/src/cli/dispatch-frontend.ts +179 -52
  40. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  41. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +150 -33
  43. package/packages/core/src/cli/dispatch.ts +209 -36
  44. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  45. package/packages/core/src/cli/forge-clear.ts +30 -0
  46. package/packages/core/src/cli/harvest.ts +2 -1
  47. package/packages/core/src/cli/help.ts +17 -3
  48. package/packages/core/src/cli/historical-build-state.ts +6 -0
  49. package/packages/core/src/cli/main.ts +43 -2
  50. package/packages/core/src/cli/publication-settlement.ts +17 -0
  51. package/packages/core/src/cli/remote-poll.ts +11 -1
  52. package/packages/core/src/cli/repository-status.ts +11 -0
  53. package/packages/core/src/cli/status.ts +7 -1
  54. package/packages/core/src/cli/wait.ts +9 -2
  55. package/packages/core/src/cli/watch.ts +47 -16
  56. package/packages/core/src/config/roles.ts +16 -1
  57. package/packages/core/src/events/catalog.ts +8 -0
  58. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  59. package/packages/core/src/events/payloads.ts +95 -2
  60. package/packages/core/src/events/policy.ts +19 -0
  61. package/packages/core/src/events/repository.ts +108 -2
  62. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +464 -0
  63. package/packages/core/src/kernel/change-presence.ts +74 -8
  64. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  65. package/packages/core/src/kernel/engine.ts +27 -12
  66. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  67. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  68. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  69. package/packages/core/src/kernel/log-index.ts +1 -1
  70. package/packages/core/src/kernel/node-landing.ts +27 -10
  71. package/packages/core/src/kernel/node-polling.ts +40 -7
  72. package/packages/core/src/kernel/node-restack-demand.ts +75 -0
  73. package/packages/core/src/kernel/node-restack-state.ts +20 -1
  74. package/packages/core/src/kernel/node-restack-transaction.ts +47 -1
  75. package/packages/core/src/kernel/read-facts.ts +120 -9
  76. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  77. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  78. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  79. package/packages/core/src/kernel/reducer.ts +20 -2
  80. package/packages/core/src/kernel/replay-retention.ts +176 -0
  81. package/packages/core/src/kernel/target-lineage.ts +65 -0
  82. package/packages/core/src/kernel/target-observation.ts +117 -0
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +2 -0
  87. package/packages/core/src/operator/registry.ts +25 -13
  88. package/packages/core/src/operator/tickets.ts +8 -2
  89. package/packages/core/src/plugin-sdk/index.ts +1 -0
  90. package/packages/core/src/ports/forge/fake.ts +22 -0
  91. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  92. package/packages/core/src/ports/forge/github.ts +42 -10
  93. package/packages/core/src/ports/forge/local-git.ts +16 -1
  94. package/packages/core/src/ports/runner/account-env.ts +60 -9
  95. package/packages/core/src/ports/runner/claude.ts +49 -45
  96. package/packages/core/src/ports/types.ts +58 -4
  97. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  98. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  99. package/packages/core/src/ports/workspace/create.ts +2 -0
  100. package/packages/core/src/ports/workspace/fake.ts +4 -0
  101. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  102. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  103. package/packages/core/src/processes/build-runner.ts +240 -111
  104. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  105. package/packages/core/src/processes/dispatcher.ts +732 -201
  106. package/packages/core/src/processes/execution-no-progress.ts +8 -0
  107. package/packages/core/src/processes/harvest-runner.ts +6 -7
  108. package/packages/core/src/processes/harvest.ts +11 -16
  109. package/packages/core/src/processes/publication-state.ts +2 -1
  110. package/packages/core/src/processes/repo-view.ts +25 -0
  111. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  112. package/packages/core/src/scenarios/harness.ts +7 -0
  113. package/packages/core/src/store/adapter.ts +9 -0
  114. package/packages/core/src/store/artifact-meta.ts +7 -0
  115. package/packages/core/src/store/build-scope.ts +28 -0
  116. package/packages/core/src/store/contract.ts +182 -0
  117. package/packages/core/src/store/event-reads.ts +156 -0
  118. package/packages/core/src/store/local/schema.ts +11 -0
  119. package/packages/core/src/store/local/store.ts +117 -2
  120. package/packages/core/src/store/memory.ts +241 -0
  121. package/packages/core/src/store/phase-session.ts +47 -0
  122. package/packages/core/src/store/reduced-reads.ts +8 -0
  123. package/packages/core/src/store/reducer-value-shapes.json +10546 -8877
  124. package/packages/core/src/store/reducer-value-validation.ts +109 -6
  125. package/packages/core/src/store/reducer-values.ts +62 -2
  126. package/packages/core/src/store/remote/client.ts +208 -23
  127. package/packages/core/src/store/remote/compatibility.ts +195 -25
  128. package/packages/core/src/store/remote/errors.ts +16 -0
  129. package/packages/core/src/store/remote/index.ts +17 -0
  130. package/packages/core/src/store/remote/protocol.ts +30 -1
  131. package/packages/core/src/store/remote/released-clients.json +37 -0
  132. package/packages/core/src/store/remote/released-clients.ts +88 -0
  133. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  135. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  136. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  137. package/packages/core/src/store/remote/version.ts +8 -1
  138. package/packages/core/src/store/repo-state-events.ts +6 -3
  139. package/packages/core/src/store/scan-cadence.ts +15 -0
  140. package/packages/core/src/store/session-handle.ts +18 -0
  141. package/packages/core/src/store/snapshots.ts +16 -3
  142. package/packages/core/src/store/types.ts +29 -6
  143. package/packages/core/src/testing/dispatch-read-budget.ts +457 -7
  144. package/packages/core/src/testing/index.ts +6 -1
  145. package/packages/core/src/testing/reduced-read-budget.ts +1240 -9
  146. package/skills/guide/SKILL.md +220 -22
  147. package/skills/guide/references/accounts.md +50 -1
  148. package/skills/guide/references/integration-tree.md +24 -5
  149. package/skills/guide/references/operator-api.md +81 -10
  150. package/skills/guide/references/plugin-authoring.md +51 -2
  151. package/skills/guide/references/remote-store-protocol.md +321 -46
  152. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  153. package/skills/guide/references/restacking.md +105 -3
  154. package/skills/guide/references/setup.md +37 -8
  155. package/skills/guide/references/spec-standard.md +41 -5
  156. package/skills/guide/references/ticket-dependencies.md +8 -0
  157. package/skills/implement/SKILL.md +12 -3
  158. package/skills/operate/SKILL.md +85 -12
  159. package/skills/plan/SKILL.md +27 -4
  160. package/skills/plan-review/SKILL.md +22 -2
  161. package/skills/reconcile/SKILL.md +16 -1
  162. package/skills/spec/SKILL.md +7 -4
  163. package/skills/tickets/SKILL.md +7 -3
  164. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,11 @@
1
+ import { selectDispatchMode } from './dispatch-mode'
2
+ import { createTerminalModeController } from './terminal-restore'
3
+ import { inspectLocalAccountEnvironment } from '../accounts/local-owner'
4
+ import {
5
+ applyProjectAccountSnapshot,
6
+ missingAccountCredentials,
7
+ MissingAccountCredentialsError,
8
+ } from '../accounts/availability'
1
9
  import { LocalCredentials } from '../accounts/local-credentials'
2
10
  import { LocalAccountOwner, renewLocalAccounts } from '../accounts/local-owner'
3
11
  import { accountRedactor, redactAccountStore } from '../store/account-redaction'
@@ -92,7 +100,12 @@ import {
92
100
  type PipelineSourceFailure,
93
101
  type PipelineSourceMeta,
94
102
  } from '../config/pipeline-source'
95
- import { effectiveRuntimeReferences, roleKeyWarnings, SLUG_ROLE } from '../config/roles'
103
+ import {
104
+ effectiveRuntimeReferences,
105
+ selectedExecutionAccounts,
106
+ roleKeyWarnings,
107
+ SLUG_ROLE,
108
+ } from '../config/roles'
96
109
  import type { Config } from '../config/schema'
97
110
  import { loadPlugins, pluginResolutionKind } from '../plugins/load'
98
111
  import type { PluginRegistry } from '../plugins/registry'
@@ -171,7 +184,7 @@ import {
171
184
  } from '../processes/build-execution-state'
172
185
  import { HarvestRunner, type HarvestRunnerResult } from '../processes/harvest-runner'
173
186
  import {
174
- sampleUnclaimedObservationCount,
187
+ unclaimedObservationCount,
175
188
  evaluateHarvestPressureFromStore,
176
189
  evaluateHarvestPressureFromDigests,
177
190
  } from '../processes/harvest'
@@ -300,7 +313,8 @@ interface ResumePrompt {
300
313
  /** The real adapters the loop drives — resolved by `wire` (default: the
301
314
  * production ports; tests inject fakes). */
302
315
  export interface DispatchWiring {
303
- renewAccounts?: (authority: { repo: string; run: string }) => Promise<void>
316
+ inspectAccounts?: () => Record<string, string | undefined>
317
+ renewAccounts?: (authority?: { repo: string; run: string }) => Promise<void>
304
318
  releaseAccounts?: () => Promise<void>
305
319
 
306
320
  credentialIssuer?: typeof delegateCredential
@@ -360,6 +374,9 @@ const DEFAULT_TIMERS: TimerScheduler = {
360
374
  }
361
375
 
362
376
  export interface DispatchOpts {
377
+ takeover?: boolean
378
+ viewer?: boolean
379
+ dispatchedBy?: string
363
380
  /** Repo the dispatcher serves (§12: one dispatcher per repo) — the cwd, or
364
381
  * in origin mode a private scratch root. Filesystem consumers only.
365
382
  * Callers without a checkout may pass a non-filesystem identity token
@@ -552,16 +569,22 @@ async function defaultWire(
552
569
  if (opts.env.AB_PROJECT_SECRETS_FAILED === '1')
553
570
  for (const name of JSON.parse(opts.env.AB_PROJECT_SECRETS_UNAVAILABLE ?? '[]') as string[])
554
571
  delete opts.env[name]
555
- let accounts = config.accounts
572
+ let allAccounts = config.accounts
573
+ let accounts = selectedExecutionAccounts(config)
574
+ // Origin execution accepts only the project snapshot, including an empty one.
575
+ if (originMode) {
576
+ const snapshot = JSON.parse(opts.env.AB_PROJECT_ACCOUNT_ENV ?? '{}') as Record<string, string>
577
+ applyProjectAccountSnapshot(allAccounts, opts.env, snapshot)
578
+ }
556
579
  const credentials = new LocalCredentials(join(state.checkout, '.autobuild'))
557
580
  const owner = new LocalAccountOwner(credentials)
558
581
  const claimed = new Set<string>()
559
582
  let renewal: Promise<void> | undefined
560
583
  let accountTimer: ReturnType<typeof setInterval> | undefined
561
- const renewAccounts = async (authority: { repo: string; run: string }) => {
584
+ const renewAccounts = async (authority?: { repo: string; run: string }) => {
562
585
  if (opts.repository || !Object.values(accounts).some((a) => a.kind === 'chatgpt-subscription'))
563
586
  return
564
- if (!accountTimer) {
587
+ if (authority && !accountTimer) {
565
588
  accountTimer = setInterval(() => {
566
589
  void (async () => {
567
590
  const held = await opened.store.getRepo(authority.repo)
@@ -592,9 +615,9 @@ async function defaultWire(
592
615
  }
593
616
  opened.store = redactAccountStore(
594
617
  opened.store,
595
- accountRedactor(() => accounts, opts.env),
618
+ accountRedactor(() => allAccounts, opts.env),
596
619
  )
597
- let runtimeReferences = effectiveRuntimeReferences(config)
620
+ let runtimeReferences = effectiveRuntimeReferences(config, { includeUnusedAccounts: false })
598
621
  // A local override relocates the whole tree. Remote stores still need local
599
622
  // scratch beneath the repository default. Plugin factories receive only
600
623
  // their explicit config plus repository/environment context.
@@ -607,7 +630,8 @@ async function defaultWire(
607
630
  env: opts.env,
608
631
  storeRef: opened.storeRef,
609
632
  runtimeReferences: () => runtimeReferences,
610
- accounts: () => accounts,
633
+ accounts: () => allAccounts,
634
+ executionAccounts: () => accounts,
611
635
  sandboxSetupCommand: config.commands.setup,
612
636
  sandboxRoot: resolve(join(opened.localStateRoot, 'orchestrator-sandboxes')),
613
637
  sandboxEnvironmentVariables: config.orchestrator.sandbox.environmentVariables,
@@ -631,6 +655,8 @@ async function defaultWire(
631
655
  return {
632
656
  store: opened.store,
633
657
  renewAccounts,
658
+ inspectAccounts: () =>
659
+ inspectLocalAccountEnvironment(credentials, accounts, opts.env, undefined, true),
634
660
  releaseAccounts,
635
661
  tickets,
636
662
  forge,
@@ -647,8 +673,18 @@ async function defaultWire(
647
673
  clock: systemClock,
648
674
  plugins,
649
675
  updateRuntimeReferences: (effectiveConfig) => {
650
- accounts = effectiveConfig.accounts
651
- runtimeReferences = effectiveRuntimeReferences(effectiveConfig)
676
+ allAccounts = effectiveConfig.accounts
677
+ accounts = selectedExecutionAccounts(effectiveConfig)
678
+ if (originMode) {
679
+ const snapshot = JSON.parse(opts.env.AB_PROJECT_ACCOUNT_ENV ?? '{}') as Record<
680
+ string,
681
+ string
682
+ >
683
+ applyProjectAccountSnapshot(allAccounts, opts.env, snapshot)
684
+ }
685
+ runtimeReferences = effectiveRuntimeReferences(effectiveConfig, {
686
+ includeUnusedAccounts: false,
687
+ })
652
688
  },
653
689
  }
654
690
  }
@@ -901,6 +937,8 @@ class DispatchLoop {
901
937
  forge: wiring.forge,
902
938
  config,
903
939
  getConfig: () => this.liveConfig.current().config,
940
+ missingAccounts: () => this.missingAccounts(),
941
+ accountCredentialSource: opts.repository ? 'project-secrets' : 'environment',
904
942
  repairBuildConfig: (slug) => this.publishBuildConfig(slug),
905
943
  repo: this.repoIdentity,
906
944
  // Origin mode: the forge answers remote base-branch questions; no
@@ -926,6 +964,15 @@ class DispatchLoop {
926
964
  })
927
965
  }
928
966
 
967
+ private missingAccounts(env = this.opts.env) {
968
+ return missingAccountCredentials(
969
+ selectedExecutionAccounts(this.currentConfig().config),
970
+ env,
971
+ this.opts.repository ? 'project-secrets' : 'environment',
972
+ this.currentConfig().config.workspace.provider,
973
+ )
974
+ }
975
+
929
976
  private currentConfig(): ConfigSnapshot {
930
977
  return this.liveConfig.current()
931
978
  }
@@ -1212,6 +1259,7 @@ class DispatchLoop {
1212
1259
  return this.serialize(async () => {
1213
1260
  // Refresh before every watch decision. The owner publishes atomically;
1214
1261
  // everything below captures the resulting one snapshot for this tick.
1262
+ await this.flushPendingTickFailure()
1215
1263
  await this.refreshConfig()
1216
1264
  if (await this.acceptUpgradeYield()) return emptyTickReport()
1217
1265
  // Every tick verifies local lease currency, reclaiming when necessary. Without it,
@@ -1232,31 +1280,25 @@ class DispatchLoop {
1232
1280
  }
1233
1281
  this.tickStartedAt = startedAt
1234
1282
 
1235
- // Unclaimed observations are display-only and sampled once per interactive
1236
- // dispatcher tick from the journal and one repo-scoped digest read
1237
- // (AUT-487) — flat in the finished-build count. A journal record that
1238
- // does not yet exist reads as an empty journal (AUT-524); the sample
1239
- // writes nothing. Any other failed sample must neither fail dispatch nor
1240
- // replace the last complete measurement with a fabricated zero.
1283
+ // Refresh inside the serialized tick so claims and the display both see
1284
+ // the latest repository facts. Shared refresh failures still fail the tick.
1285
+ await this.repoView.refresh()
1286
+ const digests = await this.repoView.getRepoBuildDigests(this.repoIdentity)
1241
1287
  if (this.dashboard) {
1242
1288
  try {
1243
- this.observationCount = await sampleUnclaimedObservationCount(
1244
- this.wiring.store,
1245
- this.repoIdentity,
1246
- )
1289
+ // Display-only sampling reuses the refreshed inputs without backing
1290
+ // reads. Publish only a complete measurement; retain it on failure.
1291
+ const count = unclaimedObservationCount({
1292
+ digests,
1293
+ harvestEvents: this.repoView.repositoryFacts().harvest,
1294
+ })
1295
+ this.observationCount = count
1247
1296
  } catch {
1248
- // Display-only sampling failures retain the last factual count and
1249
- // retry on the next tick; they are not dashboard failures.
1297
+ // Retry on the next tick without fabricating a zero.
1250
1298
  }
1251
1299
  }
1252
-
1253
- // Sample inside the serialized tick, not at process startup. Every
1254
- // dispatcher therefore gates claims from the latest repository facts.
1255
- await this.repoView.refresh()
1256
1300
  const executionSlugs = new Set(
1257
- [...(await this.repoView.getRepoBuildDigests(this.repoIdentity))]
1258
- .filter(([, digest]) => digest.executionOpen)
1259
- .map(([slug]) => slug),
1301
+ [...digests].filter(([, digest]) => digest.executionOpen).map(([slug]) => slug),
1260
1302
  )
1261
1303
  await authorizeRemoteHandoffs(
1262
1304
  this.wiring.store,
@@ -2334,7 +2376,7 @@ class DispatchLoop {
2334
2376
  private launchHarvest(): void {
2335
2377
  // Do not even start a second local contender while one is active. A second
2336
2378
  // dispatch process is independently excluded by the repository lease.
2337
- if (this.stopped || this.harvestInFlight !== undefined) return
2379
+ if (this.stopped || this.harvestInFlight !== undefined || this.missingAccounts().length) return
2338
2380
 
2339
2381
  let tracked: Promise<void>
2340
2382
  tracked = this.launchHarvestIfNeeded()
@@ -2814,6 +2856,10 @@ class DispatchLoop {
2814
2856
  // Left open: durable settlement re-proves and reaps it later.
2815
2857
  }
2816
2858
  }
2859
+ if (error instanceof MissingAccountCredentialsError) {
2860
+ await this.dispatcher.holdForMissingAccounts(error)
2861
+ return
2862
+ }
2817
2863
  this.pendingHarvest.harvestFailed += 1
2818
2864
  await this.appendStatus({
2819
2865
  actor: DISPATCHER,
@@ -3077,6 +3123,50 @@ class DispatchLoop {
3077
3123
  }
3078
3124
  }
3079
3125
 
3126
+ private pendingTickFailure:
3127
+ | { original: string; first: string; last: string; count: number }
3128
+ | undefined
3129
+
3130
+ /** Reporting is diagnostic: its failure must never replace the operational error. */
3131
+ private async reportTickFailure(error: unknown): Promise<void> {
3132
+ const original = formatDispatcherError(error)
3133
+ this.warn(`tick failed: ${original}`)
3134
+ try {
3135
+ await this.publishTickFailure(error)
3136
+ } catch (publicationError) {
3137
+ const now = this.wiring.clock().toISOString()
3138
+ if (this.pendingTickFailure) {
3139
+ this.pendingTickFailure.last = now
3140
+ this.pendingTickFailure.count++
3141
+ } else {
3142
+ this.pendingTickFailure = { original, first: now, last: now, count: 1 }
3143
+ }
3144
+ // Never reuse an old boundary to close a later tick (or a peer's tick).
3145
+ this.tickStartedAt = undefined
3146
+ this.warn(`tick failure unreported: ${formatDispatcherError(publicationError)}`)
3147
+ }
3148
+ }
3149
+
3150
+ private async flushPendingTickFailure(): Promise<void> {
3151
+ const pending = this.pendingTickFailure
3152
+ if (!pending) return
3153
+ try {
3154
+ await this.wiring.store.appendRepo(this.repoIdentity, {
3155
+ actor: DISPATCHER,
3156
+ type: 'dispatcher.tick-failed',
3157
+ payload: {
3158
+ run: this.runId,
3159
+ error:
3160
+ `Unreported tick failure window ${pending.first} through ${pending.last} ` +
3161
+ `(${pending.count} failures); original tick error: ${pending.original}`,
3162
+ },
3163
+ })
3164
+ this.pendingTickFailure = undefined
3165
+ } catch (error) {
3166
+ this.warn(`tick failure window still unreported: ${formatDispatcherError(error)}`)
3167
+ }
3168
+ }
3169
+
3080
3170
  private async publishTickFailure(error: unknown): Promise<void> {
3081
3171
  const failed = {
3082
3172
  actor: DISPATCHER,
@@ -3183,6 +3273,7 @@ class DispatchLoop {
3183
3273
  cleanupPending: boolean
3184
3274
  identity?: BuildExecutionHandle['identity']
3185
3275
  }): Promise<void> {
3276
+ if (await this.dispatcher.holdForMissingAccounts(input.error)) return
3186
3277
  // The failed executor may have appended through its own handle.
3187
3278
  await this.repoView.refreshBuild(input.slug)
3188
3279
  await appendInfrastructureFailure(
@@ -3210,6 +3301,7 @@ class DispatchLoop {
3210
3301
  * kernel decisions; the kernel reserves the durable execution lease before
3211
3302
  * launch and retains it until the executor has reaped its complete tree. */
3212
3303
  private async launchRunner(slug: string): Promise<LaunchRunnerResult> {
3304
+ if (this.missingAccounts().length) return 'already-active'
3213
3305
  if (!this.acceptingBuildLaunches || this.activeBuildRuns.has(slug)) return 'already-active'
3214
3306
 
3215
3307
  const reservation = Symbol(slug)
@@ -3384,6 +3476,12 @@ class DispatchLoop {
3384
3476
  this.inFlightKinds.set(tracked, handle.supervision)
3385
3477
  return 'scheduled'
3386
3478
  } catch (error) {
3479
+ if (error instanceof MissingAccountCredentialsError) {
3480
+ await this.dispatcher.holdForMissingAccounts(error)
3481
+ if (leaseClaimed) await this.repoView.releaseLease(slug, instance)
3482
+ this.activeBuildRuns.delete(slug)
3483
+ return 'already-active'
3484
+ }
3387
3485
  if (this.activeBuildRuns.get(slug)?.reservation === reservation) {
3388
3486
  this.activeBuildRuns.delete(slug)
3389
3487
  }
@@ -4606,6 +4704,10 @@ class DispatchLoop {
4606
4704
  async run(): Promise<void> {
4607
4705
  // Before the `--once` branch, so both modes report it exactly once.
4608
4706
  this.reportRoleDiagnostics()
4707
+ if (!this.opts.repository) {
4708
+ const missing = this.missingAccounts(this.wiring.inspectAccounts?.() ?? this.opts.env)
4709
+ if (missing.length) throw new MissingAccountCredentialsError(missing)
4710
+ }
4609
4711
  // Repository supervisor lease (§12): two invocations for one repository
4610
4712
  // never both act. A losing invocation records the yield and performs no
4611
4713
  // claims, launches, or publications. The holder is the invocation's
@@ -4645,7 +4747,7 @@ class DispatchLoop {
4645
4747
  // invocation.
4646
4748
  if (this.pastDeadline()) return
4647
4749
  const initial = await this.dispatcherTick(true).catch(async (error: unknown) => {
4648
- await this.publishTickFailure(error)
4750
+ await this.reportTickFailure(error)
4649
4751
  throw error
4650
4752
  })
4651
4753
  const initialPrinted = this.printReport(initial, false)
@@ -4688,18 +4790,18 @@ class DispatchLoop {
4688
4790
  this.startUpgradeChecks()
4689
4791
  let startup = true
4690
4792
  while (!this.watchStopped && !this.superseded) {
4793
+ let failed = false
4691
4794
  try {
4692
4795
  const report = await this.dispatcherTick(startup)
4693
4796
  this.printReport(report, this.harvestInFlight === undefined)
4694
4797
  startup = false
4695
4798
  } catch (error) {
4696
4799
  if (this.forgePublicationFailed) throw error
4697
- const message = formatDispatcherError(error)
4698
- await this.publishTickFailure(error)
4699
- this.warn(`tick failed: ${message}`)
4800
+ failed = true
4801
+ await this.reportTickFailure(error)
4700
4802
  }
4701
4803
  if (this.watchStopped || this.superseded) break
4702
- await sleep(intervalMs)
4804
+ await sleep(failed || this.pendingTickFailure ? Math.max(intervalMs, 1000) : intervalMs)
4703
4805
  }
4704
4806
  if (this.superseded) {
4705
4807
  this.warn('dispatcher superseded by another invocation — detaching')
@@ -4856,6 +4958,77 @@ async function resolveOriginModeState(
4856
4958
  * path — is the served repository.
4857
4959
  */
4858
4960
  export async function abDispatch(opts: DispatchOpts): Promise<void> {
4961
+ if (opts.kernelRunId === undefined && !launchContext(opts.env)) {
4962
+ opts = { ...opts, ...(await selectDispatchMode(opts)) }
4963
+ }
4964
+ if (opts.viewer) {
4965
+ if (opts.repository !== undefined)
4966
+ throw new Error('--viewer requires a local checkout; omit --repository')
4967
+ if (opts.intake !== undefined) throw new Error('--viewer cannot set startup intake')
4968
+ if (opts.dispatchedBy !== undefined && !opts.dispatchedBy.trim())
4969
+ throw new Error('--dispatched-by requires a nonblank label')
4970
+ const state = await resolveRepoState({
4971
+ targetRepo: opts.targetRepo,
4972
+ exec: opts.exec,
4973
+ ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
4974
+ ...(opts.env.AB_STORE !== undefined ? { envStore: opts.env.AB_STORE } : {}),
4975
+ })
4976
+ const env = {
4977
+ ...opts.env,
4978
+ AB_STORE: state.storeRef,
4979
+ ...(isRemoteStoreRef(state.storeRef)
4980
+ ? { AB_TOKEN: projectToken(state.storeRef, state.repo, opts.env) }
4981
+ : {}),
4982
+ }
4983
+ const opened = openStoreForRepoState(state, { env })
4984
+ try {
4985
+ const interactive =
4986
+ opts.plain !== true && opts.terminal?.interactive === true && opts.input !== undefined
4987
+ await new DispatchFrontend({
4988
+ viewer: { ...(opts.dispatchedBy !== undefined ? { dispatchedBy: opts.dispatchedBy } : {}) },
4989
+ repo: opts.repo ?? state.repo,
4990
+ checkout: state.checkout,
4991
+ store: opened.store,
4992
+ storeRef: opened.storeRef,
4993
+ env,
4994
+ terminal: opts.terminal ?? {
4995
+ columns: 100,
4996
+ rows: 24,
4997
+ interactive: false,
4998
+ write: () => {},
4999
+ modes: createTerminalModeController(
5000
+ () => {},
5001
+ () => {},
5002
+ ),
5003
+ },
5004
+ input: opts.input ?? { start: () => () => {} },
5005
+ ...(!interactive ? { plainOutput: opts.stdout } : {}),
5006
+ ticketSource: async () =>
5007
+ (
5008
+ await openTicketSource(
5009
+ {
5010
+ targetRepo: state.checkout,
5011
+ exec: opts.exec,
5012
+ env,
5013
+ storeRef: opened.storeRef,
5014
+ stdout: opts.stdout,
5015
+ },
5016
+ 'ab merge',
5017
+ )
5018
+ ).source,
5019
+ once: opts.once === true,
5020
+ ...(opts.intervalMs !== undefined ? { intervalMs: opts.intervalMs } : {}),
5021
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
5022
+ ...(opts.resolveDashboardRenderer !== undefined
5023
+ ? { resolveDashboardRenderer: opts.resolveDashboardRenderer }
5024
+ : {}),
5025
+ }).run()
5026
+ } finally {
5027
+ await opened.store.close()
5028
+ }
5029
+ return
5030
+ }
5031
+ if (opts.dispatchedBy !== undefined) throw new Error('--dispatched-by requires --viewer')
4859
5032
  if (opts.wire !== undefined && opts.nonStoreWire !== undefined) {
4860
5033
  throw new Error('dispatch wire and nonStoreWire are mutually exclusive')
4861
5034
  }
@@ -42,6 +42,7 @@ export class StandbyIdentityResolver {
42
42
  private readonly store: BuildStore,
43
43
  private readonly repo: string,
44
44
  private readonly history?: {
45
+ selectHolder?: (holder: string | undefined) => void
45
46
  allowLookup: () => boolean
46
47
  remember: (events: RepositoryEvent[], complete: boolean) => void
47
48
  },
@@ -64,7 +65,7 @@ export class StandbyIdentityResolver {
64
65
  const facts = (await readDispatcherRunFacts(this.store, this.repo, holder)).value
65
66
  this.ingest(facts.start ? [facts.start] : [])
66
67
  const complete = false // This lookup correlates one holder, not the complete journal.
67
- this.history?.remember([...this.starts.values()], complete)
68
+ this.history?.remember(facts.start ? [facts.start] : [], complete)
68
69
  } catch {
69
70
  // Identity is best effort; the sampled holder id remains sufficient.
70
71
  }
@@ -90,8 +91,12 @@ export class StandbyIdentityResolver {
90
91
  return yieldedHolder
91
92
  }
92
93
  this.failed = false
94
+ const previousHolder = this.record?.lease?.holder
93
95
  this.record = record
94
96
  const holder = record?.lease?.holder
97
+ this.history?.selectHolder?.(holder)
98
+ const start = holder === undefined ? undefined : this.starts.get(holder)
99
+ if (start && previousHolder !== holder) this.history?.remember([start], false)
95
100
  if (holder !== undefined && holder !== run) await this.correlate(holder)
96
101
  return this.current(run, yieldedHolder, now)
97
102
  }
@@ -0,0 +1,30 @@
1
+ import { clearForgeDegradation } from '../operator/control'
2
+ import { buildControlUser } from './build-control'
3
+ import { withSessionlessStore, type SessionlessStoreOpts } from './store-opening'
4
+
5
+ export async function abForgeClear(
6
+ opts: SessionlessStoreOpts & {
7
+ forge: string
8
+ reason: string
9
+ json?: boolean
10
+ stdout: (line: string) => void
11
+ },
12
+ ): Promise<void> {
13
+ if (['AB_BUILD', 'AB_SESSION', 'AB_HARVEST'].some((name) => opts.env[name]?.trim()))
14
+ throw new Error(
15
+ 'repository forge-clear requires an operator outside a build or harvest session',
16
+ )
17
+ if (!opts.forge.trim() || !opts.reason.trim()) throw new Error('forge and reason are required')
18
+ await withSessionlessStore(opts, async ({ store, repo }) => {
19
+ const result = await clearForgeDegradation({
20
+ store,
21
+ repo,
22
+ user: buildControlUser(opts.env),
23
+ forge: opts.forge,
24
+ reason: opts.reason,
25
+ })
26
+ opts.stdout(
27
+ opts.json ? JSON.stringify(result) : `Cleared forge ${opts.forge} degradation for ${repo}`,
28
+ )
29
+ })
30
+ }
@@ -1,3 +1,4 @@
1
+ import { readHarvestTail } from '../store/event-reads'
1
2
  import { readRepositoryFacts, type RepositoryReadFacts } from '../store/reduced-reads'
2
3
  /** Typed agent/operator surface for repository-scoped harvest workflows. Agent
3
4
  * stdout is never interpreted: proposal sets and review verdicts land through
@@ -863,7 +864,7 @@ export async function abHarvestStatus(opts: HarvestStatusOpts): Promise<void> {
863
864
  view.events =
864
865
  record === null
865
866
  ? []
866
- : (await store.getRepoEvents(repo)).filter(isHarvestEvent).slice(-opts.events)
867
+ : (await readHarvestTail(store, repo, opts.events)).filter(isHarvestEvent)
867
868
  if (opts.json === true) opts.stdout(JSON.stringify(view, null, 2))
868
869
  else for (const line of renderHarvestStatus(view)) opts.stdout(line)
869
870
  },
@@ -144,19 +144,32 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
144
144
  detail: page([
145
145
  'Usage:',
146
146
  ' ab dispatch [--once] [--interval <s>] [--store <ref>] [--plain] [--intake | --no-intake]',
147
+ ' ab dispatch --viewer [--dispatched-by <label>] [--once] [--interval <s>] [--store <ref>] [--plain]',
147
148
  '',
148
149
  'Run the outer loop for this repository: resume current builds, run the',
149
150
  'janitor and lease sweep, and dispatch ready work (§3.3, §12). This command',
150
151
  'runs outside sessions.',
151
152
  '',
152
153
  'Options:',
153
- ' --once Run one pass instead of watching continuously.',
154
+ ' Hosted placement defaults to viewer before any local dispatcher starts.',
155
+ ' --takeover Dispatch locally; warns it can displace hosted dispatch.',
156
+ ' --viewer Watch shared state without dispatching or taking a lease.',
157
+ ' Unreadable placement fails closed: use --viewer or --takeover explicitly.',
158
+ ' Unknown capability/local placement preserves local dispatch; origin/cron bypass.',
159
+ ' --viewer and --takeover cannot be combined.',
160
+ ' --dispatched-by <label> Describe where dispatching runs (requires --viewer).',
161
+ ' --once Run one pass, or read one viewer snapshot, then exit.',
154
162
  ' --interval <s> Set the positive polling interval in seconds.',
155
163
  ' --store <ref> Override the BuildStore path or URL.',
156
164
  ' --plain Force line-oriented output.',
157
165
  ' --intake Durably turn new ticket intake on.',
158
166
  ' --no-intake Durably turn new ticket intake off.',
159
167
  'With omission, intake reuses stored state (fresh repository: on).',
168
+ 'Viewer requires a local checkout; --repository and startup intake flags',
169
+ 'cannot be combined with --viewer. --interval sets its polling cadence.',
170
+ 'Every viewer frame says viewer, optionally viewer · dispatched by <label>.',
171
+ 'Plain/non-TTY output states the same at startup and prints state changes.',
172
+ 'Viewer keeps the shared-store controls below; Ctrl-C never stops dispatch elsewhere.',
160
173
  '',
161
174
  '',
162
175
  'An interactive terminal gets a fixed global/harvest/build dashboard.',
@@ -171,7 +184,7 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
171
184
  ' resume or acknowledge the run.',
172
185
  ' r On the global row, resume every paused build and turn intake',
173
186
  ' back on. On a build, resume a paused or blocked build.',
174
- ' Ctrl-C Stop dispatch.',
187
+ ' Ctrl-C Stop dispatch, or close only the viewer in --viewer mode.',
175
188
  '',
176
189
  'ab pause --all and ab resume --all are the sessionless equivalents of the',
177
190
  'global row’s p and r; they need no dispatcher and no terminal.',
@@ -263,6 +276,7 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
263
276
  detail: page([
264
277
  'Usage:',
265
278
  ' ab repository status [--json] [--store <ref>]',
279
+ ' ab repository forge-clear --forge <name> --reason <text> [--json] [--store <ref>]',
266
280
  '',
267
281
  'Report the durable ticket-intake setting and repository-wide pause from',
268
282
  'the same journal projection used by dispatch and the dashboard.',
@@ -367,7 +381,7 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
367
381
  '',
368
382
  'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
369
383
  'integration.verification-failed (failed node verification), build.janitor-failing, build.compatibility-deferred,',
370
- 'node.item-conflicted, conflicted restack.replayed, derived build.consent-ready and',
384
+ 'node.item-conflicted, target.rewritten, conflicted restack.replayed, derived build.consent-ready and',
371
385
  'build.merge-decision (a current actionable merge-gate deferral or unsafe forge outcome).',
372
386
  'Consent and held ready merges use only build.consent-ready, once per readiness episode.',
373
387
  'Unready or stale consent candidates stay silent; one merge gate decision per build/PR.',
@@ -10,6 +10,9 @@ export async function historicalBuildState(
10
10
  current: { cursor: number; value: BuildStreamSeed },
11
11
  ) {
12
12
  if (requested >= current.cursor) return current.value
13
+ if (store.getStreamSeed)
14
+ return (await store.getStreamSeed({ kind: 'build', slug }, requested))
15
+ .value as unknown as BuildStreamSeed
13
16
  const events = await store.getEvents(slug)
14
17
  return buildStreamSeedReducer.reduce(events.filter((event) => event.seq <= requested))
15
18
  }
@@ -22,6 +25,9 @@ export async function historicalRepositoryAttention(
22
25
  current: { cursor: number; value: ReturnType<typeof repositoryAttentionReducer.finish> },
23
26
  ) {
24
27
  if (requested >= current.cursor) return current.value
28
+ if (store.getStreamSeed)
29
+ return (await store.getStreamSeed({ kind: 'repo', repo }, requested))
30
+ .value as unknown as ReturnType<typeof repositoryAttentionReducer.finish>
25
31
  const events = await store.getRepoEvents(repo)
26
32
  return repositoryAttentionReducer.reduce(events.filter((event) => event.seq <= requested))
27
33
  }
@@ -1,3 +1,4 @@
1
+ import { abForgeClear } from './forge-clear'
1
2
  import { abAccountsLogin } from './accounts'
2
3
  import { abSecrets } from './secrets'
3
4
  import { currentTicketRef } from '../kernel/ticket-migrations'
@@ -751,8 +752,18 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
751
752
  // a build, so it routes before any store/env requirement and does its own
752
753
  // heavy wiring (like ticket create). One dispatcher per repo (§12).
753
754
  case 'dispatch': {
754
- const { once, plain, intake, defaultAutoMerge, intervalMs, storeRef, repository } =
755
- parseDispatchArgs(rest, deps.processEnv ?? {})
755
+ const {
756
+ viewer,
757
+ takeover,
758
+ dispatchedBy,
759
+ once,
760
+ plain,
761
+ intake,
762
+ defaultAutoMerge,
763
+ intervalMs,
764
+ storeRef,
765
+ repository,
766
+ } = parseDispatchArgs(rest, deps.processEnv ?? {})
756
767
  if (deps.exec === undefined) {
757
768
  throw new Error("'ab dispatch' needs an exec seam — this is a wiring bug in the ab binary")
758
769
  }
@@ -762,6 +773,9 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
762
773
  exec: deps.exec,
763
774
  stdout,
764
775
  stderr,
776
+ viewer,
777
+ takeover,
778
+ ...(dispatchedBy !== undefined ? { dispatchedBy } : {}),
765
779
  once,
766
780
  plain,
767
781
  ...(intake !== undefined ? { intake } : {}),
@@ -812,6 +826,33 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
812
826
  case 'repository': {
813
827
  const usage = 'usage: ab repository status [--json] [--store <ref>] (§8.2)'
814
828
  const [sub, ...more] = rest
829
+ if (sub === 'forge-clear') {
830
+ const clearUsage =
831
+ 'usage: ab repository forge-clear --forge <name> --reason <text> [--json] [--store <ref>]'
832
+ const parsed = parseArgs(
833
+ more,
834
+ { forge: 'value', reason: 'value', json: 'boolean', store: 'value' },
835
+ clearUsage,
836
+ )
837
+ const forge = stringFlag(parsed, 'forge')
838
+ const reason = stringFlag(parsed, 'reason')
839
+ if (parsed.positionals.length || !forge?.trim() || !reason?.trim())
840
+ throw new Error(clearUsage)
841
+ if (!deps.exec) throw new Error('repository forge-clear requires an exec seam')
842
+ const storeRef = stringFlag(parsed, 'store')
843
+ await abForgeClear({
844
+ targetRepo: deps.workspacePath,
845
+ env: deps.processEnv ?? {},
846
+ exec: deps.exec,
847
+ stdout,
848
+ forge,
849
+ reason,
850
+ json: parsed.flags.has('json'),
851
+ ...(storeRef !== undefined ? { storeRef } : {}),
852
+ ...(deps.openStore !== undefined ? { openStore: deps.openStore } : {}),
853
+ })
854
+ return 0
855
+ }
815
856
  if (sub !== 'status') throw new Error(usage)
816
857
  const parsed = parseArgs(more, { json: 'boolean', store: 'value' }, usage)
817
858
  if (parsed.positionals.length > 0) throw new Error(usage)