@defrex/autobuild 1.0.0-beta.3 → 1.0.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 (168) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +362 -56
  3. package/bin/ab-dispatch-generation.ts +93 -0
  4. package/docs/agent-runtimes.md +157 -0
  5. package/docs/answering-blocked-builds.md +21 -3
  6. package/docs/architecture.md +166 -7
  7. package/docs/build-store.md +123 -0
  8. package/docs/builds.md +82 -0
  9. package/docs/cli.md +48 -0
  10. package/docs/configuration-overview.md +93 -0
  11. package/docs/configuration.md +1778 -188
  12. package/docs/dispatcher-hosting.md +115 -0
  13. package/docs/dispatcher.md +59 -0
  14. package/docs/forges.md +121 -0
  15. package/docs/getting-started.md +60 -0
  16. package/docs/glossary.md +60 -0
  17. package/docs/hosted-service.md +2 -2
  18. package/docs/intake.md +48 -0
  19. package/docs/integration-overview.md +81 -0
  20. package/docs/integration-tree.md +87 -2
  21. package/docs/integration.md +54 -0
  22. package/docs/operating.md +114 -0
  23. package/docs/operator-api.md +64 -11
  24. package/docs/operator-surfaces.md +90 -0
  25. package/docs/overview.md +49 -0
  26. package/docs/plugin-authoring.md +426 -0
  27. package/docs/remote-store-protocol.md +12 -9
  28. package/docs/restacking.md +4 -1
  29. package/docs/seams.md +66 -0
  30. package/docs/setup.md +28 -6
  31. package/docs/skills.md +119 -0
  32. package/docs/spec-standard.md +23 -5
  33. package/docs/ticket-sources.md +132 -0
  34. package/docs/tickets.md +69 -0
  35. package/docs/troubleshooting.md +111 -0
  36. package/docs/upgrading.md +50 -0
  37. package/docs/verification.md +146 -0
  38. package/docs/website.md +47 -5
  39. package/docs/workspaces.md +152 -0
  40. package/package.json +5 -4
  41. package/packages/core/src/cli/artifact.ts +5 -4
  42. package/packages/core/src/cli/attention.ts +2 -0
  43. package/packages/core/src/cli/binary-direct.ts +190 -0
  44. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  45. package/packages/core/src/cli/binary.ts +24 -210
  46. package/packages/core/src/cli/build-control.ts +105 -2
  47. package/packages/core/src/cli/context.ts +41 -1
  48. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  49. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  50. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  51. package/packages/core/src/cli/dashboard/model.ts +34 -10
  52. package/packages/core/src/cli/dashboard/render.ts +24 -2
  53. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  54. package/packages/core/src/cli/dispatch-args.ts +53 -0
  55. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  56. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  57. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  58. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  59. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  60. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  61. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  62. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  63. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  64. package/packages/core/src/cli/dispatch-process.ts +22 -90
  65. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  66. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  67. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  68. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  69. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  70. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  71. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  72. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  73. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  74. package/packages/core/src/cli/dispatch.ts +604 -60
  75. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  76. package/packages/core/src/cli/env.ts +1 -1
  77. package/packages/core/src/cli/harvest.ts +28 -11
  78. package/packages/core/src/cli/help.ts +10 -5
  79. package/packages/core/src/cli/installation.ts +5 -3
  80. package/packages/core/src/cli/main-checkout.ts +59 -0
  81. package/packages/core/src/cli/main.ts +15 -45
  82. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  83. package/packages/core/src/cli/repo-state.ts +3 -58
  84. package/packages/core/src/cli/repository-status.ts +67 -3
  85. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  86. package/packages/core/src/cli/status.ts +57 -3
  87. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  88. package/packages/core/src/cli/wait.ts +3 -0
  89. package/packages/core/src/cli/watch.ts +7 -0
  90. package/packages/core/src/config/landing.ts +8 -0
  91. package/packages/core/src/config/live.ts +1 -0
  92. package/packages/core/src/config/reference-metadata.ts +31 -0
  93. package/packages/core/src/config/reference.ts +342 -0
  94. package/packages/core/src/config/roles.ts +1 -1
  95. package/packages/core/src/config/schema.ts +352 -10
  96. package/packages/core/src/distribution-packaging.ts +116 -0
  97. package/packages/core/src/events/catalog.ts +6 -0
  98. package/packages/core/src/events/payloads.ts +53 -9
  99. package/packages/core/src/events/policy.ts +25 -0
  100. package/packages/core/src/events/repository.ts +184 -4
  101. package/packages/core/src/events/runtime.ts +16 -0
  102. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  103. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  104. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  105. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  106. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  107. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  108. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  109. package/packages/core/src/kernel/harvest.ts +98 -4
  110. package/packages/core/src/kernel/integration-attention.ts +20 -0
  111. package/packages/core/src/kernel/integration-state.ts +80 -11
  112. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  113. package/packages/core/src/kernel/mixed-version.ts +34 -0
  114. package/packages/core/src/kernel/node-polling.ts +160 -0
  115. package/packages/core/src/kernel/read-facts.ts +40 -5
  116. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  117. package/packages/core/src/kernel/reducer.ts +75 -14
  118. package/packages/core/src/kernel/service-facts.ts +11 -4
  119. package/packages/core/src/ontology.ts +2 -2
  120. package/packages/core/src/open-map.ts +3 -1
  121. package/packages/core/src/operator/presentation.ts +7 -0
  122. package/packages/core/src/operator/query.ts +6 -2
  123. package/packages/core/src/operator/registry.ts +1 -1
  124. package/packages/core/src/plugins/load.ts +4 -1
  125. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  126. package/packages/core/src/ports/forge/contract.ts +29 -0
  127. package/packages/core/src/ports/forge/github.ts +189 -61
  128. package/packages/core/src/ports/forge-failure.ts +1 -0
  129. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  130. package/packages/core/src/ports/runner/session-env.ts +1 -0
  131. package/packages/core/src/ports/types.ts +10 -0
  132. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  133. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  134. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  135. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  136. package/packages/core/src/processes/build-child-exit.ts +5 -26
  137. package/packages/core/src/processes/build-runner.ts +81 -11
  138. package/packages/core/src/processes/dispatcher.ts +254 -23
  139. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  140. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  141. package/packages/core/src/processes/execution-settlement.ts +16 -7
  142. package/packages/core/src/processes/harvest-runner.ts +328 -292
  143. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  144. package/packages/core/src/runtime-identity.ts +22 -3
  145. package/packages/core/src/store/contract.ts +153 -0
  146. package/packages/core/src/store/local/store.ts +197 -72
  147. package/packages/core/src/store/reduced-reads.ts +8 -0
  148. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  149. package/packages/core/src/store/remote/client.ts +43 -0
  150. package/packages/core/src/store/repo-state-events.ts +20 -3
  151. package/packages/core/src/store/types.ts +7 -0
  152. package/skills/finalize/SKILL.md +3 -1
  153. package/skills/guide/SKILL.md +273 -48
  154. package/skills/guide/references/integration-tree.md +87 -2
  155. package/skills/guide/references/operator-api.md +71 -14
  156. package/skills/guide/references/plugin-authoring.md +231 -266
  157. package/skills/guide/references/remote-store-protocol.md +12 -9
  158. package/skills/guide/references/restacking.md +4 -1
  159. package/skills/guide/references/setup.md +28 -6
  160. package/skills/guide/references/spec-standard.md +23 -5
  161. package/skills/harvest/SKILL.md +4 -0
  162. package/skills/harvest-review/SKILL.md +4 -0
  163. package/skills/implement/SKILL.md +4 -2
  164. package/skills/operate/SKILL.md +104 -35
  165. package/skills/plan/SKILL.md +12 -4
  166. package/skills/spec/SKILL.md +20 -2
  167. package/skills/tickets/SKILL.md +20 -1
  168. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,291 @@
1
+ import { isBuiltin } from 'node:module'
2
+ import { createHash } from 'node:crypto'
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ readdir,
7
+ readFile,
8
+ realpath,
9
+ readlink,
10
+ copyFile,
11
+ chmod,
12
+ symlink,
13
+ } from 'node:fs/promises'
14
+ import { dirname, join, relative, resolve, isAbsolute } from 'node:path'
15
+
16
+ export type Manifest = {
17
+ name?: string
18
+ version?: string
19
+ files?: string[]
20
+ dependencies?: Record<string, string>
21
+ optionalDependencies?: Record<string, string>
22
+ peerDependencies?: Record<string, string>
23
+ peerDependenciesMeta?: Record<string, { optional?: boolean }>
24
+ devDependencies?: Record<string, string>
25
+ [key: string]: unknown
26
+ }
27
+ export const excludedSnapshotNames = new Set(['node_modules', '.git', '.autobuild', '.ab', '.env'])
28
+ const dependencyExclusions = new Set(['node_modules'])
29
+ export function inside(root: string, path: string): boolean {
30
+ const rel = relative(root, path)
31
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
32
+ }
33
+ export async function readManifest(root: string): Promise<Manifest> {
34
+ return JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
35
+ }
36
+ export async function installedPackage(name: string, start: string): Promise<string | undefined> {
37
+ if (!/^(@[^/]+\/)?[^/]+$/.test(name) || name.includes('..'))
38
+ throw new Error(`invalid dependency name ${name}`)
39
+ let current = resolve(start)
40
+ for (;;) {
41
+ try {
42
+ return await realpath(join(current, 'node_modules', name))
43
+ } catch (error) {
44
+ if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error
45
+ }
46
+ const parent = dirname(current)
47
+ if (parent === current) return undefined
48
+ current = parent
49
+ }
50
+ }
51
+
52
+ /** Independent bytes, never hardlinks. Package-internal links are normalized;
53
+ * an escaping asset link is rejected rather than silently following a checkout. */
54
+ export async function copySnapshotTree(
55
+ source: string,
56
+ target: string,
57
+ boundary = source,
58
+ stack = new Set<string>(),
59
+ exclusions = excludedSnapshotNames,
60
+ ): Promise<void> {
61
+ const actual = await realpath(source)
62
+ if (!inside(boundary, actual))
63
+ throw new Error(`snapshot link escapes package: ${source} -> ${actual}`)
64
+ if (stack.has(actual)) throw new Error(`cyclic snapshot asset link: ${source}`)
65
+ const sourceStat = await lstat(source)
66
+ if (sourceStat.isSymbolicLink()) {
67
+ const mapped = resolve(target, relative(source, actual))
68
+ await mkdir(dirname(target), { recursive: true })
69
+ await symlink(relative(dirname(target), mapped), target)
70
+ return
71
+ }
72
+ const stat = await lstat(actual)
73
+ if (stat.isDirectory()) {
74
+ await mkdir(target, { recursive: true })
75
+ const next = new Set(stack).add(actual)
76
+ for (const name of (await readdir(actual)).sort()) {
77
+ if (exclusions.has(name) || (exclusions.has('.env') && name.startsWith('.env.'))) continue
78
+ await copySnapshotTree(join(actual, name), join(target, name), boundary, next, exclusions)
79
+ }
80
+ await chmod(target, stat.mode & 0o777)
81
+ } else if (stat.isFile()) {
82
+ await mkdir(dirname(target), { recursive: true })
83
+ await copyFile(actual, target)
84
+ await chmod(target, stat.mode & 0o777)
85
+ } else throw new Error(`unsupported snapshot asset: ${source}`)
86
+ }
87
+
88
+ /** Digest includes names, executable bits, bytes and internal link topology. */
89
+ export async function treeDigest(
90
+ root: string,
91
+ exclude = new Set<string>(),
92
+ allowedLink?: string,
93
+ ): Promise<string> {
94
+ const hash = createHash('sha256')
95
+ async function walk(path: string): Promise<void> {
96
+ const rel = relative(root, path)
97
+ const stat = await lstat(path)
98
+ hash.update(JSON.stringify([rel, stat.mode & 0o111]))
99
+ if (stat.isSymbolicLink()) {
100
+ const link = await readlink(path)
101
+ if (
102
+ !inside(root, resolve(dirname(path), link)) &&
103
+ resolve(dirname(path), link) !== allowedLink
104
+ )
105
+ throw new Error(`snapshot link escapes runtime: ${path}`)
106
+ const actual = await realpath(path)
107
+ if (!inside(root, actual) && actual !== allowedLink)
108
+ throw new Error(`snapshot link escapes runtime: ${path}`)
109
+ hash.update(`link:${relative(dirname(path), actual)}`)
110
+ } else if (stat.isDirectory()) {
111
+ hash.update('directory')
112
+ for (const name of (await readdir(path)).sort())
113
+ if (!exclude.has(name)) await walk(join(path, name))
114
+ } else if (stat.isFile()) {
115
+ hash.update('file')
116
+ hash.update(await readFile(path))
117
+ } else throw new Error(`unsupported snapshot file: ${path}`)
118
+ }
119
+ await walk(root)
120
+ return hash.digest('hex')
121
+ }
122
+
123
+ export interface DependencyGraph {
124
+ roots: Record<string, number>
125
+ packages: Array<{
126
+ source: string
127
+ manifest: Manifest
128
+ edges: Record<string, number>
129
+ digest: string
130
+ }>
131
+ fingerprint: string
132
+ }
133
+ export async function scanDependencies(
134
+ root: string,
135
+ options: { dev?: boolean; coreRoot?: string; manifest?: Manifest } = {},
136
+ ): Promise<DependencyGraph> {
137
+ const packages: DependencyGraph['packages'] = []
138
+ const ids = new Map<string, number>()
139
+ async function edges(
140
+ source: string,
141
+ manifest: Manifest,
142
+ dev = false,
143
+ ): Promise<Record<string, number>> {
144
+ const result: Record<string, number> = {}
145
+ const names = {
146
+ ...(dev ? manifest.devDependencies : {}),
147
+ ...manifest.peerDependencies,
148
+ ...manifest.dependencies,
149
+ ...manifest.optionalDependencies,
150
+ }
151
+ for (const name of Object.keys(names).sort()) {
152
+ if (name === '@defrex/autobuild' && options.coreRoot) continue
153
+ const found = await installedPackage(name, source)
154
+ if (!found) {
155
+ if (
156
+ Object.hasOwn(manifest.optionalDependencies ?? {}, name) ||
157
+ manifest.peerDependenciesMeta?.[name]?.optional ||
158
+ (dev &&
159
+ !Object.hasOwn(manifest.dependencies ?? {}, name) &&
160
+ !Object.hasOwn(manifest.peerDependencies ?? {}, name))
161
+ )
162
+ continue
163
+ throw new Error(
164
+ `missing installed dependency ${name} required by ${source}; repair the Autobuild installation before dispatch`,
165
+ )
166
+ }
167
+ let id = ids.get(found)
168
+ if (id === undefined) {
169
+ id = packages.length
170
+ ids.set(found, id)
171
+ const entry = {
172
+ source: found,
173
+ manifest: await readManifest(found),
174
+ edges: {},
175
+ digest: await treeDigest(found, dependencyExclusions),
176
+ }
177
+ packages.push(entry)
178
+ entry.edges = await edges(found, entry.manifest)
179
+ }
180
+ result[name] = id
181
+ }
182
+ return result
183
+ }
184
+ const roots = await edges(root, options.manifest ?? (await readManifest(root)), options.dev)
185
+ const fingerprint = createHash('sha256')
186
+ .update(JSON.stringify({ roots, packages: packages.map(({ source: _, ...rest }) => rest) }))
187
+ .digest('hex')
188
+ return { roots, packages, fingerprint }
189
+ }
190
+ export async function copyDependencies(
191
+ graph: DependencyGraph,
192
+ target: string,
193
+ coreRoot?: string,
194
+ ): Promise<void> {
195
+ await mkdir(join(target, 'node_modules'), { recursive: true })
196
+ const packagePath = (id: number) => join(target, 'node_modules', '.ab-packages', String(id))
197
+ async function links(root: string, edges: Record<string, number>) {
198
+ for (const [name, id] of Object.entries(edges)) {
199
+ const link = join(root, 'node_modules', name)
200
+ await mkdir(dirname(link), { recursive: true })
201
+ await symlink(relative(dirname(link), packagePath(id)), link)
202
+ }
203
+ if (coreRoot) {
204
+ const link = join(root, 'node_modules', '@defrex', 'autobuild')
205
+ await mkdir(dirname(link), { recursive: true })
206
+ await symlink(relative(dirname(link), coreRoot), link)
207
+ }
208
+ }
209
+ for (const [id, entry] of graph.packages.entries()) {
210
+ await copySnapshotTree(
211
+ entry.source,
212
+ packagePath(id),
213
+ entry.source,
214
+ new Set(),
215
+ dependencyExclusions,
216
+ )
217
+ if ((await treeDigest(packagePath(id), dependencyExclusions)) !== entry.digest)
218
+ throw new Error(`installed dependency changed while copying: ${entry.source}; retry dispatch`)
219
+ }
220
+ for (const [id, entry] of graph.packages.entries()) await links(packagePath(id), entry.edges)
221
+ await links(target, graph.roots)
222
+ }
223
+
224
+ /** Standalone plugins have no manifest. Discover their literal native module
225
+ * edges without evaluating consumer code or installing packages. Computed core
226
+ * imports are covered by the canonical core link at every package boundary. */
227
+ export async function standalonePluginManifest(
228
+ entry: string,
229
+ boundary: string,
230
+ files = new Set<string>(),
231
+ ): Promise<Manifest> {
232
+ const dependencies: Record<string, string> = {}
233
+ const visited = new Set<string>()
234
+ async function visit(file: string): Promise<void> {
235
+ if (visited.has(file)) return
236
+ visited.add(file)
237
+ const actual = await realpath(file)
238
+ if (!inside(boundary, actual))
239
+ throw new Error(`standalone plugin link escapes its directory: ${file}`)
240
+ files.add(file)
241
+ const extension = file.split('.').at(-1)
242
+ if (!['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts'].includes(extension ?? '')) return
243
+ const loader =
244
+ extension === 'tsx' || extension === 'jsx'
245
+ ? extension
246
+ : extension === 'ts' || extension === 'mts' || extension === 'cts'
247
+ ? 'ts'
248
+ : 'js'
249
+ const source = await readFile(file, 'utf8')
250
+ // Literal package-relative assets retain their import.meta.url location.
251
+ for (const match of source.matchAll(
252
+ /new\s+URL\(\s*['"](\.[^'"]+)['"]\s*,\s*import\.meta\.url\s*\)/g,
253
+ )) {
254
+ const asset = resolve(dirname(file), match[1]!)
255
+ if (!inside(boundary, asset))
256
+ throw new Error(`standalone plugin asset escapes its directory: ${asset}`)
257
+ await visit(asset)
258
+ }
259
+ const imports = new Bun.Transpiler({ loader }).scanImports(source)
260
+ for (const imported of imports) {
261
+ const path = imported.path
262
+ if (
263
+ isBuiltin(path) ||
264
+ path.startsWith('node:') ||
265
+ path.startsWith('bun:') ||
266
+ isAbsolute(path)
267
+ )
268
+ continue
269
+ if (!path.startsWith('.')) {
270
+ const parts = path.split('/')
271
+ const name = path.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!
272
+ dependencies[name] = '*'
273
+ continue
274
+ }
275
+ const base = resolve(dirname(file), path)
276
+ if (!inside(boundary, base))
277
+ throw new Error(`standalone plugin import escapes its directory: ${file}: ${path}`)
278
+ let resolved: string
279
+ try {
280
+ // Relative-only resolution stays offline and follows Bun's native
281
+ // extension substitutions and directory entry rules without loading code.
282
+ resolved = Bun.resolveSync(path, dirname(file))
283
+ } catch (cause) {
284
+ throw new Error(`cannot resolve standalone plugin import: ${file}: ${path}`, { cause })
285
+ }
286
+ await visit(resolved)
287
+ }
288
+ }
289
+ await visit(entry)
290
+ return { name: 'autobuild-standalone-plugin', dependencies }
291
+ }
@@ -0,0 +1,336 @@
1
+ import { hostname } from 'node:os'
2
+ import {
3
+ mkdirSync,
4
+ existsSync,
5
+ symlinkSync,
6
+ readlinkSync,
7
+ readFileSync,
8
+ writeFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ readdirSync,
12
+ lstatSync,
13
+ realpathSync,
14
+ } from 'node:fs'
15
+ import { basename, dirname, join, resolve } from 'node:path'
16
+ import { randomUUID } from 'node:crypto'
17
+
18
+ const localHost = hostname()
19
+ interface Claim {
20
+ host?: string
21
+ pid: number
22
+ start: string | null
23
+ group?: boolean
24
+ }
25
+ interface Retention {
26
+ current?: string
27
+ previous?: string
28
+ held: string[]
29
+ rollback?: { lineage: string; id: string }
30
+ claims: Record<string, { id: string; process: Claim; extensions?: string[] }>
31
+ }
32
+ function identity(pid: number): string | null {
33
+ try {
34
+ return readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ').at(-1)!.split(' ')[19]!
35
+ } catch {
36
+ return null
37
+ }
38
+ }
39
+ function alive(claim: Claim): boolean {
40
+ if (claim.pid === 0 || (claim.host !== undefined && claim.host !== localHost)) return true
41
+ try {
42
+ process.kill(claim.group ? -claim.pid : claim.pid, 0)
43
+ } catch (error) {
44
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH'
45
+ }
46
+ const start = identity(claim.pid)
47
+ return !start || !claim.start || start === claim.start
48
+ }
49
+ function locked<T>(cache: string, operation: (state: Retention) => T): T {
50
+ mkdirSync(cache, { recursive: true })
51
+ const lock = join(cache, '.usage-lock')
52
+ for (;;) {
53
+ try {
54
+ symlinkSync(
55
+ JSON.stringify({ pid: process.pid, start: identity(process.pid), host: localHost }),
56
+ lock,
57
+ )
58
+ break
59
+ } catch (error) {
60
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
61
+ try {
62
+ const owner = JSON.parse(readlinkSync(lock)) as Claim
63
+ if (owner.pid > 0 && !alive(owner)) {
64
+ rmSync(lock, { force: true })
65
+ continue
66
+ }
67
+ } catch {}
68
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
69
+ }
70
+ }
71
+ try {
72
+ let state: Retention
73
+ try {
74
+ state = JSON.parse(readFileSync(join(cache, 'retention.json'), 'utf8'))
75
+ } catch (error) {
76
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
77
+ state = { held: [], claims: {} }
78
+ }
79
+ const result = operation(state)
80
+ const temporary = join(cache, `.retention-${randomUUID()}`)
81
+ writeFileSync(temporary, JSON.stringify(state))
82
+ renameSync(temporary, join(cache, 'retention.json'))
83
+ return result
84
+ } finally {
85
+ rmSync(lock, { force: true })
86
+ }
87
+ }
88
+ export function looksCachedRuntime(root: string): boolean {
89
+ return basename(root) === 'distribution' && /-[a-f0-9]{64}$/.test(basename(dirname(root)))
90
+ }
91
+ export function ownCachedRuntime(root: string): { cache: string; id: string } | undefined {
92
+ if (!looksCachedRuntime(root)) return undefined
93
+ const entry = dirname(root)
94
+ let meta: { version?: number; root?: string; id?: string; digest?: string }
95
+ try {
96
+ meta = JSON.parse(readFileSync(join(entry, 'runtime.json'), 'utf8'))
97
+ } catch (error) {
98
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' && !existsSync(entry)) return undefined
99
+ throw new Error(`incomplete runtime metadata: ${root}`, { cause: error })
100
+ }
101
+ if (
102
+ meta.version !== 1 ||
103
+ meta.root !== resolve(root) ||
104
+ meta.id !== basename(entry) ||
105
+ !meta.digest ||
106
+ !meta.id.endsWith(`-${meta.digest}`) ||
107
+ realpathSync(root) !== resolve(root)
108
+ )
109
+ throw new Error(`invalid runtime metadata: ${root}`)
110
+ if (readFileSync(join(root, 'tsconfig.json'), 'utf8') !== '{}\n')
111
+ throw new Error(`invalid runtime compiler boundary: ${root}`)
112
+ return { cache: dirname(entry), id: meta.id }
113
+ }
114
+ /** Spawn and publish its process identity under the pruning lock. A reservation
115
+ * owned by this process survives spawn failure/crash conservatively. */
116
+ export function spawnUsingRuntime<T extends { pid: number }>(
117
+ root: string,
118
+ spawn: () => T,
119
+ group = false,
120
+ ): { child: T; release: () => void } {
121
+ const runtime = ownCachedRuntime(root)
122
+ if (!runtime) return { child: spawn(), release: () => {} }
123
+ const key = randomUUID()
124
+ const child = locked(runtime.cache, (state) => {
125
+ // Persist an unknown-process reservation before crossing spawn. A crash
126
+ // before identity publication must retain rather than delete live code.
127
+ state.claims[key] = { id: runtime.id, process: { pid: 0, start: null } }
128
+ const reservation = join(runtime.cache, `.retention-${randomUUID()}`)
129
+ writeFileSync(reservation, JSON.stringify(state))
130
+ renameSync(reservation, join(runtime.cache, 'retention.json'))
131
+ let child: T
132
+ try {
133
+ child = spawn()
134
+ } catch (error) {
135
+ delete state.claims[key]
136
+ const repaired = join(runtime.cache, `.retention-${randomUUID()}`)
137
+ writeFileSync(repaired, JSON.stringify(state))
138
+ renameSync(repaired, join(runtime.cache, 'retention.json'))
139
+ throw error
140
+ }
141
+ state.claims[key] = {
142
+ id: runtime.id,
143
+ process: {
144
+ pid: child.pid,
145
+ start: identity(child.pid),
146
+ host: localHost,
147
+ ...(group ? { group: true } : {}),
148
+ },
149
+ }
150
+ return child
151
+ })
152
+ return {
153
+ child,
154
+ release: () =>
155
+ locked(runtime.cache, (state) => {
156
+ delete state.claims[key]
157
+ }),
158
+ }
159
+ }
160
+ export function retainRuntime(root: string, held: boolean): void {
161
+ const runtime = ownCachedRuntime(root)
162
+ if (!runtime) throw new Error(`not a completed runtime: ${root}`)
163
+ locked(runtime.cache, (state) => {
164
+ state.held = state.held.filter((id) => id !== runtime.id)
165
+ if (held) state.held.push(runtime.id)
166
+ })
167
+ }
168
+ export function activateRuntime(root: string): void {
169
+ const runtime = ownCachedRuntime(root)
170
+ if (!runtime) throw new Error(`not a completed runtime: ${root}`)
171
+ locked(runtime.cache, (state) => {
172
+ if (state.current !== runtime.id) {
173
+ state.previous = state.current
174
+ state.current = runtime.id
175
+ }
176
+ })
177
+ }
178
+ export function pruneRuntimes(cache: string): void {
179
+ locked(cache, (state) => {
180
+ for (const [key, claim] of Object.entries(state.claims))
181
+ if (!alive(claim.process)) delete state.claims[key]
182
+ const keep = new Set([
183
+ state.current,
184
+ state.previous,
185
+ ...state.held,
186
+ state.rollback?.id,
187
+ ...Object.values(state.claims).map((c) => c.id),
188
+ ])
189
+ const liveExtensions = new Set(Object.values(state.claims).flatMap((c) => c.extensions ?? []))
190
+ const extensions = join(cache, 'extensions')
191
+ try {
192
+ for (const id of readdirSync(extensions)) {
193
+ if (!/^[a-f0-9]{64}$/.test(id)) continue
194
+ const entry = join(extensions, id)
195
+ if (liveExtensions.has(entry) || lstatSync(entry).isSymbolicLink()) continue
196
+ let meta: { version?: number; digest?: string; core?: string }
197
+ try {
198
+ meta = JSON.parse(readFileSync(join(entry, 'extension.json'), 'utf8'))
199
+ } catch {
200
+ continue
201
+ }
202
+ if (
203
+ meta.version !== 1 ||
204
+ meta.digest !== id ||
205
+ typeof meta.core !== 'string' ||
206
+ !ownCachedRuntime(meta.core)
207
+ )
208
+ continue
209
+ const tombstone = join(extensions, `.deleting-${randomUUID()}`)
210
+ renameSync(entry, tombstone)
211
+ rmSync(tombstone, { recursive: true, force: true })
212
+ }
213
+ } catch (error) {
214
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
215
+ }
216
+ // Removal is restricted to completed entries owned by this cache. Unknown
217
+ // files and preparations are never candidates.
218
+ for (const id of readdirSync(cache)) {
219
+ if (id.startsWith('.') || keep.has(id)) continue
220
+ const entry = join(cache, id)
221
+ if (lstatSync(entry).isSymbolicLink() || !lstatSync(entry).isDirectory()) continue
222
+ let meta: { id?: string; root?: string; version?: number }
223
+ try {
224
+ meta = JSON.parse(readFileSync(join(entry, 'runtime.json'), 'utf8'))
225
+ } catch {
226
+ continue
227
+ }
228
+ if (meta.id !== id || meta.root !== join(entry, 'distribution') || meta.version !== 1)
229
+ continue
230
+ const tombstone = join(cache, `.deleting-${randomUUID()}`)
231
+ renameSync(entry, tombstone)
232
+ rmSync(tombstone, { recursive: true, force: true })
233
+ }
234
+ // A preparation may be copying a shared layer without executing it.
235
+ // Conservatively defer layer cleanup while any such directory exists.
236
+ if (!readdirSync(cache).some((name) => name.startsWith('.preparing-'))) {
237
+ const needed = new Set<string>()
238
+ for (const id of readdirSync(cache)) {
239
+ if (id.startsWith('.')) continue
240
+ try {
241
+ const meta = JSON.parse(readFileSync(join(cache, id, 'runtime.json'), 'utf8'))
242
+ if (typeof meta.dependencies === 'string') needed.add(meta.dependencies)
243
+ } catch {}
244
+ }
245
+ const layers = join(cache, 'layers')
246
+ try {
247
+ for (const id of readdirSync(layers)) {
248
+ if (!/^[a-f0-9]{64}$/.test(id) || needed.has(id)) continue
249
+ const layer = join(layers, id)
250
+ if (lstatSync(layer).isSymbolicLink()) continue
251
+ try {
252
+ if (!/^[a-f0-9]{64}$/.test(readFileSync(join(layer, 'digest'), 'utf8'))) continue
253
+ } catch {
254
+ continue
255
+ }
256
+ const tombstone = join(layers, `.deleting-${randomUUID()}`)
257
+ renameSync(layer, tombstone)
258
+ rmSync(tombstone, { recursive: true, force: true })
259
+ }
260
+ } catch (error) {
261
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
262
+ }
263
+ }
264
+ })
265
+ }
266
+
267
+ export function claimRuntimeForProcess(root: string, extension?: string): void {
268
+ const runtime = ownCachedRuntime(root)
269
+ if (!runtime) return
270
+ locked(runtime.cache, (state) => {
271
+ const key = `process-${process.pid}-${identity(process.pid)}-${runtime.id}`
272
+ const extensions = new Set(state.claims[key]?.extensions ?? [])
273
+ if (extension) extensions.add(extension)
274
+ state.claims[key] = {
275
+ id: runtime.id,
276
+ process: { pid: process.pid, start: identity(process.pid), host: localHost },
277
+ extensions: [...extensions],
278
+ }
279
+ })
280
+ }
281
+
282
+ export function reservePreparedRuntime(cache: string, id: string, owner = process.pid): void {
283
+ locked(cache, (state) => {
284
+ state.claims[`preparing-${owner}-${id}`] = {
285
+ id,
286
+ process: { pid: owner, start: identity(owner), host: localHost },
287
+ }
288
+ })
289
+ }
290
+ export function releasePreparedRuntime(root: string, owner = process.pid): void {
291
+ const runtime = ownCachedRuntime(root)
292
+ if (runtime)
293
+ locked(runtime.cache, (state) => {
294
+ delete state.claims[`preparing-${owner}-${runtime.id}`]
295
+ })
296
+ }
297
+
298
+ /** Synchronous, short filesystem mutations only; shared with spawn and prune. */
299
+ export function mutateRuntimeCache<T>(cache: string, operation: () => T): T {
300
+ return locked(cache, operation)
301
+ }
302
+
303
+ /** Validate and reserve an existing candidate in the same pruning critical section. */
304
+ export function reserveExistingRuntime(root: string): boolean {
305
+ const cache = dirname(dirname(root))
306
+ return locked(cache, (state) => {
307
+ const runtime = ownCachedRuntime(root)
308
+ if (!runtime || runtime.cache !== cache) return false
309
+ state.claims[`preparing-${process.pid}-${runtime.id}`] = {
310
+ id: runtime.id,
311
+ process: { pid: process.pid, start: identity(process.pid), host: localHost },
312
+ }
313
+ return true
314
+ })
315
+ }
316
+
317
+ /** Cache retention follows the authoritative generation hold; it is not lifecycle state. */
318
+ export function syncRollbackRetention(cache: string, lineage: string, root?: string): void {
319
+ locked(cache, (state) => {
320
+ const runtime = root ? ownCachedRuntime(root) : undefined
321
+ if (root && (!runtime || runtime.cache !== cache)) throw new Error('invalid held runtime')
322
+ state.rollback = runtime ? { lineage, id: runtime.id } : undefined
323
+ })
324
+ }
325
+
326
+ /** Publication acknowledgement requires the retention transfer to be on disk. */
327
+ export function rollbackRuntimeRetained(root: string, lineage: string): boolean {
328
+ const runtime = ownCachedRuntime(root)
329
+ return (
330
+ !!runtime &&
331
+ locked(
332
+ runtime.cache,
333
+ (state) => state.rollback?.lineage === lineage && state.rollback.id === runtime.id,
334
+ )
335
+ )
336
+ }