@defrex/autobuild 1.0.0-beta.3 → 1.0.0-beta.4

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 (130) hide show
  1. package/SPEC.md +317 -20
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +166 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +87 -2
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +4 -1
  10. package/docs/restacking.md +4 -1
  11. package/docs/setup.md +20 -0
  12. package/docs/spec-standard.md +23 -5
  13. package/package.json +3 -3
  14. package/packages/core/src/cli/artifact.ts +5 -4
  15. package/packages/core/src/cli/attention.ts +2 -0
  16. package/packages/core/src/cli/binary-direct.ts +190 -0
  17. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  18. package/packages/core/src/cli/binary.ts +24 -210
  19. package/packages/core/src/cli/build-control.ts +105 -2
  20. package/packages/core/src/cli/context.ts +41 -1
  21. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  22. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  23. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  24. package/packages/core/src/cli/dashboard/model.ts +34 -10
  25. package/packages/core/src/cli/dashboard/render.ts +24 -2
  26. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  27. package/packages/core/src/cli/dispatch-args.ts +53 -0
  28. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  29. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  30. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  31. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  32. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  33. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  34. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  35. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  36. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  37. package/packages/core/src/cli/dispatch-process.ts +22 -90
  38. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  39. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  40. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  41. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  42. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  43. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  44. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  45. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  46. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  47. package/packages/core/src/cli/dispatch.ts +604 -60
  48. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  49. package/packages/core/src/cli/harvest.ts +28 -11
  50. package/packages/core/src/cli/help.ts +6 -3
  51. package/packages/core/src/cli/installation.ts +5 -3
  52. package/packages/core/src/cli/main-checkout.ts +59 -0
  53. package/packages/core/src/cli/main.ts +15 -45
  54. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  55. package/packages/core/src/cli/repo-state.ts +3 -58
  56. package/packages/core/src/cli/repository-status.ts +67 -3
  57. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  58. package/packages/core/src/cli/status.ts +57 -3
  59. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  60. package/packages/core/src/cli/wait.ts +3 -0
  61. package/packages/core/src/cli/watch.ts +7 -0
  62. package/packages/core/src/config/live.ts +1 -0
  63. package/packages/core/src/config/schema.ts +8 -4
  64. package/packages/core/src/distribution-packaging.ts +116 -0
  65. package/packages/core/src/events/catalog.ts +6 -0
  66. package/packages/core/src/events/payloads.ts +53 -9
  67. package/packages/core/src/events/policy.ts +25 -0
  68. package/packages/core/src/events/repository.ts +184 -4
  69. package/packages/core/src/events/runtime.ts +16 -0
  70. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  71. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  72. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  73. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  74. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  75. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  76. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  77. package/packages/core/src/kernel/harvest.ts +98 -4
  78. package/packages/core/src/kernel/integration-attention.ts +20 -0
  79. package/packages/core/src/kernel/integration-state.ts +80 -11
  80. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  81. package/packages/core/src/kernel/mixed-version.ts +34 -0
  82. package/packages/core/src/kernel/node-polling.ts +160 -0
  83. package/packages/core/src/kernel/read-facts.ts +40 -5
  84. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  85. package/packages/core/src/kernel/reducer.ts +75 -14
  86. package/packages/core/src/kernel/service-facts.ts +11 -4
  87. package/packages/core/src/operator/presentation.ts +7 -0
  88. package/packages/core/src/operator/query.ts +6 -2
  89. package/packages/core/src/operator/registry.ts +1 -1
  90. package/packages/core/src/plugins/load.ts +4 -1
  91. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  92. package/packages/core/src/ports/forge/contract.ts +29 -0
  93. package/packages/core/src/ports/forge/github.ts +189 -61
  94. package/packages/core/src/ports/forge-failure.ts +1 -0
  95. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  96. package/packages/core/src/ports/runner/session-env.ts +1 -0
  97. package/packages/core/src/ports/types.ts +10 -0
  98. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  99. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  100. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  101. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  102. package/packages/core/src/processes/build-child-exit.ts +5 -26
  103. package/packages/core/src/processes/build-runner.ts +81 -11
  104. package/packages/core/src/processes/dispatcher.ts +254 -23
  105. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  106. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  107. package/packages/core/src/processes/execution-settlement.ts +16 -7
  108. package/packages/core/src/processes/harvest-runner.ts +328 -292
  109. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  110. package/packages/core/src/runtime-identity.ts +22 -3
  111. package/packages/core/src/store/contract.ts +153 -0
  112. package/packages/core/src/store/local/store.ts +197 -72
  113. package/packages/core/src/store/reduced-reads.ts +8 -0
  114. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  115. package/packages/core/src/store/remote/client.ts +43 -0
  116. package/packages/core/src/store/repo-state-events.ts +20 -3
  117. package/packages/core/src/store/types.ts +7 -0
  118. package/skills/guide/SKILL.md +231 -23
  119. package/skills/guide/references/integration-tree.md +87 -2
  120. package/skills/guide/references/operator-api.md +53 -4
  121. package/skills/guide/references/plugin-authoring.md +45 -4
  122. package/skills/guide/references/remote-store-protocol.md +4 -1
  123. package/skills/guide/references/restacking.md +4 -1
  124. package/skills/guide/references/setup.md +20 -0
  125. package/skills/guide/references/spec-standard.md +23 -5
  126. package/skills/harvest/SKILL.md +4 -0
  127. package/skills/harvest-review/SKILL.md +4 -0
  128. package/skills/operate/SKILL.md +78 -8
  129. package/skills/spec/SKILL.md +19 -1
  130. package/skills/tickets/SKILL.md +19 -0
@@ -0,0 +1,522 @@
1
+ import { existsSync, renameSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import {
3
+ reservePreparedRuntime,
4
+ mutateRuntimeCache,
5
+ ownCachedRuntime,
6
+ } from './dispatch-runtime-use'
7
+ import {
8
+ cp,
9
+ stat,
10
+ mkdir,
11
+ mkdtemp,
12
+ readFile,
13
+ readdir,
14
+ rm,
15
+ writeFile,
16
+ chmod,
17
+ realpath,
18
+ } from 'node:fs/promises'
19
+ import { dirname, join, resolve } from 'node:path'
20
+ import { packageDistribution } from '../distribution-packaging'
21
+ import {
22
+ copyDependencies,
23
+ copySnapshotTree,
24
+ excludedSnapshotNames,
25
+ inside,
26
+ readManifest,
27
+ scanDependencies,
28
+ treeDigest,
29
+ } from './dispatch-runtime-dependencies'
30
+
31
+ export const RUNTIME_CONFIG = '{}\n'
32
+ const requiredRuntimeEntries = [
33
+ 'bin/ab.ts',
34
+ 'bin/agent/ab',
35
+ 'bin/ab-dispatch-generation.ts',
36
+ 'bin/ab-dispatch-kernel.ts',
37
+ 'bin/ab-build-runner.ts',
38
+ 'bin/ab-harvest-runner.ts',
39
+ 'bin/ab-process-group-reaper.ts',
40
+ ]
41
+ async function validateEntries(root: string): Promise<void> {
42
+ for (const entry of requiredRuntimeEntries) {
43
+ if (!existsSync(join(root, entry)))
44
+ throw new Error(
45
+ `incomplete Autobuild runtime: missing ${entry}; repair the Autobuild installation before dispatch`,
46
+ )
47
+ }
48
+ }
49
+
50
+ export interface CachedRuntime {
51
+ version: 1
52
+ id: string
53
+ root: string
54
+ digest: string
55
+ dependencies: string
56
+ archiveDigest: string
57
+ guestArchive?: {
58
+ provenance: 'source' | 'registry'
59
+ file: 'distribution.tgz' | 'guest-distribution.tgz'
60
+ digest?: string
61
+ }
62
+ }
63
+ export async function cachedRuntime(root: string): Promise<CachedRuntime | undefined> {
64
+ if (!ownCachedRuntime(root)) return undefined
65
+ return JSON.parse(await readFile(join(dirname(root), 'runtime.json'), 'utf8')) as CachedRuntime
66
+ }
67
+ export function runtimeSpawnArguments(
68
+ root: string,
69
+ entrypoint: string,
70
+ args: string[] = [],
71
+ ): string[] {
72
+ // Sync file presence is insufficient provenance; callers use this only for
73
+ // their own completed distribution, whose metadata is checked at startup.
74
+ return [
75
+ process.execPath,
76
+ '--no-install',
77
+ '--tsconfig-override',
78
+ join(root, 'tsconfig.json'),
79
+ entrypoint,
80
+ ...args,
81
+ ]
82
+ }
83
+ export async function validateCoreConfigs(
84
+ root: string,
85
+ paths = ['bin', 'packages'],
86
+ ): Promise<void> {
87
+ const audited = new Set<string>()
88
+ async function audit(file: string): Promise<void> {
89
+ if (audited.has(file)) return
90
+ audited.add(file)
91
+ let config: Record<string, unknown>
92
+ try {
93
+ config = Bun.JSONC.parse(await readFile(file, 'utf8')) as Record<string, unknown>
94
+ } catch {
95
+ throw new Error(`cannot validate runtime compiler configuration: ${file}`)
96
+ }
97
+ const compiler = config.compilerOptions as Record<string, unknown> | undefined
98
+ const base =
99
+ typeof compiler?.baseUrl === 'string'
100
+ ? resolve(dirname(file), compiler.baseUrl)
101
+ : dirname(file)
102
+ if (!inside(root, base))
103
+ throw new Error(`runtime compiler configuration escapes runtime: ${file}`)
104
+ if (existsSync(join(base, '@defrex', 'autobuild')))
105
+ throw new Error(`runtime compiler configuration redirects core imports: ${file}`)
106
+ if (compiler?.paths) {
107
+ for (const [name, targets] of Object.entries(compiler.paths as Record<string, string[]>)) {
108
+ // A second core namespace would split SDK value/class identity.
109
+ const core = '@defrex/autobuild'
110
+ const prefix = name.split('*')[0]!
111
+ const redirectsCore = name.includes('*')
112
+ ? core.startsWith(prefix) || prefix.startsWith(`${core}/`)
113
+ : name === core || name.startsWith(`${core}/`)
114
+ if (redirectsCore)
115
+ throw new Error(`runtime compiler configuration redirects core imports: ${file}`)
116
+ if (
117
+ !Array.isArray(targets) ||
118
+ targets.some(
119
+ (target) => typeof target !== 'string' || !inside(root, resolve(base, target)),
120
+ )
121
+ )
122
+ throw new Error(`runtime compiler configuration escapes runtime: ${file}`)
123
+ }
124
+ }
125
+ const targets = [config.extends].flat().filter((v): v is string => typeof v === 'string')
126
+ for (const reference of (config.references ?? []) as Array<{ path: string }>)
127
+ targets.push(reference.path)
128
+ for (const target of targets) {
129
+ let resolved = resolve(dirname(file), target)
130
+ if (!target.startsWith('.') || !inside(root, resolved))
131
+ throw new Error(`runtime compiler configuration escapes runtime: ${file}: ${target}`)
132
+ try {
133
+ if (!existsSync(resolved) && existsSync(`${resolved}.json`)) resolved += '.json'
134
+ if ((await stat(resolved)).isDirectory()) resolved = join(resolved, 'tsconfig.json')
135
+ if (!inside(root, await realpath(resolved))) throw new Error('external')
136
+ } catch {
137
+ throw new Error(`unresolved runtime compiler configuration: ${file}: ${target}`)
138
+ }
139
+ await audit(resolved)
140
+ }
141
+ }
142
+ async function walk(path: string): Promise<void> {
143
+ for (const item of await readdir(path, { withFileTypes: true })) {
144
+ const file = join(path, item.name)
145
+ if (item.name === 'node_modules') continue
146
+ if (item.isDirectory()) {
147
+ await walk(file)
148
+ continue
149
+ }
150
+ if (!/^(tsconfig|jsconfig)(\.[^.]+)?\.json$/.test(item.name)) continue
151
+ if (item.isSymbolicLink()) throw new Error(`linked compiler configuration: ${file}`)
152
+ await audit(file)
153
+ }
154
+ }
155
+ // Third-party development configs are installed package bytes, never input
156
+ // to this audit. Only Autobuild's sources are governed by this boundary.
157
+ for (const path of paths) {
158
+ try {
159
+ await walk(join(root, path))
160
+ } catch (error) {
161
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
162
+ }
163
+ }
164
+ }
165
+ export const cachedAgentTrampoline = `#!/bin/sh
166
+ case "$0" in
167
+ */*) launcher=$0 ;;
168
+ *) launcher=$(command -v -- "$0") ;;
169
+ esac
170
+ runtime_root=$(CDPATH= cd -- "$(dirname -- "$launcher")/../.." && pwd -P) || exit 1
171
+ exec bun --no-install --tsconfig-override "$runtime_root/tsconfig.json" "$runtime_root/bin/ab.ts" "$@"
172
+ `
173
+
174
+ /** Publication, retention and process-use claims share this short lock. */
175
+ export const withCacheLock = mutateRuntimeCache
176
+
177
+ async function stageCode(source: string, target: string): Promise<void> {
178
+ const manifest = await readManifest(source)
179
+ let bunTag: string | undefined
180
+ try {
181
+ const tag = (await readFile(join(source, '.bun-tag'), 'utf8')).trim()
182
+ const commit = /-([a-f0-9]{7,40})$/i.exec(tag)?.[1]
183
+ if (commit) {
184
+ bunTag = tag
185
+ if (manifest.gitHead === undefined && commit.length === 40) manifest.gitHead = commit
186
+ }
187
+ } catch {
188
+ /* Registry packages need not have a Bun forge tag. */
189
+ }
190
+ if (!Array.isArray(manifest.files))
191
+ throw new Error('Autobuild manifest must declare distribution files')
192
+ await mkdir(target, { recursive: true })
193
+ for (const entry of manifest.files) {
194
+ if (entry.startsWith('!') || entry === 'tsconfig.json') continue
195
+ if (!inside(source, resolve(source, entry)) || excludedSnapshotNames.has(entry))
196
+ throw new Error(`unsafe distribution path: ${entry}`)
197
+ await copySnapshotTree(join(source, entry), join(target, entry), source)
198
+ }
199
+ // Preserve Bun's forge provenance even when the tag only contains an abbreviated SHA.
200
+ if (bunTag) {
201
+ await writeFile(join(target, '.bun-tag'), bunTag)
202
+ if (!manifest.files.includes('.bun-tag')) manifest.files.push('.bun-tag')
203
+ }
204
+ delete manifest.devDependencies
205
+ delete manifest.patchedDependencies
206
+ // Capture provenance while the source still exists; no .git link survives.
207
+ try {
208
+ const git = Bun.spawn(['git', 'rev-parse', 'HEAD'], {
209
+ cwd: source,
210
+ stdout: 'pipe',
211
+ stderr: 'ignore',
212
+ })
213
+ const gitHead = (await new Response(git.stdout).text()).trim()
214
+ if ((await git.exited) === 0) {
215
+ const top = Bun.spawn(['git', 'rev-parse', '--show-toplevel'], {
216
+ cwd: source,
217
+ stdout: 'pipe',
218
+ stderr: 'ignore',
219
+ })
220
+ const topPath = (await new Response(top.stdout).text()).trim()
221
+ if ((await top.exited) === 0 && (await realpath(topPath)) === source)
222
+ manifest.gitHead = gitHead
223
+ }
224
+ } catch {
225
+ /* Package provenance may be unknown without Git. */
226
+ }
227
+ manifest.files = [...manifest.files.filter((p) => p !== 'tsconfig.json'), 'tsconfig.json']
228
+ await writeFile(join(target, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`)
229
+ await writeFile(join(target, 'tsconfig.json'), RUNTIME_CONFIG)
230
+ await writeFile(join(target, 'bin/agent/ab'), cachedAgentTrampoline)
231
+ await chmod(join(target, 'bin/agent/ab'), 0o755)
232
+ }
233
+ export async function guestArchiveProvenance(source: string): Promise<'source' | 'registry'> {
234
+ const cached = await cachedRuntime(source)
235
+ if (cached) {
236
+ await validateRuntime(cached)
237
+ return cached.guestArchive!.provenance
238
+ }
239
+ // Resolve installation evidence before staging removes package-manager paths.
240
+ source = await realpath(source)
241
+ if (existsSync(join(source, '.git')) || existsSync(join(source, '.bun-tag'))) return 'source'
242
+ const manifest = await readManifest(source)
243
+ const segments = source.split('/')
244
+ if (!segments.includes('node_modules')) return 'source'
245
+ if (
246
+ segments.some(
247
+ (part, index) =>
248
+ segments[index - 1] === '.bun' &&
249
+ (part === `@defrex+autobuild@${manifest.version}` ||
250
+ part.startsWith(`@defrex+autobuild@${manifest.version}_`)),
251
+ )
252
+ )
253
+ return 'registry'
254
+ for (let owner = dirname(source); ; owner = dirname(owner)) {
255
+ try {
256
+ const lock = Bun.JSONC.parse(await readFile(join(owner, 'bun.lock'), 'utf8')) as {
257
+ packages?: Record<string, unknown>
258
+ }
259
+ const record = lock?.packages?.['@defrex/autobuild']
260
+ if (
261
+ Array.isArray(record) &&
262
+ typeof record[0] === 'string' &&
263
+ /^@defrex\/autobuild@(file:|link:|workspace:|github:|git|https?:)/.test(record[0])
264
+ )
265
+ return 'source'
266
+ if (
267
+ Array.isArray(record) &&
268
+ record[0] === `@defrex/autobuild@${manifest.version}` &&
269
+ typeof record[1] === 'string'
270
+ )
271
+ return 'registry'
272
+ } catch (error) {
273
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
274
+ }
275
+ if (dirname(owner) === owner) break
276
+ }
277
+ throw new Error(
278
+ `cannot establish guest archive provenance for ${source}; retain the installation's Bun lock or forge tag`,
279
+ )
280
+ }
281
+
282
+ export async function validateRuntime(runtime: CachedRuntime): Promise<void> {
283
+ const recorded = await cachedRuntime(runtime.root)
284
+ if (!recorded || (await treeDigest(runtime.root)) !== runtime.digest)
285
+ throw new Error(`corrupt completed runtime: ${runtime.root}`)
286
+ const archive = await Bun.file(join(dirname(runtime.root), 'distribution.tgz')).arrayBuffer()
287
+ if (new Bun.CryptoHasher('sha256').update(archive).digest('hex') !== runtime.archiveDigest)
288
+ throw new Error(`corrupt runtime archive: ${runtime.root}`)
289
+ const guest = recorded.guestArchive
290
+ if (
291
+ !guest ||
292
+ !['distribution.tgz', 'guest-distribution.tgz'].includes(guest.file) ||
293
+ (guest.provenance === 'registry'
294
+ ? guest.file !== 'guest-distribution.tgz'
295
+ : guest.provenance !== 'source' || guest.file !== 'distribution.tgz')
296
+ )
297
+ throw new Error(
298
+ `runtime lacks guest archive provenance; prepare a fresh runtime: ${runtime.root}`,
299
+ )
300
+ if (guest.digest === undefined) {
301
+ if (guest.provenance !== 'registry')
302
+ throw new Error(`source runtime lacks guest archive digest: ${runtime.root}`)
303
+ return // Registry assets are resolved only when a guest first needs them.
304
+ }
305
+ const bytes = await readFile(join(dirname(runtime.root), guest.file))
306
+ if (new Bun.CryptoHasher('sha256').update(bytes).digest('hex') !== guest.digest)
307
+ throw new Error(`corrupt guest archive: ${runtime.root}`)
308
+ }
309
+
310
+ async function validateRuntimeImports(root: string, checkout: string): Promise<void> {
311
+ const probe = Bun.spawn(runtimeSpawnArguments(root, join(root, 'bin/ab.ts'), ['--version']), {
312
+ cwd: checkout,
313
+ stdout: 'pipe',
314
+ stderr: 'pipe',
315
+ })
316
+ const [code, stderr] = await Promise.all([
317
+ probe.exited,
318
+ new Response(probe.stderr).text(),
319
+ new Response(probe.stdout).text(),
320
+ ])
321
+ if (code !== 0) throw new Error(`cached runtime import validation failed: ${stderr}`)
322
+ }
323
+
324
+ const guestFetches = new WeakMap<
325
+ (version: string) => Promise<Uint8Array>,
326
+ Map<string, Promise<Uint8Array>>
327
+ >()
328
+ function fetchGuestArchive(
329
+ version: string,
330
+ fetchRelease: (version: string) => Promise<Uint8Array>,
331
+ ): Promise<Uint8Array> {
332
+ let versions = guestFetches.get(fetchRelease)
333
+ if (!versions) {
334
+ versions = new Map()
335
+ guestFetches.set(fetchRelease, versions)
336
+ }
337
+ const existing = versions.get(version)
338
+ if (existing) return existing
339
+ const pending = Promise.resolve().then(() => fetchRelease(version))
340
+ versions.set(version, pending)
341
+ void pending
342
+ .finally(() => {
343
+ if (versions.get(version) === pending) versions.delete(version)
344
+ })
345
+ .catch(() => {})
346
+ return pending
347
+ }
348
+
349
+ export async function prepareRuntime(
350
+ source: string,
351
+ checkout: string,
352
+ publication?: { upgradeKey: string; commit: string },
353
+ guest: {
354
+ provenance: 'source' | 'registry'
355
+ } = { provenance: 'source' },
356
+ ): Promise<CachedRuntime> {
357
+ source = await realpath(source)
358
+ checkout = await realpath(checkout)
359
+ const cache = join(checkout, '.autobuild', 'runtime')
360
+ await mkdir(cache, { recursive: true })
361
+ const stage = await mkdtemp(join(cache, '.preparing-'))
362
+ 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')
368
+ await stageCode(source, check)
369
+ if ((await treeDigest(check)) !== codeDigest)
370
+ throw new Error('Autobuild source changed while preparing runtime; retry dispatch')
371
+ 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
436
+ )
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 })
446
+ await writeFile(join(stage, 'distribution.tgz'), archive)
447
+ const guestArchive: NonNullable<CachedRuntime['guestArchive']> =
448
+ guest.provenance === 'registry'
449
+ ? { provenance: 'registry', file: 'guest-distribution.tgz' }
450
+ : { provenance: 'source', file: 'distribution.tgz', digest: archiveDigest }
451
+ const runtime: CachedRuntime = {
452
+ version: 1,
453
+ id,
454
+ root: join(destination, 'distribution'),
455
+ digest,
456
+ dependencies: graph.fingerprint,
457
+ archiveDigest,
458
+ guestArchive,
459
+ }
460
+ await writeFile(join(stage, 'runtime.json'), JSON.stringify(runtime))
461
+ if (publication)
462
+ await writeFile(join(stage, 'source-receipt.json'), JSON.stringify(publication))
463
+ reservePreparedRuntime(cache, id)
464
+ const existing = await cachedRuntime(runtime.root)
465
+ if (existing) await validateRuntime(existing)
466
+ withCacheLock(cache, () => {
467
+ if (!existsSync(destination)) renameSync(stage, destination)
468
+ })
469
+ const completed = await cachedRuntime(runtime.root)
470
+ if (!completed) throw new Error(`runtime publication incomplete: ${destination}`)
471
+ return completed
472
+ } finally {
473
+ await rm(stage, { recursive: true, force: true })
474
+ }
475
+ }
476
+
477
+ /** Complete guest delivery lazily; host launch and validation never fetch assets.
478
+ * Publication happens under the cache lock and updates only sibling metadata. */
479
+ export async function resolveCachedGuestArchive(
480
+ runtime: CachedRuntime,
481
+ fetchRelease: (version: string) => Promise<Uint8Array>,
482
+ ): Promise<Uint8Array> {
483
+ let current = (await cachedRuntime(runtime.root))!
484
+ await validateRuntime(current)
485
+ if (current.guestArchive!.digest)
486
+ return new Uint8Array(await readFile(join(dirname(current.root), current.guestArchive!.file)))
487
+ const version = String((await readManifest(current.root)).version)
488
+ const bytes = await fetchGuestArchive(version, fetchRelease)
489
+ if (!bytes.byteLength) throw new Error('published guest archive is empty')
490
+ const entry = dirname(current.root)
491
+ const stage = await mkdtemp(join(entry, '.guest-'))
492
+ try {
493
+ const archive = join(stage, 'guest-distribution.tgz')
494
+ await writeFile(archive, bytes)
495
+ const inspect = Bun.spawn(['tar', '-xOzf', archive, 'package/package.json'], {
496
+ stdout: 'pipe',
497
+ stderr: 'pipe',
498
+ })
499
+ const [text, error, code] = await Promise.all([
500
+ new Response(inspect.stdout).text(),
501
+ new Response(inspect.stderr).text(),
502
+ inspect.exited,
503
+ ])
504
+ if (code !== 0) throw new Error(`invalid published guest archive: ${error}`)
505
+ if (JSON.parse(text).version !== version)
506
+ throw new Error('published guest archive version contradicts runtime')
507
+ const digest = new Bun.CryptoHasher('sha256').update(bytes).digest('hex')
508
+ withCacheLock(dirname(entry), () => {
509
+ current = JSON.parse(readFileSync(join(entry, 'runtime.json'), 'utf8')) as CachedRuntime
510
+ if (current.guestArchive?.digest) return
511
+ renameSync(archive, join(entry, 'guest-distribution.tgz'))
512
+ current.guestArchive = { provenance: 'registry', file: 'guest-distribution.tgz', digest }
513
+ const metadata = join(stage, 'runtime.json')
514
+ writeFileSync(metadata, JSON.stringify(current))
515
+ renameSync(metadata, join(entry, 'runtime.json'))
516
+ })
517
+ await validateRuntime(current)
518
+ return new Uint8Array(await readFile(join(entry, current.guestArchive!.file)))
519
+ } finally {
520
+ await rm(stage, { recursive: true, force: true })
521
+ }
522
+ }