@defrex/autobuild 1.12.0 → 1.14.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 (167) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +465 -163
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +28 -4
  5. package/docs/architecture.md +136 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +120 -17
  8. package/docs/dispatcher.md +19 -8
  9. package/docs/integration-overview.md +1 -1
  10. package/docs/integration-tree.md +12 -9
  11. package/docs/merge-policy.md +7 -2
  12. package/docs/operating.md +13 -3
  13. package/docs/operator-api.md +46 -23
  14. package/docs/operator-surfaces.md +7 -6
  15. package/docs/optimization-nodes.md +7 -6
  16. package/docs/plugin-authoring.md +46 -18
  17. package/docs/remote-store-protocol.md +52 -13
  18. package/docs/remote-ticket-protocol.md +85 -38
  19. package/docs/restacking.md +48 -3
  20. package/docs/setup.md +2 -1
  21. package/docs/ticket-migration.md +2 -2
  22. package/docs/ticket-sources.md +23 -8
  23. package/docs/tickets.md +4 -4
  24. package/docs/troubleshooting.md +32 -2
  25. package/docs/verification.md +3 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/build-control.ts +72 -6
  28. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  29. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  30. package/packages/core/src/cli/dashboard/model.ts +14 -8
  31. package/packages/core/src/cli/dashboard/poll.ts +218 -10
  32. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  33. package/packages/core/src/cli/dashboard/row-text.ts +2 -1
  34. package/packages/core/src/cli/dashboard/vocabulary.ts +5 -1
  35. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  36. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  37. package/packages/core/src/cli/dispatch.ts +547 -145
  38. package/packages/core/src/cli/help.ts +38 -24
  39. package/packages/core/src/cli/main.ts +7 -5
  40. package/packages/core/src/cli/publication-settlement.ts +4 -0
  41. package/packages/core/src/cli/remote-poll.ts +22 -5
  42. package/packages/core/src/cli/repository-status.ts +19 -9
  43. package/packages/core/src/cli/status.ts +23 -11
  44. package/packages/core/src/cli/store-opening.ts +12 -0
  45. package/packages/core/src/cli/ticket-start.ts +3 -3
  46. package/packages/core/src/cli/ticket.ts +12 -11
  47. package/packages/core/src/cli/wait.ts +8 -28
  48. package/packages/core/src/cli/watch.ts +113 -50
  49. package/packages/core/src/config/reference-metadata.ts +7 -1
  50. package/packages/core/src/config/reference.ts +5 -2
  51. package/packages/core/src/config/schema.ts +51 -16
  52. package/packages/core/src/events/payloads.ts +74 -14
  53. package/packages/core/src/events/policy.ts +1 -0
  54. package/packages/core/src/events/repository.ts +33 -3
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  63. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  64. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  65. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  67. package/packages/core/src/kernel/done-escalations.ts +273 -0
  68. package/packages/core/src/kernel/engine.ts +28 -9
  69. package/packages/core/src/kernel/integration-landing.ts +24 -4
  70. package/packages/core/src/kernel/integration-stack.ts +39 -0
  71. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  72. package/packages/core/src/kernel/log-index-value.ts +3 -0
  73. package/packages/core/src/kernel/log-index.ts +41 -2
  74. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  75. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  76. package/packages/core/src/kernel/reducer-revisions.ts +19 -0
  77. package/packages/core/src/kernel/reducer.ts +42 -8
  78. package/packages/core/src/kernel/repository-attention.ts +14 -5
  79. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  80. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  81. package/packages/core/src/kernel/verify-stages.ts +46 -7
  82. package/packages/core/src/operator/attention.ts +28 -3
  83. package/packages/core/src/operator/done-escalations.ts +38 -0
  84. package/packages/core/src/operator/presentation.ts +1 -1
  85. package/packages/core/src/operator/protocol.ts +8 -5
  86. package/packages/core/src/operator/query.ts +33 -19
  87. package/packages/core/src/operator/registry.ts +17 -13
  88. package/packages/core/src/operator/ticket-start.ts +8 -7
  89. package/packages/core/src/operator/tickets.ts +28 -9
  90. package/packages/core/src/plugin-sdk/index.ts +10 -0
  91. package/packages/core/src/plugins/manifest.ts +14 -1
  92. package/packages/core/src/ports/forge/create.ts +8 -0
  93. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  94. package/packages/core/src/ports/forge/github.ts +3 -0
  95. package/packages/core/src/ports/tickets/contract.ts +147 -76
  96. package/packages/core/src/ports/tickets/create.ts +47 -7
  97. package/packages/core/src/ports/tickets/fake.ts +8 -4
  98. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  99. package/packages/core/src/ports/tickets/file.ts +7 -3
  100. package/packages/core/src/ports/tickets/github.ts +1 -0
  101. package/packages/core/src/ports/tickets/grants.ts +11 -3
  102. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  103. package/packages/core/src/ports/tickets/linear.ts +28 -9
  104. package/packages/core/src/ports/tickets/migration.ts +4 -4
  105. package/packages/core/src/ports/tickets/operations.ts +4 -2
  106. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  107. package/packages/core/src/ports/tickets/priority.ts +127 -21
  108. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  109. package/packages/core/src/ports/tickets/remote.ts +104 -11
  110. package/packages/core/src/ports/tickets/revision.ts +5 -3
  111. package/packages/core/src/ports/tickets/search.ts +9 -0
  112. package/packages/core/src/ports/tickets/tree.ts +8 -6
  113. package/packages/core/src/ports/types.ts +30 -15
  114. package/packages/core/src/ports/workspace/build-execution.ts +13 -1
  115. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  116. package/packages/core/src/ports/workspace/create.ts +16 -3
  117. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  118. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  119. package/packages/core/src/ports/workspace/vercel-sandbox.ts +596 -144
  120. package/packages/core/src/processes/build-execution-state.ts +4 -0
  121. package/packages/core/src/processes/build-runner.ts +14 -1
  122. package/packages/core/src/processes/dispatcher.ts +841 -230
  123. package/packages/core/src/processes/execution-settlement.ts +25 -3
  124. package/packages/core/src/processes/harvest-runner.ts +12 -7
  125. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  126. package/packages/core/src/processes/invocation-budget.ts +176 -0
  127. package/packages/core/src/processes/publication-loss.ts +38 -3
  128. package/packages/core/src/processes/tick-publication.ts +1 -0
  129. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  130. package/packages/core/src/store/contract.ts +88 -3
  131. package/packages/core/src/store/event-reads.ts +30 -1
  132. package/packages/core/src/store/reduced-reads.ts +23 -0
  133. package/packages/core/src/store/reducer-value-shapes.json +6759 -6490
  134. package/packages/core/src/store/reducer-value-validation.ts +188 -33
  135. package/packages/core/src/store/remote/client.ts +169 -29
  136. package/packages/core/src/store/remote/compatibility.ts +113 -56
  137. package/packages/core/src/store/remote/credentials.ts +4 -1
  138. package/packages/core/src/store/remote/protocol.ts +3 -0
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  143. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  144. package/packages/core/src/store/remote/retry.ts +406 -0
  145. package/packages/core/src/store/repo-state-events.ts +1 -0
  146. package/packages/core/src/testing/dispatch-read-budget.ts +155 -11
  147. package/packages/core/src/testing/index.ts +2 -0
  148. package/packages/core/src/testing/invocation-budget.ts +42 -0
  149. package/packages/core/src/testing/reduced-read-budget.ts +589 -19
  150. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  151. package/packages/core/src/web/overview-source.ts +19 -6
  152. package/skills/guide/SKILL.md +147 -67
  153. package/skills/guide/references/integration-tree.md +12 -9
  154. package/skills/guide/references/merge-policy.md +7 -2
  155. package/skills/guide/references/operator-api.md +46 -23
  156. package/skills/guide/references/optimization-nodes.md +7 -6
  157. package/skills/guide/references/plugin-authoring.md +46 -18
  158. package/skills/guide/references/remote-store-protocol.md +52 -13
  159. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  160. package/skills/guide/references/restacking.md +48 -3
  161. package/skills/guide/references/setup.md +2 -1
  162. package/skills/guide/references/ticket-migration.md +2 -2
  163. package/skills/operate/SKILL.md +136 -55
  164. package/skills/plan/SKILL.md +4 -3
  165. package/skills/spec/SKILL.md +9 -5
  166. package/skills/tickets/SKILL.md +25 -17
  167. package/templates/hosted-service/package.json +2 -2
@@ -18,6 +18,7 @@ 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 { isRecoveryDeferred } from '../ports/workspace/recovery-step'
21
22
  import { recordRuntimeRollback } from './dispatch-handoff'
22
23
  import { syncRollbackRetention } from './dispatch-runtime-use'
23
24
  import { dirname as runtimeDirname } from 'node:path'
@@ -41,7 +42,7 @@ import { formatDispatcherError, runtimeIdentity } from '../runtime-identity'
41
42
 
42
43
  import { isDeepStrictEqual } from 'node:util'
43
44
  import { guardForge } from '../kernel/guarded-forge'
44
- import { dispatchCapacity, startClaimDemand, urgentClaimDemand } from '../kernel/dispatch-capacity'
45
+ import { dispatchCapacity, startClaimDemand, claimDemand } from '../kernel/dispatch-capacity'
45
46
  import { lazyTicketSource, openTicketSource } from './ticket'
46
47
  import { ticketLifecycle } from '../ports/tickets/lifecycle'
47
48
  import {
@@ -158,7 +159,7 @@ import {
158
159
  type DashboardSelection,
159
160
  type DashboardView,
160
161
  } from './dashboard/model'
161
- import { DashboardBuildPollCache } from './dashboard/poll'
162
+ import { DashboardBuildPollCache, hasActiveBuilds } from './dashboard/poll'
162
163
  import { repositoryQueueDepth } from './dashboard/header'
163
164
  import {
164
165
  dashboardContentWidth,
@@ -189,6 +190,7 @@ import { GitHubForge, refusedArchiveFallback } from '../ports/forge/github'
189
190
  import type { RuntimeRegistry } from '../ports/runner/runtime'
190
191
  import { createTicketSource } from '../ports/tickets/create'
191
192
  import { dispatcherTicketSource } from './dispatch-tickets'
193
+ import { isTransientRemoteFailure, withRemoteRetryDeadline } from '../store/remote/retry'
192
194
  import type {
193
195
  Forge,
194
196
  TicketSource,
@@ -246,7 +248,17 @@ import {
246
248
  resolveRepoStatePaths,
247
249
  type RepoStatePaths,
248
250
  } from './repo-state'
249
- import { openStoreForRepoState } from './store-opening'
251
+ import { budgetedProductionStore, openStoreForRepoState } from './store-opening'
252
+ import {
253
+ budgetedFetch,
254
+ DEFAULT_TIMERS,
255
+ InvocationBudgetExhaustedError,
256
+ invocationSignal,
257
+ untilAborted,
258
+ withInvocationSignal,
259
+ type InvocationBudget,
260
+ type TimerScheduler,
261
+ } from '../processes/invocation-budget'
250
262
  import { DispatchFrontend } from './dispatch-frontend'
251
263
  import {
252
264
  systemClock,
@@ -367,8 +379,21 @@ export interface DispatchWiring {
367
379
  releaseAccounts?: () => Promise<void>
368
380
 
369
381
  credentialIssuer?: typeof delegateCredential
382
+ /** Bounded invocation only: the cancelling host fetch and ambient signal
383
+ * reader `defaultWire` gives the primary adapters. The loop applies them to
384
+ * the requests it makes itself (credential delegation, ticket grants) and
385
+ * to the secondary store and ticket adapters it builds for a harvest.
386
+ * Absent ⇒ global `fetch`, unchanged. */
387
+ budgetSeams?: {
388
+ fetchFn: typeof fetch
389
+ invocationSignal: () => AbortSignal | undefined
390
+ }
370
391
  store: BuildStore
371
392
  tickets: TicketSource
393
+ /** The ticket source's deferred preparation (a hosted source's policy
394
+ * synchronization and targeting negotiation), run at the first tick
395
+ * boundary until it succeeds. Absent, the source needs none. */
396
+ prepareTickets?: () => Promise<void>
372
397
  forge: Forge
373
398
  workspaces: WorkspaceProvider
374
399
  /** Provider and executor pairs for workspaces recorded before a
@@ -402,28 +427,18 @@ export interface DispatchWiring {
402
427
 
403
428
  export type DispatchNonStoreWiring = Omit<DispatchWiring, 'store' | 'storeRef' | 'token'>
404
429
 
405
- /** Timer seam for the invocation bound (hosted cron): the drain races the
406
- * in-flight build set against a `deadlineAt` expiry timer. Production uses
407
- * `DEFAULT_TIMERS`; tests inject a fake whose pending handles are inspectable
408
- * and fireable, so both race outcomes are deterministic — no real-time sleeps.
409
- * Handles are opaque (`unknown`) so the interface stays runtime-agnostic. */
410
- export interface TimerScheduler {
411
- setTimeout(handler: () => void, ms: number): unknown
412
- clearTimeout(handle: unknown): void
413
- }
414
-
415
- /** Production scheduler: real global timers, preserving the existing
416
- * `unref()` courtesy so a pending expiry never holds the process open. */
417
- const DEFAULT_TIMERS: TimerScheduler = {
418
- setTimeout(handler, ms) {
419
- const timer = setTimeout(handler, ms)
420
- ;(timer as { unref?: () => void }).unref?.()
421
- return timer
422
- },
423
- clearTimeout(handle) {
424
- clearTimeout(handle as ReturnType<typeof setTimeout>)
425
- },
426
- }
430
+ export type { TimerScheduler } from '../processes/invocation-budget'
431
+ export {
432
+ createInvocationBudget,
433
+ teardownReserveMs,
434
+ untilAborted,
435
+ withInvocationSignal,
436
+ invocationSignal,
437
+ budgetedFetch,
438
+ InvocationDeadlineError,
439
+ InvocationBudgetExhaustedError,
440
+ type InvocationBudget,
441
+ } from '../processes/invocation-budget'
427
442
 
428
443
  export interface DispatchOpts {
429
444
  takeover?: boolean
@@ -528,13 +543,22 @@ export interface DispatchOpts {
528
543
  /** Private child mode: preserve kernel behavior while routing no legacy
529
544
  * line output into the terminal-owning parent. */
530
545
  silent?: boolean
531
- /** Invocation bound (epoch ms, measured against `wiring.clock`). `--once`
546
+ /** Invocation WORK bound (epoch ms, measured against `wiring.clock`). `--once`
532
547
  * only: an already-passed deadline skips the tick and the drain entirely
533
548
  * (teardown still runs), and a deadline reached mid-drain stops awaiting
534
549
  * `local-parent` executions, which teardown then stops and reaps — so one
535
550
  * invocation always returns and unfinished work resumes next invocation.
536
551
  * Watch mode is unaffected; absent ⇒ unbounded (today's exact behavior). */
537
552
  deadlineAt?: number
553
+ /** Bounded `--once` invocation (hosted cron): an enforced wall-time budget
554
+ * with teardown headroom. The caller creates it with its own clock and
555
+ * timers and owns its disposal. Startup and the work pass run under its
556
+ * `work` signal, so every builtin adapter request is cancelled at the work
557
+ * deadline; teardown runs under `cleanup` and `final`, and a budget stop
558
+ * records a normal `dispatcher.run-stopped`. Requires `once: true`.
559
+ * `deadlineAt` defaults to `invocationBudget.workDeadlineAt`; a different
560
+ * explicit `deadlineAt` is a wiring error. */
561
+ invocationBudget?: InvocationBudget
538
562
  /** Timer seam for the `deadlineAt` drain race. Absent ⇒ `DEFAULT_TIMERS`
539
563
  * (real, unref'd timers); tests inject a manual scheduler to drive both
540
564
  * race outcomes deterministically and to assert no expiry handle outlives
@@ -626,6 +650,11 @@ async function defaultWire(
626
650
  // Origin mode: no checkout exists, so the provider's host git seams are
627
651
  // replaced by the injected origin and the forge's remote reads.
628
652
  const originMode = opts.repository !== undefined
653
+ // Bounded invocation (hosted cron): every builtin adapter request, and the
654
+ // plugin factory context's fetch, is cancelled at the current phase's
655
+ // deadline. Unbounded dispatch passes nothing and keeps global fetch.
656
+ const budgetSeams =
657
+ opts.invocationBudget !== undefined ? { fetchFn: budgetedFetch(), invocationSignal } : undefined
629
658
  await validateWorkspaceDispatchConfiguration(config, opts, plugins)
630
659
  // The builtin GitHub forge resolves its credential lazily on its first
631
660
  // request (GITHUB_TOKEN, GH_TOKEN, then the gh CLI login) and names the
@@ -641,6 +670,7 @@ async function defaultWire(
641
670
  // dispatcher routes it to its shipped Git), as `fetchOriginModeConfig`
642
671
  // already does; a checkout dispatcher keeps finding Git on its PATH.
643
672
  ...(originMode ? { exec: opts.exec } : {}),
673
+ ...budgetSeams,
644
674
  })
645
675
  // Checkout-less provider seams: the sandbox provider derives its origin and
646
676
  // remote branch heads from these instead of host `git` — every host-exec
@@ -667,14 +697,20 @@ async function defaultWire(
667
697
  // A guest whose archive push is refused falls back to the forge's REST
668
698
  // creation on the host, in checkout and origin mode alike.
669
699
  const refusedArchive = refusedArchiveFallback(forge)
670
- const opened = openStoreForRepoState(state, { env: opts.env })
700
+ const opened = openStoreForRepoState(state, {
701
+ env: opts.env,
702
+ ...(budgetSeams !== undefined
703
+ ? { openStore: budgetedProductionStore(budgetSeams.fetchFn) }
704
+ : {}),
705
+ })
671
706
 
672
- const tickets = await dispatcherTicketSource(
707
+ const { tickets, prepare: prepareTickets } = await dispatcherTicketSource(
673
708
  config.tickets,
674
709
  opts,
675
710
  state,
676
711
  opened.localStateRoot,
677
712
  plugins,
713
+ budgetSeams ?? {},
678
714
  )
679
715
  // Once, before the loop: whatever a readyAssignee or createAssignee value
680
716
  // needs is resolved here so neither a tick nor a reload ever spends a
@@ -761,6 +797,8 @@ async function defaultWire(
761
797
  ...providerSeams,
762
798
  ...(refusedArchive !== undefined ? { refusedArchive } : {}),
763
799
  ...(opened.token !== undefined ? { storeToken: opened.token } : {}),
800
+ ...budgetSeams,
801
+ ...(opts.deadlineAt !== undefined ? { invocationDeadlineAt: opts.deadlineAt } : {}),
764
802
  })
765
803
 
766
804
  // Builds provisioned before this repository switched providers still hold
@@ -795,6 +833,7 @@ async function defaultWire(
795
833
  inspectLocalAccountEnvironment(credentials, accounts, opts.env, undefined, true),
796
834
  releaseAccounts,
797
835
  tickets,
836
+ ...(prepareTickets !== undefined ? { prepareTickets } : {}),
798
837
  forge,
799
838
  workspaces: workspaceRuntime.provider,
800
839
  retiredWorkspaces,
@@ -809,6 +848,7 @@ async function defaultWire(
809
848
  uuids: randomUuids(),
810
849
  clock: systemClock,
811
850
  plugins,
851
+ ...(budgetSeams !== undefined ? { budgetSeams } : {}),
812
852
  updateRuntimeReferences: (effectiveConfig) => {
813
853
  allAccounts = effectiveConfig.accounts
814
854
  accounts = selectedExecutionAccounts(effectiveConfig)
@@ -843,6 +883,25 @@ interface ActiveBuildExecution {
843
883
  /** The dispatch loop owns deterministic decisions and supervises one
844
884
  * workspace-adjacent process per build. Build outcomes flow only through the
845
885
  * Store; child completion is liveness evidence used for reaping/single-flight. */
886
+ /** A ticket preparation failure that is not transient (authentication, a
887
+ * service predating the policy, validation): the run stops abnormally with
888
+ * `cause`, exactly as a construction-time failure always did. */
889
+ export class FatalTicketPreparationError extends Error {
890
+ override readonly name = 'FatalTicketPreparationError'
891
+ constructor(override readonly cause: unknown) {
892
+ super(cause instanceof Error ? cause.message : String(cause), { cause })
893
+ }
894
+ }
895
+
896
+ /** A `--once` tick failed and its `dispatcher.tick-failed` is durable: the run
897
+ * records a normal stop with exit code 1 and `abDispatch` rethrows `cause`. */
898
+ export class DispatchTickFailedError extends Error {
899
+ override readonly name = 'DispatchTickFailedError'
900
+ constructor(override readonly cause: unknown) {
901
+ super(cause instanceof Error ? cause.message : String(cause), { cause })
902
+ }
903
+ }
904
+
846
905
  class DispatchLoop {
847
906
  private readonly dispatcher: Dispatcher
848
907
  /** The incremental repository view (AUT-647) the dispatcher and this
@@ -1006,9 +1065,40 @@ class DispatchLoop {
1006
1065
  * absent deadline is never past, so every existing caller is unchanged. */
1007
1066
  private pastDeadline(): boolean {
1008
1067
  return (
1009
- this.opts.deadlineAt !== undefined && this.wiring.clock().getTime() >= this.opts.deadlineAt
1068
+ (this.opts.deadlineAt !== undefined &&
1069
+ this.wiring.clock().getTime() >= this.opts.deadlineAt) ||
1070
+ this.budgetStopped()
1010
1071
  )
1011
1072
  }
1073
+
1074
+ /** Bounded invocation: true once the budget's work deadline has passed. */
1075
+ private budgetStopped(): boolean {
1076
+ return this.opts.invocationBudget?.work.aborted === true
1077
+ }
1078
+
1079
+ private deadlineStop = false
1080
+ /** True when a bounded invocation stopped its work pass at the deadline. */
1081
+ get stoppedAtDeadline(): boolean {
1082
+ return this.deadlineStop
1083
+ }
1084
+
1085
+ /** Set when an initial repository-lease claim request failed: the server
1086
+ * may have committed it, so a bounded invocation releases exactly its own
1087
+ * holder before exiting. Cleared by a later successful claim. */
1088
+ private repoLeaseClaimAmbiguous = false
1089
+
1090
+ /** The work-deadline listener: synchronously stop launches, mark every
1091
+ * environment-supervised execution and the hosted harvest as detaching,
1092
+ * and signal provisioning continuations, so a request the deadline aborts
1093
+ * is classified as teardown, never as a wait or provisioning failure. */
1094
+ private readonly onWorkDeadline = (): void => {
1095
+ this.acceptingBuildLaunches = false
1096
+ for (const entry of this.activeBuildRuns.values()) {
1097
+ if (entry.handle?.supervision === 'environment') entry.detaching = true
1098
+ }
1099
+ if (this.hostedHarvest !== undefined) this.hostedHarvest.detached.value = true
1100
+ this.dispatcher.abortProvisioning()
1101
+ }
1012
1102
  /** The holder id this invocation already recorded a `tick-yielded` for. */
1013
1103
  private yieldedTo: string | undefined
1014
1104
  /** The invocation's durable journaling identity: every repository-lease
@@ -1570,6 +1660,12 @@ class DispatchLoop {
1570
1660
  // remaining budget cannot cover them (bounded overrun, one in-flight
1571
1661
  // transport call). Watch mode has no deadline ⇒ absent ⇒ unbounded.
1572
1662
  ...(this.opts.deadlineAt !== undefined ? { deadlineAt: this.opts.deadlineAt } : {}),
1663
+ ...(this.opts.invocationBudget !== undefined
1664
+ ? {
1665
+ workSignal: this.opts.invocationBudget.work,
1666
+ teardownWrite: this.teardownWrite(this.opts.invocationBudget),
1667
+ }
1668
+ : {}),
1573
1669
  })
1574
1670
  const publishedReport: TickReport = {
1575
1671
  ...report,
@@ -2675,6 +2771,7 @@ class DispatchLoop {
2675
2771
  }
2676
2772
 
2677
2773
  const { store, tickets, runtimes, ids, uuids, clock, storeRef, token } = this.wiring
2774
+ const fetchFn = this.wiring.budgetSeams?.fetchFn
2678
2775
  const harvestDeps = {
2679
2776
  shutdownSignal: AbortSignal.any([
2680
2777
  this.localHarvestShutdown.signal,
@@ -2693,6 +2790,7 @@ class DispatchLoop {
2693
2790
  uuids,
2694
2791
  clock,
2695
2792
  instance: `${this.host}-harvest-${ids('inst')}`,
2793
+ ...(fetchFn !== undefined ? { fetchFn } : {}),
2696
2794
  ...(this.repoLeaseHolder !== undefined ? { leaseHolder: this.repoLeaseHolder } : {}),
2697
2795
  holdsAuthority: () => this.holdsRepoAuthority(),
2698
2796
  sessionEnv: {
@@ -2723,6 +2821,7 @@ class DispatchLoop {
2723
2821
  this.repoIdentity,
2724
2822
  harvestDeps.instance,
2725
2823
  'runner',
2824
+ fetchFn,
2726
2825
  )
2727
2826
  let remoteRunnerStore: RemoteBuildStore | undefined
2728
2827
  let preparedRun: { run: string } | undefined
@@ -2756,8 +2855,13 @@ class DispatchLoop {
2756
2855
  id: prepared.run,
2757
2856
  leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2758
2857
  },
2858
+ fetchFn,
2759
2859
  )
2760
- remoteRunnerStore = new RemoteBuildStore({ url: storeRef, token: buildScoped })
2860
+ remoteRunnerStore = new RemoteBuildStore({
2861
+ url: storeRef,
2862
+ token: buildScoped,
2863
+ ...(fetchFn !== undefined ? { fetchFn } : {}),
2864
+ })
2761
2865
  }
2762
2866
  const sessionEnv = {
2763
2867
  ...harvestDeps.sessionEnv,
@@ -2767,11 +2871,12 @@ class DispatchLoop {
2767
2871
  }
2768
2872
  let renewalFailure: unknown
2769
2873
  renew = setInterval(() => {
2770
- void ticketGrantRequest(ticketUrl, issued.token, {
2771
- action: 'renew',
2772
- repo: this.repoIdentity,
2773
- id: issued.grant.id,
2774
- }).catch((error) => {
2874
+ void ticketGrantRequest(
2875
+ ticketUrl,
2876
+ issued.token,
2877
+ { action: 'renew', repo: this.repoIdentity, id: issued.grant.id },
2878
+ fetchFn,
2879
+ ).catch((error) => {
2775
2880
  renewalFailure = error
2776
2881
  })
2777
2882
  }, 60_000)
@@ -2781,7 +2886,10 @@ class DispatchLoop {
2781
2886
  this.opts.targetRepo,
2782
2887
  undefined,
2783
2888
  this.wiring.plugins,
2784
- this.opts.repository !== undefined ? { repository: this.repoIdentity } : {},
2889
+ {
2890
+ ...(this.opts.repository !== undefined ? { repository: this.repoIdentity } : {}),
2891
+ ...this.wiring.budgetSeams,
2892
+ },
2785
2893
  )
2786
2894
  const result = await new HarvestRunner({
2787
2895
  ...harvestDeps,
@@ -2804,6 +2912,9 @@ class DispatchLoop {
2804
2912
  await remoteRunnerStore.close()
2805
2913
  }
2806
2914
  } finally {
2915
+ // Revocation is compensation, not new work: it keeps global fetch
2916
+ // and its own 15 s bound so a work-deadline stop still releases
2917
+ // the grant rather than leaving it to expiry.
2807
2918
  await ticketGrantRequest(ticketUrl, ticketToken, {
2808
2919
  action: 'revoke',
2809
2920
  repo: this.repoIdentity,
@@ -2826,14 +2937,23 @@ class DispatchLoop {
2826
2937
  leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2827
2938
  },
2828
2939
  })
2829
- const scoped = await (this.wiring.credentialIssuer ?? delegateCredential)(storeRef, token, {
2830
- kind: 'harvest-runner',
2831
- execution: harvestDeps.instance,
2832
- repo: this.repoIdentity,
2833
- id: prepared.run,
2834
- leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2940
+ const scoped = await (this.wiring.credentialIssuer ?? delegateCredential)(
2941
+ storeRef,
2942
+ token,
2943
+ {
2944
+ kind: 'harvest-runner',
2945
+ execution: harvestDeps.instance,
2946
+ repo: this.repoIdentity,
2947
+ id: prepared.run,
2948
+ leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2949
+ },
2950
+ fetchFn,
2951
+ )
2952
+ const runnerStore = new RemoteBuildStore({
2953
+ url: storeRef,
2954
+ token: scoped,
2955
+ ...(fetchFn !== undefined ? { fetchFn } : {}),
2835
2956
  })
2836
- const runnerStore = new RemoteBuildStore({ url: storeRef, token: scoped })
2837
2957
  try {
2838
2958
  const runnerTickets =
2839
2959
  harvestDeps.config.tickets.source === 'hosted'
@@ -2852,7 +2972,10 @@ class DispatchLoop {
2852
2972
  storeRef,
2853
2973
  }).localStateRoot,
2854
2974
  this.wiring.plugins,
2855
- this.opts.repository !== undefined ? { repository: this.repoIdentity } : {},
2975
+ {
2976
+ ...(this.opts.repository !== undefined ? { repository: this.repoIdentity } : {}),
2977
+ ...this.wiring.budgetSeams,
2978
+ },
2856
2979
  )
2857
2980
  : harvestDeps.tickets
2858
2981
  return await new HarvestRunner({
@@ -3013,6 +3136,7 @@ class DispatchLoop {
3013
3136
  id: prepared.run,
3014
3137
  leaseHolder: this.repoLeaseHolder ?? execution,
3015
3138
  },
3139
+ this.wiring.budgetSeams?.fetchFn,
3016
3140
  ),
3017
3141
  }
3018
3142
  : undefined
@@ -3034,14 +3158,16 @@ class DispatchLoop {
3034
3158
  repo,
3035
3159
  execution,
3036
3160
  'runner',
3161
+ this.wiring.budgetSeams?.fetchFn,
3037
3162
  )
3038
3163
  ticketAuthority = { url: ticketConfig.url, token: issued.token, id: issued.grant.id }
3039
3164
  renewTickets = setInterval(() => {
3040
- void ticketGrantRequest(ticketConfig.url!, issued.token, {
3041
- action: 'renew',
3042
- repo,
3043
- id: issued.grant.id,
3044
- }).catch(() => {
3165
+ void ticketGrantRequest(
3166
+ ticketConfig.url!,
3167
+ issued.token,
3168
+ { action: 'renew', repo, id: issued.grant.id },
3169
+ this.wiring.budgetSeams?.fetchFn,
3170
+ ).catch(() => {
3045
3171
  // Expiry fails subsequent reads closed; the guest cannot regain project authority.
3046
3172
  })
3047
3173
  }, 60_000)
@@ -3144,6 +3270,7 @@ class DispatchLoop {
3144
3270
  }
3145
3271
  } finally {
3146
3272
  if (renewTickets) clearInterval(renewTickets)
3273
+ // Compensation keeps global fetch and its own 15 s bound (see above).
3147
3274
  if (ticketAuthority && !detached.value)
3148
3275
  await ticketGrantRequest(ticketAuthority.url, ticketAuthority.token, {
3149
3276
  action: 'revoke',
@@ -3306,6 +3433,7 @@ class DispatchLoop {
3306
3433
  creationDiagnostics: _creationDiagnostics,
3307
3434
  dependencyDiagnostics: _dependencyDiagnostics,
3308
3435
  agentContextDiagnostics: _agentContextDiagnostics,
3436
+ deferredDiagnostics: _deferredDiagnostics,
3309
3437
  ...counters
3310
3438
  } = merged
3311
3439
  const completed = {
@@ -3397,6 +3525,25 @@ class DispatchLoop {
3397
3525
  | { original: string; first: string; last: string; count: number }
3398
3526
  | undefined
3399
3527
 
3528
+ private ticketsPrepared = false
3529
+
3530
+ /** The ticket source's deferred preparation, at the tick boundary until it
3531
+ * succeeds once. A transient failure is an ordinary tick failure (the next
3532
+ * tick retries it); any other failure is fatal to the run. */
3533
+ private async prepareTickets(): Promise<void> {
3534
+ if (this.ticketsPrepared) return
3535
+ const prepare = this.wiring.prepareTickets
3536
+ if (prepare !== undefined) {
3537
+ try {
3538
+ await prepare()
3539
+ } catch (error) {
3540
+ if (isTransientRemoteFailure(error)) throw error
3541
+ throw new FatalTicketPreparationError(error)
3542
+ }
3543
+ }
3544
+ this.ticketsPrepared = true
3545
+ }
3546
+
3400
3547
  /** A tick stopped by a fenced effect is not a failed tick: publish no
3401
3548
  * `tick-failed`, abandon the open boundary (a successor's or our own next
3402
3549
  * `beginRepoTick` overwrites it), and resolve the lease. That either stops
@@ -3538,7 +3685,12 @@ class DispatchLoop {
3538
3685
  await this.settlePendingPublication(slug)
3539
3686
  } catch (error) {
3540
3687
  // A lapsed run publishes nothing; the successor settles from durable facts.
3541
- if (!(error instanceof ForgeRequestDeferred) && !isRepositoryAuthorityLapse(error))
3688
+ // A deadline-deferred recovery parks the request for a later invocation.
3689
+ if (
3690
+ !(error instanceof ForgeRequestDeferred) &&
3691
+ !isRecoveryDeferred(error) &&
3692
+ !isRepositoryAuthorityLapse(error)
3693
+ )
3542
3694
  throw error
3543
3695
  }
3544
3696
  }
@@ -3552,6 +3704,10 @@ class DispatchLoop {
3552
3704
  cleanupPending: boolean
3553
3705
  identity?: BuildExecutionHandle['identity']
3554
3706
  }): Promise<void> {
3707
+ // Work abandoned at a bounded invocation's deadline records no failure:
3708
+ // the write would be cancelled anyway, and the abort is not a failure.
3709
+ const work = this.opts.invocationBudget?.work
3710
+ if (work?.aborted && invocationSignal() === work) return
3555
3711
  if (await this.dispatcher.holdForMissingAccounts(input.error)) return
3556
3712
  // The failed executor may have appended through its own handle.
3557
3713
  await this.repoView.refreshBuild(input.slug)
@@ -3635,6 +3791,7 @@ class DispatchLoop {
3635
3791
  this.wiring.storeRef,
3636
3792
  this.wiring.token,
3637
3793
  { kind: 'build-runner', id: slug },
3794
+ this.wiring.budgetSeams?.fetchFn,
3638
3795
  ),
3639
3796
  }
3640
3797
  : undefined
@@ -3786,9 +3943,12 @@ class DispatchLoop {
3786
3943
  if (this.activeBuildRuns.get(slug)?.reservation === reservation) {
3787
3944
  this.activeBuildRuns.delete(slug)
3788
3945
  }
3789
- if (error instanceof ForgeRequestDeferred) {
3946
+ if (error instanceof ForgeRequestDeferred || isRecoveryDeferred(error)) {
3790
3947
  if (leaseClaimed) await this.repoView.releaseLease(slug, instance)
3791
3948
  await this.repoView.refreshBuild(slug)
3949
+ // The dispatcher's guarded launch entry records a recovery deferral
3950
+ // (its step and build) and reports it as `already-active`.
3951
+ if (isRecoveryDeferred(error)) throw error
3792
3952
  return 'already-active'
3793
3953
  }
3794
3954
  if (leaseClaimed) {
@@ -4183,6 +4343,7 @@ class DispatchLoop {
4183
4343
  creationDiagnostics,
4184
4344
  dependencyDiagnostics,
4185
4345
  agentContextDiagnostics,
4346
+ deferredDiagnostics,
4186
4347
  queued: _queued,
4187
4348
  ...counts
4188
4349
  } = report
@@ -4193,6 +4354,7 @@ class DispatchLoop {
4193
4354
  for (const line of ticketDiagnostics) this.routineDiagnostic(line)
4194
4355
  for (const line of creationDiagnostics) this.say(line)
4195
4356
  for (const line of dependencyDiagnostics) this.say(line)
4357
+ for (const line of deferredDiagnostics) this.say(line)
4196
4358
  const parts = Object.entries(counts)
4197
4359
  .filter(([, count]) => typeof count === 'number' && count > 0)
4198
4360
  .map(([name, count]) => `${name}=${count}`)
@@ -4206,7 +4368,8 @@ class DispatchLoop {
4206
4368
  ticketDiagnostics.length > 0 ||
4207
4369
  creationDiagnostics.length > 0 ||
4208
4370
  dependencyDiagnostics.length > 0 ||
4209
- agentContextDiagnostics.length > 0
4371
+ agentContextDiagnostics.length > 0 ||
4372
+ deferredDiagnostics.length > 0
4210
4373
  if (reportedDiagnostic) return true
4211
4374
  // A tick that did something is worth a plain line. Interactive mode
4212
4375
  // suppresses both action counts and the every-10s idle noise.
@@ -4273,7 +4436,7 @@ class DispatchLoop {
4273
4436
  (this.opts.once !== true && this.refresh !== undefined && !this.refresh.admitted)
4274
4437
  )
4275
4438
  return
4276
- if (this.opts.once !== true) this.refresh?.activity(buildSnapshot.states.size > 0)
4439
+ if (this.opts.once !== true) this.refresh?.activity(hasActiveBuilds(buildSnapshot))
4277
4440
 
4278
4441
  // Polling continues while the operator types. Keep the prompt bound to the
4279
4442
  // captured build/escalations, shrink it around externally answered ids, and
@@ -4318,7 +4481,7 @@ class DispatchLoop {
4318
4481
  configSnapshot.config.capacity,
4319
4482
  this.wiring.clock(),
4320
4483
  {
4321
- urgentClaims: urgentClaimDemand(repositoryEvents),
4484
+ claims: claimDemand(repositoryEvents),
4322
4485
  openPrs: {
4323
4486
  policy: configSnapshot.config.policy,
4324
4487
  engaged: repositoryEvents.openPrBackpressure !== undefined,
@@ -4578,8 +4741,13 @@ class DispatchLoop {
4578
4741
  const requestedAt = this.wiring.clock().getTime()
4579
4742
  const granted = await this.wiring.store
4580
4743
  .claimRepoLease(this.repoIdentity, holder, lease.ttlMs)
4581
- .catch(() => false)
4744
+ .catch(() => {
4745
+ // A rejected claim request may still have committed server-side.
4746
+ this.repoLeaseClaimAmbiguous = true
4747
+ return false
4748
+ })
4582
4749
  if (!granted || this.superseded) return false
4750
+ this.repoLeaseClaimAmbiguous = false
4583
4751
  this.leaseGeneration++
4584
4752
  this.heldLease = lease
4585
4753
  this.repoLeaseValidUntil = requestedAt + lease.ttlMs
@@ -4697,6 +4865,10 @@ class DispatchLoop {
4697
4865
  * lease no longer renewable hands the decision to the resolver; it never
4698
4866
  * concludes takeover by itself. */
4699
4867
  private restartRepoLeaseHeartbeat(): void {
4868
+ // In a bounded invocation the timer is created inside the work phase, so
4869
+ // its beats inherit the work signal and fail after the work deadline. The
4870
+ // unreachable-store branch below tolerates that, the lease TTL far
4871
+ // exceeds the teardown reserve, and the release runs under `final`.
4700
4872
  this.stopRepoLeaseHeartbeat()
4701
4873
  const holder = this.repoLeaseHolder
4702
4874
  const lease = this.heldLease
@@ -5320,6 +5492,108 @@ class DispatchLoop {
5320
5492
  this.upgradeController.start()
5321
5493
  }
5322
5494
 
5495
+ /** The single `--once` pass: one tick, its drain, settlement publication,
5496
+ * and one delivery pass per configured hook. */
5497
+ private async onePass(): Promise<void> {
5498
+ // Prepare tickets before the background triage read and single tick.
5499
+ const initial = await this.prepareTickets()
5500
+ .then(() => {
5501
+ this.triageSampler?.poke()
5502
+ return this.dispatcherTick(true)
5503
+ })
5504
+ .catch(async (error: unknown) => {
5505
+ if (isRepositoryAuthorityLapse(error)) {
5506
+ await this.settleAuthorityLapse()
5507
+ return emptyTickReport()
5508
+ }
5509
+ // A bounded invocation's work deadline cancelled the tick: a budget
5510
+ // stop, never a tick failure.
5511
+ if (this.budgetStopped()) return emptyTickReport()
5512
+ if (error instanceof FatalTicketPreparationError) throw error.cause
5513
+ await this.reportTickFailure(error)
5514
+ if (this.forgePublicationFailed || this.pendingTickFailure !== undefined) throw error
5515
+ throw new DispatchTickFailedError(error)
5516
+ })
5517
+ const initialPrinted = this.printReport(initial, false)
5518
+ await this.drainInFlight()
5519
+ // Tail stage: a spent invocation budget publishes nothing new; the next
5520
+ // invocation reports these settlements.
5521
+ const settledReports =
5522
+ this.opts.invocationBudget !== undefined && this.pastDeadline()
5523
+ ? []
5524
+ : await this.publishSettlementReports()
5525
+ let settledPrinted = false
5526
+ for (const report of settledReports) {
5527
+ settledPrinted = this.printReport(report, false) || settledPrinted
5528
+ }
5529
+ if (!initialPrinted && !settledPrinted) {
5530
+ this.printReport(emptyTickReport())
5531
+ }
5532
+ // One delivery pass per configured hook; the next invocation retries.
5533
+ if (!this.pastDeadline()) await this.drainHooksOnce()
5534
+ }
5535
+
5536
+ /** The bounded `--once` pass (hosted cron). The work pass runs under the
5537
+ * budget's work signal and is abandoned, not awaited, at the work deadline.
5538
+ * Teardown then runs as two independent racers bounded by the cleanup
5539
+ * deadline — durable provisioning abandonment beside the optional steps,
5540
+ * so a stall in one cannot skip the other — and the repository lease
5541
+ * release is bounded by the hard deadline. */
5542
+ private async boundedPass(budget: InvocationBudget): Promise<void> {
5543
+ try {
5544
+ this.startInput()
5545
+ this.startRendering()
5546
+ if (this.pastDeadline()) {
5547
+ this.deadlineStop = true
5548
+ return
5549
+ }
5550
+ const pass = await untilAborted(
5551
+ withInvocationSignal(budget.work, () => this.onePass()),
5552
+ budget.work,
5553
+ )
5554
+ if (!pass.settled || this.pastDeadline()) this.deadlineStop = true
5555
+ } finally {
5556
+ await this.boundedTeardown(budget)
5557
+ }
5558
+ }
5559
+
5560
+ /** The deferral hint's late-write scope: one write under the cleanup
5561
+ * signal, refused once that deadline has passed. */
5562
+ private teardownWrite(budget: InvocationBudget) {
5563
+ return <T>(write: () => Promise<T>): Promise<T> =>
5564
+ budget.cleanup.aborted
5565
+ ? Promise.reject(budget.cleanup.reason)
5566
+ : withInvocationSignal(budget.cleanup, write)
5567
+ }
5568
+
5569
+ private async boundedTeardown(budget: InvocationBudget): Promise<void> {
5570
+ // Whether or not the deadline fired, no launch may start during
5571
+ // teardown: provisioning abandonment runs beside execution teardown.
5572
+ this.onWorkDeadline()
5573
+ const provisioning = untilAborted(
5574
+ withInvocationSignal(budget.cleanup, () => this.dispatcher.stopProvisioning()),
5575
+ budget.cleanup,
5576
+ )
5577
+ const optional = untilAborted(
5578
+ withInvocationSignal(budget.cleanup, async () => {
5579
+ this.localHarvestShutdown.abort()
5580
+ await this.stopHooks()
5581
+ await this.stopBuildExecutions()
5582
+ await this.stopLocalHarvest()
5583
+ await this.stopHostedHarvest()
5584
+ await this.finishRendering()
5585
+ }),
5586
+ budget.cleanup,
5587
+ )
5588
+ const cleanup = await Promise.allSettled([provisioning, optional])
5589
+ await untilAborted(
5590
+ withInvocationSignal(budget.final, () => this.releaseRepoLease()),
5591
+ budget.final,
5592
+ )
5593
+ const failed = cleanup.find((result) => result.status === 'rejected')
5594
+ if (failed !== undefined) throw failed.reason
5595
+ }
5596
+
5323
5597
  async run(): Promise<void> {
5324
5598
  // Before the `--once` branch, so both modes report it exactly once.
5325
5599
  this.reportRoleDiagnostics()
@@ -5327,12 +5601,40 @@ class DispatchLoop {
5327
5601
  const missing = this.missingAccounts(this.wiring.inspectAccounts?.() ?? this.opts.env)
5328
5602
  if (missing.length) throw new MissingAccountCredentialsError(missing)
5329
5603
  }
5604
+ const budget = this.opts.once === true ? this.opts.invocationBudget : undefined
5605
+ if (budget === undefined) return this.supervise()
5606
+ if (budget.work.aborted) this.onWorkDeadline()
5607
+ else budget.work.addEventListener('abort', this.onWorkDeadline, { once: true })
5608
+ try {
5609
+ await this.supervise(budget)
5610
+ } finally {
5611
+ budget.work.removeEventListener('abort', this.onWorkDeadline)
5612
+ // The initial claim request failed, possibly after the server committed
5613
+ // it. The release is exact-holder, so it is harmless when nothing was
5614
+ // committed and never touches a peer's lease.
5615
+ if (this.repoLeaseClaimAmbiguous && this.repoLeaseHolder === undefined) {
5616
+ await untilAborted(
5617
+ withInvocationSignal(budget.final, () =>
5618
+ this.wiring.store.releaseRepoLease(this.repoIdentity, this.runId).catch(() => {}),
5619
+ ),
5620
+ budget.final,
5621
+ )
5622
+ }
5623
+ }
5624
+ }
5625
+
5626
+ private async supervise(budget?: InvocationBudget): Promise<void> {
5330
5627
  // Repository supervisor lease (§12): two invocations for one repository
5331
5628
  // never both act. A losing invocation records the yield and performs no
5332
5629
  // claims, launches, or publications. The holder is the invocation's
5333
5630
  // journaling run id — the same string every journal payload carries.
5334
5631
  const holder = this.runId
5335
5632
  if (!(await this.ensureRepoLease(holder))) {
5633
+ if (budget !== undefined && this.budgetStopped()) {
5634
+ // The claim was cut off by the work deadline, not refused by a peer.
5635
+ this.deadlineStop = true
5636
+ return
5637
+ }
5336
5638
  await this.recordTickYielded()
5337
5639
  if ((!this.dashboard && this.opts.kernelRunId === undefined) || this.opts.once) {
5338
5640
  const peer = (await this.wiring.store.getRepo(this.repoIdentity).catch(() => null))?.lease
@@ -5353,6 +5655,7 @@ class DispatchLoop {
5353
5655
  if (!this.dashboard) {
5354
5656
  this.say(`ab dispatch — one pass over ${this.opts.targetRepo} (capacity ${capacity})`)
5355
5657
  }
5658
+ if (budget !== undefined) return this.boundedPass(budget)
5356
5659
  // Render BEFORE the tick and until the drain finishes, so the operator
5357
5660
  // watches the initial pass's builds change state while they run. The
5358
5661
  // render loop only reads: `--once` still calls tick() exactly ONCE, so
@@ -5365,28 +5668,7 @@ class DispatchLoop {
5365
5668
  // lease and any provisioning state are released for the next
5366
5669
  // invocation.
5367
5670
  if (this.pastDeadline()) return
5368
- // One background triage read before the single tick, never inside it.
5369
- this.triageSampler?.poke()
5370
- const initial = await this.dispatcherTick(true).catch(async (error: unknown) => {
5371
- if (isRepositoryAuthorityLapse(error)) {
5372
- await this.settleAuthorityLapse()
5373
- return emptyTickReport()
5374
- }
5375
- await this.reportTickFailure(error)
5376
- throw error
5377
- })
5378
- const initialPrinted = this.printReport(initial, false)
5379
- await this.drainInFlight()
5380
- const settledReports = await this.publishSettlementReports()
5381
- let settledPrinted = false
5382
- for (const report of settledReports) {
5383
- settledPrinted = this.printReport(report, false) || settledPrinted
5384
- }
5385
- if (!initialPrinted && !settledPrinted) {
5386
- this.printReport(emptyTickReport())
5387
- }
5388
- // One delivery pass per configured hook; the next invocation retries.
5389
- if (!this.pastDeadline()) await this.drainHooksOnce()
5671
+ await this.onePass()
5390
5672
  } finally {
5391
5673
  this.localHarvestShutdown.abort()
5392
5674
  await this.stopHooks()
@@ -5419,15 +5701,19 @@ class DispatchLoop {
5419
5701
  let startup = true
5420
5702
  // Triage counts are sampled between ticks, never inside one: the read
5421
5703
  // runs in the background and the next publication carries its value.
5422
- this.triageSampler?.poke()
5704
+ // Both wait until the ticket source is prepared.
5705
+ if (this.ticketsPrepared || this.wiring.prepareTickets === undefined)
5706
+ this.triageSampler?.poke()
5423
5707
  while (!this.watchStopped && !this.superseded) {
5424
5708
  let failed = false
5425
5709
  try {
5710
+ await this.prepareTickets()
5426
5711
  const report = await this.dispatcherTick(startup)
5427
5712
  this.printReport(report, this.harvestInFlight === undefined)
5428
5713
  startup = false
5429
5714
  } catch (error) {
5430
5715
  if (this.forgePublicationFailed) throw error
5716
+ if (error instanceof FatalTicketPreparationError) throw error.cause
5431
5717
  if (isRepositoryAuthorityLapse(error)) {
5432
5718
  await this.settleAuthorityLapse()
5433
5719
  } else {
@@ -5435,7 +5721,7 @@ class DispatchLoop {
5435
5721
  await this.reportTickFailure(error)
5436
5722
  }
5437
5723
  }
5438
- this.triageSampler?.poke()
5724
+ if (this.ticketsPrepared) this.triageSampler?.poke()
5439
5725
  await this.syncHooks()
5440
5726
  if (this.watchStopped || this.superseded) break
5441
5727
  await sleep(failed || this.pendingTickFailure ? Math.max(intervalMs, 1000) : intervalMs)
@@ -5492,7 +5778,11 @@ async function fetchOriginModeConfig(
5492
5778
  env: opts.env,
5493
5779
  repository,
5494
5780
  exec: opts.exec,
5495
- ...(transport !== undefined ? { transport } : {}),
5781
+ ...(transport !== undefined
5782
+ ? { transport }
5783
+ : opts.invocationBudget !== undefined
5784
+ ? { fetchFn: budgetedFetch() }
5785
+ : {}),
5496
5786
  })
5497
5787
  const readFile = forge.readFile
5498
5788
  if (readFile === undefined) {
@@ -5602,6 +5892,12 @@ async function resolveOriginModeState(
5602
5892
  * path — is the served repository.
5603
5893
  */
5604
5894
  export async function abDispatch(opts: DispatchOpts): Promise<void> {
5895
+ // The invocation deadline also bounds every hosted retry this run causes.
5896
+ if (opts.deadlineAt === undefined) return abDispatchInScope(opts)
5897
+ return withRemoteRetryDeadline(opts.deadlineAt, () => abDispatchInScope(opts))
5898
+ }
5899
+
5900
+ async function abDispatchInScope(opts: DispatchOpts): Promise<void> {
5605
5901
  if (opts.kernelRunId === undefined && !launchContext(opts.env)) {
5606
5902
  opts = { ...opts, ...(await selectDispatchMode(opts)) }
5607
5903
  }
@@ -5682,6 +5978,33 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
5682
5978
  return
5683
5979
  }
5684
5980
  if (opts.dispatchedBy !== undefined) throw new Error('--dispatched-by requires --viewer')
5981
+ const budget = opts.invocationBudget
5982
+ if (budget === undefined) return dispatchKernelPath(opts)
5983
+ if (opts.once !== true) throw new Error('invocationBudget requires a one-pass (--once) dispatch')
5984
+ if (opts.deadlineAt !== undefined && opts.deadlineAt !== budget.workDeadlineAt) {
5985
+ throw new Error('invocationBudget: an explicit deadlineAt must equal its work deadline')
5986
+ }
5987
+ if (budget.work.aborted) throw new InvocationBudgetExhaustedError()
5988
+ const bounded: DispatchOpts = { ...opts, deadlineAt: budget.workDeadlineAt }
5989
+ try {
5990
+ // Startup and the whole work pass carry the work signal: every builtin
5991
+ // adapter request they make is cancelled at the work deadline. Teardown
5992
+ // re-enters with its own signals.
5993
+ await withInvocationSignal(budget.work, () => dispatchKernelPath(bounded))
5994
+ } catch (error) {
5995
+ // A budget stop after `run-started` returns normally from the kernel, so
5996
+ // an error escaping here past the work deadline happened before the run
5997
+ // started: nothing durable was claimed.
5998
+ if (budget.work.aborted && !(error instanceof InvocationBudgetExhaustedError)) {
5999
+ throw new InvocationBudgetExhaustedError(undefined, { cause: error })
6000
+ }
6001
+ throw error
6002
+ }
6003
+ }
6004
+
6005
+ /** `abDispatch` after the viewer branch: origin config, repository state,
6006
+ * the interactive frontend, or the in-process kernel. */
6007
+ async function dispatchKernelPath(opts: DispatchOpts): Promise<void> {
5685
6008
  if (opts.wire !== undefined && opts.nonStoreWire !== undefined) {
5686
6009
  throw new Error('dispatch wire and nonStoreWire are mutually exclusive')
5687
6010
  }
@@ -5917,8 +6240,12 @@ async function runDispatchKernel(
5917
6240
  // wiring or production wiring can open state or perform side effects.
5918
6241
  resolveForgeRegistration(config.forge, plugins)
5919
6242
  let wired: DispatchWiring
6243
+ const budget = resolvedOpts.invocationBudget
5920
6244
  if (resolvedOpts.nonStoreWire !== undefined) {
5921
- const opened = openStoreForRepoState(state, { env: resolvedOpts.env })
6245
+ const opened = openStoreForRepoState(state, {
6246
+ env: resolvedOpts.env,
6247
+ ...(budget !== undefined ? { openStore: budgetedProductionStore(budgetedFetch()) } : {}),
6248
+ })
5922
6249
  const ports = await resolvedOpts.nonStoreWire(config, resolvedOpts, state, plugins)
5923
6250
  wired = {
5924
6251
  ...ports,
@@ -6020,10 +6347,6 @@ async function runDispatchKernel(
6020
6347
  },
6021
6348
  )
6022
6349
 
6023
- // Launch flags are durable repository setters. Omission writes nothing, so
6024
- // another dispatcher cannot clobber the latest operator choice with a value
6025
- // it inferred at startup. Fresh-repository fallbacks live in the reducer.
6026
- await wiring.store.ensureRepo(state.repo)
6027
6350
  // Every own lifecycle append goes through one view, restored from snapshots
6028
6351
  // before the first of them, so a quiet invocation reads none of its own
6029
6352
  // rows back and the final flush covers `run-stopped` too.
@@ -6037,48 +6360,71 @@ async function runDispatchKernel(
6037
6360
  ...(web !== undefined ? { onRepositoryFacts: (facts) => web.publishFacts(facts) } : {}),
6038
6361
  })
6039
6362
  web?.attachStore(wiring.store)
6040
- await view.startJournal()
6041
- const actor = humanActor(buildControlUser(resolvedOpts.env))
6042
- if (resolvedOpts.intake !== undefined) {
6043
- await view.appendRepo(state.repo, {
6044
- actor,
6045
- type: 'dispatcher.intake-set',
6046
- payload: { enabled: resolvedOpts.intake, run: runId },
6047
- })
6048
- }
6363
+ let started: Awaited<ReturnType<RepoViewStore['appendRepoWithArtifacts']>>
6364
+ try {
6365
+ // Launch flags are durable repository setters. Omission writes nothing, so
6366
+ // another dispatcher cannot clobber the latest operator choice with a value
6367
+ // it inferred at startup. Fresh-repository fallbacks live in the reducer.
6368
+ await wiring.store.ensureRepo(state.repo)
6369
+ await view.startJournal()
6370
+ const actor = humanActor(buildControlUser(resolvedOpts.env))
6371
+ if (resolvedOpts.intake !== undefined) {
6372
+ await view.appendRepo(state.repo, {
6373
+ actor,
6374
+ type: 'dispatcher.intake-set',
6375
+ payload: { enabled: resolvedOpts.intake, run: runId },
6376
+ })
6377
+ }
6049
6378
 
6050
- const started = await view.appendRepoWithArtifacts(
6051
- state.repo,
6052
- [
6053
- {
6054
- kind: _effectiveConfigKind,
6055
- content: effectiveBuildConfigContent(config),
6056
- metadata: {
6057
- run: runId,
6058
- revision: 0,
6059
- ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6379
+ started = await view.appendRepoWithArtifacts(
6380
+ state.repo,
6381
+ [
6382
+ {
6383
+ kind: _effectiveConfigKind,
6384
+ content: effectiveBuildConfigContent(config),
6385
+ metadata: {
6386
+ run: runId,
6387
+ revision: 0,
6388
+ ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6389
+ },
6060
6390
  },
6391
+ ],
6392
+ (deposited) => {
6393
+ const artifact = deposited[0]
6394
+ if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6395
+ return {
6396
+ actor: DISPATCHER,
6397
+ type: 'dispatcher.run-started',
6398
+ payload: {
6399
+ run: runId,
6400
+ ...(launchContext(resolvedOpts.env)?.lineage
6401
+ ? { lineage: launchContext(resolvedOpts.env)!.lineage }
6402
+ : {}),
6403
+ pid: process.pid,
6404
+ host: hostname(),
6405
+ effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
6406
+ roleWarnings: startupWarnings(config, wiring.forge),
6407
+ },
6408
+ }
6061
6409
  },
6062
- ],
6063
- (deposited) => {
6064
- const artifact = deposited[0]
6065
- if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6066
- return {
6067
- actor: DISPATCHER,
6068
- type: 'dispatcher.run-started',
6069
- payload: {
6070
- run: runId,
6071
- ...(launchContext(resolvedOpts.env)?.lineage
6072
- ? { lineage: launchContext(resolvedOpts.env)!.lineage }
6073
- : {}),
6074
- pid: process.pid,
6075
- host: hostname(),
6076
- effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
6077
- roleWarnings: startupWarnings(config, wiring.forge),
6078
- },
6079
- }
6080
- },
6081
- )
6410
+ )
6411
+ } catch (error) {
6412
+ if (budget === undefined || !budget.work.aborted) throw error
6413
+ // The work deadline cut a startup write off. The `run-started` deposit
6414
+ // may still have committed with its response lost, so the bounded
6415
+ // canonical repository value decides whether this run exists.
6416
+ const recordedStart = await stopAmbiguousStart(budget, wiring.store, state.repo, runId)
6417
+ await finalStep(budget, async () => {
6418
+ await wiring.releaseAccounts?.()
6419
+ if (resolvedOpts.wire === undefined) await wiring.store.close()
6420
+ }).catch(() => {})
6421
+ if (!recordedStart) throw new InvocationBudgetExhaustedError(undefined, { cause: error })
6422
+ if (resolvedOpts.silent !== true)
6423
+ resolvedOpts.stdout(
6424
+ 'ab dispatch — invocation work deadline reached during startup; the run stopped, remaining work resumes next invocation',
6425
+ )
6426
+ return
6427
+ }
6082
6428
 
6083
6429
  try {
6084
6430
  await view.appendRepo(state.repo, {
@@ -6089,6 +6435,11 @@ async function runDispatchKernel(
6089
6435
 
6090
6436
  const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
6091
6437
  await loop.run()
6438
+ if (loop.stoppedAtDeadline && resolvedOpts.silent !== true) {
6439
+ resolvedOpts.stdout(
6440
+ 'ab dispatch — invocation work deadline reached; teardown complete, remaining work resumes next invocation',
6441
+ )
6442
+ }
6092
6443
  const stopRequest =
6093
6444
  resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted
6094
6445
  ? (await readDispatcherRunFacts(wiring.store, state.repo, runId)).value.stopRequest
@@ -6099,39 +6450,90 @@ async function runDispatchKernel(
6099
6450
  : typeof resolvedOpts.signal?.reason === 'string'
6100
6451
  ? resolvedOpts.signal.reason
6101
6452
  : undefined
6102
- await view.appendRepo(state.repo, {
6103
- actor: DISPATCHER,
6104
- type: 'dispatcher.run-stopped',
6105
- payload: {
6106
- run: runId,
6107
- outcome: 'normal',
6108
- exitCode: 0,
6109
- ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6110
- ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6111
- },
6112
- })
6113
- } catch (error) {
6114
- try {
6115
- await view.appendRepo(state.repo, {
6453
+ await finalStep(budget, () =>
6454
+ view.appendRepo(state.repo, {
6116
6455
  actor: DISPATCHER,
6117
6456
  type: 'dispatcher.run-stopped',
6118
6457
  payload: {
6119
6458
  run: runId,
6120
- outcome: 'abnormal',
6121
- exitCode: 1,
6122
- error: error instanceof Error ? error.message : String(error),
6459
+ outcome: 'normal',
6460
+ exitCode: 0,
6461
+ ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6462
+ ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6123
6463
  },
6124
- })
6464
+ }),
6465
+ )
6466
+ } catch (error) {
6467
+ // A bounded invocation past its work deadline stopped on budget, however
6468
+ // the adapter wrapped the abort: a clean stop, not a loss.
6469
+ const budgetStop = budget?.work.aborted === true
6470
+ const tickFailed = error instanceof DispatchTickFailedError
6471
+ const original = tickFailed ? error.cause : error
6472
+ try {
6473
+ await finalStep(budget, () =>
6474
+ view.appendRepo(state.repo, {
6475
+ actor: DISPATCHER,
6476
+ type: 'dispatcher.run-stopped',
6477
+ payload: budgetStop
6478
+ ? { run: runId, outcome: 'normal', exitCode: 0 }
6479
+ : {
6480
+ run: runId,
6481
+ outcome: tickFailed ? 'normal' : 'abnormal',
6482
+ exitCode: 1,
6483
+ error: original instanceof Error ? original.message : String(original),
6484
+ },
6485
+ }),
6486
+ )
6125
6487
  } catch {
6126
6488
  // Preserve the kernel failure; the supervising frontend records exit.
6127
6489
  }
6128
- throw error
6490
+ if (!budgetStop) throw original
6129
6491
  } finally {
6130
6492
  // Every append this invocation made, `run-stopped` included, is in the
6131
6493
  // view; leave the reduced state behind so the next cold process reads
6132
6494
  // only what is newer than it.
6495
+ await finalStep(budget, async () => {
6496
+ await wiring.releaseAccounts?.()
6497
+ if (resolvedOpts.wire === undefined) await wiring.store.close()
6498
+ })
6499
+ }
6500
+ }
6501
+
6502
+ /** A bounded invocation whose startup the work deadline cut off: when the
6503
+ * `run-started` deposit committed anyway, record this run's normal stop so
6504
+ * the journal never holds a start without a stop. One read of the reduced
6505
+ * `repositoryReadFacts` value (its recent runs), never history, then at most
6506
+ * one append, all under the final signal. True when the run had started. */
6507
+ async function stopAmbiguousStart(
6508
+ budget: InvocationBudget,
6509
+ store: BuildStore,
6510
+ repo: string,
6511
+ run: string,
6512
+ ): Promise<boolean> {
6513
+ let started = false
6514
+ await finalStep(budget, async () => {
6515
+ const recorded = await readDispatcherRunFacts(store, repo, run, false)
6516
+ if (recorded.value.start === undefined) return
6517
+ started = true
6518
+ await store.appendRepo(repo, {
6519
+ actor: DISPATCHER,
6520
+ type: 'dispatcher.run-stopped',
6521
+ payload: { run, outcome: 'normal', exitCode: 0 },
6522
+ })
6523
+ }).catch(() => {})
6524
+ return started
6525
+ }
6133
6526
 
6134
- await wiring.releaseAccounts?.()
6135
- if (resolvedOpts.wire === undefined) await wiring.store.close()
6527
+ /** Run a final teardown step: under the budget's `final` signal and bounded
6528
+ * by it when the invocation is bounded, else exactly as before. A step that
6529
+ * misses the hard deadline is abandoned, never awaited past it. */
6530
+ async function finalStep(
6531
+ budget: InvocationBudget | undefined,
6532
+ step: () => Promise<unknown>,
6533
+ ): Promise<void> {
6534
+ if (budget === undefined) {
6535
+ await step()
6536
+ return
6136
6537
  }
6538
+ await untilAborted(withInvocationSignal(budget.final, step), budget.final)
6137
6539
  }