@vzn/vx 0.0.16 → 0.0.21

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 (138) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +135 -124
  3. package/index.ts +10 -0
  4. package/launcher.mjs +10 -11
  5. package/package.json +11 -7
  6. package/src/bin.ts +14 -4
  7. package/src/cache/archive.ts +659 -0
  8. package/src/cache/cache.ts +769 -1101
  9. package/src/cache/chained-cache.ts +194 -0
  10. package/src/cache/config-evals.ts +89 -0
  11. package/src/cache/file-hashes.ts +262 -0
  12. package/src/cache/git-inputs.ts +637 -0
  13. package/src/cache/index.ts +24 -5
  14. package/src/cache/inputs.ts +373 -456
  15. package/src/cache/layer.ts +604 -0
  16. package/src/cache/layered-cache.ts +96 -43
  17. package/src/cache/output-index.ts +224 -0
  18. package/src/cache/policy.ts +84 -0
  19. package/src/cache/run-history.ts +147 -0
  20. package/src/cache/tar-stream.ts +358 -0
  21. package/src/cache/zstd.ts +160 -0
  22. package/src/cli/cache.ts +75 -21
  23. package/src/cli/completions.ts +104 -0
  24. package/src/cli/core-alias.ts +25 -0
  25. package/src/cli/help.ts +195 -128
  26. package/src/cli/index.ts +116 -46
  27. package/src/cli/info.ts +122 -63
  28. package/src/cli/init.ts +75 -0
  29. package/src/cli/last.ts +172 -0
  30. package/src/cli/lock.ts +2 -1
  31. package/src/cli/plan-format.ts +72 -6
  32. package/src/cli/plugin-commands.ts +103 -0
  33. package/src/cli/run.ts +245 -271
  34. package/src/cli/select.ts +332 -0
  35. package/src/cli/show.ts +144 -69
  36. package/src/cli/upgrade.ts +9 -7
  37. package/src/cli/watch.ts +858 -110
  38. package/src/cli/why.ts +223 -0
  39. package/src/cli/workspace-config.ts +126 -0
  40. package/src/config.ts +187 -150
  41. package/src/exec/env.ts +18 -1
  42. package/src/exec/executor.ts +224 -0
  43. package/src/exec/index.ts +24 -2
  44. package/src/exec/local-executor.ts +41 -0
  45. package/src/exec/runner.ts +166 -40
  46. package/src/exec/sandbox-binds.ts +182 -0
  47. package/src/exec/sandbox-paths.ts +50 -0
  48. package/src/exec/sandbox-runtime.ts +642 -260
  49. package/src/exec/sandbox-violations.ts +280 -0
  50. package/src/graph/index.ts +4 -10
  51. package/src/graph/scheduler.ts +232 -203
  52. package/src/graph/task-graph.ts +222 -8
  53. package/src/index.ts +146 -153
  54. package/src/orchestrator/admission.ts +137 -0
  55. package/src/orchestrator/deferred-outputs.ts +147 -0
  56. package/src/orchestrator/doctor.ts +255 -0
  57. package/src/orchestrator/download-policy.ts +171 -0
  58. package/src/orchestrator/events.ts +72 -8
  59. package/src/orchestrator/execute-task.ts +374 -549
  60. package/src/orchestrator/failure-mode.ts +202 -0
  61. package/src/orchestrator/framed-output.ts +126 -69
  62. package/src/orchestrator/history.ts +126 -59
  63. package/src/orchestrator/hit-restore.ts +221 -0
  64. package/src/orchestrator/index.ts +77 -93
  65. package/src/orchestrator/local-shortcircuit.ts +22 -0
  66. package/src/orchestrator/lockfile-claim.ts +281 -0
  67. package/src/orchestrator/logger.ts +208 -35
  68. package/src/orchestrator/metrics.ts +102 -1388
  69. package/src/orchestrator/miss-save.ts +169 -0
  70. package/src/orchestrator/options.ts +55 -34
  71. package/src/orchestrator/persistent.ts +79 -0
  72. package/src/orchestrator/placement.ts +182 -0
  73. package/src/orchestrator/plan.ts +144 -1
  74. package/src/orchestrator/plugin-host.ts +357 -120
  75. package/src/orchestrator/plugin.ts +298 -58
  76. package/src/orchestrator/prepare.ts +202 -106
  77. package/src/orchestrator/projects.ts +259 -0
  78. package/src/orchestrator/remote-prefetch.ts +12 -8
  79. package/src/orchestrator/run-artifacts.ts +63 -16
  80. package/src/orchestrator/run-context.ts +167 -29
  81. package/src/orchestrator/run-records.ts +149 -0
  82. package/src/orchestrator/run-report.ts +74 -47
  83. package/src/orchestrator/run.ts +534 -417
  84. package/src/orchestrator/sandbox-request.ts +243 -0
  85. package/src/orchestrator/save-lane.ts +47 -0
  86. package/src/orchestrator/signals.ts +111 -0
  87. package/src/orchestrator/stable-keys.ts +129 -31
  88. package/src/orchestrator/status-line.ts +49 -9
  89. package/src/orchestrator/summary.ts +90 -26
  90. package/src/orchestrator/tally.ts +78 -35
  91. package/src/orchestrator/task-hash.ts +111 -15
  92. package/src/orchestrator/task-log-buffer.ts +288 -0
  93. package/src/orchestrator/telemetry-host.ts +34 -6
  94. package/src/orchestrator/telemetry.ts +182 -36
  95. package/src/orchestrator/upstream.ts +72 -31
  96. package/src/util/cgroup.ts +160 -0
  97. package/src/util/edit-distance.ts +70 -0
  98. package/src/util/errors.ts +15 -1
  99. package/src/util/index.ts +15 -2
  100. package/src/util/num.ts +37 -0
  101. package/src/util/paths.ts +64 -0
  102. package/src/util/settle.ts +67 -0
  103. package/src/util/size.ts +5 -1
  104. package/src/util/tail.ts +66 -0
  105. package/src/util/timing.ts +63 -0
  106. package/src/util/verbs.ts +39 -0
  107. package/src/workspace/affected.ts +250 -23
  108. package/src/workspace/config-cache.ts +313 -0
  109. package/src/workspace/config-eval.ts +217 -0
  110. package/src/workspace/config-imports.ts +162 -0
  111. package/src/workspace/config-schema.ts +837 -0
  112. package/src/workspace/filter.ts +65 -10
  113. package/src/workspace/fingerprint.ts +53 -4
  114. package/src/workspace/index.ts +42 -3
  115. package/src/workspace/lockfile.ts +25 -9
  116. package/src/workspace/migrate-scripts.ts +134 -0
  117. package/src/workspace/migration.ts +314 -0
  118. package/src/workspace/nested-dirs.ts +21 -7
  119. package/src/workspace/package-graph.ts +114 -41
  120. package/src/workspace/project-loader.ts +224 -450
  121. package/src/workspace/workspace.ts +298 -72
  122. package/src/cache/cas-backend.ts +0 -97
  123. package/src/cache/digest.ts +0 -47
  124. package/src/cache/tar.ts +0 -343
  125. package/src/cli/backend.ts +0 -23
  126. package/src/cli/mcp-rpc.ts +0 -292
  127. package/src/cli/mcp.ts +0 -92
  128. package/src/cli/migrate-nx.ts +0 -450
  129. package/src/cli/migrate-turbo.ts +0 -364
  130. package/src/cli/migrate.ts +0 -219
  131. package/src/orchestrator/devframe-surface.ts +0 -74
  132. package/src/orchestrator/predict.ts +0 -106
  133. package/src/orchestrator/protocol.ts +0 -156
  134. package/src/orchestrator/resources.ts +0 -59
  135. package/src/orchestrator/run-state.ts +0 -145
  136. package/src/orchestrator/verify.ts +0 -164
  137. package/src/orchestrator/wire-render.ts +0 -92
  138. package/src/orchestrator/wire.ts +0 -212
@@ -17,23 +17,30 @@
17
17
  // monitor in real time; violations carry the offending command +
18
18
  // syscall line, so we get structured detection.
19
19
  // Linux — bwrap denies the read at the kernel boundary; the child
20
- // sees ENOENT (or EPERM for some operations). SRT doesn't surface
21
- // structured events for Linux, so detection is enforcement-only.
20
+ // sees ENOENT (or EPERM for some operations). SRT surfaces no
21
+ // structured events there, so we wrap the spawn in strace and parse
22
+ // the trace ourselves (`deniedCalls`) — detection is NOT
23
+ // enforcement-only on Linux, and the fail-on-violation branch in
24
+ // execute-task is live on both platforms.
22
25
 
23
26
  import path from 'node:path'
24
27
  import os from 'node:os'
25
- import { realpathSync } from 'node:fs'
26
- import { unlink } from 'node:fs/promises'
27
- import type { SandboxConfig, SandboxNetworkConfig } from '../config.js'
28
+ import { mkdir, unlink } from 'node:fs/promises'
29
+ import type { SandboxConfig } from '../config.js'
28
30
  import {
29
31
  armTimeout,
32
+ drainOrAbort,
30
33
  shellQuote,
31
34
  signalExitCode,
32
35
  streamToString,
33
36
  resourceUsageToCpuRss,
37
+ type CaptureConfig,
34
38
  type RunResult,
35
39
  } from './runner.js'
36
- import { xxh3hex } from '../util/index.js'
40
+ import { UserError, xxh3hex } from '../util/index.js'
41
+ import { buildCustomConfig } from './sandbox-binds.js'
42
+ import { localBindingOn, toRealPath, unique } from './sandbox-paths.js'
43
+ import { parseStraceViolations, reportableViolations } from './sandbox-violations.js'
37
44
 
38
45
  type SrtModule = typeof import('@anthropic-ai/sandbox-runtime')
39
46
  let srtPromise: Promise<SrtModule> | undefined
@@ -49,62 +56,127 @@ export interface SandboxAvailability {
49
56
  reason: string
50
57
  }
51
58
 
52
- let availabilityCache: SandboxAvailability | undefined
59
+ /** One verdict per mode: the wrapper the probe runs differs by mode. */
60
+ const availabilityCache = new Map<'secure' | 'weaker', SandboxAvailability>()
53
61
 
54
62
  /**
55
- * Probe whether SRT can sandbox on this host. Memoized — the binary
56
- * presence + platform check doesn't change within a process.
63
+ * Probe whether SRT can sandbox on this host. Memoized per mode — the
64
+ * binary presence + platform check doesn't change within a process.
57
65
  *
58
66
  * In addition to SRT's own `checkDependencies` (which only verifies
59
- * binary presence on PATH), this runs a minimal bwrap invocation on
60
- * Linux to catch the "bwrap installed but unprivileged user namespaces
61
- * blocked by AppArmor / sysctl" case that's the default on stock
62
- * Ubuntu 24.04. Without this real-execution probe, the unavailability
63
- * surfaces only at the first task spawn, deep inside the orchestrator.
67
+ * binary presence on PATH), this runs ONE sandboxed `true` on Linux
68
+ * through SRT's own wrapper: bwrap with the runtime's namespace flags
69
+ * plus its vendored seccomp helper, which creates a NESTED user
70
+ * namespace. A bare `bwrap … /bin/true` (the probe until 2026-09-04)
71
+ * passed on hosts where every task then failed — as root inside a
72
+ * container, the helper's `write /proc/self/uid_map` is EPERM under
73
+ * `--cap-drop ALL`. Without this real-execution probe the
74
+ * unavailability surfaces only at the first task spawn, deep inside the
75
+ * orchestrator, as exit 1 with the helper's line in the task's stderr.
76
+ *
77
+ * `weakerNested` probes with `enableWeakerNestedSandbox`; the caller
78
+ * passes it only when EVERY sandboxed task opts in, since the secure
79
+ * wrapper is what any other task will run under.
80
+ *
81
+ * On Linux the probe INITIALIZES SRT (idempotent — `run()` initializes
82
+ * right after anyway), and SRT's proxy sockets then keep the event loop
83
+ * alive: a standalone caller must `resetSandbox()` or exit. CI's
84
+ * diagnostic `bun -e` step sat on this for its whole 10-minute timeout
85
+ * (2026-09-04).
64
86
  */
65
- export async function probeSandbox(): Promise<SandboxAvailability> {
66
- if (availabilityCache) return availabilityCache
87
+ export async function probeSandbox(opts?: {
88
+ weakerNested?: boolean
89
+ }): Promise<SandboxAvailability> {
90
+ const mode = opts?.weakerNested === true ? 'weaker' : 'secure'
91
+ const cached = availabilityCache.get(mode)
92
+ if (cached) return cached
93
+ const verdict = await probeUncached(mode === 'weaker')
94
+ availabilityCache.set(mode, verdict)
95
+ return verdict
96
+ }
97
+
98
+ async function probeUncached(weakerNested: boolean): Promise<SandboxAvailability> {
67
99
  const { SandboxManager } = await loadSrt()
68
100
  if (!SandboxManager.isSupportedPlatform()) {
69
- availabilityCache = { available: false, reason: `platform ${process.platform} not supported` }
70
- return availabilityCache
101
+ return { available: false, reason: `platform ${process.platform} not supported` }
71
102
  }
72
103
  const deps = SandboxManager.checkDependencies()
73
- if (deps.errors.length > 0) {
74
- availabilityCache = { available: false, reason: deps.errors.join('; ') }
75
- return availabilityCache
76
- }
77
- // Linux only: real-execution probe. Run `bwrap` with the minimal
78
- // user-namespace invocation it'd attempt for a sandboxed task; if
79
- // the kernel rejects (AppArmor / sysctl), surface that here.
104
+ if (deps.errors.length > 0) return { available: false, reason: deps.errors.join('; ') }
80
105
  if (process.platform === 'linux') {
81
- const ok = await tryBwrapOnce()
82
- if (!ok.available) {
83
- availabilityCache = ok
84
- return availabilityCache
106
+ await initSandbox()
107
+ return trySandboxedTrue(SandboxManager, weakerNested)
108
+ }
109
+ return applyPolicyHere()
110
+ }
111
+
112
+ /**
113
+ * Can a seatbelt policy be applied in THIS process at all?
114
+ *
115
+ * Not if one already is: macOS refuses `sandbox_apply` inside a sandbox,
116
+ * at any permission level — an inner profile of `(allow default)` still
117
+ * dies `sandbox_apply: Operation not permitted` (exit 71, measured
118
+ * 2026-09-05). No grant fixes it, so the honest verdict is "unavailable",
119
+ * which is what stops a sandboxed task from spawning tasks that report
120
+ * a sandbox they never got. Answering `available: true` here is how a
121
+ * suite that exercises the sandbox came to fail sixteen ways at once.
122
+ *
123
+ * The probe costs one `/usr/bin/true` and is memoized with the rest.
124
+ */
125
+ function applyPolicyHere(): SandboxAvailability {
126
+ const proc = Bun.spawnSync({
127
+ cmd: ['sandbox-exec', '-p', '(version 1)(allow default)', '/usr/bin/true'],
128
+ stdout: 'ignore',
129
+ stderr: 'pipe',
130
+ })
131
+ if (proc.exitCode === 0) return { available: true, reason: '' }
132
+ const stderr = proc.stderr.toString().trim()
133
+ if (stderr.includes('sandbox_apply')) {
134
+ return {
135
+ available: false,
136
+ reason:
137
+ 'this process is already sandboxed and macOS cannot nest one — a task that ' +
138
+ 'itself sandboxes has to run without `exec.sandbox` of its own',
85
139
  }
86
140
  }
87
- availabilityCache = { available: true, reason: '' }
88
- return availabilityCache
141
+ return { available: false, reason: `sandbox-exec failed: ${stderr || `exit ${proc.exitCode}`}` }
142
+ }
143
+
144
+ /**
145
+ * Why the probe's sandboxed `true` failed, in the user's terms. The hint
146
+ * names the CONFIG field (`exec.sandbox.weakerWhenNested`), not the
147
+ * runtime option it maps to — a user who followed the runtime's name into
148
+ * their config met the loader's unknown-field refusal instead of a fix
149
+ * (`tests/sandbox-hint.test.ts` pins every field the hint names against
150
+ * the loader).
151
+ */
152
+ export function unavailableReason(exitCode: number | null, stderr: string): string {
153
+ const hint = stderr.includes('uid_map')
154
+ ? " — the runtime's seccomp helper cannot create its nested user namespace here (root inside a container, or a kernel that forbids nested user namespaces): run as a non-root user, or set `sandbox.weakerWhenNested: true` on every sandboxed task"
155
+ : ''
156
+ return `a sandboxed \`true\` failed (exit ${exitCode}): ${stderr.slice(0, 200)}${hint}`
89
157
  }
90
158
 
91
- async function tryBwrapOnce(): Promise<SandboxAvailability> {
159
+ async function trySandboxedTrue(
160
+ SandboxManager: SrtModule['SandboxManager'],
161
+ weakerNested: boolean,
162
+ ): Promise<SandboxAvailability> {
92
163
  try {
93
- const proc = Bun.spawn(
94
- ['bwrap', '--ro-bind', '/', '/', '--proc', '/proc', '--dev', '/dev', '/bin/true'],
95
- { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' },
164
+ const wrapped = await SandboxManager.wrapWithSandbox(
165
+ 'true',
166
+ undefined,
167
+ weakerNested ? { enableWeakerNestedSandbox: true } : undefined,
96
168
  )
97
- const stderr = await new Response(proc.stderr).text()
169
+ const proc = Bun.spawn(['sh', '-c', wrapped], {
170
+ stdout: 'ignore',
171
+ stderr: 'pipe',
172
+ stdin: 'ignore',
173
+ })
174
+ const stderr = (await new Response(proc.stderr).text()).trim()
98
175
  await proc.exited
99
- if (proc.exitCode !== 0) {
100
- return {
101
- available: false,
102
- reason: `bwrap probe failed (exit ${proc.exitCode}): ${stderr.trim().slice(0, 200)}`,
103
- }
104
- }
105
- return { available: true, reason: '' }
176
+ if (proc.exitCode === 0) return { available: true, reason: '' }
177
+ return { available: false, reason: unavailableReason(proc.exitCode, stderr) }
106
178
  } catch (err) {
107
- return { available: false, reason: `bwrap probe threw: ${(err as Error).message}` }
179
+ return { available: false, reason: `sandbox probe threw: ${(err as Error).message}` }
108
180
  }
109
181
  }
110
182
 
@@ -118,7 +190,7 @@ async function tryBwrapOnce(): Promise<SandboxAvailability> {
118
190
  *
119
191
  * Format mirrors SRT's: `'*'` is a wildcard pattern; entries in the
120
192
  * array are substring-matched against the violation details line.
121
- * Users can ADD to this via per-task `sandbox.ignoreViolations`;
193
+ * Users can ADD to this via per-task `sandbox.ignore`;
122
194
  * those are applied at violation read-back time, on top of the
123
195
  * defaults installed here.
124
196
  */
@@ -137,24 +209,76 @@ const DEFAULT_IGNORE_VIOLATIONS: Record<string, string[]> = {
137
209
  * Per-task wrapping passes a customConfig that re-enables network for
138
210
  * tasks with `sandbox.network: true`.
139
211
  */
140
- export async function initSandbox(): Promise<void> {
212
+ /**
213
+ * The temp directory SRT hands every sandboxed task. It overrides `TMPDIR`
214
+ * so temp-file writers land somewhere its filesystem policy already allows,
215
+ * and it deliberately does NOT create the directory — its own comment says
216
+ * "/tmp/claude may not exist". Nobody else does either, so on any machine
217
+ * that is not Claude Code's own, every sandboxed task that writes a temp
218
+ * file died with ENOENT: this repo's `bun build --compile` under
219
+ * a sandboxed `bun build --compile` reported only `error: An unknown error occurred
220
+ * (Unexpected)` (2026-09-04). Resolution mirrors SRT's exactly.
221
+ */
222
+ function sandboxTmpdir(): string {
223
+ // `process.env`, not `Bun.env`: a caller that REPLACES the env object
224
+ // (two tests here do, and an embedder may) leaves `Bun.env` pointing at
225
+ // the original, so a late assignment would be invisible.
226
+ const named = process.env['CLAUDE_CODE_TMPDIR'] ?? process.env['CLAUDE_TMPDIR']
227
+ return named !== undefined && named !== '' ? named : '/tmp/claude'
228
+ }
229
+
230
+ /**
231
+ * @param opts.allowedDomains every domain any sandboxed task in this run
232
+ * declared. SRT's filtering proxy is per-RUN and reads its allowlist from
233
+ * this call, never from the per-task config, so the union is the only
234
+ * place a domain list can take effect. Per-task precision survives where
235
+ * it matters: a task that declared none is never handed the proxy port.
236
+ */
237
+ export async function initSandbox(opts?: {
238
+ allowedDomains?: readonly string[]
239
+ /**
240
+ * Lift SRT's seccomp block on `socket(AF_UNIX)` for every sandboxed
241
+ * task of the run (Linux; per-run like the proxy allowlist, since SRT
242
+ * reads it at `initialize()` only). Armed when any task declares
243
+ * `unixSockets` or a `localBinding` port list — the port bridge is a
244
+ * unix socket the task's side has to create.
245
+ */
246
+ allowAllUnixSockets?: boolean
247
+ }): Promise<void> {
248
+ // Before SRT starts, so the very first task already has one.
249
+ await mkdir(sandboxTmpdir(), { recursive: true })
141
250
  const { SandboxManager } = await loadSrt()
142
- await SandboxManager.initialize(
143
- {
144
- network: { allowedDomains: [], deniedDomains: [] },
145
- filesystem: { denyRead: [], allowWrite: [], denyWrite: [] },
146
- ignoreViolations: DEFAULT_IGNORE_VIOLATIONS,
251
+ const config: Parameters<typeof SandboxManager.initialize>[0] = {
252
+ network: {
253
+ allowedDomains: [...(opts?.allowedDomains ?? [])],
254
+ deniedDomains: [],
255
+ ...(opts?.allowAllUnixSockets === true ? { allowAllUnixSockets: true } : {}),
147
256
  },
257
+ filesystem: { denyRead: [], allowWrite: [], denyWrite: [] },
258
+ ignoreViolations: DEFAULT_IGNORE_VIOLATIONS,
259
+ }
260
+ await SandboxManager.initialize(
261
+ config,
148
262
  undefined,
149
263
  // enableLogMonitor — macOS-only; populates the SandboxViolationStore.
150
264
  true,
151
265
  )
266
+ // `initialize()` returns early once SRT is up, and on Linux the
267
+ // availability probe brought it up with an EMPTY config before the run's
268
+ // own call — so the run's allowlist and unix-socket allowance never
269
+ // reached it (found 2026-09-10 by the port bridge: the task's side died
270
+ // on `socket(AF_UNIX)` with the flag set). `updateConfig` is SRT's hot
271
+ // reload of exactly these fields; the proxy and the wrapper read them
272
+ // through getters, so the run's config is what every task sees.
273
+ SandboxManager.updateConfig(config)
152
274
  }
153
275
 
154
276
  export async function resetSandbox(): Promise<void> {
277
+ for (const tag of [...hostBridges.keys()]) releaseBridges(tag)
155
278
  const { SandboxManager } = await loadSrt()
156
279
  await SandboxManager.reset()
157
- availabilityCache = undefined
280
+ availabilityCache.clear()
281
+ straceAvailableCache = undefined
158
282
  }
159
283
 
160
284
  export interface SandboxedRunArgs {
@@ -168,6 +292,8 @@ export interface SandboxedRunArgs {
168
292
  liveChildren?: Set<ReturnType<typeof Bun.spawn>>
169
293
  /** See `RunOptions.timeoutMs` — SIGTERM the child after this many ms. */
170
294
  timeoutMs?: number
295
+ /** See `CaptureConfig` — which streams are retained on the result. */
296
+ capture?: CaptureConfig
171
297
  /**
172
298
  * Baseline reads — paths the sandbox unconditionally allows. The
173
299
  * caller builds this from resolved `cache.inputs.files`.
@@ -184,6 +310,12 @@ export interface SandboxedRunArgs {
184
310
  * is forbidden. Pass `[workspaceRoot]` to enforce project boundaries.
185
311
  */
186
312
  baseDenyRead: readonly string[]
313
+ /**
314
+ * Only denials on a path under this directory are reported. A denial
315
+ * outside it is still ENFORCED — the task cannot leave its project — but
316
+ * that is the wall doing its job, not a finding to fail a run over.
317
+ */
318
+ readonly reportWithin: string
187
319
  /**
188
320
  * User-declared sandbox block (after path-resolution). Path lists are
189
321
  * unioned with the baselines; bool/object fields fall through to SRT.
@@ -197,33 +329,55 @@ export interface SandboxedRunArgs {
197
329
  * but every string in a path list is guaranteed absolute.
198
330
  */
199
331
  export interface ResolvedSandboxConfig {
332
+ /** Readable path prefixes, absolute. */
200
333
  allowRead: readonly string[]
334
+ /** Writable path prefixes, absolute. */
201
335
  allowWrite: readonly string[]
202
- allowGitConfig?: boolean
203
- network?: boolean | SandboxNetworkConfig
204
- allowPty?: boolean
205
- enableWeakerNestedSandbox?: boolean
206
- enableWeakerNetworkIsolation?: boolean
207
- ignoreViolations?: Record<string, string[]>
336
+ network?: true | readonly string[]
337
+ denyNetwork?: readonly string[]
338
+ systemInfo?: readonly string[]
339
+ unixSockets?: true | readonly string[]
340
+ localBinding?: boolean | readonly number[]
341
+ machLookup?: readonly string[]
342
+ pty?: boolean
343
+ gitConfig?: boolean
344
+ weakerWhenNested?: boolean
345
+ weakerNetworkIsolation?: boolean
346
+ ignore?: {
347
+ read?: readonly string[]
348
+ write?: readonly string[]
349
+ systemInfo?: readonly string[]
350
+ network?: readonly string[]
351
+ }
208
352
  }
209
353
 
210
354
  /**
211
- * Canonicalize a path with realpath, tolerating paths that don't exist
212
- * yet: resolve the longest existing ancestor and re-append the rest.
355
+ * Canonical form of every path the sandbox policy is expressed in.
213
356
  *
214
- * Why: the sandbox policy matches on canonical paths (macOS seatbelt
215
- * evaluates real vnode paths), and SRT's own normalization refuses to
216
- * canonicalize bare symlinked roots like `/tmp` → `/private/tmp` (its
217
- * boundary check only whitelists `/tmp/<child>` forms). Without this,
218
- * `allowWrite: ['/tmp']` silently never matches on macOS.
357
+ * `resolveSandboxConfig` already canonicalizes the USER's paths; the
358
+ * orchestrator-supplied baselines (resolved inputs, output prefixes, the
359
+ * workspace-root deny anchor) arrived raw, so a workspace reached through a
360
+ * symlink expressed HALF its policy in real paths and half in link paths.
361
+ * bwrap then died mounting the link path inside its new root
362
+ * (`Can't mount tmpfs on /newroot/<link>`) and EVERY sandboxed task failed —
363
+ * whatever the config, with an error naming an internal path the user has no
364
+ * way to act on. Canonicalizing here is what makes the two halves agree.
219
365
  */
220
- function toRealPath(p: string): string {
221
- try {
222
- return realpathSync(p)
223
- } catch {
224
- const parent = path.dirname(p)
225
- if (parent === p) return p
226
- return path.join(toRealPath(parent), path.basename(p))
366
+ interface CanonicalBaselines {
367
+ allowRead: string[]
368
+ allowWrite: string[]
369
+ denyRead: string[]
370
+ cwd: string
371
+ }
372
+
373
+ function canonicalBaselines(
374
+ args: Pick<SandboxedRunArgs, 'baseAllowRead' | 'baseAllowWrite' | 'baseDenyRead' | 'cwd'>,
375
+ ): CanonicalBaselines {
376
+ return {
377
+ allowRead: args.baseAllowRead.map(toRealPath),
378
+ allowWrite: args.baseAllowWrite.map(toRealPath),
379
+ denyRead: args.baseDenyRead.map(toRealPath),
380
+ cwd: toRealPath(args.cwd),
227
381
  }
228
382
  }
229
383
 
@@ -242,20 +396,35 @@ export function resolveSandboxConfig(
242
396
  if (path.isAbsolute(p)) return toRealPath(p)
243
397
  return toRealPath(path.resolve(projectDir, p))
244
398
  }
399
+ const a = cfg.allow ?? {}
245
400
  const r: ResolvedSandboxConfig = {
246
- allowRead: (cfg.allowRead ?? []).map(resolve),
247
- allowWrite: (cfg.allowWrite ?? []).map(resolve),
401
+ allowRead: expandGrants((a.read ?? []).map(resolve)),
402
+ allowWrite: expandGrants((a.write ?? []).map(resolve)),
248
403
  }
249
- if (cfg.allowGitConfig !== undefined) r.allowGitConfig = cfg.allowGitConfig
250
- if (cfg.network !== undefined) r.network = cfg.network
251
- if (cfg.allowPty !== undefined) r.allowPty = cfg.allowPty
252
- if (cfg.enableWeakerNestedSandbox !== undefined) {
253
- r.enableWeakerNestedSandbox = cfg.enableWeakerNestedSandbox
404
+ if (a.network !== undefined) r.network = a.network
405
+ if (cfg.deny?.network !== undefined) r.denyNetwork = cfg.deny.network
406
+ if (a.systemInfo !== undefined) r.systemInfo = a.systemInfo
407
+ if (a.unixSockets !== undefined) r.unixSockets = a.unixSockets
408
+ if (a.localBinding !== undefined) r.localBinding = a.localBinding
409
+ if (a.machLookup !== undefined) r.machLookup = a.machLookup
410
+ if (a.pty !== undefined) r.pty = a.pty
411
+ if (a.gitConfig !== undefined) r.gitConfig = a.gitConfig
412
+ if (cfg.weakerWhenNested !== undefined) r.weakerWhenNested = cfg.weakerWhenNested
413
+ if (cfg.weakerNetworkIsolation !== undefined) {
414
+ r.weakerNetworkIsolation = cfg.weakerNetworkIsolation
254
415
  }
255
- if (cfg.enableWeakerNetworkIsolation !== undefined) {
256
- r.enableWeakerNetworkIsolation = cfg.enableWeakerNetworkIsolation
416
+ if (cfg.ignore !== undefined) {
417
+ // Relative patterns anchor at the project dir; absolute and `~` ones
418
+ // are taken as written. NOT realpath'd — a pattern is not a path.
419
+ const anchor = (pat: string): string =>
420
+ pat.startsWith('~') || path.isAbsolute(pat) ? pat : path.join(projectDir, pat)
421
+ r.ignore = {
422
+ ...(cfg.ignore.read ? { read: cfg.ignore.read.map(anchor) } : {}),
423
+ ...(cfg.ignore.write ? { write: cfg.ignore.write.map(anchor) } : {}),
424
+ ...(cfg.ignore.systemInfo ? { systemInfo: [...cfg.ignore.systemInfo] } : {}),
425
+ ...(cfg.ignore.network ? { network: [...(cfg.ignore.network as string[])] } : {}),
426
+ }
257
427
  }
258
- if (cfg.ignoreViolations !== undefined) r.ignoreViolations = cfg.ignoreViolations
259
428
  return r
260
429
  }
261
430
 
@@ -263,6 +432,17 @@ export interface SandboxViolation {
263
432
  /** Raw log line from SRT. Format differs between macOS / Linux. */
264
433
  line: string
265
434
  timestamp: Date
435
+ /**
436
+ * What the denial named, and which `ignore` lists could silence it —
437
+ * filled in by whichever platform produced the record. The filters read
438
+ * these instead of re-parsing a line whose shape depends on the OS: a
439
+ * seatbelt `deny(1) file-read-data /x` and a strace
440
+ * `openat(../x) = -1 ENOENT [/x]` say the same thing.
441
+ */
442
+ target?: string
443
+ /** Absolute, when `target` is a path at all. */
444
+ path?: string
445
+ ignorable?: readonly ('read' | 'write' | 'network' | 'systemInfo')[]
266
446
  }
267
447
 
268
448
  export interface SandboxedRunResult extends RunResult {
@@ -280,9 +460,24 @@ export interface SandboxedRunResult extends RunResult {
280
460
  * across packages) would otherwise collide. We prepend `: '<tag>';`
281
461
  * (shell no-op) to make every command's first 100 chars unique.
282
462
  */
283
- export async function runSandboxed(args: SandboxedRunArgs): Promise<SandboxedRunResult> {
463
+ /**
464
+ * The sandboxed form of a command: SRT's wrapper over the tagged command,
465
+ * with vx's own seatbelt rules appended on macOS. This is the ENFORCEMENT
466
+ * half of `runSandboxed`, shared with persistent tasks — a dev server is
467
+ * spawned through it and never exits while the run watches, so it gets
468
+ * the same walls and no violation report (reporting reads the trace after
469
+ * exit). Returns the wrapped command and the tag the store keys by.
470
+ */
471
+ export async function wrapSandboxedCommand(
472
+ args: Pick<SandboxedRunArgs, 'command' | 'cwd' | 'forwardArgs' | 'config'> &
473
+ Pick<SandboxedRunArgs, 'baseAllowRead' | 'baseAllowWrite' | 'baseDenyRead'>,
474
+ ): Promise<{
475
+ wrapped: string
476
+ tag: string
477
+ taggedCommand: string
478
+ baselines: CanonicalBaselines
479
+ }> {
284
480
  const { SandboxManager } = await loadSrt()
285
- const start = Date.now()
286
481
  const userCommand =
287
482
  args.forwardArgs && args.forwardArgs.length > 0
288
483
  ? args.command + ' ' + args.forwardArgs.map(shellQuote).join(' ')
@@ -291,8 +486,102 @@ export async function runSandboxed(args: SandboxedRunArgs): Promise<SandboxedRun
291
486
  const tag = xxh3hex(`${args.cwd}|${userCommand}|${process.hrtime.bigint()}`).slice(0, 16)
292
487
  const taggedCommand = `: 'vx-${tag}'; ${userCommand}`
293
488
 
294
- const customConfig = buildCustomConfig(args)
295
- const wrapped = await SandboxManager.wrapWithSandbox(taggedCommand, undefined, customConfig)
489
+ const baselines = canonicalBaselines(args)
490
+ const customConfig = buildCustomConfig(args, baselines)
491
+ // Linux: the ports a list grants are bridged out of the task's network
492
+ // namespace. The task's side of each bridge is a socat in front of the
493
+ // user command, so it goes INTO the sandboxed command; the host side is
494
+ // spawned here and released when the task's process ends.
495
+ const ports = process.platform === 'linux' ? bridgedPorts(args.config) : []
496
+ const inner = ports.length > 0 ? `${portBridgeInner(ports, tag)} ${taggedCommand}` : taggedCommand
497
+ let wrapped = await SandboxManager.wrapWithSandbox(inner, undefined, customConfig)
498
+ if (process.platform === 'darwin') {
499
+ const rules = macProfileRules(args.config)
500
+ if (rules.length > 0) wrapped = injectProfileRules(wrapped, rules)
501
+ }
502
+ if (ports.length > 0) spawnHostBridges(ports, tag)
503
+ return { wrapped, tag, taggedCommand, baselines }
504
+ }
505
+
506
+ /** The ports a list grants, deduped; `true` bridges nothing (the host sees no port on Linux). */
507
+ export function bridgedPorts(c: Pick<ResolvedSandboxConfig, 'localBinding'>): number[] {
508
+ return Array.isArray(c.localBinding) ? [...new Set(c.localBinding)] : []
509
+ }
510
+
511
+ /** Where a bridge's unix socket lives: the sandbox tmpdir, bound read-write on both sides. */
512
+ export function portBridgeSocket(tag: string, port: number): string {
513
+ return path.join(sandboxTmpdir(), `vx-port-${tag}-${port}.sock`)
514
+ }
515
+
516
+ /**
517
+ * The task's side of the bridge, in front of the user command inside the
518
+ * sandbox: one socat per port, listening on the unix socket and relaying
519
+ * into the namespace's loopback. Backgrounded and reaped with the shell,
520
+ * exactly as SRT starts its own proxy bridges. `unlink-early` clears a
521
+ * socket a killed task left behind; `>/dev/null` keeps its chatter out
522
+ * of the task's frame.
523
+ */
524
+ export function portBridgeInner(ports: readonly number[], tag: string): string {
525
+ const cmds = ports.map(
526
+ (p) =>
527
+ `socat UNIX-LISTEN:${shellQuote(portBridgeSocket(tag, p))},fork,unlink-early TCP:127.0.0.1:${p} >/dev/null 2>&1 &`,
528
+ )
529
+ return `${cmds.join(' ')} trap 'kill $(jobs -p) 2>/dev/null' EXIT;`
530
+ }
531
+
532
+ /**
533
+ * The host's side: one socat per port, listening on the host's loopback
534
+ * and connecting into the unix socket per client — with a retry, since a
535
+ * client can arrive before the task's side has bound the socket.
536
+ */
537
+ export function portBridgeHostArgv(tag: string, port: number): string[] {
538
+ return [
539
+ 'socat',
540
+ `TCP-LISTEN:${port},bind=127.0.0.1,fork,reuseaddr`,
541
+ `UNIX-CONNECT:${portBridgeSocket(tag, port)},retry=40,interval=0.25`,
542
+ ]
543
+ }
544
+
545
+ const hostBridges = new Map<string, Array<ReturnType<typeof Bun.spawn>>>()
546
+
547
+ function spawnHostBridges(ports: readonly number[], tag: string): void {
548
+ const procs: Array<ReturnType<typeof Bun.spawn>> = []
549
+ for (const p of ports) {
550
+ // A spawn failure (no socat on the host) is the task's to report:
551
+ // its own side dies the same way, in its frame.
552
+ try {
553
+ procs.push(
554
+ Bun.spawn(portBridgeHostArgv(tag, p), {
555
+ stdin: 'ignore',
556
+ stdout: 'ignore',
557
+ stderr: 'ignore',
558
+ }),
559
+ )
560
+ } catch {
561
+ // see above
562
+ }
563
+ }
564
+ if (procs.length > 0) hostBridges.set(tag, procs)
565
+ }
566
+
567
+ /** Stop the host side of a task's port bridges; idempotent. */
568
+ export function releaseBridges(tag: string): void {
569
+ const procs = hostBridges.get(tag)
570
+ if (procs === undefined) return
571
+ hostBridges.delete(tag)
572
+ for (const p of procs) {
573
+ try {
574
+ p.kill('SIGTERM')
575
+ } catch {
576
+ // already gone
577
+ }
578
+ }
579
+ }
580
+
581
+ export async function runSandboxed(args: SandboxedRunArgs): Promise<SandboxedRunResult> {
582
+ const start = Date.now()
583
+ const { SandboxManager } = await loadSrt()
584
+ const { wrapped, tag, taggedCommand, baselines } = await wrapSandboxedCommand(args)
296
585
 
297
586
  // Linux: SRT's SandboxViolationStore is macOS-only, so structured
298
587
  // detection on Linux requires us to wrap the spawn with strace and
@@ -307,8 +596,31 @@ export async function runSandboxed(args: SandboxedRunArgs): Promise<SandboxedRun
307
596
  // are mostly shell PATH-walking and stat probes that aren't
308
597
  // actionable (we'd report every node_modules/.bin entry the shell
309
598
  // checks before resolving a command).
599
+ //
600
+ // `--seccomp-bpf` is what makes that filter cheap: without it strace
601
+ // ptrace-stops the tracee on EVERY syscall and discards the untraced
602
+ // ones in userspace, so a stat-heavy task ran many times slower under
603
+ // the sandbox than outside it. That is what failed the cache perf
604
+ // baselines on the Linux job (reproduced 2026-09-09: plain `bun test`
605
+ // 24/24; under `strace -f -e trace=openat` the same four fail with
606
+ // medians 2.5–7× over budget; with `--seccomp-bpf` 24/24 again), and
607
+ // it taxed every other sandboxed task the same way. With the flag the
608
+ // kernel filter stops only on `openat`. strace ≥ 5.3 (2019); an older
609
+ // one gets the slow form rather than no detection.
310
610
  const spawnArgv = straceLog
311
- ? ['strace', '-f', '-e', 'trace=openat', '-o', straceLog, '--', 'sh', '-c', wrapped]
611
+ ? [
612
+ 'strace',
613
+ '-f',
614
+ ...(useStrace === 'seccomp' ? ['--seccomp-bpf'] : []),
615
+ '-e',
616
+ 'trace=openat',
617
+ '-o',
618
+ straceLog,
619
+ '--',
620
+ 'sh',
621
+ '-c',
622
+ wrapped,
623
+ ]
312
624
  : ['sh', '-c', wrapped]
313
625
 
314
626
  let proc: ReturnType<typeof Bun.spawn>
@@ -335,31 +647,73 @@ export async function runSandboxed(args: SandboxedRunArgs): Promise<SandboxedRun
335
647
  const timeout = armTimeout(proc, args.timeoutMs)
336
648
  const ac = new AbortController()
337
649
  const streams = Promise.all([
338
- streamToString(proc.stdout, args.onStdout, ac.signal),
339
- streamToString(proc.stderr, args.onStderr, ac.signal),
650
+ streamToString(proc.stdout, args.onStdout, ac.signal, args.capture?.stdout ?? true),
651
+ streamToString(proc.stderr, args.onStderr, ac.signal, args.capture?.stderr ?? true),
340
652
  ])
341
- // See runCommand: gate on child exit, abort the readers on timeout so
342
- // a lingering grandchild pipe can't hang the run.
653
+ // See runCommand: gate on child exit; a lingering grandchild pipe (timeout
654
+ // OR a clean exit that backgrounds a process) can't hang the run — timeout
655
+ // aborts at once, otherwise drainOrAbort bounds the post-exit drain.
343
656
  await proc.exited
344
657
  timeout.clear()
345
658
  if (timeout.timedOut()) ac.abort()
659
+ else await drainOrAbort(streams, ac)
346
660
  const [stdout, stderr] = await streams
347
661
  args.liveChildren?.delete(proc)
662
+ releaseBridges(tag)
348
663
  const exitCode = proc.exitCode ?? (proc.signalCode ? signalExitCode(proc.signalCode) : 1)
349
664
 
350
665
  // macOS: read the violation store keyed by our tagged command.
666
+ //
667
+ // The store is fed ASYNCHRONOUSLY — SRT's monitor ingests macOS unified-log
668
+ // records, and log delivery lags under load — so reading it immediately
669
+ // after child exit races the pipeline: the denial happened, the child died
670
+ // on it, and the store is still empty. Observed locally as the 1-in-N
671
+ // "denied but zero violation lines" flake (decision log 2026-08-23/24).
672
+ // When the exit is a FAILURE and the store is empty, give the pipeline a
673
+ // bounded settle window; a clean exit skips the poll entirely, so the warm
674
+ // path pays nothing.
675
+ //
676
+ // MEASURED (2026-08-24, ~430 runs/arm under full-suite load): the poll
677
+ // HALVES the loss (5.0% → 2.2%) but cannot eliminate it — the residual
678
+ // failures survive the whole 1 s window, meaning those records were
679
+ // DROPPED by the unified log under pressure, not delayed. Reporting on
680
+ // macOS is therefore lossy-by-OS under load; ENFORCEMENT is unaffected
681
+ // (every observed loss still denied the read and failed the child).
351
682
  const store = SandboxManager.getSandboxViolationStore()
352
- const macViolations = store.getViolationsForCommand(taggedCommand).map((v) => ({
353
- line: v.line,
354
- timestamp: v.timestamp,
355
- }))
356
-
683
+ // EVERY record the store holds for this command, unfiltered (owner,
684
+ // 2026-09-05). A sandboxed task that fails must say what it was denied;
685
+ // deciding on the user's behalf that a record was "just traversal" is how
686
+ // a failure ends up with an empty violations section and no explanation.
687
+ const readMacViolations = (): SandboxViolation[] =>
688
+ store.getViolationsForCommand(taggedCommand).map((v) => ({
689
+ line: v.line,
690
+ timestamp: v.timestamp,
691
+ }))
692
+ // Darwin only. Since SRT 0.0.75 the store is fed on Linux too, by the
693
+ // seccomp helper's write observer — but SRT judges those reports against
694
+ // the GLOBAL `filesystem.allowWrite` from `initialize` (empty here; the
695
+ // per-task list travels in `customConfig`, which the monitor never sees),
696
+ // so every write a task makes to its own declared output arrived as
697
+ // `deny openat <output>` and failed the task (reproduced 2026-09-04 in a
698
+ // Linux container: exit 1, empty stderr). Linux detection is the strace
699
+ // pass below, judged against the task's own baselines.
700
+ let macViolations = process.platform === 'darwin' ? readMacViolations() : []
701
+ // No settle window: the store is read once, right after the child exits
702
+ // (owner, 2026-09-05). It cost 300ms on EVERY clean sandboxed task — the
703
+ // full budget, since a task with nothing to report can only prove that by
704
+ // waiting — against 26ms for one that reports something and breaks out
705
+ // early. Measured: clean `echo` 331ms sandboxed vs 16ms plain.
706
+ //
707
+ // The price is that macOS feeds this store asynchronously, so a record
708
+ // that has not arrived yet is not reported. Enforcement is unaffected —
709
+ // the OS denied the operation either way, and a command that could not
710
+ // proceed still fails on its own exit code.
357
711
  // Linux: parse the strace log and emit one violation per denied
358
712
  // syscall on a path inside denyRead that wasn't unconditionally
359
713
  // allowed. Best-effort — if parsing fails we surface no Linux
360
714
  // violations rather than fail the whole task.
361
715
  const linuxViolations: SandboxViolation[] = straceLog
362
- ? await parseStraceViolations(straceLog, args).catch(() => [])
716
+ ? await parseStraceViolations(straceLog, args, baselines).catch(() => [])
363
717
  : []
364
718
  if (straceLog) await unlink(straceLog).catch(() => undefined)
365
719
 
@@ -368,12 +722,33 @@ export async function runSandboxed(args: SandboxedRunArgs): Promise<SandboxedRun
368
722
  // ignoreViolations through to the log monitor — that filter is set
369
723
  // once globally at initSandbox time. So per-task user overrides have
370
724
  // to be applied here, after read-back.
371
- const userIgnore = args.config.ignoreViolations
372
- const violations: SandboxViolation[] = filterIgnored(
373
- [...macViolations, ...linuxViolations],
374
- userIgnore,
375
- userCommand,
376
- )
725
+ const violations = reportableViolations([...macViolations, ...linuxViolations], {
726
+ within: args.reportWithin,
727
+ config: args.config,
728
+ })
729
+
730
+ // The one denial macOS never logs. MEASURED 2026-09-05, same machine, two
731
+ // runs differing only in the grant: with the cwd granted a failing task
732
+ // reports its denials normally; WITHOUT it the store stays empty across
733
+ // the whole settle window (11 reads, 0 records) and the child reports
734
+ // whatever it likes — `bun test` says only `error: An unknown error
735
+ // occurred (Unexpected)`. The process dies before macOS logs anything, so
736
+ // no amount of un-filtering can surface it.
737
+ //
738
+ // Not a guess about the cause: the cwd lying outside every allowRead
739
+ // prefix is a fact of the resolved baselines. Added only when the task
740
+ // ALREADY failed with nothing to show, so it can never redden a pass.
741
+ const grantedRead = [...baselines.allowRead, ...args.config.allowRead]
742
+ if (exitCode !== 0 && violations.length === 0 && !readableUnder(args.cwd, grantedRead)) {
743
+ violations.push({
744
+ timestamp: new Date(),
745
+ line:
746
+ `vx: this sandbox grants no read access to the task's own working directory ` +
747
+ `(${args.cwd}), so a command that reads or lists it fails with whatever error it ` +
748
+ `reports for that — macOS logs no violation record. Add ` +
749
+ "`sandbox: { allow: { read: ['.'] } }`.",
750
+ })
751
+ }
377
752
 
378
753
  try {
379
754
  SandboxManager.cleanupAfterCommand()
@@ -393,186 +768,193 @@ export async function runSandboxed(args: SandboxedRunArgs): Promise<SandboxedRun
393
768
  }
394
769
  }
395
770
 
396
- /** Memoized check: is `strace` on PATH on a Linux host? */
397
- let straceAvailableCache: boolean | undefined
398
- async function wantsStraceDetection(): Promise<boolean> {
399
- if (process.platform !== 'linux') return false
400
- if (straceAvailableCache !== undefined) return straceAvailableCache
401
- try {
402
- const p = Bun.spawn(['strace', '--version'], { stdout: 'ignore', stderr: 'ignore' })
403
- await p.exited
404
- straceAvailableCache = p.exitCode === 0
405
- } catch {
406
- straceAvailableCache = false
407
- }
408
- return straceAvailableCache
771
+ /**
772
+ * Is `dir` inside a path the sandbox granted for reading? bwrap binds and
773
+ * seatbelt rules are both prefix-based, so a grant covers the subtree.
774
+ */
775
+ function readableUnder(dir: string, granted: readonly string[]): boolean {
776
+ const target = toRealPath(dir)
777
+ return granted.some((p) => {
778
+ const g = toRealPath(p)
779
+ return target === g || target.startsWith(g.endsWith(path.sep) ? g : g + path.sep)
780
+ })
409
781
  }
410
782
 
411
783
  /**
412
- * Parse a strace log for denied filesystem syscalls and convert each
413
- * one inside the workspace deny anchor (and not in allowRead) into a
414
- * SandboxViolation. Dedups by (syscall, abs-path) so a tool that
415
- * statx's the same missing path 10 times in a row produces one line.
416
- *
417
- * strace line shape (with -f):
418
- * <pid> openat(AT_FDCWD, "<path>", <flags>) = -1 ENOENT (...)
419
- * <pid> access("<path>", <mode>) = -1 EACCES (...)
420
- * <pid> statx(AT_FDCWD, "<path>", <flags>, <mask>, ...) = -1 ENOENT (...)
421
- *
422
- * We capture the first quoted-string argument as the path. paths that
423
- * are relative resolve against the task's cwd (set by Bun.spawn).
784
+ * A token safe to interpolate into a seatbelt profile. The profile travels
785
+ * inside a shell-quoted `sandbox-exec -p '…'` argument, so a value carrying
786
+ * a quote, paren or backslash could rewrite the policy or escape the
787
+ * argument. Refuse rather than escape — every real info type is a plain
788
+ * dotted name.
424
789
  */
425
- const STRACE_RE =
426
- /^\d+\s+(openat|access|statx|newfstatat)\([^"]*"([^"]+)"[^)]*\)\s*=\s*-1\s+(ENOENT|EACCES|EPERM)/gm
427
-
428
- async function parseStraceViolations(
429
- logPath: string,
430
- args: SandboxedRunArgs,
431
- ): Promise<SandboxViolation[]> {
432
- const text = await Bun.file(logPath).text()
433
- if (text.length === 0) return []
434
-
435
- // Treat every baseAllow + sandbox.allowRead path as "this was
436
- // explicitly permitted; any -ENOENT here is the user's own missing
437
- // file, not a sandbox-induced denial". Same for absolute denyRead
438
- // checks below.
439
- const allowAbs = new Set<string>(
440
- [...args.baseAllowRead, ...args.config.allowRead].map((p) => absolutize(p)),
441
- )
442
- const denyAnchors = args.baseDenyRead.map((p) => absolutize(p))
443
-
444
- const seen = new Set<string>()
445
- const out: SandboxViolation[] = []
446
- for (const m of text.matchAll(STRACE_RE)) {
447
- const [, syscall, rawPath, errno] = m
448
- if (!rawPath) continue
449
- const abs = absolutize(rawPath, args.cwd)
450
- // Only report paths under the workspace-root deny anchor — system
451
- // libs / /proc / /sys / etc. probes are not interesting violations.
452
- if (!denyAnchors.some((root) => abs === root || abs.startsWith(root + path.sep))) continue
453
- // Skip paths the user explicitly allowed (and their descendants).
454
- if (isUnderAny(abs, allowAbs)) continue
455
- const key = `${syscall}|${abs}`
456
- if (seen.has(key)) continue
457
- seen.add(key)
458
- out.push({
459
- line: `${syscall}(${rawPath}) = -1 ${errno} [${abs}]`,
460
- timestamp: new Date(),
461
- })
790
+ function sbplToken(value: string, field: string): string {
791
+ if (!/^[A-Za-z0-9._-]+$/.test(value)) {
792
+ throw new UserError(`${field}: '${value}' is not a valid name`)
462
793
  }
463
- return out
794
+ return value
464
795
  }
465
796
 
466
- function absolutize(p: string, cwd?: string): string {
467
- if (p.startsWith('~')) return path.join(os.homedir(), p.slice(1))
468
- if (path.isAbsolute(p)) return p
469
- return path.resolve(cwd ?? process.cwd(), p)
797
+ /**
798
+ * The capabilities that reach the macOS profile as rules rather than
799
+ * through SRT's config.
800
+ *
801
+ * `systemInfo` has no SRT field at any level. The rest DO have fields,
802
+ * but SRT reads `network.allowLocalBinding` / `allowUnixSockets` /
803
+ * `allowMachLookup` off the config given to `initialize()` and never off
804
+ * the per-call one (`sandbox-manager.js` getters, 0.0.75) — so a per-task
805
+ * grant passed there is silently dropped. vx is per-task by definition,
806
+ * so it emits them itself. The rule text mirrors SRT's own.
807
+ */
808
+ function macProfileRules(c: ResolvedSandboxConfig): string[] {
809
+ const rules: string[] = []
810
+ for (const t of c.systemInfo ?? []) {
811
+ rules.push(`(allow system-info (info-type "${sbplToken(t, 'allow.systemInfo')}"))`)
812
+ }
813
+ if (localBindingOn(c)) {
814
+ // `*:*`, not `localhost:*`: a dual-stack socket bound to 127.0.0.1 is
815
+ // ::ffff:127.0.0.1 in the kernel, which seatbelt's `localhost` does
816
+ // not match. bind and inbound carry no remote endpoint, so this is
817
+ // not egress. Egress stays pinned to loopback.
818
+ rules.push('(allow network-bind (local ip "*:*"))')
819
+ rules.push('(allow network-inbound (local ip "*:*"))')
820
+ rules.push('(allow network-outbound (remote ip "localhost:*"))')
821
+ }
822
+ if (c.unixSockets === true) {
823
+ rules.push('(allow system-socket (socket-domain AF_UNIX))')
824
+ rules.push('(allow network-bind (local unix-socket (path-regex #"^/")))')
825
+ rules.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))')
826
+ } else if (c.unixSockets !== undefined && c.unixSockets.length > 0) {
827
+ rules.push('(allow system-socket (socket-domain AF_UNIX))')
828
+ for (const sock of c.unixSockets) {
829
+ // Both the declared path and what it resolves to: seatbelt matches the
830
+ // path the kernel sees, and on macOS `/tmp` is a symlink to
831
+ // `/private/tmp` — a grant on the former alone never matches.
832
+ for (const p of unique([sbplPath(sock, 'allow.unixSockets'), toRealPath(sock)])) {
833
+ rules.push(`(allow network-bind (local unix-socket (subpath "${p}")))`)
834
+ rules.push(`(allow network-outbound (remote unix-socket (subpath "${p}")))`)
835
+ }
836
+ }
837
+ }
838
+ for (const name of c.machLookup ?? []) {
839
+ rules.push(`(allow mach-lookup (global-name "${sbplToken(name, 'allow.machLookup')}"))`)
840
+ }
841
+ return rules
470
842
  }
471
843
 
472
- function isUnderAny(abs: string, allow: Set<string>): boolean {
473
- if (allow.has(abs)) return true
474
- for (const a of allow) {
475
- if (abs === a || abs.startsWith(a + path.sep)) return true
844
+ /**
845
+ * A path safe to interpolate into a seatbelt profile. Same reasoning as
846
+ * {@link sbplToken}, with the separators a path needs.
847
+ */
848
+ function sbplPath(value: string, field: string): string {
849
+ if (!/^[A-Za-z0-9._\-/@+]+$/.test(value) || value.includes('..')) {
850
+ throw new UserError(`${field}: '${value}' is not a valid path`)
476
851
  }
477
- return false
852
+ return value
478
853
  }
479
854
 
480
855
  /**
481
- * Apply the task's user-provided `sandbox.ignoreViolations` map on top
482
- * of whatever the macOS log monitor + Linux strace pass produced.
483
- * Mirrors SRT's own substring-match semantics:
484
- * - `'*'` entries match every command
485
- * - other keys match commands whose userCommand string CONTAINS the key
486
- * - the array of strings under each key is substring-matched against
487
- * the violation line
856
+ * Add rules to the END of the seatbelt profile SRT generated.
488
857
  *
489
- * The defaults installed in `initSandbox` already filter on the macOS
490
- * side; this pass catches per-task additions + Linux strace results.
858
+ * SBPL is last-match-wins, so the tail is the only place a rule of ours
859
+ * outranks one of SRT's. Measured 2026-09-05: the same rules injected
860
+ * after the `(deny default …)` header were inert in both directions —
861
+ * SRT's own later clauses won. Filesystem capabilities still go through
862
+ * SRT's config, where they also work on Linux; what arrives here is what
863
+ * SRT's per-call config CANNOT carry.
864
+ *
865
+ * A profile that does not have the expected shape THROWS. Silently
866
+ * running a task without a capability it asked for is worse than not
867
+ * offering the capability.
491
868
  */
492
- function filterIgnored(
493
- violations: SandboxViolation[],
494
- ignore: Record<string, string[]> | undefined,
495
- userCommand: string,
496
- ): SandboxViolation[] {
497
- if (!ignore) return violations
498
- const wildcard = ignore['*'] ?? []
499
- const cmdEntries = Object.entries(ignore).filter(([k]) => k !== '*')
500
- return violations.filter((v) => {
501
- if (wildcard.some((s) => v.line.includes(s))) return false
502
- for (const [pattern, needles] of cmdEntries) {
503
- if (userCommand.includes(pattern) && needles.some((s) => v.line.includes(s))) {
504
- return false
505
- }
869
+ function injectProfileRules(wrapped: string, rules: readonly string[]): string {
870
+ const anchor = /sandbox-exec -p '\(version 1\)\n\(deny default[^\n]*\n/.exec(wrapped)
871
+ if (anchor === null) {
872
+ throw new UserError(
873
+ 'sandbox: the OS sandbox policy did not have the expected shape, so the ' +
874
+ 'capabilities this task declared could not be applied',
875
+ )
876
+ }
877
+ // The profile is a single-quoted shell argument; SRT escapes a literal
878
+ // quote inside it as `'"'"'` (5 chars). The first bare `'` after the
879
+ // header therefore closes the profile.
880
+ let i = anchor.index + anchor[0].length
881
+ for (;;) {
882
+ const q = wrapped.indexOf("'", i)
883
+ if (q === -1) {
884
+ throw new UserError(
885
+ 'sandbox: the OS sandbox policy was not quoted as expected, so the ' +
886
+ 'capabilities this task declared could not be applied',
887
+ )
506
888
  }
507
- return true
508
- })
889
+ if (wrapped.startsWith(`'"'"'`, q)) {
890
+ i = q + 5
891
+ continue
892
+ }
893
+ return `${wrapped.slice(0, q)}\n${rules.join('\n')}\n${wrapped.slice(q)}`
894
+ }
509
895
  }
510
896
 
511
897
  /**
512
- * Merge the orchestrator-provided baseline (declared inputs / outputs /
513
- * workspace-root anchor) with the user's resolved sandbox block to
514
- * produce the SRT customConfig. Path arrays are unioned and deduped.
898
+ * Grant paths, with globs handled per platform.
515
899
  *
516
- * Network coercion:
517
- * - missing / undefined / false → block all (allowedDomains: [])
518
- * - true → allow all (allowedDomains: ['*'])
519
- * - object → use as-is (no merge with shortcuts)
900
+ * macOS: SRT's own `pathFilter` turns a glob into `(regex …)` and a literal
901
+ * into `(subpath …)`, so a pattern is passed through and seatbelt matches
902
+ * it — including files created DURING the run.
903
+ *
904
+ * Linux: a grant is a bwrap bind mount, and you cannot mount a pattern.
905
+ * The glob is expanded against the filesystem here, which means it covers
906
+ * what exists when the task STARTS. A pattern matching a file the task
907
+ * creates later grants nothing there — declare its directory instead.
520
908
  */
521
- function buildCustomConfig(
522
- args: SandboxedRunArgs,
523
- ): Parameters<SrtModule['SandboxManager']['wrapWithSandbox']>[2] {
524
- const c = args.config
525
- const allowRead = unique([...args.baseAllowRead, ...c.allowRead])
526
- const denyRead = unique([...args.baseDenyRead])
527
- const allowWrite = unique([...args.baseAllowWrite, ...c.allowWrite])
528
-
529
- const custom: Parameters<SrtModule['SandboxManager']['wrapWithSandbox']>[2] = {
530
- filesystem: {
531
- denyRead,
532
- allowRead,
533
- allowWrite,
534
- denyWrite: [],
535
- ...(c.allowGitConfig !== undefined ? { allowGitConfig: c.allowGitConfig } : {}),
536
- },
537
- }
538
-
539
- // Network coercion. SRT requires allowedDomains + deniedDomains to be
540
- // present on any network config; we always supply both.
541
- if (c.network === true) {
542
- custom.network = { allowedDomains: ['*'], deniedDomains: [] }
543
- } else if (c.network && typeof c.network === 'object') {
544
- custom.network = {
545
- allowedDomains: c.network.allowedDomains ?? [],
546
- deniedDomains: c.network.deniedDomains ?? [],
547
- ...(c.network.allowUnixSockets !== undefined
548
- ? { allowUnixSockets: c.network.allowUnixSockets }
549
- : {}),
550
- ...(c.network.allowAllUnixSockets !== undefined
551
- ? { allowAllUnixSockets: c.network.allowAllUnixSockets }
552
- : {}),
553
- ...(c.network.allowLocalBinding !== undefined
554
- ? { allowLocalBinding: c.network.allowLocalBinding }
555
- : {}),
556
- ...(c.network.allowMachLookup !== undefined
557
- ? { allowMachLookup: c.network.allowMachLookup }
558
- : {}),
909
+ function expandGrants(paths: readonly string[]): string[] {
910
+ // A pattern covering a directory WHOLE is that directory. `<d>/**/*` and
911
+ // `<d>/**` match everything UNDER `<d>` and never `<d>` itself, so a task
912
+ // granted `read: ['**/*']` still could not list its own cwd — the exact
913
+ // shape `bun test` and `oxlint` need. Collapsing is not a widening: the
914
+ // pattern already covered every file there; it adds the directory entry.
915
+ const collapsed = paths.map((p) => {
916
+ const m = /^(.*?)\/\*\*(?:\/\*)?$/.exec(p)
917
+ return m === null ? p : m[1]!
918
+ })
919
+ if (process.platform !== 'linux') return collapsed
920
+ const out: string[] = []
921
+ for (const p of collapsed) {
922
+ if (!/[*?[\]]/.test(p)) {
923
+ out.push(p)
924
+ continue
925
+ }
926
+ // Anchor the scan at the longest literal prefix so a pattern does not
927
+ // walk the whole filesystem to find its matches.
928
+ const base = path.dirname(p.slice(0, p.search(/[*?[\]]/)))
929
+ const pattern = path.relative(base, p)
930
+ for (const hit of new Bun.Glob(pattern).scanSync({ cwd: base, onlyFiles: false, dot: true })) {
931
+ out.push(path.join(base, hit))
559
932
  }
560
- } else {
561
- // false / undefined → block all
562
- custom.network = { allowedDomains: [], deniedDomains: [] }
563
- }
564
-
565
- if (c.allowPty !== undefined) custom.allowPty = c.allowPty
566
- if (c.enableWeakerNestedSandbox !== undefined) {
567
- custom.enableWeakerNestedSandbox = c.enableWeakerNestedSandbox
568
- }
569
- if (c.enableWeakerNetworkIsolation !== undefined) {
570
- custom.enableWeakerNetworkIsolation = c.enableWeakerNetworkIsolation
571
933
  }
572
- if (c.ignoreViolations !== undefined) custom.ignoreViolations = c.ignoreViolations
573
- return custom
934
+ return out
574
935
  }
575
936
 
576
- function unique(arr: readonly string[]): string[] {
577
- return [...new Set(arr)]
937
+ /**
938
+ * Memoized check: is `strace` on PATH on a Linux host, and does it know
939
+ * `--seccomp-bpf` (5.3+)? `'seccomp'` is the fast form; `'plain'` traces
940
+ * every syscall through ptrace and is kept only for an old strace.
941
+ */
942
+ let straceAvailableCache: false | 'plain' | 'seccomp' | undefined
943
+ async function wantsStraceDetection(): Promise<false | 'plain' | 'seccomp'> {
944
+ if (process.platform !== 'linux') return false
945
+ if (straceAvailableCache !== undefined) return straceAvailableCache
946
+ try {
947
+ const p = Bun.spawn(['strace', '--version'], { stdout: 'pipe', stderr: 'ignore' })
948
+ const out = await new Response(p.stdout).text()
949
+ await p.exited
950
+ if (p.exitCode !== 0) straceAvailableCache = false
951
+ else {
952
+ const m = /version (\d+)\.(\d+)/.exec(out)
953
+ const [major, minor] = m ? [Number(m[1]), Number(m[2])] : [0, 0]
954
+ straceAvailableCache = major > 5 || (major === 5 && minor >= 3) ? 'seccomp' : 'plain'
955
+ }
956
+ } catch {
957
+ straceAvailableCache = false
958
+ }
959
+ return straceAvailableCache
578
960
  }