@zergai/ztc 0.26.6-dev.202611240947 → 0.27.0-beta.1

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 (268) hide show
  1. package/README.md +629 -167
  2. package/RUST_THIRD_PARTY_LICENSES.txt +5 -5
  3. package/bin/zmux-darwin-arm64 +0 -0
  4. package/bin/zmux-linux-x64 +0 -0
  5. package/bin/ztc-audio-darwin-arm64 +0 -0
  6. package/bin/ztc-capture-darwin-arm64 +0 -0
  7. package/bin/ztc-computer-darwin-arm64 +0 -0
  8. package/bin/ztc-llm-darwin-arm64 +0 -0
  9. package/bin/ztc-tts-darwin-arm64 +0 -0
  10. package/bin/ztc-tui-darwin-arm64 +0 -0
  11. package/bin/ztc-tui-linux-x64 +0 -0
  12. package/bin/zterm-darwin-arm64 +2 -2
  13. package/dist/App.js +6 -1
  14. package/dist/agent/agent.d.ts +21 -15
  15. package/dist/agent/agent.js +389 -163
  16. package/dist/agent/backends/codex_app_server.d.ts +7 -1
  17. package/dist/agent/backends/codex_app_server.js +11 -1
  18. package/dist/agent/backends/gemini.js +22 -8
  19. package/dist/agent/commands/batch.js +8 -0
  20. package/dist/agent/commands/config.js +10 -0
  21. package/dist/agent/commands/environment.js +5 -5
  22. package/dist/agent/commands/goal.d.ts +1 -0
  23. package/dist/agent/commands/goal.js +2 -1
  24. package/dist/agent/commands/index.js +2 -1
  25. package/dist/agent/commands/manifest.js +4 -0
  26. package/dist/agent/commands/optimize.js +5 -2
  27. package/dist/agent/commands/pane_cli.d.ts +29 -0
  28. package/dist/agent/commands/pane_cli.js +303 -0
  29. package/dist/agent/commands/settings.js +13 -3
  30. package/dist/agent/commands/shannon.js +8 -0
  31. package/dist/agent/commands/update.js +15 -3
  32. package/dist/agent/commands/zerg.js +31 -1
  33. package/dist/agent/commands/ztc_pane.js +3 -1
  34. package/dist/agent/factory.d.ts +4 -0
  35. package/dist/agent/factory.js +11 -1
  36. package/dist/agent/loop_policy.d.ts +42 -5
  37. package/dist/agent/loop_policy.js +206 -3
  38. package/dist/agent/runtime/command_jobs.d.ts +5 -0
  39. package/dist/agent/runtime/command_jobs.js +241 -31
  40. package/dist/agent/runtime/command_wait.d.ts +2 -0
  41. package/dist/agent/runtime/command_wait.js +1 -0
  42. package/dist/agent/runtime/done_report.d.ts +18 -0
  43. package/dist/agent/runtime/done_report.js +130 -0
  44. package/dist/agent/runtime/execution_context.js +4 -1
  45. package/dist/agent/runtime/failure_cause.d.ts +2 -0
  46. package/dist/agent/runtime/failure_cause.js +35 -0
  47. package/dist/agent/runtime/policy.d.ts +14 -2
  48. package/dist/agent/runtime/policy.js +104 -12
  49. package/dist/agent/runtime/quiet_job.d.ts +18 -0
  50. package/dist/agent/runtime/quiet_job.js +48 -0
  51. package/dist/agent/runtime/recovery.d.ts +1 -5
  52. package/dist/agent/runtime/recovery.js +2 -44
  53. package/dist/agent/runtime/tool_runtime.d.ts +1 -0
  54. package/dist/agent/runtime/tool_runtime.js +2 -0
  55. package/dist/agent/subagent.js +6 -1
  56. package/dist/agent/tools/deferred.js +1 -0
  57. package/dist/agent/tools/index.d.ts +2 -0
  58. package/dist/agent/tools/index.js +1 -0
  59. package/dist/agent/tools/outcome.d.ts +15 -0
  60. package/dist/agent/tools/outcome.js +107 -0
  61. package/dist/agent/tools/pane.d.ts +2 -1
  62. package/dist/agent/tools/pane.js +21 -3
  63. package/dist/agent/tools/registry.js +2 -0
  64. package/dist/agent/tools/shell.d.ts +1 -0
  65. package/dist/agent/tools/shell.js +128 -17
  66. package/dist/agent/tools/sim_domain_tools.js +4 -2
  67. package/dist/agent/tools/supervision.js +4 -2
  68. package/dist/agent/tools/types.d.ts +3 -0
  69. package/dist/app/command_context.js +5 -9
  70. package/dist/app/conversation_compaction.d.ts +4 -2
  71. package/dist/app/conversation_compaction.js +16 -5
  72. package/dist/app/headless_shell_mode.d.ts +14 -0
  73. package/dist/app/headless_shell_mode.js +7 -0
  74. package/dist/app/hosted_resident.d.ts +356 -0
  75. package/dist/app/hosted_resident.js +677 -0
  76. package/dist/app/restart.js +11 -2
  77. package/dist/app/session_manager.d.ts +5 -0
  78. package/dist/app/session_manager.js +21 -6
  79. package/dist/app/session_messages.js +6 -6
  80. package/dist/app/workspace_layout_controller.js +7 -0
  81. package/dist/batch/worktree.d.ts +10 -0
  82. package/dist/batch/worktree.js +15 -0
  83. package/dist/bench/registry.js +4 -2
  84. package/dist/cli_args.js +1 -1
  85. package/dist/cli_main.js +80 -10
  86. package/dist/cli_ratatui.d.ts +75 -0
  87. package/dist/cli_ratatui.js +485 -84
  88. package/dist/components/InputArea.js +4 -4
  89. package/dist/config/execution.d.ts +10 -0
  90. package/dist/config/execution.js +10 -0
  91. package/dist/config/hosted_runtime.d.ts +4 -1
  92. package/dist/config/hosted_runtime.js +4 -1
  93. package/dist/config/permission_pin.d.ts +34 -2
  94. package/dist/config/permission_pin.js +52 -2
  95. package/dist/config/person_command_policy.d.ts +38 -0
  96. package/dist/config/person_command_policy.js +11 -0
  97. package/dist/config/profiles.d.ts +21 -0
  98. package/dist/config/profiles.js +56 -2
  99. package/dist/config/types.d.ts +4 -1
  100. package/dist/config.js +34 -19
  101. package/dist/desktop/daily/codex_exec_adapter.js +7 -2
  102. package/dist/desktop/daily/desktop_wiring.d.ts +7 -1
  103. package/dist/desktop/daily/desktop_wiring.js +11 -3
  104. package/dist/desktop/daily/recipes.js +20 -4
  105. package/dist/desktop/health.d.ts +24 -0
  106. package/dist/desktop/health.js +151 -0
  107. package/dist/desktop/native_dialogs.d.ts +37 -0
  108. package/dist/desktop/native_dialogs.js +105 -0
  109. package/dist/diagnostics/session_export.d.ts +1 -0
  110. package/dist/diagnostics/session_export.js +28 -0
  111. package/dist/embedded/registry.js +4 -2
  112. package/dist/emulation/tool_adapters.js +9 -4
  113. package/dist/emulation/ztc_addendum.js +3 -0
  114. package/dist/headless.d.ts +11 -4
  115. package/dist/headless.js +99 -34
  116. package/dist/headless_approval.d.ts +6 -0
  117. package/dist/headless_cli.js +1 -1
  118. package/dist/hooks/runner.js +7 -6
  119. package/dist/library.d.ts +4 -0
  120. package/dist/library.js +3 -0
  121. package/dist/mcp/client.js +3 -3
  122. package/dist/modes/registry.js +13 -4
  123. package/dist/onboarding/setup_environment.js +13 -1
  124. package/dist/optimize/adapters/kernelbench.js +88 -10
  125. package/dist/optimize/adapters/types.d.ts +5 -0
  126. package/dist/optimize/executor.js +21 -0
  127. package/dist/panes/cli_install.d.ts +54 -0
  128. package/dist/panes/cli_install.js +157 -0
  129. package/dist/panes/model_catalog.js +3 -0
  130. package/dist/panes/new_pane_choices.d.ts +6 -2
  131. package/dist/panes/new_pane_choices.js +24 -12
  132. package/dist/panes/pane_cli_launch.d.ts +50 -0
  133. package/dist/panes/pane_cli_launch.js +124 -0
  134. package/dist/panes/pane_clis.d.ts +171 -0
  135. package/dist/panes/pane_clis.js +325 -0
  136. package/dist/panes/person_only_panes.d.ts +45 -0
  137. package/dist/panes/person_only_panes.js +117 -0
  138. package/dist/plugin/simulation_living.js +0 -2
  139. package/dist/plugin/simulation_living_engine.d.ts +1 -0
  140. package/dist/plugin/simulation_living_engine.js +1 -0
  141. package/dist/plugin/simulation_living_labels.d.ts +3 -0
  142. package/dist/plugin/simulation_living_labels.js +2 -0
  143. package/dist/router_auth.js +12 -1
  144. package/dist/session.js +26 -1
  145. package/dist/simulation/art/gemini_image.js +11 -5
  146. package/dist/simulation/domains/loader.js +25 -3
  147. package/dist/simulation/living/cold.d.ts +23 -0
  148. package/dist/simulation/living/cold.js +41 -0
  149. package/dist/simulation/living/context.d.ts +591 -1283
  150. package/dist/simulation/living/context.js +378 -244
  151. package/dist/simulation/living/contradictions.d.ts +14 -0
  152. package/dist/simulation/living/contradictions.js +282 -0
  153. package/dist/simulation/living/core/ids.d.ts +53 -0
  154. package/dist/simulation/living/core/ids.js +39 -0
  155. package/dist/simulation/living/core/kind.d.ts +20 -0
  156. package/dist/simulation/living/core/kind.js +15 -0
  157. package/dist/simulation/living/core/laws.d.ts +179 -0
  158. package/dist/simulation/living/core/laws.js +184 -0
  159. package/dist/simulation/living/core/ops.d.ts +257 -0
  160. package/dist/simulation/living/core/ops.js +34 -0
  161. package/dist/simulation/living/definer.d.ts +17 -1
  162. package/dist/simulation/living/definer.js +130 -51
  163. package/dist/simulation/living/definition.d.ts +174 -65
  164. package/dist/simulation/living/definition.js +287 -180
  165. package/dist/simulation/living/director.d.ts +80 -0
  166. package/dist/simulation/living/director.js +363 -0
  167. package/dist/simulation/living/frame.d.ts +108 -21
  168. package/dist/simulation/living/frame.js +111 -66
  169. package/dist/simulation/living/identifiers.d.ts +0 -1
  170. package/dist/simulation/living/identifiers.js +0 -3
  171. package/dist/simulation/living/index.d.ts +18 -9
  172. package/dist/simulation/living/index.js +18 -9
  173. package/dist/simulation/living/inference.d.ts +92 -50
  174. package/dist/simulation/living/inference.js +319 -175
  175. package/dist/simulation/living/knowledge.d.ts +28 -0
  176. package/dist/simulation/living/knowledge.js +73 -0
  177. package/dist/simulation/living/library.json +1177 -0
  178. package/dist/simulation/living/mechanics.d.ts +31 -34
  179. package/dist/simulation/living/mechanics.js +222 -138
  180. package/dist/simulation/living/model-input.d.ts +6 -3
  181. package/dist/simulation/living/model-input.js +18 -26
  182. package/dist/simulation/living/open-world.d.ts +74 -94
  183. package/dist/simulation/living/open-world.js +151 -30
  184. package/dist/simulation/living/phrases.d.ts +3 -0
  185. package/dist/simulation/living/phrases.js +37 -0
  186. package/dist/simulation/living/phrases.json +560 -0
  187. package/dist/simulation/living/projection.d.ts +316 -2
  188. package/dist/simulation/living/projection.js +50 -2
  189. package/dist/simulation/living/prompts/example-spec.json +11 -0
  190. package/dist/simulation/living/prompts/role-text.json +14 -0
  191. package/dist/simulation/living/prompts.d.ts +5 -0
  192. package/dist/simulation/living/prompts.js +275 -0
  193. package/dist/simulation/living/recall.d.ts +2 -2
  194. package/dist/simulation/living/reduce.d.ts +51 -14
  195. package/dist/simulation/living/reduce.js +941 -579
  196. package/dist/simulation/living/replay.d.ts +5 -4
  197. package/dist/simulation/living/replay.js +10 -9
  198. package/dist/simulation/living/runtime.d.ts +135 -25
  199. package/dist/simulation/living/runtime.js +1641 -583
  200. package/dist/simulation/living/scale.d.ts +96 -0
  201. package/dist/simulation/living/scale.js +124 -0
  202. package/dist/simulation/living/script.d.ts +5 -0
  203. package/dist/simulation/living/script.js +115 -0
  204. package/dist/simulation/living/shared-kinds.d.ts +4 -11
  205. package/dist/simulation/living/shared-kinds.js +11 -81
  206. package/dist/simulation/living/space.d.ts +14 -0
  207. package/dist/simulation/living/space.js +132 -0
  208. package/dist/simulation/living/state.d.ts +100 -0
  209. package/dist/simulation/living/state.js +393 -0
  210. package/dist/simulation/living/types.d.ts +829 -512
  211. package/dist/simulation/living/types.js +162 -187
  212. package/dist/simulation/living/world-rules.d.ts +100 -0
  213. package/dist/simulation/living/world-rules.js +267 -0
  214. package/dist/simulation/plugins/loader.js +11 -0
  215. package/dist/skills/loader.js +4 -0
  216. package/dist/tools.d.ts +1 -0
  217. package/dist/tools.js +1 -0
  218. package/dist/ui/ratatui/headless_pane_manager.d.ts +4 -1
  219. package/dist/ui/ratatui/headless_pane_manager.js +13 -9
  220. package/dist/ui/ratatui/pane_relay.js +29 -0
  221. package/dist/ui/ratatui/pane_type.d.ts +10 -0
  222. package/dist/ui/ratatui/pane_type.js +11 -0
  223. package/dist/ui/ratatui/process.d.ts +30 -0
  224. package/dist/ui/ratatui/process.js +133 -19
  225. package/dist/ui/ratatui/protocol.d.ts +124 -2
  226. package/dist/ui/ratatui/protocol.js +35 -0
  227. package/dist/ui/ratatui/relay_policy.js +3 -0
  228. package/dist/ui/ratatui/ztc_launch_trust.d.ts +2 -1
  229. package/dist/ui/ratatui/ztc_launch_trust.js +8 -1
  230. package/dist/ui/terminal_image.d.ts +12 -0
  231. package/dist/ui/terminal_image.js +21 -1
  232. package/dist/utils/codex_project_trust.d.ts +19 -0
  233. package/dist/utils/codex_project_trust.js +37 -0
  234. package/dist/utils/compaction.js +103 -20
  235. package/dist/utils/git_program_files.d.ts +19 -12
  236. package/dist/utils/git_program_files.js +411 -83
  237. package/dist/utils/host_shell.d.ts +10 -1
  238. package/dist/utils/host_shell.js +14 -1
  239. package/dist/utils/mid_turn_compaction.d.ts +2 -0
  240. package/dist/utils/mid_turn_compaction.js +2 -0
  241. package/dist/utils/models.js +6 -1
  242. package/dist/utils/sandbox.d.ts +109 -8
  243. package/dist/utils/sandbox.js +981 -187
  244. package/dist/utils/shell.d.ts +2 -0
  245. package/dist/utils/shell.js +10 -4
  246. package/dist/utils/subprocess_env.d.ts +47 -11
  247. package/dist/utils/subprocess_env.js +107 -15
  248. package/dist/utils/system_ps.d.ts +8 -0
  249. package/dist/utils/system_ps.js +39 -7
  250. package/dist/utils/unattended_compaction.d.ts +9 -0
  251. package/dist/utils/unattended_compaction.js +13 -0
  252. package/dist/utils/ztc_own_state.d.ts +8 -5
  253. package/dist/utils/ztc_own_state.js +17 -11
  254. package/dist/web/mirror_client.js +1 -0
  255. package/dist/web/mirror_stream.d.ts +50 -6
  256. package/dist/web/mirror_stream.js +160 -15
  257. package/dist/workflows/registry.js +3 -1
  258. package/dist/workspace/controller.js +12 -0
  259. package/dist/workspace_collision.d.ts +3 -0
  260. package/dist/workspace_collision.js +14 -1
  261. package/dist/workspace_session_context.js +2 -1
  262. package/dist/zlm-embed.mjs +3823 -1970
  263. package/node_modules/@zerg/model-contracts/README.md +16 -4
  264. package/node_modules/@zerg/model-contracts/index.js +6 -1
  265. package/npm-shrinkwrap.json +1 -1
  266. package/package.json +42 -24
  267. package/packages/model-contracts/README.md +16 -4
  268. package/packages/model-contracts/index.js +6 -1
@@ -1,12 +1,12 @@
1
- import { accessSync, closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs';
1
+ import { accessSync, chmodSync, closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readlinkSync, readSync, realpathSync, rmdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs';
2
2
  import { randomUUID } from 'crypto';
3
3
  import { homedir, tmpdir } from 'os';
4
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
4
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'path';
5
5
  import { execFileSync, spawnSync } from 'child_process';
6
6
  import { buildCredentialSafeSubprocessEnv, buildUserSubprocessEnv } from './subprocess_env.js';
7
- import { bubblewrapGitProgramBinds, gitProgramFiles, putBackBrokenRepositories, seatbeltGitProgramRules, undoGitProgramWrites } from './git_program_files.js';
8
- import { hostShell } from './host_shell.js';
9
- import { canonicalPath } from './canonical_path.js';
7
+ import { bubblewrapGitProgramBinds, gitProgramFiles, outermostRoots, putBackBrokenRepositories, seatbeltGitProgramRules, undoGitProgramWrites } from './git_program_files.js';
8
+ import { hostShell, posixShell, posixShellArgs } from './host_shell.js';
9
+ import { canonicalPath, sameFileKey } from './canonical_path.js';
10
10
  import { osSandboxRequested, osSandboxRequired, profileLimitsAgent } from '../config/profile_limits.js';
11
11
  import { ztcOwnSkillRoots, ztcOwnStateRoots, ztcRuntimeEntries, ztcRuntimeSeatbeltPatterns, ztcRuntimeTempFolders } from './ztc_own_state.js';
12
12
  function commandExists(command) {
@@ -19,6 +19,16 @@ function commandExists(command) {
19
19
  function shellEscape(value) {
20
20
  return "'" + value.replace(/'/g, "'\\''") + "'";
21
21
  }
22
+ /**
23
+ * What reads COMMAND inside an OS sandbox, program and arguments. The agent's shell text goes to the host's POSIX shell
24
+ * (utils/host_shell.ts), as it does outside one. A hook's command (KEEP_ENVIRONMENT, SandboxCommandOptions) goes to
25
+ * /bin/sh, as Node's shell runs it where no sandbox holds it (hooks/runner.ts): the person wrote it for that shell. The
26
+ * shell that opens bwrap's filter runs outside the sandbox and reads ZTC's own words alone: it stays /bin/sh, which reads
27
+ * no startup file (buildBubblewrapCommandPlan).
28
+ */
29
+ function planShell(command, keepEnvironment = false) {
30
+ return keepEnvironment ? ['/bin/sh', '-c', command] : [posixShell(), ...posixShellArgs(command)];
31
+ }
22
32
  function schemeString(value) {
23
33
  return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
24
34
  }
@@ -37,22 +47,230 @@ function profileAllowsNetwork(profile) {
37
47
  function profileAllowsFileWrite(profile) {
38
48
  return profile?.capabilities?.file_write !== false;
39
49
  }
50
+ /** What profileRootLooks found under a profile that names no allowedPaths: nothing. */
51
+ const NO_ROOT_LOOKS = { roots: [], linked: [], unreadable: [] };
52
+ /** An error's code, as Node gives it. */
53
+ const errorCode = (error) => error.code ?? String(error);
40
54
  /**
41
- * Where a command in CWD may write: the profile's allowedPaths, a relative one resolved against ROOTS_CWD, the session's
42
- * folder (SandboxCommandOptions.sessionCwd), as the agent's file tools resolve it; or CWD itself for a profile that names
43
- * none. A command the agent runs in another folder (run_command's `cwd`) had that folder as the root `.` names, outside
44
- * the mounted workspace (the reviewer's pinned-resident probe, 2026-11-22).
55
+ * One look at ROOT (absolute): each folder on the way to it, from /, lstat'ed once by the real path the look has built so
56
+ * far, a link read once (readlink) and followed by splicing what it names into what is left, so the look builds the real
57
+ * path itself, as realpath(3) would, and sees each link on the way with the folder that holds it. That path is then
58
+ * resolved once more (canonicalPath), which gives each folder the spelling the filesystem keeps (macOS ignores case) and
59
+ * would follow a link swapped in since: where it leads elsewhere, the root changed while ZTC looked, and is no root
60
+ * (ECHANGED). A part that doesn't exist yet (ENOENT, ENOTDIR) is kept as named, with what follows it. A folder ZTC can't
61
+ * look into, a link it can't read, a loop of links: the root is no root, and ZTC says which folder and why.
45
62
  */
46
- function allowedRoots(profile, cwd, rootsCwd = cwd) {
47
- const roots = profile?.allowedPaths?.length ? profile.allowedPaths.map(root => normalizeRoot(root, rootsCwd)) : [normalizeRoot(cwd, cwd)];
48
- return Array.from(new Set(roots));
63
+ function lookAtRoot(root) {
64
+ const top = parse(root).root;
65
+ const pending = [];
66
+ let named = top;
67
+ for (const part of root.slice(top.length).split(sep).filter(Boolean)) {
68
+ named = join(named, part);
69
+ pending.push({ part, named });
70
+ }
71
+ let real = top;
72
+ let missing;
73
+ const links = [];
74
+ let hops = 0;
75
+ for (let next = pending.shift(); next !== undefined; next = pending.shift()) {
76
+ if (next.part === '.')
77
+ continue;
78
+ if (next.part === '..') {
79
+ real = dirname(real);
80
+ continue;
81
+ }
82
+ const path = join(real, next.part);
83
+ if (missing !== undefined) {
84
+ real = path;
85
+ continue;
86
+ }
87
+ let info;
88
+ try {
89
+ info = lstatSync(path);
90
+ }
91
+ catch (error) {
92
+ const code = errorCode(error);
93
+ if (code === 'ENOENT' || code === 'ENOTDIR') {
94
+ missing = code;
95
+ real = path;
96
+ continue;
97
+ }
98
+ return { folder: real, code };
99
+ }
100
+ if (!info.isSymbolicLink()) {
101
+ real = path;
102
+ continue;
103
+ }
104
+ if (++hops > 40)
105
+ return { folder: real, code: 'ELOOP' };
106
+ let target;
107
+ try {
108
+ target = readlinkSync(path);
109
+ }
110
+ catch (error) {
111
+ return { folder: real, code: errorCode(error) };
112
+ }
113
+ links.push({ link: path, named: next.named ?? path, holder: real, leads: resolve(real, target) });
114
+ pending.unshift(...target.split(sep).filter(Boolean).map(part => ({ part })));
115
+ if (isAbsolute(target))
116
+ real = parse(target).root;
117
+ }
118
+ let checked;
119
+ try {
120
+ checked = canonicalPath(real);
121
+ }
122
+ catch (error) {
123
+ return { folder: real, code: errorCode(error) };
124
+ }
125
+ if (sameFileKey(checked) !== sameFileKey(real))
126
+ return { folder: real, code: 'ECHANGED' };
127
+ return { real: checked, ...(missing === undefined ? {} : { missing }), links };
128
+ }
129
+ /**
130
+ * One look at each root PROFILE names (allowedPaths, a relative one ROOTS_CWD's: lookAtRoot), which every plan, rule and
131
+ * check after it takes as it found them, each root by the real path that look built, without resolving the root again:
132
+ * the look was a walk by lstat, and everything after it resolved each root again by its path (the policy's canonical
133
+ * roots, Seatbelt's rules, bubblewrap's real path and bind), so a command left running in the background that swapped a
134
+ * root, or a folder above it, between a folder and a link to a folder outside every root had the policy, the rules or
135
+ * the bind follow the link the look hadn't seen: write_file, read_file and the command itself wrote and read outside
136
+ * every root (the review of fix/r9-release-blockers' repair, R9C-ESCAPE-1, R9C-ESCAPE-2). A root that is, or is named
137
+ * through, a symbolic link in a folder that lies, by its real path, in one of the roots (their real paths, this one's
138
+ * among them) is a link a confined command could have made, or pointed elsewhere, as one can any file in a root it
139
+ * writes, or a writing profile's command did before; it is refused, and it alone (LINKED): the OS sandbox doesn't bind
140
+ * it, so the link stays a plain link in the bind of the root that holds it, and the policy keeps the file tools out of it
141
+ * (agent/runtime/policy.ts). The policy, which resolved each root through links on every call, let write_file write
142
+ * HOME/.bashrc once a command had made `./build` a link there, and the next plan bound where the link led (the review of
143
+ * fix/r9-release-blockers, RV8-LINK); a profile whose commands write nothing read through one a writing profile's command
144
+ * had made (R9C-ESCAPE-3), so this holds under every profile that names allowedPaths. A link no root holds (macOS's /tmp
145
+ * and /var, ~/link -> ~/real, a HOME that is a link) names a root as before. A root ZTC can't look at (a folder on the
146
+ * way it can't look into, `chmod 000`; one that became a link as it looked) is refused alone too (UNREADABLE): the policy
147
+ * threw on it, and every tool of the profile failed (R9C-TRUTH-5).
148
+ */
149
+ export function profileRootLooks(profile, rootsCwd) {
150
+ if (!profile?.allowedPaths?.length)
151
+ return NO_ROOT_LOOKS;
152
+ const looks = Array.from(new Set(profile.allowedPaths.map(root => normalizeRoot(root, rootsCwd)))).map(root => ({ root, look: lookAtRoot(root) }));
153
+ const reals = looks.flatMap(({ look }) => 'real' in look ? [sameFileKey(look.real)] : []);
154
+ const held = (folder) => reals.some(real => folder === real || folder.startsWith(real.endsWith(sep) ? real : `${real}${sep}`));
155
+ const found = { roots: [], linked: [], unreadable: [] };
156
+ for (const { root, look } of looks) {
157
+ if (!('real' in look)) {
158
+ found.unreadable.push({ root, ...look });
159
+ continue;
160
+ }
161
+ const link = look.links.find(({ holder }) => held(sameFileKey(holder)));
162
+ if (link !== undefined)
163
+ found.linked.push({ root, link: link.named, leads: link.leads, real: look.real });
164
+ else
165
+ found.roots.push({ root, real: look.real, ...(look.missing === undefined ? {} : { missing: look.missing }) });
166
+ }
167
+ return found;
49
168
  }
50
169
  /**
51
- * ROOTS as Seatbelt's rules must name them, each as named and by its real path (canonicalPath: the part that exists
52
- * resolved, the rest as named). Seatbelt matches a rule against the real path of what a command opens, so a root spelled
53
- * through a link matched nothing: with the session's folder named through one (a /cd to it by another name, the agent
54
- * built again there), a command could write nowhere in its workspace, and could make a denied folder that didn't exist
55
- * yet (the reviewer's resident probe, 2026-11-22).
170
+ * The roots a command in CWD under PROFILE has, by one look at each (LOOKS, profileRootLooks, of the session's folder's
171
+ * relative roots): those the profile names that it keeps, or CWD itself for a profile that names none. A command the agent
172
+ * runs in another folder (run_command's `cwd`) had that folder as the root `.` names, outside the mounted workspace (the
173
+ * reviewer's pinned-resident probe, 2026-11-22).
174
+ */
175
+ function commandRoots(profile, cwd, looks) {
176
+ if (profile?.allowedPaths?.length)
177
+ return looks.roots;
178
+ const root = normalizeRoot(cwd, cwd);
179
+ const look = lookAtRoot(root);
180
+ return [{ root, real: 'real' in look ? look.real : root, ...('real' in look && look.missing !== undefined ? { missing: look.missing } : {}) }];
181
+ }
182
+ /**
183
+ * Where a command in CWD may write, as named: the profile's allowedPaths that one look at each keeps (commandRoots), a
184
+ * relative one resolved against ROOTS_CWD, the session's folder (SandboxCommandOptions.sessionCwd), as the agent's file
185
+ * tools resolve it; or CWD itself for a profile that names none.
186
+ */
187
+ function allowedRoots(profile, cwd, rootsCwd = cwd, looks = profileRootLooks(profile, rootsCwd)) {
188
+ return commandRoots(profile, cwd, looks).map(({ root }) => root);
189
+ }
190
+ /**
191
+ * Why ZTC couldn't look at a root (UnreadableProfileRoot: FOLDER, where its look stopped, and CODE, why), and what to do
192
+ * about it: a folder that changed as ZTC looked; a link on the way that leads round in a loop (ELOOP); a name longer than
193
+ * the filesystem allows (ENAMETOOLONG); a folder ZTC may not look into (EACCES, EPERM, and anything else), whose mode to
194
+ * give back. Each but the last said to give a folder back its mode, which none of them helps.
195
+ */
196
+ export function unreadableRootReason({ folder, code }) {
197
+ if (code === 'ECHANGED') {
198
+ return `it changed while ZTC looked at it (a folder on the way to it became a link, ${folder} leading elsewhere when ZTC looked again). `
199
+ + 'Run the command again once nothing alongside moves the folders in its roots.';
200
+ }
201
+ if (code === 'ELOOP') {
202
+ return `a link on the way to it, in ${folder}, leads round in a loop (ELOOP). Remove that link, or remove the root from the profile's allowedPaths.`;
203
+ }
204
+ if (code === 'ENAMETOOLONG') {
205
+ return `a name on the way to it, below ${folder}, is longer than the filesystem allows (ENAMETOOLONG). Name it by a shorter path in the profile's `
206
+ + 'allowedPaths, or remove it.';
207
+ }
208
+ return `ZTC can't look into ${folder} to find it (${code}). Give the folder back its mode (chmod u+rx ${folder}), or remove the root from the `
209
+ + 'profile\'s allowedPaths.';
210
+ }
211
+ /**
212
+ * What a link root's refusal says to do (LINKED, a root its profile names that is, or is named through, a link a command
213
+ * could have made; ROOTS, the real paths of the roots kept beside it; SESSION, the session's folder, or none): remove the
214
+ * link, or name the folder the person meant in allowedPaths, by its real path, or start the session from it where the
215
+ * root is the session's own (allowedPaths [~, .] in a session at ~/proj-link), once they have checked that it is the
216
+ * folder the link leads to now, which a command could have chosen; and where the link leads into another root, that its
217
+ * folder is reachable through that root (the review of fix/r9-release-blockers' repair, R9C-REGRESSION-6). It said to
218
+ * name the folder the link leads to, whatever a command had pointed it at (appstore's LINK-ADVICE).
219
+ */
220
+ export function linkedRootAdvice({ root, real }, roots, session) {
221
+ const through = roots.find(other => real === other || real.startsWith(other.endsWith(sep) ? other : `${other}${sep}`));
222
+ return 'Remove the link, or name the folder you meant by its real path in the profile\'s allowedPaths'
223
+ + `${session !== undefined && root === session ? ', or start the session from it' : ''}: the link leads to ${real} now, where a command could have `
224
+ + 'pointed it, so check that it is that folder first.'
225
+ + `${through === undefined ? '' : ` What it leads to is in ${through}, a root of this profile, and reachable through it.`}`;
226
+ }
227
+ /** What a plan says of LINKED, a root its profile names that it doesn't bind (profileRootLooks), in the command's result. */
228
+ function linkedRootNotice(linked, roots, session) {
229
+ return `ZTC's sandbox gives this command no root at ${linked.root}, which its permission profile names: `
230
+ + `${linked.link === linked.root ? 'it is' : `it is named through ${linked.link},`} a link in a folder a command may write, which a command `
231
+ + `could have made, to ${linked.leads}. ${linkedRootAdvice(linked, roots, session)}`;
232
+ }
233
+ /** What a plan says of UNREADABLE, a root its profile names that ZTC couldn't look at (profileRootLooks), in the command's result. */
234
+ function unreadableRootNotice(unreadable) {
235
+ return `ZTC's sandbox gives this command no root at ${unreadable.root}, which its permission profile names: ${unreadableRootReason(unreadable)}`;
236
+ }
237
+ /**
238
+ * What a plan under OPTIONS, whose roots one look found as LOOKS (profileRootLooks of the session's folder's, SESSION's,
239
+ * relative roots), says of the roots it leaves out: those that are links a command could have made, and those ZTC
240
+ * couldn't look at.
241
+ */
242
+ function profileRootNotices(looks, session) {
243
+ const reals = looks.roots.map(({ real }) => real);
244
+ return [...looks.linked.map(linked => linkedRootNotice(linked, reals, resolve(session))), ...looks.unreadable.map(unreadableRootNotice)];
245
+ }
246
+ /**
247
+ * What a bubblewrap plan says of each root its profile names, kept by one look at the roots (LOOKS, profileRootLooks), that
248
+ * lies by its real path inside another root but is named by a spelling no root's bind shows (`../sub-link`, a link beside
249
+ * the workspace that leads into ws/sub): bubblewrap binds nothing of its own for a root inside another root
250
+ * (buildBubblewrapArgs), so that spelling is no folder in the command's sandbox, and a command that reads it finds nothing
251
+ * and one that writes there loses what it writes when it ends, where it said nothing (appstore's ALIAS-UNBOUND). A bind at
252
+ * that spelling would be one of the folder inside the root by its path, which bwrap looks up again as it starts, and which
253
+ * a command left running in the background can swap for a link to a folder outside every root (R9C-ESCAPE-2).
254
+ */
255
+ function unboundRootNotices(looks) {
256
+ const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
257
+ const outer = looks.roots.filter(({ real }) => !looks.roots.some(other => other.real !== real && inside(real, other.real)));
258
+ return looks.roots.flatMap(({ root, real }) => {
259
+ const holder = outer.find(other => other.real !== real && inside(real, other.real));
260
+ if (holder === undefined || outer.some(other => inside(root, other.root) || inside(root, other.real)))
261
+ return [];
262
+ return [`ZTC's sandbox shows this command nothing at ${root}, which its permission profile names as a root: it leads to ${real}, inside `
263
+ + `${holder.root}, another of the profile's roots, and bubblewrap binds nothing of its own for a root inside another root. The command `
264
+ + `reaches that folder by its real path (${real}); at ${root} it finds nothing, and what it writes there is lost when it ends.`];
265
+ });
266
+ }
267
+ /**
268
+ * ROOTS as Seatbelt's deny rules name them, each as named and by its real path (canonicalPath: the part that exists
269
+ * resolved, the rest as named): Seatbelt matches a rule against the real path of what a command opens, and a rule naming
270
+ * a link's own path matches what is done to the link itself, so a denial named through a link stays denied, and its link
271
+ * can't be removed. Not for what a command may reach: an allow rule for a root that is itself a link (~/link -> ~/real,
272
+ * the session's folder reached through a link) let a command remove the link and make it lead elsewhere, which the next
273
+ * plan's look followed, so allow rules name each root by its real path alone (writeSeatbeltProfile).
56
274
  */
57
275
  function seatbeltRoots(roots) {
58
276
  return Array.from(new Set(roots.flatMap(root => {
@@ -65,12 +283,14 @@ function seatbeltRoots(roots) {
65
283
  })));
66
284
  }
67
285
  /**
68
- * The folders a command under PROFILE may write, its relative roots those of FOLDER (allowedRoots), each as named and by
69
- * its real path (seatbeltRoots); none under a profile that writes nothing. ConfigStore.pinStartupPermissions keeps ZTC's
70
- * own state and TMPDIR out of them.
286
+ * The folders a command under PROFILE may write, its relative roots those of FOLDER, each as named and by the real path
287
+ * one look at it found (commandRoots); none under a profile that writes nothing. ConfigStore.pinStartupPermissions keeps
288
+ * ZTC's own state and TMPDIR out of them.
71
289
  */
72
290
  export function commandWriteRoots(profile, folder) {
73
- return profileAllowsFileWrite(profile) ? seatbeltRoots(allowedRoots(profile, folder, folder)) : [];
291
+ if (!profileAllowsFileWrite(profile))
292
+ return [];
293
+ return Array.from(new Set(commandRoots(profile, folder, profileRootLooks(profile, folder)).flatMap(({ root, real }) => [root, real])));
74
294
  }
75
295
  /**
76
296
  * Whether the folders a command under PROFILE may write follow the folder it runs in: a profile that writes and names
@@ -84,11 +304,13 @@ export function commandWriteRootsFollowCwd(profile) {
84
304
  function deniedRoots(profile, rootsCwd) {
85
305
  const roots = (profile?.deniedPaths || []).map(root => normalizeRoot(root, rootsCwd));
86
306
  for (const root of [...roots]) {
307
+ // By its real path too, one not made yet included (canonicalPath: the part that exists resolved, the rest as named):
308
+ // a root bubblewrap doesn't bind on its own (one inside another root, below) shows the denial only by its real path.
87
309
  try {
88
- roots.push(realpathSync(root));
310
+ roots.push(canonicalPath(root));
89
311
  }
90
312
  catch {
91
- // Keep the original denial even when its target does not exist yet.
313
+ // Keep the original denial even when ZTC can't look it up.
92
314
  }
93
315
  }
94
316
  return Array.from(new Set(roots));
@@ -250,10 +472,13 @@ function gitFileDirs(dotGit, directory, cwd, home, depth = 0) {
250
472
  }
251
473
  /**
252
474
  * What git reads outside the project: the person's settings files (never ~/.config/git/credentials, git's plain-text
253
- * credential store), and the repository holding `cwd`, a worktree's included, when it is a real git dir.
475
+ * credential store), and the repository holding `cwd`, a worktree's included, when it is a real git dir; none that one
476
+ * of ROOTS (the real paths one look at each root found) holds, which the command reads through that root already. Each
477
+ * was bound again, by its path, as bwrap started: a mount point inside a root, under one inside another too, which a
478
+ * folder above it swapped for a link led outside every root.
254
479
  */
255
- function gitReadRoots(cwd, home = homedir()) {
256
- const roots = [join(home, '.gitconfig'), ...['config', 'ignore', 'attributes'].map(name => join(home, '.config', 'git', name))];
480
+ function gitReadRoots(cwd, roots, home = homedir()) {
481
+ const found = [join(home, '.gitconfig'), ...['config', 'ignore', 'attributes'].map(name => join(home, '.config', 'git', name))];
257
482
  for (let directory = cwd;; directory = dirname(directory)) {
258
483
  const dotGit = join(directory, '.git');
259
484
  try {
@@ -261,10 +486,10 @@ function gitReadRoots(cwd, home = homedir()) {
261
486
  if (info.isDirectory()) {
262
487
  const gitDir = gitDirFolder(dotGit, cwd, home);
263
488
  if (gitDir)
264
- roots.push(gitDir);
489
+ found.push(gitDir);
265
490
  }
266
491
  else if (info.isFile()) {
267
- roots.push(...gitFileDirs(dotGit, directory, cwd, home));
492
+ found.push(...gitFileDirs(dotGit, directory, cwd, home));
268
493
  }
269
494
  break;
270
495
  }
@@ -272,20 +497,48 @@ function gitReadRoots(cwd, home = homedir()) {
272
497
  if (dirname(directory) === directory)
273
498
  break;
274
499
  }
275
- return Array.from(new Set(roots)).filter(root => existsSync(root));
500
+ const held = (path) => roots.some(root => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`));
501
+ return Array.from(new Set(found)).filter(path => existsSync(path) && !held(path));
276
502
  }
277
503
  /**
278
- * Where a sandboxed command may read, as the audit records it: its roots (relative ones the session's folder's, ROOTS_CWD),
279
- * and the files READ_PATHS names beside them.
504
+ * The folder CWD a command runs in, where it may read beside its ROOTS (commandRoots) and the system's folders
505
+ * (SYSTEM_ROOTS): its real path, by one look at it (lookAtRoot), where no root holds it, as named or by that path, and
506
+ * the look met no link in a root on the way; undefined where a root holds it, or where it is named through such a link (a
507
+ * link a command could have made, or a command left running in the background swapped in after the policy admitted the
508
+ * folder), or ZTC can't look at it, so nothing outside the roots is read through it. Seatbelt's read rules named the
509
+ * folder by its real path as the plan resolved it again, after the policy's check: a command that swapped `sub` for a
510
+ * link to a folder outside every root had a plan read there (the review of fix/r9-release-blockers' repair,
511
+ * R9C-ESCAPE-4). A folder a profile not requiring the sandbox lets a command run in, outside the roots, is read as before.
280
512
  */
281
- function commandReadRoots(profile, cwd, systemRoots, readPaths = [], rootsCwd = cwd) {
513
+ function commandFolderRead(cwd, roots, systemRoots) {
514
+ const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
515
+ const folder = resolve(cwd);
516
+ if (roots.some(({ root, real }) => inside(folder, root) || inside(folder, real)))
517
+ return undefined;
518
+ const look = lookAtRoot(folder);
519
+ if (!('real' in look))
520
+ return undefined;
521
+ const reals = roots.map(({ real }) => sameFileKey(real));
522
+ if (look.links.some(({ holder }) => reals.some(real => inside(sameFileKey(holder), real))))
523
+ return undefined;
524
+ if (roots.some(({ real }) => inside(look.real, real)) || seatbeltRoots(systemRoots).some(root => inside(look.real, root)))
525
+ return undefined;
526
+ return look.real;
527
+ }
528
+ /**
529
+ * Where a sandboxed command in CWD may read, as the audit records it: the system's folders (SYSTEM_ROOTS) that exist, the
530
+ * folder it runs in where its roots don't hold it (commandFolderRead), its roots (ROOTS, commandRoots: relative ones the
531
+ * session's folder's) as named, what git reads under a profile that writes nothing, and the files READ_PATHS names.
532
+ */
533
+ function commandReadRoots(profile, cwd, systemRoots, readPaths = [], roots) {
282
534
  if (readsEverywhere(profile))
283
535
  return ['/'];
536
+ const folder = commandFolderRead(cwd, roots, systemRoots);
284
537
  return Array.from(new Set([
285
538
  ...systemRoots.filter(root => existsSync(root)),
286
- cwd,
287
- ...allowedRoots(profile, cwd, rootsCwd),
288
- ...(profileAllowsFileWrite(profile) ? [] : gitReadRoots(cwd)),
539
+ ...(folder === undefined ? [] : [folder]),
540
+ ...roots.map(({ root }) => root),
541
+ ...(profileAllowsFileWrite(profile) ? [] : gitReadRoots(cwd, roots.map(({ real }) => real))),
289
542
  ...readPaths.filter(path => isAbsolute(path) && existsSync(path)),
290
543
  ]));
291
544
  }
@@ -460,13 +713,18 @@ const SEATBELT_SYSTEM_READ_ROOTS = ['/bin', '/sbin', '/usr', '/System', '/Librar
460
713
  /**
461
714
  * What a command in CWD under PROFILE may not change of the repositories it can write (utils/git_program_files.ts): the
462
715
  * one it runs in, the session's (SESSION_CWD), each its writable roots hold, and each an earlier plan of this process
463
- * found there. Null for a profile that writes nothing.
716
+ * found there. Its protection roots are the real paths one look at each found (LOOKS, profileRootLooks), the outermost
717
+ * alone (outermostRoots): a root inside another is that root's, as bubblewrap binds it, so the pins above a repository
718
+ * run to the outermost root, and no root is resolved again. Each named root's look real path is still walked (`walk`),
719
+ * so a named nested root deeper than 4 folders below an outer root is still found and pinned to the outermost root.
720
+ * Null for a profile that writes nothing.
464
721
  */
465
- function commandGitProgramFiles(profile, cwd, sessionCwd) {
722
+ function commandGitProgramFiles(profile, cwd, sessionCwd, looks = profileRootLooks(profile, sessionCwd ?? cwd)) {
466
723
  if (!profileAllowsFileWrite(profile))
467
724
  return null;
468
- const roots = allowedRoots(profile, cwd, sessionCwd ?? cwd);
469
- return gitProgramFiles([cwd, ...(sessionCwd ? [sessionCwd] : []), ...roots], roots);
725
+ const reals = commandRoots(profile, cwd, looks).map(({ real }) => real);
726
+ const roots = outermostRoots(reals);
727
+ return gitProgramFiles([cwd, ...(sessionCwd ? [sessionCwd] : []), ...roots], roots, { walk: reals });
470
728
  }
471
729
  /** The notices each ZTC process has said already (sandboxNoticesToTell). */
472
730
  const toldNotices = new Set();
@@ -526,12 +784,22 @@ function seatbeltAncestorPins(writeRoots, denied, tempFolders) {
526
784
  missing: [...aboveDenials].filter(folder => !exists(folder)).sort((a, b) => a.split(sep).length - b.split(sep).length || a.localeCompare(b)),
527
785
  };
528
786
  }
787
+ /**
788
+ * Which folder each folder a Seatbelt plan of this process made above a denial not made yet is (makeSeatbeltAncestors):
789
+ * by its device and inode at the real path it had, so the step after the last command that holds it (placeholderRelease)
790
+ * removes it only where it is still that folder.
791
+ */
792
+ const seatbeltMadeFolders = new Map();
529
793
  /**
530
794
  * Makes each of MISSING (seatbeltAncestorPins), outermost first, for a Seatbelt command to write in: only where the
531
- * folder that holds it is, by its real path, inside a root the command writes (WRITE_ROOTS), and there by its real path,
532
- * so nothing is made through a link outside them. A folder another plan of this process made and still holds is this
533
- * plan's too. The folders it made, held by the plan, for the step after the command to remove where nothing was put in
534
- * them (placeholderRelease); a folder it can't make stays missing, and denied as one.
795
+ * folder that holds it is, by its real path, inside a root the command writes (WRITE_ROOTS, the real paths one look at
796
+ * each root found), and there by its real path, so nothing is made through a link outside them; and looks at it again once
797
+ * made, as bubblewrap's plan does (madeFolderError): one its mkdir made through a link swapped in for a folder above it,
798
+ * which isn't at its real path, is removed where it is still the one made, and stays missing, denied as one. It made
799
+ * where the link led and kept it (the review of fix/r9-release-blockers' repair, R9C-TRUTH-7). A folder another plan of
800
+ * this process made and still holds is this plan's too. The folders it made, held by the plan, for the step after the
801
+ * command to remove where nothing was put in them and they are still the folders made (placeholderRelease); a folder it
802
+ * can't make stays missing, and denied as one.
535
803
  */
536
804
  function makeSeatbeltAncestors(missing, writeRoots) {
537
805
  const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
@@ -541,7 +809,6 @@ function makeSeatbeltAncestors(missing, writeRoots) {
541
809
  catch {
542
810
  return undefined;
543
811
  } };
544
- const roots = Array.from(new Set(writeRoots.flatMap(root => real(root) ?? [])));
545
812
  const made = [];
546
813
  for (const folder of missing) {
547
814
  const existing = real(folder);
@@ -551,29 +818,63 @@ function makeSeatbeltAncestors(missing, writeRoots) {
551
818
  continue;
552
819
  }
553
820
  const holder = real(dirname(folder));
554
- if (holder === undefined || !roots.some(root => inside(holder, root)))
821
+ if (holder === undefined || !writeRoots.some(root => inside(holder, root)))
555
822
  continue;
556
823
  const target = join(holder, basename(folder));
557
824
  try {
558
825
  mkdirSync(target);
826
+ }
827
+ catch {
828
+ continue; /* it stays missing, and denied as one */
829
+ }
830
+ let info;
831
+ try {
832
+ info = lstatSync(target);
833
+ }
834
+ catch {
835
+ continue;
836
+ }
837
+ if (info.isDirectory() && real(target) === target) {
838
+ seatbeltMadeFolders.set(target, { dev: info.dev, ino: info.ino, physical: target });
559
839
  made.push(target);
840
+ continue;
560
841
  }
561
- catch { /* it stays missing, and denied as one */ }
842
+ // Made through a link: removed, where the folder there is still the one this mkdir made.
843
+ try {
844
+ const again = lstatSync(target);
845
+ if (info.isDirectory() && again.dev === info.dev && again.ino === info.ino)
846
+ rmdirSync(target);
847
+ }
848
+ catch { /* gone */ }
562
849
  }
563
850
  return made;
564
851
  }
565
- function writeSeatbeltProfile(profile, cwd, env, hideOwnState = false, sessionCwd, readPaths = []) {
852
+ function writeSeatbeltProfile(profile, cwd, env, hideOwnState = false, sessionCwd, readPaths = [], looks = profileRootLooks(profile, sessionCwd ?? cwd)) {
566
853
  // A profile that writes nothing and names no allowedPaths reads everywhere (see readsEverywhere). Denied roots still
567
854
  // apply below, and so does the denial of ZTC's own state, over the files READ_PATHS names too. The profile's relative
568
- // roots are the session's folder's, wherever in it or outside it the command runs (allowedRoots).
855
+ // roots are the session's folder's, wherever in it or outside it the command runs (allowedRoots). Each root as one look
856
+ // at it found it (LOOKS, profileRootLooks), by that real path alone, resolved no more: the rules named each as named and
857
+ // by its real path as the plan resolved it again, so a root a command swapped for a link to a folder outside every root
858
+ // after that look had its rules allow the folder outside (the review of fix/r9-release-blockers' repair, R9C-ESCAPE-1),
859
+ // and a rule naming a root that is itself a link (~/link -> ~/real, the session's folder reached through one) let a
860
+ // command remove the link and point it elsewhere for the next plan to follow (seatbeltRoots).
569
861
  const rootsCwd = sessionCwd ?? cwd;
570
- const readRoots = seatbeltRoots(commandReadRoots(profile, cwd, [...SEATBELT_SYSTEM_READ_ROOTS, ...selectedDeveloperReadRoots(cwd, env)], readPaths, rootsCwd));
571
- const writeRoots = profileAllowsFileWrite(profile) ? seatbeltRoots(allowedRoots(profile, cwd, rootsCwd)) : [];
862
+ const roots = commandRoots(profile, cwd, looks);
863
+ const systemRoots = [...SEATBELT_SYSTEM_READ_ROOTS, ...selectedDeveloperReadRoots(cwd, env)];
864
+ const folder = readsEverywhere(profile) ? undefined : commandFolderRead(cwd, roots, systemRoots);
865
+ const readRoots = readsEverywhere(profile) ? ['/'] : Array.from(new Set([
866
+ ...seatbeltRoots(systemRoots.filter(root => existsSync(root))),
867
+ ...(folder === undefined ? [] : [folder]),
868
+ ...roots.map(({ real }) => real),
869
+ ...(profileAllowsFileWrite(profile) ? [] : seatbeltRoots(gitReadRoots(cwd, roots.map(({ real }) => real)))),
870
+ ...seatbeltRoots(readPaths.filter(path => isAbsolute(path) && existsSync(path))),
871
+ ]));
872
+ const writeRoots = profileAllowsFileWrite(profile) ? Array.from(new Set(roots.map(({ real }) => real))) : [];
572
873
  const denyRoots = seatbeltRoots(deniedRoots(profile, rootsCwd));
573
874
  const writes = profileAllowsFileWrite(profile);
574
875
  // Where the repositories the command may write name the programs git starts: read-only to it, though it may commit,
575
876
  // stage, branch and fetch (utils/git_program_files.ts).
576
- const programs = commandGitProgramFiles(profile, cwd, sessionCwd);
877
+ const programs = commandGitProgramFiles(profile, cwd, sessionCwd, looks);
577
878
  const gitPrograms = programs ? seatbeltGitProgramRules(programs, schemeString) : [];
578
879
  // Each folder from a writable root down to what the profile denies, ZTC's own state and its runtime's temp folders,
579
880
  // pinned as itself (seatbeltAncestorPins).
@@ -630,7 +931,8 @@ function writeSeatbeltProfile(profile, cwd, env, hideOwnState = false, sessionCw
630
931
  ...ancestors.rules,
631
932
  // The person's skills folder in it, which the agent reads as the file tools do: reads alone, after the denial, so they
632
933
  // win as equally specific rules that come later do; a link there into the rest of ZTC's state stays denied.
633
- ...ownSkillReadRoots(hideOwnState, readRoots).map(root => `(allow file-read* file-read-data (subpath ${schemeString(root)}))`),
934
+ ...ownSkillReadRoots(hideOwnState, [...readRoots, ...roots.map(({ root }) => root)])
935
+ .map(root => `(allow file-read* file-read-data (subpath ${schemeString(root)}))`),
634
936
  ];
635
937
  // Every plan owns its policy. Timestamp names let simultaneous plans replace
636
938
  // each other's permissions before sandbox-exec has read the file.
@@ -766,15 +1068,21 @@ function hostSocketFolderRefusal(cwd, real, env, roots, session) {
766
1068
  * folder below it, was in the command's reach: the agent named one with a socket in it, or the folder that holds
767
1069
  * ~/.docker, and the service acted outside the sandbox (the reviewer's re-verify of the bwrap plan, R2, 2026-11-23). ROOTS,
768
1070
  * and the session's folder SESSION where a bind holds it, are where to run the command instead. NETWORK says why no filter
769
- * does: the profile keeps the network, or, without it, ZTC has no filter for this architecture (unixSocketFilter).
1071
+ * does: the profile keeps the network, or, without it, ZTC has no filter for this architecture (unixSocketFilter). LINKED:
1072
+ * the folder is named through a link in a root, which a command could have made, or swapped in after the policy admitted
1073
+ * the folder, to one outside the roots: no bind is made through it, filter or none (R9C-ESCAPE-4).
770
1074
  */
771
- function outsideRootsRefusal(cwd, roots, session, network) {
1075
+ function outsideRootsRefusal(cwd, roots, session, network, linked = false) {
772
1076
  const unfiltered = network ? 'a command that may use the network'
773
1077
  : 'a command no filter keeps from Unix sockets, as ZTC has none for this architecture';
774
- return `Permission denied: working directory is outside this profile's roots (${cwd}), and bubblewrap binds no folder outside them `
775
- + `for ${unfiltered}: a host service's socket in it would be in the command's reach. `
776
- + `Run the command in a folder inside this profile's roots (${roots.join(', ')}): give it one there as its working directory`
1078
+ const instead = `Run the command in a folder inside this profile's roots (${roots.join(', ')}): give it one there as its working directory`
777
1079
  + `${session !== undefined && session !== cwd ? ', or none to run it in the session\'s folder' : ''}.`;
1080
+ if (linked) {
1081
+ return `Permission denied: working directory is named through a link in a folder a command may write, which a command could have `
1082
+ + `made, to a folder outside this profile's roots (${cwd}), and bubblewrap binds no folder through such a link. ${instead}`;
1083
+ }
1084
+ return `Permission denied: working directory is outside this profile's roots (${cwd}), and bubblewrap binds no folder outside them `
1085
+ + `for ${unfiltered}: a host service's socket in it would be in the command's reach. ${instead}`;
778
1086
  }
779
1087
  /**
780
1088
  * Why bubblewrap won't plan a command in CWD under PROFILE whose roots (allowedRoots, a relative one ROOTS_CWD's) would put
@@ -789,7 +1097,7 @@ function outsideRootsRefusal(cwd, roots, session, network) {
789
1097
  * refused too, unless it is the session's folder (SESSION_CWD) or lies in it: the folder the person started ZTC in is
790
1098
  * theirs to work in.
791
1099
  */
792
- function hostSocketRootRefusal(profile, cwd, rootsCwd, env, sessionCwd) {
1100
+ function hostSocketRootRefusal(profile, cwd, rootsCwd, env, sessionCwd, looks = profileRootLooks(profile, rootsCwd)) {
793
1101
  const real = (path) => { try {
794
1102
  return realpathSync(path);
795
1103
  }
@@ -798,9 +1106,14 @@ function hostSocketRootRefusal(profile, cwd, rootsCwd, env, sessionCwd) {
798
1106
  } };
799
1107
  const reach = 'which bubblewrap keeps out of a command\'s reach.';
800
1108
  if (profile?.allowedPaths?.length) {
1109
+ // Each root as one look found it (LOOKS, profileRootLooks): one the plan doesn't bind, a link a command could have made
1110
+ // or one ZTC couldn't look at, puts nothing in reach.
1111
+ const kept = new Map(looks.roots.map(({ root, real: found }) => [root, found]));
801
1112
  for (const entry of profile.allowedPaths) {
802
1113
  const root = normalizeRoot(entry, rootsCwd);
803
- const what = hostSocketRelation(root, real(root), env, 'runtime');
1114
+ if (!kept.has(root))
1115
+ continue;
1116
+ const what = hostSocketRelation(root, kept.get(root), env, 'runtime');
804
1117
  if (what === undefined)
805
1118
  continue;
806
1119
  const instead = expandedRoot(entry).startsWith(sep)
@@ -865,16 +1178,12 @@ export function unixSocketFilter(arch = process.arch) {
865
1178
  return filter;
866
1179
  }
867
1180
  /**
868
- * How many plans of this process stand a placeholder on each folder bwrap makes for one (placeholderPlan). The step after
869
- * a command (placeholderRelease) removes a folder only once no plan holds it: a command another plan runs alongside
870
- * would have its mount dropped with the folder, and could then make the denied path after all.
1181
+ * How many Seatbelt plans of this process hold each folder made above a denial not made yet (makeSeatbeltAncestors). The
1182
+ * step after a command (placeholderRelease) removes a folder only once no plan holds it. A bubblewrap plan holds what it
1183
+ * stands on by a hold on the host instead (HOLD_NAME), which every ZTC sees.
871
1184
  */
872
1185
  const placeholderHolds = new Map();
873
- /**
874
- * Whether PATH is only the folder a plan of this process still stands a placeholder on (placeholderHolds): held, and still
875
- * a folder. One the person has since made a file of, while a command whose plan stood one there still ran, is theirs, and
876
- * hidden as a file is: an empty folder bwrap mounted over it would start no command (the recheck of the follow-ups).
877
- */
1186
+ /** Whether PATH is a folder a Seatbelt plan of this process made, and still holds (placeholderHolds), and still a folder. */
878
1187
  function heldPlaceholder(path) {
879
1188
  if (!placeholderHolds.has(path))
880
1189
  return false;
@@ -885,22 +1194,87 @@ function heldPlaceholder(path) {
885
1194
  return false;
886
1195
  }
887
1196
  }
1197
+ /**
1198
+ * The hold a bubblewrap plan puts in each folder its placeholders stand on (placeholderPlan), on the host, before bwrap
1199
+ * starts (holdPlaceholderFolders): an empty folder of its own, `.ztc-hold-<pid namespace>-<pid>-<nonce>`, which the
1200
+ * placeholder's mount hides from every command. rmdir(2) removes no folder that holds anything, so no ZTC's step after
1201
+ * its command (bubblewrapRelease) removes that folder, nor a folder above it, while another plan, of its own process or
1202
+ * of another ZTC's, still holds it. Plans counted only their own process's: the step after one ZTC's command removed the
1203
+ * folders another ZTC's running command stood on, and Linux lets a process remove a folder that is a mount point only in
1204
+ * another mount namespace, whose mounts go with it, so that command made the denied path (the review of
1205
+ * fix/r9-release-blockers, RV-2; the README's Limits had it, as N8). The pid and its namespace (the inode of
1206
+ * /proc/self/ns/pid; 0 where there is none) say whose hold it is: the step after a command removes the hold of a process
1207
+ * of this namespace that has ended (holdLive), as a ZTC killed while its command ran leaves one.
1208
+ */
1209
+ const HOLD_NAME = /^\.ztc-hold-(\d+)-(\d+)-[0-9a-f]+$/;
1210
+ /** This process's pid namespace, as its holds name it (HOLD_NAME). */
1211
+ const HOLD_NAMESPACE = (() => {
1212
+ try {
1213
+ return /\[(\d+)\]/.exec(readlinkSync('/proc/self/ns/pid'))?.[1] ?? '0';
1214
+ }
1215
+ catch {
1216
+ return '0';
1217
+ }
1218
+ })();
1219
+ /**
1220
+ * Whether the plan whose hold is NAME (HOLD_NAME) may still run: not where its process, one of this pid namespace, has
1221
+ * ended. One of another namespace's (a container sharing the folder), or one this process may not signal, may.
1222
+ */
1223
+ function holdLive(name) {
1224
+ const match = HOLD_NAME.exec(name);
1225
+ if (match === null || match[1] !== HOLD_NAMESPACE)
1226
+ return true;
1227
+ try {
1228
+ process.kill(Number(match[2]), 0);
1229
+ return true;
1230
+ }
1231
+ catch (error) {
1232
+ return error.code !== 'ESRCH';
1233
+ }
1234
+ }
1235
+ /**
1236
+ * Whether PATH is a folder that holds nothing but plans' holds (HOLD_NAME) and folders that are such themselves, one hold
1237
+ * at least: one a bubblewrap plan made for a placeholder, of this ZTC or another, or of one that ended without the step
1238
+ * after its command, that nothing has been put in since. It is the plan's to stand its placeholder on, or to make, again
1239
+ * (placeholderPlan), not a denied folder of the person's to hide with a writable empty folder over it. One the person has
1240
+ * since made a file of, while a command whose plan stood one there still ran, is theirs, and hidden as a file is: an
1241
+ * empty folder bwrap mounted over it would start no command (the recheck of the follow-ups).
1242
+ */
1243
+ function heldByPlans(path, depth = 0) {
1244
+ let entries;
1245
+ try {
1246
+ if (!lstatSync(path).isDirectory())
1247
+ return false;
1248
+ entries = readdirSync(path, { withFileTypes: true });
1249
+ }
1250
+ catch {
1251
+ return false;
1252
+ }
1253
+ return entries.length > 0 && entries.every(entry => entry.isDirectory()
1254
+ && (HOLD_NAME.test(entry.name) || (depth < 32 && heldByPlans(join(path, entry.name), depth + 1))));
1255
+ }
888
1256
  /**
889
1257
  * Where bwrap is to stand an empty read-only folder over each of HIDDEN, the paths a command under the plan must not reach,
890
1258
  * that doesn't exist yet (or is only the folder another plan's placeholder stands on) where the command could make it: in
891
1259
  * one of the roots it writes (WRITABLE), through no link below that root, under no mount the plan puts over the roots
892
- * (MOUNTED: read-only, or emptied), in no other placeholder, and in a folder the person may write, since bwrap makes the
893
- * folder a placeholder stands on as the person and otherwise starts no command at all. bwrap hides a path that exists by
894
- * a mount over it, and a missing path has nothing for one to stand on, so a command made a denied .env, or
895
- * .github/workflows, and wrote in it (the reviewer's re-verify, R3). As named and by where the part that exists leads, as
896
- * Seatbelt's rules name a denial (seatbeltRoots). Each stands at the path itself, and each folder above it that doesn't
897
- * exist either (.github, for a .github/workflows whose .github doesn't exist), its ANCESTORS, outermost first, bwrap
898
- * makes before (`--dir`) and pins (hiddenPathPins), so no command renames one away and makes the denied path anew (the
899
- * reviewer's follow-up review, N1), and what the profile doesn't deny in it stays the command's to write: a placeholder
900
- * at the outermost one froze all of it, .github/dependabot.yml and a build's dist/bundle.js beside a denied
901
- * dist/secret.key (the review of fix/sandbox-ancestor-pins, MISSING-ANCESTOR-ORDINARY-WORK). Each with the folders bwrap
902
- * makes for it on the host (MADE: the path and its ancestors), for the step after the command to remove
903
- * (placeholderRelease); an ancestor another plan of this process made and still holds is this plan's too.
1260
+ * (MOUNTED: read-only, or emptied), in no other placeholder, and in a folder the person may write, where ZTC, outside any
1261
+ * namespace, makes the folders above it. A folder of the person's they may not write gets none, though a command that
1262
+ * changes its mode can then make the denied path in it, and bwrap could have stood one there (the final review of
1263
+ * cd9cce92dcd, R9-3: open, and among the README's Limits). bwrap hides a path that exists by a mount over it, and a
1264
+ * missing path has nothing for one to stand on, so a command made a denied .env, or .github/workflows, and wrote in it
1265
+ * (the reviewer's re-verify, R3). As named and by where the part that exists leads, as Seatbelt's rules name a denial
1266
+ * (seatbeltRoots). Each stands at the path itself, and each folder above it that doesn't exist either (.github, for a
1267
+ * .github/workflows whose .github doesn't exist), its ANCESTORS, outermost first, ZTC makes on the host before it starts
1268
+ * bwrap (holdPlaceholderFolders) and bwrap pins (hiddenPathPins), so no command renames one away and makes the denied
1269
+ * path anew (the reviewer's follow-up review, N1), and what the profile doesn't deny in it stays the command's to write:
1270
+ * a placeholder at the outermost one froze all of it, .github/dependabot.yml and a build's dist/bundle.js beside a denied
1271
+ * dist/secret.key (the review of fix/sandbox-ancestor-pins, MISSING-ANCESTOR-ORDINARY-WORK). Each with the folders made
1272
+ * for it on the host (MADE: the path, which ZTC makes with a hold of the plan's in it, and its ancestors), for the step
1273
+ * after the command to remove (bubblewrapRelease); a path, or an ancestor, that another plan, of this ZTC or another,
1274
+ * made and still holds (heldByPlans) is this plan's too. A path in such a root that ZTC can't look for (lstat's error is none of ENOENT, ENOTDIR and
1275
+ * ENAMETOOLONG, which say nothing is there), as below a folder a command took the search permission from
1276
+ * (`chmod 600 a`), refuses the plan, naming that folder (hiddenPathLookupRefusal): ZTC took the folder for one that
1277
+ * doesn't exist yet, and its refusal said to make it (the review of fix/r9-release-blockers, RV-6).
904
1278
  */
905
1279
  function placeholderPlan(hidden, writable, mounted) {
906
1280
  const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
@@ -911,7 +1285,31 @@ function placeholderPlan(hidden, writable, mounted) {
911
1285
  catch {
912
1286
  return false;
913
1287
  } };
914
- const ours = (path) => !exists(path) || heldPlaceholder(path);
1288
+ const ours = (path) => !exists(path) || heldByPlans(path);
1289
+ /** As ours, for PATH in ROOT, a root the command writes, where a path ZTC can't look for refuses the plan. */
1290
+ const oursIn = (path, root) => {
1291
+ try {
1292
+ lstatSync(path);
1293
+ }
1294
+ catch (error) {
1295
+ const code = error.code ?? String(error);
1296
+ if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ENAMETOOLONG')
1297
+ return true;
1298
+ // The deepest folder from the root down that ZTC can look into, and not into what is below it.
1299
+ let folder = root;
1300
+ for (const part of relative(root, path).split(sep)) {
1301
+ try {
1302
+ lstatSync(join(folder, part));
1303
+ }
1304
+ catch {
1305
+ break;
1306
+ }
1307
+ folder = join(folder, part);
1308
+ }
1309
+ throw new Error(hiddenPathLookupRefusal(path, folder, code));
1310
+ }
1311
+ return heldByPlans(path);
1312
+ };
915
1313
  const real = (path) => { try {
916
1314
  return realpathSync(path);
917
1315
  }
@@ -926,35 +1324,44 @@ function placeholderPlan(hidden, writable, mounted) {
926
1324
  } })));
927
1325
  const candidates = [];
928
1326
  for (const path of spellings) {
929
- const root = writable.find(candidate => inside(path, candidate) && path !== candidate);
930
- if (root === undefined || !ours(path) || mounted.some(mount => inside(path, mount)))
1327
+ // The root to stand it in: one the command writes that holds it and is there. A root the profile names may not exist
1328
+ // yet (`./build` before a build makes it), bound only if it is there as bwrap starts; taking one named before the root
1329
+ // that holds it, the plan stood no placeholder, and a command made the root's folder through that root's bind and
1330
+ // wrote the denied path in it (the repair's focused mutation run, after RV-8).
1331
+ const root = writable.find(candidate => inside(path, candidate) && path !== candidate && real(candidate) !== undefined);
1332
+ if (root === undefined || mounted.some(mount => inside(path, mount)) || !oursIn(path, root))
931
1333
  continue;
932
1334
  const ancestors = [];
933
1335
  let holder = dirname(path);
934
- while (holder !== root && ours(holder)) {
1336
+ while (holder !== root && oursIn(holder, root)) {
935
1337
  ancestors.unshift(holder);
936
1338
  holder = dirname(holder);
937
1339
  }
938
- // The folder bwrap makes the rest in: a folder the root's bind holds at the same path, reached through no link.
1340
+ // The folder the rest is made in: a folder the root's bind holds at the same path, reached through no link, which the
1341
+ // person may write where something is still to be made in it. A folder another plan holds (heldByPlans) is there
1342
+ // already, and a plan stands its placeholder there, and holds it, though a command took the write permission from
1343
+ // the folder above it (`chmod 555 .github`): one that hid it by no mount left the denied path in the command's reach.
939
1344
  const realRoot = real(root);
940
1345
  if (realRoot === undefined || real(holder) !== join(realRoot, relative(root, holder)))
941
1346
  continue;
942
1347
  try {
943
1348
  if (!statSync(holder).isDirectory())
944
1349
  continue;
945
- accessSync(holder, constants.W_OK);
1350
+ if (!exists(ancestors[0] ?? path))
1351
+ accessSync(holder, constants.W_OK);
946
1352
  }
947
1353
  catch {
948
1354
  continue;
949
1355
  }
950
- candidates.push({ path, ancestors });
1356
+ // Where each folder ZTC makes for it is to be by its real path, which madeFolderError holds it to.
1357
+ candidates.push({ path, ancestors, physical: [path, ...ancestors].map(folder => [folder, join(realRoot, relative(root, folder))]) });
951
1358
  }
952
1359
  const chosen = [];
953
1360
  // The shallowest first, so one in another placeholder is left out: bwrap could make no folder in a read-only one.
954
- for (const { path, ancestors } of candidates.sort((a, b) => a.path.length - b.path.length)) {
1361
+ for (const { path, ancestors, physical } of candidates.sort((a, b) => a.path.length - b.path.length)) {
955
1362
  if (chosen.some(placeholder => inside(path, placeholder.path)))
956
1363
  continue;
957
- chosen.push({ path, ancestors, made: [path, ...ancestors] });
1364
+ chosen.push({ path, ancestors, made: [path, ...ancestors], physical });
958
1365
  }
959
1366
  return chosen;
960
1367
  }
@@ -1064,9 +1471,12 @@ function removableLinkOnPath(path, writable) {
1064
1471
  * path or under the link's new name; a denial that was itself a link fell the same way; and with ZTC_CONFIG_DIR named
1065
1472
  * through such a link, a command put a folder of its own in the link's place and wrote the config.json ZTC reads there
1066
1473
  * (the review of fix/sandbox-ancestor-pins, LINK-DENIAL-NEXT-READ). Seatbelt denies the link itself as a literal path, so
1067
- * it holds there (seatbeltAncestorPins).
1474
+ * it holds there (seatbeltAncestorPins). Where LINK is that of LINKED, a root the profile names that is itself refused for
1475
+ * being, or being named through, such a link (profileRootLooks), the refusal says so first: it told the person to name
1476
+ * the denial by the real path of wherever a command had pointed that link (the review of fix/r9-release-blockers'
1477
+ * repair, R9C-TRUTH-9).
1068
1478
  */
1069
- function hiddenPathLinkRefusal(path, link, entry) {
1479
+ function hiddenPathLinkRefusal(path, link, entry, linked) {
1070
1480
  let real = path;
1071
1481
  try {
1072
1482
  real = canonicalPath(path);
@@ -1074,6 +1484,12 @@ function hiddenPathLinkRefusal(path, link, entry) {
1074
1484
  catch { /* as named */ }
1075
1485
  const through = `named through a link in a folder the command may write (${link}). bubblewrap hides a path by a mount, which `
1076
1486
  + 'stands where a link leads and never on the link itself, so a command could remove or rename the link';
1487
+ if (entry !== undefined && linked !== undefined) {
1488
+ return `ZTC did not start this command: its permission profile denies ${entry} (${path}), named through ${link}, and names ${linked.root} `
1489
+ + `as a root, which ${linked.link === linked.root ? 'is' : `is named through ${linked.link},`} a link in a folder a command may write, `
1490
+ + `which a command could have made, to ${linked.leads}. Remove the link, or name that root and the denial by their real paths `
1491
+ + 'in the profile\'s allowedPaths and deniedPaths.';
1492
+ }
1077
1493
  if (entry !== undefined) {
1078
1494
  return `ZTC did not start this command: its permission profile denies ${entry} (${path}), ${through}, and the next command `
1079
1495
  + `would see what the denial hides at its real path. Name the denial by its real path (${real}) in the profile's deniedPaths.`;
@@ -1088,9 +1504,330 @@ function holdPlaceholders(made) {
1088
1504
  placeholderHolds.set(path, (placeholderHolds.get(path) ?? 0) + 1);
1089
1505
  }
1090
1506
  /**
1091
- * The step after a command whose plan stood placeholders on MADE, once only: each folder no other plan still holds is
1092
- * removed, the deepest first, if nothing is in it (rmdir removes only an empty folder), so the host keeps nothing of
1093
- * them; one something was put in while the command ran is the person's, and stays.
1507
+ * What a plan says, refused, where ZTC can't tell whether PATH, which it hides in a root the command writes, is there,
1508
+ * since it can't look into FOLDER, a folder above it that is there (CODE: lstat's error, EACCES where a command took the
1509
+ * folder's search permission): it could stand no placeholder at the path, nor pin the folders above it (placeholderPlan).
1510
+ */
1511
+ function hiddenPathLookupRefusal(path, folder, code) {
1512
+ return 'ZTC did not start this command: bubblewrap hides what its permission profile denies, and ZTC\'s own state, by a mount at '
1513
+ + `each path, and ZTC can't look into ${folder} (${code}) to find ${path}, which it hides there. The folder is there: give it `
1514
+ + `back its mode (chmod u+x ${folder}).`;
1515
+ }
1516
+ /**
1517
+ * What stands in the way of ZTC's mkdir of FOLDER, which failed with CODE, and what to do about it: for ENOTDIR the file
1518
+ * that stands where a folder above it would be, to move or remove; for EACCES (or EPERM) the deepest folder above it that
1519
+ * is there, whose write and search permission to give back; for EEXIST what stands at FOLDER itself. "Make the folder, or
1520
+ * remove what stands at that path" named neither (the review of fix/r9-release-blockers' repair, R9C-TRUTH-8).
1521
+ */
1522
+ function madeFolderAdvice(folder, code) {
1523
+ if (code === 'ENOTDIR') {
1524
+ for (let above = dirname(folder); above !== dirname(above); above = dirname(above)) {
1525
+ try {
1526
+ if (!lstatSync(above).isDirectory())
1527
+ return `A file stands at ${above}, where a folder above it would be: move or remove the file.`;
1528
+ }
1529
+ catch { /* not there either: further up */ }
1530
+ }
1531
+ }
1532
+ if (code === 'EACCES' || code === 'EPERM') {
1533
+ let above = dirname(folder);
1534
+ for (; above !== dirname(above); above = dirname(above)) {
1535
+ try {
1536
+ lstatSync(above);
1537
+ break;
1538
+ }
1539
+ catch { /* further up */ }
1540
+ }
1541
+ return `ZTC may not make a folder in ${above}: give it back its write and search permission (chmod u+wx ${above}).`;
1542
+ }
1543
+ if (code === 'EEXIST')
1544
+ return `Something that is no folder stands at ${folder}: move or remove it.`;
1545
+ if (code === 'ENAMETOOLONG')
1546
+ return 'A name on the way to it is longer than the filesystem allows: name a shorter path in the profile\'s deniedPaths.';
1547
+ return 'Make the folder, or remove what stands at that path.';
1548
+ }
1549
+ /** What a plan says, refused, where ZTC could not make FOLDER, above what it hides, for bwrap to pin (CODE: the error's). */
1550
+ function madeAncestorRefusal(folder, code) {
1551
+ return `ZTC did not start this command: bubblewrap pins each folder above what its permission profile denies, and ZTC's `
1552
+ + `own state, and ZTC could not make ${folder}, one that doesn't exist yet (${code}), for it to pin. ${madeFolderAdvice(folder, code)}`;
1553
+ }
1554
+ /** What a plan says, refused, where ZTC could not make FOLDER, one of its placeholders stands on, and hold it (CODE: the error's). */
1555
+ function placeholderFolderRefusal(folder, code) {
1556
+ return 'ZTC did not start this command: bubblewrap stands an empty read-only folder over each path its permission profile '
1557
+ + `denies, and ZTC's own state, that doesn't exist yet, and ZTC could not make and hold the folder it stands on, ${folder} (${code}). `
1558
+ + madeFolderAdvice(folder, code);
1559
+ }
1560
+ /**
1561
+ * What a plan says, refused, where FOLDER, which ZTC makes for it on the host (a folder above a denial, one a placeholder
1562
+ * stands on, or a hold), or the folder that holds it, is not where the plan found it by its real path (PHYSICAL, the real
1563
+ * path FOLDER is to have): a folder on the way to it is a link, or became one while ZTC made it (madeFolderError). It says
1564
+ * where FOLDER led when ZTC looked again: it named the plan's path twice, "X … is not where the plan found it (X)" (the
1565
+ * review of fix/r9-release-blockers' repair, R9C-TRUTH-9).
1566
+ */
1567
+ function madeFolderLinkRefusal(folder, physical) {
1568
+ let now;
1569
+ try {
1570
+ now = realpathSync(folder);
1571
+ }
1572
+ catch {
1573
+ try {
1574
+ now = join(realpathSync(dirname(folder)), basename(folder));
1575
+ }
1576
+ catch { /* gone */ }
1577
+ }
1578
+ const made = folder === physical ? folder : `${folder} (by its real path, ${physical})`;
1579
+ const found = now === undefined || now === physical ? 'it wasn\'t there when ZTC looked again' : `it led to ${now} when ZTC looked again`;
1580
+ return `ZTC did not start this command: ZTC makes ${made} for it on the host, where the plan found it, and ${found}: a folder on the `
1581
+ + 'way to it is a link, or became one while ZTC made it, and ZTC makes nothing through a link. Run the command again once nothing '
1582
+ + 'alongside moves the folders in its roots.';
1583
+ }
1584
+ /**
1585
+ * Makes FOLDER on the host, as the person, where none is, there by its real path PHYSICAL (in a root the command writes,
1586
+ * through no link below it, as the plan found it): undefined where it is made, or a folder is there already at PHYSICAL
1587
+ * (another plan's, or this one's by another spelling), MADE then knowing which folder it is; else why not: lstat's or
1588
+ * mkdir's error code, EEXIST where something that is no folder stands there, or ELINK where the folder that holds it isn't
1589
+ * at PHYSICAL's folder, or the folder at FOLDER isn't at PHYSICAL, by their real paths: a folder on the way to it is a
1590
+ * link, or became one while ZTC made it (a command running alongside, whose plan pins nothing there, can swap one in;
1591
+ * RV-7's shape). ZTC makes nothing through such a link: it looks at the folder that holds FOLDER before its mkdir, and at
1592
+ * FOLDER after it, and removes a folder it made that isn't at PHYSICAL, where it is still the one its mkdir made (by its
1593
+ * device and inode). Both are by path, so a link swapped in for the moment between ZTC's look at the folder that holds
1594
+ * FOLDER and its mkdir, and gone again before its look after it, leaves an empty folder where the link led, outside the
1595
+ * roots, which ZTC can't see again; the plan is then refused, and nothing is bound there.
1596
+ */
1597
+ function madeFolderError(folder, physical, made) {
1598
+ const real = (path) => { try {
1599
+ return realpathSync(path);
1600
+ }
1601
+ catch {
1602
+ return undefined;
1603
+ } };
1604
+ if (real(dirname(folder)) !== dirname(physical)) {
1605
+ try {
1606
+ lstatSync(dirname(folder));
1607
+ }
1608
+ catch (error) {
1609
+ return error.code ?? String(error);
1610
+ }
1611
+ return 'ELINK';
1612
+ }
1613
+ let ours = false;
1614
+ try {
1615
+ mkdirSync(folder);
1616
+ ours = true;
1617
+ }
1618
+ catch (error) {
1619
+ const code = error.code ?? String(error);
1620
+ if (code !== 'EEXIST')
1621
+ return code;
1622
+ }
1623
+ let info;
1624
+ try {
1625
+ info = lstatSync(folder);
1626
+ }
1627
+ catch (error) {
1628
+ return error.code ?? String(error);
1629
+ }
1630
+ if (info.isDirectory() && real(folder) === physical) {
1631
+ made.set(folder, { dev: info.dev, ino: info.ino, physical });
1632
+ return undefined;
1633
+ }
1634
+ // Made through a link: removed, where the folder there is still the one this mkdir made.
1635
+ if (ours && info.isDirectory()) {
1636
+ try {
1637
+ const again = lstatSync(folder);
1638
+ if (again.dev === info.dev && again.ino === info.ino)
1639
+ rmdirSync(folder);
1640
+ }
1641
+ catch { /* gone */ }
1642
+ }
1643
+ return info.isDirectory() || info.isSymbolicLink() ? 'ELINK' : 'EEXIST';
1644
+ }
1645
+ /** Whether PATH is still the folder MADE knows it by (madeFolderError): the same folder, at the real path it had. */
1646
+ function stillMade(path, made) {
1647
+ const folder = made.get(path);
1648
+ if (folder === undefined)
1649
+ return false;
1650
+ try {
1651
+ const info = lstatSync(path);
1652
+ return info.isDirectory() && info.dev === folder.dev && info.ino === folder.ino && realpathSync(path) === folder.physical;
1653
+ }
1654
+ catch {
1655
+ return false;
1656
+ }
1657
+ }
1658
+ /** The real path PHYSICAL gives FOLDER, or FOLDER's own where it gives none (a folder made by its real path). */
1659
+ const physicalOf = (physical, folder) => physical.get(folder) ?? folder;
1660
+ /**
1661
+ * Makes each of ANCESTORS (placeholderPlan's: the folders above a placeholder that don't exist yet, outermost first) on the
1662
+ * host, as the person, before bwrap starts: bwrap looks up the source of every bind before it applies any option, so the
1663
+ * plan's `--dir F --bind F F` stopped it ("Can't find source path"), and while one denial's folder above didn't exist no
1664
+ * command of the profile started, the person's own under ZTC_PERMISSION_PROFILE_PINNED included (the final review of
1665
+ * cd9cce92dcd, R9-2). ZTC makes them, as makeSeatbeltAncestors does for Seatbelt, rather than have bwrap bind them with
1666
+ * `--bind-try` after `--dir`, which skips a bind whose source isn't there by then and would start the command unpinned.
1667
+ * Each is made where placeholderPlan found the folder it lies in, through no link below its root, there by its real path
1668
+ * (PHYSICAL), into MADE (madeFolderError). A folder already there (one another plan, of this ZTC or another, made, and
1669
+ * still holds) is this plan's too; one ZTC can't make, where something that is no folder now stands, or where a folder on
1670
+ * the way is a link, refuses the plan, saying why. The step after the command removes each left empty (bubblewrapRelease),
1671
+ * as it removes a placeholder's.
1672
+ */
1673
+ function makeBubblewrapAncestors(ancestors, physical, made) {
1674
+ for (const folder of ancestors) {
1675
+ const code = madeFolderError(folder, physicalOf(physical, folder), made);
1676
+ if (code === 'ELINK')
1677
+ throw new Error(madeFolderLinkRefusal(folder, physicalOf(physical, folder)));
1678
+ if (code !== undefined)
1679
+ throw new Error(madeAncestorRefusal(folder, code));
1680
+ }
1681
+ }
1682
+ /**
1683
+ * Puts the plan's hold (NAME, HOLD_NAME) in FOLDER, a folder it made or took over at PHYSICAL (madeFolderError), into
1684
+ * HOLDS and MADE: undefined where it is there, or why not, as madeFolderError says it. One by the plan's own name already
1685
+ * there isn't the plan's, and refuses it (EEXIST).
1686
+ */
1687
+ function madeHoldError(folder, physical, name, holds, made) {
1688
+ const hold = join(folder, name);
1689
+ try {
1690
+ mkdirSync(hold);
1691
+ }
1692
+ catch (error) {
1693
+ return error.code ?? String(error);
1694
+ }
1695
+ holds.push(hold);
1696
+ let info;
1697
+ try {
1698
+ info = lstatSync(hold);
1699
+ }
1700
+ catch (error) {
1701
+ return error.code ?? String(error);
1702
+ }
1703
+ let at;
1704
+ try {
1705
+ at = realpathSync(hold);
1706
+ }
1707
+ catch { /* gone */ }
1708
+ if (info.isDirectory() && at === join(physical, name)) {
1709
+ made.set(hold, { dev: info.dev, ino: info.ino, physical: join(physical, name) });
1710
+ return undefined;
1711
+ }
1712
+ if (info.isDirectory()) {
1713
+ try {
1714
+ const again = lstatSync(hold);
1715
+ if (again.dev === info.dev && again.ino === info.ino)
1716
+ rmdirSync(hold);
1717
+ }
1718
+ catch { /* gone */ }
1719
+ }
1720
+ return 'ELINK';
1721
+ }
1722
+ /** The name of the hold a bubblewrap plan of this process puts in each folder it stands on (HOLD_NAME), new for each plan. */
1723
+ function bubblewrapHoldName() {
1724
+ return `.ztc-hold-${HOLD_NAMESPACE}-${process.pid}-${randomUUID().replace(/-/g, '')}`;
1725
+ }
1726
+ /**
1727
+ * Makes what a bubblewrap plan stands on, on the host, as the person, before bwrap starts: each of ANCESTORS, the folders
1728
+ * above its placeholders that don't exist yet (makeBubblewrapAncestors), then each of FOLDERS, those its placeholders
1729
+ * stand on, each with the plan's hold in it (NAME, HOLD_NAME), whose paths go into HOLDS as they are made; each by the
1730
+ * real path PHYSICAL gives it (madeFolderError), into MADE. bwrap made a placeholder's folder as it mounted the placeholder
1731
+ * there, so the plan could put no hold in it before the mount stood. A folder already there, another plan's, is this
1732
+ * plan's too. Each folder on the host is held once (HELD, by device and inode), however many of FOLDERS name it: under a root named through a link, two roots that name one folder, or a root that links
1733
+ * into another, a placeholder stands at each spelling a root's bind shows the path by, each a mount of its own, on one
1734
+ * folder, and the plan's second hold there, by its one name, failed (EEXIST), so every command of the profile was refused
1735
+ * (the review of fix/r9-release-blockers, LINKROOT-EEXIST). One ZTC can't make or hold, where something that is no folder
1736
+ * now stands, where a hold by the plan's own name is there already and isn't the plan's, or where a folder on the way is
1737
+ * a link, refuses the plan, saying why; its caller releases what was made (bubblewrapRelease).
1738
+ */
1739
+ function holdPlaceholderFolders(ancestors, folders, holds, physical, made, name, held) {
1740
+ makeBubblewrapAncestors(ancestors, physical, made);
1741
+ for (const folder of folders) {
1742
+ const at = physicalOf(physical, folder);
1743
+ let code = madeFolderError(folder, at, made);
1744
+ if (code === undefined) {
1745
+ const { dev, ino } = made.get(folder);
1746
+ if (!held.has(`${dev}:${ino}`)) {
1747
+ code = madeHoldError(folder, at, name, holds, made);
1748
+ if (code === undefined)
1749
+ held.add(`${dev}:${ino}`);
1750
+ }
1751
+ }
1752
+ if (code === 'ELINK')
1753
+ throw new Error(madeFolderLinkRefusal(folder, at));
1754
+ if (code !== undefined)
1755
+ throw new Error(placeholderFolderRefusal(folder, code));
1756
+ }
1757
+ }
1758
+ /**
1759
+ * The step after a bubblewrap command, once only, whose plan made MADE (placeholderPlan: FOLDERS, those its placeholders
1760
+ * stand on, and the folders above them) and put HOLDS in FOLDERS: its holds are removed, and in each of FOLDERS the hold of any plan whose process has ended (holdLive); then
1761
+ * each of MADE, the deepest first, if nothing is in it (rmdir removes only an empty folder), so the host keeps nothing of
1762
+ * them. One another plan still holds, of this ZTC or another, stays for the last of them to remove, and one something was
1763
+ * put in while the command ran is the person's, and stays. A folder of MADE whose mode the command took through its pin
1764
+ * (`chmod 555 .github`, or 000) is first given its owner's write and search back, outermost first, so what was made in
1765
+ * it, and it, can be removed, and one that stays stays writable to the person, where the next plan stands its
1766
+ * placeholder: the step after the command couldn't remove the placeholder's folder in it (EACCES), which stayed on the
1767
+ * host with it (the review of fix/r9-release-blockers, RV-3). It acts only on a folder, or a hold, that is still the one
1768
+ * the plan made, or took over (KNOWN, madeFolderError: by its device and inode, at the real path it had): by path, it
1769
+ * followed a link a command running alongside swapped in for a folder above one, and gave a folder outside every root
1770
+ * its owner's write, or removed an empty one (RELEASE-LINK).
1771
+ */
1772
+ function bubblewrapRelease(made, folders, holds, known) {
1773
+ let released = false;
1774
+ return () => {
1775
+ if (released)
1776
+ return;
1777
+ released = true;
1778
+ for (const path of [...made].sort((a, b) => a.length - b.length)) {
1779
+ if (!stillMade(path, known))
1780
+ continue;
1781
+ try {
1782
+ const info = lstatSync(path);
1783
+ if ((info.mode & 0o300) !== 0o300)
1784
+ chmodSync(path, (info.mode & 0o7777) | 0o300);
1785
+ }
1786
+ catch { /* gone */ }
1787
+ }
1788
+ for (const hold of holds) {
1789
+ if (stillMade(hold, known)) {
1790
+ try {
1791
+ rmdirSync(hold);
1792
+ }
1793
+ catch { /* gone */ }
1794
+ }
1795
+ }
1796
+ for (const folder of folders) {
1797
+ if (!stillMade(folder, known))
1798
+ continue;
1799
+ let names = [];
1800
+ try {
1801
+ names = readdirSync(folder);
1802
+ }
1803
+ catch { /* gone, or no folder now */ }
1804
+ for (const name of names) {
1805
+ if (HOLD_NAME.test(name) && !holdLive(name)) {
1806
+ try {
1807
+ rmdirSync(join(folder, name));
1808
+ }
1809
+ catch { /* gone */ }
1810
+ }
1811
+ }
1812
+ }
1813
+ for (const path of [...made].sort((a, b) => b.length - a.length)) {
1814
+ if (stillMade(path, known)) {
1815
+ try {
1816
+ rmdirSync(path);
1817
+ }
1818
+ catch { /* held, or something is in it */ }
1819
+ }
1820
+ }
1821
+ };
1822
+ }
1823
+ /**
1824
+ * The step after a Seatbelt command whose plan made MADE (makeSeatbeltAncestors), once only: each folder no other plan of
1825
+ * this process still holds is removed, the deepest first, if nothing is in it (rmdir removes only an empty folder), so
1826
+ * the host keeps nothing of them; one something was put in while the command ran is the person's, and stays. It acts only
1827
+ * on a folder that is still the one made (seatbeltMadeFolders: its device and inode at the real path it had), as
1828
+ * bubblewrap's does (bubblewrapRelease): by path, it followed a link swapped in for a folder above one while the command
1829
+ * ran, and removed an empty folder outside every root where the link led (the review of fix/r9-release-blockers' repair,
1830
+ * R9C-TRUTH-7).
1094
1831
  */
1095
1832
  function placeholderRelease(made) {
1096
1833
  let released = false;
@@ -1105,10 +1842,13 @@ function placeholderRelease(made) {
1105
1842
  continue;
1106
1843
  }
1107
1844
  placeholderHolds.delete(path);
1108
- try {
1109
- rmdirSync(path);
1845
+ if (stillMade(path, seatbeltMadeFolders)) {
1846
+ try {
1847
+ rmdirSync(path);
1848
+ }
1849
+ catch { /* something is in it, or it is gone */ }
1110
1850
  }
1111
- catch { /* something is in it, or it is gone */ }
1851
+ seatbeltMadeFolders.delete(path);
1112
1852
  }
1113
1853
  };
1114
1854
  }
@@ -1187,79 +1927,102 @@ seccompFd, plan = {}) {
1187
1927
  }
1188
1928
  }
1189
1929
  // The project and what git reads, bound again over the private folders above where they lie under one. The profile's
1190
- // relative roots are the session's folder's, wherever the command runs (allowedRoots).
1930
+ // relative roots are the session's folder's, wherever the command runs (allowedRoots), each as one look at it found it
1931
+ // (LOOKS, profileRootLooks): the plan resolves no root again.
1191
1932
  const rootsCwd = plan.sessionCwd ?? cwd;
1933
+ const looks = plan.rootLooks ?? profileRootLooks(profile, rootsCwd);
1192
1934
  // Whether a filter refuses the command Unix sockets: a profile without network, whose caller gave bwrap the filter.
1193
1935
  const filtered = seccompFd !== undefined && !profileAllowsNetwork(profile);
1194
1936
  // Where none does, no root is bound that would put the host's services' sockets in its reach (hostSocketRootRefusal):
1195
1937
  // the command doesn't start, and says why.
1196
1938
  if (!filtered) {
1197
- const refusal = hostSocketRootRefusal(profile, cwd, rootsCwd, env, plan.sessionCwd);
1939
+ const refusal = hostSocketRootRefusal(profile, cwd, rootsCwd, env, plan.sessionCwd, looks);
1198
1940
  if (refusal !== undefined)
1199
1941
  throw new Error(refusal);
1200
1942
  }
1201
1943
  // The files the command may also read (a hook's own program and script), bound read-only below.
1202
1944
  const readPaths = everywhere ? [] : (plan.readPaths ?? []).filter(path => isAbsolute(path) && existsSync(path));
1203
1945
  const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
1204
- // Each root as named and by its real path, as Seatbelt's rules name it (seatbeltRoots). bwrap binds a path as it is
1205
- // spelled, so a root named through a link was bound by the link's spelling alone: a command whose working directory was
1206
- // its real path (Linux's process.cwd() always is) wrote nothing there, and what the plan hid or held read-only by its
1207
- // real path inside the root stayed in reach through the link's spelling (the reviewer's re-verify, R7). RELINKED pairs
1208
- // each such root with its real path; SHOWN_AT gives a path at each spelling a root's bind shows it by.
1209
- const roots = allowedRoots(profile, cwd, rootsCwd);
1210
- const relinked = roots.flatMap(root => {
1211
- try {
1212
- const real = realpathSync(root);
1213
- return real === root ? [] : [[root, real]];
1214
- }
1215
- catch {
1216
- return [];
1217
- }
1218
- });
1946
+ const found = commandRoots(profile, cwd, looks);
1947
+ const roots = found.map(({ root }) => root);
1948
+ // A root inside another root, by the real paths the look found (`./build` in allowedPaths [., ./build]), is that root's:
1949
+ // bwrap binds none of its own, so what the command may do there is what it may do in the root that holds it. Its bind
1950
+ // was resolved again as bwrap started, by its path, so a command left running in the background that renamed a folder
1951
+ // above it, which nothing pinned, or swapped one for a link, had bwrap bind a folder outside every root there, and a
1952
+ // root not made yet that ZTC made and held for its bind showed the command its hold, kept `mkdir build`, `git clone x
1953
+ // build` and `[ -e build ]` from working as they did, and stopped every command of the profile below a folder ZTC
1954
+ // couldn't write (the review of fix/r9-release-blockers' repair, R9C-ESCAPE-2, R9C-REGRESSION-1 to 3). A command that
1955
+ // makes such a root a link makes it no root (profileRootLooks), so neither the policy nor a later plan follows the link.
1956
+ const outer = found.filter(({ real }) => !found.some(other => other.real !== real && inside(real, other.real)));
1957
+ // Each root bound as named and by its real path, as Seatbelt's rules name it. bwrap binds a path as it is spelled, so a
1958
+ // root named through a link was bound by the link's spelling alone: a command whose working directory was its real path
1959
+ // (Linux's process.cwd() always is) wrote nothing there, and what the plan hid or held read-only by its real path inside
1960
+ // the root stayed in reach through the link's spelling (the reviewer's re-verify, R7). RELINKED pairs each such root with
1961
+ // its real path; SHOWN_AT gives a path at each spelling a root's bind shows it by.
1962
+ const relinked = outer.flatMap(({ root, real }) => real === root ? [] : [[root, real]]);
1219
1963
  const shownAt = (path) => [path, ...relinked.flatMap(([named, real]) => inside(path, real) && !inside(path, named)
1220
1964
  ? [`${named}${path.slice(real.length)}`] : inside(path, named) && !inside(path, real) ? [`${real}${path.slice(named.length)}`] : [])];
1221
- const rootBinds = Array.from(new Set([...roots, ...relinked.map(([, real]) => real)]));
1222
- const bound = [...(everywhere ? [] : BUBBLEWRAP_SYSTEM_READ_ROOTS.filter(root => existsSync(root))), ...rootBinds,
1223
- ...(profileAllowsFileWrite(profile) ? [] : gitReadRoots(cwd)), ...readPaths];
1965
+ // Outermost first, as the plan's pins are.
1966
+ const rootBinds = Array.from(new Set([...outer.map(({ root }) => root), ...relinked.map(([, real]) => real)])).map((root, order) => ({ root, order }))
1967
+ .sort((a, b) => a.root.split(sep).length - b.root.split(sep).length || a.order - b.order).map(({ root }) => root);
1968
+ const missingAt = new Map(outer.flatMap(({ root, real, missing }) => missing === undefined ? [] : [[root, missing], [real, missing]]));
1969
+ // What git reads outside the roots, under a profile that writes nothing: none a root holds (gitReadRoots).
1970
+ const gitReads = profileAllowsFileWrite(profile) ? [] : gitReadRoots(cwd, found.map(({ real }) => real));
1971
+ const bound = [...(everywhere ? [] : BUBBLEWRAP_SYSTEM_READ_ROOTS.filter(root => existsSync(root))), ...rootBinds, ...gitReads, ...readPaths];
1224
1972
  // bwrap starts the command only in a folder its new root holds. A folder named through a link into a bound root (the
1225
- // workspace by another name) is entered by its real path. One no bind holds, which a profile that doesn't require the
1226
- // sandbox lets a command run in (the policy refuses it otherwise), is bound read-only where a filter keeps the command
1227
- // from Unix sockets, as Seatbelt lets a command read the folder it runs in, before the roots, so one it holds stays
1228
- // writable: since a profile's relative roots are the session's folder's, nothing bound it, and the command didn't start
1229
- // (the reviewer's bwrap argv probe, 2026-11-22). Where none does, a read-only bind would put a host service's socket in
1230
- // it in the command's reach, so the command doesn't start, and says why (outsideRootsRefusal). A profile that reads
1231
- // everywhere binds its folder as its root (allowedRoots). A folder where the host's services keep their sockets, or /
1232
- // that holds them, is never bound so: the command doesn't start, and says why (hostSocketFolderRefusal).
1973
+ // workspace by another name) is entered by its real path, as one look at it found it. One no bind holds, which a profile
1974
+ // that doesn't require the sandbox lets a command run in (the policy refuses it otherwise), is bound read-only where a
1975
+ // filter keeps the command from Unix sockets, as Seatbelt lets a command read the folder it runs in, before the roots, so
1976
+ // one it holds stays writable: since a profile's relative roots are the session's folder's, nothing bound it, and the
1977
+ // command didn't start (the reviewer's bwrap argv probe, 2026-11-22); but not one named through a link in a root, which a
1978
+ // command could have made, or swapped in after the policy's check (R9C-ESCAPE-4), so no folder outside the roots is bound
1979
+ // through it. Where no filter does, a read-only bind would put a host service's socket in it in the command's reach, so
1980
+ // the command doesn't start, and says why (outsideRootsRefusal). A profile that reads everywhere binds its folder as its
1981
+ // root (allowedRoots). A folder where the host's services keep their sockets, or / that holds them, is never bound so:
1982
+ // the command doesn't start, and says why (hostSocketFolderRefusal).
1233
1983
  let chdir = cwd;
1234
1984
  if (!bound.some(root => inside(cwd, root))) {
1235
- let real;
1236
- try {
1237
- real = realpathSync(cwd);
1238
- }
1239
- catch { /* bwrap says it can't enter it */ }
1985
+ const look = lookAtRoot(resolve(cwd));
1986
+ const real = 'real' in look && look.missing === undefined ? look.real : undefined;
1987
+ const reals = found.map(({ real: folder }) => sameFileKey(folder));
1988
+ const linked = 'real' in look && look.links.some(({ holder }) => reals.some(folder => inside(sameFileKey(holder), folder)));
1240
1989
  if (real !== undefined && bound.some(root => inside(real, root)))
1241
1990
  chdir = real;
1242
1991
  else {
1243
1992
  const sessionHeld = bound.some(root => inside(rootsCwd, root)) ? rootsCwd : undefined;
1244
- const refusal = hostSocketFolderRefusal(cwd, real, env, allowedRoots(profile, cwd, rootsCwd), sessionHeld);
1993
+ const refusal = hostSocketFolderRefusal(cwd, real, env, roots, sessionHeld);
1245
1994
  if (refusal !== undefined)
1246
1995
  throw new Error(refusal);
1247
- if (!filtered)
1248
- throw new Error(outsideRootsRefusal(cwd, allowedRoots(profile, cwd, rootsCwd), sessionHeld, profileAllowsNetwork(profile)));
1996
+ if (!filtered || linked)
1997
+ throw new Error(outsideRootsRefusal(cwd, roots, sessionHeld, profileAllowsNetwork(profile), linked));
1249
1998
  if (real !== undefined) {
1250
1999
  args.push('--ro-bind', cwd, cwd);
1251
2000
  bound.push(cwd);
1252
2001
  }
1253
2002
  }
1254
2003
  }
2004
+ // A root that doesn't exist yet (`./build` before a build makes it), outside every other root (a root inside one is that
2005
+ // root's, above), is bound only if it is there when bwrap starts (`--bind-try`, which bwrap skips where its source doesn't
2006
+ // exist): bwrap looks up the source of every bind before it applies any option, so a plain bind of it stopped bwrap
2007
+ // ("Can't find source path"), and every command of the profile failed until the folder existed (the review of
2008
+ // fix/r9-release-blockers, RV-8). But not one ZTC can't look up for another reason than its absence (a file where a
2009
+ // folder above it would be, ENOTDIR), which bwrap's lookup stops at as at a plain bind's (C-4), nor one the plan hides a
2010
+ // path in: bound as bwrap starts, that path, made since the plan, was in the command's reach unhidden (C-3). The next plan
2011
+ // binds such a root once it is there.
2012
+ const hiddenNames = [...deniedRoots(profile, rootsCwd), ...ownStateRoots(hideOwnState), ...(hideOwnState ? ztcRuntimeEntries() : [])];
1255
2013
  for (const root of rootBinds) {
1256
- args.push(profileAllowsFileWrite(profile) ? '--bind' : '--ro-bind', root, root);
2014
+ const writes = profileAllowsFileWrite(profile);
2015
+ const missing = missingAt.get(root);
2016
+ if (missing === undefined)
2017
+ args.push(writes ? '--bind' : '--ro-bind', root, root);
2018
+ else if (missing === 'ENOENT' && !hiddenNames.some(path => inside(path, root)))
2019
+ args.push(writes ? '--bind-try' : '--ro-bind-try', root, root);
1257
2020
  }
1258
2021
  const afterRoots = args.length;
1259
2022
  // Where the repositories the command may work in name the programs git starts, read-only inside the writable roots
1260
2023
  // though the command may commit (utils/git_program_files.ts): after the roots are bound, before anything is hidden.
1261
2024
  // Their pinned folders are bound with the folders above what the plan hides (below), in one list.
1262
- const programs = plan.gitPrograms !== undefined ? plan.gitPrograms : commandGitProgramFiles(profile, cwd, plan.sessionCwd);
2025
+ const programs = plan.gitPrograms !== undefined ? plan.gitPrograms : commandGitProgramFiles(profile, cwd, plan.sessionCwd, looks);
1263
2026
  const isFolder = (path) => { try {
1264
2027
  return lstatSync(path).isDirectory();
1265
2028
  }
@@ -1277,10 +2040,8 @@ seccompFd, plan = {}) {
1277
2040
  args.push(...bubblewrapGitProgramBinds({ ...programs, files: shown(programs.files), configs: shown(programs.configs),
1278
2041
  folders: shown(programs.folders), pinned: [] }));
1279
2042
  }
1280
- if (!profileAllowsFileWrite(profile)) {
1281
- for (const root of gitReadRoots(cwd))
1282
- args.push('--ro-bind', root, root);
1283
- }
2043
+ for (const root of gitReads)
2044
+ args.push('--ro-bind', root, root);
1284
2045
  // The files the command may also read (a hook's own program and script), read-only, after its roots and before
1285
2046
  // anything is hidden, so ZTC's own state stays hidden under them too; at each spelling a root's bind shows them by.
1286
2047
  for (const path of new Set(readPaths.flatMap(shownAt)))
@@ -1294,19 +2055,14 @@ seccompFd, plan = {}) {
1294
2055
  const hidden = [...deniedRoots(profile, rootsCwd), ...[...ownStateRoots(hideOwnState), ...(hideOwnState ? ztcRuntimeEntries() : [])].filter(seen)]
1295
2056
  .flatMap(shownAt);
1296
2057
  // A denial, or ZTC's own state, named through a link a command could remove: no mount holds the link, so the plan is
1297
- // refused before anything is hidden (hiddenPathLinkRefusal).
2058
+ // refused before anything is hidden (hiddenPathLinkRefusal), saying first where the link is a root's the profile names.
1298
2059
  if (profileAllowsFileWrite(profile)) {
1299
- const writableReal = Array.from(new Set(rootBinds.map(root => { try {
1300
- return realpathSync(root);
1301
- }
1302
- catch {
1303
- return root;
1304
- } })));
2060
+ const writableReal = Array.from(new Set(outer.map(({ real }) => real)));
1305
2061
  for (const entry of profile?.deniedPaths ?? []) {
1306
2062
  const path = normalizeRoot(entry, rootsCwd);
1307
2063
  const link = removableLinkOnPath(path, writableReal);
1308
2064
  if (link !== undefined)
1309
- throw new Error(hiddenPathLinkRefusal(path, link, entry));
2065
+ throw new Error(hiddenPathLinkRefusal(path, link, entry, looks.linked.find(linked => linked.link === link)));
1310
2066
  }
1311
2067
  for (const path of ownStateRoots(hideOwnState)) {
1312
2068
  const link = removableLinkOnPath(path, writableReal);
@@ -1317,9 +2073,11 @@ seccompFd, plan = {}) {
1317
2073
  const emptiedOwnState = [];
1318
2074
  /** The hidden paths that exist, each hidden by a mount at it. */
1319
2075
  const hiddenMounts = [];
2076
+ const writable = profileAllowsFileWrite(profile) ? rootBinds : [];
1320
2077
  for (const root of Array.from(new Set(hidden))) {
1321
- // Only the folder another plan's placeholder stands on: one stands here too (below). A file made there since is hidden.
1322
- if (heldPlaceholder(root))
2078
+ // Only the folder plans' placeholders stand on, in a root the command writes (heldByPlans): one stands here too
2079
+ // (below). A file made there since is hidden.
2080
+ if (writable.some(folder => inside(root, folder) && root !== folder) && heldByPlans(root))
1323
2081
  continue;
1324
2082
  try {
1325
2083
  const info = statSync(root);
@@ -1333,29 +2091,34 @@ seccompFd, plan = {}) {
1333
2091
  }
1334
2092
  catch { /* nothing there to hide but a name, which a placeholder keeps (below) */ }
1335
2093
  }
1336
- // A hidden path that doesn't exist yet, where the command could make it, gets an empty read-only folder over it: bwrap
1337
- // makes the folder it stands on, which the step after the command removes (placeholderPlan).
2094
+ // A hidden path that doesn't exist yet, where the command could make it, gets an empty read-only folder over it: ZTC
2095
+ // makes the folder it stands on before bwrap starts, with a hold of the plan's in it, and the step after the command
2096
+ // removes it (placeholderPlan, holdPlaceholderFolders, bubblewrapRelease).
1338
2097
  const mountedAfterRoots = () => args.slice(afterRoots).flatMap((arg, index, after) => arg === '--ro-bind' ? [after[index + 2]]
1339
2098
  : arg === '--tmpfs' || arg === '--remount-ro' ? [after[index + 1]] : []);
1340
- const writable = profileAllowsFileWrite(profile) ? rootBinds : [];
1341
2099
  const placeholders = placeholderPlan(Array.from(new Set(hidden)), writable, mountedAfterRoots());
1342
2100
  for (const { path } of placeholders)
1343
2101
  args.push('--tmpfs', path, '--remount-ro', path);
1344
2102
  // Every folder from a writable root down to what the plan hides, bound onto itself so that no command renames it away
1345
2103
  // (hiddenPathPins), with the git program files' pinned folders, in one list, outermost first, right after the roots are
1346
2104
  // bound: bwrap applies its options in order, and a pin made after a mount inside it would cover that mount. A folder
1347
- // above a placeholder that doesn't exist yet (placeholderPlan's ancestors) bwrap makes first (`--dir`, through the
1348
- // root's bind, so on the host), then binds: a bind's source is looked up when bwrap comes to it. A plan that would pin
1349
- // too many is refused before its caller holds anything of it.
2105
+ // above a placeholder that doesn't exist yet (placeholderPlan's ancestors) is pinned as any other: bwrap looks up the
2106
+ // source of every bind before it applies any option, so the plan's caller makes it on the host before it starts bwrap
2107
+ // (ANCESTORS, makeBubblewrapAncestors); a `--dir` before its bind made it too late, and the command never started (the
2108
+ // final review of cd9cce92dcd, R9-2). A plan that would pin too many is refused before its caller holds or makes
2109
+ // anything of it.
1350
2110
  const madeAncestors = new Set(placeholders.flatMap(placeholder => placeholder.ancestors));
1351
2111
  const hiddenPins = [...new Set([...hiddenPathPins([...hiddenMounts, ...placeholders.map(placeholder => placeholder.path)], writable, mountedAfterRoots()), ...madeAncestors])];
1352
2112
  const extraPins = hiddenPins.filter(folder => !gitPinned.has(folder));
1353
2113
  if (extraPins.length > MAX_HIDDEN_PATH_PINS)
1354
2114
  throw new Error(hiddenPathPinRefusal(extraPins.length));
1355
2115
  const pins = [...new Set([...gitPinned, ...extraPins])].sort((a, b) => a.split(sep).length - b.split(sep).length || a.localeCompare(b));
1356
- args.splice(afterRoots, 0, ...pins.flatMap(folder => madeAncestors.has(folder) ? ['--dir', folder, '--bind', folder, folder]
1357
- : ['--bind', folder, folder]));
2116
+ args.splice(afterRoots, 0, ...pins.flatMap(folder => ['--bind', folder, folder]));
1358
2117
  plan.placeholders?.push(...new Set(placeholders.flatMap(placeholder => placeholder.made)));
2118
+ plan.ancestors?.push(...pins.filter(folder => madeAncestors.has(folder)));
2119
+ plan.placeholderFolders?.push(...placeholders.map(placeholder => placeholder.path));
2120
+ for (const [folder, physical] of placeholders.flatMap(placeholder => placeholder.physical))
2121
+ plan.physical?.set(folder, physical);
1359
2122
  // The person's skills folder in ZTC's own state, where hiding that state emptied it: bound back read-only, as the file
1360
2123
  // tools read it, after every hide; a link in it into the rest of that state leads into the empty folder.
1361
2124
  for (const root of ztcOwnSkillRoots()) {
@@ -1369,10 +2132,10 @@ seccompFd, plan = {}) {
1369
2132
  if (seccompFd !== undefined)
1370
2133
  args.push('--seccomp', String(seccompFd));
1371
2134
  }
1372
- args.push('--chdir', chdir, '--', '/bin/sh', '-c', command);
2135
+ args.push('--chdir', chdir, '--', ...planShell(command, plan.keepEnvironment));
1373
2136
  return args;
1374
2137
  }
1375
- function writeAudit(command, plan, options) {
2138
+ function writeAudit(command, plan, options, looks = profileRootLooks(options.profile, options.sessionCwd ?? plan.cwd)) {
1376
2139
  // Under the active config folder: an isolated launch sets ZTC_CONFIG_DIR and expects nothing in ~/.ztc (forge3d, 2026-11-06).
1377
2140
  const auditDir = options.sandbox?.auditDir || join(process.env.ZTC_CONFIG_DIR || join(homedir(), '.ztc'), 'sandbox', 'audits');
1378
2141
  mkdirSync(auditDir, { recursive: true, mode: 0o700 });
@@ -1380,8 +2143,10 @@ function writeAudit(command, plan, options) {
1380
2143
  // A busy session can emit many per-command audit files; cap by age, count, or total size.
1381
2144
  const createdAt = new Date().toISOString();
1382
2145
  const auditPath = join(auditDir, `${createdAt.replace(/[:.]/g, '-')}-${process.pid}-${randomUUID()}.json`);
1383
- // The profile's relative roots are the session's folder's (allowedRoots), as the plan bound them.
2146
+ // The profile's relative roots are the session's folder's (allowedRoots), as the plan bound them, by the plan's one look
2147
+ // at each (LOOKS, profileRootLooks).
1384
2148
  const rootsCwd = options.sessionCwd ?? plan.cwd;
2149
+ const roots = commandRoots(options.profile, plan.cwd, looks);
1385
2150
  writeFileSync(auditPath, JSON.stringify({
1386
2151
  schema_version: 1,
1387
2152
  created_at: createdAt,
@@ -1390,10 +2155,10 @@ function writeAudit(command, plan, options) {
1390
2155
  backend: plan.backend,
1391
2156
  enforcement: plan.enforcement,
1392
2157
  profile_id: options.profileId || null,
1393
- allowed_paths: allowedRoots(options.profile, plan.cwd, rootsCwd),
2158
+ allowed_paths: roots.map(({ root }) => root),
1394
2159
  // Where the command may read: the whole filesystem for a profile that reads everywhere (see readsEverywhere).
1395
2160
  read_paths: plan.enforcement !== 'os' ? null
1396
- : commandReadRoots(options.profile, plan.cwd, plan.backend === 'seatbelt' ? SEATBELT_SYSTEM_READ_ROOTS : BUBBLEWRAP_SYSTEM_READ_ROOTS, options.readPaths, rootsCwd),
2161
+ : commandReadRoots(options.profile, plan.cwd, plan.backend === 'seatbelt' ? SEATBELT_SYSTEM_READ_ROOTS : BUBBLEWRAP_SYSTEM_READ_ROOTS, options.readPaths, roots),
1397
2162
  denied_paths: deniedRoots(options.profile, rootsCwd),
1398
2163
  // ZTC's own state, which a command under a profile that limits the agent never sees (utils/ztc_own_state.ts).
1399
2164
  ztc_state_denied: ownStateRoots(plan.enforcement === 'os' && profileLimitsAgent(options.profile, options.sandbox)),
@@ -1404,35 +2169,60 @@ function writeAudit(command, plan, options) {
1404
2169
  }
1405
2170
  /**
1406
2171
  * The bwrap plan for COMMAND in CWD under OPTIONS, which buildSandboxCommandPlan makes once it has found bwrap on this
1407
- * host: its argv (buildBubblewrapArgs), and the step after the command (afterCommand) that undoes what bwrap could not
1408
- * refuse it where a repository names the programs git starts, then puts back what it broke of a repository the plan
1409
- * knew, both from what the plan found before it ran.
2172
+ * host: its argv (buildBubblewrapArgs), by one look at each root its profile names (LOOKS, profileRootLooks, which
2173
+ * buildSandboxCommandPlan's audit records too), with what its placeholders stand on, and the folders above a denial not
2174
+ * made yet for bwrap to pin, made and held on the host (holdPlaceholderFolders) and removed by its cleanup where left
2175
+ * empty, still the ones it made, and no other plan holds them (bubblewrapRelease), and the step after the command
2176
+ * (afterCommand) that undoes what bwrap could not refuse it where a repository names the programs git starts, then puts
2177
+ * back what it broke of a repository the plan knew, both from what the plan found before it ran.
1410
2178
  */
1411
- export function buildBubblewrapCommandPlan(command, cwd, options = {}) {
2179
+ export function buildBubblewrapCommandPlan(command, cwd, options = {}, looks = profileRootLooks(options.profile, options.sessionCwd ?? cwd)) {
1412
2180
  const hideOwnState = profileLimitsAgent(options.profile, options.sandbox || { enabled: true, backend: 'auto' });
1413
2181
  // Without network, bwrap reads a filter refusing Unix sockets from descriptor 3, which a shell opens for it.
1414
2182
  const filter = profileAllowsNetwork(options.profile) ? null : unixSocketFilter();
1415
2183
  // A plan whose roots would put the host's services' sockets in the command's reach is refused before anything looks
1416
2184
  // for repositories in them (hostSocketRootRefusal), so it walks and records none.
1417
2185
  if (!filter) {
1418
- const refusal = hostSocketRootRefusal(options.profile, cwd, options.sessionCwd ?? cwd, options.env ?? process.env, options.sessionCwd);
2186
+ const refusal = hostSocketRootRefusal(options.profile, cwd, options.sessionCwd ?? cwd, options.env ?? process.env, options.sessionCwd, looks);
1419
2187
  if (refusal !== undefined)
1420
2188
  throw new Error(refusal);
1421
2189
  }
1422
- const gitPrograms = commandGitProgramFiles(options.profile, cwd, options.sessionCwd);
1423
- // The folders bwrap makes for the plan's placeholders, held while the command runs and removed after it.
2190
+ const gitPrograms = commandGitProgramFiles(options.profile, cwd, options.sessionCwd, looks);
2191
+ // The folders made for the plan, made and held on the host before bwrap starts and removed after the command where left
2192
+ // empty, still the ones the plan made, and no other plan, of this ZTC or another, holds them: for its placeholders the
2193
+ // folders above them that don't exist yet (ANCESTORS) and those they stand on (each with a hold), each where the plan
2194
+ // found it by its real path (PHYSICAL); KNOWN says which folder each made, or took over, is.
1424
2195
  const placeholders = [];
2196
+ const ancestors = [];
2197
+ const placeholderFolders = [];
2198
+ const physical = new Map();
2199
+ const holds = [];
2200
+ const known = new Map();
1425
2201
  const planOptions = { hideOwnState, keepEnvironment: options.keepEnvironment, sessionCwd: options.sessionCwd,
1426
- gitPrograms, readPaths: options.readPaths, placeholders };
1427
- const release = placeholderRelease(placeholders);
2202
+ gitPrograms, readPaths: options.readPaths, placeholders, ancestors, placeholderFolders, physical, rootLooks: looks };
2203
+ const release = bubblewrapRelease(placeholders, placeholderFolders, holds, known);
2204
+ /** What the plan stands on made and held (holdPlaceholderFolders), or, refused, released. */
2205
+ const holdAndMake = () => {
2206
+ try {
2207
+ holdPlaceholderFolders(ancestors, placeholderFolders, holds, physical, known, bubblewrapHoldName(), new Set());
2208
+ }
2209
+ catch (error) {
2210
+ release();
2211
+ throw error;
2212
+ }
2213
+ };
1428
2214
  const afterCommand = gitPrograms
1429
2215
  ? { afterCommand: () => [...undoGitProgramWrites(gitPrograms), ...putBackBrokenRepositories(gitPrograms)] }
1430
2216
  : {};
1431
- const said = gitPrograms?.notes.length ? { notices: gitPrograms.notes } : {};
2217
+ // The roots its profile names that the plan doesn't bind, links a command could have made and roots ZTC couldn't look
2218
+ // at (profileRootLooks), the spellings of roots inside another root that no bind shows (unboundRootNotices), and where it
2219
+ // stopped looking for repositories to protect: the command's result says each once.
2220
+ const notes = [...profileRootNotices(looks, options.sessionCwd ?? cwd), ...unboundRootNotices(looks), ...(gitPrograms?.notes ?? [])];
2221
+ const said = notes.length ? { notices: notes } : {};
1432
2222
  if (filter) {
1433
2223
  // The argv first: a command it refuses to start leaves no filter behind (hostSocketFolderRefusal).
1434
2224
  const bwrapArgs = buildBubblewrapArgs(command, cwd, options.profile, options.env, 3, planOptions);
1435
- holdPlaceholders(placeholders);
2225
+ holdAndMake();
1436
2226
  let directory;
1437
2227
  try {
1438
2228
  directory = mkdtempSync(join(tmpdir(), 'ztc-seccomp-'));
@@ -1456,21 +2246,21 @@ export function buildBubblewrapCommandPlan(command, cwd, options = {}) {
1456
2246
  cwd,
1457
2247
  backend: 'bubblewrap',
1458
2248
  enforcement: 'os',
1459
- notes: ['bubblewrap namespace sandbox active; Unix sockets refused.', ...(gitPrograms?.notes ?? [])],
2249
+ notes: ['bubblewrap namespace sandbox active; Unix sockets refused.', ...notes],
1460
2250
  cleanup,
1461
2251
  ...said,
1462
2252
  ...afterCommand,
1463
2253
  };
1464
2254
  }
1465
2255
  const args = buildBubblewrapArgs(command, cwd, options.profile, options.env, undefined, planOptions);
1466
- holdPlaceholders(placeholders);
2256
+ holdAndMake();
1467
2257
  return {
1468
2258
  executable: 'bwrap',
1469
2259
  args,
1470
2260
  cwd,
1471
2261
  backend: 'bubblewrap',
1472
2262
  enforcement: 'os',
1473
- notes: ['bubblewrap namespace sandbox active.', ...(gitPrograms?.notes ?? [])],
2263
+ notes: ['bubblewrap namespace sandbox active.', ...notes],
1474
2264
  ...(placeholders.length > 0 ? { cleanup: release } : {}),
1475
2265
  ...said,
1476
2266
  ...afterCommand,
@@ -1494,12 +2284,14 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
1494
2284
  const requireOs = requiresOsSandbox({ ...options, sandbox });
1495
2285
  // Under a profile that limits the agent, its commands never see ZTC's own state (utils/ztc_own_state.ts).
1496
2286
  const hideOwnState = profileLimitsAgent(options.profile, sandbox);
2287
+ // One look at each root the profile names, for the whole plan and its audit (profileRootLooks).
2288
+ const looks = profileRootLooks(options.profile, options.sessionCwd ?? cwd);
1497
2289
  let plan;
1498
2290
  if (backend === 'seatbelt') {
1499
2291
  if (process.platform !== 'darwin' || !commandExists('sandbox-exec')) {
1500
2292
  plan = {
1501
- executable: '/bin/sh',
1502
- args: ['-c', command],
2293
+ executable: posixShell(),
2294
+ args: posixShellArgs(command),
1503
2295
  cwd,
1504
2296
  backend: 'unsupported',
1505
2297
  enforcement: 'unsupported',
@@ -1507,16 +2299,18 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
1507
2299
  };
1508
2300
  }
1509
2301
  else {
1510
- const { path: profilePath, cleanup, programs } = writeSeatbeltProfile(options.profile, cwd, options.env, hideOwnState, options.sessionCwd, options.readPaths);
2302
+ const { path: profilePath, cleanup, programs } = writeSeatbeltProfile(options.profile, cwd, options.env, hideOwnState, options.sessionCwd, options.readPaths, looks);
2303
+ // The roots its profile names that the profile allows nothing in (profileRootLooks), and the repositories' notes.
2304
+ const notes = [...profileRootNotices(looks, options.sessionCwd ?? cwd), ...(programs?.notes ?? [])];
1511
2305
  plan = {
1512
2306
  executable: '/usr/bin/sandbox-exec',
1513
- args: ['-f', profilePath, '/bin/sh', '-c', command],
2307
+ args: ['-f', profilePath, ...planShell(command, options.keepEnvironment)],
1514
2308
  ...(!profileAllowsFileWrite(options.profile) ? { env: withoutAppleToolShims(options.env ?? process.env) } : {}),
1515
2309
  cwd,
1516
2310
  backend: 'seatbelt',
1517
2311
  enforcement: 'os',
1518
- notes: [`Seatbelt profile: ${profilePath}`, ...(programs?.notes ?? [])],
1519
- ...(programs?.notes.length ? { notices: programs.notes } : {}),
2312
+ notes: [`Seatbelt profile: ${profilePath}`, ...notes],
2313
+ ...(notes.length ? { notices: notes } : {}),
1520
2314
  // Seatbelt refuses what bwrap's step undoes, but not a write to HEAD, refs or objects, which a checkout needs.
1521
2315
  ...(programs ? { afterCommand: () => putBackBrokenRepositories(programs) } : {}),
1522
2316
  cleanup,
@@ -1526,8 +2320,8 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
1526
2320
  else if (backend === 'bubblewrap') {
1527
2321
  if (process.platform !== 'linux' || !commandExists('bwrap')) {
1528
2322
  plan = {
1529
- executable: '/bin/sh',
1530
- args: ['-c', command],
2323
+ executable: posixShell(),
2324
+ args: posixShellArgs(command),
1531
2325
  cwd,
1532
2326
  backend: 'unsupported',
1533
2327
  enforcement: 'unsupported',
@@ -1535,7 +2329,7 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
1535
2329
  };
1536
2330
  }
1537
2331
  else {
1538
- plan = buildBubblewrapCommandPlan(command, cwd, { ...options, sandbox });
2332
+ plan = buildBubblewrapCommandPlan(command, cwd, { ...options, sandbox }, looks);
1539
2333
  }
1540
2334
  }
1541
2335
  else if (backend === 'windows-job') {
@@ -1552,8 +2346,8 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
1552
2346
  }
1553
2347
  else {
1554
2348
  plan = {
1555
- executable: '/bin/sh',
1556
- args: ['-c', command],
2349
+ executable: posixShell(),
2350
+ args: posixShellArgs(command),
1557
2351
  cwd,
1558
2352
  backend: 'unsupported',
1559
2353
  enforcement: 'unsupported',
@@ -1564,7 +2358,7 @@ export function buildSandboxCommandPlan(command, cwd, options = {}) {
1564
2358
  throw new Error(`OS sandbox enforcement required but unavailable: ${plan.notes.join(' ')}`);
1565
2359
  }
1566
2360
  try {
1567
- plan.auditPath = writeAudit(command, plan, { ...options, sandbox });
2361
+ plan.auditPath = writeAudit(command, plan, { ...options, sandbox }, looks);
1568
2362
  }
1569
2363
  catch (error) {
1570
2364
  plan.cleanup?.();