@defrex/autobuild 1.11.1 → 1.12.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 (102) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +177 -54
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +66 -6
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +13 -11
  7. package/docs/dispatcher.md +1 -1
  8. package/docs/integration-tree.md +28 -16
  9. package/docs/operator-api.md +4 -4
  10. package/docs/operator-surfaces.md +35 -0
  11. package/docs/optimization-nodes.md +3 -2
  12. package/docs/tickets.md +1 -1
  13. package/docs/troubleshooting.md +1 -1
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/ambient-errors.ts +17 -0
  16. package/packages/core/src/cli/bounded-io.ts +174 -0
  17. package/packages/core/src/cli/dashboard/model.ts +81 -23
  18. package/packages/core/src/cli/dashboard/poll.ts +20 -31
  19. package/packages/core/src/cli/dashboard/render.ts +14 -37
  20. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  21. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  22. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  23. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  24. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  25. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  26. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  27. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  28. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  29. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  30. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  31. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  32. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  33. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  34. package/packages/core/src/cli/dispatch.ts +68 -5
  35. package/packages/core/src/cli/env.ts +2 -15
  36. package/packages/core/src/cli/help.ts +5 -4
  37. package/packages/core/src/cli/main.ts +4 -2
  38. package/packages/core/src/cli/production-store.ts +102 -0
  39. package/packages/core/src/cli/repo-state.ts +2 -3
  40. package/packages/core/src/cli/repository-status.ts +28 -22
  41. package/packages/core/src/cli/sessionless-store.ts +26 -0
  42. package/packages/core/src/cli/status.ts +169 -40
  43. package/packages/core/src/cli/store-opening.ts +15 -58
  44. package/packages/core/src/cli/store-ref.ts +6 -1
  45. package/packages/core/src/config/schema.ts +1 -1
  46. package/packages/core/src/distribution-packaging.ts +156 -18
  47. package/packages/core/src/events/catalog-identity.ts +28 -0
  48. package/packages/core/src/events/catalog.ts +3 -9
  49. package/packages/core/src/events/compatibility.ts +2 -30
  50. package/packages/core/src/events/payloads.ts +11 -0
  51. package/packages/core/src/events/policy.ts +3 -0
  52. package/packages/core/src/events/repository.ts +1 -1
  53. package/packages/core/src/events/sessions.ts +1 -1
  54. package/packages/core/src/events/validation-error.ts +12 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +9 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  59. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  60. package/packages/core/src/kernel/capacity-build.ts +21 -0
  61. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  63. package/packages/core/src/kernel/engine.ts +2 -8
  64. package/packages/core/src/kernel/measurement.ts +24 -0
  65. package/packages/core/src/kernel/read-facts.ts +8 -370
  66. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  67. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  68. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  69. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  70. package/packages/core/src/kernel/reducer.ts +57 -9
  71. package/packages/core/src/kernel/reopen-state.ts +10 -0
  72. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  73. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  74. package/packages/core/src/operator/presentation.ts +13 -0
  75. package/packages/core/src/operator/query.ts +40 -39
  76. package/packages/core/src/operator/registry.ts +3 -3
  77. package/packages/core/src/ports/workspace/fake.ts +15 -3
  78. package/packages/core/src/processes/dispatcher.ts +232 -75
  79. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  80. package/packages/core/src/store/local/capabilities.ts +115 -0
  81. package/packages/core/src/store/local/store.ts +86 -56
  82. package/packages/core/src/store/reduced-reads.ts +9 -1
  83. package/packages/core/src/store/reducer-value-read.ts +235 -0
  84. package/packages/core/src/store/reducer-value-shapes.json +1437 -1349
  85. package/packages/core/src/store/reducer-values.ts +36 -204
  86. package/packages/core/src/store/remote/released-clients.json +11 -0
  87. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  88. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  89. package/packages/core/src/store/rollup-lease.ts +41 -0
  90. package/packages/core/src/store/rollups.ts +7 -38
  91. package/packages/core/src/store/snapshots.ts +1 -1
  92. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  93. package/packages/core/src/testing/import-graph.ts +78 -0
  94. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  95. package/packages/core/src/testing/slot-agreement.ts +52 -0
  96. package/packages/core/src/web/assets/app.js +5 -5
  97. package/skills/guide/SKILL.md +115 -44
  98. package/skills/guide/references/integration-tree.md +28 -16
  99. package/skills/guide/references/operator-api.md +4 -4
  100. package/skills/guide/references/optimization-nodes.md +3 -2
  101. package/skills/operate/SKILL.md +38 -20
  102. package/templates/hosted-service/package.json +2 -2
@@ -190,6 +190,10 @@ export interface UpgradeProjection {
190
190
  accepted?: boolean
191
191
  successor?: string
192
192
  released?: boolean
193
+ /** The active run's detected upgrade correlation while it has no prepared
194
+ * target, failure, request or handoff yet. Advisory scheduling input for
195
+ * the launcher's observation cadence only, never a lifecycle decision. */
196
+ preparing?: string
193
197
  }
194
198
  export interface UpgradeCondition {
195
199
  version: 1
@@ -252,6 +256,7 @@ function validUpgradeProjection(value: unknown): value is UpgradeProjection {
252
256
  (p.rollbackVersion === undefined || p.rollbackVersion === 1) &&
253
257
  (p.takeoverAt === undefined || typeof p.takeoverAt === 'string') &&
254
258
  (p.successor === undefined || typeof p.successor === 'string') &&
259
+ (p.preparing === undefined || (typeof p.preparing === 'string' && p.preparing.length > 0)) &&
255
260
  (p.journal === undefined ||
256
261
  (!!p.journal && typeof p.journal.storeRef === 'string' && typeof p.journal.repo === 'string'))
257
262
  )
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Launcher supervision pacing. The launcher observes durable upgrade state
3
+ * through runtime-owned readers between pauses; this module only decides how
4
+ * long each pause lasts and how it ends. It has no imports, so it keeps the
5
+ * launcher's filesystem/process-only import graph.
6
+ */
7
+
8
+ /** Ordinary supervision while no successor is pending. */
9
+ export const SUPERVISION_IDLE_MS = 1_000
10
+ /** Supervision while a successor preflight is pending. */
11
+ export const SUPERVISION_PENDING_MS = 250
12
+ /** Temporary cadence while the active run's detected upgrade is unresolved. */
13
+ export const PREPARATION_OBSERVATION_MS = 50
14
+ /** Fast observations allowed per detection correlation before idle cadence. */
15
+ export const PREPARATION_OBSERVATION_LIMIT = 600
16
+
17
+ /**
18
+ * Returns the delay before the next observation. A durably detected,
19
+ * unresolved preparation (`preparing`, an advisory reader field) earns at most
20
+ * `PREPARATION_OBSERVATION_LIMIT` fast observations per correlation. The
21
+ * budget resets only when a different correlation appears, so a stalled
22
+ * preparation returns to the idle cadence for good. Readers that omit the
23
+ * field keep the ordinary cadence.
24
+ */
25
+ export function supervisionCadence() {
26
+ let correlation: string | undefined
27
+ let observed = 0
28
+ return (projection: { preparing?: string }, pending: boolean): number => {
29
+ if (pending) return SUPERVISION_PENDING_MS
30
+ const preparing = projection.preparing
31
+ if (typeof preparing !== 'string') return SUPERVISION_IDLE_MS
32
+ if (preparing !== correlation) {
33
+ correlation = preparing
34
+ observed = 0
35
+ }
36
+ if (observed >= PREPARATION_OBSERVATION_LIMIT) return SUPERVISION_IDLE_MS
37
+ observed++
38
+ return PREPARATION_OBSERVATION_MS
39
+ }
40
+ }
41
+
42
+ interface PauseTimers {
43
+ setTimeout(callback: () => void, ms: number): unknown
44
+ clearTimeout(timer: unknown): void
45
+ }
46
+ const realTimers: PauseTimers = {
47
+ setTimeout: (callback, ms) => setTimeout(callback, ms),
48
+ clearTimeout: (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),
49
+ }
50
+
51
+ /**
52
+ * Waits `delay` ms, or until any wakeup settles, or until `signal` aborts
53
+ * (immediately when it already has). The timer and abort listener are always
54
+ * released.
55
+ */
56
+ export async function supervisionPause(
57
+ delay: number,
58
+ wakeups: Promise<unknown>[],
59
+ signal: Pick<AbortSignal, 'aborted' | 'addEventListener' | 'removeEventListener'>,
60
+ timers: PauseTimers = realTimers,
61
+ ): Promise<void> {
62
+ if (signal.aborted) return
63
+ let timer: unknown
64
+ let onAbort: (() => void) | undefined
65
+ try {
66
+ await Promise.race([
67
+ new Promise<void>((resolve) => {
68
+ timer = timers.setTimeout(resolve, delay)
69
+ }),
70
+ new Promise<void>((resolve) => {
71
+ onAbort = resolve
72
+ signal.addEventListener('abort', onAbort)
73
+ }),
74
+ ...wakeups,
75
+ ])
76
+ } finally {
77
+ timers.clearTimeout(timer)
78
+ if (onAbort) signal.removeEventListener('abort', onAbort)
79
+ }
80
+ }
@@ -14,6 +14,7 @@ import {
14
14
  restoreLauncherTerminal,
15
15
  } from './dispatch-launch-stop'
16
16
  import { watchPresentationJob } from './dispatch-presentation-job'
17
+ import { supervisionCadence, supervisionPause } from './dispatch-launcher-cadence'
17
18
  import { dirname, basename, resolve, join } from 'node:path'
18
19
  import { randomUUID } from 'node:crypto'
19
20
  import { distributionRoot } from '../distribution'
@@ -334,6 +335,7 @@ export async function launchDispatcher(launchArgv: string[]): Promise<number> {
334
335
  bootstrap.rollbackVersion === 1,
335
336
  )
336
337
  const readerFailures = generationReaderFailures((message) => console.error(message))
338
+ const cadence = supervisionCadence()
337
339
  for (;;) {
338
340
  if (signal) break
339
341
  // Once recovery has expired, a failed child must retain its ordinary
@@ -361,6 +363,7 @@ export async function launchDispatcher(launchArgv: string[]): Promise<number> {
361
363
  successor?: string
362
364
  accepted?: boolean
363
365
  released?: boolean
366
+ preparing?: string
364
367
  }
365
368
  try {
366
369
  projection = await upgradeReader(active)
@@ -571,18 +574,14 @@ export async function launchDispatcher(launchArgv: string[]): Promise<number> {
571
574
  if (record !== active && record !== pending?.record && record.result)
572
575
  children.delete(record)
573
576
  pruneRuntimes(dirname(dirname(runtime.root)))
574
- let timer: ReturnType<typeof setTimeout> | undefined
575
- try {
576
- await Promise.race([
577
- new Promise<void>((resolve) => {
578
- timer = setTimeout(resolve, pending ? 250 : 1_000)
579
- }),
577
+ await supervisionPause(
578
+ cadence(projection, !!pending),
579
+ [
580
580
  ...(!active.result ? [active.exited] : []),
581
581
  ...(pending && !pending.record.result ? [pending.record.exited] : []),
582
- ])
583
- } finally {
584
- clearTimeout(timer)
585
- }
582
+ ],
583
+ stopping.signal,
584
+ )
586
585
  }
587
586
  } catch (error) {
588
587
  if (!signal) throw error
@@ -210,10 +210,19 @@ async function runGenerationPreflight(
210
210
  prepared = true
211
211
  // The successor claims with its own configured lease timeout.
212
212
  let leaseTtlMs = 60_000
213
+ const { observeSuccessorRelease, releaseObservationCadence } = await import(
214
+ './dispatch-release-observer'
215
+ )
216
+ const { supervisionPause } = await import('./dispatch-launcher-cadence')
217
+ const cadence = releaseObservationCadence()
213
218
  for (;;) {
214
219
  signal.throwIfAborted()
215
- const current = (await readDispatchUpgrade(opened.store, opened.repo)).value.runs[handoff.run]
216
- const facts = (await readDispatcherRunFacts(opened.store, opened.repo, handoff.run)).value
220
+ const started = performance.now()
221
+ const { current, facts } = await observeSuccessorRelease(
222
+ opened.store,
223
+ opened.repo,
224
+ handoff.run,
225
+ )
217
226
  if (facts.stopRequest || current?.failure) return false
218
227
  if (facts.stop && !current?.handoff) return false
219
228
  if (
@@ -257,7 +266,7 @@ async function runGenerationPreflight(
257
266
  })
258
267
  return true
259
268
  }
260
- await new Promise<void>((resolve) => setTimeout(resolve, 500))
269
+ await supervisionPause(cadence(performance.now() - started), [], signal)
261
270
  }
262
271
  } finally {
263
272
  await opened.store.close()
@@ -0,0 +1,53 @@
1
+ import { readDispatcherRunFacts, readDispatchUpgrade } from '../store/reduced-reads'
2
+ import type { BuildStore } from '../store/types'
3
+
4
+ /** Pause between the successor's post-yield observations during the fast
5
+ * window. Each observation is the two canonical reduced reads of
6
+ * `observeSuccessorRelease`, which read zero event rows while nothing changed,
7
+ * so a step costs the same at any journal length. */
8
+ export const RELEASE_OBSERVATION_FAST_MS = 25
9
+
10
+ /** Observations of one preflight that use the fast pause: at least six seconds
11
+ * of sleep, which covers a drain-mode release with wide margin. Later
12
+ * observations back off, so the fast observations per handoff are finite. */
13
+ export const RELEASE_OBSERVATION_FAST_LIMIT = 240
14
+
15
+ /** Steady pause after the backoff, for slow drains and for cutovers waiting on
16
+ * the predecessor's stop: two observations per second until takeover, stop,
17
+ * failure, abort or preflight's deadline. */
18
+ export const RELEASE_OBSERVATION_IDLE_MS = 500
19
+
20
+ /** Pause schedule of one preflight's release observation. Each call takes how
21
+ * long the last observation took and returns the next pause: the fast pause
22
+ * for the first `RELEASE_OBSERVATION_FAST_LIMIT` calls, then doubling to the
23
+ * idle pause and staying there. A pause is never shorter than the last
24
+ * observation, so a slow or struggling store is never queried back-to-back. */
25
+ export function releaseObservationCadence(): (lastObservationMs: number) => number {
26
+ let calls = 0
27
+ return (lastObservationMs) => {
28
+ calls++
29
+ const floor =
30
+ Number.isFinite(lastObservationMs) && lastObservationMs > 0 ? lastObservationMs : 0
31
+ const over = calls - RELEASE_OBSERVATION_FAST_LIMIT
32
+ const scheduled =
33
+ over <= 0
34
+ ? RELEASE_OBSERVATION_FAST_MS
35
+ : RELEASE_OBSERVATION_FAST_MS * 2 ** over >= RELEASE_OBSERVATION_IDLE_MS
36
+ ? RELEASE_OBSERVATION_IDLE_MS
37
+ : RELEASE_OBSERVATION_FAST_MS * 2 ** over
38
+ return Math.max(scheduled, floor)
39
+ }
40
+ }
41
+
42
+ /** One observation step: the predecessor run's durable upgrade state, then its
43
+ * run facts, in that order. Exactly these reduced reads, no event rows while
44
+ * nothing changed. The caller validates every fact itself. */
45
+ export async function observeSuccessorRelease(
46
+ store: Pick<BuildStore, 'getReducerValue'>,
47
+ repo: string,
48
+ run: string,
49
+ ) {
50
+ const current = (await readDispatchUpgrade(store, repo)).value.runs[run]
51
+ const facts = (await readDispatcherRunFacts(store, repo, run)).value
52
+ return { current, facts }
53
+ }
@@ -5,7 +5,6 @@ import {
5
5
  ownCachedRuntime,
6
6
  } from './dispatch-runtime-use'
7
7
  import {
8
- cp,
9
8
  stat,
10
9
  mkdir,
11
10
  mkdtemp,
@@ -15,16 +14,22 @@ import {
15
14
  writeFile,
16
15
  chmod,
17
16
  realpath,
17
+ symlink,
18
18
  } from 'node:fs/promises'
19
- import { dirname, join, resolve } from 'node:path'
20
- import { packageDistribution } from '../distribution-packaging'
19
+ import { dirname, join, relative, resolve } from 'node:path'
20
+ import { packageDistribution, RUNTIME_ARCHIVE_GZIP_LEVEL } from '../distribution-packaging'
21
+ import { settleInOrder, withSpeculation } from './bounded-io'
21
22
  import {
23
+ assertTreeUnchanged,
22
24
  copyDependencies,
23
25
  copySnapshotTree,
26
+ copyTreeVerbatim,
24
27
  excludedSnapshotNames,
25
28
  inside,
26
29
  readManifest,
27
30
  scanDependencies,
31
+ sealTreeWitness,
32
+ type TreeWitness,
28
33
  treeDigest,
29
34
  } from './dispatch-runtime-dependencies'
30
35
 
@@ -307,11 +312,16 @@ export async function validateRuntime(runtime: CachedRuntime): Promise<void> {
307
312
  throw new Error(`corrupt guest archive: ${runtime.root}`)
308
313
  }
309
314
 
310
- async function validateRuntimeImports(root: string, checkout: string): Promise<void> {
315
+ async function validateRuntimeImports(
316
+ root: string,
317
+ checkout: string,
318
+ signal?: AbortSignal,
319
+ ): Promise<void> {
311
320
  const probe = Bun.spawn(runtimeSpawnArguments(root, join(root, 'bin/ab.ts'), ['--version']), {
312
321
  cwd: checkout,
313
322
  stdout: 'pipe',
314
323
  stderr: 'pipe',
324
+ signal,
315
325
  })
316
326
  const [code, stderr] = await Promise.all([
317
327
  probe.exited,
@@ -346,103 +356,215 @@ function fetchGuestArchive(
346
356
  return pending
347
357
  }
348
358
 
359
+ /** Verifies the content-addressed dependency layer for `graph`, building and
360
+ * publishing it under the cache lock when absent. Returns its path. */
361
+ async function acquireLayer(
362
+ cache: string,
363
+ stage: string,
364
+ graph: Awaited<ReturnType<typeof scanDependencies>>,
365
+ ): Promise<string> {
366
+ const layers = join(cache, 'layers')
367
+ await mkdir(layers, { recursive: true })
368
+ const layer = join(layers, graph.fingerprint)
369
+ const layerStage = join(stage, 'layer')
370
+ try {
371
+ const expected = await readFile(join(layer, 'digest'), 'utf8')
372
+ if ((await readFile(join(layer, 'distribution', 'tsconfig.json'), 'utf8')) !== RUNTIME_CONFIG)
373
+ throw new Error(`corrupt dependency compiler boundary: ${layer}`)
374
+ if ((await treeDigest(join(layer, 'distribution'))) !== expected)
375
+ throw new Error(`corrupt dependency layer: ${layer}`)
376
+ } catch (error) {
377
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
378
+ if (existsSync(layer)) throw new Error(`corrupt dependency layer: ${layer}`, { cause: error })
379
+ await mkdir(join(layerStage, 'distribution'), { recursive: true })
380
+ await copyDependencies(graph, join(layerStage, 'distribution'))
381
+ await writeFile(join(layerStage, 'distribution', 'tsconfig.json'), RUNTIME_CONFIG)
382
+ await writeFile(join(layerStage, 'digest'), await treeDigest(join(layerStage, 'distribution')))
383
+ withCacheLock(cache, () => {
384
+ if (!existsSync(layer)) renameSync(layerStage, layer)
385
+ })
386
+ }
387
+ await rm(layerStage, { recursive: true, force: true })
388
+ return layer
389
+ }
390
+
391
+ type PreparedArchive =
392
+ | { kind: 'reuse'; id: string; reusable: CachedRuntime }
393
+ | {
394
+ kind: 'fresh'
395
+ id: string
396
+ destination: string
397
+ digest: string
398
+ archive: Uint8Array
399
+ archiveDigest: string
400
+ }
401
+
402
+ /** Round-trips the distribution archive: extracts it, checks its compiler
403
+ * boundary, entries and configs, links the stage-private verified dependency
404
+ * snapshot beside it and runs a real import probe against the result. The link
405
+ * lives outside the published root and is removed with the extracted tree;
406
+ * `prepareRuntime` proves the shared snapshot unchanged before publication. */
407
+ async function verifyArchive(
408
+ root: string,
409
+ stage: string,
410
+ checkout: string,
411
+ takeArchive: () => Promise<Uint8Array>,
412
+ signal: AbortSignal,
413
+ ): Promise<{ archive: Uint8Array; archiveDigest: string }> {
414
+ const extracted = join(stage, 'archive-check')
415
+ const archive = await takeArchive()
416
+ signal.throwIfAborted()
417
+ const archiveDigest = new Bun.CryptoHasher('sha256').update(archive).digest('hex')
418
+ await mkdir(extracted)
419
+ const archiveFile = join(stage, 'distribution.tgz')
420
+ await writeFile(archiveFile, archive)
421
+ const unpack = Bun.spawn(['tar', '-xzf', archiveFile, '--strip-components=1', '-C', extracted], {
422
+ stdout: 'ignore',
423
+ stderr: 'pipe',
424
+ signal,
425
+ })
426
+ const unpackError = await new Response(unpack.stderr).text()
427
+ if (
428
+ (await unpack.exited) !== 0 ||
429
+ (await readFile(join(extracted, 'tsconfig.json'), 'utf8')) !== RUNTIME_CONFIG
430
+ )
431
+ throw new Error(`runtime archive lost compiler boundary: ${unpackError}`)
432
+ await validateEntries(extracted)
433
+ await validateCoreConfigs(extracted)
434
+ signal.throwIfAborted()
435
+ // Archived dependencies would shadow the snapshot's verified copy.
436
+ if (existsSync(join(extracted, 'node_modules')))
437
+ throw new Error('runtime archive must not contain node_modules')
438
+ await symlink(relative(extracted, join(root, 'node_modules')), join(extracted, 'node_modules'))
439
+ await validateRuntimeImports(extracted, checkout, signal)
440
+ await rm(extracted, { recursive: true })
441
+ return { archive, archiveDigest }
442
+ }
443
+
444
+ /** Digests the completed snapshot and reuses a matching runtime, or else
445
+ * requires the archive round trip. That round trip runs speculatively beside
446
+ * the digest, is aborted on reuse, and is awaited before this settles. */
447
+ async function prepareArchive(
448
+ root: string,
449
+ stage: string,
450
+ cache: string,
451
+ checkout: string,
452
+ guest: { provenance: 'source' | 'registry' },
453
+ takeArchive: () => Promise<Uint8Array>,
454
+ ): Promise<PreparedArchive> {
455
+ return withSpeculation(
456
+ (signal) => verifyArchive(root, stage, checkout, takeArchive, signal),
457
+ async (takeVerified): Promise<PreparedArchive> => {
458
+ const digest = await treeDigest(root)
459
+ const manifest = await readManifest(root)
460
+ const id = `${String(manifest.version).replace(/[^\w.-]/g, '_')}-${guest.provenance}-guest1-${digest}`
461
+ const destination = join(cache, id)
462
+ const reusable = await cachedRuntime(join(destination, 'distribution'))
463
+ if (reusable) return { kind: 'reuse', id, reusable }
464
+ return { kind: 'fresh', id, destination, digest, ...(await takeVerified()) }
465
+ },
466
+ )
467
+ }
468
+
349
469
  export async function prepareRuntime(
350
470
  source: string,
351
471
  checkout: string,
352
472
  publication?: { upgradeKey: string; commit: string },
353
473
  guest: {
354
474
  provenance: 'source' | 'registry'
475
+ /** Refuse any production dependency that resolves outside `source`. */
476
+ containDependencies?: boolean
355
477
  } = { provenance: 'source' },
356
478
  ): Promise<CachedRuntime> {
357
479
  source = await realpath(source)
480
+ const scan = async () => {
481
+ const graph = await scanDependencies(source)
482
+ if (guest.containDependencies)
483
+ for (const entry of graph.packages)
484
+ if (!inside(source, entry.source))
485
+ throw new Error(
486
+ `installed dependency ${entry.manifest.name ?? 'unnamed'} resolves outside the prepared source; retry dispatch`,
487
+ )
488
+ return graph
489
+ }
358
490
  checkout = await realpath(checkout)
359
491
  const cache = join(checkout, '.autobuild', 'runtime')
360
492
  await mkdir(cache, { recursive: true })
361
493
  const stage = await mkdtemp(join(cache, '.preparing-'))
362
494
  const root = join(stage, 'distribution')
363
- try {
364
- const graph = await scanDependencies(source)
365
- await stageCode(source, root)
366
- const codeDigest = await treeDigest(root)
367
- const check = join(stage, 'source-check')
495
+ const check = join(stage, 'source-check')
496
+ const recheckSource = async (codeDigest: string): Promise<void> => {
368
497
  await stageCode(source, check)
369
498
  if ((await treeDigest(check)) !== codeDigest)
370
499
  throw new Error('Autobuild source changed while preparing runtime; retry dispatch')
371
500
  await rm(check, { recursive: true })
372
- const layers = join(cache, 'layers')
373
- await mkdir(layers, { recursive: true })
374
- const layer = join(layers, graph.fingerprint)
375
- const layerStage = join(stage, 'layer')
376
- try {
377
- const expected = await readFile(join(layer, 'digest'), 'utf8')
378
- if ((await readFile(join(layer, 'distribution', 'tsconfig.json'), 'utf8')) !== RUNTIME_CONFIG)
379
- throw new Error(`corrupt dependency compiler boundary: ${layer}`)
380
- if ((await treeDigest(join(layer, 'distribution'))) !== expected)
381
- throw new Error(`corrupt dependency layer: ${layer}`)
382
- } catch (error) {
383
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
384
- if (existsSync(layer)) throw new Error(`corrupt dependency layer: ${layer}`, { cause: error })
385
- await mkdir(join(layerStage, 'distribution'), { recursive: true })
386
- await copyDependencies(graph, join(layerStage, 'distribution'))
387
- await writeFile(join(layerStage, 'distribution', 'tsconfig.json'), RUNTIME_CONFIG)
388
- await writeFile(
389
- join(layerStage, 'digest'),
390
- await treeDigest(join(layerStage, 'distribution')),
391
- )
392
- withCacheLock(cache, () => {
393
- if (!existsSync(layer)) renameSync(layerStage, layer)
394
- })
395
- }
396
- await rm(layerStage, { recursive: true, force: true })
397
- await cp(join(layer, 'distribution', 'node_modules'), join(root, 'node_modules'), {
398
- recursive: true,
399
- verbatimSymlinks: true,
400
- })
401
- await validateEntries(root)
402
- await validateCoreConfigs(root)
403
- if ((await scanDependencies(source)).fingerprint !== graph.fingerprint)
404
- throw new Error('installed dependencies changed while preparing runtime; retry dispatch')
405
- await stageCode(source, check)
406
- if ((await treeDigest(check)) !== codeDigest)
407
- throw new Error('Autobuild source changed while preparing runtime; retry dispatch')
408
- await rm(check, { recursive: true })
409
- // Real Bun import graph validation uses the same pre-entry compiler boundary
410
- // as every generation and runner. No automatic installer can run here.
411
- await validateRuntimeImports(root, checkout)
412
- const digest = await treeDigest(root)
413
- const manifest = await readManifest(root)
414
- const id = `${String(manifest.version).replace(/[^\w.-]/g, '_')}-${guest.provenance}-guest1-${digest}`
415
- const destination = join(cache, id)
416
- const reusable = await cachedRuntime(join(destination, 'distribution'))
417
- if (reusable) {
418
- reservePreparedRuntime(cache, id)
419
- await validateRuntime(reusable)
420
- return reusable
421
- }
422
- const archive = await packageDistribution(root)
423
- const archiveDigest = new Bun.CryptoHasher('sha256').update(archive).digest('hex')
424
- const extracted = join(stage, 'archive-check')
425
- await mkdir(extracted)
426
- const archiveFile = join(stage, 'distribution.tgz')
427
- await writeFile(archiveFile, archive)
428
- const unpack = Bun.spawn(
429
- ['tar', '-xzf', archiveFile, '--strip-components=1', '-C', extracted],
430
- { stdout: 'ignore', stderr: 'pipe' },
431
- )
432
- const unpackError = await new Response(unpack.stderr).text()
433
- if (
434
- (await unpack.exited) !== 0 ||
435
- (await readFile(join(extracted, 'tsconfig.json'), 'utf8')) !== RUNTIME_CONFIG
501
+ }
502
+ try {
503
+ const scanned = scan()
504
+ const staged = stageCode(source, root)
505
+ // Every branch is joined before cleanup or publication, and each join
506
+ // reports failures in the order the stages once ran serially. Packaging
507
+ // reads only the staged code, so it starts as soon as that is complete and
508
+ // is awaited, or aborted and awaited, before anything else proceeds.
509
+ let witness: TreeWitness | undefined
510
+ const { graph, prepared } = await withSpeculation(
511
+ async (signal) => {
512
+ await staged
513
+ signal.throwIfAborted()
514
+ return packageDistribution(root, undefined, signal, undefined, {
515
+ gzipLevel: RUNTIME_ARCHIVE_GZIP_LEVEL,
516
+ })
517
+ },
518
+ async (takeArchive) => {
519
+ const [graph, codeDigest, layer] = await settleInOrder([
520
+ scanned,
521
+ (async () => {
522
+ await staged
523
+ const digest = await treeDigest(root)
524
+ await recheckSource(digest)
525
+ return digest
526
+ })(),
527
+ scanned.then((graph) => acquireLayer(cache, stage, graph)),
528
+ ])
529
+ // Both import probes resolve this one stage-private snapshot. Sealing
530
+ // its witness before any probe starts makes every later change to it
531
+ // observable; publication checks the witness once both have exited.
532
+ witness = await copyTreeVerbatim(
533
+ join(layer, 'distribution', 'node_modules'),
534
+ join(root, 'node_modules'),
535
+ )
536
+ await sealTreeWitness(witness, join(stage, 'dependency-witness'))
537
+ await validateEntries(root)
538
+ await validateCoreConfigs(root)
539
+ // The snapshot is complete. These branches only read it or the source,
540
+ // and nothing is reserved, returned or published until all of them pass.
541
+ const [, , , prepared] = await settleInOrder([
542
+ (async () => {
543
+ if ((await scan()).fingerprint !== graph.fingerprint)
544
+ throw new Error(
545
+ 'installed dependencies changed while preparing runtime; retry dispatch',
546
+ )
547
+ })(),
548
+ recheckSource(codeDigest),
549
+ // Real Bun import graph validation uses the same pre-entry compiler
550
+ // boundary as every generation and runner. No automatic installer
551
+ // can run here.
552
+ validateRuntimeImports(root, checkout),
553
+ prepareArchive(root, stage, cache, checkout, guest, takeArchive),
554
+ ])
555
+ return { graph, prepared }
556
+ },
436
557
  )
437
- throw new Error(`runtime archive lost compiler boundary: ${unpackError}`)
438
- await validateEntries(extracted)
439
- await validateCoreConfigs(extracted)
440
- await cp(join(root, 'node_modules'), join(extracted, 'node_modules'), {
441
- recursive: true,
442
- verbatimSymlinks: true,
443
- })
444
- await validateRuntimeImports(extracted, checkout)
445
- await rm(extracted, { recursive: true })
558
+ if (prepared.kind === 'reuse') {
559
+ reservePreparedRuntime(cache, prepared.id)
560
+ await validateRuntime(prepared.reusable)
561
+ return prepared.reusable
562
+ }
563
+ // Every probe and branch has settled. The published digest describes the
564
+ // snapshot as copied from the verified layer, so refuse it if a probe
565
+ // changed any dependency byte, mode, link or entry since.
566
+ await assertTreeUnchanged(witness!, 'runtime dependency snapshot')
567
+ const { id, destination, digest, archive, archiveDigest } = prepared
446
568
  await writeFile(join(stage, 'distribution.tgz'), archive)
447
569
  const guestArchive: NonNullable<CachedRuntime['guestArchive']> =
448
570
  guest.provenance === 'registry'