@defrex/autobuild 1.3.0 → 1.4.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 (142) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +302 -26
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +187 -19
  5. package/docs/build-store.md +18 -0
  6. package/docs/builds.md +5 -1
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +38 -19
  9. package/docs/dispatcher-hosting.md +42 -0
  10. package/docs/dispatcher.md +41 -0
  11. package/docs/forges.md +5 -0
  12. package/docs/integration-tree.md +8 -0
  13. package/docs/operating.md +11 -3
  14. package/docs/operator-api.md +37 -4
  15. package/docs/plugin-authoring.md +45 -1
  16. package/docs/remote-store-protocol.md +258 -42
  17. package/docs/remote-ticket-protocol.md +12 -10
  18. package/docs/restacking.md +60 -3
  19. package/docs/setup.md +37 -8
  20. package/docs/skills.md +1 -1
  21. package/docs/spec-standard.md +37 -3
  22. package/docs/troubleshooting.md +9 -0
  23. package/docs/workspaces.md +1 -1
  24. package/package.json +4 -3
  25. package/packages/core/src/accounts/availability.ts +96 -0
  26. package/packages/core/src/accounts/local-owner.ts +49 -2
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary.ts +17 -1
  29. package/packages/core/src/cli/context.ts +62 -0
  30. package/packages/core/src/cli/dashboard/model.ts +12 -3
  31. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  32. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  33. package/packages/core/src/cli/dashboard/render.ts +46 -5
  34. package/packages/core/src/cli/dispatch-args.ts +27 -3
  35. package/packages/core/src/cli/dispatch-frontend.ts +178 -52
  36. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +45 -9
  39. package/packages/core/src/cli/dispatch.ts +145 -11
  40. package/packages/core/src/cli/harvest.ts +2 -1
  41. package/packages/core/src/cli/help.ts +16 -3
  42. package/packages/core/src/cli/historical-build-state.ts +6 -0
  43. package/packages/core/src/cli/main.ts +15 -2
  44. package/packages/core/src/cli/publication-settlement.ts +17 -0
  45. package/packages/core/src/cli/remote-poll.ts +11 -1
  46. package/packages/core/src/cli/repository-status.ts +11 -0
  47. package/packages/core/src/cli/status.ts +7 -1
  48. package/packages/core/src/cli/wait.ts +9 -2
  49. package/packages/core/src/cli/watch.ts +38 -3
  50. package/packages/core/src/config/roles.ts +16 -1
  51. package/packages/core/src/events/catalog.ts +7 -0
  52. package/packages/core/src/events/payloads.ts +85 -2
  53. package/packages/core/src/events/policy.ts +10 -0
  54. package/packages/core/src/events/repository.ts +35 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +189 -0
  56. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  57. package/packages/core/src/kernel/engine.ts +19 -12
  58. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  59. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  60. package/packages/core/src/kernel/log-index.ts +1 -1
  61. package/packages/core/src/kernel/node-landing.ts +27 -10
  62. package/packages/core/src/kernel/node-restack-demand.ts +1 -0
  63. package/packages/core/src/kernel/node-restack-state.ts +16 -1
  64. package/packages/core/src/kernel/node-restack-transaction.ts +14 -0
  65. package/packages/core/src/kernel/read-facts.ts +114 -9
  66. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  67. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  68. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  69. package/packages/core/src/kernel/reducer.ts +20 -2
  70. package/packages/core/src/kernel/replay-retention.ts +176 -0
  71. package/packages/core/src/kernel/target-lineage.ts +65 -0
  72. package/packages/core/src/kernel/target-observation.ts +117 -0
  73. package/packages/core/src/operator/registry.ts +5 -13
  74. package/packages/core/src/operator/tickets.ts +8 -2
  75. package/packages/core/src/plugin-sdk/index.ts +1 -0
  76. package/packages/core/src/ports/forge/fake.ts +22 -0
  77. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  78. package/packages/core/src/ports/forge/github.ts +42 -10
  79. package/packages/core/src/ports/forge/local-git.ts +16 -1
  80. package/packages/core/src/ports/types.ts +58 -4
  81. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  82. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  83. package/packages/core/src/ports/workspace/create.ts +2 -0
  84. package/packages/core/src/ports/workspace/fake.ts +4 -0
  85. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  86. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  87. package/packages/core/src/processes/build-runner.ts +240 -111
  88. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  89. package/packages/core/src/processes/dispatcher.ts +262 -80
  90. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  91. package/packages/core/src/processes/harvest-runner.ts +6 -7
  92. package/packages/core/src/processes/publication-state.ts +2 -1
  93. package/packages/core/src/processes/repo-view.ts +22 -0
  94. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  95. package/packages/core/src/scenarios/harness.ts +7 -0
  96. package/packages/core/src/store/adapter.ts +9 -0
  97. package/packages/core/src/store/build-scope.ts +28 -0
  98. package/packages/core/src/store/contract.ts +125 -0
  99. package/packages/core/src/store/event-reads.ts +156 -0
  100. package/packages/core/src/store/local/schema.ts +11 -0
  101. package/packages/core/src/store/local/store.ts +117 -2
  102. package/packages/core/src/store/memory.ts +237 -0
  103. package/packages/core/src/store/phase-session.ts +47 -0
  104. package/packages/core/src/store/reduced-reads.ts +8 -0
  105. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  106. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  107. package/packages/core/src/store/reducer-values.ts +62 -2
  108. package/packages/core/src/store/remote/client.ts +161 -16
  109. package/packages/core/src/store/remote/compatibility.ts +177 -46
  110. package/packages/core/src/store/remote/errors.ts +16 -0
  111. package/packages/core/src/store/remote/index.ts +11 -0
  112. package/packages/core/src/store/remote/protocol.ts +22 -0
  113. package/packages/core/src/store/remote/released-clients.json +37 -0
  114. package/packages/core/src/store/remote/released-clients.ts +88 -0
  115. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  116. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  117. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  118. package/packages/core/src/store/remote/version.ts +5 -2
  119. package/packages/core/src/store/repo-state-events.ts +4 -3
  120. package/packages/core/src/store/scan-cadence.ts +15 -0
  121. package/packages/core/src/store/session-handle.ts +18 -0
  122. package/packages/core/src/store/types.ts +27 -6
  123. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  124. package/packages/core/src/testing/index.ts +5 -0
  125. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  126. package/skills/guide/SKILL.md +177 -16
  127. package/skills/guide/references/accounts.md +38 -0
  128. package/skills/guide/references/integration-tree.md +8 -0
  129. package/skills/guide/references/operator-api.md +37 -4
  130. package/skills/guide/references/plugin-authoring.md +45 -1
  131. package/skills/guide/references/remote-store-protocol.md +258 -42
  132. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  133. package/skills/guide/references/restacking.md +60 -3
  134. package/skills/guide/references/setup.md +37 -8
  135. package/skills/guide/references/spec-standard.md +37 -3
  136. package/skills/implement/SKILL.md +12 -3
  137. package/skills/operate/SKILL.md +64 -7
  138. package/skills/plan/SKILL.md +27 -4
  139. package/skills/plan-review/SKILL.md +22 -2
  140. package/skills/reconcile/SKILL.md +10 -1
  141. package/skills/spec/SKILL.md +7 -4
  142. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,9 @@
1
+ import {
2
+ missingAccountCredentials,
3
+ MissingAccountCredentialsError,
4
+ } from '../../accounts/availability'
5
+ import { WorkspaceCleanupRequired } from '../types'
6
+ import { inspectGitCandidate, preserveGitCommits, restoreGitCommits } from './commit-preservation'
1
7
  import { accountPolicy, accountGuestEnvironment } from './account-policy'
2
8
  import { gitRewrite, parseRemoteHead } from '../forge/git-rewrite'
3
9
  import { delegateCredential } from '../../store/remote/credentials'
@@ -254,8 +260,10 @@ export interface VercelSnapshotPurge {
254
260
 
255
261
  export interface VercelSandboxFacade {
256
262
  get(name: string, signal?: AbortSignal): Promise<VercelSandboxHandle | null>
257
- /** Durable build workspaces retain the named get-or-create lifecycle. */
263
+ /** Creation never deletes an existing named environment. */
258
264
  create(input: VercelSandboxCreateInput): Promise<VercelSandboxHandle>
265
+ /** Dispatcher-authorized destruction only, after fence and commit receipt. */
266
+ deleteByName?(name: string, signal?: AbortSignal): Promise<'confirmed' | 'absent'>
259
267
  /** Readiness always acquires a new unnamed disposable environment. */
260
268
  createFresh?(
261
269
  input: Omit<VercelSandboxCreateInput, 'name' | 'persistent'>,
@@ -327,50 +335,79 @@ function withSessionMetadata(sandbox: object): VercelSandboxHandle {
327
335
  return sandbox as VercelSandboxHandle
328
336
  }
329
337
 
338
+ export function isUnavailableVercelSnapshot(error: unknown): boolean {
339
+ if (error === null || typeof error !== 'object') return false
340
+ const candidate = error as {
341
+ response?: { status?: number }
342
+ json?: { error?: { code?: string } }
343
+ }
344
+ return candidate.response?.status === 410 && candidate.json?.error?.code === 'snapshot_not_found'
345
+ }
346
+
347
+ /** Confirmed filesystem absence; an expired snapshot may still reserve the name. */
330
348
  export function isMissingVercelSandbox(error: unknown): boolean {
331
349
  if (error === null || typeof error !== 'object') return false
332
350
  const candidate = error as {
333
351
  response?: { status?: number }
334
352
  json?: { error?: { code?: string } }
335
353
  }
336
- return (
337
- candidate.response?.status === 404 ||
338
- (candidate.response?.status === 410 && candidate.json?.error?.code === 'snapshot_not_found')
339
- )
354
+ return candidate.response?.status === 404 || isUnavailableVercelSnapshot(error)
340
355
  }
341
356
 
342
357
  export function createVercelSdkFacade(
343
358
  env: Record<string, string | undefined>,
359
+ fetch: typeof globalThis.fetch = globalThis.fetch,
344
360
  ): VercelSandboxFacade {
345
361
  const credentials = vercelSdkCredentials(env)
346
362
  return {
347
363
  async get(name, signal) {
348
364
  try {
349
- return withSessionMetadata(await Sandbox.get({ name, signal, ...credentials }))
365
+ return withSessionMetadata(
366
+ await Sandbox.get({ name, signal, resume: false, fetch, ...credentials }),
367
+ )
350
368
  } catch (error) {
369
+ // Provision must retain the stale name so dispatcher cleanup can delete it.
370
+ if (isUnavailableVercelSnapshot(error)) throw error
351
371
  if (isMissingVercelSandbox(error)) return null
352
372
  throw error
353
373
  }
354
374
  },
355
375
  async create(input) {
356
- // get() returning null includes stale snapshots. getOrCreate performs the
357
- // SDK's required stale-name deletion before recreating and also closes a
358
- // concurrent provision race safely.
359
376
  return withSessionMetadata(
360
- await Sandbox.getOrCreate({
377
+ await Sandbox.create({
361
378
  ...input,
362
379
  region: input.region as SandboxRegion | undefined,
363
380
  failoverRegions: input.failoverRegions as SandboxRegion[] | undefined,
381
+ fetch,
364
382
  ...credentials,
365
383
  }),
366
384
  )
367
385
  },
386
+ async deleteByName(name, signal) {
387
+ const { token, projectId, teamId } = credentials
388
+ if (!token || !projectId || !teamId)
389
+ throw new Error(
390
+ 'sandbox deletion requires explicitly resolved credentials and project scope',
391
+ )
392
+ const url = new URL(`https://vercel.com/api/v2/sandboxes/${encodeURIComponent(name)}`)
393
+ url.searchParams.set('projectId', projectId)
394
+ url.searchParams.set('teamId', teamId)
395
+ const response = await fetch(url, {
396
+ method: 'DELETE',
397
+ headers: { authorization: `Bearer ${token}` },
398
+ ...(signal === undefined ? {} : { signal }),
399
+ })
400
+ if (response.status === 404 || response.status === 410) return 'absent'
401
+ if (!response.ok) throw new Error(`sandbox deletion failed with HTTP ${response.status}`)
402
+ return 'confirmed'
403
+ },
368
404
  async createFresh(input) {
369
405
  return withSessionMetadata(
370
406
  await Sandbox.create({
371
407
  ...input,
372
408
  region: input.region as SandboxRegion | undefined,
373
409
  failoverRegions: input.failoverRegions as SandboxRegion[] | undefined,
410
+ fetch,
374
411
  ...credentials,
375
412
  }),
376
413
  )
@@ -380,6 +417,7 @@ export function createVercelSdkFacade(
380
417
  const page = await Snapshot.list({
381
418
  name,
382
419
  limit: 50,
420
+ fetch,
383
421
  ...(signal === undefined ? {} : { signal }),
384
422
  ...credentials,
385
423
  })
@@ -393,7 +431,7 @@ export function createVercelSdkFacade(
393
431
  }))
394
432
  },
395
433
  async deleteSnapshot(snapshotId, signal) {
396
- const snapshot = await Snapshot.get({ snapshotId, ...credentials })
434
+ const snapshot = await Snapshot.get({ snapshotId, fetch, ...credentials })
397
435
  await snapshot.delete(signal === undefined ? {} : { signal })
398
436
  },
399
437
  }
@@ -1137,6 +1175,7 @@ export interface VercelSandboxProviderOptions {
1137
1175
  exec?: Exec
1138
1176
  packageArchive?: () => Promise<Uint8Array>
1139
1177
  accounts?: () => import('../../config/accounts').Accounts
1178
+ executionAccounts?: () => import('../../config/accounts').Accounts
1140
1179
  runtimeReferences?: RuntimeReferencesSource
1141
1180
  /** Checkout-less seam: the repository's HTTPS GitHub origin. Default reads
1142
1181
  * `git remote get-url origin` from `repo` on the host. */
@@ -1177,9 +1216,12 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1177
1216
  readonly buildExecution: BuildExecution
1178
1217
  readonly harvestExecution: HarvestExecution
1179
1218
  readonly orchestratorSandbox: OperatorSandboxExecution
1180
- readonly publication
1219
+ readonly publication: WorkspacePublication &
1220
+ Required<
1221
+ Pick<WorkspacePublication, 'isPublished' | 'rewrite' | 'preserve' | 'recoverCandidate'>
1222
+ >
1181
1223
  readonly sandboxPublication: WorkspacePublication
1182
- readonly recovery
1224
+ readonly recovery: import('../types').WorkspaceRecovery
1183
1225
  private readonly facade: VercelSandboxFacade
1184
1226
  private readonly exec: Exec
1185
1227
  private readonly active = new Set<string>()
@@ -1258,16 +1300,91 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1258
1300
  release: (input) => this.sandboxRelease(input),
1259
1301
  }
1260
1302
  this.recovery = {
1303
+ fence: async (handle) => {
1304
+ if (handle.provider !== this.name) throw new Error('workspace fence provider mismatch')
1305
+ try {
1306
+ // Never trust the in-process handle after restart or another resume.
1307
+ const sandbox = await this.facade.get(handle.ref, this.operationSignal())
1308
+ if (sandbox === null) {
1309
+ this.forget(handle.ref)
1310
+ return { outcome: 'absent' }
1311
+ }
1312
+ await sandbox.stop({ signal: this.operationSignal() })
1313
+ this.active.delete(handle.ref)
1314
+ this.uncertain.delete(handle.ref)
1315
+ this.sessions.set(handle.ref, sandbox)
1316
+ return { outcome: 'confirmed' }
1317
+ } catch (error) {
1318
+ if (isMissingVercelSandbox(error)) {
1319
+ this.forget(handle.ref)
1320
+ return { outcome: 'absent' }
1321
+ }
1322
+ return {
1323
+ outcome: 'unknown',
1324
+ error: error instanceof Error ? error.message : String(error),
1325
+ }
1326
+ }
1327
+ },
1261
1328
  reap: (handle: WorkspaceHandle) => {
1262
1329
  if (handle.provider !== this.name) {
1263
1330
  throw new Error(
1264
1331
  `vercel-sandbox cannot reap a workspace owned by provider "${handle.provider}" (${handle.ref})`,
1265
1332
  )
1266
1333
  }
1267
- return this.reap(handle.ref)
1334
+ return this.reap(handle.ref, true)
1268
1335
  },
1269
1336
  }
1270
1337
  this.publication = {
1338
+ recoverCandidate: (input) =>
1339
+ this.withPolicyLock(input.ref, async () => {
1340
+ if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1341
+ throw new Error('candidate recovery requires confirmed teardown')
1342
+ const sandbox = await this.facade.get(input.ref, this.operationSignal())
1343
+ if (!sandbox) throw new Error('candidate recovery awaits replacement workspace')
1344
+ return this.withTrustedGit(sandbox, input.ref, async (exec) => {
1345
+ const archiveRef = `refs/autobuild/archive/${input.slug}/${input.sha}`
1346
+ const available = await inspectGitCandidate({
1347
+ ...input,
1348
+ exec,
1349
+ workspacePath: VERCEL_WORKSPACE_PATH,
1350
+ archiveRef,
1351
+ })
1352
+ if (available)
1353
+ await gitRewrite(exec, false).archive({
1354
+ workspacePath: VERCEL_WORKSPACE_PATH,
1355
+ ref: archiveRef,
1356
+ sha: input.sha,
1357
+ })
1358
+ return available
1359
+ })
1360
+ }),
1361
+ preserve: (input) =>
1362
+ this.withPolicyLock(input.ref, async () => {
1363
+ if (this.active.has(input.ref) || this.uncertain.has(input.ref))
1364
+ throw new Error('preservation requires confirmed execution teardown')
1365
+ const sandbox = await this.facade.get(input.ref, this.operationSignal())
1366
+ if (sandbox === null) return { outcome: 'absent' }
1367
+ const heads = await this.withTrustedGit(sandbox, input.ref, async (exec) => {
1368
+ const capability = gitRewrite(exec, false)
1369
+ const remote = await this.remoteBranchHead(input.branch, 'preservation branch')
1370
+ const base =
1371
+ remote === null
1372
+ ? input.base
1373
+ : await capability.snapshot({
1374
+ workspacePath: VERCEL_WORKSPACE_PATH,
1375
+ branch: input.branch,
1376
+ destinationRef: `refs/autobuild/reconcile/${input.slug}/preservation`,
1377
+ })
1378
+ return preserveGitCommits({
1379
+ ...input,
1380
+ base,
1381
+ exec,
1382
+ workspacePath: VERCEL_WORKSPACE_PATH,
1383
+ archive: capability.archive,
1384
+ })
1385
+ })
1386
+ return { outcome: 'preserved', heads }
1387
+ }),
1271
1388
  rewrite: (input: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]) =>
1272
1389
  this.withPolicyLock(input.ref, () => this.publish(input)),
1273
1390
  isPublished: (input: { sha: string; branch: string }) => this.isPublished(input),
@@ -1290,6 +1407,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1290
1407
  branch: string
1291
1408
  revision?: string
1292
1409
  generation?: number
1410
+ restoration?: import('../types').WorkspacePreservationHead[]
1293
1411
  }): Promise<WorkspaceProvisionResult> {
1294
1412
  const scopedToken = await (this.options.delegateCredential ?? delegateCredential)(
1295
1413
  this.options.storeRef,
@@ -1303,7 +1421,6 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1303
1421
  // current archive source would deliver, against which both a fresh
1304
1422
  // install's marker and a reused sandbox's marker are compared.
1305
1423
  const distributionIdentity = await this.identityStamp()
1306
- let sandbox = await this.facade.get(name, this.operationSignal())
1307
1424
  const existing = await this.remoteBranchHead(opts.branch, `remote branch ${opts.branch}`)
1308
1425
  const base =
1309
1426
  existing ??
@@ -1314,6 +1431,23 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1314
1431
  `remote branch ${existing === null ? opts.baseBranch : opts.branch} does not exist`,
1315
1432
  )
1316
1433
 
1434
+ let sandbox: VercelSandboxHandle | null
1435
+ try {
1436
+ sandbox = await this.facade.get(name, this.operationSignal())
1437
+ } catch (error) {
1438
+ if (!isUnavailableVercelSnapshot(error)) throw error
1439
+ throw new WorkspaceCleanupRequired(
1440
+ {
1441
+ provider: this.name,
1442
+ ref: name,
1443
+ path: VERCEL_WORKSPACE_PATH,
1444
+ branch: opts.branch,
1445
+ base: { source: 'existing', sha: base },
1446
+ },
1447
+ error,
1448
+ )
1449
+ }
1450
+
1317
1451
  if (sandbox !== null) {
1318
1452
  const marker = await sandbox.runCommand({
1319
1453
  cmd: 'test',
@@ -1337,24 +1471,32 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1337
1471
  this.operationSignal(),
1338
1472
  )
1339
1473
  } catch (error) {
1340
- try {
1341
- this.sessions.set(name, sandbox)
1342
- await this.reap(name)
1343
- } catch (deleteError) {
1344
- throw new AggregateError(
1345
- [error, deleteError],
1346
- `sandbox ${name} distribution refresh failed and its incomplete environment could not be confirmed deleted`,
1347
- )
1348
- }
1349
- throw error
1474
+ throw new WorkspaceCleanupRequired(
1475
+ {
1476
+ provider: this.name,
1477
+ ref: name,
1478
+ path: VERCEL_WORKSPACE_PATH,
1479
+ branch: opts.branch,
1480
+ base: { source: 'existing', sha: base },
1481
+ },
1482
+ error,
1483
+ )
1350
1484
  }
1351
1485
  await sandbox.stop({ signal: this.operationSignal() })
1352
1486
  }
1353
1487
  } else {
1354
1488
  // A named VM without the marker is a crashed/legacy provisioning
1355
1489
  // attempt. Never expose its potentially unscrubbed checkout to agents.
1356
- await sandbox.delete({ signal: this.operationSignal() })
1357
- sandbox = null
1490
+ throw new WorkspaceCleanupRequired(
1491
+ {
1492
+ provider: this.name,
1493
+ ref: name,
1494
+ path: VERCEL_WORKSPACE_PATH,
1495
+ branch: opts.branch,
1496
+ base: { source: 'existing', sha: base },
1497
+ },
1498
+ new Error('incomplete provisioning marker'),
1499
+ )
1358
1500
  }
1359
1501
  }
1360
1502
 
@@ -1447,18 +1589,35 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1447
1589
  })
1448
1590
  await sandbox.stop({ signal: this.operationSignal() })
1449
1591
  } catch (error) {
1450
- try {
1451
- this.sessions.set(name, sandbox)
1452
- await this.reap(name)
1453
- } catch (deleteError) {
1454
- throw new AggregateError(
1455
- [error, deleteError],
1456
- `sandbox ${name} setup failed and its incomplete environment could not be confirmed deleted`,
1457
- )
1458
- }
1459
- throw error
1592
+ throw new WorkspaceCleanupRequired(
1593
+ {
1594
+ provider: this.name,
1595
+ ref: name,
1596
+ path: VERCEL_WORKSPACE_PATH,
1597
+ branch: opts.branch,
1598
+ base: { source: 'remote', sha: base },
1599
+ },
1600
+ error,
1601
+ )
1460
1602
  }
1461
1603
  }
1604
+ let provisionHead = base
1605
+ if (opts.restoration?.length) {
1606
+ provisionHead = await this.withTrustedGit(sandbox, name, async (exec) => {
1607
+ await restoreGitCommits({
1608
+ exec,
1609
+ workspacePath: VERCEL_WORKSPACE_PATH,
1610
+ branch: opts.branch,
1611
+ heads: opts.restoration!,
1612
+ })
1613
+ const result = await exec(
1614
+ ['git', 'rev-parse', '--verify', `refs/heads/${opts.branch}^{commit}`],
1615
+ { cwd: VERCEL_WORKSPACE_PATH },
1616
+ )
1617
+ if (result.exitCode !== 0) throw new Error('cannot confirm restored workspace branch')
1618
+ return result.stdout.trim()
1619
+ })
1620
+ }
1462
1621
  this.origins.set(name, origin)
1463
1622
  this.sessions.set(name, sandbox)
1464
1623
  return {
@@ -1466,7 +1625,10 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1466
1625
  ref: name,
1467
1626
  path: VERCEL_WORKSPACE_PATH,
1468
1627
  branch: opts.branch,
1469
- base: { source: existing === null ? 'remote' : 'existing', sha: base },
1628
+ base: {
1629
+ source: opts.restoration?.length || existing !== null ? 'existing' : 'remote',
1630
+ sha: provisionHead,
1631
+ },
1470
1632
  }
1471
1633
  }
1472
1634
 
@@ -1482,9 +1644,21 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1482
1644
  /** Stop/delete and then prove absence by exact deterministic name — for the
1483
1645
  * sandbox and, because deleting a sandbox never removes the automatic
1484
1646
  * snapshots its sessions created, for its snapshot storage too. */
1485
- private async reap(ref: string): Promise<WorkspaceReapOutcome> {
1486
- let sandbox = this.sessions.get(ref) ?? (await this.facade.get(ref, this.operationSignal()))
1647
+ private async reap(ref: string, dispatcherAuthorized = false): Promise<WorkspaceReapOutcome> {
1648
+ let sandbox: VercelSandboxHandle | null
1649
+ try {
1650
+ sandbox = this.sessions.get(ref) ?? (await this.facade.get(ref, this.operationSignal()))
1651
+ } catch (error) {
1652
+ if (!isMissingVercelSandbox(error)) throw error
1653
+ sandbox = null
1654
+ }
1487
1655
  if (sandbox === null) {
1656
+ // A snapshot-unavailable lookup also leaves a stale name reservation.
1657
+ if (dispatcherAuthorized) {
1658
+ if (!this.facade.deleteByName)
1659
+ throw new Error('sandbox facade lacks dispatcher-authorized deleteByName')
1660
+ await this.facade.deleteByName(ref, this.operationSignal())
1661
+ }
1488
1662
  // An environment can vanish without its snapshots; the purge still
1489
1663
  // applies and only a confirmed empty list may forget the reference.
1490
1664
  try {
@@ -1508,7 +1682,11 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1508
1682
  // name filter is unambiguous, and after the explicit stop no new
1509
1683
  // snapshot can be created.
1510
1684
  const purged = await this.purgeOrRetryable(ref)
1511
- await sandbox.delete({ signal: this.operationSignal() })
1685
+ if (dispatcherAuthorized) {
1686
+ if (!this.facade.deleteByName)
1687
+ throw new Error('sandbox facade lacks dispatcher-authorized deleteByName')
1688
+ await this.facade.deleteByName(ref, this.operationSignal())
1689
+ } else await sandbox.delete({ signal: this.operationSignal() })
1512
1690
  sandbox = await this.facade.get(ref, this.operationSignal())
1513
1691
  if (sandbox !== null)
1514
1692
  throw new Error(`sandbox ${ref} still exists after delete acknowledgement`)
@@ -1566,8 +1744,13 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1566
1744
 
1567
1745
  private billingPolicy(base: NetworkPolicy, ref?: string): NetworkPolicy {
1568
1746
  if (ref?.startsWith('autobuild-sandbox-')) return base
1569
- const result = accountPolicy(base, this.options.accounts?.() ?? {}, this.options.env)
1570
- if (result.missing.length) throw new Error(`Missing credentials: ${result.missing.join('; ')}`)
1747
+ const accounts = this.options.accounts?.() ?? {}
1748
+ const required = this.options.executionAccounts?.() ?? accounts
1749
+ const result = accountPolicy(base, accounts, this.options.env, required)
1750
+ if (result.missing.length)
1751
+ throw new MissingAccountCredentialsError(
1752
+ missingAccountCredentials(required, this.options.env),
1753
+ )
1571
1754
  return result.policy
1572
1755
  }
1573
1756
 
@@ -1621,8 +1804,8 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1621
1804
  // reuse paths do: a guest installed by an older dispatcher — including one
1622
1805
  // stranded by a protocol-only bump or a missing/unreadable marker — is
1623
1806
  // refreshed before the runner starts, or the hosted store would 409 its
1624
- // heartbeat and the build would strand. Refresh failure deletes the
1625
- // sandbox so the next pass rematerializes it cleanly.
1807
+ // heartbeat and the build would strand. Refresh failure retains the
1808
+ // sandbox for dispatcher-owned preservation and cleanup.
1626
1809
  const distributionIdentity = await this.identityStamp()
1627
1810
  const installed = await readDistributionVersionMarker(sandbox, this.operationSignal())
1628
1811
  if (installed !== distributionIdentity) {
@@ -1630,16 +1813,10 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1630
1813
  const archive = await this.archiveBytes()
1631
1814
  await installDistribution(sandbox, archive, distributionIdentity, this.operationSignal())
1632
1815
  } catch (error) {
1633
- try {
1634
- this.sessions.set(ref, sandbox)
1635
- await this.reap(ref)
1636
- } catch (deleteError) {
1637
- throw new AggregateError(
1638
- [error, deleteError],
1639
- `sandbox ${ref} distribution refresh failed and its incomplete environment could not be confirmed deleted`,
1640
- )
1641
- }
1642
- throw error
1816
+ throw new WorkspaceCleanupRequired(
1817
+ { provider: this.name, ref, path: VERCEL_WORKSPACE_PATH, branch: `ab/${input.slug}` },
1818
+ error,
1819
+ )
1643
1820
  }
1644
1821
  }
1645
1822
  await preflightBun(sandbox, this.options.config.image)
@@ -2052,7 +2229,12 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2052
2229
  ? undefined
2053
2230
  : `Basic ${Buffer.from(`${requireVercelEnvironmentValue(this.options.env, this.options.config.gitUsernameEnv!)}:${requireVercelEnvironmentValue(this.options.env, this.options.config.gitPasswordEnv)}`).toString('base64')}`,
2054
2231
  )
2055
- const refreshed = accountPolicy(base, accounts, this.options.env)
2232
+ const refreshed = accountPolicy(
2233
+ base,
2234
+ accounts,
2235
+ this.options.env,
2236
+ this.options.executionAccounts?.() ?? accounts,
2237
+ )
2056
2238
  try {
2057
2239
  await sandbox.update(
2058
2240
  { networkPolicy: refreshed.policy },
@@ -2643,6 +2825,72 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2643
2825
  return head === input.sha
2644
2826
  }
2645
2827
 
2828
+ private async withTrustedGit<T>(
2829
+ sandbox: VercelSandboxHandle,
2830
+ ref: string,
2831
+ effect: (exec: Exec) => Promise<T>,
2832
+ ): Promise<T> {
2833
+ const { origin } = await this.normalNetworkPolicy(ref)
2834
+ const token = this.options.env.GITHUB_TOKEN || this.options.env.GH_TOKEN
2835
+ if (!token) throw new Error('workspace preservation requires GITHUB_TOKEN or GH_TOKEN')
2836
+ const authorization = `Basic ${Buffer.from(`x-access-token:${token}`).toString('base64')}`
2837
+ const policy: NetworkPolicy = {
2838
+ allow: {
2839
+ [origin.host]: [
2840
+ {
2841
+ match: {
2842
+ method: ['GET'],
2843
+ path: { exact: `${origin.path}/info/refs` },
2844
+ queryString: [
2845
+ { key: { exact: 'service' }, value: { regex: '^git-(receive|upload)-pack$' } },
2846
+ ],
2847
+ },
2848
+ transform: [{ headers: { authorization } }],
2849
+ },
2850
+ {
2851
+ match: {
2852
+ method: ['POST'],
2853
+ path: {
2854
+ regex: `^${origin.path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/git-(receive|upload)-pack$`,
2855
+ },
2856
+ },
2857
+ transform: [{ headers: { authorization } }],
2858
+ },
2859
+ ],
2860
+ },
2861
+ }
2862
+ try {
2863
+ await sandbox.update(
2864
+ { networkPolicy: this.billingPolicy(policy, ref) },
2865
+ { signal: this.operationSignal() },
2866
+ )
2867
+ return await effect(async (cmd) => {
2868
+ const result = await sandbox.runCommand({
2869
+ cmd: cmd[0]!,
2870
+ args: cmd.slice(1),
2871
+ cwd: VERCEL_WORKSPACE_PATH,
2872
+ signal: this.operationSignal(),
2873
+ })
2874
+ if (!('stdout' in result) || !('stderr' in result) || result.exitCode === null)
2875
+ throw new Error('trusted preservation requires captured command output')
2876
+ return {
2877
+ exitCode: result.exitCode,
2878
+ stdout: await result.stdout!(),
2879
+ stderr: await result.stderr!(),
2880
+ }
2881
+ })
2882
+ } finally {
2883
+ try {
2884
+ await sandbox.update(
2885
+ { networkPolicy: (await this.normalNetworkPolicy(ref)).policy },
2886
+ { signal: this.operationSignal() },
2887
+ )
2888
+ } finally {
2889
+ await sandbox.stop({ signal: this.operationSignal() })
2890
+ }
2891
+ }
2892
+ }
2893
+
2646
2894
  private async publish(
2647
2895
  input: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0],
2648
2896
  ): Promise<import('../types').RewriteResult>