@defrex/autobuild 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +110 -10
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +41 -7
  5. package/docs/configuration.md +41 -7
  6. package/docs/dispatcher-hosting.md +3 -0
  7. package/docs/operator-api.md +15 -5
  8. package/docs/plugin-authoring.md +1 -0
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +3 -1
  11. package/docs/restacking.md +41 -1
  12. package/docs/setup.md +15 -6
  13. package/docs/troubleshooting.md +51 -3
  14. package/docs/workspaces.md +4 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/accounts.ts +3 -0
  17. package/packages/core/src/cli/binary-direct.ts +14 -1
  18. package/packages/core/src/cli/binary.ts +10 -7
  19. package/packages/core/src/cli/dispatch.ts +610 -356
  20. package/packages/core/src/cli/secrets.ts +2 -0
  21. package/packages/core/src/config/schema.ts +15 -2
  22. package/packages/core/src/events/payloads.ts +8 -5
  23. package/packages/core/src/events/repository.ts +12 -6
  24. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e28c68e63cbd265f.json +108 -0
  25. package/packages/core/src/kernel/engine.ts +118 -0
  26. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  27. package/packages/core/src/kernel/reducer-revisions.ts +1 -0
  28. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  29. package/packages/core/src/ontology.ts +1 -0
  30. package/packages/core/src/operator/index.ts +10 -0
  31. package/packages/core/src/operator/merged-builds.ts +51 -0
  32. package/packages/core/src/operator/registry.ts +190 -101
  33. package/packages/core/src/operator/repo-argument.ts +43 -0
  34. package/packages/core/src/ports/tickets/grants.ts +2 -0
  35. package/packages/core/src/ports/tickets/remote.ts +2 -0
  36. package/packages/core/src/ports/types.ts +25 -4
  37. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  38. package/packages/core/src/ports/workspace/vercel-sandbox.ts +811 -169
  39. package/packages/core/src/processes/build-child.ts +15 -1
  40. package/packages/core/src/processes/build-runner.ts +349 -20
  41. package/packages/core/src/processes/dispatcher.ts +509 -104
  42. package/packages/core/src/processes/harvest-child.ts +21 -1
  43. package/packages/core/src/processes/harvest-runner.ts +82 -35
  44. package/packages/core/src/processes/invocation-budget.ts +6 -0
  45. package/packages/core/src/processes/launch-cut.ts +37 -0
  46. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  47. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  48. package/packages/core/src/processes/repo-view.ts +25 -4
  49. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  50. package/packages/core/src/store/adapter.ts +34 -5
  51. package/packages/core/src/store/build-feed.ts +148 -22
  52. package/packages/core/src/store/build-scope.ts +12 -3
  53. package/packages/core/src/store/caller-attribution.ts +170 -0
  54. package/packages/core/src/store/contract.ts +1038 -165
  55. package/packages/core/src/store/local/schema.ts +12 -1
  56. package/packages/core/src/store/local/store.ts +260 -25
  57. package/packages/core/src/store/memory.ts +156 -9
  58. package/packages/core/src/store/phase-session.ts +23 -3
  59. package/packages/core/src/store/reducer-value-shapes.json +5351 -5338
  60. package/packages/core/src/store/remote/client.ts +90 -11
  61. package/packages/core/src/store/remote/credentials.ts +2 -0
  62. package/packages/core/src/store/remote/index.ts +31 -5
  63. package/packages/core/src/store/remote/protocol.ts +45 -8
  64. package/packages/core/src/store/remote/released-clients.json +22 -0
  65. package/packages/core/src/store/remote/released-reducer-values/1.16.0.json +36358 -0
  66. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  67. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  68. package/packages/core/src/store/remote/released-value-policy.ts +7 -0
  69. package/packages/core/src/store/session-handle.ts +12 -3
  70. package/packages/core/src/store/types.ts +48 -3
  71. package/packages/core/src/testing/reduced-read-budget.ts +310 -12
  72. package/skills/guide/SKILL.md +58 -9
  73. package/skills/guide/references/operator-api.md +15 -5
  74. package/skills/guide/references/plugin-authoring.md +1 -0
  75. package/skills/guide/references/remote-store-protocol.md +13 -3
  76. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  77. package/skills/guide/references/restacking.md +41 -1
  78. package/skills/guide/references/setup.md +15 -6
  79. package/skills/operate/SKILL.md +31 -7
  80. package/templates/hosted-service/package.json +2 -2
@@ -26,13 +26,21 @@ import { displayName, tomlKey, type RuntimeReferenceGroup } from '../../config/r
26
26
  import {
27
27
  type VercelProvisioningStep,
28
28
  type VercelSandboxConfig,
29
+ VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS,
30
+ VERCEL_PROVISIONING_STEP_TIMEOUT_MAX_SECONDS,
29
31
  vercelSandboxConfigSchema,
30
32
  } from '../../config/schema'
31
33
  import { distributionStampFor, resolveDistributionArchive } from './distribution-archive'
34
+ import {
35
+ formatSandboxCommandFailure,
36
+ type SandboxCommandFailure,
37
+ type SandboxCommandOutcome,
38
+ } from './vercel-command-diagnostics'
32
39
  import type {
33
40
  ForgeRewrite,
34
41
  WorkspaceHandle,
35
42
  WorkspaceProvider,
43
+ WorkspaceProvisionProgress,
36
44
  WorkspaceProvisionResult,
37
45
  WorkspacePublication,
38
46
  WorkspaceReapOutcome,
@@ -198,6 +206,9 @@ export interface VercelSandboxHandle {
198
206
  detached?: true
199
207
  sudo?: boolean
200
208
  signal?: AbortSignal
209
+ /** Server-side kill bound (SDK `timeoutMs`): the sandbox SIGKILLs the
210
+ * command when it elapses, whether or not the request is still awaited. */
211
+ timeoutMs?: number
201
212
  }): Promise<VercelCommand | { exitCode: number }>
202
213
  writeFiles(
203
214
  files: { path: string; content: Uint8Array }[],
@@ -272,6 +283,83 @@ export const VERCEL_OBSERVE_WAIT_MS = 5_000
272
283
  * finishes. */
273
284
  export const VERCEL_PROVISION_ESTIMATE_MS = 150_000
274
285
 
286
+ // Provisioning command bounds (#1400). Each is passed to the SDK as the
287
+ // server-side kill (`timeoutMs`) and backed by a host timer `grace` later.
288
+ // Every bound stays under the ~15-minute request timeout Bun's native fetch
289
+ // puts on the SDK's `wait=true` command request (see `waitForCommandExit`).
290
+
291
+ /** Small provisioning commands: checkout, remote and config scrub, mkdir,
292
+ * checkpoints, the completion marker, relocation, and adoption probes. */
293
+ export const VERCEL_PROVISION_COMMAND_TIMEOUT_MS = 120_000
294
+ /** `npm install bun@<pin>` and its version check. */
295
+ export const VERCEL_BUN_INSTALL_TIMEOUT_MS = 300_000
296
+ /** Each distribution install command: extraction, production install, and
297
+ * the identity marker write and readback. */
298
+ export const VERCEL_DISTRIBUTION_INSTALL_TIMEOUT_MS = 300_000
299
+ /** The repository's lockfile dependency install. */
300
+ export const VERCEL_DEPENDENCY_INSTALL_TIMEOUT_MS = 600_000
301
+ /** Each runtime install and each runtime preflight. */
302
+ export const VERCEL_RUNTIME_BOOTSTRAP_TIMEOUT_MS = 600_000
303
+ /** How long past the server-side kill the host waits for the response. */
304
+ export const VERCEL_COMMAND_TIMEOUT_GRACE_MS = 15_000
305
+ /** Bound on every command output read: a read opens its own log stream that
306
+ * inherits neither the command's signal nor its server-side timeout. */
307
+ export const VERCEL_COMMAND_OUTPUT_READ_MS = 30_000
308
+
309
+ /** Per-stage provisioning command bounds in milliseconds. A composition and
310
+ * test seam, not configuration: a declared step's `timeoutSeconds` beats
311
+ * `step`, which beats the default. */
312
+ export interface VercelProvisioningTimeouts {
313
+ command: number
314
+ bun: number
315
+ step: number
316
+ distribution: number
317
+ dependencies: number
318
+ runtime: number
319
+ grace: number
320
+ outputRead: number
321
+ }
322
+
323
+ function resolveProvisioningTimeouts(
324
+ overrides: Partial<VercelProvisioningTimeouts> = {},
325
+ ): VercelProvisioningTimeouts {
326
+ return {
327
+ command: VERCEL_PROVISION_COMMAND_TIMEOUT_MS,
328
+ bun: VERCEL_BUN_INSTALL_TIMEOUT_MS,
329
+ step: VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS * 1000,
330
+ distribution: VERCEL_DISTRIBUTION_INSTALL_TIMEOUT_MS,
331
+ dependencies: VERCEL_DEPENDENCY_INSTALL_TIMEOUT_MS,
332
+ runtime: VERCEL_RUNTIME_BOOTSTRAP_TIMEOUT_MS,
333
+ grace: VERCEL_COMMAND_TIMEOUT_GRACE_MS,
334
+ outputRead: VERCEL_COMMAND_OUTPUT_READ_MS,
335
+ ...overrides,
336
+ }
337
+ }
338
+
339
+ /** How one guest command is bounded and labelled for diagnostics. */
340
+ interface CommandBound {
341
+ /** Server-side kill and timeout classification; absent leaves the command
342
+ * bounded only by its signal. */
343
+ timeoutMs?: number
344
+ graceMs?: number
345
+ outputReadMs?: number
346
+ /** Provisioning stage named in a failure. */
347
+ stage?: string
348
+ }
349
+
350
+ function commandBound(
351
+ timeouts: VercelProvisioningTimeouts,
352
+ timeoutMs: number,
353
+ stage?: string,
354
+ ): CommandBound {
355
+ return {
356
+ timeoutMs,
357
+ graceMs: timeouts.grace,
358
+ outputReadMs: timeouts.outputRead,
359
+ ...(stage === undefined ? {} : { stage }),
360
+ }
361
+ }
362
+
275
363
  /** Default ceiling for one stopped-sandbox recovery: an explicit cold resume
276
364
  * plus the guest git work that follows it (`recoveryTimeoutMs`). A bounded
277
365
  * invocation admits a recovery on `VERCEL_RECOVERY_ESTIMATE_MS`, not on this
@@ -692,6 +780,7 @@ async function relocateCheckout(
692
780
  sandbox: VercelSandboxHandle,
693
781
  directory: string,
694
782
  signal?: AbortSignal,
783
+ bound?: CommandBound,
695
784
  ): Promise<void> {
696
785
  const sourcePath = sourceCheckoutPath(sandbox, directory)
697
786
  try {
@@ -705,6 +794,7 @@ async function relocateCheckout(
705
794
  VERCEL_WORKSPACE_PATH,
706
795
  ],
707
796
  ...(signal === undefined ? {} : { signal }),
797
+ ...bound,
708
798
  })
709
799
  } catch (error) {
710
800
  throw new Error(
@@ -740,47 +830,229 @@ async function guestCloneCheckout(
740
830
  })
741
831
  }
742
832
 
833
+ type SandboxCommandParams = {
834
+ cmd: string
835
+ args?: string[]
836
+ cwd?: string
837
+ env?: Record<string, string>
838
+ sudo?: boolean
839
+ /** The caller's cancellation: an abort rethrows promptly, unformatted, and
840
+ * reads no output. */
841
+ signal?: AbortSignal
842
+ /** Values redacted from any failure text, besides every `env` value. */
843
+ secrets?: readonly string[]
844
+ /** Read and return stdout on success. */
845
+ readStdout?: boolean
846
+ /** Exit codes that count as success; default only 0. A timeout always
847
+ * fails. */
848
+ accept?: (exitCode: number) => boolean
849
+ } & CommandBound
850
+
851
+ function abortReason(signal: AbortSignal): unknown {
852
+ return signal.reason ?? new Error('aborted')
853
+ }
854
+
855
+ function anySignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
856
+ const present = signals.filter((signal): signal is AbortSignal => signal !== undefined)
857
+ if (present.length === 0) return undefined
858
+ return present.length === 1 ? present[0] : AbortSignal.any(present)
859
+ }
860
+
861
+ /** One output stream, bounded by `signal` even when the reader ignores it. */
862
+ function boundedRead(
863
+ read: ((opts?: { signal?: AbortSignal }) => Promise<string>) | undefined,
864
+ signal: AbortSignal,
865
+ ): Promise<string> {
866
+ if (read === undefined) return Promise.resolve('')
867
+ if (signal.aborted) return Promise.reject(abortReason(signal))
868
+ return new Promise<string>((resolve, reject) => {
869
+ const onAbort = () => reject(abortReason(signal))
870
+ signal.addEventListener('abort', onAbort, { once: true })
871
+ read({ signal }).then(
872
+ (output) => {
873
+ signal.removeEventListener('abort', onAbort)
874
+ resolve(output)
875
+ },
876
+ (error: unknown) => {
877
+ signal.removeEventListener('abort', onAbort)
878
+ reject(error)
879
+ },
880
+ )
881
+ })
882
+ }
883
+
884
+ /** The one guest-command runner behind `commandOrThrow` and
885
+ * `readableCommand`. Failures (non-zero exit, missing status, timeout, request
886
+ * failure) throw a diagnostic naming the redacted argv, cwd, stage, and
887
+ * bounded stderr/stdout tails (#1399). With `timeoutMs`, the sandbox kills the
888
+ * command and a host backstop bounds the response (#1400): a result arriving
889
+ * at or past `timeoutMs` is a timeout whatever its exit code, because the SDK
890
+ * reads a killed command's missing exit code as 0. */
891
+ async function runSandboxCommand(
892
+ sandbox: VercelSandboxHandle,
893
+ params: SandboxCommandParams,
894
+ ): Promise<{ stdout: string; exitCode: number }> {
895
+ const {
896
+ signal,
897
+ secrets,
898
+ readStdout,
899
+ accept,
900
+ timeoutMs,
901
+ graceMs,
902
+ outputReadMs,
903
+ stage,
904
+ ...command
905
+ } = params
906
+ if (signal?.aborted) throw abortReason(signal)
907
+ const redact = [...(secrets ?? []), ...Object.values(command.env ?? {})]
908
+ const readMs = outputReadMs ?? VERCEL_COMMAND_OUTPUT_READ_MS
909
+ const fail = (
910
+ outcome: SandboxCommandOutcome,
911
+ output: Pick<SandboxCommandFailure, 'stdout' | 'stderr' | 'outputUnavailable'>,
912
+ cause?: unknown,
913
+ ): Error =>
914
+ new Error(
915
+ formatSandboxCommandFailure({
916
+ cmd: command.cmd,
917
+ ...(command.args === undefined ? {} : { args: command.args }),
918
+ ...(command.cwd === undefined ? {} : { cwd: command.cwd }),
919
+ ...(stage === undefined ? {} : { stage }),
920
+ secrets: redact,
921
+ outcome,
922
+ ...output,
923
+ }),
924
+ cause === undefined ? undefined : { cause },
925
+ )
926
+ const hostTimer =
927
+ timeoutMs === undefined
928
+ ? undefined
929
+ : AbortSignal.timeout(timeoutMs + (graceMs ?? VERCEL_COMMAND_TIMEOUT_GRACE_MS))
930
+ const combined = anySignal([signal, hostTimer])
931
+ const started = Date.now()
932
+ let result: VercelCommand | { exitCode: number }
933
+ try {
934
+ result = await sandbox.runCommand({
935
+ ...command,
936
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
937
+ ...(combined === undefined ? {} : { signal: combined }),
938
+ })
939
+ } catch (error) {
940
+ if (signal?.aborted) throw error
941
+ if (timeoutMs !== undefined && hostTimer?.aborted)
942
+ throw fail(
943
+ { kind: 'timeout', timeoutMs, elapsedMs: Date.now() - started },
944
+ { outputUnavailable: 'the command did not report back before the host backstop' },
945
+ error,
946
+ )
947
+ // Unbounded callers keep the provider's own error for classification.
948
+ if (timeoutMs === undefined) throw error
949
+ throw fail(
950
+ { kind: 'error', message: error instanceof Error ? error.message : String(error) },
951
+ { outputUnavailable: 'the command request failed' },
952
+ error,
953
+ )
954
+ }
955
+ const elapsedMs = Date.now() - started
956
+ const outputs = result as Partial<Pick<VercelCommand, 'stdout' | 'stderr'>>
957
+ const exitCode = result.exitCode as number | null | undefined
958
+ const timedOut = timeoutMs !== undefined && elapsedMs >= timeoutMs
959
+ const ok =
960
+ !timedOut &&
961
+ exitCode !== null &&
962
+ exitCode !== undefined &&
963
+ (accept ?? ((code) => code === 0))(exitCode)
964
+ if (ok) {
965
+ if (readStdout !== true) return { stdout: '', exitCode }
966
+ const outputSignal = anySignal([signal, AbortSignal.timeout(readMs)])!
967
+ try {
968
+ return { stdout: await boundedRead(outputs.stdout?.bind(result), outputSignal), exitCode }
969
+ } catch (error) {
970
+ if (signal?.aborted) throw error
971
+ if (!outputSignal.aborted) throw error
972
+ throw fail(
973
+ {
974
+ kind: 'error',
975
+ message: `command exited 0 but its output could not be read within ${Math.round(readMs / 1000)}s`,
976
+ },
977
+ { outputUnavailable: 'output read deadline' },
978
+ error,
979
+ )
980
+ }
981
+ }
982
+ const outputSignal = anySignal([signal, AbortSignal.timeout(readMs)])!
983
+ let output: Pick<SandboxCommandFailure, 'stdout' | 'stderr' | 'outputUnavailable'>
984
+ try {
985
+ const [stderr, stdout] = await Promise.all([
986
+ boundedRead(outputs.stderr?.bind(result), outputSignal),
987
+ boundedRead(outputs.stdout?.bind(result), outputSignal),
988
+ ])
989
+ output = { stderr, stdout }
990
+ } catch (error) {
991
+ if (signal?.aborted) throw signal.reason ?? error
992
+ output = {
993
+ outputUnavailable: outputSignal.aborted
994
+ ? `output could not be read within ${Math.round(readMs / 1000)}s`
995
+ : error instanceof Error
996
+ ? error.message
997
+ : String(error),
998
+ }
999
+ }
1000
+ throw fail(
1001
+ timedOut
1002
+ ? { kind: 'timeout', timeoutMs: timeoutMs!, elapsedMs }
1003
+ : exitCode === null || exitCode === undefined
1004
+ ? { kind: 'no-status' }
1005
+ : { kind: 'exit', code: exitCode },
1006
+ output,
1007
+ )
1008
+ }
1009
+
743
1010
  async function commandOrThrow(
744
1011
  sandbox: VercelSandboxHandle,
745
- params: {
746
- cmd: string
747
- args?: string[]
748
- cwd?: string
749
- env?: Record<string, string>
750
- sudo?: boolean
751
- signal?: AbortSignal
752
- },
1012
+ params: Omit<SandboxCommandParams, 'readStdout'>,
753
1013
  ): Promise<void> {
754
- const result = await sandbox.runCommand(params)
755
- if (result.exitCode === null || result.exitCode === undefined) {
756
- throw new Error(`sandbox command ${params.cmd} did not return an exit status`)
757
- }
758
- if (result.exitCode !== 0)
759
- throw new Error(`sandbox command ${params.cmd} exited ${result.exitCode}`)
1014
+ await runSandboxCommand(sandbox, params)
760
1015
  }
761
1016
 
1017
+ /** The cause's message rides on its own line: `WorkspaceCleanupRequired` and
1018
+ * `dispatch.failed` copy only the visible message, never `cause`. */
762
1019
  function bunProvisioningError(image: string, operation: string, error: unknown): Error {
763
1020
  return new Error(
764
- `vercel-sandbox could not ${operation} Bun ${VERCEL_BUN_VERSION} on image ${JSON.stringify(image)}; Autobuild supports the universal managed image with working Node/npm, shell, filesystem, and package-registry access`,
1021
+ `vercel-sandbox could not ${operation} Bun ${VERCEL_BUN_VERSION} on image ${JSON.stringify(image)}; Autobuild supports the universal managed image with working Node/npm, shell, filesystem, and package-registry access\n${
1022
+ error instanceof Error ? error.message : String(error)
1023
+ }`,
765
1024
  { cause: error },
766
1025
  )
767
1026
  }
768
1027
 
769
1028
  /** The trimmed `bun --version` output of the provisioned executable, or
770
- * undefined when it cannot run or prints nothing. */
1029
+ * undefined when it prints nothing. A command that fails or times out
1030
+ * rejects with the runner's diagnostics. */
1031
+ async function bunVersion(
1032
+ sandbox: VercelSandboxHandle,
1033
+ signal?: AbortSignal,
1034
+ bound?: CommandBound,
1035
+ ): Promise<string | undefined> {
1036
+ const version = (
1037
+ await readableCommand(sandbox, {
1038
+ cmd: VERCEL_BUN_EXECUTABLE,
1039
+ args: ['--version'],
1040
+ ...(signal === undefined ? {} : { signal }),
1041
+ ...bound,
1042
+ })
1043
+ ).trim()
1044
+ return version === '' ? undefined : version
1045
+ }
1046
+
1047
+ /** {@link bunVersion} for an optional preflight: undefined when the
1048
+ * executable cannot run, so the caller reinstalls at the pin. */
771
1049
  async function reportedBunVersion(
772
1050
  sandbox: VercelSandboxHandle,
773
1051
  signal?: AbortSignal,
1052
+ bound?: CommandBound,
774
1053
  ): Promise<string | undefined> {
775
1054
  try {
776
- const version = (
777
- await readableCommand(sandbox, {
778
- cmd: VERCEL_BUN_EXECUTABLE,
779
- args: ['--version'],
780
- ...(signal === undefined ? {} : { signal }),
781
- })
782
- ).trim()
783
- return version === '' ? undefined : version
1055
+ return await bunVersion(sandbox, signal, bound)
784
1056
  } catch (error) {
785
1057
  if (signal?.aborted) throw error
786
1058
  return undefined
@@ -795,17 +1067,28 @@ async function provisionBun(
795
1067
  sandbox: VercelSandboxHandle,
796
1068
  image: string,
797
1069
  signal?: AbortSignal,
1070
+ bound?: CommandBound,
798
1071
  ): Promise<void> {
799
1072
  try {
800
1073
  await commandOrThrow(sandbox, {
801
1074
  cmd: 'npm',
802
1075
  args: ['install', '--prefix', VERCEL_BUN_PREFIX, '--no-save', `bun@${VERCEL_BUN_VERSION}`],
803
1076
  ...(signal === undefined ? {} : { signal }),
1077
+ ...bound,
804
1078
  })
805
1079
  } catch (error) {
1080
+ if (signal?.aborted) throw error
806
1081
  throw bunProvisioningError(image, 'provision', error)
807
1082
  }
808
- const reported = await reportedBunVersion(sandbox, signal)
1083
+ // Verification after an install is mandatory: a failing or hung version
1084
+ // check keeps its command diagnostics instead of reading as "no version".
1085
+ let reported: string | undefined
1086
+ try {
1087
+ reported = await bunVersion(sandbox, signal, bound)
1088
+ } catch (error) {
1089
+ if (signal?.aborted) throw error
1090
+ throw bunProvisioningError(image, 'verify provisioned', error)
1091
+ }
809
1092
  if (reported !== VERCEL_BUN_VERSION) {
810
1093
  throw bunProvisioningError(
811
1094
  image,
@@ -849,6 +1132,13 @@ async function bootstrapRuntimes(
849
1132
  references: readonly RuntimeReferenceGroup[],
850
1133
  install: boolean,
851
1134
  signal?: AbortSignal,
1135
+ opts: {
1136
+ /** Bound for each install and preflight; its stage label is replaced by
1137
+ * `runtime bootstrap <runtime> <install|preflight>`. */
1138
+ bound?: CommandBound
1139
+ /** Reports `<runtime> install` / `<runtime> preflight` before each. */
1140
+ onStage?: (step: string) => void
1141
+ } = {},
852
1142
  ): Promise<void> {
853
1143
  for (const group of [...references].sort((left, right) =>
854
1144
  left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
@@ -860,6 +1150,8 @@ async function bootstrapRuntimes(
860
1150
  )
861
1151
  }
862
1152
  for (const stage of install ? (['install', 'preflight'] as const) : (['preflight'] as const)) {
1153
+ const step = `${group.runtime} ${stage}`
1154
+ opts.onStage?.(step)
863
1155
  try {
864
1156
  await readableCommand(sandbox, {
865
1157
  cmd: 'sh',
@@ -867,8 +1159,12 @@ async function bootstrapRuntimes(
867
1159
  cwd: VERCEL_WORKSPACE_PATH,
868
1160
  env,
869
1161
  ...(signal === undefined ? {} : { signal }),
1162
+ ...(opts.bound === undefined
1163
+ ? {}
1164
+ : { ...opts.bound, stage: `runtime bootstrap ${step}` }),
870
1165
  })
871
1166
  } catch (error) {
1167
+ if (signal?.aborted) throw error
872
1168
  throw new Error(
873
1169
  `runtime ${displayName(group.runtime)} ${stage} failed (selected by ${group.references.join(', ')}); fix workspace.config.runtimeProvisioning.${group.runtime}.${stage}: ${redactRuntimeError(error, env)}`,
874
1170
  )
@@ -881,33 +1177,52 @@ async function runSystemProvisioning(
881
1177
  sandbox: VercelSandboxHandle,
882
1178
  steps: readonly VercelProvisioningStep[],
883
1179
  signal?: AbortSignal,
1180
+ bound?: CommandBound,
884
1181
  ): Promise<string[]> {
885
1182
  const completed: string[] = []
886
1183
  for (const step of steps) {
887
- const result = (await sandbox.runCommand({
1184
+ await runSystemProvisioningStep(sandbox, step, signal, bound)
1185
+ completed.push(step.name)
1186
+ }
1187
+ return completed
1188
+ }
1189
+
1190
+ /** Run one declared system provisioning step under its own timeout:
1191
+ * `timeoutSeconds` when declared, else `bound.timeoutMs`, else the default. */
1192
+ async function runSystemProvisioningStep(
1193
+ sandbox: VercelSandboxHandle,
1194
+ step: VercelProvisioningStep,
1195
+ signal?: AbortSignal,
1196
+ bound?: CommandBound,
1197
+ ): Promise<void> {
1198
+ const timeoutMs =
1199
+ step.timeoutSeconds !== undefined
1200
+ ? step.timeoutSeconds * 1000
1201
+ : (bound?.timeoutMs ?? VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS * 1000)
1202
+ try {
1203
+ await commandOrThrow(sandbox, {
888
1204
  cmd: 'sh',
889
1205
  args: ['-c', step.command],
890
1206
  cwd: VERCEL_WORKSPACE_PATH,
891
1207
  sudo: true,
892
1208
  ...(signal === undefined ? {} : { signal }),
893
- })) as VercelCommand
894
- if (result.exitCode !== 0) {
895
- const [stdout, stderr] = await Promise.all([
896
- result.stdout?.() ?? Promise.resolve(''),
897
- result.stderr?.() ?? Promise.resolve(''),
898
- ])
899
- throw new Error(
900
- `system provisioning step ${JSON.stringify(step.name)} failed\n` +
901
- `command: ${step.command}\n` +
902
- `exit status: ${result.exitCode ?? '(missing)'}\n` +
903
- `stdout:\n${stdout.trim() === '' ? '(empty)' : stdout}\n` +
904
- `stderr:\n${stderr.trim() === '' ? '(empty)' : stderr}\n` +
905
- 'remediation: fix [workspace.config].provisioning and rerun ab init --validate',
906
- )
907
- }
908
- completed.push(step.name)
1209
+ ...bound,
1210
+ timeoutMs,
1211
+ stage: `system provisioning step ${step.name}`,
1212
+ })
1213
+ } catch (error) {
1214
+ if (signal?.aborted) throw error
1215
+ const detail = error instanceof Error ? error.message : String(error)
1216
+ const timedOut = /^sandbox command \S+ exceeded its /.test(detail)
1217
+ throw new Error(
1218
+ `system provisioning step ${JSON.stringify(step.name)} failed\n${detail}\n` +
1219
+ 'remediation: fix [workspace.config].provisioning and rerun ab init --validate' +
1220
+ (timedOut
1221
+ ? `; if the step hangs on an upstream mirror, check that mirror or raise the step's timeoutSeconds (at most ${VERCEL_PROVISIONING_STEP_TIMEOUT_MAX_SECONDS})`
1222
+ : ''),
1223
+ { cause: error },
1224
+ )
909
1225
  }
910
- return completed
911
1226
  }
912
1227
 
913
1228
  /** Bring a reused sandbox's Bun to exactly the pin before any guest command
@@ -919,12 +1234,14 @@ async function ensurePinnedBun(
919
1234
  sandbox: VercelSandboxHandle,
920
1235
  image: string,
921
1236
  signal?: AbortSignal,
1237
+ bound?: CommandBound,
922
1238
  ): Promise<void> {
923
- const reported = await reportedBunVersion(sandbox, signal)
1239
+ const reported = await reportedBunVersion(sandbox, signal, bound)
924
1240
  if (reported === VERCEL_BUN_VERSION) return
925
1241
  try {
926
- await provisionBun(sandbox, image, signal)
1242
+ await provisionBun(sandbox, image, signal, bound)
927
1243
  } catch (error) {
1244
+ if (signal?.aborted) throw error
928
1245
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error
929
1246
  throw new Error(
930
1247
  `vercel-sandbox Bun preflight on image ${JSON.stringify(image)} found ${describeBunVersion(reported)} (pin ${VERCEL_BUN_VERSION}) and could not bring it to the pin: ${
@@ -965,28 +1282,9 @@ export interface VercelReadinessResult {
965
1282
 
966
1283
  async function readableCommand(
967
1284
  sandbox: VercelSandboxHandle,
968
- params: {
969
- cmd: string
970
- args?: string[]
971
- cwd?: string
972
- env?: Record<string, string>
973
- sudo?: boolean
974
- signal?: AbortSignal
975
- },
1285
+ params: Omit<SandboxCommandParams, 'readStdout'>,
976
1286
  ): Promise<string> {
977
- const result = (await sandbox.runCommand(params)) as VercelCommand
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)
981
- if (result.exitCode === null || result.exitCode === undefined) {
982
- throw new Error(`sandbox command ${params.cmd} did not return an exit status`)
983
- }
984
- if (result.exitCode !== 0) {
985
- throw new Error(
986
- `sandbox command ${params.cmd} exited ${result.exitCode}: ${stderr.trim() || stdout.trim() || '(no output)'}`,
987
- )
988
- }
989
- return stdout
1287
+ return (await runSandboxCommand(sandbox, { ...params, readStdout: true })).stdout
990
1288
  }
991
1289
 
992
1290
  /** The commit the guest checkout is actually on: HEAD and the build branch
@@ -1016,6 +1314,120 @@ async function checkedOutBranchHead(
1016
1314
  return head
1017
1315
  }
1018
1316
 
1317
+ /** The commit the guest clone's HEAD resolves to, whether detached at the
1318
+ * cloned revision or already on the build branch. */
1319
+ async function guestHeadCommit(
1320
+ sandbox: VercelSandboxHandle,
1321
+ signal?: AbortSignal,
1322
+ ): Promise<string> {
1323
+ const stdout = await readableCommand(sandbox, {
1324
+ cmd: 'git',
1325
+ args: ['rev-parse', '--verify', 'HEAD^{commit}'],
1326
+ cwd: VERCEL_WORKSPACE_PATH,
1327
+ ...(signal ? { signal } : {}),
1328
+ })
1329
+ const head = stdout.trim()
1330
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head))
1331
+ throw new Error(`unreadable clone head: ${JSON.stringify(head)}`)
1332
+ return head
1333
+ }
1334
+
1335
+ /** Per-stage provisioning checkpoints: one file per completed stage holding a
1336
+ * sha256 fingerprint of that stage's inputs chained onto the previous stage's
1337
+ * fingerprint. Consulted only when finishing a teardown-abandoned attempt, so
1338
+ * a resumed provision skips stages already completed with unchanged inputs.
1339
+ * Fingerprints cover non-secret inputs only; no env value or token is ever
1340
+ * written here. */
1341
+ export const VERCEL_PROVISION_CHECKPOINT_DIR = `${VERCEL_AUTOBUILD_PATH}/.provision-checkpoints`
1342
+
1343
+ const PROVISION_CHECKPOINT_KEY = /^\d{2}-[a-z]+(?:-\d+)?$/
1344
+ const PROVISION_CHECKPOINT_FINGERPRINT = /^[0-9a-f]{64}$/
1345
+
1346
+ function provisionFingerprint(previous: string, stage: string, inputs: unknown): string {
1347
+ return createHash('sha256')
1348
+ .update(JSON.stringify([previous, stage, inputs]))
1349
+ .digest('hex')
1350
+ }
1351
+
1352
+ async function writeProvisionCheckpoint(
1353
+ sandbox: VercelSandboxHandle,
1354
+ key: string,
1355
+ fingerprint: string,
1356
+ signal?: AbortSignal,
1357
+ bound?: CommandBound,
1358
+ ): Promise<void> {
1359
+ await commandOrThrow(sandbox, {
1360
+ cmd: 'sh',
1361
+ args: [
1362
+ '-c',
1363
+ 'mkdir -p "$1" && printf %s "$3" > "$1/$2"',
1364
+ 'provision-checkpoint',
1365
+ VERCEL_PROVISION_CHECKPOINT_DIR,
1366
+ key,
1367
+ fingerprint,
1368
+ ],
1369
+ ...(signal === undefined ? {} : { signal }),
1370
+ ...bound,
1371
+ })
1372
+ }
1373
+
1374
+ /** Every well-formed checkpoint in the guest; malformed entries are absent. */
1375
+ async function readProvisionCheckpoints(
1376
+ sandbox: VercelSandboxHandle,
1377
+ signal?: AbortSignal,
1378
+ bound?: CommandBound,
1379
+ ): Promise<Map<string, string>> {
1380
+ const stdout = await readableCommand(sandbox, {
1381
+ cmd: 'sh',
1382
+ args: [
1383
+ '-c',
1384
+ '[ -d "$1" ] || exit 0; for f in "$1"/*; do [ -f "$f" ] || continue; printf "%s %s\\n" "$(basename "$f")" "$(cat "$f")"; done',
1385
+ 'provision-checkpoints',
1386
+ VERCEL_PROVISION_CHECKPOINT_DIR,
1387
+ ],
1388
+ ...(signal === undefined ? {} : { signal }),
1389
+ ...bound,
1390
+ })
1391
+ const checkpoints = new Map<string, string>()
1392
+ for (const line of stdout.split('\n')) {
1393
+ const [key, fingerprint, ...rest] = line.trim().split(' ')
1394
+ if (
1395
+ rest.length === 0 &&
1396
+ key !== undefined &&
1397
+ fingerprint !== undefined &&
1398
+ PROVISION_CHECKPOINT_KEY.test(key) &&
1399
+ PROVISION_CHECKPOINT_FINGERPRINT.test(fingerprint)
1400
+ )
1401
+ checkpoints.set(key, fingerprint)
1402
+ }
1403
+ return checkpoints
1404
+ }
1405
+
1406
+ async function clearProvisionCheckpoints(
1407
+ sandbox: VercelSandboxHandle,
1408
+ keys: readonly string[],
1409
+ signal?: AbortSignal,
1410
+ bound?: CommandBound,
1411
+ ): Promise<void> {
1412
+ if (keys.length === 0) return
1413
+ for (const key of keys) {
1414
+ if (!PROVISION_CHECKPOINT_KEY.test(key))
1415
+ throw new Error(`invalid provisioning checkpoint key ${JSON.stringify(key)}`)
1416
+ }
1417
+ await commandOrThrow(sandbox, {
1418
+ cmd: 'sh',
1419
+ args: [
1420
+ '-c',
1421
+ 'cd "$1" || exit 0; shift; rm -f -- "$@"',
1422
+ 'provision-checkpoints-clear',
1423
+ VERCEL_PROVISION_CHECKPOINT_DIR,
1424
+ ...keys,
1425
+ ],
1426
+ ...(signal === undefined ? {} : { signal }),
1427
+ ...bound,
1428
+ })
1429
+ }
1430
+
1019
1431
  /** Create, inspect, and always delete one remote readiness environment. Unlike
1020
1432
  * build provisioning this never uses a stable name, branch, or marker. */
1021
1433
  export async function validateVercelSandbox(
@@ -1262,33 +1674,45 @@ async function installDistribution(
1262
1674
  archive: Uint8Array,
1263
1675
  identity: string,
1264
1676
  signal?: AbortSignal,
1677
+ opts: {
1678
+ /** Bound for each guest command. */
1679
+ bound?: CommandBound
1680
+ /** The archive upload's signal; defaults to `signal`. */
1681
+ writeSignal?: AbortSignal
1682
+ } = {},
1265
1683
  ): Promise<void> {
1266
- await sandbox.writeFiles([{ path: '/tmp/autobuild.tgz', content: archive }], {
1684
+ const writeSignal = opts.writeSignal ?? signal
1685
+ const guest = {
1267
1686
  ...(signal === undefined ? {} : { signal }),
1687
+ ...opts.bound,
1688
+ }
1689
+ await sandbox.writeFiles([{ path: '/tmp/autobuild.tgz', content: archive }], {
1690
+ ...(writeSignal === undefined ? {} : { signal: writeSignal }),
1268
1691
  })
1269
1692
  await commandOrThrow(sandbox, {
1270
1693
  cmd: 'mkdir',
1271
1694
  args: ['-p', VERCEL_AUTOBUILD_PATH],
1272
- ...(signal === undefined ? {} : { signal }),
1695
+ ...guest,
1273
1696
  })
1274
1697
  await commandOrThrow(sandbox, {
1275
1698
  cmd: 'tar',
1276
1699
  args: ['-xzf', '/tmp/autobuild.tgz', '--strip-components=1', '-C', VERCEL_AUTOBUILD_PATH],
1277
- ...(signal === undefined ? {} : { signal }),
1700
+ ...guest,
1278
1701
  })
1279
1702
  await commandOrThrow(sandbox, {
1280
1703
  cmd: VERCEL_BUN_EXECUTABLE,
1281
1704
  args: ['install', '--production', '--ignore-scripts'],
1282
1705
  cwd: VERCEL_AUTOBUILD_PATH,
1283
- ...(signal === undefined ? {} : { signal }),
1706
+ ...guest,
1284
1707
  })
1285
- await writeDistributionVersionMarker(sandbox, identity, signal)
1708
+ await writeDistributionVersionMarker(sandbox, identity, signal, opts.bound)
1286
1709
  }
1287
1710
 
1288
1711
  async function writeDistributionVersionMarker(
1289
1712
  sandbox: VercelSandboxHandle,
1290
1713
  identity: string,
1291
1714
  signal?: AbortSignal,
1715
+ bound?: CommandBound,
1292
1716
  ): Promise<void> {
1293
1717
  await commandOrThrow(sandbox, {
1294
1718
  cmd: 'sh',
@@ -1300,11 +1724,13 @@ async function writeDistributionVersionMarker(
1300
1724
  VERCEL_DISTRIBUTION_VERSION_MARKER,
1301
1725
  ],
1302
1726
  ...(signal === undefined ? {} : { signal }),
1727
+ ...bound,
1303
1728
  })
1304
1729
  const readback = await readableCommand(sandbox, {
1305
1730
  cmd: 'cat',
1306
1731
  args: [VERCEL_DISTRIBUTION_VERSION_MARKER],
1307
1732
  ...(signal === undefined ? {} : { signal }),
1733
+ ...bound,
1308
1734
  })
1309
1735
  if (readback.trim() !== identity) {
1310
1736
  throw new Error(
@@ -1316,10 +1742,12 @@ async function writeDistributionVersionMarker(
1316
1742
 
1317
1743
  /** The installed distribution's identity stamp, or `undefined` when the marker
1318
1744
  * is unreadable — which includes every guest provisioned before the marker
1319
- * existed and is treated as a mismatch by the reuse and restart paths. */
1745
+ * existed and is treated as a mismatch by the reuse and restart paths. An
1746
+ * abort of `cancel` is never read as an unreadable marker: it rethrows. */
1320
1747
  async function readDistributionVersionMarker(
1321
1748
  sandbox: VercelSandboxHandle,
1322
1749
  signal?: AbortSignal,
1750
+ cancel?: AbortSignal,
1323
1751
  ): Promise<string | undefined> {
1324
1752
  try {
1325
1753
  const content = await readableCommand(sandbox, {
@@ -1329,7 +1757,8 @@ async function readDistributionVersionMarker(
1329
1757
  })
1330
1758
  const trimmed = content.trim()
1331
1759
  return trimmed === '' ? undefined : trimmed
1332
- } catch {
1760
+ } catch (error) {
1761
+ if (cancel?.aborted) throw error
1333
1762
  return undefined
1334
1763
  }
1335
1764
  }
@@ -1584,6 +2013,10 @@ export interface VercelSandboxProviderOptions {
1584
2013
  /** Test seam: the expected wall time of one `provision`. Defaults to
1585
2014
  * `VERCEL_PROVISION_ESTIMATE_MS`. */
1586
2015
  provisionEstimateMs?: number
2016
+ /** Composition and test seam, never configuration: per-stage provisioning
2017
+ * command bounds in milliseconds over the `VERCEL_*_TIMEOUT_MS` defaults. A
2018
+ * declared step's `timeoutSeconds` still beats `step`. */
2019
+ provisioningTimeouts?: Partial<VercelProvisioningTimeouts>
1587
2020
  /** Test seam: the expected wall time of one stopped-sandbox recovery, used
1588
2021
  * to admit it in a bounded invocation. Defaults to
1589
2022
  * `VERCEL_RECOVERY_ESTIMATE_MS`; `recoveryTimeoutMs` stays the ceiling. */
@@ -1729,20 +2162,25 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1729
2162
  release: (input) => this.sandboxRelease(input),
1730
2163
  }
1731
2164
  this.recovery = {
1732
- fence: async (handle) => {
2165
+ fence: async (handle, fenceOpts) => {
1733
2166
  if (handle.provider !== this.name) throw new Error('workspace fence provider mismatch')
2167
+ // In teardown the work deadline has passed: the cleanup scope bounds
2168
+ // the transport, and each call keeps only its own cap.
2169
+ const signal = () =>
2170
+ fenceOpts?.teardown === true
2171
+ ? AbortSignal.timeout(this.operationTimeoutMs())
2172
+ : this.recoveryMetadataSignal()
1734
2173
  try {
1735
2174
  return await this.deadlineAware('fence', async () => {
1736
2175
  // Never trust the in-process handle after restart or another resume.
1737
- const sandbox = await this.facade.get(handle.ref, this.recoveryMetadataSignal())
2176
+ const sandbox = await this.facade.get(handle.ref, signal())
1738
2177
  if (sandbox === null) {
1739
2178
  this.forget(handle.ref)
1740
2179
  return { outcome: 'absent' as const }
1741
2180
  }
1742
2181
  // A session the provider already reports stopped needs no second
1743
2182
  // stop; asking would only spend the acknowledgement budget.
1744
- if (sandbox.sessionStatus !== 'stopped')
1745
- await sandbox.stop({ signal: this.recoveryMetadataSignal() })
2183
+ if (sandbox.sessionStatus !== 'stopped') await sandbox.stop({ signal: signal() })
1746
2184
  this.active.delete(handle.ref)
1747
2185
  this.uncertain.delete(handle.ref)
1748
2186
  this.sessions.set(handle.ref, sandbox)
@@ -1883,7 +2321,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1883
2321
  restorationArchives?: 'local' | 'remote'
1884
2322
  restoreStored?: Parameters<WorkspaceProvider['provision']>[0]['restoreStored']
1885
2323
  adoptAbandoned?: boolean
2324
+ signal?: AbortSignal
2325
+ onProgress?: (progress: WorkspaceProvisionProgress) => void
1886
2326
  }): Promise<WorkspaceProvisionResult> {
2327
+ const invocation = opts.signal
2328
+ const report = (stage: string, step?: string): void => {
2329
+ try {
2330
+ opts.onProgress?.(step === undefined ? { stage } : { stage, step })
2331
+ } catch {
2332
+ // An observer never fails provisioning.
2333
+ }
2334
+ }
2335
+ const timeouts = resolveProvisioningTimeouts(this.options.provisioningTimeouts)
2336
+ const small = commandBound(timeouts, timeouts.command)
1887
2337
  const scopedToken = await (this.options.delegateCredential ?? delegateCredential)(
1888
2338
  this.options.storeRef,
1889
2339
  this.options.storeToken,
@@ -1926,9 +2376,12 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1926
2376
 
1927
2377
  let checkedOut = base
1928
2378
  if (sandbox !== null) {
1929
- const marker = await sandbox.runCommand({
2379
+ const marker = await runSandboxCommand(sandbox, {
1930
2380
  cmd: 'test',
1931
2381
  args: ['-f', VERCEL_PROVISIONED_MARKER],
2382
+ accept: () => true,
2383
+ ...(invocation === undefined ? {} : { signal: invocation }),
2384
+ ...small,
1932
2385
  })
1933
2386
  if (marker.exitCode === 0) {
1934
2387
  // A completed sandbox from an attempt that recorded nothing keeps the
@@ -1936,7 +2389,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1936
2389
  // since. Read it before any stop: a command after stop would resume
1937
2390
  // the persistent guest.
1938
2391
  try {
1939
- checkedOut = await checkedOutBranchHead(sandbox, opts.branch, this.operationSignal())
2392
+ checkedOut = await checkedOutBranchHead(
2393
+ sandbox,
2394
+ opts.branch,
2395
+ this.stageSignal(invocation),
2396
+ )
1940
2397
  } catch (error) {
1941
2398
  throw new WorkspaceCleanupRequired(
1942
2399
  {
@@ -1949,23 +2406,31 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1949
2406
  error,
1950
2407
  )
1951
2408
  }
1952
- const installed = await readDistributionVersionMarker(sandbox, this.operationSignal())
2409
+ const installed = await readDistributionVersionMarker(
2410
+ sandbox,
2411
+ this.stageSignal(invocation),
2412
+ invocation,
2413
+ )
1953
2414
  if (installed === distributionIdentity) {
1954
- await sandbox.stop({ signal: this.operationSignal() })
2415
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
1955
2416
  } else {
1956
2417
  // A completed sandbox whose installed distribution disagrees with
1957
2418
  // what the current system would deliver — including legacy guests
1958
2419
  // without a marker — is refreshed in place. Any refresh failure
1959
2420
  // deletes the sandbox so the next pass rematerializes cleanly.
2421
+ report('distribution refresh')
1960
2422
  try {
1961
- await ensurePinnedBun(sandbox, this.options.config.image, this.operationSignal())
1962
- const archive = await this.archiveBytes()
1963
- await installDistribution(
2423
+ await ensurePinnedBun(
1964
2424
  sandbox,
1965
- archive,
1966
- distributionIdentity,
1967
- this.operationSignal(),
2425
+ this.options.config.image,
2426
+ invocation,
2427
+ commandBound(timeouts, timeouts.bun, 'bun install'),
1968
2428
  )
2429
+ const archive = await this.archiveBytes()
2430
+ await installDistribution(sandbox, archive, distributionIdentity, invocation, {
2431
+ bound: commandBound(timeouts, timeouts.distribution, 'distribution install'),
2432
+ writeSignal: this.stageSignal(invocation),
2433
+ })
1969
2434
  } catch (error) {
1970
2435
  throw new WorkspaceCleanupRequired(
1971
2436
  {
@@ -1978,7 +2443,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1978
2443
  error,
1979
2444
  )
1980
2445
  }
1981
- await sandbox.stop({ signal: this.operationSignal() })
2446
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
1982
2447
  }
1983
2448
  } else if (!opts.adoptAbandoned) {
1984
2449
  // A named VM without the marker is a crashed/legacy provisioning
@@ -1996,14 +2461,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1996
2461
  } else {
1997
2462
  // The dispatcher recorded this generation's attempt as abandoned at
1998
2463
  // its own teardown, and its lease is gone. Finish the same sandbox in
1999
- // place, but only after verification; any doubt still reaps it.
2464
+ // place at the commit it cloned, resuming after its last completed
2465
+ // stage, but only after verification; any doubt still reaps it.
2466
+ report('adopt')
2000
2467
  try {
2001
2468
  // Quiesce first: stopping ends any command the dead invocation left
2002
2469
  // running, and the persistent guest resumes on the next command.
2003
- await sandbox.stop({ signal: this.operationSignal() })
2004
- const checkout = await sandbox.runCommand({
2470
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2471
+ const checkout = await runSandboxCommand(sandbox, {
2005
2472
  cmd: 'test',
2006
2473
  args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
2474
+ accept: () => true,
2475
+ ...(invocation === undefined ? {} : { signal: invocation }),
2476
+ ...small,
2007
2477
  })
2008
2478
  if (checkout.exitCode !== 0)
2009
2479
  throw new Error('abandoned provisioning left no checkout to finish')
@@ -2013,7 +2483,10 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2013
2483
  base,
2014
2484
  distributionIdentity,
2015
2485
  scopedToken,
2016
- verifyClean: true,
2486
+ resume: true,
2487
+ ...(invocation === undefined ? {} : { signal: invocation }),
2488
+ report,
2489
+ timeouts,
2017
2490
  })
2018
2491
  } catch (error) {
2019
2492
  throw new WorkspaceCleanupRequired(
@@ -2043,6 +2516,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2043
2516
  password === undefined
2044
2517
  ? undefined
2045
2518
  : `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
2519
+ // Create stays on its own acknowledgement bound: aborting it mid-flight
2520
+ // would leave a half-created VM nothing addresses.
2521
+ report('create')
2046
2522
  sandbox = await this.facade.create({
2047
2523
  name,
2048
2524
  source: {
@@ -2067,13 +2543,17 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2067
2543
  signal: this.operationSignal(),
2068
2544
  })
2069
2545
  try {
2070
- await relocateCheckout(sandbox, origin.directory)
2546
+ report('relocate')
2547
+ await relocateCheckout(sandbox, origin.directory, invocation, small)
2071
2548
  checkedOut = await this.completeProvisioning(sandbox, {
2072
2549
  origin,
2073
2550
  branch: opts.branch,
2074
2551
  base,
2075
2552
  distributionIdentity,
2076
2553
  scopedToken,
2554
+ ...(invocation === undefined ? {} : { signal: invocation }),
2555
+ report,
2556
+ timeouts,
2077
2557
  })
2078
2558
  } catch (error) {
2079
2559
  throw new WorkspaceCleanupRequired(
@@ -2091,31 +2571,38 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2091
2571
  let provisionHead = checkedOut
2092
2572
  let restorationSkipped: import('../types').RestorationSkip[] = []
2093
2573
  if (opts.restoration?.length) {
2094
- provisionHead = await this.withTrustedGit(sandbox, name, undefined, async (exec) => {
2095
- restorationSkipped = (
2096
- await restoreGitCommits({
2097
- exec,
2098
- workspacePath: VERCEL_WORKSPACE_PATH,
2099
- branch: opts.branch,
2100
- heads: opts.restoration!,
2101
- replaced: opts.restorationReplaced,
2102
- // Store copies are read host-side and applied over the trusted
2103
- // transport; the guest never holds store credentials.
2104
- ...(opts.restoreStored
2105
- ? {
2106
- restoreStored: (sha: string) =>
2107
- opts.restoreStored!({ exec, workspacePath: VERCEL_WORKSPACE_PATH, sha }),
2108
- }
2109
- : {}),
2110
- })
2111
- ).skipped
2112
- const result = await exec(
2113
- ['git', 'rev-parse', '--verify', `refs/heads/${opts.branch}^{commit}`],
2114
- { cwd: VERCEL_WORKSPACE_PATH },
2115
- )
2116
- if (result.exitCode !== 0) throw new Error('cannot confirm restored workspace branch')
2117
- return result.stdout.trim()
2118
- })
2574
+ report('restoration')
2575
+ provisionHead = await this.withTrustedGit(
2576
+ sandbox,
2577
+ name,
2578
+ undefined,
2579
+ async (exec) => {
2580
+ restorationSkipped = (
2581
+ await restoreGitCommits({
2582
+ exec,
2583
+ workspacePath: VERCEL_WORKSPACE_PATH,
2584
+ branch: opts.branch,
2585
+ heads: opts.restoration!,
2586
+ replaced: opts.restorationReplaced,
2587
+ // Store copies are read host-side and applied over the trusted
2588
+ // transport; the guest never holds store credentials.
2589
+ ...(opts.restoreStored
2590
+ ? {
2591
+ restoreStored: (sha: string) =>
2592
+ opts.restoreStored!({ exec, workspacePath: VERCEL_WORKSPACE_PATH, sha }),
2593
+ }
2594
+ : {}),
2595
+ })
2596
+ ).skipped
2597
+ const result = await exec(
2598
+ ['git', 'rev-parse', '--verify', `refs/heads/${opts.branch}^{commit}`],
2599
+ { cwd: VERCEL_WORKSPACE_PATH },
2600
+ )
2601
+ if (result.exitCode !== 0) throw new Error('cannot confirm restored workspace branch')
2602
+ return result.stdout.trim()
2603
+ },
2604
+ invocation,
2605
+ )
2119
2606
  }
2120
2607
  this.origins.set(name, origin)
2121
2608
  this.sessions.set(name, sandbox)
@@ -2134,11 +2621,16 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2134
2621
  }
2135
2622
  }
2136
2623
 
2137
- /** The idempotent post-create sequence: branch checkout at the selected
2138
- * base, credential scrub, toolchain, distribution, dependencies, runtimes,
2139
- * then the completion marker and a snapshot stop. Shared by a fresh create
2140
- * and by finishing a teardown-abandoned attempt in place. Returns the
2141
- * verified checked-out head. */
2624
+ /** The checkpointed post-create sequence: branch checkout and credential
2625
+ * scrub, pinned Bun, each named system provisioning step, distribution,
2626
+ * lockfile dependencies, runtimes, then the completion marker and a
2627
+ * snapshot stop. Each stage records an input fingerprint chained onto the
2628
+ * previous stage's once it succeeds. Shared by a fresh create and by
2629
+ * finishing a teardown-abandoned attempt in place; with `resume`, the
2630
+ * sequence stays on the commit the clone holds, skips the leading run of
2631
+ * stages whose checkpoints match the current inputs, and executes every
2632
+ * stage from the first mismatch onward. Returns the verified checked-out
2633
+ * head. */
2142
2634
  private async completeProvisioning(
2143
2635
  sandbox: VercelSandboxHandle,
2144
2636
  input: {
@@ -2147,70 +2639,205 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2147
2639
  base: string
2148
2640
  distributionIdentity: string
2149
2641
  scopedToken: string
2150
- /** Require no tracked modifications before the marker is written. */
2151
- verifyClean?: boolean
2642
+ /** Finish an abandoned attempt: keep the cloned commit, skip completed
2643
+ * stages, and require no tracked modifications. */
2644
+ resume?: boolean
2645
+ /** The invocation's teardown signal: every guest command stops on it. */
2646
+ signal?: AbortSignal
2647
+ /** Reports the stage (and step) about to run. */
2648
+ report: (stage: string, step?: string) => void
2649
+ timeouts: VercelProvisioningTimeouts
2152
2650
  },
2153
2651
  ): Promise<string> {
2154
- const { origin, branch, base, distributionIdentity, scopedToken } = input
2155
- await commandOrThrow(sandbox, {
2156
- cmd: 'git',
2157
- args: ['checkout', '-B', branch, base],
2158
- cwd: VERCEL_WORKSPACE_PATH,
2159
- })
2160
- const head = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2161
- if (head !== base)
2162
- throw new Error(`checked out ${branch} at ${head}, expected selected base ${base}`)
2163
- if (input.verifyClean) {
2652
+ const { origin, branch, distributionIdentity, scopedToken, report, timeouts } = input
2653
+ const resume = input.resume === true
2654
+ const invocation = input.signal
2655
+ const cancel = invocation === undefined ? {} : { signal: invocation }
2656
+ const small = commandBound(timeouts, timeouts.command)
2657
+ const head = resume ? await guestHeadCommit(sandbox, this.stageSignal(invocation)) : input.base
2658
+ const checkpoints = resume
2659
+ ? await readProvisionCheckpoints(sandbox, invocation, small)
2660
+ : new Map<string, string>()
2661
+ let previous = ''
2662
+ let executing = !resume
2663
+ const kept = new Set<string>()
2664
+ const stage = async (
2665
+ key: string,
2666
+ label: { stage: string; step?: string },
2667
+ inputs: unknown,
2668
+ run: () => Promise<void>,
2669
+ skipped?: () => Promise<void>,
2670
+ ): Promise<void> => {
2671
+ const fingerprint = provisionFingerprint(previous, key, inputs)
2672
+ if (!executing && checkpoints.get(key) === fingerprint) {
2673
+ kept.add(key)
2674
+ await skipped?.()
2675
+ } else {
2676
+ if (!executing) {
2677
+ // Durably drop every checkpoint outside the kept prefix before this
2678
+ // stage mutates the guest, so an interrupted rerun can never leave
2679
+ // a downstream checkpoint a later adoption would skip.
2680
+ await clearProvisionCheckpoints(
2681
+ sandbox,
2682
+ [...checkpoints.keys()].filter((existing) => !kept.has(existing)),
2683
+ invocation,
2684
+ small,
2685
+ )
2686
+ executing = true
2687
+ }
2688
+ report(label.stage, label.step)
2689
+ await run()
2690
+ await writeProvisionCheckpoint(sandbox, key, fingerprint, invocation, small)
2691
+ }
2692
+ previous = fingerprint
2693
+ }
2694
+
2695
+ const checkout = commandBound(timeouts, timeouts.command, 'checkout')
2696
+ await stage(
2697
+ '01-checkout',
2698
+ { stage: 'checkout' },
2699
+ { branch, origin: origin.url, head },
2700
+ async () => {
2701
+ await commandOrThrow(sandbox, {
2702
+ cmd: 'git',
2703
+ args: ['checkout', '-B', branch, head],
2704
+ cwd: VERCEL_WORKSPACE_PATH,
2705
+ ...cancel,
2706
+ ...checkout,
2707
+ })
2708
+ const checked = await checkedOutBranchHead(sandbox, branch, this.stageSignal(invocation))
2709
+ if (checked !== head)
2710
+ throw new Error(`checked out ${branch} at ${checked}, expected selected base ${head}`)
2711
+ await commandOrThrow(sandbox, {
2712
+ cmd: 'git',
2713
+ args: ['remote', 'set-url', 'origin', origin.url],
2714
+ cwd: VERCEL_WORKSPACE_PATH,
2715
+ ...cancel,
2716
+ ...checkout,
2717
+ })
2718
+ for (const key of [
2719
+ 'credential.helper',
2720
+ 'http.extraheader',
2721
+ `http.${origin.url}.extraheader`,
2722
+ ]) {
2723
+ // Exit 5: the key was not set.
2724
+ await commandOrThrow(sandbox, {
2725
+ cmd: 'git',
2726
+ args: ['config', '--local', '--unset-all', key],
2727
+ cwd: VERCEL_WORKSPACE_PATH,
2728
+ accept: (code) => code === 0 || code === 5,
2729
+ ...cancel,
2730
+ ...checkout,
2731
+ })
2732
+ }
2733
+ },
2734
+ async () => {
2735
+ const checked = await checkedOutBranchHead(sandbox, branch, this.stageSignal(invocation))
2736
+ if (checked !== head)
2737
+ throw new Error(`checked out ${branch} at ${checked}, expected cloned head ${head}`)
2738
+ },
2739
+ )
2740
+ if (resume) {
2164
2741
  // A finished abandoned attempt must not expose tracked edits the dead
2165
2742
  // invocation may have left behind.
2166
- const diff = await sandbox.runCommand({
2743
+ const diff = await runSandboxCommand(sandbox, {
2167
2744
  cmd: 'git',
2168
2745
  args: ['diff', '--quiet', 'HEAD', '--'],
2169
2746
  cwd: VERCEL_WORKSPACE_PATH,
2747
+ accept: () => true,
2748
+ ...cancel,
2749
+ ...small,
2170
2750
  })
2171
2751
  if (diff.exitCode !== 0) throw new Error('abandoned provisioning left tracked modifications')
2172
2752
  }
2173
- await commandOrThrow(sandbox, {
2174
- cmd: 'git',
2175
- args: ['remote', 'set-url', 'origin', origin.url],
2176
- cwd: VERCEL_WORKSPACE_PATH,
2177
- })
2178
- for (const key of ['credential.helper', 'http.extraheader', `http.${origin.url}.extraheader`]) {
2179
- const result = await sandbox.runCommand({
2180
- cmd: 'git',
2181
- args: ['config', '--local', '--unset-all', key],
2182
- cwd: VERCEL_WORKSPACE_PATH,
2183
- })
2184
- if (result.exitCode !== 0 && result.exitCode !== 5)
2185
- throw new Error(`failed to scrub git config ${key}`)
2753
+ const image = this.options.config.image
2754
+ await stage('02-bun', { stage: 'bun install' }, { version: VERCEL_BUN_VERSION, image }, () =>
2755
+ provisionBun(sandbox, image, invocation, commandBound(timeouts, timeouts.bun, 'bun install')),
2756
+ )
2757
+ const steps = this.options.config.provisioning ?? []
2758
+ for (const [index, step] of steps.entries()) {
2759
+ // The fingerprint deliberately omits `timeoutSeconds`: a bound change
2760
+ // never reruns a completed step.
2761
+ await stage(
2762
+ `03-step-${index}`,
2763
+ { stage: 'system provisioning step', step: step.name },
2764
+ { name: step.name, command: step.command },
2765
+ () =>
2766
+ runSystemProvisioningStep(
2767
+ sandbox,
2768
+ step,
2769
+ invocation,
2770
+ commandBound(timeouts, timeouts.step),
2771
+ ),
2772
+ )
2186
2773
  }
2187
- await provisionBun(sandbox, this.options.config.image)
2188
- await runSystemProvisioning(sandbox, this.options.config.provisioning ?? [])
2189
- const archive = await this.archiveBytes()
2190
- await installDistribution(sandbox, archive, distributionIdentity, this.operationSignal())
2774
+ await stage(
2775
+ '04-distribution',
2776
+ { stage: 'distribution install' },
2777
+ { identity: distributionIdentity },
2778
+ async () => {
2779
+ const archive = await this.archiveBytes()
2780
+ await installDistribution(sandbox, archive, distributionIdentity, invocation, {
2781
+ bound: commandBound(timeouts, timeouts.distribution, 'distribution install'),
2782
+ writeSignal: this.stageSignal(invocation),
2783
+ })
2784
+ },
2785
+ )
2191
2786
  // Repository dependencies precede branch-owned package plugin loading.
2192
2787
  // The fixed bootstrap supports the consuming repository's lockfile; its
2193
2788
  // configured setup command still runs at every runner attachment.
2194
- await commandOrThrow(sandbox, {
2195
- cmd: 'sh',
2196
- args: [
2197
- '-c',
2198
- `if [ -f bun.lock ] || [ -f bun.lockb ]; then ${VERCEL_BUN_EXECUTABLE} install --frozen-lockfile; elif [ -f package-lock.json ]; then npm ci; elif [ -f pnpm-lock.yaml ]; then corepack pnpm install --frozen-lockfile; elif [ -f yarn.lock ]; then corepack yarn install --immutable; fi`,
2199
- ],
2200
- cwd: VERCEL_WORKSPACE_PATH,
2201
- })
2202
- await bootstrapRuntimes(
2203
- sandbox,
2204
- this.options.config,
2205
- { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
2206
- currentRuntimeReferences(this.options.runtimeReferences),
2207
- true,
2789
+ await stage(
2790
+ '05-dependencies',
2791
+ { stage: 'dependency install' },
2792
+ { command: DEPENDENCY_INSTALL_COMMAND },
2793
+ () =>
2794
+ commandOrThrow(sandbox, {
2795
+ cmd: 'sh',
2796
+ args: ['-c', DEPENDENCY_INSTALL_COMMAND],
2797
+ cwd: VERCEL_WORKSPACE_PATH,
2798
+ ...cancel,
2799
+ ...commandBound(timeouts, timeouts.dependencies, 'dependency install'),
2800
+ }),
2801
+ )
2802
+ const references = currentRuntimeReferences(this.options.runtimeReferences)
2803
+ await stage(
2804
+ '06-runtimes',
2805
+ { stage: 'runtime bootstrap' },
2806
+ [...references]
2807
+ .sort((left, right) =>
2808
+ left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
2809
+ )
2810
+ .map((group) => {
2811
+ const provisioning = this.options.config.runtimeProvisioning?.[group.runtime]
2812
+ return {
2813
+ runtime: group.runtime,
2814
+ references: group.references,
2815
+ install: provisioning?.install ?? null,
2816
+ preflight: provisioning?.preflight ?? null,
2817
+ }
2818
+ }),
2819
+ () =>
2820
+ bootstrapRuntimes(
2821
+ sandbox,
2822
+ this.options.config,
2823
+ { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
2824
+ references,
2825
+ true,
2826
+ invocation,
2827
+ {
2828
+ bound: commandBound(timeouts, timeouts.runtime),
2829
+ onStage: (step) => report('runtime bootstrap', step),
2830
+ },
2831
+ ),
2208
2832
  )
2833
+ report('finalize')
2209
2834
  await commandOrThrow(sandbox, {
2210
2835
  cmd: 'touch',
2211
2836
  args: [VERCEL_PROVISIONED_MARKER],
2837
+ ...cancel,
2838
+ ...commandBound(timeouts, timeouts.command, 'finalize'),
2212
2839
  })
2213
- await sandbox.stop({ signal: this.operationSignal() })
2840
+ await sandbox.stop({ signal: this.stageSignal(invocation) })
2214
2841
  return head
2215
2842
  }
2216
2843
 
@@ -2223,6 +2850,14 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2223
2850
  return AbortSignal.timeout(this.operationTimeoutMs())
2224
2851
  }
2225
2852
 
2853
+ /** A metadata call inside provisioning: its own acknowledgement bound, and
2854
+ * stopped by the invocation's teardown signal. */
2855
+ private stageSignal(invocation?: AbortSignal): AbortSignal {
2856
+ return invocation === undefined
2857
+ ? this.operationSignal()
2858
+ : AbortSignal.any([this.operationSignal(), invocation])
2859
+ }
2860
+
2226
2861
  private operationTimeoutMs(): number {
2227
2862
  return this.options.config.operationTimeoutMs ?? 30_000
2228
2863
  }
@@ -4685,6 +5320,9 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4685
5320
  ref: string,
4686
5321
  signal: AbortSignal | undefined,
4687
5322
  effect: (exec: Exec) => Promise<T>,
5323
+ /** Also stops each guest command (provisioning restore at teardown);
5324
+ * each keeps its own acknowledgement cap. */
5325
+ cancel?: AbortSignal,
4688
5326
  ): Promise<T> {
4689
5327
  const { origin } = await this.normalNetworkPolicy(ref)
4690
5328
  const token = this.options.env.GITHUB_TOKEN || this.options.env.GH_TOKEN
@@ -4721,7 +5359,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
4721
5359
  { signal: this.recoveryMetadataSignal() },
4722
5360
  )
4723
5361
  return await effect(async (cmd) => {
4724
- const bound = signal ?? this.operationSignal()
5362
+ const bound =
5363
+ signal ??
5364
+ (cancel === undefined
5365
+ ? this.operationSignal()
5366
+ : AbortSignal.any([this.operationSignal(), cancel]))
4725
5367
  const result = await sandbox.runCommand({
4726
5368
  cmd: cmd[0]!,
4727
5369
  args: cmd.slice(1),