typeclaw 0.48.10 → 0.48.12

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 (68) hide show
  1. package/package.json +2 -2
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +86 -16
  5. package/src/agent/index.ts +11 -1
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  12. package/src/bundled-plugins/github-cli-auth/index.ts +2 -1
  13. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  14. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  15. package/src/channels/adapters/github/inbound.ts +195 -25
  16. package/src/channels/adapters/github/index.ts +16 -18
  17. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  18. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  19. package/src/channels/adapters/github/review-submitter.ts +28 -0
  20. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  21. package/src/channels/adapters/kakaotalk.ts +7 -8
  22. package/src/channels/adapters/teams-classify.ts +21 -0
  23. package/src/channels/adapters/teams-edit.ts +2 -1
  24. package/src/channels/adapters/teams-format.ts +16 -0
  25. package/src/channels/adapters/teams.ts +12 -5
  26. package/src/channels/github-repo.ts +11 -0
  27. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  28. package/src/channels/github-verdict-activity.ts +10 -6
  29. package/src/channels/manager.ts +9 -0
  30. package/src/channels/persistence.ts +28 -2
  31. package/src/channels/router.ts +284 -61
  32. package/src/channels/schema.ts +18 -0
  33. package/src/channels/types.ts +1 -0
  34. package/src/cli/compose.ts +3 -3
  35. package/src/cli/docker-preflight.ts +8 -4
  36. package/src/cli/restart.ts +89 -23
  37. package/src/cli/start.ts +68 -16
  38. package/src/cli/status.ts +38 -6
  39. package/src/cli/stop.ts +5 -2
  40. package/src/compose/stop.ts +5 -4
  41. package/src/config/config.ts +9 -1
  42. package/src/container/build-cache.ts +807 -0
  43. package/src/container/compose-project.ts +4 -0
  44. package/src/container/docker-app.ts +74 -0
  45. package/src/container/log-archive.ts +33 -5
  46. package/src/container/memory-limit.ts +80 -0
  47. package/src/container/memory-oversubscription.ts +125 -0
  48. package/src/container/restart.ts +6 -1
  49. package/src/container/shared.ts +43 -16
  50. package/src/container/start.ts +313 -77
  51. package/src/container/stop.ts +19 -13
  52. package/src/container/verify-running.ts +12 -0
  53. package/src/cron/scheduler.ts +12 -4
  54. package/src/doctor/apparmor.ts +101 -0
  55. package/src/doctor/bounded-exec.ts +14 -0
  56. package/src/doctor/checks.ts +42 -15
  57. package/src/doctor/index.ts +14 -2
  58. package/src/doctor/plugin-bridge.ts +15 -3
  59. package/src/hostd/paths.ts +4 -0
  60. package/src/init/dockerfile.ts +7 -6
  61. package/src/init/windows-dev-link.ts +34 -2
  62. package/src/run/index.ts +17 -0
  63. package/src/run/resource-sample.ts +171 -0
  64. package/src/sandbox/availability.ts +7 -5
  65. package/src/sandbox/index.ts +8 -1
  66. package/src/sandbox/session-tmp.ts +26 -1
  67. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  68. package/typeclaw.schema.json +7 -0
@@ -0,0 +1,807 @@
1
+ import { createHash, randomBytes, randomUUID } from 'node:crypto'
2
+ import { chmod, lstat, mkdir, readFile, readdir, rename, rm, rmdir, writeFile } from 'node:fs/promises'
3
+ import { dirname, join } from 'node:path'
4
+
5
+ import lockfile from 'proper-lockfile'
6
+
7
+ import { buildCacheDir } from '@/hostd/paths'
8
+
9
+ import { sanitizeDockerStderr, type DockerExec } from './shared'
10
+
11
+ const STATE_VERSION = 1
12
+ const ACTIVE_VERSION = 1
13
+ const BUILDER_NAME = /^typeclaw-[a-f0-9]{24}$/
14
+ const GENERATION_ID = /^[a-f0-9]{32}$/
15
+ const HASH_DIRECTORY = /^[a-f0-9]{64}$/
16
+
17
+ type BuilderState = {
18
+ version: typeof STATE_VERSION
19
+ daemonId: string
20
+ builderName: string
21
+ status: 'reserved' | 'ready'
22
+ }
23
+
24
+ type ActiveCache = {
25
+ version: typeof ACTIVE_VERSION
26
+ generationId: string
27
+ }
28
+
29
+ export type ManagedBuildxBuilder = {
30
+ builderName: string
31
+ daemonId: string
32
+ statePath: string
33
+ env: { BUILDX_CONFIG: string }
34
+ }
35
+
36
+ export type ManagedBuildCacheLease = {
37
+ builder: ManagedBuildxBuilder
38
+ cacheRoot: string
39
+ stagingPath: string
40
+ cacheArgs: string[]
41
+ finish: (success: boolean) => Promise<{ warnings: string[] }>
42
+ }
43
+
44
+ export type ManagedBuildCacheResult =
45
+ | { ok: true; lease: ManagedBuildCacheLease; warnings: string[] }
46
+ | { ok: false; reason: string }
47
+
48
+ export async function acquireManagedBuildCache(options: {
49
+ exec: DockerExec
50
+ cacheScope: string
51
+ stateDir?: string
52
+ randomBuilderName?: () => string
53
+ randomGenerationId?: () => string
54
+ faultInjection?: {
55
+ removeGeneration?: (path: string) => Promise<void>
56
+ beforeActivePersist?: () => void | Promise<void>
57
+ beforeReadyPersist?: () => void | Promise<void>
58
+ releaseLock?: (release: () => Promise<void>) => Promise<void>
59
+ }
60
+ }): Promise<ManagedBuildCacheResult> {
61
+ const daemon = await queryDaemonId(options.exec)
62
+ if (!daemon.ok) return daemon
63
+
64
+ const stateDir = options.stateDir ?? buildCacheDir()
65
+ const scopeKey = createHash('sha256').update(options.cacheScope).digest('hex')
66
+ const daemonKey = createHash('sha256').update(daemon.daemonId).digest('hex')
67
+ const scopePath = join(stateDir, scopeKey)
68
+ const daemonStatePath = join(scopePath, daemonKey)
69
+ const builderStatePath = join(daemonStatePath, 'builder.json')
70
+ const cacheRoot = join(daemonStatePath, 'local-cache')
71
+ const generationsPath = join(cacheRoot, 'generations')
72
+ const activePath = join(cacheRoot, 'active.json')
73
+ const lockPath = join(daemonStatePath, 'lease.lock')
74
+ const builderBase = {
75
+ daemonId: daemon.daemonId,
76
+ statePath: builderStatePath,
77
+ env: { BUILDX_CONFIG: join(daemonStatePath, 'buildx') },
78
+ }
79
+ if (cacheRoot.includes(',')) return { ok: false, reason: 'managed local cache path cannot contain a comma' }
80
+
81
+ const randomBuilderName = options.randomBuilderName ?? (() => `typeclaw-${randomBytes(12).toString('hex')}`)
82
+ const randomGenerationId = options.randomGenerationId ?? (() => randomBytes(16).toString('hex'))
83
+ let release: (() => Promise<void>) | null = null
84
+ let preparedBuilder: ManagedBuildxBuilder | null = null
85
+ let compromised: Error | null = null
86
+ const assertLock = (): void => {
87
+ if (compromised !== null) throw compromised
88
+ }
89
+ const failAcquire = async (reason: string): Promise<ManagedBuildCacheResult> => {
90
+ let combined = reason
91
+ if (preparedBuilder !== null) {
92
+ const cleanupFailure = await removeExplicitOwnedBuilder(options.exec, preparedBuilder)
93
+ if (cleanupFailure !== null) {
94
+ combined = `${combined} ${builderFirstRecovery(preparedBuilder, daemonStatePath, cleanupFailure)}`
95
+ }
96
+ }
97
+ try {
98
+ if (release !== null) {
99
+ if (options.faultInjection?.releaseLock !== undefined) {
100
+ await options.faultInjection.releaseLock(release)
101
+ } else {
102
+ await releaseLock(release)
103
+ }
104
+ }
105
+ } catch (error) {
106
+ combined = `${combined} Managed build cache lock release failed: ${describeError(error)}`
107
+ }
108
+ release = null
109
+ return { ok: false, reason: combined }
110
+ }
111
+
112
+ try {
113
+ await ensurePrivateDirectory(stateDir)
114
+ await ensurePrivateDirectory(scopePath)
115
+ const warnings = await cleanupRetiredDaemonRoots(options.exec, scopePath, daemonKey)
116
+ await ensurePrivateDirectory(daemonStatePath)
117
+ await ensurePrivateDirectory(builderBase.env.BUILDX_CONFIG)
118
+ await ensurePrivateDirectory(cacheRoot)
119
+ await ensurePrivateDirectory(generationsPath)
120
+ await rejectSymlink(lockPath)
121
+ release = await lockfile.lock(builderStatePath, {
122
+ lockfilePath: lockPath,
123
+ realpath: false,
124
+ stale: 30_000,
125
+ update: 5_000,
126
+ retries: { retries: 2_400, factor: 1, minTimeout: 50, maxTimeout: 50, randomize: false },
127
+ onCompromised: (error) => {
128
+ compromised = error
129
+ },
130
+ })
131
+
132
+ const prepared = await prepareLocked(
133
+ options.exec,
134
+ builderBase,
135
+ randomBuilderName,
136
+ assertLock,
137
+ options.faultInjection?.beforeReadyPersist,
138
+ )
139
+ assertLock()
140
+ if (!prepared.ok) {
141
+ return await failAcquire(
142
+ isOwnershipStateReason(prepared.reason) ? recoveryReason(prepared.reason, daemonStatePath) : prepared.reason,
143
+ )
144
+ }
145
+ preparedBuilder = prepared.builder
146
+
147
+ const active = await readActiveCache(activePath, generationsPath)
148
+ if (!active.ok) {
149
+ return await failAcquire(recoveryReason(active.reason, daemonStatePath))
150
+ }
151
+ assertLock()
152
+ try {
153
+ await removeInactiveGenerations(generationsPath, active.generationId, assertLock)
154
+ } catch (error) {
155
+ return await failAcquire(recoveryReason(describeError(error), daemonStatePath))
156
+ }
157
+
158
+ const generationId = await reserveGenerationId(generationsPath, randomGenerationId)
159
+ if (!generationId.ok) {
160
+ return await failAcquire(generationId.reason)
161
+ }
162
+ const stagingPath = join(generationsPath, generationId.generationId)
163
+ const cacheArgs = [
164
+ ...(active.generationId === null
165
+ ? []
166
+ : ['--cache-from', `type=local,src=${join(generationsPath, active.generationId)}`]),
167
+ '--cache-to',
168
+ `type=local,dest=${stagingPath},mode=min`,
169
+ ]
170
+ let finished = false
171
+ const heldRelease = release
172
+ release = null
173
+
174
+ return {
175
+ ok: true,
176
+ warnings,
177
+ lease: {
178
+ builder: prepared.builder,
179
+ cacheRoot,
180
+ stagingPath,
181
+ cacheArgs,
182
+ finish: async (success) => {
183
+ if (finished) return { warnings: ['managed build cache lease was already finished'] }
184
+ finished = true
185
+ return await finishLease({
186
+ exec: options.exec,
187
+ builder: prepared.builder,
188
+ generationsPath,
189
+ activePath,
190
+ generationId: generationId.generationId,
191
+ stagingPath,
192
+ success,
193
+ assertLock,
194
+ release: heldRelease,
195
+ ...(options.faultInjection?.removeGeneration !== undefined
196
+ ? { removeGeneration: options.faultInjection.removeGeneration }
197
+ : {}),
198
+ ...(options.faultInjection?.beforeActivePersist !== undefined
199
+ ? { beforeActivePersist: options.faultInjection.beforeActivePersist }
200
+ : {}),
201
+ })
202
+ },
203
+ },
204
+ }
205
+ } catch (error) {
206
+ return await failAcquire(describeError(error))
207
+ }
208
+ }
209
+
210
+ async function cleanupRetiredDaemonRoots(
211
+ exec: DockerExec,
212
+ scopePath: string,
213
+ currentDaemonKey: string,
214
+ ): Promise<string[]> {
215
+ const warnings: string[] = []
216
+ for (const entry of await readdir(scopePath, { withFileTypes: true })) {
217
+ if (entry.name === currentDaemonKey) continue
218
+ const retiredPath = join(scopePath, entry.name)
219
+ if (!isHashDirectory(entry.name) || entry.isSymbolicLink() || !entry.isDirectory()) {
220
+ warnings.push(`unsafe managed build cache entry preserved at ${retiredPath}; inspect and remove it manually`)
221
+ continue
222
+ }
223
+ warnings.push(...(await cleanupRetiredDaemonRoot(exec, retiredPath, entry.name)))
224
+ }
225
+ return warnings
226
+ }
227
+
228
+ async function cleanupRetiredDaemonRoot(exec: DockerExec, retiredPath: string, daemonKey: string): Promise<string[]> {
229
+ const warnings: string[] = []
230
+ const statePath = join(retiredPath, 'builder.json')
231
+ const buildxConfig = join(retiredPath, 'buildx')
232
+ const cacheRoot = join(retiredPath, 'local-cache')
233
+ const lockPath = join(retiredPath, 'lease.lock')
234
+ let release: (() => Promise<void>) | null = null
235
+ let compromised: Error | null = null
236
+ try {
237
+ if ((await inspectDirectory(retiredPath)) !== 'directory') {
238
+ return [`unsafe retired managed build cache preserved at ${retiredPath}; inspect and remove it manually`]
239
+ }
240
+ await rejectSymlink(lockPath)
241
+ release = await lockfile.lock(statePath, {
242
+ lockfilePath: lockPath,
243
+ realpath: false,
244
+ stale: 30_000,
245
+ retries: 0,
246
+ onCompromised: (error) => {
247
+ compromised = error
248
+ },
249
+ })
250
+ const assertLock = (): void => {
251
+ if (compromised !== null) throw compromised
252
+ }
253
+ assertLock()
254
+
255
+ const allowedEntries = new Set(['builder.json', 'buildx', 'local-cache', 'lease.lock'])
256
+ const entries = await readdir(retiredPath, { withFileTypes: true })
257
+ const unknown = entries.find((entry) => !allowedEntries.has(entry.name))
258
+ if (unknown !== undefined) {
259
+ return [
260
+ `unknown retired managed build cache entry preserved at ${join(retiredPath, unknown.name)}; inspect it manually`,
261
+ ]
262
+ }
263
+
264
+ const stored = await readOwnedState(statePath)
265
+ if (
266
+ !stored.ok ||
267
+ stored.state === null ||
268
+ createHash('sha256').update(stored.state.daemonId).digest('hex') !== daemonKey
269
+ ) {
270
+ return [
271
+ `retired managed build cache ownership could not be proven at ${retiredPath}; remove ${retiredPath} manually after inspection`,
272
+ ]
273
+ }
274
+ if ((await inspectDirectory(buildxConfig)) !== 'directory') {
275
+ return [
276
+ `retired managed buildx config is unsafe at ${buildxConfig}; remove ${retiredPath} manually after inspection`,
277
+ ]
278
+ }
279
+ if ((await inspectDirectory(cacheRoot)) !== 'directory') {
280
+ return [`retired managed local cache is unsafe at ${cacheRoot}; remove ${retiredPath} manually after inspection`]
281
+ }
282
+ await validatePrivateTree(buildxConfig)
283
+ assertLock()
284
+
285
+ const env = { BUILDX_CONFIG: buildxConfig }
286
+ const inspected = await exec(['buildx', 'inspect', stored.state.builderName], { env })
287
+ assertLock()
288
+ if (inspected.exitCode === 0) {
289
+ const removed = await exec(['buildx', 'rm', stored.state.builderName], { env })
290
+ assertLock()
291
+ if (removed.exitCode !== 0) {
292
+ return [
293
+ `retired managed builder removal failed for ${stored.state.builderName}; preserving ${retiredPath}: ${sanitizeDockerStderr(removed.stderr) || `docker buildx rm exited ${removed.exitCode}`}`,
294
+ ]
295
+ }
296
+ } else if (!isMissingBuildxBuilder(inspected.stderr)) {
297
+ return [
298
+ `retired managed builder could not be inspected; preserving ${retiredPath}: ${sanitizeDockerStderr(inspected.stderr) || `docker buildx inspect exited ${inspected.exitCode}`}`,
299
+ ]
300
+ }
301
+
302
+ await rm(cacheRoot, { recursive: true, force: true })
303
+ await rm(buildxConfig, { recursive: true, force: true })
304
+ await rm(statePath, { force: true })
305
+ assertLock()
306
+ } catch (error) {
307
+ if (errorCode(error) === 'ELOCKED') {
308
+ warnings.push(`retired managed build cache is in use and was preserved at ${retiredPath}`)
309
+ } else {
310
+ warnings.push(`retired managed build cache was preserved at ${retiredPath}: ${describeError(error)}`)
311
+ }
312
+ } finally {
313
+ try {
314
+ await releaseLock(release)
315
+ } catch (error) {
316
+ warnings.push(`retired managed build cache lock release failed at ${retiredPath}: ${describeError(error)}`)
317
+ }
318
+ }
319
+
320
+ if (warnings.length === 0) {
321
+ try {
322
+ await rmdir(retiredPath)
323
+ } catch (error) {
324
+ if (errorCode(error) !== 'ENOENT') {
325
+ warnings.push(
326
+ `retired managed build cache root could not be removed at ${retiredPath}: ${describeError(error)}`,
327
+ )
328
+ }
329
+ }
330
+ }
331
+ return warnings
332
+ }
333
+
334
+ async function finishLease(options: {
335
+ exec: DockerExec
336
+ builder: ManagedBuildxBuilder
337
+ generationsPath: string
338
+ activePath: string
339
+ generationId: string
340
+ stagingPath: string
341
+ success: boolean
342
+ assertLock: () => void
343
+ release: () => Promise<void>
344
+ removeGeneration?: (path: string) => Promise<void>
345
+ beforeActivePersist?: () => void | Promise<void>
346
+ }): Promise<{ warnings: string[] }> {
347
+ const warnings: string[] = []
348
+ try {
349
+ options.assertLock()
350
+ const ownership = await validateOwnership(options.exec, options.builder)
351
+ options.assertLock()
352
+ if (!ownership.ok) {
353
+ warnings.push(ownership.reason)
354
+ await removeStaging(options.stagingPath, warnings)
355
+ } else {
356
+ try {
357
+ if (options.success) await promoteSuccessfulCache(options, warnings)
358
+ else await removeStaging(options.stagingPath, warnings)
359
+ } catch (error) {
360
+ warnings.push(`managed build cache rotation failed: ${describeError(error)}`)
361
+ await removeStaging(options.stagingPath, warnings)
362
+ } finally {
363
+ try {
364
+ options.assertLock()
365
+ const cleanupFailure = await removeExplicitOwnedBuilder(options.exec, options.builder)
366
+ options.assertLock()
367
+ if (cleanupFailure !== null) {
368
+ warnings.push(`managed builder removal failed for ${options.builder.builderName}: ${cleanupFailure}`)
369
+ }
370
+ } catch (error) {
371
+ warnings.push(`managed builder removal refused for ${options.builder.builderName}: ${describeError(error)}`)
372
+ }
373
+ }
374
+ }
375
+ } catch (error) {
376
+ warnings.push(`managed build cache rotation/builder removal refused: ${describeError(error)}`)
377
+ } finally {
378
+ try {
379
+ await options.release()
380
+ } catch (error) {
381
+ warnings.push(`managed build cache lock release failed: ${describeError(error)}`)
382
+ }
383
+ }
384
+ return { warnings }
385
+ }
386
+
387
+ async function promoteSuccessfulCache(
388
+ options: {
389
+ generationsPath: string
390
+ activePath: string
391
+ generationId: string
392
+ stagingPath: string
393
+ assertLock: () => void
394
+ removeGeneration?: (path: string) => Promise<void>
395
+ beforeActivePersist?: () => void | Promise<void>
396
+ },
397
+ warnings: string[],
398
+ ): Promise<void> {
399
+ const staging = await inspectDirectory(options.stagingPath)
400
+ options.assertLock()
401
+ if (staging === 'missing') {
402
+ warnings.push('managed build succeeded but did not export the expected local cache; retaining the previous cache')
403
+ return
404
+ }
405
+ if (staging !== 'directory') {
406
+ warnings.push('managed build cache export path is not a private directory; retaining the previous cache')
407
+ return
408
+ }
409
+
410
+ // Publish the pointer before pruning: a prune failure only leaves a spare
411
+ // generation for the next acquire to collect, while pruning first would strand
412
+ // the old pointer on a deleted directory if this write fails.
413
+ try {
414
+ await options.beforeActivePersist?.()
415
+ options.assertLock()
416
+ await persistJson(options.activePath, {
417
+ version: ACTIVE_VERSION,
418
+ generationId: options.generationId,
419
+ })
420
+ options.assertLock()
421
+ } catch (error) {
422
+ warnings.push(`managed build cache pointer promotion failed: ${describeError(error)}`)
423
+ await removeStaging(options.stagingPath, warnings)
424
+ return
425
+ }
426
+
427
+ try {
428
+ await removeInactiveGenerations(
429
+ options.generationsPath,
430
+ options.generationId,
431
+ options.assertLock,
432
+ options.removeGeneration,
433
+ )
434
+ } catch (error) {
435
+ warnings.push(`managed build cache generation cleanup failed: ${describeError(error)}`)
436
+ }
437
+ }
438
+
439
+ async function validateOwnership(
440
+ exec: DockerExec,
441
+ builder: ManagedBuildxBuilder,
442
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
443
+ if (!BUILDER_NAME.test(builder.builderName)) {
444
+ return { ok: false, reason: 'refusing managed cache rotation/builder removal for a non-TypeClaw builder name' }
445
+ }
446
+ const daemon = await queryDaemonId(exec)
447
+ if (!daemon.ok || daemon.daemonId !== builder.daemonId) {
448
+ return { ok: false, reason: 'refusing managed cache rotation/builder removal after Docker daemon identity changed' }
449
+ }
450
+ const ownership = await readState(builder.statePath, builder.daemonId)
451
+ if (!ownership.ok || ownership.state?.status !== 'ready' || ownership.state.builderName !== builder.builderName) {
452
+ return {
453
+ ok: false,
454
+ reason: 'refusing managed cache rotation/builder removal without matching daemon-scoped ownership state',
455
+ }
456
+ }
457
+ const inspected = await exec(['buildx', 'inspect', builder.builderName], { env: builder.env })
458
+ if (inspected.exitCode !== 0) {
459
+ return { ok: false, reason: 'refusing managed cache rotation/builder removal for a missing managed builder' }
460
+ }
461
+ return { ok: true }
462
+ }
463
+
464
+ async function queryDaemonId(
465
+ exec: DockerExec,
466
+ ): Promise<{ ok: true; daemonId: string } | { ok: false; reason: string }> {
467
+ try {
468
+ const result = await exec(['info', '--format', '{{.ID}}'])
469
+ const daemonId = result.stdout.trim()
470
+ if (result.exitCode !== 0 || daemonId.length === 0) {
471
+ return { ok: false, reason: sanitizeDockerStderr(result.stderr) || 'docker info returned no daemon ID' }
472
+ }
473
+ return { ok: true, daemonId }
474
+ } catch (error) {
475
+ return { ok: false, reason: describeError(error) }
476
+ }
477
+ }
478
+
479
+ async function prepareLocked(
480
+ exec: DockerExec,
481
+ builder: Omit<ManagedBuildxBuilder, 'builderName'>,
482
+ randomName: () => string,
483
+ assertLock: () => void,
484
+ beforeReadyPersist?: () => void | Promise<void>,
485
+ ): Promise<{ ok: true; builder: ManagedBuildxBuilder } | { ok: false; reason: string }> {
486
+ assertLock()
487
+ const stored = await readState(builder.statePath, builder.daemonId)
488
+ if (!stored.ok) return stored
489
+
490
+ if (stored.state?.status === 'ready') {
491
+ const inspected = await exec(['buildx', 'inspect', stored.state.builderName], { env: builder.env })
492
+ assertLock()
493
+ if (inspected.exitCode === 0) return { ok: true, builder: { ...builder, builderName: stored.state.builderName } }
494
+ return await createOwnedBuilder(exec, builder, stored.state, assertLock, beforeReadyPersist)
495
+ }
496
+
497
+ if (stored.state?.status === 'reserved') {
498
+ const inspected = await exec(['buildx', 'inspect', stored.state.builderName], { env: builder.env })
499
+ assertLock()
500
+ if (inspected.exitCode !== 0)
501
+ return await createOwnedBuilder(exec, builder, stored.state, assertLock, beforeReadyPersist)
502
+ await persistJson(builder.statePath, { ...stored.state, status: 'ready' })
503
+ assertLock()
504
+ return { ok: true, builder: { ...builder, builderName: stored.state.builderName } }
505
+ }
506
+
507
+ for (let attempt = 0; attempt < 8; attempt += 1) {
508
+ const builderName = randomName()
509
+ if (builderName.length !== 33 || !BUILDER_NAME.test(builderName)) {
510
+ return { ok: false, reason: 'generated an invalid managed builder name' }
511
+ }
512
+ const inspected = await exec(['buildx', 'inspect', builderName], { env: builder.env })
513
+ assertLock()
514
+ if (inspected.exitCode === 0) continue
515
+ const reserved: BuilderState = {
516
+ version: STATE_VERSION,
517
+ daemonId: builder.daemonId,
518
+ builderName,
519
+ status: 'reserved',
520
+ }
521
+ await persistJson(builder.statePath, reserved)
522
+ assertLock()
523
+ return await createOwnedBuilder(exec, builder, reserved, assertLock, beforeReadyPersist)
524
+ }
525
+ return { ok: false, reason: 'could not allocate a collision-free managed builder name' }
526
+ }
527
+
528
+ async function createOwnedBuilder(
529
+ exec: DockerExec,
530
+ builder: Omit<ManagedBuildxBuilder, 'builderName'>,
531
+ reserved: BuilderState,
532
+ assertLock: () => void,
533
+ beforeReadyPersist?: () => void | Promise<void>,
534
+ ): Promise<{ ok: true; builder: ManagedBuildxBuilder } | { ok: false; reason: string }> {
535
+ const created = await exec(['buildx', 'create', '--driver', 'docker-container', '--name', reserved.builderName], {
536
+ env: builder.env,
537
+ })
538
+ if (created.exitCode !== 0) {
539
+ assertLock()
540
+ return {
541
+ ok: false,
542
+ reason: sanitizeDockerStderr(created.stderr) || `docker buildx create exited ${created.exitCode}`,
543
+ }
544
+ }
545
+ const ownedBuilder = { ...builder, builderName: reserved.builderName }
546
+ try {
547
+ assertLock()
548
+ await beforeReadyPersist?.()
549
+ await persistJson(builder.statePath, { ...reserved, status: 'ready' })
550
+ assertLock()
551
+ return { ok: true, builder: ownedBuilder }
552
+ } catch (error) {
553
+ const reason = `managed builder ready-state persistence failed: ${describeError(error)}`
554
+ const cleanupFailure = await removeExplicitOwnedBuilder(exec, ownedBuilder)
555
+ return {
556
+ ok: false,
557
+ reason:
558
+ cleanupFailure === null
559
+ ? reason
560
+ : `${reason} ${builderFirstRecovery(ownedBuilder, dirname(builder.statePath), cleanupFailure)}`,
561
+ }
562
+ }
563
+ }
564
+
565
+ async function readState(
566
+ path: string,
567
+ daemonId: string,
568
+ ): Promise<{ ok: true; state: BuilderState | null } | { ok: false; reason: string }> {
569
+ const file = await readRegularFile(path, 'managed builder ownership state')
570
+ if (!file.ok || file.raw === null) return file.ok ? { ok: true, state: null } : file
571
+ try {
572
+ const value: unknown = JSON.parse(file.raw)
573
+ if (!isBuilderState(value) || value.daemonId !== daemonId) {
574
+ return { ok: false, reason: 'managed builder ownership state is invalid' }
575
+ }
576
+ return { ok: true, state: value }
577
+ } catch (error) {
578
+ return { ok: false, reason: `managed builder ownership state is invalid: ${describeError(error)}` }
579
+ }
580
+ }
581
+
582
+ async function readOwnedState(
583
+ path: string,
584
+ ): Promise<{ ok: true; state: BuilderState | null } | { ok: false; reason: string }> {
585
+ const file = await readRegularFile(path, 'managed builder ownership state')
586
+ if (!file.ok || file.raw === null) return file.ok ? { ok: true, state: null } : file
587
+ try {
588
+ const value: unknown = JSON.parse(file.raw)
589
+ return isBuilderState(value)
590
+ ? { ok: true, state: value }
591
+ : { ok: false, reason: 'managed builder ownership state is invalid' }
592
+ } catch (error) {
593
+ return { ok: false, reason: `managed builder ownership state is invalid: ${describeError(error)}` }
594
+ }
595
+ }
596
+
597
+ async function readActiveCache(
598
+ activePath: string,
599
+ generationsPath: string,
600
+ ): Promise<{ ok: true; generationId: string | null } | { ok: false; reason: string }> {
601
+ const file = await readRegularFile(activePath, 'managed cache active pointer')
602
+ if (!file.ok || file.raw === null) return file.ok ? { ok: true, generationId: null } : file
603
+ try {
604
+ const value: unknown = JSON.parse(file.raw)
605
+ if (!isActiveCache(value)) return { ok: false, reason: 'managed cache active pointer is invalid' }
606
+ const kind = await inspectDirectory(join(generationsPath, value.generationId))
607
+ if (kind === 'missing') {
608
+ await rm(activePath, { force: true })
609
+ return { ok: true, generationId: null }
610
+ }
611
+ if (kind !== 'directory') return { ok: false, reason: 'managed cache active generation is not a private directory' }
612
+ return { ok: true, generationId: value.generationId }
613
+ } catch (error) {
614
+ return { ok: false, reason: `managed cache active pointer is invalid: ${describeError(error)}` }
615
+ }
616
+ }
617
+
618
+ async function readRegularFile(
619
+ path: string,
620
+ label: string,
621
+ ): Promise<{ ok: true; raw: string | null } | { ok: false; reason: string }> {
622
+ try {
623
+ const info = await lstat(path)
624
+ if (info.isSymbolicLink() || !info.isFile()) return { ok: false, reason: `${label} is not a regular file` }
625
+ return { ok: true, raw: await readFile(path, 'utf8') }
626
+ } catch (error) {
627
+ if (errorCode(error) === 'ENOENT') return { ok: true, raw: null }
628
+ return { ok: false, reason: describeError(error) }
629
+ }
630
+ }
631
+
632
+ async function reserveGenerationId(
633
+ generationsPath: string,
634
+ randomGenerationId: () => string,
635
+ ): Promise<{ ok: true; generationId: string } | { ok: false; reason: string }> {
636
+ for (let attempt = 0; attempt < 8; attempt += 1) {
637
+ const generationId = randomGenerationId()
638
+ if (generationId.length !== 32 || !GENERATION_ID.test(generationId)) {
639
+ return { ok: false, reason: 'generated an invalid managed cache generation ID' }
640
+ }
641
+ if ((await inspectDirectory(join(generationsPath, generationId))) === 'missing') {
642
+ return { ok: true, generationId }
643
+ }
644
+ }
645
+ return { ok: false, reason: 'could not allocate a collision-free managed cache generation ID' }
646
+ }
647
+
648
+ async function removeInactiveGenerations(
649
+ generationsPath: string,
650
+ retainedGenerationId: string | null,
651
+ assertLock: () => void,
652
+ removeGeneration: (path: string) => Promise<void> = async (path) => await rm(path, { recursive: true, force: true }),
653
+ ): Promise<void> {
654
+ for (const entry of await readdir(generationsPath, { withFileTypes: true })) {
655
+ assertLock()
656
+ if (!GENERATION_ID.test(entry.name))
657
+ throw new Error(`managed cache contains an invalid generation name: ${entry.name}`)
658
+ if (entry.isSymbolicLink() || !entry.isDirectory()) {
659
+ throw new Error(`managed cache generation is not a directory: ${entry.name}`)
660
+ }
661
+ if (entry.name !== retainedGenerationId) await removeGeneration(join(generationsPath, entry.name))
662
+ }
663
+ }
664
+
665
+ async function removeStaging(path: string, warnings: string[]): Promise<void> {
666
+ try {
667
+ await rm(path, { recursive: true, force: true })
668
+ } catch (error) {
669
+ warnings.push(`managed build cache staging cleanup failed: ${describeError(error)}`)
670
+ }
671
+ }
672
+
673
+ async function inspectDirectory(path: string): Promise<'directory' | 'missing' | 'unsafe'> {
674
+ try {
675
+ const info = await lstat(path)
676
+ if (info.isSymbolicLink() || !info.isDirectory()) return 'unsafe'
677
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
678
+ if (uid !== undefined && info.uid !== uid) return 'unsafe'
679
+ await chmod(path, 0o700)
680
+ return 'directory'
681
+ } catch (error) {
682
+ if (errorCode(error) === 'ENOENT') return 'missing'
683
+ throw error
684
+ }
685
+ }
686
+
687
+ async function validatePrivateTree(path: string): Promise<void> {
688
+ const info = await lstat(path)
689
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
690
+ if (info.isSymbolicLink() || (uid !== undefined && info.uid !== uid)) {
691
+ throw new Error(`managed build cache tree contains an unsafe path: ${path}`)
692
+ }
693
+ if (!info.isDirectory()) return
694
+ await chmod(path, 0o700)
695
+ for (const entry of await readdir(path)) await validatePrivateTree(join(path, entry))
696
+ }
697
+
698
+ async function ensurePrivateDirectory(path: string): Promise<void> {
699
+ await mkdir(path, { recursive: true, mode: 0o700 })
700
+ const info = await lstat(path)
701
+ if (info.isSymbolicLink() || !info.isDirectory())
702
+ throw new Error(`managed build cache path is not a directory: ${path}`)
703
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
704
+ if (uid !== undefined && info.uid !== uid) {
705
+ throw new Error(`managed build cache path is not owned by the current user: ${path}`)
706
+ }
707
+ await chmod(path, 0o700)
708
+ }
709
+
710
+ async function rejectSymlink(path: string): Promise<void> {
711
+ try {
712
+ if ((await lstat(path)).isSymbolicLink()) throw new Error(`managed build cache lock path is a symlink: ${path}`)
713
+ } catch (error) {
714
+ if (errorCode(error) !== 'ENOENT') throw error
715
+ }
716
+ }
717
+
718
+ function isBuilderState(value: unknown): value is BuilderState {
719
+ if (typeof value !== 'object' || value === null) return false
720
+ const record = value as Record<string, unknown>
721
+ return (
722
+ record.version === STATE_VERSION &&
723
+ typeof record.daemonId === 'string' &&
724
+ typeof record.builderName === 'string' &&
725
+ record.builderName.length === 33 &&
726
+ BUILDER_NAME.test(record.builderName) &&
727
+ (record.status === 'reserved' || record.status === 'ready')
728
+ )
729
+ }
730
+
731
+ function isActiveCache(value: unknown): value is ActiveCache {
732
+ if (typeof value !== 'object' || value === null) return false
733
+ const record = value as Record<string, unknown>
734
+ return (
735
+ record.version === ACTIVE_VERSION &&
736
+ typeof record.generationId === 'string' &&
737
+ record.generationId.length === 32 &&
738
+ GENERATION_ID.test(record.generationId)
739
+ )
740
+ }
741
+
742
+ function isHashDirectory(value: string): boolean {
743
+ return value.length === 64 && HASH_DIRECTORY.test(value)
744
+ }
745
+
746
+ function isOwnershipStateReason(reason: string): boolean {
747
+ return reason.startsWith('managed builder ownership state')
748
+ }
749
+
750
+ function recoveryReason(reason: string, resetPath: string): string {
751
+ return `${reason}. Remove ${resetPath} and retry.`
752
+ }
753
+
754
+ async function removeExplicitOwnedBuilder(exec: DockerExec, builder: ManagedBuildxBuilder): Promise<string | null> {
755
+ try {
756
+ const result = await exec(['buildx', 'rm', builder.builderName], { env: builder.env })
757
+ return result.exitCode === 0
758
+ ? null
759
+ : sanitizeDockerStderr(result.stderr) || `docker buildx rm exited ${result.exitCode}`
760
+ } catch (error) {
761
+ return describeError(error)
762
+ }
763
+ }
764
+
765
+ function builderFirstRecovery(builder: ManagedBuildxBuilder, statePath: string, failure: string): string {
766
+ return (
767
+ `Owned builder cleanup failed: ${failure}. Remove builder ${builder.builderName} first with ` +
768
+ `\`BUILDX_CONFIG="${builder.env.BUILDX_CONFIG}" docker buildx rm ${builder.builderName}\`, ` +
769
+ `then remove ${statePath} and retry.`
770
+ )
771
+ }
772
+
773
+ function isMissingBuildxBuilder(stderr: string): boolean {
774
+ return /(?:no builder|not found|does not exist)/i.test(stderr)
775
+ }
776
+
777
+ async function persistJson(path: string, value: BuilderState | ActiveCache): Promise<void> {
778
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
779
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`
780
+ try {
781
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
782
+ await chmod(temporary, 0o600)
783
+ await rename(temporary, path)
784
+ } finally {
785
+ await rm(temporary, { force: true }).catch((error: unknown) => {
786
+ if (errorCode(error) !== 'ENOENT') throw error
787
+ })
788
+ }
789
+ }
790
+
791
+ async function releaseLock(release: (() => Promise<void>) | null): Promise<void> {
792
+ if (release === null) return
793
+ try {
794
+ await release()
795
+ } catch (error) {
796
+ if (errorCode(error) !== 'ERELEASED') throw error
797
+ }
798
+ }
799
+
800
+ function errorCode(error: unknown): string | undefined {
801
+ if (typeof error !== 'object' || error === null || !('code' in error)) return undefined
802
+ return typeof error.code === 'string' ? error.code : undefined
803
+ }
804
+
805
+ function describeError(error: unknown): string {
806
+ return error instanceof Error ? error.message : String(error)
807
+ }