@defrex/autobuild 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +465 -163
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +28 -4
  5. package/docs/architecture.md +136 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +120 -17
  8. package/docs/dispatcher.md +19 -8
  9. package/docs/integration-overview.md +1 -1
  10. package/docs/integration-tree.md +12 -9
  11. package/docs/merge-policy.md +7 -2
  12. package/docs/operating.md +13 -3
  13. package/docs/operator-api.md +46 -23
  14. package/docs/operator-surfaces.md +7 -6
  15. package/docs/optimization-nodes.md +7 -6
  16. package/docs/plugin-authoring.md +46 -18
  17. package/docs/remote-store-protocol.md +52 -13
  18. package/docs/remote-ticket-protocol.md +85 -38
  19. package/docs/restacking.md +48 -3
  20. package/docs/setup.md +2 -1
  21. package/docs/ticket-migration.md +2 -2
  22. package/docs/ticket-sources.md +23 -8
  23. package/docs/tickets.md +4 -4
  24. package/docs/troubleshooting.md +32 -2
  25. package/docs/verification.md +3 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/build-control.ts +72 -6
  28. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  29. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  30. package/packages/core/src/cli/dashboard/model.ts +14 -8
  31. package/packages/core/src/cli/dashboard/poll.ts +218 -10
  32. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  33. package/packages/core/src/cli/dashboard/row-text.ts +2 -1
  34. package/packages/core/src/cli/dashboard/vocabulary.ts +5 -1
  35. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  36. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  37. package/packages/core/src/cli/dispatch.ts +547 -145
  38. package/packages/core/src/cli/help.ts +38 -24
  39. package/packages/core/src/cli/main.ts +7 -5
  40. package/packages/core/src/cli/publication-settlement.ts +4 -0
  41. package/packages/core/src/cli/remote-poll.ts +22 -5
  42. package/packages/core/src/cli/repository-status.ts +19 -9
  43. package/packages/core/src/cli/status.ts +23 -11
  44. package/packages/core/src/cli/store-opening.ts +12 -0
  45. package/packages/core/src/cli/ticket-start.ts +3 -3
  46. package/packages/core/src/cli/ticket.ts +12 -11
  47. package/packages/core/src/cli/wait.ts +8 -28
  48. package/packages/core/src/cli/watch.ts +113 -50
  49. package/packages/core/src/config/reference-metadata.ts +7 -1
  50. package/packages/core/src/config/reference.ts +5 -2
  51. package/packages/core/src/config/schema.ts +51 -16
  52. package/packages/core/src/events/payloads.ts +74 -14
  53. package/packages/core/src/events/policy.ts +1 -0
  54. package/packages/core/src/events/repository.ts +33 -3
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  63. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  64. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  65. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  67. package/packages/core/src/kernel/done-escalations.ts +273 -0
  68. package/packages/core/src/kernel/engine.ts +28 -9
  69. package/packages/core/src/kernel/integration-landing.ts +24 -4
  70. package/packages/core/src/kernel/integration-stack.ts +39 -0
  71. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  72. package/packages/core/src/kernel/log-index-value.ts +3 -0
  73. package/packages/core/src/kernel/log-index.ts +41 -2
  74. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  75. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  76. package/packages/core/src/kernel/reducer-revisions.ts +19 -0
  77. package/packages/core/src/kernel/reducer.ts +42 -8
  78. package/packages/core/src/kernel/repository-attention.ts +14 -5
  79. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  80. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  81. package/packages/core/src/kernel/verify-stages.ts +46 -7
  82. package/packages/core/src/operator/attention.ts +28 -3
  83. package/packages/core/src/operator/done-escalations.ts +38 -0
  84. package/packages/core/src/operator/presentation.ts +1 -1
  85. package/packages/core/src/operator/protocol.ts +8 -5
  86. package/packages/core/src/operator/query.ts +33 -19
  87. package/packages/core/src/operator/registry.ts +17 -13
  88. package/packages/core/src/operator/ticket-start.ts +8 -7
  89. package/packages/core/src/operator/tickets.ts +28 -9
  90. package/packages/core/src/plugin-sdk/index.ts +10 -0
  91. package/packages/core/src/plugins/manifest.ts +14 -1
  92. package/packages/core/src/ports/forge/create.ts +8 -0
  93. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  94. package/packages/core/src/ports/forge/github.ts +3 -0
  95. package/packages/core/src/ports/tickets/contract.ts +147 -76
  96. package/packages/core/src/ports/tickets/create.ts +47 -7
  97. package/packages/core/src/ports/tickets/fake.ts +8 -4
  98. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  99. package/packages/core/src/ports/tickets/file.ts +7 -3
  100. package/packages/core/src/ports/tickets/github.ts +1 -0
  101. package/packages/core/src/ports/tickets/grants.ts +11 -3
  102. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  103. package/packages/core/src/ports/tickets/linear.ts +28 -9
  104. package/packages/core/src/ports/tickets/migration.ts +4 -4
  105. package/packages/core/src/ports/tickets/operations.ts +4 -2
  106. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  107. package/packages/core/src/ports/tickets/priority.ts +127 -21
  108. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  109. package/packages/core/src/ports/tickets/remote.ts +104 -11
  110. package/packages/core/src/ports/tickets/revision.ts +5 -3
  111. package/packages/core/src/ports/tickets/search.ts +9 -0
  112. package/packages/core/src/ports/tickets/tree.ts +8 -6
  113. package/packages/core/src/ports/types.ts +30 -15
  114. package/packages/core/src/ports/workspace/build-execution.ts +13 -1
  115. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  116. package/packages/core/src/ports/workspace/create.ts +16 -3
  117. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  118. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  119. package/packages/core/src/ports/workspace/vercel-sandbox.ts +596 -144
  120. package/packages/core/src/processes/build-execution-state.ts +4 -0
  121. package/packages/core/src/processes/build-runner.ts +14 -1
  122. package/packages/core/src/processes/dispatcher.ts +841 -230
  123. package/packages/core/src/processes/execution-settlement.ts +25 -3
  124. package/packages/core/src/processes/harvest-runner.ts +12 -7
  125. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  126. package/packages/core/src/processes/invocation-budget.ts +176 -0
  127. package/packages/core/src/processes/publication-loss.ts +38 -3
  128. package/packages/core/src/processes/tick-publication.ts +1 -0
  129. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  130. package/packages/core/src/store/contract.ts +88 -3
  131. package/packages/core/src/store/event-reads.ts +30 -1
  132. package/packages/core/src/store/reduced-reads.ts +23 -0
  133. package/packages/core/src/store/reducer-value-shapes.json +6759 -6490
  134. package/packages/core/src/store/reducer-value-validation.ts +188 -33
  135. package/packages/core/src/store/remote/client.ts +169 -29
  136. package/packages/core/src/store/remote/compatibility.ts +113 -56
  137. package/packages/core/src/store/remote/credentials.ts +4 -1
  138. package/packages/core/src/store/remote/protocol.ts +3 -0
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  143. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  144. package/packages/core/src/store/remote/retry.ts +406 -0
  145. package/packages/core/src/store/repo-state-events.ts +1 -0
  146. package/packages/core/src/testing/dispatch-read-budget.ts +155 -11
  147. package/packages/core/src/testing/index.ts +2 -0
  148. package/packages/core/src/testing/invocation-budget.ts +42 -0
  149. package/packages/core/src/testing/reduced-read-budget.ts +589 -19
  150. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  151. package/packages/core/src/web/overview-source.ts +19 -6
  152. package/skills/guide/SKILL.md +147 -67
  153. package/skills/guide/references/integration-tree.md +12 -9
  154. package/skills/guide/references/merge-policy.md +7 -2
  155. package/skills/guide/references/operator-api.md +46 -23
  156. package/skills/guide/references/optimization-nodes.md +7 -6
  157. package/skills/guide/references/plugin-authoring.md +46 -18
  158. package/skills/guide/references/remote-store-protocol.md +52 -13
  159. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  160. package/skills/guide/references/restacking.md +48 -3
  161. package/skills/guide/references/setup.md +2 -1
  162. package/skills/guide/references/ticket-migration.md +2 -2
  163. package/skills/operate/SKILL.md +136 -55
  164. package/skills/plan/SKILL.md +4 -3
  165. package/skills/spec/SKILL.md +9 -5
  166. package/skills/tickets/SKILL.md +25 -17
  167. package/templates/hosted-service/package.json +2 -2
@@ -12,6 +12,15 @@ import { GITHUB_REQUIRE_CREDENTIAL_ENV } from '../forge/github-transport'
12
12
  import { delegateCredential } from '../../store/remote/credentials'
13
13
  import type { ExecutionLaunchAuth } from './build-execution'
14
14
  import { createHash } from 'node:crypto'
15
+ import { setTimeout as sleep } from 'node:timers/promises'
16
+ import { EXECUTION_EXIT_FILE_ENV, parseExecutionExit } from './execution-exit-marker'
17
+ import {
18
+ isRecoveryDeferred,
19
+ recoveryStepOf,
20
+ WorkspaceRecoveryDeferred,
21
+ WorkspaceRecoveryStepError,
22
+ type WorkspaceRecoveryStep,
23
+ } from './recovery-step'
15
24
  import { Sandbox, Snapshot, type NetworkPolicy, type SandboxRegion } from '@vercel/sandbox'
16
25
  import { displayName, tomlKey, type RuntimeReferenceGroup } from '../../config/roles'
17
26
  import {
@@ -96,8 +105,10 @@ export interface VercelCommand {
96
105
  * and declared system-provisioning failure diagnostics, including failures
97
106
  * during durable build provisioning. It is not a durable build-state channel;
98
107
  * scoped Store facts/events remain authoritative. */
99
- stdout?(): Promise<string>
100
- stderr?(): Promise<string>
108
+ /** Reading output opens its own log stream, bounded only by the signal
109
+ * passed here, never by the command's. */
110
+ stdout?(opts?: { signal?: AbortSignal }): Promise<string>
111
+ stderr?(opts?: { signal?: AbortSignal }): Promise<string>
101
112
  }
102
113
 
103
114
  /**
@@ -142,8 +153,10 @@ export interface VercelCommandLookup {
142
153
  wait(params?: { signal?: AbortSignal }): Promise<{ exitCode: number }>
143
154
  /** Completed-command output, when the concrete handle exposes it (the SDK's
144
155
  * `Command` does; narrow lookups may omit it). Read only after exit. */
145
- stdout?(): Promise<string>
146
- stderr?(): Promise<string>
156
+ /** Reading output opens its own log stream, bounded only by the signal
157
+ * passed here, never by the command's. */
158
+ stdout?(opts?: { signal?: AbortSignal }): Promise<string>
159
+ stderr?(opts?: { signal?: AbortSignal }): Promise<string>
147
160
  }
148
161
 
149
162
  export interface VercelSandboxHandle {
@@ -259,6 +272,30 @@ export const VERCEL_OBSERVE_WAIT_MS = 5_000
259
272
  * finishes. */
260
273
  export const VERCEL_PROVISION_ESTIMATE_MS = 150_000
261
274
 
275
+ /** Default ceiling for one stopped-sandbox recovery: an explicit cold resume
276
+ * plus the guest git work that follows it (`recoveryTimeoutMs`). A bounded
277
+ * invocation admits a recovery on `VERCEL_RECOVERY_ESTIMATE_MS`, not on this
278
+ * ceiling. */
279
+ export const VERCEL_RECOVERY_TIMEOUT_MS = 120_000
280
+
281
+ /** Expected wall time of one stopped-sandbox recovery: a cold resume plus
282
+ * guest git. A bounded invocation starts a recovery when this plus the
283
+ * cleanup reserve fits; `recoveryTimeoutMs` stays the ceiling. */
284
+ export const VERCEL_RECOVERY_ESTIMATE_MS = 45_000
285
+
286
+ /** Interval between session polls while a resume or stop settles. */
287
+ const SESSION_POLL_MS = 500
288
+
289
+ /** Timer slack when deciding whether an abort came from a deadline. */
290
+ const DEADLINE_SLACK_MS = 10
291
+
292
+ /** Where the guest runner of one execution instance records its exit, on the
293
+ * sandbox's persistent filesystem. Hashing keeps any instance id a safe
294
+ * file name. */
295
+ export function executionExitPath(instance: string): string {
296
+ return `/vercel/sandbox/.autobuild-executions/${createHash('sha256').update(instance).digest('hex')}.json`
297
+ }
298
+
262
299
  /** The snapshot rows that hold billed storage. `deleted`/`failed` rows hold
263
300
  * none and are never purge targets. */
264
301
  const LIVE_SNAPSHOT_STATUS = 'created'
@@ -285,6 +322,11 @@ export interface VercelSnapshotPurge {
285
322
 
286
323
  export interface VercelSandboxFacade {
287
324
  get(name: string, signal?: AbortSignal): Promise<VercelSandboxHandle | null>
325
+ /** Explicitly resume a stopped persistent environment and return a handle
326
+ * on its running session; null when the environment is absent. A stop in
327
+ * progress settles first, and a pending session is polled until running,
328
+ * all under `signal`. Required by recovery of a stopped sandbox. */
329
+ resume?(name: string, signal?: AbortSignal): Promise<VercelSandboxHandle | null>
288
330
  /** Creation never deletes an existing named environment. */
289
331
  create(input: VercelSandboxCreateInput): Promise<VercelSandboxHandle>
290
332
  /** Dispatcher-authorized destruction only, after fence and commit receipt. */
@@ -384,18 +426,35 @@ export function createVercelSdkFacade(
384
426
  fetch: typeof globalThis.fetch = globalThis.fetch,
385
427
  ): VercelSandboxFacade {
386
428
  const credentials = vercelSdkCredentials(env)
429
+ const lookup = async (name: string, signal: AbortSignal | undefined, resume: boolean) => {
430
+ try {
431
+ return withSessionMetadata(await Sandbox.get({ name, signal, resume, fetch, ...credentials }))
432
+ } catch (error) {
433
+ // Provision must retain the stale name so dispatcher cleanup can delete it.
434
+ if (isUnavailableVercelSnapshot(error)) throw error
435
+ if (isMissingVercelSandbox(error)) return null
436
+ throw error
437
+ }
438
+ }
439
+ const settling = (status: VercelSandboxHandle['sessionStatus']) =>
440
+ status === 'stopping' || status === 'snapshotting'
387
441
  return {
388
- async get(name, signal) {
389
- try {
390
- return withSessionMetadata(
391
- await Sandbox.get({ name, signal, resume: false, fetch, ...credentials }),
392
- )
393
- } catch (error) {
394
- // Provision must retain the stale name so dispatcher cleanup can delete it.
395
- if (isUnavailableVercelSnapshot(error)) throw error
396
- if (isMissingVercelSandbox(error)) return null
397
- throw error
442
+ get: (name, signal) => lookup(name, signal, false),
443
+ async resume(name, signal) {
444
+ // The provider refuses to resume a session that is still stopping or
445
+ // snapshotting, so wait for it to settle first.
446
+ let current = await lookup(name, signal, false)
447
+ while (current !== null && settling(current.sessionStatus)) {
448
+ await sleep(SESSION_POLL_MS, undefined, { signal })
449
+ current = await lookup(name, signal, false)
450
+ }
451
+ if (current === null || current.sessionStatus === 'running') return current
452
+ current = await lookup(name, signal, true)
453
+ while (current !== null && current.sessionStatus === 'pending') {
454
+ await sleep(SESSION_POLL_MS, undefined, { signal })
455
+ current = await lookup(name, signal, false)
398
456
  }
457
+ return current
399
458
  },
400
459
  async create(input) {
401
460
  return withSessionMetadata(
@@ -916,8 +975,9 @@ async function readableCommand(
916
975
  },
917
976
  ): Promise<string> {
918
977
  const result = (await sandbox.runCommand(params)) as VercelCommand
919
- const stderr = result.stderr === undefined ? '' : await result.stderr()
920
- const stdout = result.stdout === undefined ? '' : await result.stdout()
978
+ const output = params.signal === undefined ? undefined : { signal: params.signal }
979
+ const stderr = result.stderr === undefined ? '' : await result.stderr(output)
980
+ const stdout = result.stdout === undefined ? '' : await result.stdout(output)
921
981
  if (result.exitCode === null || result.exitCode === undefined) {
922
982
  throw new Error(`sandbox command ${params.cmd} did not return an exit status`)
923
983
  }
@@ -1491,6 +1551,9 @@ export interface VercelSandboxProviderOptions {
1491
1551
  * mode) it is never touched on the host. */
1492
1552
  repo: string
1493
1553
  facade?: VercelSandboxFacade
1554
+ /** SDK transport for the default facade; absent ⇒ global `fetch`. A
1555
+ * bounded dispatcher invocation passes one that cancels at its deadline. */
1556
+ fetch?: typeof globalThis.fetch
1494
1557
  exec?: Exec
1495
1558
  packageArchive?: () => Promise<Uint8Array>
1496
1559
  accounts?: () => import('../../config/accounts').Accounts
@@ -1521,6 +1584,10 @@ export interface VercelSandboxProviderOptions {
1521
1584
  /** Test seam: the expected wall time of one `provision`. Defaults to
1522
1585
  * `VERCEL_PROVISION_ESTIMATE_MS`. */
1523
1586
  provisionEstimateMs?: number
1587
+ /** Test seam: the expected wall time of one stopped-sandbox recovery, used
1588
+ * to admit it in a bounded invocation. Defaults to
1589
+ * `VERCEL_RECOVERY_ESTIMATE_MS`; `recoveryTimeoutMs` stays the ceiling. */
1590
+ recoveryEstimateMs?: number
1524
1591
  /** The repository's raw `[commands].setup` shell string, run once at the end
1525
1592
  * of a fresh operator-sandbox provision (never on resume). Set once at
1526
1593
  * construction; never per call. */
@@ -1544,6 +1611,11 @@ export interface VercelSandboxProviderOptions {
1544
1611
  * provisioning never uses it. Mutually exclusive with a configured
1545
1612
  * `gitPasswordEnv`. */
1546
1613
  egressReadCredential?: { username: string; password: string }
1614
+ /** The hosted invocation's deadline (epoch ms). Every recovery-path
1615
+ * provider call is bounded by it; guest recovery work stops early enough to
1616
+ * leave a cleanup reserve of twice `operationTimeoutMs`. Absent (local
1617
+ * dispatch) means each call keeps only its own cap. */
1618
+ invocationDeadlineAt?: number
1547
1619
  }
1548
1620
 
1549
1621
  /** Vercel-backed working copy and executor. Completed SDK command output is
@@ -1590,6 +1662,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1590
1662
  private readonly sessions = new Map<string, VercelSandboxHandle>()
1591
1663
  private readonly observeWaitMs: number
1592
1664
  readonly provisionEstimateMs: number
1665
+ private readonly recoveryEstimateMs: number
1593
1666
 
1594
1667
  /** The archive bytes this provider installs: the injected `packageArchive`
1595
1668
  * seam when set, else the per-process memoized running distribution
@@ -1621,12 +1694,13 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1621
1694
  'vercel-sandbox accepts either a deployment egress read credential or a configured gitPasswordEnv, not both',
1622
1695
  )
1623
1696
  }
1624
- this.facade = options.facade ?? createVercelSdkFacade(options.env)
1697
+ this.facade = options.facade ?? createVercelSdkFacade(options.env, options.fetch)
1625
1698
  this.exec = options.exec ?? spawnExec
1626
1699
  this.observeWaitMs = options.observeWaitMs ?? VERCEL_OBSERVE_WAIT_MS
1627
1700
  // Constructor-body assignment, never a field initializer (see the
1628
1701
  // `useDefineForClassFields` note on `sandboxPublication`).
1629
1702
  this.provisionEstimateMs = options.provisionEstimateMs ?? VERCEL_PROVISION_ESTIMATE_MS
1703
+ this.recoveryEstimateMs = options.recoveryEstimateMs ?? VERCEL_RECOVERY_ESTIMATE_MS
1630
1704
  this.buildExecution = {
1631
1705
  start: (input, auth) => this.start(input, auth),
1632
1706
  observe: (identity) =>
@@ -1658,25 +1732,32 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1658
1732
  fence: async (handle) => {
1659
1733
  if (handle.provider !== this.name) throw new Error('workspace fence provider mismatch')
1660
1734
  try {
1661
- // Never trust the in-process handle after restart or another resume.
1662
- const sandbox = await this.facade.get(handle.ref, this.operationSignal())
1663
- if (sandbox === null) {
1664
- this.forget(handle.ref)
1665
- return { outcome: 'absent' }
1666
- }
1667
- await sandbox.stop({ signal: this.operationSignal() })
1668
- this.active.delete(handle.ref)
1669
- this.uncertain.delete(handle.ref)
1670
- this.sessions.set(handle.ref, sandbox)
1671
- return { outcome: 'confirmed' }
1735
+ return await this.deadlineAware('fence', async () => {
1736
+ // Never trust the in-process handle after restart or another resume.
1737
+ const sandbox = await this.facade.get(handle.ref, this.recoveryMetadataSignal())
1738
+ if (sandbox === null) {
1739
+ this.forget(handle.ref)
1740
+ return { outcome: 'absent' as const }
1741
+ }
1742
+ // A session the provider already reports stopped needs no second
1743
+ // stop; asking would only spend the acknowledgement budget.
1744
+ if (sandbox.sessionStatus !== 'stopped')
1745
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
1746
+ this.active.delete(handle.ref)
1747
+ this.uncertain.delete(handle.ref)
1748
+ this.sessions.set(handle.ref, sandbox)
1749
+ return { outcome: 'confirmed' as const }
1750
+ })
1672
1751
  } catch (error) {
1752
+ // The invocation deadline is not a fence failure: retry next time.
1753
+ if (isRecoveryDeferred(error)) throw error
1673
1754
  if (isMissingVercelSandbox(error)) {
1674
1755
  this.forget(handle.ref)
1675
1756
  return { outcome: 'absent' }
1676
1757
  }
1677
1758
  return {
1678
1759
  outcome: 'unknown',
1679
- error: error instanceof Error ? error.message : String(error),
1760
+ error: `fence: ${error instanceof Error ? error.message : String(error)}`,
1680
1761
  }
1681
1762
  }
1682
1763
  },
@@ -1691,77 +1772,88 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1691
1772
  }
1692
1773
  this.publication = {
1693
1774
  recoverCandidate: (input) =>
1694
- this.withPolicyLock(input.ref, async () => {
1695
- if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1696
- throw new Error('candidate recovery requires confirmed teardown')
1697
- const sandbox = await this.facade.get(input.ref, this.operationSignal())
1698
- if (!sandbox) throw new Error('candidate recovery awaits replacement workspace')
1699
- return this.withTrustedGit(sandbox, input.ref, async (exec) => {
1700
- const archiveRef = `refs/autobuild/archive/${input.slug}/${input.sha}`
1701
- const available = await inspectGitCandidate({
1702
- ...input,
1703
- exec,
1704
- workspacePath: VERCEL_WORKSPACE_PATH,
1705
- archiveRef,
1706
- })
1707
- if (available)
1708
- try {
1709
- await this.archiveTransport(exec).archive({
1710
- workspacePath: VERCEL_WORKSPACE_PATH,
1711
- ref: archiveRef,
1712
- sha: input.sha,
1713
- })
1714
- } catch (error) {
1715
- // Archive refs are best effort: the settlement rewrite retains
1716
- // the candidate through its `retain` fallback.
1717
- if (!isArchiveRefusal(error)) throw error
1718
- }
1719
- return available
1720
- })
1721
- }),
1722
- preserve: (input) =>
1723
- this.withPolicyLock(input.ref, async () => {
1724
- if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1725
- throw new Error('preservation requires confirmed execution teardown')
1726
- const sandbox = await this.facade.get(input.ref, this.operationSignal())
1727
- if (sandbox === null) return { outcome: 'absent' }
1728
- const heads = await this.withTrustedGit(sandbox, input.ref, async (exec) => {
1729
- // A VM whose provisioning stopped before the checkout was moved
1730
- // into place has nothing to preserve. The probe runs without the
1731
- // checkout as cwd, and only a definite "missing" proves absence.
1732
- const checkout = await sandbox.runCommand({
1733
- cmd: 'test',
1734
- args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
1735
- signal: this.operationSignal(),
1736
- })
1737
- if (checkout.exitCode === 1) return null
1738
- if (checkout.exitCode !== 0)
1739
- throw new Error(
1740
- `preservation could not confirm the checkout at ${VERCEL_WORKSPACE_PATH} (exit ${checkout.exitCode})`,
1741
- )
1742
- const capability = this.archiveTransport(exec)
1743
- const remote = await this.remoteBranchHead(input.branch, 'preservation branch')
1744
- const base =
1745
- remote === null
1746
- ? input.base
1747
- : await capability.snapshot({
1775
+ this.withPolicyLock(input.ref, () =>
1776
+ this.deadlineAware('preserve', async () => {
1777
+ if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1778
+ throw new Error('candidate recovery requires confirmed teardown')
1779
+ const found = await this.facade.get(input.ref, this.recoveryMetadataSignal())
1780
+ const signal = this.recoveryWorkSignal()
1781
+ const sandbox = found && (await this.resumeForRecovery(input.ref, found, signal))
1782
+ if (!sandbox) throw new Error('candidate recovery awaits replacement workspace')
1783
+ return this.withTrustedGit(sandbox, input.ref, signal, async (exec) => {
1784
+ const archiveRef = `refs/autobuild/archive/${input.slug}/${input.sha}`
1785
+ const available = await inspectGitCandidate({
1786
+ ...input,
1787
+ exec,
1788
+ workspacePath: VERCEL_WORKSPACE_PATH,
1789
+ archiveRef,
1790
+ })
1791
+ if (available)
1792
+ try {
1793
+ await this.archiveTransport(exec).archive({
1748
1794
  workspacePath: VERCEL_WORKSPACE_PATH,
1749
- branch: input.branch,
1750
- destinationRef: `refs/autobuild/reconcile/${input.slug}/preservation`,
1795
+ ref: archiveRef,
1796
+ sha: input.sha,
1751
1797
  })
1752
- // After the guest push and the host REST fallback both refuse,
1753
- // `input.retain` keeps the head as a store copy host-side.
1754
- return preserveGitCommits({
1755
- ...input,
1756
- base,
1757
- exec,
1758
- workspacePath: VERCEL_WORKSPACE_PATH,
1759
- archive: capability.archive,
1798
+ } catch (error) {
1799
+ // Archive refs are best effort: the settlement rewrite retains
1800
+ // the candidate through its `retain` fallback.
1801
+ if (!isArchiveRefusal(error)) throw error
1802
+ }
1803
+ return available
1760
1804
  })
1761
- })
1762
- if (heads === null) return { outcome: 'absent' }
1763
- return { outcome: 'preserved', heads }
1764
- }),
1805
+ }),
1806
+ ),
1807
+ preserve: (input) =>
1808
+ this.withPolicyLock(input.ref, () =>
1809
+ this.deadlineAware('preserve', async () => {
1810
+ if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1811
+ throw new Error('preservation requires confirmed execution teardown')
1812
+ const found = await this.facade.get(input.ref, this.recoveryMetadataSignal())
1813
+ // A stopped persistent sandbox is resumed explicitly under the
1814
+ // recovery budget, never implicitly by the first guest command
1815
+ // under the short acknowledgement cap.
1816
+ const signal = this.recoveryWorkSignal()
1817
+ const sandbox = found && (await this.resumeForRecovery(input.ref, found, signal))
1818
+ if (sandbox === null) return { outcome: 'absent' as const }
1819
+ const heads = await this.withTrustedGit(sandbox, input.ref, signal, async (exec) => {
1820
+ // A VM whose provisioning stopped before the checkout was moved
1821
+ // into place has nothing to preserve. The probe runs without the
1822
+ // checkout as cwd, and only a definite "missing" proves absence.
1823
+ const checkout = await sandbox.runCommand({
1824
+ cmd: 'test',
1825
+ args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
1826
+ signal,
1827
+ })
1828
+ if (checkout.exitCode === 1) return null
1829
+ if (checkout.exitCode !== 0)
1830
+ throw new Error(
1831
+ `preservation could not confirm the checkout at ${VERCEL_WORKSPACE_PATH} (exit ${checkout.exitCode})`,
1832
+ )
1833
+ const capability = this.archiveTransport(exec)
1834
+ const remote = await this.remoteBranchHead(input.branch, 'preservation branch')
1835
+ const base =
1836
+ remote === null
1837
+ ? input.base
1838
+ : await capability.snapshot({
1839
+ workspacePath: VERCEL_WORKSPACE_PATH,
1840
+ branch: input.branch,
1841
+ destinationRef: `refs/autobuild/reconcile/${input.slug}/preservation`,
1842
+ })
1843
+ // After the guest push and the host REST fallback both refuse,
1844
+ // `input.retain` keeps the head as a store copy host-side.
1845
+ return preserveGitCommits({
1846
+ ...input,
1847
+ base,
1848
+ exec,
1849
+ workspacePath: VERCEL_WORKSPACE_PATH,
1850
+ archive: capability.archive,
1851
+ })
1852
+ })
1853
+ if (heads === null) return { outcome: 'absent' as const }
1854
+ return { outcome: 'preserved' as const, heads }
1855
+ }),
1856
+ ),
1765
1857
  rewrite: (input: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]) =>
1766
1858
  this.withPolicyLock(input.ref, () => this.publish(input)),
1767
1859
  isPublished: (input: { sha: string; branch: string }) => this.isPublished(input),
@@ -1796,6 +1888,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1796
1888
  this.options.storeRef,
1797
1889
  this.options.storeToken,
1798
1890
  { kind: 'build-runner', id: buildSlugFromBranch(opts.branch) },
1891
+ this.options.fetch,
1799
1892
  )
1800
1893
  const rawOrigin = await this.origin()
1801
1894
  const origin = cleanGithubOrigin(rawOrigin)
@@ -1998,7 +2091,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1998
2091
  let provisionHead = checkedOut
1999
2092
  let restorationSkipped: import('../types').RestorationSkip[] = []
2000
2093
  if (opts.restoration?.length) {
2001
- provisionHead = await this.withTrustedGit(sandbox, name, async (exec) => {
2094
+ provisionHead = await this.withTrustedGit(sandbox, name, undefined, async (exec) => {
2002
2095
  restorationSkipped = (
2003
2096
  await restoreGitCommits({
2004
2097
  exec,
@@ -2127,16 +2220,213 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2127
2220
  }
2128
2221
 
2129
2222
  private operationSignal(): AbortSignal {
2130
- return AbortSignal.timeout(this.options.config.operationTimeoutMs ?? 30_000)
2223
+ return AbortSignal.timeout(this.operationTimeoutMs())
2224
+ }
2225
+
2226
+ private operationTimeoutMs(): number {
2227
+ return this.options.config.operationTimeoutMs ?? 30_000
2228
+ }
2229
+
2230
+ private recoveryTimeoutMs(): number {
2231
+ return this.options.config.recoveryTimeoutMs ?? VERCEL_RECOVERY_TIMEOUT_MS
2232
+ }
2233
+
2234
+ /** Time held back from guest recovery work for the finally-block policy
2235
+ * restore and stop that follow it. */
2236
+ private cleanupReserveMs(): number {
2237
+ return 2 * this.operationTimeoutMs()
2238
+ }
2239
+
2240
+ /** The last moment guest recovery work may run: the invocation deadline
2241
+ * less the cleanup reserve. Undefined without an invocation deadline. */
2242
+ private recoveryWorkBound(): number | undefined {
2243
+ const deadline = this.options.invocationDeadlineAt
2244
+ return deadline === undefined ? undefined : deadline - this.cleanupReserveMs()
2245
+ }
2246
+
2247
+ private static bounded(cap: number, until: number | undefined): AbortSignal {
2248
+ const own = AbortSignal.timeout(cap)
2249
+ if (until === undefined) return own
2250
+ return AbortSignal.any([own, AbortSignal.timeout(Math.max(0, until - Date.now()))])
2251
+ }
2252
+
2253
+ /** A metadata call on a recovery path: `operationTimeoutMs`, and never
2254
+ * past the invocation deadline. Taken fresh at the moment the call starts,
2255
+ * so a finally-block call still gets the reserved cleanup window. */
2256
+ private recoveryMetadataSignal(): AbortSignal {
2257
+ return VercelSandboxProvider.bounded(
2258
+ this.operationTimeoutMs(),
2259
+ this.options.invocationDeadlineAt,
2260
+ )
2261
+ }
2262
+
2263
+ /** A resume or guest command on a recovery path: `recoveryTimeoutMs`, and
2264
+ * never past the reserved work bound. */
2265
+ private recoveryWorkSignal(): AbortSignal {
2266
+ return VercelSandboxProvider.bounded(this.recoveryTimeoutMs(), this.recoveryWorkBound())
2267
+ }
2268
+
2269
+ /** The time a recovery needs left before the invocation deadline to start:
2270
+ * a realistic resume (never more than the `recoveryTimeoutMs` ceiling)
2271
+ * plus the cleanup reserve. */
2272
+ private recoveryAdmissionMs(): number {
2273
+ return Math.min(this.recoveryEstimateMs, this.recoveryTimeoutMs()) + this.cleanupReserveMs()
2274
+ }
2275
+
2276
+ /** Whether a realistic cold resume plus its cleanup still fits before the
2277
+ * invocation deadline. Always true without one. Admission uses the
2278
+ * estimate; `recoveryTimeoutMs` stays the ceiling on the recovery itself,
2279
+ * and the deadline bounds it further. */
2280
+ private recoveryBudgetAvailable(): boolean {
2281
+ const deadline = this.options.invocationDeadlineAt
2282
+ if (deadline === undefined) return true
2283
+ return deadline - Date.now() >= this.recoveryAdmissionMs()
2284
+ }
2285
+
2286
+ /** Leave a session a cut-short recovery resumed (or may have resumed)
2287
+ * stopped, or marked uncertain for a later fence: never running
2288
+ * unsupervised. Runs in the reserved cleanup window and never throws. */
2289
+ private async stopAfterCutRecovery(ref: string, handle?: VercelSandboxHandle): Promise<void> {
2290
+ try {
2291
+ const sandbox = handle ?? (await this.facade.get(ref, this.recoveryMetadataSignal()))
2292
+ if (sandbox === null) {
2293
+ this.forget(ref)
2294
+ return
2295
+ }
2296
+ const status = sandbox.sessionStatus
2297
+ if (status === 'stopped' || status === 'stopping' || status === 'snapshotting') {
2298
+ this.sessions.delete(ref)
2299
+ return
2300
+ }
2301
+ await this.recoveryStop(ref, sandbox)
2302
+ this.sessions.delete(ref)
2303
+ } catch {
2304
+ this.uncertain.add(ref)
2305
+ this.sessions.delete(ref)
2306
+ }
2307
+ }
2308
+
2309
+ private remainingMs(): number {
2310
+ const deadline = this.options.invocationDeadlineAt
2311
+ return deadline === undefined ? Number.POSITIVE_INFINITY : deadline - Date.now()
2312
+ }
2313
+
2314
+ /** Whether an error is the invocation deadline aborting a call rather than
2315
+ * a provider failure: the reserved work bound has passed and the error
2316
+ * reads as an abort or timeout. */
2317
+ private deadlineAbort(error: unknown): boolean {
2318
+ const bound = this.recoveryWorkBound()
2319
+ if (bound === undefined || Date.now() + DEADLINE_SLACK_MS < bound) return false
2320
+ const seen = new Set<unknown>()
2321
+ for (let current = error; current instanceof Error && !seen.has(current); ) {
2322
+ seen.add(current)
2323
+ if (current.name === 'AbortError' || current.name === 'TimeoutError') return true
2324
+ if (/abort|timed out|timeout/i.test(current.message)) return true
2325
+ current = current.cause
2326
+ }
2327
+ return false
2328
+ }
2329
+
2330
+ /** Run one recovery operation, reporting a deadline abort as a typed
2331
+ * deferral naming `step` instead of as a provider failure. */
2332
+ private async deadlineAware<T>(step: WorkspaceRecoveryStep, fn: () => Promise<T>): Promise<T> {
2333
+ try {
2334
+ return await fn()
2335
+ } catch (error) {
2336
+ if (isRecoveryDeferred(error) || !this.deadlineAbort(error)) throw error
2337
+ throw new WorkspaceRecoveryDeferred(
2338
+ step,
2339
+ { remainingMs: this.remainingMs() },
2340
+ { cause: error },
2341
+ )
2342
+ }
2343
+ }
2344
+
2345
+ /** Stop at the end of a recovery operation. A stop the deadline aborted
2346
+ * may leave the VM running, so the ref stays uncertain until a later fence
2347
+ * or reap confirms teardown. */
2348
+ private async recoveryStop(ref: string, sandbox: VercelSandboxHandle): Promise<void> {
2349
+ try {
2350
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2351
+ } catch (error) {
2352
+ if (this.deadlineAbort(error)) {
2353
+ this.uncertain.add(ref)
2354
+ this.sessions.delete(ref)
2355
+ }
2356
+ throw error
2357
+ }
2358
+ }
2359
+
2360
+ /** Bring a stopped persistent sandbox back explicitly, under the recovery
2361
+ * budget rather than the short metadata cap. A running handle (or one from
2362
+ * a facade without session metadata) is returned unchanged; null means the
2363
+ * environment is gone. */
2364
+ private async resumeForRecovery(
2365
+ ref: string,
2366
+ sandbox: VercelSandboxHandle,
2367
+ signal: AbortSignal = this.recoveryWorkSignal(),
2368
+ ): Promise<VercelSandboxHandle | null> {
2369
+ if (sandbox.sessionStatus === undefined || sandbox.sessionStatus === 'running') return sandbox
2370
+ if (!this.recoveryBudgetAvailable())
2371
+ throw new WorkspaceRecoveryDeferred('resume', {
2372
+ remainingMs: this.remainingMs(),
2373
+ requiredMs: this.recoveryAdmissionMs(),
2374
+ })
2375
+ if (this.facade.resume === undefined)
2376
+ throw new WorkspaceRecoveryStepError(
2377
+ 'resume',
2378
+ new Error('sandbox facade lacks explicit resume; upgrade the facade'),
2379
+ )
2380
+ let resumed: VercelSandboxHandle | null
2381
+ try {
2382
+ resumed = await this.facade.resume(ref, signal)
2383
+ } catch (error) {
2384
+ if (isMissingVercelSandbox(error)) throw error
2385
+ if (this.deadlineAbort(error)) {
2386
+ // The resume may still be completing provider-side: stop it inside
2387
+ // the reserved cleanup window, or leave the ref uncertain.
2388
+ await this.stopAfterCutRecovery(ref)
2389
+ throw new WorkspaceRecoveryDeferred(
2390
+ 'resume',
2391
+ { remainingMs: this.remainingMs() },
2392
+ {
2393
+ cause: error,
2394
+ },
2395
+ )
2396
+ }
2397
+ throw new WorkspaceRecoveryStepError(
2398
+ 'resume',
2399
+ signal.aborted
2400
+ ? new Error(
2401
+ `resume of sandbox ${ref} exceeded its ${this.recoveryTimeoutMs()} ms recovery timeout`,
2402
+ { cause: error },
2403
+ )
2404
+ : error,
2405
+ )
2406
+ }
2407
+ if (resumed === null) {
2408
+ this.forget(ref)
2409
+ return null
2410
+ }
2411
+ this.sessions.set(ref, resumed)
2412
+ return resumed
2131
2413
  }
2132
2414
 
2133
2415
  /** Stop/delete and then prove absence by exact deterministic name — for the
2134
2416
  * sandbox and, because deleting a sandbox never removes the automatic
2135
2417
  * snapshots its sessions created, for its snapshot storage too. */
2136
- private async reap(ref: string, dispatcherAuthorized = false): Promise<WorkspaceReapOutcome> {
2418
+ private reap(ref: string, dispatcherAuthorized = false): Promise<WorkspaceReapOutcome> {
2419
+ return this.deadlineAware('cleanup', () => this.reapOnce(ref, dispatcherAuthorized))
2420
+ }
2421
+
2422
+ private async reapOnce(
2423
+ ref: string,
2424
+ dispatcherAuthorized: boolean,
2425
+ ): Promise<WorkspaceReapOutcome> {
2137
2426
  let sandbox: VercelSandboxHandle | null
2138
2427
  try {
2139
- sandbox = this.sessions.get(ref) ?? (await this.facade.get(ref, this.operationSignal()))
2428
+ sandbox =
2429
+ this.sessions.get(ref) ?? (await this.facade.get(ref, this.recoveryMetadataSignal()))
2140
2430
  } catch (error) {
2141
2431
  if (!isMissingVercelSandbox(error)) throw error
2142
2432
  sandbox = null
@@ -2146,7 +2436,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2146
2436
  if (dispatcherAuthorized) {
2147
2437
  if (!this.facade.deleteByName)
2148
2438
  throw new Error('sandbox facade lacks dispatcher-authorized deleteByName')
2149
- await this.facade.deleteByName(ref, this.operationSignal())
2439
+ await this.facade.deleteByName(ref, this.recoveryMetadataSignal())
2150
2440
  }
2151
2441
  // An environment can vanish without its snapshots; the purge still
2152
2442
  // applies and only a confirmed empty list may forget the reference.
@@ -2160,7 +2450,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2160
2450
  }
2161
2451
  try {
2162
2452
  try {
2163
- await sandbox.stop({ signal: this.operationSignal() })
2453
+ // An already-stopped session needs no second stop.
2454
+ if (sandbox.sessionStatus !== 'stopped')
2455
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2164
2456
  } catch (error) {
2165
2457
  // A persistent sandbox that was resumed once can wedge so that stop
2166
2458
  // never returns while delete still succeeds within seconds. Absence
@@ -2174,9 +2466,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2174
2466
  if (dispatcherAuthorized) {
2175
2467
  if (!this.facade.deleteByName)
2176
2468
  throw new Error('sandbox facade lacks dispatcher-authorized deleteByName')
2177
- await this.facade.deleteByName(ref, this.operationSignal())
2178
- } else await sandbox.delete({ signal: this.operationSignal() })
2179
- sandbox = await this.facade.get(ref, this.operationSignal())
2469
+ await this.facade.deleteByName(ref, this.recoveryMetadataSignal())
2470
+ } else await sandbox.delete({ signal: this.recoveryMetadataSignal() })
2471
+ sandbox = await this.facade.get(ref, this.recoveryMetadataSignal())
2180
2472
  if (sandbox !== null)
2181
2473
  throw new Error(`sandbox ${ref} still exists after delete acknowledgement`)
2182
2474
  // The post-delete pass catches anything the delete itself created;
@@ -2200,7 +2492,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2200
2492
  /** Purge one environment's snapshots, converting an unknown outcome into
2201
2493
  * the retryable cleanup failure the dispatcher already retries. */
2202
2494
  private async purgeOrRetryable(ref: string): Promise<VercelSnapshotPurge> {
2203
- const purged = await purgeEnvironmentSnapshots(this.facade, ref, this.operationSignal())
2495
+ const purged = await purgeEnvironmentSnapshots(this.facade, ref, this.recoveryMetadataSignal())
2204
2496
  if (purged.outcome === 'unknown') {
2205
2497
  throw new Error(
2206
2498
  `snapshot purge for ${JSON.stringify(ref)} is unconfirmed: ${purged.error ?? 'unknown outcome'}`,
@@ -2286,6 +2578,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2286
2578
  this.options.storeRef,
2287
2579
  this.options.storeToken,
2288
2580
  { kind: 'build-runner', id: input.slug },
2581
+ this.options.fetch,
2289
2582
  ))
2290
2583
  const ref = input.workspaceRef
2291
2584
  if (this.active.has(ref)) throw new Error(`sandbox ${ref} already has a live execution`)
@@ -2351,6 +2644,10 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2351
2644
  // instead of going out anonymously. Applied last so no forwarded value
2352
2645
  // can disable it.
2353
2646
  env[GITHUB_REQUIRE_CREDENTIAL_ENV] = '1'
2647
+ // The runner records its exit here, so a later observation of a stopped
2648
+ // sandbox can still settle the execution. Applied last, like the
2649
+ // credential guard, so no forwarded value can redirect it.
2650
+ env[EXECUTION_EXIT_FILE_ENV] = executionExitPath(input.instance)
2354
2651
  const command = (await sandbox.runCommand({
2355
2652
  cmd: 'sh',
2356
2653
  args: [
@@ -2696,37 +2993,79 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2696
2993
  /** Observe a recovered execution and confirm whole-environment teardown
2697
2994
  * before exposing a terminal observation. Command exit alone does not prove
2698
2995
  * descendants have stopped writing to the shared workspace. Stop failures
2699
- * propagate so settlement retains the execution and lease and retries. */
2996
+ * propagate so settlement retains the execution and lease and retries. A
2997
+ * call the invocation deadline cuts short, or one the budget cannot admit,
2998
+ * reads as `running` marked `deferred` with the step it waited on: nothing
2999
+ * is settled, nothing is charged, and the next invocation observes again. */
2700
3000
  private async observeExecution(identity: BuildExecutionIdentity): Promise<ExecutionObservation> {
2701
3001
  if (identity.commandId === undefined) {
2702
3002
  throw new Error(
2703
3003
  `execution on ${identity.workspaceRef} has no recorded command id and cannot be re-observed`,
2704
3004
  )
2705
3005
  }
2706
- const sandbox = await this.facade.get(identity.workspaceRef, this.operationSignal())
2707
- if (sandbox === null) return { state: 'lost' }
2708
- const settled = async (observation: ExecutionObservation): Promise<ExecutionObservation> => {
2709
- try {
2710
- await sandbox.stop({ signal: this.operationSignal() })
2711
- } catch (error) {
2712
- if (!isMissingVercelSandbox(error)) {
2713
- this.uncertain.add(identity.workspaceRef)
2714
- this.sessions.delete(identity.workspaceRef)
2715
- throw error
3006
+ try {
3007
+ return await this.observeOnce(identity, identity.commandId)
3008
+ } catch (error) {
3009
+ if (isRecoveryDeferred(error) || this.deadlineAbort(error))
3010
+ return {
3011
+ state: 'running',
3012
+ deferred: {
3013
+ step: recoveryStepOf(error) ?? 'fence',
3014
+ detail: error instanceof Error ? error.message : String(error),
3015
+ },
2716
3016
  }
3017
+ throw error
3018
+ }
3019
+ }
3020
+
3021
+ /** Stop the environment, then report a terminal observation. */
3022
+ private async settledObservation(
3023
+ ref: string,
3024
+ sandbox: VercelSandboxHandle,
3025
+ observation: ExecutionObservation,
3026
+ ): Promise<ExecutionObservation> {
3027
+ try {
3028
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
3029
+ } catch (error) {
3030
+ if (!isMissingVercelSandbox(error)) {
3031
+ this.uncertain.add(ref)
3032
+ this.sessions.delete(ref)
3033
+ throw error
2717
3034
  }
2718
- this.active.delete(identity.workspaceRef)
2719
- this.uncertain.delete(identity.workspaceRef)
2720
- this.sessions.delete(identity.workspaceRef)
2721
- return observation
2722
3035
  }
3036
+ this.active.delete(ref)
3037
+ this.uncertain.delete(ref)
3038
+ this.sessions.delete(ref)
3039
+ return observation
3040
+ }
3041
+
3042
+ private async observeOnce(
3043
+ identity: BuildExecutionIdentity,
3044
+ commandId: string,
3045
+ ): Promise<ExecutionObservation> {
3046
+ const ref = identity.workspaceRef
3047
+ const sandbox = await this.facade.get(ref, this.recoveryMetadataSignal())
3048
+ if (sandbox === null) return { state: 'lost' }
3049
+ const settled = (observation: ExecutionObservation) =>
3050
+ this.settledObservation(ref, sandbox, observation)
2723
3051
  const currentSession = sandbox.currentSession?.().sessionId
2724
- if (
3052
+ const newer =
2725
3053
  identity.sessionId !== undefined &&
2726
3054
  currentSession !== undefined &&
2727
3055
  currentSession !== identity.sessionId
3056
+ // A stopped session no longer reports its command's final state, and a
3057
+ // newer session (one a recovery resume created) never ran this runner.
3058
+ // The runner's own exit record on the persistent filesystem answers for
3059
+ // both, so a finished execution settles instead of reading as lost.
3060
+ if (
3061
+ identity.instance !== undefined &&
3062
+ (newer ||
3063
+ sandbox.sessionStatus === 'stopped' ||
3064
+ sandbox.sessionStatus === 'stopping' ||
3065
+ sandbox.sessionStatus === 'snapshotting')
2728
3066
  )
2729
- return { state: 'lost' }
3067
+ return this.observeExitRecord(identity.instance, ref, sandbox)
3068
+ if (newer) return { state: 'lost' }
2730
3069
  // Terminal provider status proves the recorded incarnation is stopped.
2731
3070
  // Never stop a newer resumed session or demand a second stop of one that
2732
3071
  // the provider already confirms stopped.
@@ -2766,10 +3105,18 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2766
3105
  try {
2767
3106
  await sandbox.update(
2768
3107
  { networkPolicy: refreshed.policy },
2769
- { signal: this.operationSignal() },
3108
+ { signal: this.recoveryMetadataSignal() },
2770
3109
  )
2771
- } catch {
2772
- await sandbox.stop({ signal: this.operationSignal() })
3110
+ } catch (error) {
3111
+ if (this.deadlineAbort(error))
3112
+ return {
3113
+ state: 'running',
3114
+ deferred: {
3115
+ step: 'fence',
3116
+ detail: `renewing the account policy of sandbox ${ref} stopped at the invocation deadline; retrying next invocation`,
3117
+ },
3118
+ }
3119
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2773
3120
  return { state: 'lost', attention: 'Account policy renewal failed; sandbox stopped' }
2774
3121
  }
2775
3122
  if (refreshed.missing.length) {
@@ -2784,8 +3131,8 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2784
3131
  attention === undefined ? observation : { ...observation, attention }
2785
3132
  let observation: ExecutionObservation
2786
3133
  try {
2787
- const command = await sandbox.getCommand(identity.commandId, {
2788
- signal: this.operationSignal(),
3134
+ const command = await sandbox.getCommand(commandId, {
3135
+ signal: this.recoveryMetadataSignal(),
2789
3136
  })
2790
3137
  if (command.exitCode !== null) {
2791
3138
  observation = { state: 'ended', exitCode: command.exitCode }
@@ -2794,7 +3141,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2794
3141
  const finished = await command.wait({
2795
3142
  signal: AbortSignal.any([
2796
3143
  AbortSignal.timeout(this.observeWaitMs),
2797
- this.operationSignal(),
3144
+ this.recoveryMetadataSignal(),
2798
3145
  ]),
2799
3146
  })
2800
3147
  observation = { state: 'ended', exitCode: finished.exitCode }
@@ -2814,6 +3161,83 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2814
3161
  return settled(diagnosed(observation))
2815
3162
  }
2816
3163
 
3164
+ /** Settle an execution from its runner's exit record. A session that is
3165
+ * not running is resumed explicitly under the recovery budget (or the
3166
+ * observation waits for a later invocation when the budget is short). The
3167
+ * environment is stopped again when the record proves the recorded runner
3168
+ * exited, or when this call resumed it; a newer session this call did not
3169
+ * resume is otherwise never stopped. Nothing here depends on process
3170
+ * memory, so any later observer settles the same execution. */
3171
+ private async observeExitRecord(
3172
+ instance: string,
3173
+ ref: string,
3174
+ sandbox: VercelSandboxHandle,
3175
+ ): Promise<ExecutionObservation> {
3176
+ let handle = sandbox
3177
+ let resumedHere = false
3178
+ if (sandbox.sessionStatus !== undefined && sandbox.sessionStatus !== 'running') {
3179
+ if (!this.recoveryBudgetAvailable())
3180
+ return {
3181
+ state: 'running',
3182
+ deferred: {
3183
+ step: 'resume',
3184
+ detail: new WorkspaceRecoveryDeferred('resume', {
3185
+ remainingMs: this.remainingMs(),
3186
+ requiredMs: this.recoveryAdmissionMs(),
3187
+ }).message,
3188
+ },
3189
+ }
3190
+ let resumed: VercelSandboxHandle | null
3191
+ try {
3192
+ resumed = await this.resumeForRecovery(ref, sandbox)
3193
+ } catch (error) {
3194
+ if (isMissingVercelSandbox(error)) return { state: 'lost' }
3195
+ throw error
3196
+ }
3197
+ if (resumed === null) return { state: 'lost' }
3198
+ handle = resumed
3199
+ resumedHere = true
3200
+ }
3201
+ let exitCode: number | null
3202
+ try {
3203
+ // One signal bounds the read and its output stream alike.
3204
+ const signal = this.recoveryWorkSignal()
3205
+ const result = (await handle.runCommand({
3206
+ cmd: 'cat',
3207
+ args: [executionExitPath(instance)],
3208
+ signal,
3209
+ })) as VercelCommand
3210
+ if (result.exitCode === 0) {
3211
+ exitCode = parseExecutionExit(
3212
+ result.stdout === undefined ? '' : await result.stdout({ signal }),
3213
+ instance,
3214
+ )
3215
+ } else if (result.exitCode === 1) exitCode = null
3216
+ else
3217
+ throw new Error(
3218
+ `reading the exit record of execution ${instance} on sandbox ${ref} exited ${String(result.exitCode)}`,
3219
+ )
3220
+ } catch (error) {
3221
+ if (isMissingVercelSandbox(error)) return { state: 'lost' }
3222
+ // A session this call resumed is never left running after a read that
3223
+ // failed or that the deadline cut short; a session it did not resume
3224
+ // belongs to someone else and is never stopped here.
3225
+ if (resumedHere) await this.stopAfterCutRecovery(ref, handle)
3226
+ if (this.deadlineAbort(error))
3227
+ return {
3228
+ state: 'running',
3229
+ deferred: {
3230
+ step: 'fence',
3231
+ detail: `reading the exit record of execution ${instance} stopped at the invocation deadline; retrying next invocation`,
3232
+ },
3233
+ }
3234
+ throw error
3235
+ }
3236
+ if (exitCode !== null) return this.settledObservation(ref, handle, { state: 'ended', exitCode })
3237
+ if (resumedHere) return this.settledObservation(ref, handle, { state: 'lost' })
3238
+ return { state: 'lost' }
3239
+ }
3240
+
2817
3241
  // ── Operator sandbox capability (AUT-340) ─────────────────────────
2818
3242
  //
2819
3243
  // One persistent, credential-free environment per operator × repository,
@@ -4251,9 +4675,15 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4251
4675
  return head === input.sha
4252
4676
  }
4253
4677
 
4678
+ /** Run guest git with a trusted forge credential in the network policy.
4679
+ * `signal` bounds the guest commands (one recovery operation's budget);
4680
+ * without it (provisioning restore) each command gets its own
4681
+ * acknowledgement cap. Every policy write and the final stop take a fresh
4682
+ * deadline-bounded metadata signal. */
4254
4683
  private async withTrustedGit<T>(
4255
4684
  sandbox: VercelSandboxHandle,
4256
4685
  ref: string,
4686
+ signal: AbortSignal | undefined,
4257
4687
  effect: (exec: Exec) => Promise<T>,
4258
4688
  ): Promise<T> {
4259
4689
  const { origin } = await this.normalNetworkPolicy(ref)
@@ -4288,31 +4718,32 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4288
4718
  try {
4289
4719
  await sandbox.update(
4290
4720
  { networkPolicy: this.billingPolicy(policy, ref) },
4291
- { signal: this.operationSignal() },
4721
+ { signal: this.recoveryMetadataSignal() },
4292
4722
  )
4293
4723
  return await effect(async (cmd) => {
4724
+ const bound = signal ?? this.operationSignal()
4294
4725
  const result = await sandbox.runCommand({
4295
4726
  cmd: cmd[0]!,
4296
4727
  args: cmd.slice(1),
4297
4728
  cwd: VERCEL_WORKSPACE_PATH,
4298
- signal: this.operationSignal(),
4729
+ signal: bound,
4299
4730
  })
4300
4731
  if (!('stdout' in result) || !('stderr' in result) || result.exitCode === null)
4301
4732
  throw new Error('trusted preservation requires captured command output')
4302
4733
  return {
4303
4734
  exitCode: result.exitCode,
4304
- stdout: await result.stdout!(),
4305
- stderr: await result.stderr!(),
4735
+ stdout: await result.stdout!({ signal: bound }),
4736
+ stderr: await result.stderr!({ signal: bound }),
4306
4737
  }
4307
4738
  })
4308
4739
  } finally {
4309
4740
  try {
4310
4741
  await sandbox.update(
4311
4742
  { networkPolicy: (await this.normalNetworkPolicy(ref)).policy },
4312
- { signal: this.operationSignal() },
4743
+ { signal: this.recoveryMetadataSignal() },
4313
4744
  )
4314
4745
  } finally {
4315
- await sandbox.stop({ signal: this.operationSignal() })
4746
+ await this.recoveryStop(ref, sandbox)
4316
4747
  }
4317
4748
  }
4318
4749
  }
@@ -4329,6 +4760,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4329
4760
  localExpected?: string
4330
4761
  archives?: { ref: string; sha: string }[]
4331
4762
  retain?: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]['retain']
4763
+ }): Promise<void | import('../types').RewriteResult> {
4764
+ // Settling a requested publication is part of preserving the work.
4765
+ return this.deadlineAware('preserve', () => this.publishOnce(input))
4766
+ }
4767
+
4768
+ private async publishOnce(input: {
4769
+ ref: string
4770
+ sha: string
4771
+ branch: string
4772
+ expected?: string
4773
+ localExpected?: string
4774
+ archives?: { ref: string; sha: string }[]
4775
+ retain?: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]['retain']
4332
4776
  }): Promise<void | import('../types').RewriteResult> {
4333
4777
  if (this.active.has(input.ref) || this.uncertain.has(input.ref)) {
4334
4778
  throw new Error('publication is forbidden until sandbox execution teardown is confirmed')
@@ -4341,8 +4785,13 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4341
4785
  throw new Error('vercel-sandbox publication requires GITHUB_TOKEN or GH_TOKEN')
4342
4786
  }
4343
4787
  const { origin } = await this.normalNetworkPolicy(input.ref)
4344
- const sandbox =
4345
- this.sessions.get(input.ref) ?? (await this.facade.get(input.ref, this.operationSignal()))
4788
+ const found =
4789
+ this.sessions.get(input.ref) ??
4790
+ (await this.facade.get(input.ref, this.recoveryMetadataSignal()))
4791
+ if (found === null) throw new Error(`unknown sandbox ${input.ref}`)
4792
+ // One recovery budget covers the explicit resume and the guest git.
4793
+ const signal = this.recoveryWorkSignal()
4794
+ const sandbox = await this.resumeForRecovery(input.ref, found, signal)
4346
4795
  if (sandbox === null) throw new Error(`unknown sandbox ${input.ref}`)
4347
4796
  this.sessions.set(input.ref, sandbox)
4348
4797
  const publicationPolicy: NetworkPolicy = {
@@ -4394,7 +4843,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4394
4843
  try {
4395
4844
  await sandbox.update(
4396
4845
  { networkPolicy: this.billingPolicy(publicationPolicy, input.ref) },
4397
- { signal: this.operationSignal() },
4846
+ { signal: this.recoveryMetadataSignal() },
4398
4847
  )
4399
4848
  if (input.expected !== undefined) {
4400
4849
  const trustedExec: Exec = async (cmd) => {
@@ -4402,6 +4851,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4402
4851
  cmd: cmd[0]!,
4403
4852
  args: cmd.slice(1),
4404
4853
  cwd: VERCEL_WORKSPACE_PATH,
4854
+ signal,
4405
4855
  })
4406
4856
  if (result.exitCode === null)
4407
4857
  throw new Error('trusted rewrite command has no exit status')
@@ -4409,8 +4859,8 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4409
4859
  throw new Error('trusted rewrite requires command output capture')
4410
4860
  return {
4411
4861
  exitCode: result.exitCode,
4412
- stdout: await result.stdout!(),
4413
- stderr: await result.stderr!(),
4862
+ stdout: await result.stdout!({ signal }),
4863
+ stderr: await result.stderr!({ signal }),
4414
4864
  }
4415
4865
  }
4416
4866
  const capability = this.archiveTransport(trustedExec)
@@ -4437,6 +4887,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4437
4887
  cmd: 'git',
4438
4888
  args: ['push', '--no-verify', 'origin', `${input.sha}:refs/heads/${input.branch}`],
4439
4889
  cwd: VERCEL_WORKSPACE_PATH,
4890
+ signal,
4440
4891
  })
4441
4892
  } catch (error) {
4442
4893
  if (!(await this.isPublished(input))) throw error
@@ -4451,16 +4902,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4451
4902
  cmd: 'git',
4452
4903
  args: ['update-ref', `refs/heads/${input.branch}`, input.sha],
4453
4904
  cwd: VERCEL_WORKSPACE_PATH,
4905
+ signal,
4454
4906
  })
4455
- await sandbox.stop({ signal: this.operationSignal() })
4907
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
4456
4908
  } finally {
4457
4909
  try {
4458
4910
  await sandbox.update(
4459
4911
  { networkPolicy: (await this.normalNetworkPolicy(input.ref)).policy },
4460
- { signal: this.operationSignal() },
4912
+ { signal: this.recoveryMetadataSignal() },
4461
4913
  )
4462
4914
  } finally {
4463
- await sandbox.stop({ signal: this.operationSignal() })
4915
+ await this.recoveryStop(input.ref, sandbox)
4464
4916
  }
4465
4917
  }
4466
4918
  }