@defrex/autobuild 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +435 -160
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +25 -3
  5. package/docs/architecture.md +124 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +110 -15
  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 +5 -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 +51 -12
  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 +17 -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 +527 -144
  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/repository.ts +14 -3
  54. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +27 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  61. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  63. package/packages/core/src/kernel/done-escalations.ts +269 -0
  64. package/packages/core/src/kernel/engine.ts +28 -9
  65. package/packages/core/src/kernel/integration-landing.ts +24 -4
  66. package/packages/core/src/kernel/integration-stack.ts +39 -0
  67. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  68. package/packages/core/src/kernel/log-index-value.ts +3 -0
  69. package/packages/core/src/kernel/log-index.ts +41 -2
  70. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  71. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  72. package/packages/core/src/kernel/reducer-revisions.ts +15 -0
  73. package/packages/core/src/kernel/reducer.ts +27 -7
  74. package/packages/core/src/kernel/repository-attention.ts +14 -5
  75. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  76. package/packages/core/src/kernel/verify-stages.ts +46 -7
  77. package/packages/core/src/operator/attention.ts +28 -3
  78. package/packages/core/src/operator/done-escalations.ts +38 -0
  79. package/packages/core/src/operator/presentation.ts +1 -1
  80. package/packages/core/src/operator/protocol.ts +8 -5
  81. package/packages/core/src/operator/query.ts +33 -19
  82. package/packages/core/src/operator/registry.ts +17 -13
  83. package/packages/core/src/operator/ticket-start.ts +8 -7
  84. package/packages/core/src/operator/tickets.ts +28 -9
  85. package/packages/core/src/plugin-sdk/index.ts +10 -0
  86. package/packages/core/src/plugins/manifest.ts +14 -1
  87. package/packages/core/src/ports/forge/create.ts +8 -0
  88. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  89. package/packages/core/src/ports/forge/github.ts +3 -0
  90. package/packages/core/src/ports/tickets/contract.ts +147 -76
  91. package/packages/core/src/ports/tickets/create.ts +47 -7
  92. package/packages/core/src/ports/tickets/fake.ts +8 -4
  93. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  94. package/packages/core/src/ports/tickets/file.ts +7 -3
  95. package/packages/core/src/ports/tickets/github.ts +1 -0
  96. package/packages/core/src/ports/tickets/grants.ts +11 -3
  97. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  98. package/packages/core/src/ports/tickets/linear.ts +28 -9
  99. package/packages/core/src/ports/tickets/migration.ts +4 -4
  100. package/packages/core/src/ports/tickets/operations.ts +4 -2
  101. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  102. package/packages/core/src/ports/tickets/priority.ts +127 -21
  103. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  104. package/packages/core/src/ports/tickets/remote.ts +104 -11
  105. package/packages/core/src/ports/tickets/revision.ts +5 -3
  106. package/packages/core/src/ports/tickets/search.ts +9 -0
  107. package/packages/core/src/ports/tickets/tree.ts +8 -6
  108. package/packages/core/src/ports/types.ts +30 -15
  109. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  110. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  111. package/packages/core/src/ports/workspace/create.ts +16 -3
  112. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  113. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  114. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  115. package/packages/core/src/processes/build-execution-state.ts +4 -0
  116. package/packages/core/src/processes/build-runner.ts +14 -1
  117. package/packages/core/src/processes/dispatcher.ts +544 -212
  118. package/packages/core/src/processes/execution-settlement.ts +1 -0
  119. package/packages/core/src/processes/harvest-runner.ts +12 -7
  120. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  121. package/packages/core/src/processes/invocation-budget.ts +176 -0
  122. package/packages/core/src/processes/publication-loss.ts +38 -3
  123. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  124. package/packages/core/src/store/contract.ts +81 -3
  125. package/packages/core/src/store/event-reads.ts +30 -1
  126. package/packages/core/src/store/reduced-reads.ts +23 -0
  127. package/packages/core/src/store/reducer-value-shapes.json +6628 -6469
  128. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  129. package/packages/core/src/store/remote/client.ts +169 -29
  130. package/packages/core/src/store/remote/compatibility.ts +113 -56
  131. package/packages/core/src/store/remote/credentials.ts +4 -1
  132. package/packages/core/src/store/remote/protocol.ts +3 -0
  133. package/packages/core/src/store/remote/released-clients.json +11 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  135. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  136. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  137. package/packages/core/src/store/remote/retry.ts +406 -0
  138. package/packages/core/src/testing/dispatch-read-budget.ts +144 -10
  139. package/packages/core/src/testing/index.ts +2 -0
  140. package/packages/core/src/testing/invocation-budget.ts +42 -0
  141. package/packages/core/src/testing/reduced-read-budget.ts +381 -18
  142. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  143. package/packages/core/src/web/overview-source.ts +19 -6
  144. package/skills/guide/SKILL.md +138 -67
  145. package/skills/guide/references/integration-tree.md +12 -9
  146. package/skills/guide/references/merge-policy.md +7 -2
  147. package/skills/guide/references/operator-api.md +46 -23
  148. package/skills/guide/references/optimization-nodes.md +7 -6
  149. package/skills/guide/references/plugin-authoring.md +46 -18
  150. package/skills/guide/references/remote-store-protocol.md +51 -12
  151. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  152. package/skills/guide/references/restacking.md +48 -3
  153. package/skills/guide/references/setup.md +2 -1
  154. package/skills/guide/references/ticket-migration.md +2 -2
  155. package/skills/operate/SKILL.md +82 -51
  156. package/skills/plan/SKILL.md +4 -3
  157. package/skills/spec/SKILL.md +9 -5
  158. package/skills/tickets/SKILL.md +25 -17
  159. package/templates/hosted-service/package.json +2 -2
@@ -12,6 +12,14 @@ 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
+ WorkspaceRecoveryDeferred,
20
+ WorkspaceRecoveryStepError,
21
+ type WorkspaceRecoveryStep,
22
+ } from './recovery-step'
15
23
  import { Sandbox, Snapshot, type NetworkPolicy, type SandboxRegion } from '@vercel/sandbox'
16
24
  import { displayName, tomlKey, type RuntimeReferenceGroup } from '../../config/roles'
17
25
  import {
@@ -96,8 +104,10 @@ export interface VercelCommand {
96
104
  * and declared system-provisioning failure diagnostics, including failures
97
105
  * during durable build provisioning. It is not a durable build-state channel;
98
106
  * scoped Store facts/events remain authoritative. */
99
- stdout?(): Promise<string>
100
- stderr?(): Promise<string>
107
+ /** Reading output opens its own log stream, bounded only by the signal
108
+ * passed here, never by the command's. */
109
+ stdout?(opts?: { signal?: AbortSignal }): Promise<string>
110
+ stderr?(opts?: { signal?: AbortSignal }): Promise<string>
101
111
  }
102
112
 
103
113
  /**
@@ -142,8 +152,10 @@ export interface VercelCommandLookup {
142
152
  wait(params?: { signal?: AbortSignal }): Promise<{ exitCode: number }>
143
153
  /** Completed-command output, when the concrete handle exposes it (the SDK's
144
154
  * `Command` does; narrow lookups may omit it). Read only after exit. */
145
- stdout?(): Promise<string>
146
- stderr?(): Promise<string>
155
+ /** Reading output opens its own log stream, bounded only by the signal
156
+ * passed here, never by the command's. */
157
+ stdout?(opts?: { signal?: AbortSignal }): Promise<string>
158
+ stderr?(opts?: { signal?: AbortSignal }): Promise<string>
147
159
  }
148
160
 
149
161
  export interface VercelSandboxHandle {
@@ -259,6 +271,23 @@ export const VERCEL_OBSERVE_WAIT_MS = 5_000
259
271
  * finishes. */
260
272
  export const VERCEL_PROVISION_ESTIMATE_MS = 150_000
261
273
 
274
+ /** Default budget for one stopped-sandbox recovery: an explicit cold resume
275
+ * plus the guest git work that follows it (`recoveryTimeoutMs`). */
276
+ export const VERCEL_RECOVERY_TIMEOUT_MS = 120_000
277
+
278
+ /** Interval between session polls while a resume or stop settles. */
279
+ const SESSION_POLL_MS = 500
280
+
281
+ /** Timer slack when deciding whether an abort came from a deadline. */
282
+ const DEADLINE_SLACK_MS = 10
283
+
284
+ /** Where the guest runner of one execution instance records its exit, on the
285
+ * sandbox's persistent filesystem. Hashing keeps any instance id a safe
286
+ * file name. */
287
+ export function executionExitPath(instance: string): string {
288
+ return `/vercel/sandbox/.autobuild-executions/${createHash('sha256').update(instance).digest('hex')}.json`
289
+ }
290
+
262
291
  /** The snapshot rows that hold billed storage. `deleted`/`failed` rows hold
263
292
  * none and are never purge targets. */
264
293
  const LIVE_SNAPSHOT_STATUS = 'created'
@@ -285,6 +314,11 @@ export interface VercelSnapshotPurge {
285
314
 
286
315
  export interface VercelSandboxFacade {
287
316
  get(name: string, signal?: AbortSignal): Promise<VercelSandboxHandle | null>
317
+ /** Explicitly resume a stopped persistent environment and return a handle
318
+ * on its running session; null when the environment is absent. A stop in
319
+ * progress settles first, and a pending session is polled until running,
320
+ * all under `signal`. Required by recovery of a stopped sandbox. */
321
+ resume?(name: string, signal?: AbortSignal): Promise<VercelSandboxHandle | null>
288
322
  /** Creation never deletes an existing named environment. */
289
323
  create(input: VercelSandboxCreateInput): Promise<VercelSandboxHandle>
290
324
  /** Dispatcher-authorized destruction only, after fence and commit receipt. */
@@ -384,18 +418,35 @@ export function createVercelSdkFacade(
384
418
  fetch: typeof globalThis.fetch = globalThis.fetch,
385
419
  ): VercelSandboxFacade {
386
420
  const credentials = vercelSdkCredentials(env)
421
+ const lookup = async (name: string, signal: AbortSignal | undefined, resume: boolean) => {
422
+ try {
423
+ return withSessionMetadata(await Sandbox.get({ name, signal, resume, fetch, ...credentials }))
424
+ } catch (error) {
425
+ // Provision must retain the stale name so dispatcher cleanup can delete it.
426
+ if (isUnavailableVercelSnapshot(error)) throw error
427
+ if (isMissingVercelSandbox(error)) return null
428
+ throw error
429
+ }
430
+ }
431
+ const settling = (status: VercelSandboxHandle['sessionStatus']) =>
432
+ status === 'stopping' || status === 'snapshotting'
387
433
  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
434
+ get: (name, signal) => lookup(name, signal, false),
435
+ async resume(name, signal) {
436
+ // The provider refuses to resume a session that is still stopping or
437
+ // snapshotting, so wait for it to settle first.
438
+ let current = await lookup(name, signal, false)
439
+ while (current !== null && settling(current.sessionStatus)) {
440
+ await sleep(SESSION_POLL_MS, undefined, { signal })
441
+ current = await lookup(name, signal, false)
442
+ }
443
+ if (current === null || current.sessionStatus === 'running') return current
444
+ current = await lookup(name, signal, true)
445
+ while (current !== null && current.sessionStatus === 'pending') {
446
+ await sleep(SESSION_POLL_MS, undefined, { signal })
447
+ current = await lookup(name, signal, false)
398
448
  }
449
+ return current
399
450
  },
400
451
  async create(input) {
401
452
  return withSessionMetadata(
@@ -916,8 +967,9 @@ async function readableCommand(
916
967
  },
917
968
  ): Promise<string> {
918
969
  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()
970
+ const output = params.signal === undefined ? undefined : { signal: params.signal }
971
+ const stderr = result.stderr === undefined ? '' : await result.stderr(output)
972
+ const stdout = result.stdout === undefined ? '' : await result.stdout(output)
921
973
  if (result.exitCode === null || result.exitCode === undefined) {
922
974
  throw new Error(`sandbox command ${params.cmd} did not return an exit status`)
923
975
  }
@@ -1491,6 +1543,9 @@ export interface VercelSandboxProviderOptions {
1491
1543
  * mode) it is never touched on the host. */
1492
1544
  repo: string
1493
1545
  facade?: VercelSandboxFacade
1546
+ /** SDK transport for the default facade; absent ⇒ global `fetch`. A
1547
+ * bounded dispatcher invocation passes one that cancels at its deadline. */
1548
+ fetch?: typeof globalThis.fetch
1494
1549
  exec?: Exec
1495
1550
  packageArchive?: () => Promise<Uint8Array>
1496
1551
  accounts?: () => import('../../config/accounts').Accounts
@@ -1544,6 +1599,11 @@ export interface VercelSandboxProviderOptions {
1544
1599
  * provisioning never uses it. Mutually exclusive with a configured
1545
1600
  * `gitPasswordEnv`. */
1546
1601
  egressReadCredential?: { username: string; password: string }
1602
+ /** The hosted invocation's deadline (epoch ms). Every recovery-path
1603
+ * provider call is bounded by it; guest recovery work stops early enough to
1604
+ * leave a cleanup reserve of twice `operationTimeoutMs`. Absent (local
1605
+ * dispatch) means each call keeps only its own cap. */
1606
+ invocationDeadlineAt?: number
1547
1607
  }
1548
1608
 
1549
1609
  /** Vercel-backed working copy and executor. Completed SDK command output is
@@ -1621,7 +1681,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1621
1681
  'vercel-sandbox accepts either a deployment egress read credential or a configured gitPasswordEnv, not both',
1622
1682
  )
1623
1683
  }
1624
- this.facade = options.facade ?? createVercelSdkFacade(options.env)
1684
+ this.facade = options.facade ?? createVercelSdkFacade(options.env, options.fetch)
1625
1685
  this.exec = options.exec ?? spawnExec
1626
1686
  this.observeWaitMs = options.observeWaitMs ?? VERCEL_OBSERVE_WAIT_MS
1627
1687
  // Constructor-body assignment, never a field initializer (see the
@@ -1658,25 +1718,32 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1658
1718
  fence: async (handle) => {
1659
1719
  if (handle.provider !== this.name) throw new Error('workspace fence provider mismatch')
1660
1720
  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' }
1721
+ return await this.deadlineAware('fence', async () => {
1722
+ // Never trust the in-process handle after restart or another resume.
1723
+ const sandbox = await this.facade.get(handle.ref, this.recoveryMetadataSignal())
1724
+ if (sandbox === null) {
1725
+ this.forget(handle.ref)
1726
+ return { outcome: 'absent' as const }
1727
+ }
1728
+ // A session the provider already reports stopped needs no second
1729
+ // stop; asking would only spend the acknowledgement budget.
1730
+ if (sandbox.sessionStatus !== 'stopped')
1731
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
1732
+ this.active.delete(handle.ref)
1733
+ this.uncertain.delete(handle.ref)
1734
+ this.sessions.set(handle.ref, sandbox)
1735
+ return { outcome: 'confirmed' as const }
1736
+ })
1672
1737
  } catch (error) {
1738
+ // The invocation deadline is not a fence failure: retry next time.
1739
+ if (isRecoveryDeferred(error)) throw error
1673
1740
  if (isMissingVercelSandbox(error)) {
1674
1741
  this.forget(handle.ref)
1675
1742
  return { outcome: 'absent' }
1676
1743
  }
1677
1744
  return {
1678
1745
  outcome: 'unknown',
1679
- error: error instanceof Error ? error.message : String(error),
1746
+ error: `fence: ${error instanceof Error ? error.message : String(error)}`,
1680
1747
  }
1681
1748
  }
1682
1749
  },
@@ -1691,77 +1758,88 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1691
1758
  }
1692
1759
  this.publication = {
1693
1760
  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({
1761
+ this.withPolicyLock(input.ref, () =>
1762
+ this.deadlineAware('preserve', async () => {
1763
+ if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1764
+ throw new Error('candidate recovery requires confirmed teardown')
1765
+ const found = await this.facade.get(input.ref, this.recoveryMetadataSignal())
1766
+ const signal = this.recoveryWorkSignal()
1767
+ const sandbox = found && (await this.resumeForRecovery(input.ref, found, signal))
1768
+ if (!sandbox) throw new Error('candidate recovery awaits replacement workspace')
1769
+ return this.withTrustedGit(sandbox, input.ref, signal, async (exec) => {
1770
+ const archiveRef = `refs/autobuild/archive/${input.slug}/${input.sha}`
1771
+ const available = await inspectGitCandidate({
1772
+ ...input,
1773
+ exec,
1774
+ workspacePath: VERCEL_WORKSPACE_PATH,
1775
+ archiveRef,
1776
+ })
1777
+ if (available)
1778
+ try {
1779
+ await this.archiveTransport(exec).archive({
1748
1780
  workspacePath: VERCEL_WORKSPACE_PATH,
1749
- branch: input.branch,
1750
- destinationRef: `refs/autobuild/reconcile/${input.slug}/preservation`,
1781
+ ref: archiveRef,
1782
+ sha: input.sha,
1751
1783
  })
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,
1784
+ } catch (error) {
1785
+ // Archive refs are best effort: the settlement rewrite retains
1786
+ // the candidate through its `retain` fallback.
1787
+ if (!isArchiveRefusal(error)) throw error
1788
+ }
1789
+ return available
1760
1790
  })
1761
- })
1762
- if (heads === null) return { outcome: 'absent' }
1763
- return { outcome: 'preserved', heads }
1764
- }),
1791
+ }),
1792
+ ),
1793
+ preserve: (input) =>
1794
+ this.withPolicyLock(input.ref, () =>
1795
+ this.deadlineAware('preserve', async () => {
1796
+ if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1797
+ throw new Error('preservation requires confirmed execution teardown')
1798
+ const found = await this.facade.get(input.ref, this.recoveryMetadataSignal())
1799
+ // A stopped persistent sandbox is resumed explicitly under the
1800
+ // recovery budget, never implicitly by the first guest command
1801
+ // under the short acknowledgement cap.
1802
+ const signal = this.recoveryWorkSignal()
1803
+ const sandbox = found && (await this.resumeForRecovery(input.ref, found, signal))
1804
+ if (sandbox === null) return { outcome: 'absent' as const }
1805
+ const heads = await this.withTrustedGit(sandbox, input.ref, signal, async (exec) => {
1806
+ // A VM whose provisioning stopped before the checkout was moved
1807
+ // into place has nothing to preserve. The probe runs without the
1808
+ // checkout as cwd, and only a definite "missing" proves absence.
1809
+ const checkout = await sandbox.runCommand({
1810
+ cmd: 'test',
1811
+ args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
1812
+ signal,
1813
+ })
1814
+ if (checkout.exitCode === 1) return null
1815
+ if (checkout.exitCode !== 0)
1816
+ throw new Error(
1817
+ `preservation could not confirm the checkout at ${VERCEL_WORKSPACE_PATH} (exit ${checkout.exitCode})`,
1818
+ )
1819
+ const capability = this.archiveTransport(exec)
1820
+ const remote = await this.remoteBranchHead(input.branch, 'preservation branch')
1821
+ const base =
1822
+ remote === null
1823
+ ? input.base
1824
+ : await capability.snapshot({
1825
+ workspacePath: VERCEL_WORKSPACE_PATH,
1826
+ branch: input.branch,
1827
+ destinationRef: `refs/autobuild/reconcile/${input.slug}/preservation`,
1828
+ })
1829
+ // After the guest push and the host REST fallback both refuse,
1830
+ // `input.retain` keeps the head as a store copy host-side.
1831
+ return preserveGitCommits({
1832
+ ...input,
1833
+ base,
1834
+ exec,
1835
+ workspacePath: VERCEL_WORKSPACE_PATH,
1836
+ archive: capability.archive,
1837
+ })
1838
+ })
1839
+ if (heads === null) return { outcome: 'absent' as const }
1840
+ return { outcome: 'preserved' as const, heads }
1841
+ }),
1842
+ ),
1765
1843
  rewrite: (input: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]) =>
1766
1844
  this.withPolicyLock(input.ref, () => this.publish(input)),
1767
1845
  isPublished: (input: { sha: string; branch: string }) => this.isPublished(input),
@@ -1796,6 +1874,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1796
1874
  this.options.storeRef,
1797
1875
  this.options.storeToken,
1798
1876
  { kind: 'build-runner', id: buildSlugFromBranch(opts.branch) },
1877
+ this.options.fetch,
1799
1878
  )
1800
1879
  const rawOrigin = await this.origin()
1801
1880
  const origin = cleanGithubOrigin(rawOrigin)
@@ -1998,7 +2077,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1998
2077
  let provisionHead = checkedOut
1999
2078
  let restorationSkipped: import('../types').RestorationSkip[] = []
2000
2079
  if (opts.restoration?.length) {
2001
- provisionHead = await this.withTrustedGit(sandbox, name, async (exec) => {
2080
+ provisionHead = await this.withTrustedGit(sandbox, name, undefined, async (exec) => {
2002
2081
  restorationSkipped = (
2003
2082
  await restoreGitCommits({
2004
2083
  exec,
@@ -2127,16 +2206,177 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2127
2206
  }
2128
2207
 
2129
2208
  private operationSignal(): AbortSignal {
2130
- return AbortSignal.timeout(this.options.config.operationTimeoutMs ?? 30_000)
2209
+ return AbortSignal.timeout(this.operationTimeoutMs())
2210
+ }
2211
+
2212
+ private operationTimeoutMs(): number {
2213
+ return this.options.config.operationTimeoutMs ?? 30_000
2214
+ }
2215
+
2216
+ private recoveryTimeoutMs(): number {
2217
+ return this.options.config.recoveryTimeoutMs ?? VERCEL_RECOVERY_TIMEOUT_MS
2218
+ }
2219
+
2220
+ /** Time held back from guest recovery work for the finally-block policy
2221
+ * restore and stop that follow it. */
2222
+ private cleanupReserveMs(): number {
2223
+ return 2 * this.operationTimeoutMs()
2224
+ }
2225
+
2226
+ /** The last moment guest recovery work may run: the invocation deadline
2227
+ * less the cleanup reserve. Undefined without an invocation deadline. */
2228
+ private recoveryWorkBound(): number | undefined {
2229
+ const deadline = this.options.invocationDeadlineAt
2230
+ return deadline === undefined ? undefined : deadline - this.cleanupReserveMs()
2231
+ }
2232
+
2233
+ private static bounded(cap: number, until: number | undefined): AbortSignal {
2234
+ const own = AbortSignal.timeout(cap)
2235
+ if (until === undefined) return own
2236
+ return AbortSignal.any([own, AbortSignal.timeout(Math.max(0, until - Date.now()))])
2237
+ }
2238
+
2239
+ /** A metadata call on a recovery path: `operationTimeoutMs`, and never
2240
+ * past the invocation deadline. Taken fresh at the moment the call starts,
2241
+ * so a finally-block call still gets the reserved cleanup window. */
2242
+ private recoveryMetadataSignal(): AbortSignal {
2243
+ return VercelSandboxProvider.bounded(
2244
+ this.operationTimeoutMs(),
2245
+ this.options.invocationDeadlineAt,
2246
+ )
2247
+ }
2248
+
2249
+ /** A resume or guest command on a recovery path: `recoveryTimeoutMs`, and
2250
+ * never past the reserved work bound. */
2251
+ private recoveryWorkSignal(): AbortSignal {
2252
+ return VercelSandboxProvider.bounded(this.recoveryTimeoutMs(), this.recoveryWorkBound())
2253
+ }
2254
+
2255
+ /** Whether a cold resume plus its cleanup still fits before the
2256
+ * invocation deadline. Always true without one. */
2257
+ private recoveryBudgetAvailable(): boolean {
2258
+ const deadline = this.options.invocationDeadlineAt
2259
+ if (deadline === undefined) return true
2260
+ return deadline - Date.now() >= this.recoveryTimeoutMs() + this.cleanupReserveMs()
2261
+ }
2262
+
2263
+ private remainingMs(): number {
2264
+ const deadline = this.options.invocationDeadlineAt
2265
+ return deadline === undefined ? Number.POSITIVE_INFINITY : deadline - Date.now()
2266
+ }
2267
+
2268
+ /** Whether an error is the invocation deadline aborting a call rather than
2269
+ * a provider failure: the reserved work bound has passed and the error
2270
+ * reads as an abort or timeout. */
2271
+ private deadlineAbort(error: unknown): boolean {
2272
+ const bound = this.recoveryWorkBound()
2273
+ if (bound === undefined || Date.now() + DEADLINE_SLACK_MS < bound) return false
2274
+ const seen = new Set<unknown>()
2275
+ for (let current = error; current instanceof Error && !seen.has(current); ) {
2276
+ seen.add(current)
2277
+ if (current.name === 'AbortError' || current.name === 'TimeoutError') return true
2278
+ if (/abort|timed out|timeout/i.test(current.message)) return true
2279
+ current = current.cause
2280
+ }
2281
+ return false
2282
+ }
2283
+
2284
+ /** Run one recovery operation, reporting a deadline abort as a typed
2285
+ * deferral naming `step` instead of as a provider failure. */
2286
+ private async deadlineAware<T>(step: WorkspaceRecoveryStep, fn: () => Promise<T>): Promise<T> {
2287
+ try {
2288
+ return await fn()
2289
+ } catch (error) {
2290
+ if (isRecoveryDeferred(error) || !this.deadlineAbort(error)) throw error
2291
+ throw new WorkspaceRecoveryDeferred(
2292
+ step,
2293
+ { remainingMs: this.remainingMs() },
2294
+ { cause: error },
2295
+ )
2296
+ }
2297
+ }
2298
+
2299
+ /** Stop at the end of a recovery operation. A stop the deadline aborted
2300
+ * may leave the VM running, so the ref stays uncertain until a later fence
2301
+ * or reap confirms teardown. */
2302
+ private async recoveryStop(ref: string, sandbox: VercelSandboxHandle): Promise<void> {
2303
+ try {
2304
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2305
+ } catch (error) {
2306
+ if (this.deadlineAbort(error)) {
2307
+ this.uncertain.add(ref)
2308
+ this.sessions.delete(ref)
2309
+ }
2310
+ throw error
2311
+ }
2312
+ }
2313
+
2314
+ /** Bring a stopped persistent sandbox back explicitly, under the recovery
2315
+ * budget rather than the short metadata cap. A running handle (or one from
2316
+ * a facade without session metadata) is returned unchanged; null means the
2317
+ * environment is gone. */
2318
+ private async resumeForRecovery(
2319
+ ref: string,
2320
+ sandbox: VercelSandboxHandle,
2321
+ signal: AbortSignal = this.recoveryWorkSignal(),
2322
+ ): Promise<VercelSandboxHandle | null> {
2323
+ if (sandbox.sessionStatus === undefined || sandbox.sessionStatus === 'running') return sandbox
2324
+ if (!this.recoveryBudgetAvailable())
2325
+ throw new WorkspaceRecoveryDeferred('resume', {
2326
+ remainingMs: this.remainingMs(),
2327
+ requiredMs: this.recoveryTimeoutMs() + this.cleanupReserveMs(),
2328
+ })
2329
+ if (this.facade.resume === undefined)
2330
+ throw new WorkspaceRecoveryStepError(
2331
+ 'resume',
2332
+ new Error('sandbox facade lacks explicit resume; upgrade the facade'),
2333
+ )
2334
+ let resumed: VercelSandboxHandle | null
2335
+ try {
2336
+ resumed = await this.facade.resume(ref, signal)
2337
+ } catch (error) {
2338
+ if (isMissingVercelSandbox(error)) throw error
2339
+ if (this.deadlineAbort(error))
2340
+ throw new WorkspaceRecoveryDeferred(
2341
+ 'resume',
2342
+ { remainingMs: this.remainingMs() },
2343
+ {
2344
+ cause: error,
2345
+ },
2346
+ )
2347
+ throw new WorkspaceRecoveryStepError(
2348
+ 'resume',
2349
+ signal.aborted
2350
+ ? new Error(
2351
+ `resume of sandbox ${ref} exceeded its ${this.recoveryTimeoutMs()} ms recovery timeout`,
2352
+ { cause: error },
2353
+ )
2354
+ : error,
2355
+ )
2356
+ }
2357
+ if (resumed === null) {
2358
+ this.forget(ref)
2359
+ return null
2360
+ }
2361
+ this.sessions.set(ref, resumed)
2362
+ return resumed
2131
2363
  }
2132
2364
 
2133
2365
  /** Stop/delete and then prove absence by exact deterministic name — for the
2134
2366
  * sandbox and, because deleting a sandbox never removes the automatic
2135
2367
  * snapshots its sessions created, for its snapshot storage too. */
2136
- private async reap(ref: string, dispatcherAuthorized = false): Promise<WorkspaceReapOutcome> {
2368
+ private reap(ref: string, dispatcherAuthorized = false): Promise<WorkspaceReapOutcome> {
2369
+ return this.deadlineAware('cleanup', () => this.reapOnce(ref, dispatcherAuthorized))
2370
+ }
2371
+
2372
+ private async reapOnce(
2373
+ ref: string,
2374
+ dispatcherAuthorized: boolean,
2375
+ ): Promise<WorkspaceReapOutcome> {
2137
2376
  let sandbox: VercelSandboxHandle | null
2138
2377
  try {
2139
- sandbox = this.sessions.get(ref) ?? (await this.facade.get(ref, this.operationSignal()))
2378
+ sandbox =
2379
+ this.sessions.get(ref) ?? (await this.facade.get(ref, this.recoveryMetadataSignal()))
2140
2380
  } catch (error) {
2141
2381
  if (!isMissingVercelSandbox(error)) throw error
2142
2382
  sandbox = null
@@ -2146,7 +2386,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2146
2386
  if (dispatcherAuthorized) {
2147
2387
  if (!this.facade.deleteByName)
2148
2388
  throw new Error('sandbox facade lacks dispatcher-authorized deleteByName')
2149
- await this.facade.deleteByName(ref, this.operationSignal())
2389
+ await this.facade.deleteByName(ref, this.recoveryMetadataSignal())
2150
2390
  }
2151
2391
  // An environment can vanish without its snapshots; the purge still
2152
2392
  // applies and only a confirmed empty list may forget the reference.
@@ -2160,7 +2400,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2160
2400
  }
2161
2401
  try {
2162
2402
  try {
2163
- await sandbox.stop({ signal: this.operationSignal() })
2403
+ // An already-stopped session needs no second stop.
2404
+ if (sandbox.sessionStatus !== 'stopped')
2405
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2164
2406
  } catch (error) {
2165
2407
  // A persistent sandbox that was resumed once can wedge so that stop
2166
2408
  // never returns while delete still succeeds within seconds. Absence
@@ -2174,9 +2416,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2174
2416
  if (dispatcherAuthorized) {
2175
2417
  if (!this.facade.deleteByName)
2176
2418
  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())
2419
+ await this.facade.deleteByName(ref, this.recoveryMetadataSignal())
2420
+ } else await sandbox.delete({ signal: this.recoveryMetadataSignal() })
2421
+ sandbox = await this.facade.get(ref, this.recoveryMetadataSignal())
2180
2422
  if (sandbox !== null)
2181
2423
  throw new Error(`sandbox ${ref} still exists after delete acknowledgement`)
2182
2424
  // The post-delete pass catches anything the delete itself created;
@@ -2200,7 +2442,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2200
2442
  /** Purge one environment's snapshots, converting an unknown outcome into
2201
2443
  * the retryable cleanup failure the dispatcher already retries. */
2202
2444
  private async purgeOrRetryable(ref: string): Promise<VercelSnapshotPurge> {
2203
- const purged = await purgeEnvironmentSnapshots(this.facade, ref, this.operationSignal())
2445
+ const purged = await purgeEnvironmentSnapshots(this.facade, ref, this.recoveryMetadataSignal())
2204
2446
  if (purged.outcome === 'unknown') {
2205
2447
  throw new Error(
2206
2448
  `snapshot purge for ${JSON.stringify(ref)} is unconfirmed: ${purged.error ?? 'unknown outcome'}`,
@@ -2286,6 +2528,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2286
2528
  this.options.storeRef,
2287
2529
  this.options.storeToken,
2288
2530
  { kind: 'build-runner', id: input.slug },
2531
+ this.options.fetch,
2289
2532
  ))
2290
2533
  const ref = input.workspaceRef
2291
2534
  if (this.active.has(ref)) throw new Error(`sandbox ${ref} already has a live execution`)
@@ -2351,6 +2594,10 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2351
2594
  // instead of going out anonymously. Applied last so no forwarded value
2352
2595
  // can disable it.
2353
2596
  env[GITHUB_REQUIRE_CREDENTIAL_ENV] = '1'
2597
+ // The runner records its exit here, so a later observation of a stopped
2598
+ // sandbox can still settle the execution. Applied last, like the
2599
+ // credential guard, so no forwarded value can redirect it.
2600
+ env[EXECUTION_EXIT_FILE_ENV] = executionExitPath(input.instance)
2354
2601
  const command = (await sandbox.runCommand({
2355
2602
  cmd: 'sh',
2356
2603
  args: [
@@ -2696,37 +2943,71 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2696
2943
  /** Observe a recovered execution and confirm whole-environment teardown
2697
2944
  * before exposing a terminal observation. Command exit alone does not prove
2698
2945
  * descendants have stopped writing to the shared workspace. Stop failures
2699
- * propagate so settlement retains the execution and lease and retries. */
2946
+ * propagate so settlement retains the execution and lease and retries. A
2947
+ * call the invocation deadline cuts short reads as `running`: nothing is
2948
+ * settled and the next invocation observes again. */
2700
2949
  private async observeExecution(identity: BuildExecutionIdentity): Promise<ExecutionObservation> {
2701
2950
  if (identity.commandId === undefined) {
2702
2951
  throw new Error(
2703
2952
  `execution on ${identity.workspaceRef} has no recorded command id and cannot be re-observed`,
2704
2953
  )
2705
2954
  }
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
2716
- }
2955
+ try {
2956
+ return await this.observeOnce(identity, identity.commandId)
2957
+ } catch (error) {
2958
+ if (isRecoveryDeferred(error) || this.deadlineAbort(error)) return { state: 'running' }
2959
+ throw error
2960
+ }
2961
+ }
2962
+
2963
+ /** Stop the environment, then report a terminal observation. */
2964
+ private async settledObservation(
2965
+ ref: string,
2966
+ sandbox: VercelSandboxHandle,
2967
+ observation: ExecutionObservation,
2968
+ ): Promise<ExecutionObservation> {
2969
+ try {
2970
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2971
+ } catch (error) {
2972
+ if (!isMissingVercelSandbox(error)) {
2973
+ this.uncertain.add(ref)
2974
+ this.sessions.delete(ref)
2975
+ throw error
2717
2976
  }
2718
- this.active.delete(identity.workspaceRef)
2719
- this.uncertain.delete(identity.workspaceRef)
2720
- this.sessions.delete(identity.workspaceRef)
2721
- return observation
2722
2977
  }
2978
+ this.active.delete(ref)
2979
+ this.uncertain.delete(ref)
2980
+ this.sessions.delete(ref)
2981
+ return observation
2982
+ }
2983
+
2984
+ private async observeOnce(
2985
+ identity: BuildExecutionIdentity,
2986
+ commandId: string,
2987
+ ): Promise<ExecutionObservation> {
2988
+ const ref = identity.workspaceRef
2989
+ const sandbox = await this.facade.get(ref, this.recoveryMetadataSignal())
2990
+ if (sandbox === null) return { state: 'lost' }
2991
+ const settled = (observation: ExecutionObservation) =>
2992
+ this.settledObservation(ref, sandbox, observation)
2723
2993
  const currentSession = sandbox.currentSession?.().sessionId
2724
- if (
2994
+ const newer =
2725
2995
  identity.sessionId !== undefined &&
2726
2996
  currentSession !== undefined &&
2727
2997
  currentSession !== identity.sessionId
2998
+ // A stopped session no longer reports its command's final state, and a
2999
+ // newer session (one a recovery resume created) never ran this runner.
3000
+ // The runner's own exit record on the persistent filesystem answers for
3001
+ // both, so a finished execution settles instead of reading as lost.
3002
+ if (
3003
+ identity.instance !== undefined &&
3004
+ (newer ||
3005
+ sandbox.sessionStatus === 'stopped' ||
3006
+ sandbox.sessionStatus === 'stopping' ||
3007
+ sandbox.sessionStatus === 'snapshotting')
2728
3008
  )
2729
- return { state: 'lost' }
3009
+ return this.observeExitRecord(identity.instance, ref, sandbox)
3010
+ if (newer) return { state: 'lost' }
2730
3011
  // Terminal provider status proves the recorded incarnation is stopped.
2731
3012
  // Never stop a newer resumed session or demand a second stop of one that
2732
3013
  // the provider already confirms stopped.
@@ -2766,10 +3047,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2766
3047
  try {
2767
3048
  await sandbox.update(
2768
3049
  { networkPolicy: refreshed.policy },
2769
- { signal: this.operationSignal() },
3050
+ { signal: this.recoveryMetadataSignal() },
2770
3051
  )
2771
- } catch {
2772
- await sandbox.stop({ signal: this.operationSignal() })
3052
+ } catch (error) {
3053
+ if (this.deadlineAbort(error)) return { state: 'running' }
3054
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2773
3055
  return { state: 'lost', attention: 'Account policy renewal failed; sandbox stopped' }
2774
3056
  }
2775
3057
  if (refreshed.missing.length) {
@@ -2784,8 +3066,8 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2784
3066
  attention === undefined ? observation : { ...observation, attention }
2785
3067
  let observation: ExecutionObservation
2786
3068
  try {
2787
- const command = await sandbox.getCommand(identity.commandId, {
2788
- signal: this.operationSignal(),
3069
+ const command = await sandbox.getCommand(commandId, {
3070
+ signal: this.recoveryMetadataSignal(),
2789
3071
  })
2790
3072
  if (command.exitCode !== null) {
2791
3073
  observation = { state: 'ended', exitCode: command.exitCode }
@@ -2794,7 +3076,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2794
3076
  const finished = await command.wait({
2795
3077
  signal: AbortSignal.any([
2796
3078
  AbortSignal.timeout(this.observeWaitMs),
2797
- this.operationSignal(),
3079
+ this.recoveryMetadataSignal(),
2798
3080
  ]),
2799
3081
  })
2800
3082
  observation = { state: 'ended', exitCode: finished.exitCode }
@@ -2814,6 +3096,61 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2814
3096
  return settled(diagnosed(observation))
2815
3097
  }
2816
3098
 
3099
+ /** Settle an execution from its runner's exit record. A session that is
3100
+ * not running is resumed explicitly under the recovery budget (or the
3101
+ * observation waits for a later invocation when the budget is short). The
3102
+ * environment is stopped again when the record proves the recorded runner
3103
+ * exited, or when this call resumed it; a newer session this call did not
3104
+ * resume is otherwise never stopped. Nothing here depends on process
3105
+ * memory, so any later observer settles the same execution. */
3106
+ private async observeExitRecord(
3107
+ instance: string,
3108
+ ref: string,
3109
+ sandbox: VercelSandboxHandle,
3110
+ ): Promise<ExecutionObservation> {
3111
+ let handle = sandbox
3112
+ let resumedHere = false
3113
+ if (sandbox.sessionStatus !== undefined && sandbox.sessionStatus !== 'running') {
3114
+ if (!this.recoveryBudgetAvailable()) return { state: 'running' }
3115
+ let resumed: VercelSandboxHandle | null
3116
+ try {
3117
+ resumed = await this.resumeForRecovery(ref, sandbox)
3118
+ } catch (error) {
3119
+ if (isMissingVercelSandbox(error)) return { state: 'lost' }
3120
+ throw error
3121
+ }
3122
+ if (resumed === null) return { state: 'lost' }
3123
+ handle = resumed
3124
+ resumedHere = true
3125
+ }
3126
+ let exitCode: number | null
3127
+ try {
3128
+ // One signal bounds the read and its output stream alike.
3129
+ const signal = this.recoveryWorkSignal()
3130
+ const result = (await handle.runCommand({
3131
+ cmd: 'cat',
3132
+ args: [executionExitPath(instance)],
3133
+ signal,
3134
+ })) as VercelCommand
3135
+ if (result.exitCode === 0) {
3136
+ exitCode = parseExecutionExit(
3137
+ result.stdout === undefined ? '' : await result.stdout({ signal }),
3138
+ instance,
3139
+ )
3140
+ } else if (result.exitCode === 1) exitCode = null
3141
+ else
3142
+ throw new Error(
3143
+ `reading the exit record of execution ${instance} on sandbox ${ref} exited ${String(result.exitCode)}`,
3144
+ )
3145
+ } catch (error) {
3146
+ if (isMissingVercelSandbox(error)) return { state: 'lost' }
3147
+ throw error
3148
+ }
3149
+ if (exitCode !== null) return this.settledObservation(ref, handle, { state: 'ended', exitCode })
3150
+ if (resumedHere) return this.settledObservation(ref, handle, { state: 'lost' })
3151
+ return { state: 'lost' }
3152
+ }
3153
+
2817
3154
  // ── Operator sandbox capability (AUT-340) ─────────────────────────
2818
3155
  //
2819
3156
  // One persistent, credential-free environment per operator × repository,
@@ -4251,9 +4588,15 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4251
4588
  return head === input.sha
4252
4589
  }
4253
4590
 
4591
+ /** Run guest git with a trusted forge credential in the network policy.
4592
+ * `signal` bounds the guest commands (one recovery operation's budget);
4593
+ * without it (provisioning restore) each command gets its own
4594
+ * acknowledgement cap. Every policy write and the final stop take a fresh
4595
+ * deadline-bounded metadata signal. */
4254
4596
  private async withTrustedGit<T>(
4255
4597
  sandbox: VercelSandboxHandle,
4256
4598
  ref: string,
4599
+ signal: AbortSignal | undefined,
4257
4600
  effect: (exec: Exec) => Promise<T>,
4258
4601
  ): Promise<T> {
4259
4602
  const { origin } = await this.normalNetworkPolicy(ref)
@@ -4288,31 +4631,32 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4288
4631
  try {
4289
4632
  await sandbox.update(
4290
4633
  { networkPolicy: this.billingPolicy(policy, ref) },
4291
- { signal: this.operationSignal() },
4634
+ { signal: this.recoveryMetadataSignal() },
4292
4635
  )
4293
4636
  return await effect(async (cmd) => {
4637
+ const bound = signal ?? this.operationSignal()
4294
4638
  const result = await sandbox.runCommand({
4295
4639
  cmd: cmd[0]!,
4296
4640
  args: cmd.slice(1),
4297
4641
  cwd: VERCEL_WORKSPACE_PATH,
4298
- signal: this.operationSignal(),
4642
+ signal: bound,
4299
4643
  })
4300
4644
  if (!('stdout' in result) || !('stderr' in result) || result.exitCode === null)
4301
4645
  throw new Error('trusted preservation requires captured command output')
4302
4646
  return {
4303
4647
  exitCode: result.exitCode,
4304
- stdout: await result.stdout!(),
4305
- stderr: await result.stderr!(),
4648
+ stdout: await result.stdout!({ signal: bound }),
4649
+ stderr: await result.stderr!({ signal: bound }),
4306
4650
  }
4307
4651
  })
4308
4652
  } finally {
4309
4653
  try {
4310
4654
  await sandbox.update(
4311
4655
  { networkPolicy: (await this.normalNetworkPolicy(ref)).policy },
4312
- { signal: this.operationSignal() },
4656
+ { signal: this.recoveryMetadataSignal() },
4313
4657
  )
4314
4658
  } finally {
4315
- await sandbox.stop({ signal: this.operationSignal() })
4659
+ await this.recoveryStop(ref, sandbox)
4316
4660
  }
4317
4661
  }
4318
4662
  }
@@ -4329,6 +4673,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4329
4673
  localExpected?: string
4330
4674
  archives?: { ref: string; sha: string }[]
4331
4675
  retain?: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]['retain']
4676
+ }): Promise<void | import('../types').RewriteResult> {
4677
+ // Settling a requested publication is part of preserving the work.
4678
+ return this.deadlineAware('preserve', () => this.publishOnce(input))
4679
+ }
4680
+
4681
+ private async publishOnce(input: {
4682
+ ref: string
4683
+ sha: string
4684
+ branch: string
4685
+ expected?: string
4686
+ localExpected?: string
4687
+ archives?: { ref: string; sha: string }[]
4688
+ retain?: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]['retain']
4332
4689
  }): Promise<void | import('../types').RewriteResult> {
4333
4690
  if (this.active.has(input.ref) || this.uncertain.has(input.ref)) {
4334
4691
  throw new Error('publication is forbidden until sandbox execution teardown is confirmed')
@@ -4341,8 +4698,13 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4341
4698
  throw new Error('vercel-sandbox publication requires GITHUB_TOKEN or GH_TOKEN')
4342
4699
  }
4343
4700
  const { origin } = await this.normalNetworkPolicy(input.ref)
4344
- const sandbox =
4345
- this.sessions.get(input.ref) ?? (await this.facade.get(input.ref, this.operationSignal()))
4701
+ const found =
4702
+ this.sessions.get(input.ref) ??
4703
+ (await this.facade.get(input.ref, this.recoveryMetadataSignal()))
4704
+ if (found === null) throw new Error(`unknown sandbox ${input.ref}`)
4705
+ // One recovery budget covers the explicit resume and the guest git.
4706
+ const signal = this.recoveryWorkSignal()
4707
+ const sandbox = await this.resumeForRecovery(input.ref, found, signal)
4346
4708
  if (sandbox === null) throw new Error(`unknown sandbox ${input.ref}`)
4347
4709
  this.sessions.set(input.ref, sandbox)
4348
4710
  const publicationPolicy: NetworkPolicy = {
@@ -4394,7 +4756,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4394
4756
  try {
4395
4757
  await sandbox.update(
4396
4758
  { networkPolicy: this.billingPolicy(publicationPolicy, input.ref) },
4397
- { signal: this.operationSignal() },
4759
+ { signal: this.recoveryMetadataSignal() },
4398
4760
  )
4399
4761
  if (input.expected !== undefined) {
4400
4762
  const trustedExec: Exec = async (cmd) => {
@@ -4402,6 +4764,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4402
4764
  cmd: cmd[0]!,
4403
4765
  args: cmd.slice(1),
4404
4766
  cwd: VERCEL_WORKSPACE_PATH,
4767
+ signal,
4405
4768
  })
4406
4769
  if (result.exitCode === null)
4407
4770
  throw new Error('trusted rewrite command has no exit status')
@@ -4409,8 +4772,8 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4409
4772
  throw new Error('trusted rewrite requires command output capture')
4410
4773
  return {
4411
4774
  exitCode: result.exitCode,
4412
- stdout: await result.stdout!(),
4413
- stderr: await result.stderr!(),
4775
+ stdout: await result.stdout!({ signal }),
4776
+ stderr: await result.stderr!({ signal }),
4414
4777
  }
4415
4778
  }
4416
4779
  const capability = this.archiveTransport(trustedExec)
@@ -4437,6 +4800,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4437
4800
  cmd: 'git',
4438
4801
  args: ['push', '--no-verify', 'origin', `${input.sha}:refs/heads/${input.branch}`],
4439
4802
  cwd: VERCEL_WORKSPACE_PATH,
4803
+ signal,
4440
4804
  })
4441
4805
  } catch (error) {
4442
4806
  if (!(await this.isPublished(input))) throw error
@@ -4451,16 +4815,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4451
4815
  cmd: 'git',
4452
4816
  args: ['update-ref', `refs/heads/${input.branch}`, input.sha],
4453
4817
  cwd: VERCEL_WORKSPACE_PATH,
4818
+ signal,
4454
4819
  })
4455
- await sandbox.stop({ signal: this.operationSignal() })
4820
+ await sandbox.stop({ signal: this.recoveryMetadataSignal() })
4456
4821
  } finally {
4457
4822
  try {
4458
4823
  await sandbox.update(
4459
4824
  { networkPolicy: (await this.normalNetworkPolicy(input.ref)).policy },
4460
- { signal: this.operationSignal() },
4825
+ { signal: this.recoveryMetadataSignal() },
4461
4826
  )
4462
4827
  } finally {
4463
- await sandbox.stop({ signal: this.operationSignal() })
4828
+ await this.recoveryStop(input.ref, sandbox)
4464
4829
  }
4465
4830
  }
4466
4831
  }