@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
@@ -62,12 +62,26 @@
62
62
  */
63
63
  import { execFileSync } from 'node:child_process';
64
64
  import { randomBytes } from 'node:crypto';
65
- import { accessSync, chmodSync, closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
65
+ import { accessSync, chmodSync, closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, statSync, symlinkSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
66
66
  import { homedir } from 'node:os';
67
67
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
68
68
  import { GIT_PROBE_OPTIONS } from './git_probe_options.js';
69
69
  import { buildGitSubprocessEnv, buildGitSubprocessEnvFor } from './subprocess_env.js';
70
70
  const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
71
+ /**
72
+ * ROOTS, each as given (absolute: the real path one look at it found, utils/sandbox.ts's profileRootLooks), but those
73
+ * inside another of them: a root inside another root is that root's (as bubblewrap binds it), so the pins from a root
74
+ * down to a repository, and the walk for work trees, run from the outermost root, and none of them is resolved again.
75
+ * They stopped at the innermost root, so under allowedPaths [ws, ws/proj] nothing pinned ws/proj, which bubblewrap no
76
+ * longer binds as a mount point of its own: a command renamed it away, with the repository's protected files, and made a
77
+ * repository of its own there whose core.fsmonitor the person's git ran; and each root, resolved again by its path, had a
78
+ * folder above a nested root that a command swapped for a link lead the walk, the pins and the step after the command to
79
+ * a repository outside every root (appstore's NESTED-GIT-PIN and RESIDUAL-SCOPE).
80
+ */
81
+ export function outermostRoots(roots) {
82
+ const given = [...new Set(roots.map(root => resolve(root)))];
83
+ return given.filter(root => !given.some(other => other !== root && inside(root, other)));
84
+ }
71
85
  /** PATH's nearest existing folder or file as the filesystem spells it, and the names after it, as given. */
72
86
  function existingPart(path) {
73
87
  const rest = [];
@@ -147,14 +161,16 @@ const MAX_WALK_FOLDERS = 2000;
147
161
  /** Folders the walk does not enter: package trees, which hold no repository of the person's and can hold thousands of folders. */
148
162
  const WALK_SKIPPED = new Set(['node_modules']);
149
163
  /**
150
- * Each folder in ROOTS, or below one down to MAX_WALK_DEPTH, that holds a .git entry (in any letter case, as git finds
151
- * one on a volume that ignores case): where a repository's work tree begins. Breadth first, so the shallow ones are
152
- * found before the walk stops; no link is followed, and no .git or node_modules is entered. With them, each of ROOTS
153
- * (as the filesystem spells it) that still held folders unread when the walk stopped at MAX_WALK_FOLDERS.
164
+ * Each folder in ROOTS (each named root walked from its own look real path), or below one down to MAX_WALK_DEPTH, that
165
+ * holds a .git entry (in any letter case, as git finds one on a volume that ignores case): where a repository's work tree
166
+ * begins. Breadth first, so the shallow ones are found before the walk stops; no link is followed, no visited folder is
167
+ * entered twice, and no .git or node_modules is entered. With them, each of ROOTS that still held folders unread when
168
+ * the walk stopped at MAX_WALK_FOLDERS.
154
169
  */
155
170
  function workTreesBelow(roots) {
156
171
  const found = [];
157
- const starts = [...new Set(roots.map(root => realOrNamed(resolve(root))))];
172
+ const starts = [...new Set(roots.map(root => resolve(root)))];
173
+ const visited = new Set(starts);
158
174
  let level = starts;
159
175
  let read = 0;
160
176
  for (let depth = 0; level.length > 0 && depth <= MAX_WALK_DEPTH; depth++) {
@@ -175,8 +191,13 @@ function workTreesBelow(roots) {
175
191
  const name = entry.name.toLowerCase();
176
192
  if (name === '.git')
177
193
  found.push(folder);
178
- else if (entry.isDirectory() && !WALK_SKIPPED.has(name))
179
- next.push(join(folder, entry.name));
194
+ else if (entry.isDirectory() && !WALK_SKIPPED.has(name)) {
195
+ const child = join(folder, entry.name);
196
+ if (!visited.has(child)) {
197
+ visited.add(child);
198
+ next.push(child);
199
+ }
200
+ }
180
201
  }
181
202
  }
182
203
  level = next;
@@ -652,10 +673,12 @@ function wholeRepository(gitDir, commonDir, reach) {
652
673
  /**
653
674
  * What a sandboxed command working in DIRECTORIES (its cwd, the session's, the writable roots), with WRITE_ROOTS
654
675
  * writable, may not change of the repositories there and of those a walk of the writable roots finds, and of every
655
- * repository an earlier plan of this process found (knownGitDirectories).
676
+ * repository an earlier plan of this process found (knownGitDirectories). WRITE_ROOTS are the real paths one look at each
677
+ * root found (utils/sandbox.ts's profileRootLooks), which the plan takes as they are, the outermost of them alone
678
+ * (outermostRoots): it resolved each again by its path, and stopped its pins at a root inside another.
656
679
  */
657
680
  export function gitProgramFiles(directories, writeRoots, options = {}) {
658
- const roots = [...new Set(writeRoots.flatMap(root => [resolve(root), realOrNamed(resolve(root))]))];
681
+ const roots = outermostRoots(writeRoots);
659
682
  /** What the plan says of a core.hooksPath folder the repository tracks, by that folder. */
660
683
  const trackedHooks = new Map();
661
684
  /** Where the plan stopped looking for repositories. */
@@ -851,7 +874,9 @@ export function gitProgramFiles(directories, writeRoots, options = {}) {
851
874
  // looks there for the repository of a folder whose own .git it takes for none); then each work tree a walk of the
852
875
  // writable roots finds. Those git may answer for are asked about after, those found before last.
853
876
  for (const directory of directories) {
854
- const real = realOrNamed(resolve(directory));
877
+ // A root as given, resolved no more; the folder a command runs in, and the session's, as they really are.
878
+ const given = resolve(directory);
879
+ const real = roots.includes(given) ? given : realOrNamed(given);
855
880
  const root = rootHolding(real);
856
881
  for (let folder = real; root !== undefined && inside(folder, root); folder = dirname(folder)) {
857
882
  keepByPlace(folder);
@@ -865,7 +890,13 @@ export function gitProgramFiles(directories, writeRoots, options = {}) {
865
890
  + 'folder past them that ZTC has not found before is not protected from this command.');
866
891
  }
867
892
  const askedLater = [];
868
- for (const top of walk.found) {
893
+ for (const found of walk.found) {
894
+ // Where it really is: the walk reads each folder by its path, so one a command left running in the background swapped
895
+ // for a link after the walk read the folder above it led the walk outside every root, to work trees none of this
896
+ // plan's, which it recorded (appstore's RESIDUAL-SCOPE).
897
+ const top = realOrNamed(found);
898
+ if (rootHolding(top) === undefined)
899
+ continue;
869
900
  keepByPlace(top);
870
901
  if (!mayAnswer(join(top, '.git')))
871
902
  continue;
@@ -920,8 +951,13 @@ export function gitProgramFiles(directories, writeRoots, options = {}) {
920
951
  if (layout.top !== null)
921
952
  keepEntry(gitDir, join(layout.top, '.git'));
922
953
  }
923
- // Kept for every later plan, added to what earlier ones kept; what this plan found is the record's newest.
954
+ // Kept for every later plan, added to what earlier ones kept; what this plan found is the record's newest. Only a
955
+ // repository whose git directory itself lies in the writable roots by its real path (re-checked after git answers) is
956
+ // recorded and eligible for put-back: a mixed entry whose work tree is in a root while its git directory lies outside
957
+ // (a link swapped in during a race, or a .git file pointing outside) is never recorded or mutated after the command.
924
958
  for (const [gitDir, record] of records) {
959
+ if (!inRoots(realOrNamed(gitDir)))
960
+ continue;
925
961
  const kept = knownGitDirectories.get(gitDir);
926
962
  knownGitDirectories.delete(gitDir);
927
963
  if (!kept) {
@@ -959,6 +995,8 @@ export function gitProgramFiles(directories, writeRoots, options = {}) {
959
995
  };
960
996
  for (const [gitDir, record] of knownGitDirectories) {
961
997
  const { commonDir, workTree } = record;
998
+ if (!inRoots(realOrNamed(gitDir)))
999
+ continue;
962
1000
  if ([join(gitDir, 'HEAD'), join(commonDir, 'refs'), join(commonDir, 'objects')].every(path => rootHolding(path) === undefined))
963
1001
  continue;
964
1002
  const whole = wholeRepository(gitDir, commonDir, reachOf(workTree));
@@ -994,6 +1032,7 @@ export function gitProgramFiles(directories, writeRoots, options = {}) {
994
1032
  // would otherwise make it the command's): the plan says nothing of it then.
995
1033
  notes: [...[...trackedHooks].filter(([folder]) => !folders.has(folder)).map(([, note]) => note), ...stopped, ...said],
996
1034
  repositories,
1035
+ roots: [...roots],
997
1036
  };
998
1037
  }
999
1038
  const octal = (mode) => mode.toString(8).padStart(3, '0');
@@ -1029,45 +1068,292 @@ function writeHead(path, head) {
1029
1068
  closeSync(fd);
1030
1069
  }
1031
1070
  }
1071
+ /** Outermost root holding PATH (strictly below it), split into safe non-traversing relative segments, or null. */
1072
+ function rootAndParts(path, roots) {
1073
+ const root = roots.find(candidate => candidate !== path && inside(path, candidate));
1074
+ if (root === undefined)
1075
+ return null;
1076
+ const rel = relative(root, path);
1077
+ if (!rel || rel.startsWith('..') || isAbsolute(rel))
1078
+ return null;
1079
+ const parts = rel.split(sep).filter(Boolean);
1080
+ if (parts.length === 0 || parts.some(part => part === '.' || part === '..'))
1081
+ return null;
1082
+ return { root, dirParts: parts.slice(0, -1), leaf: parts[parts.length - 1] };
1083
+ }
1084
+ /** Fast-path pre-check: whether any ancestor directory from ROOT through DIR_PARTS is a link or non-directory. */
1085
+ function hasSymlinkAncestor(root, dirParts) {
1086
+ if (kindOf(root) !== 'folder')
1087
+ return true;
1088
+ let current = root;
1089
+ for (const part of dirParts) {
1090
+ current = join(current, part);
1091
+ if (kindOf(current) !== 'folder')
1092
+ return true;
1093
+ }
1094
+ return false;
1095
+ }
1096
+ const SYSTEM_PYTHON_CANDIDATES = ['/usr/bin/python3', '/opt/homebrew/bin/python3', '/usr/local/bin/python3'];
1097
+ let cachedSystemPython;
1098
+ function systemPython() {
1099
+ if (cachedSystemPython !== undefined)
1100
+ return cachedSystemPython;
1101
+ for (const candidate of SYSTEM_PYTHON_CANDIDATES) {
1102
+ try {
1103
+ if (statSync(candidate).isFile())
1104
+ return cachedSystemPython = candidate;
1105
+ }
1106
+ catch { /* try next fixed system path */ }
1107
+ }
1108
+ return cachedSystemPython = null;
1109
+ }
1110
+ /**
1111
+ * Isolated stdlib-only Python helper invoked via fixed system path (`-I -S`, minimal env) so every host filesystem
1112
+ * mutation in `afterCommand` walks from the outermost root using `openat(..., O_RDONLY | O_NOFOLLOW | O_DIRECTORY)`
1113
+ * per component and operates strictly relative to the opened `dir_fd` — preventing symlink swaps (including concurrent
1114
+ * RENAME_EXCHANGE races) from escaping outside the workspace roots, and never recursively deleting directories.
1115
+ */
1116
+ const CONFINED_AFTER_STEP_PY = `
1117
+ import base64, errno, json, os, stat, sys
1118
+
1119
+ def open_dir_chain(root, parts):
1120
+ flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, 'O_NOFOLLOW', 0)
1121
+ try:
1122
+ fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
1123
+ except OSError as e:
1124
+ if e.errno in (errno.ELOOP, errno.ENOTDIR):
1125
+ return None, 'skipped_link', None
1126
+ if e.errno == errno.ENOENT:
1127
+ return None, 'absent', None
1128
+ return None, 'error', str(e)
1129
+ for part in parts:
1130
+ try:
1131
+ nxt = os.open(part, flags, dir_fd=fd)
1132
+ except OSError as e:
1133
+ os.close(fd)
1134
+ if e.errno in (errno.ELOOP, errno.ENOTDIR):
1135
+ return None, 'skipped_link', None
1136
+ if e.errno == errno.ENOENT:
1137
+ return None, 'absent', None
1138
+ return None, 'error', str(e)
1139
+ os.close(fd)
1140
+ fd = nxt
1141
+ return fd, None, None
1142
+
1143
+ def clear_entry(parent_fd, leaf, suffix):
1144
+ try:
1145
+ st = os.lstat(leaf, dir_fd=parent_fd)
1146
+ except FileNotFoundError:
1147
+ return False, None
1148
+ if stat.S_ISDIR(st.st_mode):
1149
+ aside = f'{leaf}.ztc-{suffix}'
1150
+ os.rename(leaf, aside, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
1151
+ return True, aside
1152
+ os.unlink(leaf, dir_fd=parent_fd)
1153
+ return True, None
1154
+
1155
+ def run_op(item):
1156
+ op = item['op']
1157
+ fd, err_status, err_msg = open_dir_chain(item['root'], item['dirParts'])
1158
+ if fd is None:
1159
+ return {'status': err_status, 'error': err_msg}
1160
+ try:
1161
+ if op == 'remove_absent':
1162
+ existed, aside = clear_entry(fd, item['leaf'], item['suffix'])
1163
+ if not existed:
1164
+ return {'status': 'absent'}
1165
+ return {'status': 'moved_aside' if aside else 'removed', 'aside': aside}
1166
+ if op == 'restore_link':
1167
+ leaf = item['leaf']
1168
+ target = item['target']
1169
+ was_missing = False
1170
+ try:
1171
+ st = os.lstat(leaf, dir_fd=fd)
1172
+ if stat.S_ISLNK(st.st_mode) and os.readlink(leaf, dir_fd=fd) == target:
1173
+ return {'status': 'unchanged'}
1174
+ except FileNotFoundError:
1175
+ was_missing = True
1176
+ _, aside = clear_entry(fd, leaf, item['suffix'])
1177
+ os.symlink(target, leaf, dir_fd=fd)
1178
+ return {'status': 'restored', 'wasMissing': was_missing, 'aside': aside}
1179
+ if op == 'chmod_dir':
1180
+ leaf = item['leaf']
1181
+ mode = item['mode']
1182
+ try:
1183
+ st = os.lstat(leaf, dir_fd=fd)
1184
+ except FileNotFoundError:
1185
+ return {'status': 'absent'}
1186
+ if not stat.S_ISDIR(st.st_mode):
1187
+ return {'status': 'skipped_link'}
1188
+ try:
1189
+ os.chmod(leaf, mode, dir_fd=fd, follow_symlinks=False)
1190
+ return {'status': 'ok'}
1191
+ except NotImplementedError:
1192
+ pass
1193
+ if hasattr(os, 'O_PATH'):
1194
+ dfd = os.open(leaf, os.O_PATH | os.O_NOFOLLOW | os.O_DIRECTORY, dir_fd=fd)
1195
+ try:
1196
+ os.chmod(f'/proc/self/fd/{dfd}', mode)
1197
+ return {'status': 'ok'}
1198
+ finally:
1199
+ os.close(dfd)
1200
+ dfd = os.open(leaf, os.O_RDONLY | os.O_NOFOLLOW | os.O_DIRECTORY, dir_fd=fd)
1201
+ try:
1202
+ os.fchmod(dfd, mode)
1203
+ return {'status': 'ok'}
1204
+ finally:
1205
+ os.close(dfd)
1206
+ if op == 'put_back_head':
1207
+ _, aside = clear_entry(fd, 'HEAD', item['suffix'])
1208
+ head = item['head']
1209
+ if 'link' in head:
1210
+ os.symlink(head['link'], 'HEAD', dir_fd=fd)
1211
+ else:
1212
+ hflags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0)
1213
+ hfd = os.open('HEAD', hflags, head['mode'], dir_fd=fd)
1214
+ try:
1215
+ os.write(hfd, base64.b64decode(head['b64']))
1216
+ os.fchmod(hfd, head['mode'])
1217
+ finally:
1218
+ os.close(hfd)
1219
+ return {'status': 'ok', 'aside': aside}
1220
+ if op == 'put_back_dir':
1221
+ name = item['name']
1222
+ _, aside = clear_entry(fd, name, item['suffix'])
1223
+ os.mkdir(name, item['mode'], dir_fd=fd)
1224
+ return {'status': 'ok', 'aside': aside}
1225
+ return {'status': 'error', 'error': f'unknown op {op}'}
1226
+ except OSError as e:
1227
+ if e.errno in (errno.ELOOP, errno.ENOTDIR):
1228
+ return {'status': 'skipped_link'}
1229
+ return {'status': 'error', 'error': str(e)}
1230
+ finally:
1231
+ os.close(fd)
1232
+
1233
+ ops = json.load(sys.stdin)
1234
+ sys.stdout.write(json.dumps([run_op(item) for item in ops]))
1235
+ `;
1236
+ /** Execute confined dir_fd operations atomically via fixed system python3, or fail closed if unavailable on POSIX. */
1237
+ function runConfinedAfterOps(ops) {
1238
+ if (ops.length === 0)
1239
+ return [];
1240
+ const py = systemPython();
1241
+ if (py !== null) {
1242
+ try {
1243
+ const stdout = execFileSync(py, ['-I', '-S', '-c', CONFINED_AFTER_STEP_PY], {
1244
+ input: JSON.stringify(ops),
1245
+ env: { LC_ALL: 'C' },
1246
+ encoding: 'utf8',
1247
+ timeout: 5000,
1248
+ maxBuffer: 1024 * 1024,
1249
+ stdio: ['pipe', 'pipe', 'pipe'],
1250
+ windowsHide: true,
1251
+ });
1252
+ const parsed = JSON.parse(stdout);
1253
+ if (Array.isArray(parsed) && parsed.length === ops.length)
1254
+ return parsed;
1255
+ }
1256
+ catch (error) {
1257
+ return ops.map(() => ({ status: 'error', error: error.message }));
1258
+ }
1259
+ }
1260
+ // Fallback (e.g. non-POSIX hosts without system python3): refuse symlink ancestors and never recursively delete.
1261
+ return ops.map((item) => {
1262
+ if (hasSymlinkAncestor(item.root, item.dirParts))
1263
+ return { status: 'skipped_link' };
1264
+ const parent = join(item.root, ...item.dirParts);
1265
+ try {
1266
+ if (item.op === 'remove_absent') {
1267
+ const target = join(parent, item.leaf);
1268
+ if (kindOf(target) === 'none')
1269
+ return { status: 'absent' };
1270
+ const aside = clearForPutBack(target);
1271
+ return { status: aside ? 'moved_aside' : 'removed', aside: aside ? basename(aside) : null };
1272
+ }
1273
+ if (item.op === 'restore_link') {
1274
+ const target = join(parent, item.leaf);
1275
+ let now;
1276
+ try {
1277
+ now = lstatSync(target).isSymbolicLink() ? readlinkSync(target) : '\0';
1278
+ }
1279
+ catch {
1280
+ now = null;
1281
+ }
1282
+ if (now === item.target)
1283
+ return { status: 'unchanged' };
1284
+ const aside = clearForPutBack(target);
1285
+ symlinkSync(item.target, target);
1286
+ return { status: 'restored', wasMissing: now === null, aside: aside ? basename(aside) : null };
1287
+ }
1288
+ if (item.op === 'chmod_dir') {
1289
+ const target = join(parent, item.leaf);
1290
+ if (kindOf(target) !== 'folder')
1291
+ return { status: 'skipped_link' };
1292
+ chmodSync(target, item.mode);
1293
+ return { status: 'ok' };
1294
+ }
1295
+ if (item.op === 'put_back_head') {
1296
+ const target = join(parent, 'HEAD');
1297
+ const aside = clearForPutBack(target);
1298
+ const head = 'link' in item.head
1299
+ ? { link: item.head.link }
1300
+ : { text: Buffer.from(item.head.b64, 'base64').toString('latin1'), mode: item.head.mode };
1301
+ writeHead(target, head);
1302
+ return { status: 'ok', aside: aside ? basename(aside) : null };
1303
+ }
1304
+ const target = join(parent, item.name);
1305
+ const aside = clearForPutBack(target);
1306
+ mkdirSync(target, { mode: item.mode });
1307
+ return { status: 'ok', aside: aside ? basename(aside) : null };
1308
+ }
1309
+ catch (error) {
1310
+ return { status: 'error', error: error.message };
1311
+ }
1312
+ });
1313
+ }
1032
1314
  /**
1033
1315
  * The step after a command, on both backends (utils/sandbox.ts), once it has ended and before anything reads its result
1034
1316
  * or any other git runs there: each repository the plan knew (FILES.repositories) that git takes for none now, put back
1035
- * as a plan last saw it whole. A command may write a repository's HEAD, refs and objects (checkouts, commits and fetches
1036
- * do), and git takes a git directory whose HEAD names no ref or commit, or whose refs or objects folder it cannot enter,
1037
- * for no repository: in a work tree whose .git that is, it looks for one in the folders above, where the same command
1038
- * may have made one (git init, which a command may run anywhere it writes, or a .git file naming a git directory of its
1039
- * own), and the person's git there, or a host service's, would read that config and start what it names (the walk-up
1040
- * route of the R3e review). So HEAD is put back as it was, the permissions of the git directory and of the folders from
1041
- * below the writable root down to the work tree too (bwrap lets a command change a pinned folder's; git, in a shell
1042
- * already in a folder it cannot reach from the top, looks above on Linux), and a refs or objects folder git cannot enter
1043
- * is an empty one again: one that is missing made new, one git may not enter moved aside first. A repository git takes
1044
- * for one is the command's as it left it: a checkout, a commit, a branch switch, a detached HEAD, refs packed or
1045
- * emptied. What ZTC did, for the command's result.
1317
+ * as a plan last saw it whole. Every host mutation walks from the outermost writable root without following links
1318
+ * (`O_NOFOLLOW` per component via `dir_fd`), so a folder swapped for a link by a background command cannot redirect
1319
+ * chmod, HEAD rewrite, or directory restoration outside the workspace roots. What ZTC did, for the command's result.
1046
1320
  */
1047
1321
  export function putBackBrokenRepositories(files) {
1048
1322
  const said = [];
1323
+ const roots = files.roots;
1049
1324
  for (const { gitDir, commonDir, workTree, whole, brokenAtStart } of files.repositories) {
1050
1325
  // Never seen whole, or whole, as the command left it.
1051
1326
  if (whole === null || wholeRepository(gitDir, commonDir, whole.reach.map(({ folder }) => folder)) !== null)
1052
1327
  continue;
1053
1328
  /** What ZTC put back, or could not, each told once all is done, when what git finds there is known. */
1054
1329
  const done = [];
1055
- // The folders down to its work tree, which git passes through to reach it: a plan pins them, so each is still the
1056
- // folder the plan saw, but bwrap lets a command change a pinned folder's permissions (Seatbelt refuses it).
1330
+ // The folders down to its work tree, which git passes through to reach it (outermost first, so restoring an outer
1331
+ // 000 folder unlocks walking into its child via O_NOFOLLOW).
1332
+ const reachOps = [];
1057
1333
  for (const { folder, mode } of whole.reach) {
1058
1334
  if (enterable(folder))
1059
1335
  continue;
1060
- try {
1061
- chmodSync(folder, mode);
1062
- done.push({ path: folder, what: ` (its permissions, ${octal(mode)})` });
1063
- }
1064
- catch (error) {
1065
- done.push({ path: folder, what: ` (its permissions, ${octal(mode)})`, error });
1336
+ const loc = rootAndParts(folder, roots);
1337
+ if (loc === null || hasSymlinkAncestor(loc.root, loc.dirParts))
1338
+ continue;
1339
+ reachOps.push({ folder, mode, op: { op: 'chmod_dir', root: loc.root, dirParts: loc.dirParts, leaf: loc.leaf, mode } });
1340
+ }
1341
+ if (reachOps.length > 0) {
1342
+ const results = runConfinedAfterOps(reachOps.map(entry => entry.op));
1343
+ for (const [index, result] of results.entries()) {
1344
+ const { folder, mode } = reachOps[index];
1345
+ if (result.status === 'ok')
1346
+ done.push({ path: folder, what: ` (its permissions, ${octal(mode)})` });
1347
+ else if (result.status === 'error')
1348
+ done.push({ path: folder, what: ` (its permissions, ${octal(mode)})`, error: new Error(result.error ?? 'chmod failed') });
1066
1349
  }
1067
1350
  }
1068
- // Gone, which a plan's pin leaves to the person; or whole now that git may reach it.
1069
- if (kindOf(gitDir) === 'folder' && wholeRepository(gitDir, commonDir, []) === null)
1070
- putBackGitDirectory(gitDir, commonDir, whole, done);
1351
+ // Gone, swapped for a link, or whole now that git may reach it.
1352
+ const gitLoc = rootAndParts(gitDir, roots);
1353
+ if (gitLoc !== null && !hasSymlinkAncestor(gitLoc.root, gitLoc.dirParts)
1354
+ && kindOf(gitDir) === 'folder' && wholeRepository(gitDir, commonDir, []) === null) {
1355
+ putBackGitDirectory(gitDir, commonDir, whole, roots, done);
1356
+ }
1071
1357
  if (done.length === 0)
1072
1358
  continue;
1073
1359
  const folder = workTree ?? gitDir;
@@ -1091,47 +1377,67 @@ export function putBackBrokenRepositories(files) {
1091
1377
  }
1092
1378
  /**
1093
1379
  * GIT_DIR (common directory COMMON_DIR), which git takes for no repository, put back as WHOLE says it was, each step in
1094
- * DONE: its permissions, where git cannot enter it; its HEAD; a refs or objects folder git cannot enter.
1380
+ * DONE: its permissions, where git cannot enter it; its HEAD; a refs or objects folder git cannot enter. Every write
1381
+ * executes through `runConfinedAfterOps` from the outermost root with `O_NOFOLLOW` on every component.
1095
1382
  */
1096
- function putBackGitDirectory(gitDir, commonDir, whole, done) {
1383
+ function putBackGitDirectory(gitDir, commonDir, whole, roots, done) {
1097
1384
  const tell = (path, what, error) => {
1098
1385
  done.push(error === undefined ? { path, what } : { path, what, error });
1099
1386
  };
1100
- // The git directory, which git enters: a plan pins it, so it is still the folder the plan saw.
1387
+ const gitLoc = rootAndParts(gitDir, roots);
1388
+ if (gitLoc === null || hasSymlinkAncestor(gitLoc.root, gitLoc.dirParts))
1389
+ return;
1390
+ const gitDirParts = [...gitLoc.dirParts, gitLoc.leaf];
1101
1391
  if (!enterable(gitDir)) {
1102
- try {
1103
- chmodSync(gitDir, whole.modes.gitDir);
1392
+ const [result] = runConfinedAfterOps([
1393
+ { op: 'chmod_dir', root: gitLoc.root, dirParts: gitLoc.dirParts, leaf: gitLoc.leaf, mode: whole.modes.gitDir },
1394
+ ]);
1395
+ if (result?.status === 'ok')
1104
1396
  tell(gitDir, ` (its permissions, ${octal(whole.modes.gitDir)})`);
1105
- }
1106
- catch (error) {
1107
- tell(gitDir, ` (its permissions, ${octal(whole.modes.gitDir)})`, error);
1108
- }
1397
+ else if (result?.status === 'error')
1398
+ tell(gitDir, ` (its permissions, ${octal(whole.modes.gitDir)})`, new Error(result.error ?? 'chmod failed'));
1109
1399
  }
1400
+ const ops = [];
1110
1401
  if (wholeHead(gitDir) === null) {
1111
1402
  const head = join(gitDir, 'HEAD');
1112
- try {
1113
- const aside = clearForPutBack(head);
1114
- writeHead(head, whole.head);
1115
- tell(head, aside === null ? '' : ` (what the command left there is at ${aside})`);
1116
- }
1117
- catch (error) {
1118
- tell(head, '', error);
1119
- }
1403
+ const serializedHead = 'link' in whole.head
1404
+ ? { link: whole.head.link }
1405
+ : { b64: Buffer.from(whole.head.text, 'latin1').toString('base64'), mode: whole.head.mode };
1406
+ ops.push({
1407
+ op: { op: 'put_back_head', root: gitLoc.root, dirParts: gitDirParts, head: serializedHead, suffix: randomBytes(4).toString('hex') },
1408
+ report: result => {
1409
+ if (result.status === 'ok')
1410
+ tell(head, result.aside ? ` (what the command left there is at ${join(gitDir, result.aside)})` : '');
1411
+ else if (result.status === 'error')
1412
+ tell(head, '', new Error(result.error ?? 'write HEAD failed'));
1413
+ },
1414
+ });
1120
1415
  }
1121
- for (const name of ['refs', 'objects']) {
1122
- const path = join(commonDir, name);
1123
- if (enterable(path))
1124
- continue;
1125
- try {
1126
- const aside = clearForPutBack(path);
1127
- mkdirSync(path, { mode: whole.modes[name] });
1128
- tell(path, aside === null ? ', an empty folder (what it held is gone, or where the command moved it)'
1129
- : `, an empty folder (the one the command left, which git could not enter, is at ${aside})`);
1130
- }
1131
- catch (error) {
1132
- tell(path, ', an empty folder', error);
1416
+ const commonLoc = rootAndParts(commonDir, roots);
1417
+ if (commonLoc !== null && !hasSymlinkAncestor(commonLoc.root, commonLoc.dirParts)) {
1418
+ const commonDirParts = [...commonLoc.dirParts, commonLoc.leaf];
1419
+ for (const name of ['refs', 'objects']) {
1420
+ const path = join(commonDir, name);
1421
+ if (enterable(path))
1422
+ continue;
1423
+ ops.push({
1424
+ op: { op: 'put_back_dir', root: commonLoc.root, dirParts: commonDirParts, name, mode: whole.modes[name], suffix: randomBytes(4).toString('hex') },
1425
+ report: result => {
1426
+ if (result.status === 'ok') {
1427
+ tell(path, result.aside
1428
+ ? `, an empty folder (the one the command left, which git could not enter, is at ${join(commonDir, result.aside)})`
1429
+ : ', an empty folder (what it held is gone, or where the command moved it)');
1430
+ }
1431
+ else if (result.status === 'error') {
1432
+ tell(path, ', an empty folder', new Error(result.error ?? `mkdir ${name} failed`));
1433
+ }
1434
+ },
1435
+ });
1133
1436
  }
1134
1437
  }
1438
+ const results = runConfinedAfterOps(ops.map(entry => entry.op));
1439
+ for (const [index, result] of results.entries())
1440
+ ops[index].report(result);
1135
1441
  }
1136
1442
  /** What git says when the OS sandbox kept a protected file from its write: the file, or none where it names none. */
1137
1443
  const GIT_WRITE_REFUSED = [
@@ -1189,20 +1495,36 @@ export function refusedGitWriteNotes(output, command, cwd) {
1189
1495
  */
1190
1496
  export function undoGitProgramWrites(files) {
1191
1497
  const said = [];
1498
+ const roots = files.roots;
1499
+ const ops = [];
1192
1500
  for (const path of files.absent) {
1501
+ const loc = rootAndParts(path, roots);
1502
+ if (loc === null || hasSymlinkAncestor(loc.root, loc.dirParts))
1503
+ continue;
1193
1504
  if (kindOf(path) === 'none')
1194
1505
  continue;
1195
- try {
1196
- rmSync(path, { recursive: true, force: true });
1197
- said.push(`ZTC removed ${path}, which the command made: git would read it outside the sandbox, and a sandboxed command may `
1198
- + 'not change where the repository names the programs git starts.');
1199
- }
1200
- catch (error) {
1201
- said.push(`ZTC could not remove ${path}, which the command made (${error.message}): run no git in that repository `
1202
- + 'until it is gone.');
1203
- }
1506
+ ops.push({
1507
+ op: { op: 'remove_absent', root: loc.root, dirParts: loc.dirParts, leaf: loc.leaf, suffix: randomBytes(4).toString('hex') },
1508
+ report: result => {
1509
+ if (result.status === 'removed') {
1510
+ said.push(`ZTC removed ${path}, which the command made: git would read it outside the sandbox, and a sandboxed command may `
1511
+ + 'not change where the repository names the programs git starts.');
1512
+ }
1513
+ else if (result.status === 'moved_aside') {
1514
+ said.push(`ZTC moved ${path} aside to ${join(dirname(path), result.aside)}, which the command made as a folder: git would read it `
1515
+ + 'outside the sandbox, and a sandboxed command may not change where the repository names the programs git starts.');
1516
+ }
1517
+ else if (result.status === 'error') {
1518
+ said.push(`ZTC could not remove ${path}, which the command made (${result.error ?? 'error'}): run no git in that repository `
1519
+ + 'until it is gone.');
1520
+ }
1521
+ },
1522
+ });
1204
1523
  }
1205
1524
  for (const { path, target } of files.links) {
1525
+ const loc = rootAndParts(path, roots);
1526
+ if (loc === null || hasSymlinkAncestor(loc.root, loc.dirParts))
1527
+ continue;
1206
1528
  let now;
1207
1529
  try {
1208
1530
  now = lstatSync(path).isSymbolicLink() ? readlinkSync(path) : '\0';
@@ -1212,17 +1534,23 @@ export function undoGitProgramWrites(files) {
1212
1534
  }
1213
1535
  if (now === target)
1214
1536
  continue;
1215
- try {
1216
- rmSync(path, { recursive: true, force: true });
1217
- symlinkSync(target, path);
1218
- said.push(`ZTC put back ${path}, a link to ${target}, which the command ${now === null ? 'removed' : 'replaced'}: git would read `
1219
- + 'what it left there outside the sandbox.');
1220
- }
1221
- catch (error) {
1222
- said.push(`ZTC could not put back ${path}, a link to ${target} (${error.message}): run no git in that repository `
1223
- + 'until it is a link again.');
1224
- }
1537
+ ops.push({
1538
+ op: { op: 'restore_link', root: loc.root, dirParts: loc.dirParts, leaf: loc.leaf, target, suffix: randomBytes(4).toString('hex') },
1539
+ report: result => {
1540
+ if (result.status === 'restored') {
1541
+ said.push(`ZTC put back ${path}, a link to ${target}, which the command ${result.wasMissing ? 'removed' : 'replaced'}: git would read `
1542
+ + 'what it left there outside the sandbox.');
1543
+ }
1544
+ else if (result.status === 'error') {
1545
+ said.push(`ZTC could not put back ${path}, a link to ${target} (${result.error ?? 'error'}): run no git in that repository `
1546
+ + 'until it is a link again.');
1547
+ }
1548
+ },
1549
+ });
1225
1550
  }
1551
+ const results = runConfinedAfterOps(ops.map(entry => entry.op));
1552
+ for (const [index, result] of results.entries())
1553
+ ops[index].report(result);
1226
1554
  return said;
1227
1555
  }
1228
1556
  /**