@defrex/autobuild 1.16.0 → 1.18.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 (97) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +132 -9
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +42 -3
  5. package/docs/configuration.md +44 -7
  6. package/docs/dispatcher-hosting.md +5 -3
  7. package/docs/operator-api.md +29 -6
  8. package/docs/plugin-authoring.md +30 -1
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +37 -2
  11. package/docs/restacking.md +46 -1
  12. package/docs/setup.md +24 -9
  13. package/docs/ticket-sources.md +28 -1
  14. package/docs/troubleshooting.md +54 -2
  15. package/docs/workspaces.md +3 -1
  16. package/package.json +4 -4
  17. package/packages/core/src/cli/accounts.ts +3 -0
  18. package/packages/core/src/cli/binary-direct.ts +14 -1
  19. package/packages/core/src/cli/binary.ts +10 -7
  20. package/packages/core/src/cli/dashboard/refresh.ts +8 -0
  21. package/packages/core/src/cli/dispatch.ts +503 -334
  22. package/packages/core/src/cli/secrets.ts +2 -0
  23. package/packages/core/src/config/schema.ts +17 -3
  24. package/packages/core/src/events/payloads.ts +8 -5
  25. package/packages/core/src/events/repository.ts +37 -1
  26. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  27. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  28. package/packages/core/src/kernel/engine.ts +118 -0
  29. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  30. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  31. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  32. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  33. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  34. package/packages/core/src/ontology.ts +1 -0
  35. package/packages/core/src/operator/index.ts +10 -0
  36. package/packages/core/src/operator/merged-builds.ts +51 -0
  37. package/packages/core/src/operator/registry.ts +254 -110
  38. package/packages/core/src/operator/repo-argument.ts +43 -0
  39. package/packages/core/src/operator/tickets.ts +139 -25
  40. package/packages/core/src/plugin-sdk/index.ts +4 -0
  41. package/packages/core/src/plugins/manifest.ts +1 -1
  42. package/packages/core/src/ports/tickets/completion.ts +71 -0
  43. package/packages/core/src/ports/tickets/contract.ts +73 -0
  44. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  45. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  46. package/packages/core/src/ports/tickets/github.ts +18 -6
  47. package/packages/core/src/ports/tickets/grants.ts +2 -0
  48. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  49. package/packages/core/src/ports/tickets/linear.ts +18 -2
  50. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  51. package/packages/core/src/ports/tickets/remote.ts +43 -3
  52. package/packages/core/src/ports/tickets/tree.ts +11 -1
  53. package/packages/core/src/ports/types.ts +47 -4
  54. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  55. package/packages/core/src/ports/workspace/vercel-sandbox.ts +649 -160
  56. package/packages/core/src/processes/build-child.ts +15 -1
  57. package/packages/core/src/processes/build-runner.ts +349 -20
  58. package/packages/core/src/processes/dispatcher.ts +880 -283
  59. package/packages/core/src/processes/harvest-child.ts +21 -1
  60. package/packages/core/src/processes/harvest-runner.ts +82 -35
  61. package/packages/core/src/processes/pass-stages.ts +32 -6
  62. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  63. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  64. package/packages/core/src/processes/repo-view.ts +25 -4
  65. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  66. package/packages/core/src/store/adapter.ts +34 -5
  67. package/packages/core/src/store/build-feed.ts +148 -22
  68. package/packages/core/src/store/build-scope.ts +12 -3
  69. package/packages/core/src/store/caller-attribution.ts +170 -0
  70. package/packages/core/src/store/contract.ts +1038 -165
  71. package/packages/core/src/store/local/schema.ts +12 -1
  72. package/packages/core/src/store/local/store.ts +260 -25
  73. package/packages/core/src/store/memory.ts +156 -9
  74. package/packages/core/src/store/phase-session.ts +23 -3
  75. package/packages/core/src/store/reducer-value-shapes.json +8196 -8118
  76. package/packages/core/src/store/remote/client.ts +90 -11
  77. package/packages/core/src/store/remote/credentials.ts +2 -0
  78. package/packages/core/src/store/remote/index.ts +31 -5
  79. package/packages/core/src/store/remote/protocol.ts +45 -8
  80. package/packages/core/src/store/remote/released-clients.json +22 -0
  81. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  82. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  83. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  84. package/packages/core/src/store/session-handle.ts +12 -3
  85. package/packages/core/src/store/types.ts +48 -3
  86. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  87. package/packages/core/src/testing/index.ts +2 -0
  88. package/packages/core/src/testing/reduced-read-budget.ts +420 -6
  89. package/skills/guide/SKILL.md +67 -13
  90. package/skills/guide/references/operator-api.md +29 -6
  91. package/skills/guide/references/plugin-authoring.md +30 -1
  92. package/skills/guide/references/remote-store-protocol.md +13 -3
  93. package/skills/guide/references/remote-ticket-protocol.md +37 -2
  94. package/skills/guide/references/restacking.md +46 -1
  95. package/skills/guide/references/setup.md +24 -9
  96. package/skills/operate/SKILL.md +42 -4
  97. 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,
@@ -435,6 +442,8 @@ export interface DispatchWiring {
435
442
  export type DispatchNonStoreWiring = Omit<DispatchWiring, 'store' | 'storeRef' | 'token'>
436
443
 
437
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'
438
447
  export {
439
448
  createInvocationBudget,
440
449
  teardownReserveMs,
@@ -915,6 +924,40 @@ export class DispatchTickFailedError extends Error {
915
924
  }
916
925
  }
917
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
+
918
961
  class DispatchLoop {
919
962
  private readonly dispatcher: Dispatcher
920
963
  /** The incremental repository view (AUT-647) the dispatcher and this
@@ -937,7 +980,10 @@ class DispatchLoop {
937
980
  * before awaits; the durable lease remains the cross-kernel exclusion gate. */
938
981
  private readonly activeBuildRuns = new Map<string, ActiveBuildExecution>()
939
982
  private acceptingBuildLaunches = true
940
- /** 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. */
941
987
  private localHarvestShutdown = new AbortController()
942
988
  private localHarvestFailure: unknown
943
989
  private harvestInFlight: Promise<void> | undefined
@@ -950,6 +996,13 @@ class DispatchLoop {
950
996
  private hostedHarvest:
951
997
  | { execution: string; handle: BuildExecutionHandle; detached: { value: boolean } }
952
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
953
1006
  /** Execution ids THIS process supervises; the dispatcher's harvest
954
1007
  * settlement stage skips them (their completion chain owns the facts). */
955
1008
  private readonly hostedHarvestExecutions = new Set<string>()
@@ -2740,8 +2793,22 @@ class DispatchLoop {
2740
2793
  // dispatch process is independently excluded by the repository lease.
2741
2794
  if (this.stopped || this.harvestInFlight !== undefined || this.missingAccounts().length) return
2742
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
+ }
2743
2810
  let tracked: Promise<void>
2744
- tracked = this.launchHarvestIfNeeded()
2811
+ tracked = this.launchHarvestIfNeeded(hosted)
2745
2812
  .catch((error: unknown) => {
2746
2813
  if (isRepositoryAuthorityLapse(error)) return
2747
2814
  if (this.stopped || this.localHarvestShutdown.signal.aborted)
@@ -2757,12 +2824,22 @@ class DispatchLoop {
2757
2824
  .finally(() => {
2758
2825
  this.inFlight.delete(tracked)
2759
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
+ }
2760
2833
  })
2761
2834
  this.harvestInFlight = tracked
2762
2835
  this.inFlight.add(tracked)
2763
2836
  }
2764
2837
 
2765
- private async launchHarvestIfNeeded(): Promise<void> {
2838
+ private async launchHarvestIfNeeded(hostedLaunch?: {
2839
+ prelaunch: { resolve: () => void }
2840
+ fence: HostedHarvestFence
2841
+ shutdown: AbortSignal
2842
+ }): Promise<void> {
2766
2843
  const state = this.repoView.repositoryFacts().harvest
2767
2844
  const control = decideHarvestControl(state, this.maxHarvestRecoveryAttempts)
2768
2845
  if (control.kind === 'park') return
@@ -2774,13 +2851,13 @@ class DispatchLoop {
2774
2851
  })
2775
2852
  if (pressure.trigger === undefined) return
2776
2853
  }
2777
- if (this.stopped) return
2854
+ if (this.stopped || hostedLaunch?.shutdown.aborted === true) return
2778
2855
  const hosted = this.wiring.workspaces.harvestExecution
2779
- if (hosted !== undefined) {
2856
+ if (hosted !== undefined && hostedLaunch !== undefined) {
2780
2857
  const execution = `${this.host}-harvest-${this.wiring.ids('inst')}`
2781
2858
  this.hostedHarvestExecutions.add(execution)
2782
2859
  try {
2783
- await this.launchHostedHarvest(hosted, execution)
2860
+ await this.launchHostedHarvest(hosted, execution, hostedLaunch)
2784
2861
  } finally {
2785
2862
  this.hostedHarvestExecutions.delete(execution)
2786
2863
  }
@@ -2878,6 +2955,8 @@ class DispatchLoop {
2878
2955
  url: storeRef,
2879
2956
  token: buildScoped,
2880
2957
  ...(fetchFn !== undefined ? { fetchFn } : {}),
2958
+ // Its ending append and close run after the runner returns.
2959
+ caller: harvestRunnerCaller(prepared.run, harvestDeps.instance),
2881
2960
  })
2882
2961
  }
2883
2962
  const sessionEnv = {
@@ -2970,6 +3049,8 @@ class DispatchLoop {
2970
3049
  url: storeRef,
2971
3050
  token: scoped,
2972
3051
  ...(fetchFn !== undefined ? { fetchFn } : {}),
3052
+ // Its ending append and close run after the runner returns.
3053
+ caller: harvestRunnerCaller(prepared.run, harvestDeps.instance),
2973
3054
  })
2974
3055
  try {
2975
3056
  const runnerTickets =
@@ -3079,9 +3160,18 @@ class DispatchLoop {
3079
3160
  private async launchHostedHarvest(
3080
3161
  harvestExecution: HarvestExecution,
3081
3162
  execution: string,
3163
+ launch: {
3164
+ prelaunch: { resolve: () => void }
3165
+ fence: HostedHarvestFence
3166
+ shutdown: AbortSignal
3167
+ },
3082
3168
  ): Promise<void> {
3083
3169
  const { store, storeRef } = this.wiring
3084
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
3085
3175
  let handle: BuildExecutionHandle | undefined
3086
3176
  let startedSeq: number | undefined
3087
3177
  let ticketAuthority: { url: string; token: string; id: string } | undefined
@@ -3091,6 +3181,7 @@ class DispatchLoop {
3091
3181
  // entry is cleared, or the chain would classify and reap a live guest.
3092
3182
  const detached = { value: false }
3093
3183
  try {
3184
+ if (cancelled()) return
3094
3185
  // Threshold gate before any provisioning — with resume precedence. The
3095
3186
  // runner's real check runs in the guest after a full provisioning
3096
3187
  // chain, and its order is resume-first, pressure-second: it settles
@@ -3105,6 +3196,7 @@ class DispatchLoop {
3105
3196
  // reduces durable types only. Take the journal delta first — guests and
3106
3197
  // other dispatchers write harvest facts between ticks.
3107
3198
  await this.repoView.refreshJournal()
3199
+ if (cancelled()) return
3108
3200
  const events = this.repoView.repositoryFacts().harvest
3109
3201
  const state = events
3110
3202
  const control = decideHarvestControl(state, this.maxHarvestRecoveryAttempts)
@@ -3126,34 +3218,46 @@ class DispatchLoop {
3126
3218
  policy: this.currentConfig().config.policy,
3127
3219
  })
3128
3220
  if (pressure.trigger === undefined) return
3221
+ if (cancelled()) return
3129
3222
  }
3130
3223
 
3131
- const prepared = await this.prepareHarvest(execution)
3224
+ if (cancelled()) return
3225
+ this.requireRepoAuthority()
3226
+ const prepared = await fence.run(() => this.prepareHarvest(execution))
3132
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
3133
3232
  this.requireRepoAuthority()
3134
- await this.repoView.appendRepo(repo, {
3135
- actor: DISPATCHER,
3136
- type: 'harvest.execution.authorized',
3137
- payload: {
3138
- execution,
3139
- run: prepared.run,
3140
- launch: prepared.launch,
3141
- leaseHolder: this.repoLeaseHolder ?? execution,
3142
- },
3143
- })
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
+ )
3144
3246
  const launchAuth = /^https?:/i.test(storeRef)
3145
3247
  ? {
3146
- token: await (this.wiring.credentialIssuer ?? delegateCredential)(
3147
- storeRef,
3148
- this.wiring.token,
3149
- {
3150
- kind: 'harvest-runner',
3151
- execution,
3152
- repo,
3153
- id: prepared.run,
3154
- leaseHolder: this.repoLeaseHolder ?? execution,
3155
- },
3156
- 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
+ ),
3157
3261
  ),
3158
3262
  }
3159
3263
  : undefined
@@ -3189,6 +3293,9 @@ class DispatchLoop {
3189
3293
  })
3190
3294
  }, 60_000)
3191
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
3192
3299
  handle = await harvestExecution.start(
3193
3300
  {
3194
3301
  preparedRun: { run: prepared.run },
@@ -3214,18 +3321,22 @@ class DispatchLoop {
3214
3321
  )
3215
3322
  }
3216
3323
  this.hostedHarvest = { execution, handle, detached }
3217
- const started = await this.repoView.appendRepo(repo, {
3218
- actor: DISPATCHER,
3219
- type: 'harvest.execution.started',
3220
- payload: {
3221
- execution,
3222
- provider: identity.provider,
3223
- environmentId: identity.environmentId,
3224
- ...(identity.sessionId !== undefined ? { sessionId: identity.sessionId } : {}),
3225
- commandId: identity.commandId,
3226
- },
3227
- })
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
+ )
3228
3338
  startedSeq = started.seq
3339
+ launch.prelaunch.resolve()
3229
3340
 
3230
3341
  await handle.completion
3231
3342
  if (detached.value) {
@@ -3252,7 +3363,7 @@ class DispatchLoop {
3252
3363
  if (result.outcome === 'failed') this.failureNotice(line)
3253
3364
  else this.say(line)
3254
3365
  }
3255
- await this.releaseHostedHarvest(repo, execution, handle)
3366
+ await this.releaseHostedHarvest(repo, execution, handle, fence)
3256
3367
  } catch (error) {
3257
3368
  // Launch or wait failure: best-effort release attempt, the existing
3258
3369
  // durable failure event + warn path, retried on a later threshold tick.
@@ -3260,26 +3371,29 @@ class DispatchLoop {
3260
3371
  // next run's get-or-create; a marked-but-unlaunched one is reused.
3261
3372
  if (handle !== undefined) {
3262
3373
  try {
3263
- await this.releaseHostedHarvest(repo, execution, handle)
3374
+ await this.releaseHostedHarvest(repo, execution, handle, fence)
3264
3375
  } catch {
3265
3376
  // Left open: durable settlement re-proves and reaps it later.
3266
3377
  }
3267
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
3268
3382
  if (error instanceof MissingAccountCredentialsError) {
3269
- await this.dispatcher.holdForMissingAccounts(error)
3383
+ await fence.run(() => this.dispatcher.holdForMissingAccounts(error))
3270
3384
  return
3271
3385
  }
3272
- // Nothing started without authority; a later tick retries.
3273
- if (isRepositoryAuthorityLapse(error)) return
3274
3386
  this.pendingHarvest.harvestFailed += 1
3275
- await this.appendStatus({
3276
- actor: DISPATCHER,
3277
- type: 'dispatcher.harvest-runner-failed',
3278
- payload: {
3279
- run: this.runId,
3280
- error: error instanceof Error ? error.message : String(error),
3281
- },
3282
- })
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
+ )
3283
3397
  if (!this.stopped) {
3284
3398
  this.warn(
3285
3399
  `harvest runner failed: ${error instanceof Error ? error.message : String(error)}`,
@@ -3319,34 +3433,40 @@ class DispatchLoop {
3319
3433
  }
3320
3434
 
3321
3435
  /** Release the disposable environment through the owning provider's reap
3322
- * 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. */
3323
3439
  private async releaseHostedHarvest(
3324
3440
  repo: string,
3325
3441
  execution: string,
3326
3442
  handle: BuildExecutionHandle,
3443
+ fence?: HostedHarvestFence,
3327
3444
  ): Promise<void> {
3328
3445
  const identity = handle.identity
3329
- if (identity === undefined || identity.environmentId === undefined) return
3446
+ const environmentId = identity?.environmentId
3447
+ if (identity === undefined || environmentId === undefined) return
3330
3448
  const workspaceHandle: WorkspaceHandle = {
3331
3449
  provider: identity.provider,
3332
- ref: identity.environmentId,
3333
- path: identity.environmentId,
3450
+ ref: environmentId,
3451
+ path: environmentId,
3334
3452
  branch: '',
3335
3453
  }
3336
3454
  const reap = await this.reapHostedWorkspace(workspaceHandle)
3337
- await this.repoView.appendRepo(repo, {
3338
- actor: DISPATCHER,
3339
- type: 'harvest.execution.released',
3340
- payload: {
3341
- execution,
3342
- environmentId: identity.environmentId,
3343
- snapshots: {
3344
- outcome: reap.snapshots.outcome === 'unknown' ? 'unknown' : 'confirmed',
3345
- ...(reap.snapshots.deleted !== undefined ? { deleted: reap.snapshots.deleted } : {}),
3346
- ...(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
+ },
3347
3467
  },
3348
- },
3349
- })
3468
+ })
3469
+ await (fence !== undefined ? fence.run(append) : append())
3350
3470
  }
3351
3471
 
3352
3472
  /** Reap through the provider's recovery capability when it reports the
@@ -3379,7 +3499,13 @@ class DispatchLoop {
3379
3499
  if (this.localHarvestFailure !== undefined) throw this.localHarvestFailure
3380
3500
  }
3381
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. */
3382
3506
  private async stopHostedHarvest(): Promise<void> {
3507
+ this.localHarvestShutdown.abort()
3508
+ await this.hostedHarvestPrelaunch
3383
3509
  const entry = this.hostedHarvest
3384
3510
  if (entry === undefined) return
3385
3511
  entry.detached.value = true
@@ -5030,11 +5156,17 @@ class DispatchLoop {
5030
5156
  }
5031
5157
 
5032
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()
5033
5164
  this.stopRepoLeaseHeartbeat()
5034
5165
  const holder = this.repoLeaseHolder
5035
5166
  this.repoLeaseHolder = undefined
5036
5167
  this.repoLeaseValidUntil = 0
5037
5168
  this.leaseGeneration++
5169
+ await fence?.settled()
5038
5170
  if (holder === undefined) return
5039
5171
  try {
5040
5172
  await this.wiring.store.releaseRepoLease(this.repoIdentity, holder)
@@ -5672,7 +5804,11 @@ class DispatchLoop {
5672
5804
  : withInvocationSignal(budget.cleanup, write)
5673
5805
  }
5674
5806
 
5675
- 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> {
5676
5812
  // Whether or not the deadline fired, no launch may start during
5677
5813
  // teardown: provisioning abandonment runs beside execution teardown.
5678
5814
  this.onWorkDeadline()
@@ -6059,90 +6195,39 @@ async function resolveOriginModeState(
6059
6195
  */
6060
6196
  export async function abDispatch(opts: DispatchOpts): Promise<void> {
6061
6197
  // The invocation deadline also bounds every hosted retry this run causes.
6062
- if (opts.deadlineAt === undefined) return abDispatchInScope(opts)
6063
- 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',
6064
6222
  }
6065
6223
 
6066
6224
  async function abDispatchInScope(opts: DispatchOpts): Promise<void> {
6067
6225
  if (opts.kernelRunId === undefined && !launchContext(opts.env)) {
6068
6226
  opts = { ...opts, ...(await selectDispatchMode(opts)) }
6069
6227
  }
6070
- if (opts.viewer) {
6071
- if (opts.repository !== undefined)
6072
- throw new Error('--viewer requires a local checkout; omit --repository')
6073
- if (opts.intake !== undefined) throw new Error('--viewer cannot set startup intake')
6074
- if (opts.dispatchedBy !== undefined && !opts.dispatchedBy.trim())
6075
- throw new Error('--dispatched-by requires a nonblank label')
6076
- const state = await resolveRepoState({
6077
- targetRepo: opts.targetRepo,
6078
- exec: opts.exec,
6079
- ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
6080
- ...(opts.env.AB_STORE !== undefined ? { envStore: opts.env.AB_STORE } : {}),
6081
- })
6082
- const env = {
6083
- ...opts.env,
6084
- AB_STORE: state.storeRef,
6085
- ...(isRemoteStoreRef(state.storeRef)
6086
- ? { AB_TOKEN: projectToken(state.storeRef, state.repo, opts.env) }
6087
- : {}),
6088
- }
6089
- const web = await startOptionalDispatchWeb(opts, opts.repo ?? state.repo)
6090
- let opened: ReturnType<typeof openStoreForRepoState> | undefined
6091
- try {
6092
- opened = openStoreForRepoState(state, { env })
6093
- const interactive =
6094
- opts.plain !== true && opts.terminal?.interactive === true && opts.input !== undefined
6095
- // Without a TTY the web UI is the only presentation: the viewer reads
6096
- // exactly as it would, and its text frames are discarded.
6097
- const plainOutput = web !== undefined ? () => {} : opts.stdout
6098
- const store = opened
6099
- web?.attachStore(store.store)
6100
- await new DispatchFrontend({
6101
- viewer: { ...(opts.dispatchedBy !== undefined ? { dispatchedBy: opts.dispatchedBy } : {}) },
6102
- repo: opts.repo ?? state.repo,
6103
- checkout: state.checkout,
6104
- store: store.store,
6105
- storeRef: store.storeRef,
6106
- env,
6107
- terminal: opts.terminal ?? {
6108
- columns: 100,
6109
- rows: 24,
6110
- interactive: false,
6111
- write: () => {},
6112
- modes: createTerminalModeController(
6113
- () => {},
6114
- () => {},
6115
- ),
6116
- },
6117
- input: opts.input ?? { start: () => () => {} },
6118
- ...(!interactive ? { plainOutput } : {}),
6119
- ...(web !== undefined ? { web: { dispatch: web } } : {}),
6120
- controlTickets: () =>
6121
- lazyTicketSource(() =>
6122
- openTicketSource(
6123
- {
6124
- targetRepo: state.checkout,
6125
- exec: opts.exec,
6126
- env,
6127
- storeRef: store.storeRef,
6128
- stdout: opts.stdout,
6129
- },
6130
- 'ab merge',
6131
- ),
6132
- ),
6133
- once: opts.once === true,
6134
- ...(opts.intervalMs !== undefined ? { intervalMs: opts.intervalMs } : {}),
6135
- ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
6136
- ...(opts.resolveDashboardRenderer !== undefined
6137
- ? { resolveDashboardRenderer: opts.resolveDashboardRenderer }
6138
- : {}),
6139
- }).run()
6140
- } finally {
6141
- await web?.close()
6142
- await opened?.store.close()
6143
- }
6144
- return
6145
- }
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))
6146
6231
  if (opts.dispatchedBy !== undefined) throw new Error('--dispatched-by requires --viewer')
6147
6232
  const budget = opts.invocationBudget
6148
6233
  if (budget === undefined) return dispatchKernelPath(opts)
@@ -6168,6 +6253,84 @@ async function abDispatchInScope(opts: DispatchOpts): Promise<void> {
6168
6253
  }
6169
6254
  }
6170
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
+
6171
6334
  /** `abDispatch` after the viewer branch: origin config, repository state,
6172
6335
  * the interactive frontend, or the in-process kernel. */
6173
6336
  async function dispatchKernelPath(opts: DispatchOpts): Promise<void> {
@@ -6445,224 +6608,230 @@ async function runDispatchKernel(
6445
6608
  launchContext(resolvedOpts.env)?.run ??
6446
6609
  `${hostname()}-dispatch-${wiring.ids('inst')}`
6447
6610
  resolvedOpts.runId = runId
6448
- // Construction eagerly validates every startup role before repository
6449
- // settings or runner work can mutate durable state. The publisher is used
6450
- // only by later watch refreshes.
6451
- const liveConfig = new LiveConfig(
6452
- configPath,
6453
- config,
6454
- localContent === undefined ? configContent : { committed: configContent, local: localContent },
6455
- wiring.runtimes,
6456
- async ({ content, localOverrides, effectiveConfig, restartRequired, effectiveChanged }) => {
6457
- await wiring.store.appendRepoWithArtifacts(
6458
- state.repo,
6459
- [
6460
- {
6461
- kind: DISPATCHER_CONFIG_ARTIFACT,
6462
- content,
6463
- metadata: {
6464
- restartRequired: [...restartRequired],
6465
- effectiveChanged,
6466
- ...(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
+ },
6636
+ },
6637
+ {
6638
+ kind: _effectiveConfigKind,
6639
+ content: effectiveBuildConfigContent(effectiveConfig),
6640
+ metadata: {
6641
+ run: runId,
6642
+ effectiveChanged,
6643
+ ...(localOverrides ? { localOverrides } : {}),
6644
+ },
6467
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
+ }
6468
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
+ [
6469
6716
  {
6470
6717
  kind: _effectiveConfigKind,
6471
- content: effectiveBuildConfigContent(effectiveConfig),
6718
+ content: effectiveBuildConfigContent(config),
6472
6719
  metadata: {
6473
6720
  run: runId,
6474
- effectiveChanged,
6475
- ...(localOverrides ? { localOverrides } : {}),
6721
+ revision: 0,
6722
+ ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6476
6723
  },
6477
6724
  },
6478
6725
  ],
6479
6726
  (deposited) => {
6480
6727
  const artifact = deposited[0]
6481
- const effectiveArtifact = deposited[1]
6482
- if (artifact === undefined || effectiveArtifact === undefined) {
6483
- throw new Error('config reload deposit returned incomplete artifacts')
6484
- }
6728
+ if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6485
6729
  return {
6486
6730
  actor: DISPATCHER,
6487
- type: 'dispatcher.config-reloaded',
6731
+ type: 'dispatcher.run-started',
6488
6732
  payload: {
6489
- artifact: { kind: artifact.kind, rev: artifact.revision },
6490
- restartRequired: [...restartRequired],
6491
- effectiveChanged,
6492
6733
  run: runId,
6493
- effectiveConfig: {
6494
- kind: effectiveArtifact.kind,
6495
- rev: effectiveArtifact.revision,
6496
- },
6497
- 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),
6498
6741
  },
6499
6742
  }
6500
6743
  },
6501
6744
  )
6502
- wiring.updateRuntimeReferences?.(effectiveConfig)
6503
- },
6504
- startupDeprecations,
6505
- (next) => {
6506
- assertReadyAssigneeAccepted(next.tickets, wiring.tickets)
6507
- assertCreateAssigneeAccepted(next.tickets, wiring.tickets)
6508
- assertHooksDeliverable(next, resolvedOpts)
6509
- },
6510
- {
6511
- ...(localSource !== undefined ? { localSource } : {}),
6512
- ...(startupLocalOverrides ? { startupLocalOverrides } : {}),
6513
- },
6514
- )
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
+ }
6515
6762
 
6516
- // Every own lifecycle append goes through one view, restored from snapshots
6517
- // before the first of them, so a quiet invocation reads none of its own
6518
- // rows back and the final flush covers `run-stopped` too.
6519
- const view = new RepoViewStore(wiring.store, {
6520
- // The loop's store-keyed identity (an explicit `repo` pins it).
6521
- repo: resolvedOpts.repo ?? resolvedOpts.targetRepo,
6522
- resident: resolvedOpts.once !== true,
6523
- // `--web` shows what these journal refreshes read. Their frames carry no
6524
- // change position, so while a browser is connected each one reads one
6525
- // `getRepoChangePosition` for the page's refetch signal; nothing else.
6526
- ...(web !== undefined ? { onRepositoryFacts: (facts) => web.publishFacts(facts) } : {}),
6527
- })
6528
- web?.attachStore(wiring.store)
6529
- let started: Awaited<ReturnType<RepoViewStore['appendRepoWithArtifacts']>>
6530
- try {
6531
- // Launch flags are durable repository setters. Omission writes nothing, so
6532
- // another dispatcher cannot clobber the latest operator choice with a value
6533
- // it inferred at startup. Fresh-repository fallbacks live in the reducer.
6534
- await wiring.store.ensureRepo(state.repo)
6535
- await view.startJournal()
6536
- const actor = humanActor(buildControlUser(resolvedOpts.env))
6537
- if (resolvedOpts.intake !== undefined) {
6763
+ try {
6538
6764
  await view.appendRepo(state.repo, {
6539
- actor,
6540
- type: 'dispatcher.intake-set',
6541
- payload: { enabled: resolvedOpts.intake, run: runId },
6765
+ actor: DISPATCHER,
6766
+ type: 'dispatcher.runtime-recorded',
6767
+ payload: { run: runId, startedSeq: started.event.seq, runtime: runtimeIdentity() },
6542
6768
  })
6543
- }
6544
-
6545
- started = await view.appendRepoWithArtifacts(
6546
- state.repo,
6547
- [
6548
- {
6549
- kind: _effectiveConfigKind,
6550
- content: effectiveBuildConfigContent(config),
6551
- metadata: {
6552
- run: runId,
6553
- revision: 0,
6554
- ...(startupLocalOverrides ? { localOverrides: startupLocalOverrides } : {}),
6555
- },
6556
- },
6557
- ],
6558
- (deposited) => {
6559
- const artifact = deposited[0]
6560
- if (artifact === undefined) throw new Error('startup config deposit returned no artifact')
6561
- return {
6562
- actor: DISPATCHER,
6563
- type: 'dispatcher.run-started',
6564
- payload: {
6565
- run: runId,
6566
- ...(launchContext(resolvedOpts.env)?.lineage
6567
- ? { lineage: launchContext(resolvedOpts.env)!.lineage }
6568
- : {}),
6569
- pid: process.pid,
6570
- host: hostname(),
6571
- effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
6572
- roleWarnings: startupWarnings(config, wiring.forge),
6573
- },
6574
- }
6575
- },
6576
- )
6577
- } catch (error) {
6578
- if (budget === undefined || !budget.work.aborted) throw error
6579
- // The work deadline cut a startup write off. The `run-started` deposit
6580
- // may still have committed with its response lost, so the bounded
6581
- // canonical repository value decides whether this run exists.
6582
- const recordedStart = await stopAmbiguousStart(budget, wiring.store, state.repo, runId)
6583
- await finalStep(budget, async () => {
6584
- await wiring.releaseAccounts?.()
6585
- if (resolvedOpts.wire === undefined) await wiring.store.close()
6586
- }).catch(() => {})
6587
- if (!recordedStart) throw new InvocationBudgetExhaustedError(undefined, { cause: error })
6588
- if (resolvedOpts.silent !== true)
6589
- resolvedOpts.stdout(
6590
- 'ab dispatch — invocation work deadline reached during startup; the run stopped, remaining work resumes next invocation',
6591
- )
6592
- return
6593
- }
6594
6769
 
6595
- try {
6596
- await view.appendRepo(state.repo, {
6597
- actor: DISPATCHER,
6598
- type: 'dispatcher.runtime-recorded',
6599
- payload: { run: runId, startedSeq: started.event.seq, runtime: runtimeIdentity() },
6600
- })
6601
-
6602
- const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
6603
- await loop.run()
6604
- if (loop.stoppedAtDeadline && resolvedOpts.silent !== true) {
6605
- resolvedOpts.stdout(
6606
- 'ab dispatch — invocation work deadline reached; teardown complete, remaining work resumes next invocation',
6607
- )
6608
- }
6609
- const stopRequest =
6610
- resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted
6611
- ? (await readDispatcherRunFacts(wiring.store, state.repo, runId)).value.stopRequest
6612
- : undefined
6613
- const stoppedSignal =
6614
- stopRequest?.type === 'dispatcher.stop-requested'
6615
- ? stopRequest.payload.signal
6616
- : typeof resolvedOpts.signal?.reason === 'string'
6617
- ? 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
6618
6780
  : undefined
6619
- await finalStep(budget, () =>
6620
- view.appendRepo(state.repo, {
6621
- actor: DISPATCHER,
6622
- type: 'dispatcher.run-stopped',
6623
- payload: {
6624
- run: runId,
6625
- outcome: 'normal',
6626
- exitCode: 0,
6627
- ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6628
- ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6629
- },
6630
- }),
6631
- )
6632
- } catch (error) {
6633
- // A bounded invocation past its work deadline stopped on budget, however
6634
- // the adapter wrapped the abort: a clean stop, not a loss.
6635
- const budgetStop = budget?.work.aborted === true
6636
- const tickFailed = error instanceof DispatchTickFailedError
6637
- const original = tickFailed ? error.cause : error
6638
- 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
6639
6787
  await finalStep(budget, () =>
6640
6788
  view.appendRepo(state.repo, {
6641
6789
  actor: DISPATCHER,
6642
6790
  type: 'dispatcher.run-stopped',
6643
- payload: budgetStop
6644
- ? { run: runId, outcome: 'normal', exitCode: 0 }
6645
- : {
6646
- run: runId,
6647
- outcome: tickFailed ? 'normal' : 'abnormal',
6648
- exitCode: 1,
6649
- error: original instanceof Error ? original.message : String(original),
6650
- },
6791
+ payload: {
6792
+ run: runId,
6793
+ outcome: 'normal',
6794
+ exitCode: 0,
6795
+ ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
6796
+ ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
6797
+ },
6651
6798
  }),
6652
6799
  )
6653
- } catch {
6654
- // 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
+ })
6655
6833
  }
6656
- if (!budgetStop) throw original
6657
- } finally {
6658
- // Every append this invocation made, `run-stopped` included, is in the
6659
- // view; leave the reduced state behind so the next cold process reads
6660
- // only what is newer than it.
6661
- await finalStep(budget, async () => {
6662
- await wiring.releaseAccounts?.()
6663
- if (resolvedOpts.wire === undefined) await wiring.store.close()
6664
- })
6665
- }
6834
+ })
6666
6835
  }
6667
6836
 
6668
6837
  /** A bounded invocation whose startup the work deadline cut off: when the