@defrex/autobuild 1.11.1 → 1.13.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 (213) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +601 -203
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +32 -2
  5. package/docs/architecture.md +188 -57
  6. package/docs/assets/headline-wide.png +0 -0
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +120 -23
  9. package/docs/dispatcher.md +19 -8
  10. package/docs/integration-overview.md +1 -1
  11. package/docs/integration-tree.md +33 -18
  12. package/docs/merge-policy.md +7 -2
  13. package/docs/operating.md +5 -3
  14. package/docs/operator-api.md +48 -25
  15. package/docs/operator-surfaces.md +39 -3
  16. package/docs/optimization-nodes.md +10 -8
  17. package/docs/plugin-authoring.md +46 -18
  18. package/docs/remote-store-protocol.md +51 -12
  19. package/docs/remote-ticket-protocol.md +85 -38
  20. package/docs/restacking.md +48 -3
  21. package/docs/setup.md +2 -1
  22. package/docs/ticket-migration.md +2 -2
  23. package/docs/ticket-sources.md +23 -8
  24. package/docs/tickets.md +4 -4
  25. package/docs/troubleshooting.md +17 -2
  26. package/docs/verification.md +3 -1
  27. package/package.json +3 -3
  28. package/packages/core/src/cli/ambient-errors.ts +17 -0
  29. package/packages/core/src/cli/bounded-io.ts +174 -0
  30. package/packages/core/src/cli/build-control.ts +72 -6
  31. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  32. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  33. package/packages/core/src/cli/dashboard/model.ts +93 -29
  34. package/packages/core/src/cli/dashboard/poll.ts +231 -34
  35. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  36. package/packages/core/src/cli/dashboard/render.ts +14 -37
  37. package/packages/core/src/cli/dashboard/row-text.ts +26 -8
  38. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  39. package/packages/core/src/cli/dashboard/vocabulary.ts +165 -20
  40. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  41. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  42. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  43. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  44. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  45. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  46. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  47. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  48. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  49. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  50. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  51. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  52. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  53. package/packages/core/src/cli/dispatch.ts +595 -149
  54. package/packages/core/src/cli/env.ts +2 -15
  55. package/packages/core/src/cli/help.ts +43 -28
  56. package/packages/core/src/cli/main.ts +11 -7
  57. package/packages/core/src/cli/production-store.ts +102 -0
  58. package/packages/core/src/cli/publication-settlement.ts +4 -0
  59. package/packages/core/src/cli/remote-poll.ts +22 -5
  60. package/packages/core/src/cli/repo-state.ts +2 -3
  61. package/packages/core/src/cli/repository-status.ts +44 -28
  62. package/packages/core/src/cli/sessionless-store.ts +26 -0
  63. package/packages/core/src/cli/status.ts +188 -47
  64. package/packages/core/src/cli/store-opening.ts +26 -57
  65. package/packages/core/src/cli/store-ref.ts +6 -1
  66. package/packages/core/src/cli/ticket-start.ts +3 -3
  67. package/packages/core/src/cli/ticket.ts +12 -11
  68. package/packages/core/src/cli/wait.ts +8 -28
  69. package/packages/core/src/cli/watch.ts +113 -50
  70. package/packages/core/src/config/reference-metadata.ts +7 -1
  71. package/packages/core/src/config/reference.ts +5 -2
  72. package/packages/core/src/config/schema.ts +51 -16
  73. package/packages/core/src/distribution-packaging.ts +156 -18
  74. package/packages/core/src/events/catalog-identity.ts +28 -0
  75. package/packages/core/src/events/catalog.ts +3 -9
  76. package/packages/core/src/events/compatibility.ts +2 -30
  77. package/packages/core/src/events/payloads.ts +85 -14
  78. package/packages/core/src/events/policy.ts +3 -0
  79. package/packages/core/src/events/repository.ts +15 -4
  80. package/packages/core/src/events/sessions.ts +1 -1
  81. package/packages/core/src/events/validation-error.ts +12 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +36 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  92. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  93. package/packages/core/src/kernel/capacity-build.ts +21 -0
  94. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  95. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +578 -235
  97. package/packages/core/src/kernel/done-escalations.ts +269 -0
  98. package/packages/core/src/kernel/engine.ts +30 -17
  99. package/packages/core/src/kernel/integration-landing.ts +24 -4
  100. package/packages/core/src/kernel/integration-stack.ts +39 -0
  101. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  102. package/packages/core/src/kernel/log-index-value.ts +3 -0
  103. package/packages/core/src/kernel/log-index.ts +41 -2
  104. package/packages/core/src/kernel/measurement.ts +24 -0
  105. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  106. package/packages/core/src/kernel/read-facts.ts +8 -370
  107. package/packages/core/src/kernel/reducer-registry.ts +43 -125
  108. package/packages/core/src/kernel/reducer-revisions.ts +18 -0
  109. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  110. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  111. package/packages/core/src/kernel/reducer.ts +84 -16
  112. package/packages/core/src/kernel/reopen-state.ts +10 -0
  113. package/packages/core/src/kernel/repository-attention.ts +14 -5
  114. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  115. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  116. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  117. package/packages/core/src/kernel/verify-stages.ts +46 -7
  118. package/packages/core/src/operator/attention.ts +28 -3
  119. package/packages/core/src/operator/done-escalations.ts +38 -0
  120. package/packages/core/src/operator/presentation.ts +14 -1
  121. package/packages/core/src/operator/protocol.ts +8 -5
  122. package/packages/core/src/operator/query.ts +72 -57
  123. package/packages/core/src/operator/registry.ts +19 -15
  124. package/packages/core/src/operator/ticket-start.ts +8 -7
  125. package/packages/core/src/operator/tickets.ts +28 -9
  126. package/packages/core/src/plugin-sdk/index.ts +10 -0
  127. package/packages/core/src/plugins/manifest.ts +14 -1
  128. package/packages/core/src/ports/forge/create.ts +8 -0
  129. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  130. package/packages/core/src/ports/forge/github.ts +3 -0
  131. package/packages/core/src/ports/tickets/contract.ts +147 -76
  132. package/packages/core/src/ports/tickets/create.ts +47 -7
  133. package/packages/core/src/ports/tickets/fake.ts +8 -4
  134. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  135. package/packages/core/src/ports/tickets/file.ts +7 -3
  136. package/packages/core/src/ports/tickets/github.ts +1 -0
  137. package/packages/core/src/ports/tickets/grants.ts +11 -3
  138. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  139. package/packages/core/src/ports/tickets/linear.ts +28 -9
  140. package/packages/core/src/ports/tickets/migration.ts +4 -4
  141. package/packages/core/src/ports/tickets/operations.ts +4 -2
  142. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  143. package/packages/core/src/ports/tickets/priority.ts +127 -21
  144. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  145. package/packages/core/src/ports/tickets/remote.ts +104 -11
  146. package/packages/core/src/ports/tickets/revision.ts +5 -3
  147. package/packages/core/src/ports/tickets/search.ts +9 -0
  148. package/packages/core/src/ports/tickets/tree.ts +8 -6
  149. package/packages/core/src/ports/types.ts +30 -15
  150. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  151. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  152. package/packages/core/src/ports/workspace/create.ts +16 -3
  153. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  154. package/packages/core/src/ports/workspace/fake.ts +15 -3
  155. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  156. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  157. package/packages/core/src/processes/build-execution-state.ts +4 -0
  158. package/packages/core/src/processes/build-runner.ts +14 -1
  159. package/packages/core/src/processes/dispatcher.ts +777 -288
  160. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  161. package/packages/core/src/processes/execution-settlement.ts +1 -0
  162. package/packages/core/src/processes/harvest-runner.ts +12 -7
  163. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  164. package/packages/core/src/processes/invocation-budget.ts +176 -0
  165. package/packages/core/src/processes/publication-loss.ts +38 -3
  166. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  167. package/packages/core/src/store/contract.ts +81 -3
  168. package/packages/core/src/store/event-reads.ts +30 -1
  169. package/packages/core/src/store/local/capabilities.ts +115 -0
  170. package/packages/core/src/store/local/store.ts +86 -56
  171. package/packages/core/src/store/reduced-reads.ts +32 -1
  172. package/packages/core/src/store/reducer-value-read.ts +235 -0
  173. package/packages/core/src/store/reducer-value-shapes.json +6722 -6475
  174. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  175. package/packages/core/src/store/reducer-values.ts +36 -204
  176. package/packages/core/src/store/remote/client.ts +169 -29
  177. package/packages/core/src/store/remote/compatibility.ts +113 -56
  178. package/packages/core/src/store/remote/credentials.ts +4 -1
  179. package/packages/core/src/store/remote/protocol.ts +3 -0
  180. package/packages/core/src/store/remote/released-clients.json +22 -0
  181. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  182. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  183. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  184. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  185. package/packages/core/src/store/remote/retry.ts +406 -0
  186. package/packages/core/src/store/rollup-lease.ts +41 -0
  187. package/packages/core/src/store/rollups.ts +7 -38
  188. package/packages/core/src/store/snapshots.ts +1 -1
  189. package/packages/core/src/testing/dispatch-read-budget.ts +409 -14
  190. package/packages/core/src/testing/import-graph.ts +78 -0
  191. package/packages/core/src/testing/index.ts +2 -0
  192. package/packages/core/src/testing/invocation-budget.ts +42 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +602 -40
  194. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  195. package/packages/core/src/testing/slot-agreement.ts +52 -0
  196. package/packages/core/src/web/assets/app.js +5 -5
  197. package/packages/core/src/web/overview-source.ts +19 -6
  198. package/skills/guide/SKILL.md +245 -103
  199. package/skills/guide/references/integration-tree.md +33 -18
  200. package/skills/guide/references/merge-policy.md +7 -2
  201. package/skills/guide/references/operator-api.md +48 -25
  202. package/skills/guide/references/optimization-nodes.md +10 -8
  203. package/skills/guide/references/plugin-authoring.md +46 -18
  204. package/skills/guide/references/remote-store-protocol.md +51 -12
  205. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  206. package/skills/guide/references/restacking.md +48 -3
  207. package/skills/guide/references/setup.md +2 -1
  208. package/skills/guide/references/ticket-migration.md +2 -2
  209. package/skills/operate/SKILL.md +114 -65
  210. package/skills/plan/SKILL.md +4 -3
  211. package/skills/spec/SKILL.md +9 -5
  212. package/skills/tickets/SKILL.md +25 -17
  213. package/templates/hosted-service/package.json +2 -2
@@ -18,7 +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 { migrationIdentity } from '../kernel/ticket-migrations'
21
+ import { isRecoveryDeferred } from '../ports/workspace/recovery-step'
22
22
  import { recordRuntimeRollback } from './dispatch-handoff'
23
23
  import { syncRollbackRetention } from './dispatch-runtime-use'
24
24
  import { dirname as runtimeDirname } from 'node:path'
@@ -32,6 +32,7 @@ import { authorizeRemoteHandoffs, recoverDispatchDrain } from '../kernel/dispatc
32
32
  import { distributionRoot } from '../distribution'
33
33
  import { readDistributionIdentity } from './installation'
34
34
  import { launchContext } from './dispatch-launch-contract'
35
+ import { observeYield, watchForYieldRequest } from './dispatch-yield-observer'
35
36
  import { DispatchUpgradeController } from './dispatch-upgrade-controller'
36
37
  import { resolveUpgradeTarget } from './dispatch-upgrade-target'
37
38
  import { prepareUpgrade } from './dispatch-upgrade-install'
@@ -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
@@ -1510,6 +1600,8 @@ class DispatchLoop {
1510
1600
 
1511
1601
  private dispatcherTick(resumeCurrent: boolean): Promise<Awaited<ReturnType<Dispatcher['tick']>>> {
1512
1602
  return this.serialize(async () => {
1603
+ // The yield observer may have accepted while this tick was queued.
1604
+ if (this.retirement !== undefined) return emptyTickReport()
1513
1605
  // Refresh before every watch decision. The owner publishes atomically;
1514
1606
  // everything below captures the resulting one snapshot for this tick.
1515
1607
  await this.flushPendingTickFailure()
@@ -1568,6 +1660,9 @@ class DispatchLoop {
1568
1660
  // remaining budget cannot cover them (bounded overrun, one in-flight
1569
1661
  // transport call). Watch mode has no deadline ⇒ absent ⇒ unbounded.
1570
1662
  ...(this.opts.deadlineAt !== undefined ? { deadlineAt: this.opts.deadlineAt } : {}),
1663
+ ...(this.opts.invocationBudget !== undefined
1664
+ ? { workSignal: this.opts.invocationBudget.work }
1665
+ : {}),
1571
1666
  })
1572
1667
  const publishedReport: TickReport = {
1573
1668
  ...report,
@@ -2673,6 +2768,7 @@ class DispatchLoop {
2673
2768
  }
2674
2769
 
2675
2770
  const { store, tickets, runtimes, ids, uuids, clock, storeRef, token } = this.wiring
2771
+ const fetchFn = this.wiring.budgetSeams?.fetchFn
2676
2772
  const harvestDeps = {
2677
2773
  shutdownSignal: AbortSignal.any([
2678
2774
  this.localHarvestShutdown.signal,
@@ -2691,6 +2787,7 @@ class DispatchLoop {
2691
2787
  uuids,
2692
2788
  clock,
2693
2789
  instance: `${this.host}-harvest-${ids('inst')}`,
2790
+ ...(fetchFn !== undefined ? { fetchFn } : {}),
2694
2791
  ...(this.repoLeaseHolder !== undefined ? { leaseHolder: this.repoLeaseHolder } : {}),
2695
2792
  holdsAuthority: () => this.holdsRepoAuthority(),
2696
2793
  sessionEnv: {
@@ -2721,6 +2818,7 @@ class DispatchLoop {
2721
2818
  this.repoIdentity,
2722
2819
  harvestDeps.instance,
2723
2820
  'runner',
2821
+ fetchFn,
2724
2822
  )
2725
2823
  let remoteRunnerStore: RemoteBuildStore | undefined
2726
2824
  let preparedRun: { run: string } | undefined
@@ -2754,8 +2852,13 @@ class DispatchLoop {
2754
2852
  id: prepared.run,
2755
2853
  leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2756
2854
  },
2855
+ fetchFn,
2757
2856
  )
2758
- remoteRunnerStore = new RemoteBuildStore({ url: storeRef, token: buildScoped })
2857
+ remoteRunnerStore = new RemoteBuildStore({
2858
+ url: storeRef,
2859
+ token: buildScoped,
2860
+ ...(fetchFn !== undefined ? { fetchFn } : {}),
2861
+ })
2759
2862
  }
2760
2863
  const sessionEnv = {
2761
2864
  ...harvestDeps.sessionEnv,
@@ -2765,11 +2868,12 @@ class DispatchLoop {
2765
2868
  }
2766
2869
  let renewalFailure: unknown
2767
2870
  renew = setInterval(() => {
2768
- void ticketGrantRequest(ticketUrl, issued.token, {
2769
- action: 'renew',
2770
- repo: this.repoIdentity,
2771
- id: issued.grant.id,
2772
- }).catch((error) => {
2871
+ void ticketGrantRequest(
2872
+ ticketUrl,
2873
+ issued.token,
2874
+ { action: 'renew', repo: this.repoIdentity, id: issued.grant.id },
2875
+ fetchFn,
2876
+ ).catch((error) => {
2773
2877
  renewalFailure = error
2774
2878
  })
2775
2879
  }, 60_000)
@@ -2779,7 +2883,10 @@ class DispatchLoop {
2779
2883
  this.opts.targetRepo,
2780
2884
  undefined,
2781
2885
  this.wiring.plugins,
2782
- this.opts.repository !== undefined ? { repository: this.repoIdentity } : {},
2886
+ {
2887
+ ...(this.opts.repository !== undefined ? { repository: this.repoIdentity } : {}),
2888
+ ...this.wiring.budgetSeams,
2889
+ },
2783
2890
  )
2784
2891
  const result = await new HarvestRunner({
2785
2892
  ...harvestDeps,
@@ -2802,6 +2909,9 @@ class DispatchLoop {
2802
2909
  await remoteRunnerStore.close()
2803
2910
  }
2804
2911
  } finally {
2912
+ // Revocation is compensation, not new work: it keeps global fetch
2913
+ // and its own 15 s bound so a work-deadline stop still releases
2914
+ // the grant rather than leaving it to expiry.
2805
2915
  await ticketGrantRequest(ticketUrl, ticketToken, {
2806
2916
  action: 'revoke',
2807
2917
  repo: this.repoIdentity,
@@ -2824,14 +2934,23 @@ class DispatchLoop {
2824
2934
  leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2825
2935
  },
2826
2936
  })
2827
- const scoped = await (this.wiring.credentialIssuer ?? delegateCredential)(storeRef, token, {
2828
- kind: 'harvest-runner',
2829
- execution: harvestDeps.instance,
2830
- repo: this.repoIdentity,
2831
- id: prepared.run,
2832
- leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2937
+ const scoped = await (this.wiring.credentialIssuer ?? delegateCredential)(
2938
+ storeRef,
2939
+ token,
2940
+ {
2941
+ kind: 'harvest-runner',
2942
+ execution: harvestDeps.instance,
2943
+ repo: this.repoIdentity,
2944
+ id: prepared.run,
2945
+ leaseHolder: this.repoLeaseHolder ?? harvestDeps.instance,
2946
+ },
2947
+ fetchFn,
2948
+ )
2949
+ const runnerStore = new RemoteBuildStore({
2950
+ url: storeRef,
2951
+ token: scoped,
2952
+ ...(fetchFn !== undefined ? { fetchFn } : {}),
2833
2953
  })
2834
- const runnerStore = new RemoteBuildStore({ url: storeRef, token: scoped })
2835
2954
  try {
2836
2955
  const runnerTickets =
2837
2956
  harvestDeps.config.tickets.source === 'hosted'
@@ -2850,7 +2969,10 @@ class DispatchLoop {
2850
2969
  storeRef,
2851
2970
  }).localStateRoot,
2852
2971
  this.wiring.plugins,
2853
- this.opts.repository !== undefined ? { repository: this.repoIdentity } : {},
2972
+ {
2973
+ ...(this.opts.repository !== undefined ? { repository: this.repoIdentity } : {}),
2974
+ ...this.wiring.budgetSeams,
2975
+ },
2854
2976
  )
2855
2977
  : harvestDeps.tickets
2856
2978
  return await new HarvestRunner({
@@ -3011,6 +3133,7 @@ class DispatchLoop {
3011
3133
  id: prepared.run,
3012
3134
  leaseHolder: this.repoLeaseHolder ?? execution,
3013
3135
  },
3136
+ this.wiring.budgetSeams?.fetchFn,
3014
3137
  ),
3015
3138
  }
3016
3139
  : undefined
@@ -3032,14 +3155,16 @@ class DispatchLoop {
3032
3155
  repo,
3033
3156
  execution,
3034
3157
  'runner',
3158
+ this.wiring.budgetSeams?.fetchFn,
3035
3159
  )
3036
3160
  ticketAuthority = { url: ticketConfig.url, token: issued.token, id: issued.grant.id }
3037
3161
  renewTickets = setInterval(() => {
3038
- void ticketGrantRequest(ticketConfig.url!, issued.token, {
3039
- action: 'renew',
3040
- repo,
3041
- id: issued.grant.id,
3042
- }).catch(() => {
3162
+ void ticketGrantRequest(
3163
+ ticketConfig.url!,
3164
+ issued.token,
3165
+ { action: 'renew', repo, id: issued.grant.id },
3166
+ this.wiring.budgetSeams?.fetchFn,
3167
+ ).catch(() => {
3043
3168
  // Expiry fails subsequent reads closed; the guest cannot regain project authority.
3044
3169
  })
3045
3170
  }, 60_000)
@@ -3142,6 +3267,7 @@ class DispatchLoop {
3142
3267
  }
3143
3268
  } finally {
3144
3269
  if (renewTickets) clearInterval(renewTickets)
3270
+ // Compensation keeps global fetch and its own 15 s bound (see above).
3145
3271
  if (ticketAuthority && !detached.value)
3146
3272
  await ticketGrantRequest(ticketAuthority.url, ticketAuthority.token, {
3147
3273
  action: 'revoke',
@@ -3395,6 +3521,25 @@ class DispatchLoop {
3395
3521
  | { original: string; first: string; last: string; count: number }
3396
3522
  | undefined
3397
3523
 
3524
+ private ticketsPrepared = false
3525
+
3526
+ /** The ticket source's deferred preparation, at the tick boundary until it
3527
+ * succeeds once. A transient failure is an ordinary tick failure (the next
3528
+ * tick retries it); any other failure is fatal to the run. */
3529
+ private async prepareTickets(): Promise<void> {
3530
+ if (this.ticketsPrepared) return
3531
+ const prepare = this.wiring.prepareTickets
3532
+ if (prepare !== undefined) {
3533
+ try {
3534
+ await prepare()
3535
+ } catch (error) {
3536
+ if (isTransientRemoteFailure(error)) throw error
3537
+ throw new FatalTicketPreparationError(error)
3538
+ }
3539
+ }
3540
+ this.ticketsPrepared = true
3541
+ }
3542
+
3398
3543
  /** A tick stopped by a fenced effect is not a failed tick: publish no
3399
3544
  * `tick-failed`, abandon the open boundary (a successor's or our own next
3400
3545
  * `beginRepoTick` overwrites it), and resolve the lease. That either stops
@@ -3536,7 +3681,12 @@ class DispatchLoop {
3536
3681
  await this.settlePendingPublication(slug)
3537
3682
  } catch (error) {
3538
3683
  // A lapsed run publishes nothing; the successor settles from durable facts.
3539
- if (!(error instanceof ForgeRequestDeferred) && !isRepositoryAuthorityLapse(error))
3684
+ // A deadline-deferred recovery parks the request for a later invocation.
3685
+ if (
3686
+ !(error instanceof ForgeRequestDeferred) &&
3687
+ !isRecoveryDeferred(error) &&
3688
+ !isRepositoryAuthorityLapse(error)
3689
+ )
3540
3690
  throw error
3541
3691
  }
3542
3692
  }
@@ -3550,6 +3700,10 @@ class DispatchLoop {
3550
3700
  cleanupPending: boolean
3551
3701
  identity?: BuildExecutionHandle['identity']
3552
3702
  }): Promise<void> {
3703
+ // Work abandoned at a bounded invocation's deadline records no failure:
3704
+ // the write would be cancelled anyway, and the abort is not a failure.
3705
+ const work = this.opts.invocationBudget?.work
3706
+ if (work?.aborted && invocationSignal() === work) return
3553
3707
  if (await this.dispatcher.holdForMissingAccounts(input.error)) return
3554
3708
  // The failed executor may have appended through its own handle.
3555
3709
  await this.repoView.refreshBuild(input.slug)
@@ -3633,6 +3787,7 @@ class DispatchLoop {
3633
3787
  this.wiring.storeRef,
3634
3788
  this.wiring.token,
3635
3789
  { kind: 'build-runner', id: slug },
3790
+ this.wiring.budgetSeams?.fetchFn,
3636
3791
  ),
3637
3792
  }
3638
3793
  : undefined
@@ -3784,7 +3939,7 @@ class DispatchLoop {
3784
3939
  if (this.activeBuildRuns.get(slug)?.reservation === reservation) {
3785
3940
  this.activeBuildRuns.delete(slug)
3786
3941
  }
3787
- if (error instanceof ForgeRequestDeferred) {
3942
+ if (error instanceof ForgeRequestDeferred || isRecoveryDeferred(error)) {
3788
3943
  if (leaseClaimed) await this.repoView.releaseLease(slug, instance)
3789
3944
  await this.repoView.refreshBuild(slug)
3790
3945
  return 'already-active'
@@ -4271,7 +4426,7 @@ class DispatchLoop {
4271
4426
  (this.opts.once !== true && this.refresh !== undefined && !this.refresh.admitted)
4272
4427
  )
4273
4428
  return
4274
- if (this.opts.once !== true) this.refresh?.activity(buildSnapshot.states.size > 0)
4429
+ if (this.opts.once !== true) this.refresh?.activity(hasActiveBuilds(buildSnapshot))
4275
4430
 
4276
4431
  // Polling continues while the operator types. Keep the prompt bound to the
4277
4432
  // captured build/escalations, shrink it around externally answered ids, and
@@ -4315,12 +4470,8 @@ class DispatchLoop {
4315
4470
  buildSnapshot.capacityBuilds ?? [],
4316
4471
  configSnapshot.config.capacity,
4317
4472
  this.wiring.clock(),
4318
- migrationIdentity(
4319
- repositoryEvents.ticketMigrations,
4320
- configSnapshot.config.tickets.source,
4321
- ),
4322
4473
  {
4323
- urgentClaims: urgentClaimDemand(repositoryEvents),
4474
+ claims: claimDemand(repositoryEvents),
4324
4475
  openPrs: {
4325
4476
  policy: configSnapshot.config.policy,
4326
4477
  engaged: repositoryEvents.openPrBackpressure !== undefined,
@@ -4580,8 +4731,13 @@ class DispatchLoop {
4580
4731
  const requestedAt = this.wiring.clock().getTime()
4581
4732
  const granted = await this.wiring.store
4582
4733
  .claimRepoLease(this.repoIdentity, holder, lease.ttlMs)
4583
- .catch(() => false)
4734
+ .catch(() => {
4735
+ // A rejected claim request may still have committed server-side.
4736
+ this.repoLeaseClaimAmbiguous = true
4737
+ return false
4738
+ })
4584
4739
  if (!granted || this.superseded) return false
4740
+ this.repoLeaseClaimAmbiguous = false
4585
4741
  this.leaseGeneration++
4586
4742
  this.heldLease = lease
4587
4743
  this.repoLeaseValidUntil = requestedAt + lease.ttlMs
@@ -4699,6 +4855,10 @@ class DispatchLoop {
4699
4855
  * lease no longer renewable hands the decision to the resolver; it never
4700
4856
  * concludes takeover by itself. */
4701
4857
  private restartRepoLeaseHeartbeat(): void {
4858
+ // In a bounded invocation the timer is created inside the work phase, so
4859
+ // its beats inherit the work signal and fail after the work deadline. The
4860
+ // unreachable-store branch below tolerates that, the lease TTL far
4861
+ // exceeds the teardown reserve, and the release runs under `final`.
4702
4862
  this.stopRepoLeaseHeartbeat()
4703
4863
  const holder = this.repoLeaseHolder
4704
4864
  const lease = this.heldLease
@@ -4829,6 +4989,16 @@ class DispatchLoop {
4829
4989
  request.lineage !== launch.lineage ||
4830
4990
  !this.currentConfig().config.upgrade.automatic
4831
4991
  ) {
4992
+ // A prepared target still awaiting its request: observe for it between
4993
+ // ticks. Arming reuses the read above and never accepts by itself.
4994
+ if (
4995
+ state?.prepared &&
4996
+ state.prepared.payload.lineage === launch.lineage &&
4997
+ !state.failure &&
4998
+ !state.handoff &&
4999
+ !state.request
5000
+ )
5001
+ this.armYieldObservation(state.prepared.payload.correlation, launch.lineage)
4832
5002
  this.abandonUpgradeYield()
4833
5003
  return false
4834
5004
  }
@@ -4938,6 +5108,59 @@ class DispatchLoop {
4938
5108
  return this.adoptUpgradeYield(accepted)
4939
5109
  }
4940
5110
 
5111
+ private yieldObservation?: { correlation: string; stop: AbortController }
5112
+ /** A preparation observed to its step limit is left to ordinary ticks, so
5113
+ * re-arming from a tick cannot extend the observation indefinitely. */
5114
+ private exhaustedYieldObservation?: string
5115
+
5116
+ /** While this run has a prepared target outstanding, observe durable state
5117
+ * for its yield request between ticks at a bounded cadence, and attempt
5118
+ * acceptance through the same serialization as ticks. The observation only
5119
+ * decides when to call `acceptUpgradeYield()`, which re-reads and validates
5120
+ * durable state; ordinary tick cadence is unchanged. */
5121
+ private armYieldObservation(correlation: string, lineage: string): void {
5122
+ if (
5123
+ this.opts.once === true ||
5124
+ this.watchStopped ||
5125
+ this.superseded ||
5126
+ this.retirement !== undefined
5127
+ )
5128
+ return
5129
+ if (
5130
+ this.yieldObservation?.correlation === correlation ||
5131
+ this.exhaustedYieldObservation === correlation
5132
+ )
5133
+ return
5134
+ this.yieldObservation?.stop.abort()
5135
+ const stop = new AbortController()
5136
+ const observation = { correlation, stop }
5137
+ this.yieldObservation = observation
5138
+ // The sleep and the cancellation listen to the same stop sources, so an
5139
+ // interrupted sleep never becomes a back-to-back read.
5140
+ const signals = [stop.signal, this.opts.signal, this.inputStop.signal].filter(
5141
+ (signal): signal is AbortSignal => signal !== undefined,
5142
+ )
5143
+ void watchForYieldRequest({
5144
+ observe: () =>
5145
+ observeYield(this.wiring.store, this.repoIdentity, this.runId, correlation, lineage),
5146
+ accept: () =>
5147
+ this.serialize(async () => {
5148
+ if (this.retirement !== undefined || this.watchStopped || this.superseded) return
5149
+ await this.refreshConfig()
5150
+ await this.acceptUpgradeYield()
5151
+ }),
5152
+ sleep: (ms) => interruptibleSleep(ms, signals),
5153
+ signal: AbortSignal.any(signals),
5154
+ })
5155
+ .then((outcome) => {
5156
+ if (outcome === 'exhausted') this.exhaustedYieldObservation = correlation
5157
+ })
5158
+ .catch(() => {})
5159
+ .finally(() => {
5160
+ if (this.yieldObservation === observation) this.yieldObservation = undefined
5161
+ })
5162
+ }
5163
+
4941
5164
  /** Repository authority may transfer only from a current holder. A record
4942
5165
  * naming another run, or no record, means a peer replaced us. An expired
4943
5166
  * lease that still names us is resolved like any other lapse. */
@@ -5245,6 +5468,7 @@ class DispatchLoop {
5245
5468
  type: 'dispatcher.target-prepared',
5246
5469
  payload: handoff,
5247
5470
  })
5471
+ this.armYieldObservation(handoff.correlation, launch.lineage!)
5248
5472
  return true
5249
5473
  }),
5250
5474
  })
@@ -5258,6 +5482,99 @@ class DispatchLoop {
5258
5482
  this.upgradeController.start()
5259
5483
  }
5260
5484
 
5485
+ /** The single `--once` pass: one tick, its drain, settlement publication,
5486
+ * and one delivery pass per configured hook. */
5487
+ private async onePass(): Promise<void> {
5488
+ // Prepare tickets before the background triage read and single tick.
5489
+ const initial = await this.prepareTickets()
5490
+ .then(() => {
5491
+ this.triageSampler?.poke()
5492
+ return this.dispatcherTick(true)
5493
+ })
5494
+ .catch(async (error: unknown) => {
5495
+ if (isRepositoryAuthorityLapse(error)) {
5496
+ await this.settleAuthorityLapse()
5497
+ return emptyTickReport()
5498
+ }
5499
+ // A bounded invocation's work deadline cancelled the tick: a budget
5500
+ // stop, never a tick failure.
5501
+ if (this.budgetStopped()) return emptyTickReport()
5502
+ if (error instanceof FatalTicketPreparationError) throw error.cause
5503
+ await this.reportTickFailure(error)
5504
+ if (this.forgePublicationFailed || this.pendingTickFailure !== undefined) throw error
5505
+ throw new DispatchTickFailedError(error)
5506
+ })
5507
+ const initialPrinted = this.printReport(initial, false)
5508
+ await this.drainInFlight()
5509
+ // Tail stage: a spent invocation budget publishes nothing new; the next
5510
+ // invocation reports these settlements.
5511
+ const settledReports =
5512
+ this.opts.invocationBudget !== undefined && this.pastDeadline()
5513
+ ? []
5514
+ : await this.publishSettlementReports()
5515
+ let settledPrinted = false
5516
+ for (const report of settledReports) {
5517
+ settledPrinted = this.printReport(report, false) || settledPrinted
5518
+ }
5519
+ if (!initialPrinted && !settledPrinted) {
5520
+ this.printReport(emptyTickReport())
5521
+ }
5522
+ // One delivery pass per configured hook; the next invocation retries.
5523
+ if (!this.pastDeadline()) await this.drainHooksOnce()
5524
+ }
5525
+
5526
+ /** The bounded `--once` pass (hosted cron). The work pass runs under the
5527
+ * budget's work signal and is abandoned, not awaited, at the work deadline.
5528
+ * Teardown then runs as two independent racers bounded by the cleanup
5529
+ * deadline — durable provisioning abandonment beside the optional steps,
5530
+ * so a stall in one cannot skip the other — and the repository lease
5531
+ * release is bounded by the hard deadline. */
5532
+ private async boundedPass(budget: InvocationBudget): Promise<void> {
5533
+ try {
5534
+ this.startInput()
5535
+ this.startRendering()
5536
+ if (this.pastDeadline()) {
5537
+ this.deadlineStop = true
5538
+ return
5539
+ }
5540
+ const pass = await untilAborted(
5541
+ withInvocationSignal(budget.work, () => this.onePass()),
5542
+ budget.work,
5543
+ )
5544
+ if (!pass.settled || this.pastDeadline()) this.deadlineStop = true
5545
+ } finally {
5546
+ await this.boundedTeardown(budget)
5547
+ }
5548
+ }
5549
+
5550
+ private async boundedTeardown(budget: InvocationBudget): Promise<void> {
5551
+ // Whether or not the deadline fired, no launch may start during
5552
+ // teardown: provisioning abandonment runs beside execution teardown.
5553
+ this.onWorkDeadline()
5554
+ const provisioning = untilAborted(
5555
+ withInvocationSignal(budget.cleanup, () => this.dispatcher.stopProvisioning()),
5556
+ budget.cleanup,
5557
+ )
5558
+ const optional = untilAborted(
5559
+ withInvocationSignal(budget.cleanup, async () => {
5560
+ this.localHarvestShutdown.abort()
5561
+ await this.stopHooks()
5562
+ await this.stopBuildExecutions()
5563
+ await this.stopLocalHarvest()
5564
+ await this.stopHostedHarvest()
5565
+ await this.finishRendering()
5566
+ }),
5567
+ budget.cleanup,
5568
+ )
5569
+ const cleanup = await Promise.allSettled([provisioning, optional])
5570
+ await untilAborted(
5571
+ withInvocationSignal(budget.final, () => this.releaseRepoLease()),
5572
+ budget.final,
5573
+ )
5574
+ const failed = cleanup.find((result) => result.status === 'rejected')
5575
+ if (failed !== undefined) throw failed.reason
5576
+ }
5577
+
5261
5578
  async run(): Promise<void> {
5262
5579
  // Before the `--once` branch, so both modes report it exactly once.
5263
5580
  this.reportRoleDiagnostics()
@@ -5265,12 +5582,40 @@ class DispatchLoop {
5265
5582
  const missing = this.missingAccounts(this.wiring.inspectAccounts?.() ?? this.opts.env)
5266
5583
  if (missing.length) throw new MissingAccountCredentialsError(missing)
5267
5584
  }
5585
+ const budget = this.opts.once === true ? this.opts.invocationBudget : undefined
5586
+ if (budget === undefined) return this.supervise()
5587
+ if (budget.work.aborted) this.onWorkDeadline()
5588
+ else budget.work.addEventListener('abort', this.onWorkDeadline, { once: true })
5589
+ try {
5590
+ await this.supervise(budget)
5591
+ } finally {
5592
+ budget.work.removeEventListener('abort', this.onWorkDeadline)
5593
+ // The initial claim request failed, possibly after the server committed
5594
+ // it. The release is exact-holder, so it is harmless when nothing was
5595
+ // committed and never touches a peer's lease.
5596
+ if (this.repoLeaseClaimAmbiguous && this.repoLeaseHolder === undefined) {
5597
+ await untilAborted(
5598
+ withInvocationSignal(budget.final, () =>
5599
+ this.wiring.store.releaseRepoLease(this.repoIdentity, this.runId).catch(() => {}),
5600
+ ),
5601
+ budget.final,
5602
+ )
5603
+ }
5604
+ }
5605
+ }
5606
+
5607
+ private async supervise(budget?: InvocationBudget): Promise<void> {
5268
5608
  // Repository supervisor lease (§12): two invocations for one repository
5269
5609
  // never both act. A losing invocation records the yield and performs no
5270
5610
  // claims, launches, or publications. The holder is the invocation's
5271
5611
  // journaling run id — the same string every journal payload carries.
5272
5612
  const holder = this.runId
5273
5613
  if (!(await this.ensureRepoLease(holder))) {
5614
+ if (budget !== undefined && this.budgetStopped()) {
5615
+ // The claim was cut off by the work deadline, not refused by a peer.
5616
+ this.deadlineStop = true
5617
+ return
5618
+ }
5274
5619
  await this.recordTickYielded()
5275
5620
  if ((!this.dashboard && this.opts.kernelRunId === undefined) || this.opts.once) {
5276
5621
  const peer = (await this.wiring.store.getRepo(this.repoIdentity).catch(() => null))?.lease
@@ -5291,6 +5636,7 @@ class DispatchLoop {
5291
5636
  if (!this.dashboard) {
5292
5637
  this.say(`ab dispatch — one pass over ${this.opts.targetRepo} (capacity ${capacity})`)
5293
5638
  }
5639
+ if (budget !== undefined) return this.boundedPass(budget)
5294
5640
  // Render BEFORE the tick and until the drain finishes, so the operator
5295
5641
  // watches the initial pass's builds change state while they run. The
5296
5642
  // render loop only reads: `--once` still calls tick() exactly ONCE, so
@@ -5303,28 +5649,7 @@ class DispatchLoop {
5303
5649
  // lease and any provisioning state are released for the next
5304
5650
  // invocation.
5305
5651
  if (this.pastDeadline()) return
5306
- // One background triage read before the single tick, never inside it.
5307
- this.triageSampler?.poke()
5308
- const initial = await this.dispatcherTick(true).catch(async (error: unknown) => {
5309
- if (isRepositoryAuthorityLapse(error)) {
5310
- await this.settleAuthorityLapse()
5311
- return emptyTickReport()
5312
- }
5313
- await this.reportTickFailure(error)
5314
- throw error
5315
- })
5316
- const initialPrinted = this.printReport(initial, false)
5317
- await this.drainInFlight()
5318
- const settledReports = await this.publishSettlementReports()
5319
- let settledPrinted = false
5320
- for (const report of settledReports) {
5321
- settledPrinted = this.printReport(report, false) || settledPrinted
5322
- }
5323
- if (!initialPrinted && !settledPrinted) {
5324
- this.printReport(emptyTickReport())
5325
- }
5326
- // One delivery pass per configured hook; the next invocation retries.
5327
- if (!this.pastDeadline()) await this.drainHooksOnce()
5652
+ await this.onePass()
5328
5653
  } finally {
5329
5654
  this.localHarvestShutdown.abort()
5330
5655
  await this.stopHooks()
@@ -5357,15 +5682,19 @@ class DispatchLoop {
5357
5682
  let startup = true
5358
5683
  // Triage counts are sampled between ticks, never inside one: the read
5359
5684
  // runs in the background and the next publication carries its value.
5360
- this.triageSampler?.poke()
5685
+ // Both wait until the ticket source is prepared.
5686
+ if (this.ticketsPrepared || this.wiring.prepareTickets === undefined)
5687
+ this.triageSampler?.poke()
5361
5688
  while (!this.watchStopped && !this.superseded) {
5362
5689
  let failed = false
5363
5690
  try {
5691
+ await this.prepareTickets()
5364
5692
  const report = await this.dispatcherTick(startup)
5365
5693
  this.printReport(report, this.harvestInFlight === undefined)
5366
5694
  startup = false
5367
5695
  } catch (error) {
5368
5696
  if (this.forgePublicationFailed) throw error
5697
+ if (error instanceof FatalTicketPreparationError) throw error.cause
5369
5698
  if (isRepositoryAuthorityLapse(error)) {
5370
5699
  await this.settleAuthorityLapse()
5371
5700
  } else {
@@ -5373,7 +5702,7 @@ class DispatchLoop {
5373
5702
  await this.reportTickFailure(error)
5374
5703
  }
5375
5704
  }
5376
- this.triageSampler?.poke()
5705
+ if (this.ticketsPrepared) this.triageSampler?.poke()
5377
5706
  await this.syncHooks()
5378
5707
  if (this.watchStopped || this.superseded) break
5379
5708
  await sleep(failed || this.pendingTickFailure ? Math.max(intervalMs, 1000) : intervalMs)
@@ -5383,6 +5712,7 @@ class DispatchLoop {
5383
5712
  }
5384
5713
  } finally {
5385
5714
  this.localHarvestShutdown.abort()
5715
+ this.yieldObservation?.stop.abort()
5386
5716
  await this.upgradeController?.stop()
5387
5717
  await this.stopHooks()
5388
5718
  if (this.retirement) {
@@ -5429,7 +5759,11 @@ async function fetchOriginModeConfig(
5429
5759
  env: opts.env,
5430
5760
  repository,
5431
5761
  exec: opts.exec,
5432
- ...(transport !== undefined ? { transport } : {}),
5762
+ ...(transport !== undefined
5763
+ ? { transport }
5764
+ : opts.invocationBudget !== undefined
5765
+ ? { fetchFn: budgetedFetch() }
5766
+ : {}),
5433
5767
  })
5434
5768
  const readFile = forge.readFile
5435
5769
  if (readFile === undefined) {
@@ -5539,6 +5873,12 @@ async function resolveOriginModeState(
5539
5873
  * path — is the served repository.
5540
5874
  */
5541
5875
  export async function abDispatch(opts: DispatchOpts): Promise<void> {
5876
+ // The invocation deadline also bounds every hosted retry this run causes.
5877
+ if (opts.deadlineAt === undefined) return abDispatchInScope(opts)
5878
+ return withRemoteRetryDeadline(opts.deadlineAt, () => abDispatchInScope(opts))
5879
+ }
5880
+
5881
+ async function abDispatchInScope(opts: DispatchOpts): Promise<void> {
5542
5882
  if (opts.kernelRunId === undefined && !launchContext(opts.env)) {
5543
5883
  opts = { ...opts, ...(await selectDispatchMode(opts)) }
5544
5884
  }
@@ -5619,6 +5959,33 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
5619
5959
  return
5620
5960
  }
5621
5961
  if (opts.dispatchedBy !== undefined) throw new Error('--dispatched-by requires --viewer')
5962
+ const budget = opts.invocationBudget
5963
+ if (budget === undefined) return dispatchKernelPath(opts)
5964
+ if (opts.once !== true) throw new Error('invocationBudget requires a one-pass (--once) dispatch')
5965
+ if (opts.deadlineAt !== undefined && opts.deadlineAt !== budget.workDeadlineAt) {
5966
+ throw new Error('invocationBudget: an explicit deadlineAt must equal its work deadline')
5967
+ }
5968
+ if (budget.work.aborted) throw new InvocationBudgetExhaustedError()
5969
+ const bounded: DispatchOpts = { ...opts, deadlineAt: budget.workDeadlineAt }
5970
+ try {
5971
+ // Startup and the whole work pass carry the work signal: every builtin
5972
+ // adapter request they make is cancelled at the work deadline. Teardown
5973
+ // re-enters with its own signals.
5974
+ await withInvocationSignal(budget.work, () => dispatchKernelPath(bounded))
5975
+ } catch (error) {
5976
+ // A budget stop after `run-started` returns normally from the kernel, so
5977
+ // an error escaping here past the work deadline happened before the run
5978
+ // started: nothing durable was claimed.
5979
+ if (budget.work.aborted && !(error instanceof InvocationBudgetExhaustedError)) {
5980
+ throw new InvocationBudgetExhaustedError(undefined, { cause: error })
5981
+ }
5982
+ throw error
5983
+ }
5984
+ }
5985
+
5986
+ /** `abDispatch` after the viewer branch: origin config, repository state,
5987
+ * the interactive frontend, or the in-process kernel. */
5988
+ async function dispatchKernelPath(opts: DispatchOpts): Promise<void> {
5622
5989
  if (opts.wire !== undefined && opts.nonStoreWire !== undefined) {
5623
5990
  throw new Error('dispatch wire and nonStoreWire are mutually exclusive')
5624
5991
  }
@@ -5854,8 +6221,12 @@ async function runDispatchKernel(
5854
6221
  // wiring or production wiring can open state or perform side effects.
5855
6222
  resolveForgeRegistration(config.forge, plugins)
5856
6223
  let wired: DispatchWiring
6224
+ const budget = resolvedOpts.invocationBudget
5857
6225
  if (resolvedOpts.nonStoreWire !== undefined) {
5858
- const opened = openStoreForRepoState(state, { env: resolvedOpts.env })
6226
+ const opened = openStoreForRepoState(state, {
6227
+ env: resolvedOpts.env,
6228
+ ...(budget !== undefined ? { openStore: budgetedProductionStore(budgetedFetch()) } : {}),
6229
+ })
5859
6230
  const ports = await resolvedOpts.nonStoreWire(config, resolvedOpts, state, plugins)
5860
6231
  wired = {
5861
6232
  ...ports,
@@ -5957,10 +6328,6 @@ async function runDispatchKernel(
5957
6328
  },
5958
6329
  )
5959
6330
 
5960
- // Launch flags are durable repository setters. Omission writes nothing, so
5961
- // another dispatcher cannot clobber the latest operator choice with a value
5962
- // it inferred at startup. Fresh-repository fallbacks live in the reducer.
5963
- await wiring.store.ensureRepo(state.repo)
5964
6331
  // Every own lifecycle append goes through one view, restored from snapshots
5965
6332
  // before the first of them, so a quiet invocation reads none of its own
5966
6333
  // rows back and the final flush covers `run-stopped` too.
@@ -5974,48 +6341,71 @@ async function runDispatchKernel(
5974
6341
  ...(web !== undefined ? { onRepositoryFacts: (facts) => web.publishFacts(facts) } : {}),
5975
6342
  })
5976
6343
  web?.attachStore(wiring.store)
5977
- await view.startJournal()
5978
- const actor = humanActor(buildControlUser(resolvedOpts.env))
5979
- if (resolvedOpts.intake !== undefined) {
5980
- await view.appendRepo(state.repo, {
5981
- actor,
5982
- type: 'dispatcher.intake-set',
5983
- payload: { enabled: resolvedOpts.intake, run: runId },
5984
- })
5985
- }
6344
+ let started: Awaited<ReturnType<RepoViewStore['appendRepoWithArtifacts']>>
6345
+ try {
6346
+ // Launch flags are durable repository setters. Omission writes nothing, so
6347
+ // another dispatcher cannot clobber the latest operator choice with a value
6348
+ // it inferred at startup. Fresh-repository fallbacks live in the reducer.
6349
+ await wiring.store.ensureRepo(state.repo)
6350
+ await view.startJournal()
6351
+ const actor = humanActor(buildControlUser(resolvedOpts.env))
6352
+ if (resolvedOpts.intake !== undefined) {
6353
+ await view.appendRepo(state.repo, {
6354
+ actor,
6355
+ type: 'dispatcher.intake-set',
6356
+ payload: { enabled: resolvedOpts.intake, run: runId },
6357
+ })
6358
+ }
5986
6359
 
5987
- const started = await view.appendRepoWithArtifacts(
5988
- state.repo,
5989
- [
5990
- {
5991
- kind: _effectiveConfigKind,
5992
- content: effectiveBuildConfigContent(config),
5993
- metadata: {
5994
- run: runId,
5995
- revision: 0,
5996
- ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6360
+ started = await view.appendRepoWithArtifacts(
6361
+ state.repo,
6362
+ [
6363
+ {
6364
+ kind: _effectiveConfigKind,
6365
+ content: effectiveBuildConfigContent(config),
6366
+ metadata: {
6367
+ run: runId,
6368
+ revision: 0,
6369
+ ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6370
+ },
5997
6371
  },
6372
+ ],
6373
+ (deposited) => {
6374
+ const artifact = deposited[0]
6375
+ if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6376
+ return {
6377
+ actor: DISPATCHER,
6378
+ type: 'dispatcher.run-started',
6379
+ payload: {
6380
+ run: runId,
6381
+ ...(launchContext(resolvedOpts.env)?.lineage
6382
+ ? { lineage: launchContext(resolvedOpts.env)!.lineage }
6383
+ : {}),
6384
+ pid: process.pid,
6385
+ host: hostname(),
6386
+ effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
6387
+ roleWarnings: startupWarnings(config, wiring.forge),
6388
+ },
6389
+ }
5998
6390
  },
5999
- ],
6000
- (deposited) => {
6001
- const artifact = deposited[0]
6002
- if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6003
- return {
6004
- actor: DISPATCHER,
6005
- type: 'dispatcher.run-started',
6006
- payload: {
6007
- run: runId,
6008
- ...(launchContext(resolvedOpts.env)?.lineage
6009
- ? { lineage: launchContext(resolvedOpts.env)!.lineage }
6010
- : {}),
6011
- pid: process.pid,
6012
- host: hostname(),
6013
- effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
6014
- roleWarnings: startupWarnings(config, wiring.forge),
6015
- },
6016
- }
6017
- },
6018
- )
6391
+ )
6392
+ } catch (error) {
6393
+ if (budget === undefined || !budget.work.aborted) throw error
6394
+ // The work deadline cut a startup write off. The `run-started` deposit
6395
+ // may still have committed with its response lost, so the bounded
6396
+ // canonical repository value decides whether this run exists.
6397
+ const recordedStart = await stopAmbiguousStart(budget, wiring.store, state.repo, runId)
6398
+ await finalStep(budget, async () => {
6399
+ await wiring.releaseAccounts?.()
6400
+ if (resolvedOpts.wire === undefined) await wiring.store.close()
6401
+ }).catch(() => {})
6402
+ if (!recordedStart) throw new InvocationBudgetExhaustedError(undefined, { cause: error })
6403
+ if (resolvedOpts.silent !== true)
6404
+ resolvedOpts.stdout(
6405
+ 'ab dispatch — invocation work deadline reached during startup; the run stopped, remaining work resumes next invocation',
6406
+ )
6407
+ return
6408
+ }
6019
6409
 
6020
6410
  try {
6021
6411
  await view.appendRepo(state.repo, {
@@ -6026,6 +6416,11 @@ async function runDispatchKernel(
6026
6416
 
6027
6417
  const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
6028
6418
  await loop.run()
6419
+ if (loop.stoppedAtDeadline && resolvedOpts.silent !== true) {
6420
+ resolvedOpts.stdout(
6421
+ 'ab dispatch — invocation work deadline reached; teardown complete, remaining work resumes next invocation',
6422
+ )
6423
+ }
6029
6424
  const stopRequest =
6030
6425
  resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted
6031
6426
  ? (await readDispatcherRunFacts(wiring.store, state.repo, runId)).value.stopRequest
@@ -6036,39 +6431,90 @@ async function runDispatchKernel(
6036
6431
  : typeof resolvedOpts.signal?.reason === 'string'
6037
6432
  ? resolvedOpts.signal.reason
6038
6433
  : undefined
6039
- await view.appendRepo(state.repo, {
6040
- actor: DISPATCHER,
6041
- type: 'dispatcher.run-stopped',
6042
- payload: {
6043
- run: runId,
6044
- outcome: 'normal',
6045
- exitCode: 0,
6046
- ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6047
- ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6048
- },
6049
- })
6050
- } catch (error) {
6051
- try {
6052
- await view.appendRepo(state.repo, {
6434
+ await finalStep(budget, () =>
6435
+ view.appendRepo(state.repo, {
6053
6436
  actor: DISPATCHER,
6054
6437
  type: 'dispatcher.run-stopped',
6055
6438
  payload: {
6056
6439
  run: runId,
6057
- outcome: 'abnormal',
6058
- exitCode: 1,
6059
- error: error instanceof Error ? error.message : String(error),
6440
+ outcome: 'normal',
6441
+ exitCode: 0,
6442
+ ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6443
+ ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6060
6444
  },
6061
- })
6445
+ }),
6446
+ )
6447
+ } catch (error) {
6448
+ // A bounded invocation past its work deadline stopped on budget, however
6449
+ // the adapter wrapped the abort: a clean stop, not a loss.
6450
+ const budgetStop = budget?.work.aborted === true
6451
+ const tickFailed = error instanceof DispatchTickFailedError
6452
+ const original = tickFailed ? error.cause : error
6453
+ try {
6454
+ await finalStep(budget, () =>
6455
+ view.appendRepo(state.repo, {
6456
+ actor: DISPATCHER,
6457
+ type: 'dispatcher.run-stopped',
6458
+ payload: budgetStop
6459
+ ? { run: runId, outcome: 'normal', exitCode: 0 }
6460
+ : {
6461
+ run: runId,
6462
+ outcome: tickFailed ? 'normal' : 'abnormal',
6463
+ exitCode: 1,
6464
+ error: original instanceof Error ? original.message : String(original),
6465
+ },
6466
+ }),
6467
+ )
6062
6468
  } catch {
6063
6469
  // Preserve the kernel failure; the supervising frontend records exit.
6064
6470
  }
6065
- throw error
6471
+ if (!budgetStop) throw original
6066
6472
  } finally {
6067
6473
  // Every append this invocation made, `run-stopped` included, is in the
6068
6474
  // view; leave the reduced state behind so the next cold process reads
6069
6475
  // only what is newer than it.
6476
+ await finalStep(budget, async () => {
6477
+ await wiring.releaseAccounts?.()
6478
+ if (resolvedOpts.wire === undefined) await wiring.store.close()
6479
+ })
6480
+ }
6481
+ }
6070
6482
 
6071
- await wiring.releaseAccounts?.()
6072
- if (resolvedOpts.wire === undefined) await wiring.store.close()
6483
+ /** A bounded invocation whose startup the work deadline cut off: when the
6484
+ * `run-started` deposit committed anyway, record this run's normal stop so
6485
+ * the journal never holds a start without a stop. One read of the reduced
6486
+ * `repositoryReadFacts` value (its recent runs), never history, then at most
6487
+ * one append, all under the final signal. True when the run had started. */
6488
+ async function stopAmbiguousStart(
6489
+ budget: InvocationBudget,
6490
+ store: BuildStore,
6491
+ repo: string,
6492
+ run: string,
6493
+ ): Promise<boolean> {
6494
+ let started = false
6495
+ await finalStep(budget, async () => {
6496
+ const recorded = await readDispatcherRunFacts(store, repo, run, false)
6497
+ if (recorded.value.start === undefined) return
6498
+ started = true
6499
+ await store.appendRepo(repo, {
6500
+ actor: DISPATCHER,
6501
+ type: 'dispatcher.run-stopped',
6502
+ payload: { run, outcome: 'normal', exitCode: 0 },
6503
+ })
6504
+ }).catch(() => {})
6505
+ return started
6506
+ }
6507
+
6508
+ /** Run a final teardown step: under the budget's `final` signal and bounded
6509
+ * by it when the invocation is bounded, else exactly as before. A step that
6510
+ * misses the hard deadline is abandoned, never awaited past it. */
6511
+ async function finalStep(
6512
+ budget: InvocationBudget | undefined,
6513
+ step: () => Promise<unknown>,
6514
+ ): Promise<void> {
6515
+ if (budget === undefined) {
6516
+ await step()
6517
+ return
6073
6518
  }
6519
+ await untilAborted(withInvocationSignal(budget.final, step), budget.final)
6074
6520
  }