@defrex/autobuild 1.15.0 → 1.17.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 (80) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +110 -10
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +41 -7
  5. package/docs/configuration.md +41 -7
  6. package/docs/dispatcher-hosting.md +3 -0
  7. package/docs/operator-api.md +15 -5
  8. package/docs/plugin-authoring.md +1 -0
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +3 -1
  11. package/docs/restacking.md +41 -1
  12. package/docs/setup.md +15 -6
  13. package/docs/troubleshooting.md +51 -3
  14. package/docs/workspaces.md +4 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/accounts.ts +3 -0
  17. package/packages/core/src/cli/binary-direct.ts +14 -1
  18. package/packages/core/src/cli/binary.ts +10 -7
  19. package/packages/core/src/cli/dispatch.ts +610 -356
  20. package/packages/core/src/cli/secrets.ts +2 -0
  21. package/packages/core/src/config/schema.ts +15 -2
  22. package/packages/core/src/events/payloads.ts +8 -5
  23. package/packages/core/src/events/repository.ts +12 -6
  24. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e28c68e63cbd265f.json +108 -0
  25. package/packages/core/src/kernel/engine.ts +118 -0
  26. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  27. package/packages/core/src/kernel/reducer-revisions.ts +1 -0
  28. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  29. package/packages/core/src/ontology.ts +1 -0
  30. package/packages/core/src/operator/index.ts +10 -0
  31. package/packages/core/src/operator/merged-builds.ts +51 -0
  32. package/packages/core/src/operator/registry.ts +190 -101
  33. package/packages/core/src/operator/repo-argument.ts +43 -0
  34. package/packages/core/src/ports/tickets/grants.ts +2 -0
  35. package/packages/core/src/ports/tickets/remote.ts +2 -0
  36. package/packages/core/src/ports/types.ts +25 -4
  37. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  38. package/packages/core/src/ports/workspace/vercel-sandbox.ts +811 -169
  39. package/packages/core/src/processes/build-child.ts +15 -1
  40. package/packages/core/src/processes/build-runner.ts +349 -20
  41. package/packages/core/src/processes/dispatcher.ts +509 -104
  42. package/packages/core/src/processes/harvest-child.ts +21 -1
  43. package/packages/core/src/processes/harvest-runner.ts +82 -35
  44. package/packages/core/src/processes/invocation-budget.ts +6 -0
  45. package/packages/core/src/processes/launch-cut.ts +37 -0
  46. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  47. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  48. package/packages/core/src/processes/repo-view.ts +25 -4
  49. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  50. package/packages/core/src/store/adapter.ts +34 -5
  51. package/packages/core/src/store/build-feed.ts +148 -22
  52. package/packages/core/src/store/build-scope.ts +12 -3
  53. package/packages/core/src/store/caller-attribution.ts +170 -0
  54. package/packages/core/src/store/contract.ts +1038 -165
  55. package/packages/core/src/store/local/schema.ts +12 -1
  56. package/packages/core/src/store/local/store.ts +260 -25
  57. package/packages/core/src/store/memory.ts +156 -9
  58. package/packages/core/src/store/phase-session.ts +23 -3
  59. package/packages/core/src/store/reducer-value-shapes.json +5351 -5338
  60. package/packages/core/src/store/remote/client.ts +90 -11
  61. package/packages/core/src/store/remote/credentials.ts +2 -0
  62. package/packages/core/src/store/remote/index.ts +31 -5
  63. package/packages/core/src/store/remote/protocol.ts +45 -8
  64. package/packages/core/src/store/remote/released-clients.json +22 -0
  65. package/packages/core/src/store/remote/released-reducer-values/1.16.0.json +36358 -0
  66. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  67. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  68. package/packages/core/src/store/remote/released-value-policy.ts +7 -0
  69. package/packages/core/src/store/session-handle.ts +12 -3
  70. package/packages/core/src/store/types.ts +48 -3
  71. package/packages/core/src/testing/reduced-read-budget.ts +310 -12
  72. package/skills/guide/SKILL.md +58 -9
  73. package/skills/guide/references/operator-api.md +15 -5
  74. package/skills/guide/references/plugin-authoring.md +1 -0
  75. package/skills/guide/references/remote-store-protocol.md +13 -3
  76. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  77. package/skills/guide/references/restacking.md +41 -1
  78. package/skills/guide/references/setup.md +15 -6
  79. package/skills/operate/SKILL.md +31 -7
  80. package/templates/hosted-service/package.json +2 -2
@@ -191,6 +191,13 @@ import type { RuntimeRegistry } from '../ports/runner/runtime'
191
191
  import { createTicketSource } from '../ports/tickets/create'
192
192
  import { dispatcherTicketSource } from './dispatch-tickets'
193
193
  import { isTransientRemoteFailure, withRemoteRetryDeadline } from '../store/remote/retry'
194
+ import {
195
+ currentStoreCaller,
196
+ type StoreCaller,
197
+ withCallerStage,
198
+ withDispatcherRun,
199
+ withStoreCaller,
200
+ } from '../store/caller-attribution'
194
201
  import type {
195
202
  Forge,
196
203
  TicketSource,
@@ -258,6 +265,8 @@ import {
258
265
  budgetedFetch,
259
266
  DEFAULT_TIMERS,
260
267
  InvocationBudgetExhaustedError,
268
+ InvocationDeadlineError,
269
+ LaunchCutByDeadline,
261
270
  invocationSignal,
262
271
  untilAborted,
263
272
  withInvocationSignal,
@@ -433,6 +442,8 @@ export interface DispatchWiring {
433
442
  export type DispatchNonStoreWiring = Omit<DispatchWiring, 'store' | 'storeRef' | 'token'>
434
443
 
435
444
  export type { TimerScheduler } from '../processes/invocation-budget'
445
+ export type { StoreCaller } from '../store/caller-attribution'
446
+ export { currentStoreCaller, withDispatcherRun, withStoreCaller } from '../store/caller-attribution'
436
447
  export {
437
448
  createInvocationBudget,
438
449
  teardownReserveMs,
@@ -442,6 +453,9 @@ export {
442
453
  budgetedFetch,
443
454
  InvocationDeadlineError,
444
455
  InvocationBudgetExhaustedError,
456
+ LaunchCutByDeadline,
457
+ isLaunchCutByDeadline,
458
+ type CutLaunch,
445
459
  type InvocationBudget,
446
460
  } from '../processes/invocation-budget'
447
461
 
@@ -883,6 +897,9 @@ interface ActiveBuildExecution {
883
897
  detaching?: boolean
884
898
  /** A wait failure being recorded; teardown lets it finish rather than drop it. */
885
899
  recording?: Promise<void>
900
+ /** Set immediately before the provider start is requested: from here a
901
+ * deadline-cut launch may have a guest running and must be fenced. */
902
+ startRequested?: boolean
886
903
  }
887
904
 
888
905
  /** The dispatch loop owns deterministic decisions and supervises one
@@ -907,6 +924,40 @@ export class DispatchTickFailedError extends Error {
907
924
  }
908
925
  }
909
926
 
927
+ /** One hosted harvest launch's repository write fence. Every repository
928
+ * stream or lease-affecting operation the launch makes runs through `run`:
929
+ * once `releaseRepoLease()` closes the fence, `run` refuses synchronously
930
+ * (as an authority lapse) without issuing the operation, and `settled()`
931
+ * joins every operation issued before the close. Provider calls stay
932
+ * outside it so a late guest can still be torn down. Per launch, never per
933
+ * process: closing one never blocks a successor launch. */
934
+ class HostedHarvestFence {
935
+ open = true
936
+ private readonly pending = new Set<Promise<unknown>>()
937
+
938
+ run<T>(op: () => Promise<T>): Promise<T> {
939
+ if (!this.open)
940
+ throw new RepositoryAuthorityLapsed(
941
+ 'repository lease released; hosted harvest write not started',
942
+ )
943
+ const promise = op()
944
+ this.pending.add(promise)
945
+ const forget = (): void => {
946
+ this.pending.delete(promise)
947
+ }
948
+ promise.then(forget, forget)
949
+ return promise
950
+ }
951
+
952
+ close(): void {
953
+ this.open = false
954
+ }
955
+
956
+ async settled(): Promise<void> {
957
+ while (this.pending.size > 0) await Promise.allSettled([...this.pending])
958
+ }
959
+ }
960
+
910
961
  class DispatchLoop {
911
962
  private readonly dispatcher: Dispatcher
912
963
  /** The incremental repository view (AUT-647) the dispatcher and this
@@ -929,7 +980,10 @@ class DispatchLoop {
929
980
  * before awaits; the durable lease remains the cross-kernel exclusion gate. */
930
981
  private readonly activeBuildRuns = new Map<string, ActiveBuildExecution>()
931
982
  private acceptingBuildLaunches = true
932
- /** Process-local fast path; the repository lease is the cross-process gate. */
983
+ /** Process-local fast path; the repository lease is the cross-process gate.
984
+ * Also cancels hosted harvest pre-launch: a hosted launch captures this
985
+ * signal once, when it starts, and stops at its next boundary once it is
986
+ * aborted, so a later re-creation never un-cancels a joined launch. */
933
987
  private localHarvestShutdown = new AbortController()
934
988
  private localHarvestFailure: unknown
935
989
  private harvestInFlight: Promise<void> | undefined
@@ -942,6 +996,13 @@ class DispatchLoop {
942
996
  private hostedHarvest:
943
997
  | { execution: string; handle: BuildExecutionHandle; detached: { value: boolean } }
944
998
  | undefined
999
+ /** Resolves once an in-flight hosted harvest launch has durably recorded
1000
+ * its guest (`harvest.execution.started`) or ended without one. Teardown
1001
+ * awaits it before lease release. Never rejects. */
1002
+ private hostedHarvestPrelaunch: Promise<void> | undefined
1003
+ /** The current hosted harvest launch's repository write fence, closed by
1004
+ * `releaseRepoLease()` before the store release is issued. */
1005
+ private hostedHarvestFence: HostedHarvestFence | undefined
945
1006
  /** Execution ids THIS process supervises; the dispatcher's harvest
946
1007
  * settlement stage skips them (their completion chain owns the facts). */
947
1008
  private readonly hostedHarvestExecutions = new Set<string>()
@@ -2732,8 +2793,22 @@ class DispatchLoop {
2732
2793
  // dispatch process is independently excluded by the repository lease.
2733
2794
  if (this.stopped || this.harvestInFlight !== undefined || this.missingAccounts().length) return
2734
2795
 
2796
+ // Hosted pre-launch is joined by teardown: the window opens here,
2797
+ // synchronously, before the first await of the continuation.
2798
+ const hosted =
2799
+ this.wiring.workspaces.harvestExecution !== undefined
2800
+ ? {
2801
+ prelaunch: Promise.withResolvers<void>(),
2802
+ fence: new HostedHarvestFence(),
2803
+ shutdown: this.localHarvestShutdown.signal,
2804
+ }
2805
+ : undefined
2806
+ if (hosted !== undefined) {
2807
+ this.hostedHarvestPrelaunch = hosted.prelaunch.promise
2808
+ this.hostedHarvestFence = hosted.fence
2809
+ }
2735
2810
  let tracked: Promise<void>
2736
- tracked = this.launchHarvestIfNeeded()
2811
+ tracked = this.launchHarvestIfNeeded(hosted)
2737
2812
  .catch((error: unknown) => {
2738
2813
  if (isRepositoryAuthorityLapse(error)) return
2739
2814
  if (this.stopped || this.localHarvestShutdown.signal.aborted)
@@ -2749,12 +2824,22 @@ class DispatchLoop {
2749
2824
  .finally(() => {
2750
2825
  this.inFlight.delete(tracked)
2751
2826
  if (this.harvestInFlight === tracked) this.harvestInFlight = undefined
2827
+ if (hosted !== undefined) {
2828
+ hosted.prelaunch.resolve()
2829
+ if (this.hostedHarvestPrelaunch === hosted.prelaunch.promise)
2830
+ this.hostedHarvestPrelaunch = undefined
2831
+ if (this.hostedHarvestFence === hosted.fence) this.hostedHarvestFence = undefined
2832
+ }
2752
2833
  })
2753
2834
  this.harvestInFlight = tracked
2754
2835
  this.inFlight.add(tracked)
2755
2836
  }
2756
2837
 
2757
- private async launchHarvestIfNeeded(): Promise<void> {
2838
+ private async launchHarvestIfNeeded(hostedLaunch?: {
2839
+ prelaunch: { resolve: () => void }
2840
+ fence: HostedHarvestFence
2841
+ shutdown: AbortSignal
2842
+ }): Promise<void> {
2758
2843
  const state = this.repoView.repositoryFacts().harvest
2759
2844
  const control = decideHarvestControl(state, this.maxHarvestRecoveryAttempts)
2760
2845
  if (control.kind === 'park') return
@@ -2766,13 +2851,13 @@ class DispatchLoop {
2766
2851
  })
2767
2852
  if (pressure.trigger === undefined) return
2768
2853
  }
2769
- if (this.stopped) return
2854
+ if (this.stopped || hostedLaunch?.shutdown.aborted === true) return
2770
2855
  const hosted = this.wiring.workspaces.harvestExecution
2771
- if (hosted !== undefined) {
2856
+ if (hosted !== undefined && hostedLaunch !== undefined) {
2772
2857
  const execution = `${this.host}-harvest-${this.wiring.ids('inst')}`
2773
2858
  this.hostedHarvestExecutions.add(execution)
2774
2859
  try {
2775
- await this.launchHostedHarvest(hosted, execution)
2860
+ await this.launchHostedHarvest(hosted, execution, hostedLaunch)
2776
2861
  } finally {
2777
2862
  this.hostedHarvestExecutions.delete(execution)
2778
2863
  }
@@ -2870,6 +2955,8 @@ class DispatchLoop {
2870
2955
  url: storeRef,
2871
2956
  token: buildScoped,
2872
2957
  ...(fetchFn !== undefined ? { fetchFn } : {}),
2958
+ // Its ending append and close run after the runner returns.
2959
+ caller: harvestRunnerCaller(prepared.run, harvestDeps.instance),
2873
2960
  })
2874
2961
  }
2875
2962
  const sessionEnv = {
@@ -2962,6 +3049,8 @@ class DispatchLoop {
2962
3049
  url: storeRef,
2963
3050
  token: scoped,
2964
3051
  ...(fetchFn !== undefined ? { fetchFn } : {}),
3052
+ // Its ending append and close run after the runner returns.
3053
+ caller: harvestRunnerCaller(prepared.run, harvestDeps.instance),
2965
3054
  })
2966
3055
  try {
2967
3056
  const runnerTickets =
@@ -3071,9 +3160,18 @@ class DispatchLoop {
3071
3160
  private async launchHostedHarvest(
3072
3161
  harvestExecution: HarvestExecution,
3073
3162
  execution: string,
3163
+ launch: {
3164
+ prelaunch: { resolve: () => void }
3165
+ fence: HostedHarvestFence
3166
+ shutdown: AbortSignal
3167
+ },
3074
3168
  ): Promise<void> {
3075
3169
  const { store, storeRef } = this.wiring
3076
3170
  const repo = this.repoIdentity
3171
+ const { fence, shutdown } = launch
3172
+ // Teardown requested (or the lease already released): stop at the next
3173
+ // boundary, quietly — nothing started, like an authority lapse.
3174
+ const cancelled = (): boolean => this.stopped || shutdown.aborted || !fence.open
3077
3175
  let handle: BuildExecutionHandle | undefined
3078
3176
  let startedSeq: number | undefined
3079
3177
  let ticketAuthority: { url: string; token: string; id: string } | undefined
@@ -3083,6 +3181,7 @@ class DispatchLoop {
3083
3181
  // entry is cleared, or the chain would classify and reap a live guest.
3084
3182
  const detached = { value: false }
3085
3183
  try {
3184
+ if (cancelled()) return
3086
3185
  // Threshold gate before any provisioning — with resume precedence. The
3087
3186
  // runner's real check runs in the guest after a full provisioning
3088
3187
  // chain, and its order is resume-first, pressure-second: it settles
@@ -3097,6 +3196,7 @@ class DispatchLoop {
3097
3196
  // reduces durable types only. Take the journal delta first — guests and
3098
3197
  // other dispatchers write harvest facts between ticks.
3099
3198
  await this.repoView.refreshJournal()
3199
+ if (cancelled()) return
3100
3200
  const events = this.repoView.repositoryFacts().harvest
3101
3201
  const state = events
3102
3202
  const control = decideHarvestControl(state, this.maxHarvestRecoveryAttempts)
@@ -3118,34 +3218,46 @@ class DispatchLoop {
3118
3218
  policy: this.currentConfig().config.policy,
3119
3219
  })
3120
3220
  if (pressure.trigger === undefined) return
3221
+ if (cancelled()) return
3121
3222
  }
3122
3223
 
3123
- const prepared = await this.prepareHarvest(execution)
3224
+ if (cancelled()) return
3225
+ this.requireRepoAuthority()
3226
+ const prepared = await fence.run(() => this.prepareHarvest(execution))
3124
3227
  if (prepared.outcome !== 'prepared') return
3228
+ // An authorized-but-unstarted execution left by a cancellation here is
3229
+ // the same state a delegation failure leaves: the next authorization
3230
+ // replaces it and the open run resumes.
3231
+ if (cancelled()) return
3125
3232
  this.requireRepoAuthority()
3126
- await this.repoView.appendRepo(repo, {
3127
- actor: DISPATCHER,
3128
- type: 'harvest.execution.authorized',
3129
- payload: {
3130
- execution,
3131
- run: prepared.run,
3132
- launch: prepared.launch,
3133
- leaseHolder: this.repoLeaseHolder ?? execution,
3134
- },
3135
- })
3233
+ const leaseHolder = this.repoLeaseHolder ?? execution
3234
+ await fence.run(() =>
3235
+ this.repoView.appendRepo(repo, {
3236
+ actor: DISPATCHER,
3237
+ type: 'harvest.execution.authorized',
3238
+ payload: {
3239
+ execution,
3240
+ run: prepared.run,
3241
+ launch: prepared.launch,
3242
+ leaseHolder,
3243
+ },
3244
+ }),
3245
+ )
3136
3246
  const launchAuth = /^https?:/i.test(storeRef)
3137
3247
  ? {
3138
- token: await (this.wiring.credentialIssuer ?? delegateCredential)(
3139
- storeRef,
3140
- this.wiring.token,
3141
- {
3142
- kind: 'harvest-runner',
3143
- execution,
3144
- repo,
3145
- id: prepared.run,
3146
- leaseHolder: this.repoLeaseHolder ?? execution,
3147
- },
3148
- this.wiring.budgetSeams?.fetchFn,
3248
+ token: await fence.run(() =>
3249
+ (this.wiring.credentialIssuer ?? delegateCredential)(
3250
+ storeRef,
3251
+ this.wiring.token,
3252
+ {
3253
+ kind: 'harvest-runner',
3254
+ execution,
3255
+ repo,
3256
+ id: prepared.run,
3257
+ leaseHolder,
3258
+ },
3259
+ this.wiring.budgetSeams?.fetchFn,
3260
+ ),
3149
3261
  ),
3150
3262
  }
3151
3263
  : undefined
@@ -3181,6 +3293,9 @@ class DispatchLoop {
3181
3293
  })
3182
3294
  }, 60_000)
3183
3295
  }
3296
+ // The provider call stays unfenced so a guest that starts late can
3297
+ // still be torn down; no launch begins once teardown has started.
3298
+ if (cancelled()) return
3184
3299
  handle = await harvestExecution.start(
3185
3300
  {
3186
3301
  preparedRun: { run: prepared.run },
@@ -3206,18 +3321,22 @@ class DispatchLoop {
3206
3321
  )
3207
3322
  }
3208
3323
  this.hostedHarvest = { execution, handle, detached }
3209
- const started = await this.repoView.appendRepo(repo, {
3210
- actor: DISPATCHER,
3211
- type: 'harvest.execution.started',
3212
- payload: {
3213
- execution,
3214
- provider: identity.provider,
3215
- environmentId: identity.environmentId,
3216
- ...(identity.sessionId !== undefined ? { sessionId: identity.sessionId } : {}),
3217
- commandId: identity.commandId,
3218
- },
3219
- })
3324
+ const startedPayload = {
3325
+ execution,
3326
+ provider: identity.provider,
3327
+ environmentId: identity.environmentId,
3328
+ ...(identity.sessionId !== undefined ? { sessionId: identity.sessionId } : {}),
3329
+ commandId: identity.commandId,
3330
+ }
3331
+ const started = await fence.run(() =>
3332
+ this.repoView.appendRepo(repo, {
3333
+ actor: DISPATCHER,
3334
+ type: 'harvest.execution.started',
3335
+ payload: startedPayload,
3336
+ }),
3337
+ )
3220
3338
  startedSeq = started.seq
3339
+ launch.prelaunch.resolve()
3221
3340
 
3222
3341
  await handle.completion
3223
3342
  if (detached.value) {
@@ -3244,7 +3363,7 @@ class DispatchLoop {
3244
3363
  if (result.outcome === 'failed') this.failureNotice(line)
3245
3364
  else this.say(line)
3246
3365
  }
3247
- await this.releaseHostedHarvest(repo, execution, handle)
3366
+ await this.releaseHostedHarvest(repo, execution, handle, fence)
3248
3367
  } catch (error) {
3249
3368
  // Launch or wait failure: best-effort release attempt, the existing
3250
3369
  // durable failure event + warn path, retried on a later threshold tick.
@@ -3252,26 +3371,29 @@ class DispatchLoop {
3252
3371
  // next run's get-or-create; a marked-but-unlaunched one is reused.
3253
3372
  if (handle !== undefined) {
3254
3373
  try {
3255
- await this.releaseHostedHarvest(repo, execution, handle)
3374
+ await this.releaseHostedHarvest(repo, execution, handle, fence)
3256
3375
  } catch {
3257
3376
  // Left open: durable settlement re-proves and reaps it later.
3258
3377
  }
3259
3378
  }
3379
+ // Nothing started without authority, or the lease is already released
3380
+ // (closed fence): no repository write may follow; a later tick retries.
3381
+ if (isRepositoryAuthorityLapse(error) || !fence.open) return
3260
3382
  if (error instanceof MissingAccountCredentialsError) {
3261
- await this.dispatcher.holdForMissingAccounts(error)
3383
+ await fence.run(() => this.dispatcher.holdForMissingAccounts(error))
3262
3384
  return
3263
3385
  }
3264
- // Nothing started without authority; a later tick retries.
3265
- if (isRepositoryAuthorityLapse(error)) return
3266
3386
  this.pendingHarvest.harvestFailed += 1
3267
- await this.appendStatus({
3268
- actor: DISPATCHER,
3269
- type: 'dispatcher.harvest-runner-failed',
3270
- payload: {
3271
- run: this.runId,
3272
- error: error instanceof Error ? error.message : String(error),
3273
- },
3274
- })
3387
+ await fence.run(() =>
3388
+ this.appendStatus({
3389
+ actor: DISPATCHER,
3390
+ type: 'dispatcher.harvest-runner-failed',
3391
+ payload: {
3392
+ run: this.runId,
3393
+ error: error instanceof Error ? error.message : String(error),
3394
+ },
3395
+ }),
3396
+ )
3275
3397
  if (!this.stopped) {
3276
3398
  this.warn(
3277
3399
  `harvest runner failed: ${error instanceof Error ? error.message : String(error)}`,
@@ -3311,34 +3433,40 @@ class DispatchLoop {
3311
3433
  }
3312
3434
 
3313
3435
  /** Release the disposable environment through the owning provider's reap
3314
- * path and journal the close fact with the snapshot purge outcome. */
3436
+ * path and journal the close fact with the snapshot purge outcome. The
3437
+ * provider reap always runs; the journal append goes through the launch's
3438
+ * write fence, so it is refused once the repository lease is released. */
3315
3439
  private async releaseHostedHarvest(
3316
3440
  repo: string,
3317
3441
  execution: string,
3318
3442
  handle: BuildExecutionHandle,
3443
+ fence?: HostedHarvestFence,
3319
3444
  ): Promise<void> {
3320
3445
  const identity = handle.identity
3321
- if (identity === undefined || identity.environmentId === undefined) return
3446
+ const environmentId = identity?.environmentId
3447
+ if (identity === undefined || environmentId === undefined) return
3322
3448
  const workspaceHandle: WorkspaceHandle = {
3323
3449
  provider: identity.provider,
3324
- ref: identity.environmentId,
3325
- path: identity.environmentId,
3450
+ ref: environmentId,
3451
+ path: environmentId,
3326
3452
  branch: '',
3327
3453
  }
3328
3454
  const reap = await this.reapHostedWorkspace(workspaceHandle)
3329
- await this.repoView.appendRepo(repo, {
3330
- actor: DISPATCHER,
3331
- type: 'harvest.execution.released',
3332
- payload: {
3333
- execution,
3334
- environmentId: identity.environmentId,
3335
- snapshots: {
3336
- outcome: reap.snapshots.outcome === 'unknown' ? 'unknown' : 'confirmed',
3337
- ...(reap.snapshots.deleted !== undefined ? { deleted: reap.snapshots.deleted } : {}),
3338
- ...(reap.snapshots.error !== undefined ? { error: reap.snapshots.error } : {}),
3455
+ const append = () =>
3456
+ this.repoView.appendRepo(repo, {
3457
+ actor: DISPATCHER,
3458
+ type: 'harvest.execution.released',
3459
+ payload: {
3460
+ execution,
3461
+ environmentId,
3462
+ snapshots: {
3463
+ outcome: reap.snapshots.outcome === 'unknown' ? 'unknown' : 'confirmed',
3464
+ ...(reap.snapshots.deleted !== undefined ? { deleted: reap.snapshots.deleted } : {}),
3465
+ ...(reap.snapshots.error !== undefined ? { error: reap.snapshots.error } : {}),
3466
+ },
3339
3467
  },
3340
- },
3341
- })
3468
+ })
3469
+ await (fence !== undefined ? fence.run(append) : append())
3342
3470
  }
3343
3471
 
3344
3472
  /** Reap through the provider's recovery capability when it reports the
@@ -3371,7 +3499,13 @@ class DispatchLoop {
3371
3499
  if (this.localHarvestFailure !== undefined) throw this.localHarvestFailure
3372
3500
  }
3373
3501
 
3502
+ /** Stop hosted harvest before lease release: cancel any launch still
3503
+ * preparing (it stops at its next boundary), join it until its guest is
3504
+ * durably recorded or it ends without one, then detach the live wait — the
3505
+ * guest keeps running and a later invocation settles it. */
3374
3506
  private async stopHostedHarvest(): Promise<void> {
3507
+ this.localHarvestShutdown.abort()
3508
+ await this.hostedHarvestPrelaunch
3375
3509
  const entry = this.hostedHarvest
3376
3510
  if (entry === undefined) return
3377
3511
  entry.detached.value = true
@@ -3753,10 +3887,18 @@ class DispatchLoop {
3753
3887
  const active: ActiveBuildExecution = { reservation, instance, stopping: false }
3754
3888
  this.activeBuildRuns.set(slug, active)
3755
3889
  let leaseClaimed = false
3890
+ /** The claim was sent but not acknowledged: it may have committed. */
3891
+ let claimUnacknowledged = false
3892
+ let cutWorkspace: { provider: string; ref: string } | undefined
3893
+ /** Whether the owning provider can fence its workspace (stop a guest
3894
+ * that outlives this process). */
3895
+ let cutFenceable = false
3756
3896
 
3757
3897
  try {
3758
3898
  await this.publishBuildConfig(slug)
3899
+ claimUnacknowledged = true
3759
3900
  leaseClaimed = await this.repoView.claimLease(slug, instance, BUILD_EXECUTION_LEASE_TTL_MS)
3901
+ claimUnacknowledged = false
3760
3902
  if (!leaseClaimed) {
3761
3903
  this.activeBuildRuns.delete(slug)
3762
3904
  await this.appendStatus({
@@ -3775,7 +3917,11 @@ class DispatchLoop {
3775
3917
  // provisioned before a provider switch still runs where it lives.
3776
3918
  const owning =
3777
3919
  workspaceProvider === undefined || workspaceProvider === this.wiring.workspaces.name
3778
- ? { name: this.wiring.workspaces.name, execution: this.wiring.buildExecution }
3920
+ ? {
3921
+ name: this.wiring.workspaces.name,
3922
+ execution: this.wiring.buildExecution,
3923
+ recovery: this.wiring.workspaces.recovery,
3924
+ }
3779
3925
  : (() => {
3780
3926
  const retired = this.wiring.retiredWorkspaces?.find(
3781
3927
  (runtime) => runtime.provider.name === workspaceProvider,
@@ -3785,8 +3931,14 @@ class DispatchLoop {
3785
3931
  `build ${slug} workspace ${workspaceRef} belongs to provider "${workspaceProvider}", which is no longer configured`,
3786
3932
  )
3787
3933
  }
3788
- return { name: retired.provider.name, execution: retired.execution }
3934
+ return {
3935
+ name: retired.provider.name,
3936
+ execution: retired.execution,
3937
+ recovery: retired.provider.recovery,
3938
+ }
3789
3939
  })()
3940
+ cutWorkspace = { provider: owning.name, ref: workspaceRef }
3941
+ cutFenceable = owning.recovery !== undefined
3790
3942
  // A prior publication acknowledgement may have been lost after its push
3791
3943
  // reached the durable branch. Reconcile that fact before a replacement
3792
3944
  // runner can rerun the phase and create a non-fast-forward successor.
@@ -3804,6 +3956,9 @@ class DispatchLoop {
3804
3956
  ),
3805
3957
  }
3806
3958
  : undefined
3959
+ // No launch starts after the work deadline (teardown's invariant).
3960
+ if (!this.acceptingBuildLaunches) throw new InvocationDeadlineError('work')
3961
+ active.startRequested = true
3807
3962
  const handle = await owning.execution.start(
3808
3963
  {
3809
3964
  slug,
@@ -3960,6 +4115,25 @@ class DispatchLoop {
3960
4115
  if (isRecoveryDeferred(error)) throw error
3961
4116
  return 'already-active'
3962
4117
  }
4118
+ if (
4119
+ (leaseClaimed || claimUnacknowledged) &&
4120
+ this.opts.invocationBudget?.work.aborted === true &&
4121
+ (active.handle === undefined || (await this.releaseCutHandle(active.handle, cutFenceable)))
4122
+ ) {
4123
+ // The work deadline cut the launch after its lease claim — before
4124
+ // the claim's acknowledgement (it may have committed; the exact-holder
4125
+ // release is a no-op if not), before the provider returned, or
4126
+ // before `execution.started` committed.
4127
+ // Record nothing here: the dispatcher fences when the start was
4128
+ // requested, releases the exact holder in teardown and carries the
4129
+ // launch.
4130
+ throw new LaunchCutByDeadline({
4131
+ slug,
4132
+ instance,
4133
+ startRequested: active.startRequested === true,
4134
+ ...(cutWorkspace !== undefined ? { workspace: cutWorkspace } : {}),
4135
+ })
4136
+ }
3963
4137
  if (leaseClaimed) {
3964
4138
  // The runner appended through its own handle: take the delta.
3965
4139
  await this.repoView.refreshBuild(slug)
@@ -3994,6 +4168,28 @@ class DispatchLoop {
3994
4168
  }
3995
4169
  }
3996
4170
 
4171
+ /** A handle whose `execution.started` the work deadline cut: nothing will
4172
+ * settle it, so stop supervising it. A guest that outlives this process is
4173
+ * detached for the dispatcher's workspace fence; a local child is stopped
4174
+ * here. False when neither can prove the execution gone — the ordinary
4175
+ * start failure then keeps the lease until its TTL fences it. */
4176
+ private async releaseCutHandle(
4177
+ handle: BuildExecutionHandle,
4178
+ fenceable: boolean,
4179
+ ): Promise<boolean> {
4180
+ handle.completion.catch(() => {})
4181
+ if (handle.supervision === 'environment') {
4182
+ if (!fenceable) return false
4183
+ await handle.detach().catch(() => {})
4184
+ return true
4185
+ }
4186
+ try {
4187
+ return (await handle.stop())?.outcome !== 'unknown'
4188
+ } catch {
4189
+ return false
4190
+ }
4191
+ }
4192
+
3997
4193
  private get stopped(): boolean {
3998
4194
  return (
3999
4195
  this.cutoverRequested || this.opts.signal?.aborted === true || this.inputStop.signal.aborted
@@ -4960,11 +5156,17 @@ class DispatchLoop {
4960
5156
  }
4961
5157
 
4962
5158
  private async releaseRepoLease(): Promise<void> {
5159
+ // Invariant: once the store release is issued, no hosted harvest
5160
+ // repository write is issued, and every one issued earlier has settled.
5161
+ // Close the launch's fence synchronously, then drain its issued writes.
5162
+ const fence = this.hostedHarvestFence
5163
+ fence?.close()
4963
5164
  this.stopRepoLeaseHeartbeat()
4964
5165
  const holder = this.repoLeaseHolder
4965
5166
  this.repoLeaseHolder = undefined
4966
5167
  this.repoLeaseValidUntil = 0
4967
5168
  this.leaseGeneration++
5169
+ await fence?.settled()
4968
5170
  if (holder === undefined) return
4969
5171
  try {
4970
5172
  await this.wiring.store.releaseRepoLease(this.repoIdentity, holder)
@@ -5602,13 +5804,26 @@ class DispatchLoop {
5602
5804
  : withInvocationSignal(budget.cleanup, write)
5603
5805
  }
5604
5806
 
5605
- private async boundedTeardown(budget: InvocationBudget): Promise<void> {
5807
+ private boundedTeardown(budget: InvocationBudget): Promise<void> {
5808
+ return withCallerStage('teardown', () => this.boundedTeardownInScope(budget))
5809
+ }
5810
+
5811
+ private async boundedTeardownInScope(budget: InvocationBudget): Promise<void> {
5606
5812
  // Whether or not the deadline fired, no launch may start during
5607
5813
  // teardown: provisioning abandonment runs beside execution teardown.
5608
5814
  this.onWorkDeadline()
5815
+ // Runner starts the work deadline cut mid-flight settle their execution
5816
+ // leases (fence, exact-holder release) and carry the launch in the
5817
+ // deferred-work hint while the repository lease is still held.
5818
+ const starts = untilAborted(
5819
+ withInvocationSignal(budget.cleanup, async () => {
5820
+ for (const line of await this.dispatcher.settleCutStarts()) this.say(line)
5821
+ }),
5822
+ budget.cleanup,
5823
+ )
5609
5824
  // The cut pass's lines print now; its advisory writes race beside the
5610
5825
  // other cleanup, so a stalled write never postpones unrelated teardown.
5611
- const summary = this.reportCutPass(budget)
5826
+ const summary = this.reportCutPass(budget, starts)
5612
5827
  const provisioning = untilAborted(
5613
5828
  withInvocationSignal(budget.cleanup, () => this.dispatcher.stopProvisioning()),
5614
5829
  budget.cleanup,
@@ -5624,7 +5839,7 @@ class DispatchLoop {
5624
5839
  }),
5625
5840
  budget.cleanup,
5626
5841
  )
5627
- const cleanup = await Promise.allSettled([provisioning, optional, summary])
5842
+ const cleanup = await Promise.allSettled([provisioning, optional, summary, starts])
5628
5843
  await untilAborted(
5629
5844
  withInvocationSignal(budget.final, () => this.releaseRepoLease()),
5630
5845
  budget.final,
@@ -5639,7 +5854,7 @@ class DispatchLoop {
5639
5854
  * the pass's loops reached and close the still-open tick boundary with
5640
5855
  * that partial summary, so `ab repository status` shows it. Never rejects:
5641
5856
  * a concurrent abandoned publication may already have closed the boundary. */
5642
- private reportCutPass(budget: InvocationBudget): Promise<void> {
5857
+ private reportCutPass(budget: InvocationBudget, starts: Promise<unknown>): Promise<void> {
5643
5858
  const writes: Promise<void>[] = []
5644
5859
  const write = (what: string, run: () => Promise<unknown>) =>
5645
5860
  writes.push(
@@ -5652,24 +5867,30 @@ class DispatchLoop {
5652
5867
  // A no-op when the pass already recorded its positions; the write itself
5653
5868
  // goes through teardownWrite.
5654
5869
  write('pass positions', () => this.dispatcher.persistPassPositions())
5655
- const partial = this.stagesPrinted ? undefined : this.dispatcher.passReport()
5656
- if (partial?.stages !== undefined && partial.stages.length > 0) {
5657
- this.printStages(partial.stages)
5870
+ const stages = this.stagesPrinted ? undefined : this.dispatcher.passReport()?.stages
5871
+ if (stages !== undefined && stages.length > 0) {
5872
+ this.printStages(stages)
5658
5873
  if (this.tickStartedAt !== undefined) {
5659
- const {
5660
- queued: _queued,
5661
- janitorDiagnostics: _janitorDiagnostics,
5662
- blockedDiagnostics: _blockedDiagnostics,
5663
- ticketDiagnostics: _ticketDiagnostics,
5664
- creationDiagnostics: _creationDiagnostics,
5665
- dependencyDiagnostics: _dependencyDiagnostics,
5666
- agentContextDiagnostics: _agentContextDiagnostics,
5667
- deferredDiagnostics: _deferredDiagnostics,
5668
- ...counters
5669
- } = partial
5670
- write('partial pass summary', () =>
5671
- this.teardownWrite(budget)(() => this.finishTick({ outcome: 'completed', counters }, [])),
5672
- )
5874
+ write('partial pass summary', async () => {
5875
+ // The closed tick counts the starts teardown carried.
5876
+ await starts.catch(() => {})
5877
+ const partial = this.dispatcher.passReport()
5878
+ if (partial === undefined) return
5879
+ const {
5880
+ queued: _queued,
5881
+ janitorDiagnostics: _janitorDiagnostics,
5882
+ blockedDiagnostics: _blockedDiagnostics,
5883
+ ticketDiagnostics: _ticketDiagnostics,
5884
+ creationDiagnostics: _creationDiagnostics,
5885
+ dependencyDiagnostics: _dependencyDiagnostics,
5886
+ agentContextDiagnostics: _agentContextDiagnostics,
5887
+ deferredDiagnostics: _deferredDiagnostics,
5888
+ ...counters
5889
+ } = partial
5890
+ await this.teardownWrite(budget)(() =>
5891
+ this.finishTick({ outcome: 'completed', counters }, []),
5892
+ )
5893
+ })
5673
5894
  }
5674
5895
  }
5675
5896
  return Promise.all(writes).then(() => undefined)
@@ -5974,90 +6195,39 @@ async function resolveOriginModeState(
5974
6195
  */
5975
6196
  export async function abDispatch(opts: DispatchOpts): Promise<void> {
5976
6197
  // The invocation deadline also bounds every hosted retry this run causes.
5977
- if (opts.deadlineAt === undefined) return abDispatchInScope(opts)
5978
- return withRemoteRetryDeadline(opts.deadlineAt, () => abDispatchInScope(opts))
6198
+ const run = () =>
6199
+ opts.deadlineAt === undefined
6200
+ ? abDispatchInScope(opts)
6201
+ : withRemoteRetryDeadline(opts.deadlineAt, () => abDispatchInScope(opts))
6202
+ // Hosted requests name their caller: a viewer is an operator client; a
6203
+ // direct kernel entry with no caller yet is a dispatcher.
6204
+ if (opts.viewer) return withStoreCaller(DISPATCH_VIEWER_CALLER, run)
6205
+ if (currentStoreCaller() === undefined) return withStoreCaller({ kind: 'dispatcher' }, run)
6206
+ return run()
6207
+ }
6208
+
6209
+ /** An in-process harvest runner's store, attributed to the execution even
6210
+ * for the dispatcher-issued append that ends it. */
6211
+ const harvestRunnerCaller = (harvest: string, execution: string): StoreCaller => ({
6212
+ kind: 'runner',
6213
+ runner: 'harvest',
6214
+ harvest,
6215
+ execution,
6216
+ })
6217
+
6218
+ const DISPATCH_VIEWER_CALLER: StoreCaller = {
6219
+ kind: 'operator',
6220
+ client: 'cli',
6221
+ command: 'dispatch-viewer',
5979
6222
  }
5980
6223
 
5981
6224
  async function abDispatchInScope(opts: DispatchOpts): Promise<void> {
5982
6225
  if (opts.kernelRunId === undefined && !launchContext(opts.env)) {
5983
6226
  opts = { ...opts, ...(await selectDispatchMode(opts)) }
5984
6227
  }
5985
- if (opts.viewer) {
5986
- if (opts.repository !== undefined)
5987
- throw new Error('--viewer requires a local checkout; omit --repository')
5988
- if (opts.intake !== undefined) throw new Error('--viewer cannot set startup intake')
5989
- if (opts.dispatchedBy !== undefined && !opts.dispatchedBy.trim())
5990
- throw new Error('--dispatched-by requires a nonblank label')
5991
- const state = await resolveRepoState({
5992
- targetRepo: opts.targetRepo,
5993
- exec: opts.exec,
5994
- ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
5995
- ...(opts.env.AB_STORE !== undefined ? { envStore: opts.env.AB_STORE } : {}),
5996
- })
5997
- const env = {
5998
- ...opts.env,
5999
- AB_STORE: state.storeRef,
6000
- ...(isRemoteStoreRef(state.storeRef)
6001
- ? { AB_TOKEN: projectToken(state.storeRef, state.repo, opts.env) }
6002
- : {}),
6003
- }
6004
- const web = await startOptionalDispatchWeb(opts, opts.repo ?? state.repo)
6005
- let opened: ReturnType<typeof openStoreForRepoState> | undefined
6006
- try {
6007
- opened = openStoreForRepoState(state, { env })
6008
- const interactive =
6009
- opts.plain !== true && opts.terminal?.interactive === true && opts.input !== undefined
6010
- // Without a TTY the web UI is the only presentation: the viewer reads
6011
- // exactly as it would, and its text frames are discarded.
6012
- const plainOutput = web !== undefined ? () => {} : opts.stdout
6013
- const store = opened
6014
- web?.attachStore(store.store)
6015
- await new DispatchFrontend({
6016
- viewer: { ...(opts.dispatchedBy !== undefined ? { dispatchedBy: opts.dispatchedBy } : {}) },
6017
- repo: opts.repo ?? state.repo,
6018
- checkout: state.checkout,
6019
- store: store.store,
6020
- storeRef: store.storeRef,
6021
- env,
6022
- terminal: opts.terminal ?? {
6023
- columns: 100,
6024
- rows: 24,
6025
- interactive: false,
6026
- write: () => {},
6027
- modes: createTerminalModeController(
6028
- () => {},
6029
- () => {},
6030
- ),
6031
- },
6032
- input: opts.input ?? { start: () => () => {} },
6033
- ...(!interactive ? { plainOutput } : {}),
6034
- ...(web !== undefined ? { web: { dispatch: web } } : {}),
6035
- controlTickets: () =>
6036
- lazyTicketSource(() =>
6037
- openTicketSource(
6038
- {
6039
- targetRepo: state.checkout,
6040
- exec: opts.exec,
6041
- env,
6042
- storeRef: store.storeRef,
6043
- stdout: opts.stdout,
6044
- },
6045
- 'ab merge',
6046
- ),
6047
- ),
6048
- once: opts.once === true,
6049
- ...(opts.intervalMs !== undefined ? { intervalMs: opts.intervalMs } : {}),
6050
- ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
6051
- ...(opts.resolveDashboardRenderer !== undefined
6052
- ? { resolveDashboardRenderer: opts.resolveDashboardRenderer }
6053
- : {}),
6054
- }).run()
6055
- } finally {
6056
- await web?.close()
6057
- await opened?.store.close()
6058
- }
6059
- return
6060
- }
6228
+ // A viewer is an operator reading another process's run, even when mode
6229
+ // selection (dispatcher work) chose it.
6230
+ if (opts.viewer) return withStoreCaller(DISPATCH_VIEWER_CALLER, () => runDispatchViewer(opts))
6061
6231
  if (opts.dispatchedBy !== undefined) throw new Error('--dispatched-by requires --viewer')
6062
6232
  const budget = opts.invocationBudget
6063
6233
  if (budget === undefined) return dispatchKernelPath(opts)
@@ -6083,6 +6253,84 @@ async function abDispatchInScope(opts: DispatchOpts): Promise<void> {
6083
6253
  }
6084
6254
  }
6085
6255
 
6256
+ /** The viewer half of `abDispatch`: an operator client reading the run
6257
+ * another process dispatches. */
6258
+ async function runDispatchViewer(opts: DispatchOpts): Promise<void> {
6259
+ if (opts.repository !== undefined)
6260
+ throw new Error('--viewer requires a local checkout; omit --repository')
6261
+ if (opts.intake !== undefined) throw new Error('--viewer cannot set startup intake')
6262
+ if (opts.dispatchedBy !== undefined && !opts.dispatchedBy.trim())
6263
+ throw new Error('--dispatched-by requires a nonblank label')
6264
+ const state = await resolveRepoState({
6265
+ targetRepo: opts.targetRepo,
6266
+ exec: opts.exec,
6267
+ ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
6268
+ ...(opts.env.AB_STORE !== undefined ? { envStore: opts.env.AB_STORE } : {}),
6269
+ })
6270
+ const env = {
6271
+ ...opts.env,
6272
+ AB_STORE: state.storeRef,
6273
+ ...(isRemoteStoreRef(state.storeRef)
6274
+ ? { AB_TOKEN: projectToken(state.storeRef, state.repo, opts.env) }
6275
+ : {}),
6276
+ }
6277
+ const web = await startOptionalDispatchWeb(opts, opts.repo ?? state.repo)
6278
+ let opened: ReturnType<typeof openStoreForRepoState> | undefined
6279
+ try {
6280
+ opened = openStoreForRepoState(state, { env })
6281
+ const interactive =
6282
+ opts.plain !== true && opts.terminal?.interactive === true && opts.input !== undefined
6283
+ // Without a TTY the web UI is the only presentation: the viewer reads
6284
+ // exactly as it would, and its text frames are discarded.
6285
+ const plainOutput = web !== undefined ? () => {} : opts.stdout
6286
+ const store = opened
6287
+ web?.attachStore(store.store)
6288
+ await new DispatchFrontend({
6289
+ viewer: { ...(opts.dispatchedBy !== undefined ? { dispatchedBy: opts.dispatchedBy } : {}) },
6290
+ repo: opts.repo ?? state.repo,
6291
+ checkout: state.checkout,
6292
+ store: store.store,
6293
+ storeRef: store.storeRef,
6294
+ env,
6295
+ terminal: opts.terminal ?? {
6296
+ columns: 100,
6297
+ rows: 24,
6298
+ interactive: false,
6299
+ write: () => {},
6300
+ modes: createTerminalModeController(
6301
+ () => {},
6302
+ () => {},
6303
+ ),
6304
+ },
6305
+ input: opts.input ?? { start: () => () => {} },
6306
+ ...(!interactive ? { plainOutput } : {}),
6307
+ ...(web !== undefined ? { web: { dispatch: web } } : {}),
6308
+ controlTickets: () =>
6309
+ lazyTicketSource(() =>
6310
+ openTicketSource(
6311
+ {
6312
+ targetRepo: state.checkout,
6313
+ exec: opts.exec,
6314
+ env,
6315
+ storeRef: store.storeRef,
6316
+ stdout: opts.stdout,
6317
+ },
6318
+ 'ab merge',
6319
+ ),
6320
+ ),
6321
+ once: opts.once === true,
6322
+ ...(opts.intervalMs !== undefined ? { intervalMs: opts.intervalMs } : {}),
6323
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
6324
+ ...(opts.resolveDashboardRenderer !== undefined
6325
+ ? { resolveDashboardRenderer: opts.resolveDashboardRenderer }
6326
+ : {}),
6327
+ }).run()
6328
+ } finally {
6329
+ await web?.close()
6330
+ await opened?.store.close()
6331
+ }
6332
+ }
6333
+
6086
6334
  /** `abDispatch` after the viewer branch: origin config, repository state,
6087
6335
  * the interactive frontend, or the in-process kernel. */
6088
6336
  async function dispatchKernelPath(opts: DispatchOpts): Promise<void> {
@@ -6360,224 +6608,230 @@ async function runDispatchKernel(
6360
6608
  launchContext(resolvedOpts.env)?.run ??
6361
6609
  `${hostname()}-dispatch-${wiring.ids('inst')}`
6362
6610
  resolvedOpts.runId = runId
6363
- // Construction eagerly validates every startup role before repository
6364
- // settings or runner work can mutate durable state. The publisher is used
6365
- // only by later watch refreshes.
6366
- const liveConfig = new LiveConfig(
6367
- configPath,
6368
- config,
6369
- localContent === undefined ? configContent : { committed: configContent, local: localContent },
6370
- wiring.runtimes,
6371
- async ({ content, localOverrides, effectiveConfig, restartRequired, effectiveChanged }) => {
6372
- await wiring.store.appendRepoWithArtifacts(
6373
- state.repo,
6374
- [
6375
- {
6376
- kind: DISPATCHER_CONFIG_ARTIFACT,
6377
- content,
6378
- metadata: {
6379
- restartRequired: [...restartRequired],
6380
- effectiveChanged,
6381
- ...(localOverrides ? { localOverrides } : {}),
6611
+ // Every hosted request from here on is attributed to this run; a hosted
6612
+ // invocation id survives and its setup stage ends.
6613
+ return withDispatcherRun(runId, async () => {
6614
+ // Construction eagerly validates every startup role before repository
6615
+ // settings or runner work can mutate durable state. The publisher is used
6616
+ // only by later watch refreshes.
6617
+ const liveConfig = new LiveConfig(
6618
+ configPath,
6619
+ config,
6620
+ localContent === undefined
6621
+ ? configContent
6622
+ : { committed: configContent, local: localContent },
6623
+ wiring.runtimes,
6624
+ async ({ content, localOverrides, effectiveConfig, restartRequired, effectiveChanged }) => {
6625
+ await wiring.store.appendRepoWithArtifacts(
6626
+ state.repo,
6627
+ [
6628
+ {
6629
+ kind: DISPATCHER_CONFIG_ARTIFACT,
6630
+ content,
6631
+ metadata: {
6632
+ restartRequired: [...restartRequired],
6633
+ effectiveChanged,
6634
+ ...(localOverrides ? { localOverrides } : {}),
6635
+ },
6382
6636
  },
6637
+ {
6638
+ kind: _effectiveConfigKind,
6639
+ content: effectiveBuildConfigContent(effectiveConfig),
6640
+ metadata: {
6641
+ run: runId,
6642
+ effectiveChanged,
6643
+ ...(localOverrides ? { localOverrides } : {}),
6644
+ },
6645
+ },
6646
+ ],
6647
+ (deposited) => {
6648
+ const artifact = deposited[0]
6649
+ const effectiveArtifact = deposited[1]
6650
+ if (artifact === undefined || effectiveArtifact === undefined) {
6651
+ throw new Error('config reload deposit returned incomplete artifacts')
6652
+ }
6653
+ return {
6654
+ actor: DISPATCHER,
6655
+ type: 'dispatcher.config-reloaded',
6656
+ payload: {
6657
+ artifact: { kind: artifact.kind, rev: artifact.revision },
6658
+ restartRequired: [...restartRequired],
6659
+ effectiveChanged,
6660
+ run: runId,
6661
+ effectiveConfig: {
6662
+ kind: effectiveArtifact.kind,
6663
+ rev: effectiveArtifact.revision,
6664
+ },
6665
+ roleWarnings: startupWarnings(effectiveConfig, wiring.forge),
6666
+ },
6667
+ }
6383
6668
  },
6669
+ )
6670
+ wiring.updateRuntimeReferences?.(effectiveConfig)
6671
+ },
6672
+ startupDeprecations,
6673
+ (next) => {
6674
+ assertReadyAssigneeAccepted(next.tickets, wiring.tickets)
6675
+ assertCreateAssigneeAccepted(next.tickets, wiring.tickets)
6676
+ assertHooksDeliverable(next, resolvedOpts)
6677
+ },
6678
+ {
6679
+ ...(localSource !== undefined ? { localSource } : {}),
6680
+ ...(startupLocalOverrides ? { startupLocalOverrides } : {}),
6681
+ },
6682
+ )
6683
+
6684
+ // Every own lifecycle append goes through one view, restored from snapshots
6685
+ // before the first of them, so a quiet invocation reads none of its own
6686
+ // rows back and the final flush covers `run-stopped` too.
6687
+ const view = new RepoViewStore(wiring.store, {
6688
+ // The loop's store-keyed identity (an explicit `repo` pins it).
6689
+ repo: resolvedOpts.repo ?? resolvedOpts.targetRepo,
6690
+ resident: resolvedOpts.once !== true,
6691
+ // `--web` shows what these journal refreshes read. Their frames carry no
6692
+ // change position, so while a browser is connected each one reads one
6693
+ // `getRepoChangePosition` for the page's refetch signal; nothing else.
6694
+ ...(web !== undefined ? { onRepositoryFacts: (facts) => web.publishFacts(facts) } : {}),
6695
+ })
6696
+ web?.attachStore(wiring.store)
6697
+ let started: Awaited<ReturnType<RepoViewStore['appendRepoWithArtifacts']>>
6698
+ try {
6699
+ // Launch flags are durable repository setters. Omission writes nothing, so
6700
+ // another dispatcher cannot clobber the latest operator choice with a value
6701
+ // it inferred at startup. Fresh-repository fallbacks live in the reducer.
6702
+ await wiring.store.ensureRepo(state.repo)
6703
+ await view.startJournal()
6704
+ const actor = humanActor(buildControlUser(resolvedOpts.env))
6705
+ if (resolvedOpts.intake !== undefined) {
6706
+ await view.appendRepo(state.repo, {
6707
+ actor,
6708
+ type: 'dispatcher.intake-set',
6709
+ payload: { enabled: resolvedOpts.intake, run: runId },
6710
+ })
6711
+ }
6712
+
6713
+ started = await view.appendRepoWithArtifacts(
6714
+ state.repo,
6715
+ [
6384
6716
  {
6385
6717
  kind: _effectiveConfigKind,
6386
- content: effectiveBuildConfigContent(effectiveConfig),
6718
+ content: effectiveBuildConfigContent(config),
6387
6719
  metadata: {
6388
6720
  run: runId,
6389
- effectiveChanged,
6390
- ...(localOverrides ? { localOverrides } : {}),
6721
+ revision: 0,
6722
+ ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6391
6723
  },
6392
6724
  },
6393
6725
  ],
6394
6726
  (deposited) => {
6395
6727
  const artifact = deposited[0]
6396
- const effectiveArtifact = deposited[1]
6397
- if (artifact === undefined || effectiveArtifact === undefined) {
6398
- throw new Error('config reload deposit returned incomplete artifacts')
6399
- }
6728
+ if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6400
6729
  return {
6401
6730
  actor: DISPATCHER,
6402
- type: 'dispatcher.config-reloaded',
6731
+ type: 'dispatcher.run-started',
6403
6732
  payload: {
6404
- artifact: { kind: artifact.kind, rev: artifact.revision },
6405
- restartRequired: [...restartRequired],
6406
- effectiveChanged,
6407
6733
  run: runId,
6408
- effectiveConfig: {
6409
- kind: effectiveArtifact.kind,
6410
- rev: effectiveArtifact.revision,
6411
- },
6412
- roleWarnings: startupWarnings(effectiveConfig, wiring.forge),
6734
+ ...(launchContext(resolvedOpts.env)?.lineage
6735
+ ? { lineage: launchContext(resolvedOpts.env)!.lineage }
6736
+ : {}),
6737
+ pid: process.pid,
6738
+ host: hostname(),
6739
+ effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
6740
+ roleWarnings: startupWarnings(config, wiring.forge),
6413
6741
  },
6414
6742
  }
6415
6743
  },
6416
6744
  )
6417
- wiring.updateRuntimeReferences?.(effectiveConfig)
6418
- },
6419
- startupDeprecations,
6420
- (next) => {
6421
- assertReadyAssigneeAccepted(next.tickets, wiring.tickets)
6422
- assertCreateAssigneeAccepted(next.tickets, wiring.tickets)
6423
- assertHooksDeliverable(next, resolvedOpts)
6424
- },
6425
- {
6426
- ...(localSource !== undefined ? { localSource } : {}),
6427
- ...(startupLocalOverrides ? { startupLocalOverrides } : {}),
6428
- },
6429
- )
6745
+ } catch (error) {
6746
+ if (budget === undefined || !budget.work.aborted) throw error
6747
+ // The work deadline cut a startup write off. The `run-started` deposit
6748
+ // may still have committed with its response lost, so the bounded
6749
+ // canonical repository value decides whether this run exists.
6750
+ const recordedStart = await stopAmbiguousStart(budget, wiring.store, state.repo, runId)
6751
+ await finalStep(budget, async () => {
6752
+ await wiring.releaseAccounts?.()
6753
+ if (resolvedOpts.wire === undefined) await wiring.store.close()
6754
+ }).catch(() => {})
6755
+ if (!recordedStart) throw new InvocationBudgetExhaustedError(undefined, { cause: error })
6756
+ if (resolvedOpts.silent !== true)
6757
+ resolvedOpts.stdout(
6758
+ 'ab dispatch — invocation work deadline reached during startup; the run stopped, remaining work resumes next invocation',
6759
+ )
6760
+ return
6761
+ }
6430
6762
 
6431
- // Every own lifecycle append goes through one view, restored from snapshots
6432
- // before the first of them, so a quiet invocation reads none of its own
6433
- // rows back and the final flush covers `run-stopped` too.
6434
- const view = new RepoViewStore(wiring.store, {
6435
- // The loop's store-keyed identity (an explicit `repo` pins it).
6436
- repo: resolvedOpts.repo ?? resolvedOpts.targetRepo,
6437
- resident: resolvedOpts.once !== true,
6438
- // `--web` shows what these journal refreshes read. Their frames carry no
6439
- // change position, so while a browser is connected each one reads one
6440
- // `getRepoChangePosition` for the page's refetch signal; nothing else.
6441
- ...(web !== undefined ? { onRepositoryFacts: (facts) => web.publishFacts(facts) } : {}),
6442
- })
6443
- web?.attachStore(wiring.store)
6444
- let started: Awaited<ReturnType<RepoViewStore['appendRepoWithArtifacts']>>
6445
- try {
6446
- // Launch flags are durable repository setters. Omission writes nothing, so
6447
- // another dispatcher cannot clobber the latest operator choice with a value
6448
- // it inferred at startup. Fresh-repository fallbacks live in the reducer.
6449
- await wiring.store.ensureRepo(state.repo)
6450
- await view.startJournal()
6451
- const actor = humanActor(buildControlUser(resolvedOpts.env))
6452
- if (resolvedOpts.intake !== undefined) {
6763
+ try {
6453
6764
  await view.appendRepo(state.repo, {
6454
- actor,
6455
- type: 'dispatcher.intake-set',
6456
- payload: { enabled: resolvedOpts.intake, run: runId },
6765
+ actor: DISPATCHER,
6766
+ type: 'dispatcher.runtime-recorded',
6767
+ payload: { run: runId, startedSeq: started.event.seq, runtime: runtimeIdentity() },
6457
6768
  })
6458
- }
6459
-
6460
- started = await view.appendRepoWithArtifacts(
6461
- state.repo,
6462
- [
6463
- {
6464
- kind: _effectiveConfigKind,
6465
- content: effectiveBuildConfigContent(config),
6466
- metadata: {
6467
- run: runId,
6468
- revision: 0,
6469
- ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6470
- },
6471
- },
6472
- ],
6473
- (deposited) => {
6474
- const artifact = deposited[0]
6475
- if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6476
- return {
6477
- actor: DISPATCHER,
6478
- type: 'dispatcher.run-started',
6479
- payload: {
6480
- run: runId,
6481
- ...(launchContext(resolvedOpts.env)?.lineage
6482
- ? { lineage: launchContext(resolvedOpts.env)!.lineage }
6483
- : {}),
6484
- pid: process.pid,
6485
- host: hostname(),
6486
- effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
6487
- roleWarnings: startupWarnings(config, wiring.forge),
6488
- },
6489
- }
6490
- },
6491
- )
6492
- } catch (error) {
6493
- if (budget === undefined || !budget.work.aborted) throw error
6494
- // The work deadline cut a startup write off. The `run-started` deposit
6495
- // may still have committed with its response lost, so the bounded
6496
- // canonical repository value decides whether this run exists.
6497
- const recordedStart = await stopAmbiguousStart(budget, wiring.store, state.repo, runId)
6498
- await finalStep(budget, async () => {
6499
- await wiring.releaseAccounts?.()
6500
- if (resolvedOpts.wire === undefined) await wiring.store.close()
6501
- }).catch(() => {})
6502
- if (!recordedStart) throw new InvocationBudgetExhaustedError(undefined, { cause: error })
6503
- if (resolvedOpts.silent !== true)
6504
- resolvedOpts.stdout(
6505
- 'ab dispatch — invocation work deadline reached during startup; the run stopped, remaining work resumes next invocation',
6506
- )
6507
- return
6508
- }
6509
6769
 
6510
- try {
6511
- await view.appendRepo(state.repo, {
6512
- actor: DISPATCHER,
6513
- type: 'dispatcher.runtime-recorded',
6514
- payload: { run: runId, startedSeq: started.event.seq, runtime: runtimeIdentity() },
6515
- })
6516
-
6517
- const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
6518
- await loop.run()
6519
- if (loop.stoppedAtDeadline && resolvedOpts.silent !== true) {
6520
- resolvedOpts.stdout(
6521
- 'ab dispatch — invocation work deadline reached; teardown complete, remaining work resumes next invocation',
6522
- )
6523
- }
6524
- const stopRequest =
6525
- resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted
6526
- ? (await readDispatcherRunFacts(wiring.store, state.repo, runId)).value.stopRequest
6527
- : undefined
6528
- const stoppedSignal =
6529
- stopRequest?.type === 'dispatcher.stop-requested'
6530
- ? stopRequest.payload.signal
6531
- : typeof resolvedOpts.signal?.reason === 'string'
6532
- ? resolvedOpts.signal.reason
6770
+ const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
6771
+ await loop.run()
6772
+ if (loop.stoppedAtDeadline && resolvedOpts.silent !== true) {
6773
+ resolvedOpts.stdout(
6774
+ 'ab dispatch — invocation work deadline reached; teardown complete, remaining work resumes next invocation',
6775
+ )
6776
+ }
6777
+ const stopRequest =
6778
+ resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted
6779
+ ? (await readDispatcherRunFacts(wiring.store, state.repo, runId)).value.stopRequest
6533
6780
  : undefined
6534
- await finalStep(budget, () =>
6535
- view.appendRepo(state.repo, {
6536
- actor: DISPATCHER,
6537
- type: 'dispatcher.run-stopped',
6538
- payload: {
6539
- run: runId,
6540
- outcome: 'normal',
6541
- exitCode: 0,
6542
- ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6543
- ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6544
- },
6545
- }),
6546
- )
6547
- } catch (error) {
6548
- // A bounded invocation past its work deadline stopped on budget, however
6549
- // the adapter wrapped the abort: a clean stop, not a loss.
6550
- const budgetStop = budget?.work.aborted === true
6551
- const tickFailed = error instanceof DispatchTickFailedError
6552
- const original = tickFailed ? error.cause : error
6553
- try {
6781
+ const stoppedSignal =
6782
+ stopRequest?.type === 'dispatcher.stop-requested'
6783
+ ? stopRequest.payload.signal
6784
+ : typeof resolvedOpts.signal?.reason === 'string'
6785
+ ? resolvedOpts.signal.reason
6786
+ : undefined
6554
6787
  await finalStep(budget, () =>
6555
6788
  view.appendRepo(state.repo, {
6556
6789
  actor: DISPATCHER,
6557
6790
  type: 'dispatcher.run-stopped',
6558
- payload: budgetStop
6559
- ? { run: runId, outcome: 'normal', exitCode: 0 }
6560
- : {
6561
- run: runId,
6562
- outcome: tickFailed ? 'normal' : 'abnormal',
6563
- exitCode: 1,
6564
- error: original instanceof Error ? original.message : String(original),
6565
- },
6791
+ payload: {
6792
+ run: runId,
6793
+ outcome: 'normal',
6794
+ exitCode: 0,
6795
+ ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6796
+ ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6797
+ },
6566
6798
  }),
6567
6799
  )
6568
- } catch {
6569
- // Preserve the kernel failure; the supervising frontend records exit.
6800
+ } catch (error) {
6801
+ // A bounded invocation past its work deadline stopped on budget, however
6802
+ // the adapter wrapped the abort: a clean stop, not a loss.
6803
+ const budgetStop = budget?.work.aborted === true
6804
+ const tickFailed = error instanceof DispatchTickFailedError
6805
+ const original = tickFailed ? error.cause : error
6806
+ try {
6807
+ await finalStep(budget, () =>
6808
+ view.appendRepo(state.repo, {
6809
+ actor: DISPATCHER,
6810
+ type: 'dispatcher.run-stopped',
6811
+ payload: budgetStop
6812
+ ? { run: runId, outcome: 'normal', exitCode: 0 }
6813
+ : {
6814
+ run: runId,
6815
+ outcome: tickFailed ? 'normal' : 'abnormal',
6816
+ exitCode: 1,
6817
+ error: original instanceof Error ? original.message : String(original),
6818
+ },
6819
+ }),
6820
+ )
6821
+ } catch {
6822
+ // Preserve the kernel failure; the supervising frontend records exit.
6823
+ }
6824
+ if (!budgetStop) throw original
6825
+ } finally {
6826
+ // Every append this invocation made, `run-stopped` included, is in the
6827
+ // view; leave the reduced state behind so the next cold process reads
6828
+ // only what is newer than it.
6829
+ await finalStep(budget, async () => {
6830
+ await wiring.releaseAccounts?.()
6831
+ if (resolvedOpts.wire === undefined) await wiring.store.close()
6832
+ })
6570
6833
  }
6571
- if (!budgetStop) throw original
6572
- } finally {
6573
- // Every append this invocation made, `run-stopped` included, is in the
6574
- // view; leave the reduced state behind so the next cold process reads
6575
- // only what is newer than it.
6576
- await finalStep(budget, async () => {
6577
- await wiring.releaseAccounts?.()
6578
- if (resolvedOpts.wire === undefined) await wiring.store.close()
6579
- })
6580
- }
6834
+ })
6581
6835
  }
6582
6836
 
6583
6837
  /** A bounded invocation whose startup the work deadline cut off: when the