@zergai/ztc 0.23.0-beta.1 → 0.24.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 (146) hide show
  1. package/README.md +299 -13
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/agent/agent.js +57 -14
  8. package/dist/agent/backends/http_error.d.ts +2 -0
  9. package/dist/agent/backends/http_error.js +2 -0
  10. package/dist/agent/backends/router_gate.d.ts +3 -2
  11. package/dist/agent/backends/router_gate.js +5 -4
  12. package/dist/agent/backends/router_keys.d.ts +14 -0
  13. package/dist/agent/backends/router_keys.js +19 -0
  14. package/dist/agent/backends/router_refusal.d.ts +5 -3
  15. package/dist/agent/backends/router_refusal.js +28 -6
  16. package/dist/agent/backends/types.d.ts +1 -1
  17. package/dist/agent/backends/zrouter_stream.js +10 -6
  18. package/dist/agent/commands/agent_cli.d.ts +11 -1
  19. package/dist/agent/commands/agent_cli.js +295 -38
  20. package/dist/agent/commands/diff.js +4 -1
  21. package/dist/agent/commands/help.js +4 -1
  22. package/dist/agent/commands/plan.js +3 -1
  23. package/dist/agent/commands/session_redaction.d.ts +16 -0
  24. package/dist/agent/commands/session_redaction.js +77 -0
  25. package/dist/agent/commands/settings.js +144 -0
  26. package/dist/agent/commands/types.d.ts +5 -0
  27. package/dist/agent/commands/usage_spec.d.ts +4 -0
  28. package/dist/agent/commands/usage_spec.js +10 -4
  29. package/dist/agent/runtime/policy.d.ts +25 -0
  30. package/dist/agent/runtime/policy.js +154 -26
  31. package/dist/agent/runtime/source_verification.js +6 -2
  32. package/dist/agent/runtime/tool_runtime.js +81 -3
  33. package/dist/agent/tools/apply_patch.js +678 -131
  34. package/dist/agent/tools/bus_message.d.ts +26 -1
  35. package/dist/agent/tools/bus_message.js +126 -10
  36. package/dist/agent/tools/file.d.ts +16 -1
  37. package/dist/agent/tools/file.js +43 -5
  38. package/dist/agent/tools/index.d.ts +1 -1
  39. package/dist/agent/tools/index.js +1 -1
  40. package/dist/agent/tools/pane.js +5 -0
  41. package/dist/agent/tools/search.js +5 -1
  42. package/dist/agent/tools/supervision.js +16 -2
  43. package/dist/agent/tools/types.d.ts +22 -0
  44. package/dist/app/mirror_startup.d.ts +7 -5
  45. package/dist/app/mirror_startup.js +7 -5
  46. package/dist/app/navigator_mirrors.d.ts +20 -0
  47. package/dist/app/navigator_mirrors.js +36 -0
  48. package/dist/app/workspace_layout_controller.d.ts +11 -2
  49. package/dist/app/workspace_layout_controller.js +13 -2
  50. package/dist/batch/worktree.js +9 -1
  51. package/dist/cli_ratatui.d.ts +264 -12
  52. package/dist/cli_ratatui.js +1198 -103
  53. package/dist/config/types.d.ts +29 -0
  54. package/dist/desktop/daily/source_baseline.js +3 -1
  55. package/dist/diagnostics/session_export.d.ts +1 -0
  56. package/dist/diagnostics/session_export.js +229 -26
  57. package/dist/emulation/tool_adapters.js +42 -5
  58. package/dist/headless.js +24 -5
  59. package/dist/instance_registry.d.ts +7 -0
  60. package/dist/mcp/workspace_server.d.ts +12 -1
  61. package/dist/mcp/workspace_server.js +75 -8
  62. package/dist/panes/agent_cli.d.ts +60 -3
  63. package/dist/panes/agent_cli.js +169 -16
  64. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  65. package/dist/panes/agent_pane_sessions.js +111 -0
  66. package/dist/panes/agent_panes.d.ts +77 -3
  67. package/dist/panes/agent_panes.js +199 -10
  68. package/dist/panes/agent_profiles.d.ts +5 -0
  69. package/dist/panes/agent_profiles.js +7 -0
  70. package/dist/panes/agent_resume.d.ts +134 -0
  71. package/dist/panes/agent_resume.js +155 -0
  72. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  73. package/dist/panes/agent_sessions/claude_head.js +122 -0
  74. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  75. package/dist/panes/agent_sessions/claude_store.js +223 -0
  76. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  77. package/dist/panes/agent_sessions/codex_head.js +161 -0
  78. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  79. package/dist/panes/agent_sessions/codex_store.js +187 -0
  80. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  81. package/dist/panes/agent_sessions/controller.js +110 -0
  82. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  83. package/dist/panes/agent_sessions/cut_json.js +109 -0
  84. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  85. package/dist/panes/agent_sessions/limits.js +48 -0
  86. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  87. package/dist/panes/agent_sessions/scan.js +86 -0
  88. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  89. package/dist/panes/agent_sessions/store_fs.js +128 -0
  90. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  91. package/dist/panes/agent_sessions/stores.js +89 -0
  92. package/dist/panes/agent_sessions/title.d.ts +9 -0
  93. package/dist/panes/agent_sessions/title.js +51 -0
  94. package/dist/panes/agent_sessions/types.d.ts +48 -0
  95. package/dist/panes/agent_sessions/types.js +2 -0
  96. package/dist/panes/reply_arbitrator.d.ts +39 -0
  97. package/dist/panes/reply_arbitrator.js +185 -0
  98. package/dist/panes/reply_modes.d.ts +291 -0
  99. package/dist/panes/reply_modes.js +598 -0
  100. package/dist/runtime_info.js +11 -2
  101. package/dist/session.js +4 -2
  102. package/dist/simulation/living/context.d.ts +8 -8
  103. package/dist/simulation/living/types.d.ts +5 -5
  104. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  105. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  106. package/dist/ui/ratatui/ipc_path.js +23 -3
  107. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  108. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  109. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  110. package/dist/ui/ratatui/pane_relay.js +86 -19
  111. package/dist/ui/ratatui/process.js +3 -0
  112. package/dist/ui/ratatui/protocol.d.ts +50 -1
  113. package/dist/ui/ratatui/protocol.js +56 -0
  114. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  115. package/dist/ui/ratatui/relay_policy.js +94 -0
  116. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  117. package/dist/ui/ratatui/screen_privacy.js +24 -0
  118. package/dist/ui/scrollback.js +8 -0
  119. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  120. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  121. package/dist/ui/widgets/log_view.d.ts +5 -1
  122. package/dist/ui/widgets/log_view.js +40 -4
  123. package/dist/utils/atomic_write.js +9 -11
  124. package/dist/utils/canonical_path.d.ts +19 -0
  125. package/dist/utils/canonical_path.js +44 -0
  126. package/dist/utils/compaction.d.ts +2 -1
  127. package/dist/utils/compaction.js +3 -1
  128. package/dist/utils/git_directory_names.d.ts +51 -0
  129. package/dist/utils/git_directory_names.js +429 -0
  130. package/dist/utils/temporary_write_root.d.ts +6 -1
  131. package/dist/utils/temporary_write_root.js +32 -2
  132. package/dist/utils/tool_result_message.d.ts +4 -1
  133. package/dist/utils/tool_result_message.js +6 -2
  134. package/dist/web/bus_hold.d.ts +70 -0
  135. package/dist/web/bus_hold.js +118 -0
  136. package/dist/web/mirror_client.d.ts +7 -3
  137. package/dist/web/mirror_client.js +61 -23
  138. package/dist/web/mirror_route_gate.d.ts +40 -0
  139. package/dist/web/mirror_route_gate.js +71 -0
  140. package/dist/web/mirror_stream.d.ts +147 -22
  141. package/dist/web/mirror_stream.js +350 -83
  142. package/dist/web/pane_credentials.d.ts +32 -1
  143. package/dist/web/pane_credentials.js +62 -2
  144. package/dist/workspace_collision.js +11 -2
  145. package/dist/zlm-embed.mjs +940 -273
  146. package/package.json +34 -12
@@ -1,12 +1,15 @@
1
- import { mkdir, mkdtemp, readFile, rm, stat, unlink } from 'fs/promises';
2
- import { tmpdir } from 'os';
3
- import { dirname, join, resolve } from 'path';
1
+ import { constants } from 'fs';
2
+ import { lstat, mkdir, mkdtemp, open, readFile, readlink, realpath, rm, stat, unlink, writeFile } from 'fs/promises';
3
+ import { devNull, tmpdir } from 'os';
4
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'path';
4
5
  import { execFile } from 'child_process';
5
6
  import { promisify } from 'util';
6
7
  import { ToolCapability } from '../runtime/capabilities.js';
7
8
  import { writeFileAtomic } from '../../utils/atomic_write.js';
8
- import { withPathLock, withPathLocks } from '../../utils/path_lock.js';
9
+ import { isWellFormedText } from '../../utils/canonical_path.js';
10
+ import { withPathLocks } from '../../utils/path_lock.js';
9
11
  import { buildUserSubprocessEnv } from '../../utils/subprocess_env.js';
12
+ import { assertTemporaryWritePathAllowed } from '../../utils/temporary_write_root.js';
10
13
  import { describeEdit, fileLines } from './edit_view.js';
11
14
  import { containerPath, DockerCommandError, dockerTarget, runInContainer, writeContainerFile, } from '../../utils/docker_target.js';
12
15
  const execFileAsync = promisify(execFile);
@@ -27,48 +30,257 @@ export const applyPatchTool = {
27
30
  required: ['patch'],
28
31
  },
29
32
  },
33
+ // The paths sit inside the patch text, where the runtime's policy cannot see them: name every one, resolved
34
+ // exactly as execute resolves it, so the runtime can refuse the whole patch before anything is written.
35
+ writePaths: async (args, context) => {
36
+ const docker = dockerTarget();
37
+ return admissionPaths(await patchTargets(readPatch(patchArgument(args)), patchHost(docker, context)), docker);
38
+ },
30
39
  execute: async (args, context) => {
31
- let patch = typeof args.patch === 'string' ? args.patch : '';
32
- if (!patch.trim()) {
33
- throw new Error('apply_patch: patch argument is required');
34
- }
40
+ const plan = readPatch(patchArgument(args));
35
41
  const docker = dockerTarget();
36
- const files = docker ? containerFiles(docker) : hostFiles(context?.cwd || process.cwd());
37
- if (patch.trim().startsWith('*** Begin Patch') && !wrappedUnifiedDiff(patch)) {
38
- const result = await applyStructuredPatch(patch, files);
39
- return JSON.stringify(result);
42
+ const host = patchHost(docker, context);
43
+ const files = host.files;
44
+ const targets = await patchTargets(plan, host);
45
+ // Every path is admitted once more inside the path locks, immediately before the first write, against the
46
+ // filesystem that write will see: one refusal refuses the whole patch, never half applied.
47
+ const admit = async () => {
48
+ if (context?.temporaryWriteRoot !== undefined) {
49
+ const writeSet = targets.map(target => target.path);
50
+ for (const target of targets)
51
+ await admitTemporaryWrite(target, context.temporaryWriteRoot, context.cwd, writeSet);
52
+ }
53
+ context?.admitWrites?.(admissionPaths(targets, docker));
54
+ };
55
+ if (plan.kind === 'structured') {
56
+ return JSON.stringify(await applyStructuredPatch(plan.operations, files, targets, admit));
40
57
  }
41
- patch = wrappedUnifiedDiff(patch) ?? patch;
42
- const changedPaths = extractPatchedPaths(patch).map(path => files.resolve(path));
58
+ const changedPaths = [...new Set(targets.map(target => target.path))];
59
+ // git apply rewrites files it touches; hold the per-path locks so a sibling tool call in the same response cannot
60
+ // interleave between its read and its write.
61
+ return withPathLocks(changedPaths, async () => {
62
+ await admit();
63
+ try {
64
+ const before = await Promise.all(changedPaths.map(path => files.inspect(path)));
65
+ const { stdout, stderr } = await host.apply(plan.diff, gitApplyPathArgs(plan.diff));
66
+ const after = await Promise.all(changedPaths.map(path => files.inspect(path)));
67
+ return JSON.stringify({
68
+ path: changedPaths[0] ?? files.resolve('.'),
69
+ paths: changedPaths,
70
+ action: 'patched',
71
+ changed: changedPaths.length > 0,
72
+ stdout,
73
+ stderr,
74
+ files: changedPaths.map((path, index) => patchedFile(path, before[index], after[index])),
75
+ });
76
+ }
77
+ catch (error) {
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ throw new Error(`apply_patch failed: ${message}`);
80
+ }
81
+ });
82
+ },
83
+ };
84
+ function patchArgument(args) {
85
+ const patch = typeof args.patch === 'string' ? args.patch : '';
86
+ if (!patch.trim()) {
87
+ throw new Error('apply_patch: patch argument is required');
88
+ }
89
+ // git reads the patch as the UTF-8 Node writes, which spells each lone surrogate as U+FFFD: two names that differ
90
+ // only there are one name to git, so the names admitted would not be the names git reads.
91
+ if (!isWellFormedText(patch)) {
92
+ throw new Error('apply_patch: refusing a patch that is not well-formed Unicode text: it holds a lone surrogate, '
93
+ + 'which git would read as U+FFFD');
94
+ }
95
+ return patch;
96
+ }
97
+ function readPatch(patch) {
98
+ if (patch.trim().startsWith('*** Begin Patch') && !wrappedUnifiedDiff(patch)) {
99
+ return { kind: 'structured', operations: parseStructuredPatch(patch) };
100
+ }
101
+ return { kind: 'unified', diff: wrappedUnifiedDiff(patch) ?? patch };
102
+ }
103
+ /** The paths the runtime admits: absolute on the host; in Docker mode relative to the container's working directory,
104
+ * the way the host policy sees write_file's paths there. */
105
+ function admissionPaths(targets, docker) {
106
+ return targets.map(target => ({
107
+ path: docker ? posix.relative(docker.workdir, target.path) || '.' : target.path,
108
+ label: target.label,
109
+ }));
110
+ }
111
+ /**
112
+ * Every path the patch will create, change, move or delete. A structured patch names them in its headers: each
113
+ * operation's file and an Update's Move to. A unified diff is read by git, by git's rules (see unifiedTargets).
114
+ */
115
+ async function patchTargets(plan, host) {
116
+ if (plan.kind === 'unified')
117
+ return unifiedTargets(plan.diff, host);
118
+ return plan.operations.flatMap(operation => {
119
+ const verb = operation.kind === 'add' ? 'Add File' : operation.kind === 'delete' ? 'Delete File' : 'Update File';
120
+ const targets = [{ path: host.files.resolve(operation.path), label: `${verb} ${operation.path}` }];
121
+ if (operation.kind === 'update' && operation.moveTo) {
122
+ targets.push({ path: host.files.resolve(operation.moveTo), label: `Move to ${operation.moveTo}` });
123
+ }
124
+ return targets;
125
+ });
126
+ }
127
+ async function admitTemporaryWrite(target, root, cwd, writeSet) {
128
+ try {
129
+ await assertTemporaryWritePathAllowed(target.path, root, 'apply_patch', cwd, writeSet);
130
+ }
131
+ catch (error) {
132
+ throw new Error(`${error instanceof Error ? error.message : String(error)}. apply_patch wrote nothing: ${target.label} `
133
+ + 'is refused, and every path a call writes must be allowed.');
134
+ }
135
+ }
136
+ function patchHost(docker, context) {
137
+ return docker ? containerPatchHost(docker) : hostPatchHost(context?.cwd || process.cwd(), context?.subprocessEnv);
138
+ }
139
+ /** Variables that point git at another repository, work tree or index. */
140
+ const GIT_REPOSITORY_ENV = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
141
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_COMMON_DIR', 'GIT_NAMESPACE'];
142
+ /** Variables that hand git configuration or an attributes source. */
143
+ const GIT_CONFIG_ENV = ['GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_CONFIG_SYSTEM', 'GIT_CONFIG_GLOBAL',
144
+ 'GIT_ATTR_SOURCE'];
145
+ function withoutEnv(env, names) {
146
+ const copy = { ...env };
147
+ for (const name of names)
148
+ delete copy[name];
149
+ return copy;
150
+ }
151
+ /**
152
+ * git reads and applies a unified diff in the ZTC process, outside any OS sandbox, and git loads configuration that
153
+ * whoever can write the work tree can write too: the repository's .git/config (a filter, with the work tree's own
154
+ * .gitattributes naming it, runs a command on every file git reads or writes), and a global config under a HOME the
155
+ * profile allows. So these runs read no system or global config, have a scratch HOME, and use an empty repository
156
+ * (GIT_DIR) over the real work tree (GIT_WORK_TREE): git still places the working directory inside the work tree as
157
+ * it would, and loads nothing else. The work tree's .gitattributes still converts line endings, but without config it
158
+ * can name no driver.
159
+ */
160
+ function isolatedGitEnv(base, scratch, workTree) {
161
+ return {
162
+ ...withoutEnv(base, [...GIT_REPOSITORY_ENV, ...GIT_CONFIG_ENV]),
163
+ GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: devNull, GIT_ATTR_NOSYSTEM: '1', HOME: scratch, XDG_CONFIG_HOME: scratch,
164
+ GIT_DIR: join(scratch, 'git'), GIT_WORK_TREE: workTree,
165
+ };
166
+ }
167
+ /** A scratch directory for one isolated git run: the diff, and the empty repository isolatedGitEnv points git at. */
168
+ async function withScratchRepository(diff, use) {
169
+ const scratch = await mkdtemp(join(tmpdir(), 'ztc-apply-patch-'));
170
+ try {
171
+ await mkdir(join(scratch, 'git', 'objects'), { recursive: true });
172
+ await mkdir(join(scratch, 'git', 'refs'));
173
+ await writeFile(join(scratch, 'git', 'HEAD'), 'ref: refs/heads/main\n', { flag: 'wx' });
174
+ const file = join(scratch, 'patch.diff');
175
+ await writeFile(file, diff, { flag: 'wx' });
176
+ return await use(scratch, file);
177
+ }
178
+ finally {
179
+ await rm(scratch, { recursive: true, force: true });
180
+ }
181
+ }
182
+ function hostPatchHost(cwd, subprocessEnv) {
183
+ const env = buildUserSubprocessEnv(subprocessEnv);
184
+ const run = async (args, runEnv) => {
43
185
  try {
44
- // git apply rewrites files it touches; hold the per-path locks so a
45
- // sibling tool call in the same response cannot interleave between its
46
- // read and its write.
47
- const { stdout, stderr, patched } = await withPathLocks(changedPaths, async () => {
48
- const before = await Promise.all(changedPaths.map(path => readIfPresent(files, path)));
49
- const applied = docker
50
- ? await runInContainer(docker, ['sh', '-c', 'f=$(mktemp) && cat > "$f" && { git apply --whitespace=nowarn "$f" '
51
- + '|| git apply --whitespace=nowarn --recount --unidiff-zero "$f"; }; s=$?; rm -f "$f"; exit $s'], { input: patch })
52
- : await gitApplyOnHost(patch, files.resolve('.'), context?.subprocessEnv);
53
- const after = await Promise.all(changedPaths.map(path => readIfPresent(files, path)));
54
- return { ...applied, patched: changedPaths.map((path, index) => patchedFile(path, before[index], after[index])) };
55
- });
56
- return JSON.stringify({
57
- path: changedPaths[0] ?? files.resolve('.'),
58
- paths: changedPaths,
59
- action: 'patched',
60
- changed: changedPaths.length > 0,
61
- stdout,
62
- stderr,
63
- files: patched,
186
+ return (await execFileAsync('git', args, { cwd, env: runEnv, maxBuffer: 10 * 1024 * 1024 })).stdout;
187
+ }
188
+ catch (error) {
189
+ // A numeric code is git's own exit status. Anything else (git missing, killed, output too large) leaves
190
+ // the patch's paths unknown, and an unknown path is never admitted.
191
+ if (typeof error.code === 'number')
192
+ return null;
193
+ throw error;
194
+ }
195
+ };
196
+ let tree;
197
+ // git finds the work tree from the physical working directory, so its root is resolved from that, not from a
198
+ // spelling through a symlink that git never saw. Finding it reads the repository's config but runs nothing.
199
+ const workTree = () => tree ??= (async () => {
200
+ const physical = await realpath(cwd);
201
+ const cdup = await run(['rev-parse', '--show-cdup'], withoutEnv(env, GIT_REPOSITORY_ENV));
202
+ const root = cdup === null ? physical : resolve(physical, cdup.replace(/\n$/, '') || '.');
203
+ return { root, cwd: physical, spelled: resolve(cwd) };
204
+ })();
205
+ return {
206
+ files: hostFiles(cwd),
207
+ resolveFrom: (base, path) => resolve(base, path),
208
+ workTree,
209
+ spell: (at, path) => {
210
+ const inside = relative(at.cwd, path);
211
+ return inside === '' ? at.spelled
212
+ : inside !== '..' && !inside.startsWith(`..${sep}`) && !isAbsolute(inside) ? join(at.spelled, inside) : path;
213
+ },
214
+ git: async (args, diff) => {
215
+ const { root } = await workTree();
216
+ return withScratchRepository(diff, (scratch, file) => run([...args, file], isolatedGitEnv(env, scratch, root)));
217
+ },
218
+ apply: async (diff, pinned) => {
219
+ const { root } = await workTree();
220
+ return withScratchRepository(diff, async (scratch, file) => {
221
+ const isolated = isolatedGitEnv(env, scratch, root);
222
+ const apply = (extra) => execFileAsync('git', ['apply', '--whitespace=nowarn', ...pinned, ...extra, file], { cwd, env: isolated, maxBuffer: 10 * 1024 * 1024 });
223
+ try {
224
+ return await apply([]);
225
+ }
226
+ catch (strict) {
227
+ // Models often write hunks git apply refuses although every context line matches: no trailing context,
228
+ // which git anchors to the end of the file, or headers that miscount their lines, which it reads as corrupt
229
+ // (2026-10-27). --recount and --unidiff-zero drop only those checks; context must still match, and a patch
230
+ // that fails both ways reports the strict error.
231
+ try {
232
+ return await apply(['--recount', '--unidiff-zero']);
233
+ }
234
+ catch {
235
+ throw strict;
236
+ }
237
+ }
64
238
  });
239
+ },
240
+ };
241
+ }
242
+ /**
243
+ * The container's side of isolatedGitEnv, in sh: `$1` is the work tree root; the diff arrives on stdin and is kept in
244
+ * "$d/patch.diff" beside an empty repository. Callers append their git command and clean up "$d".
245
+ */
246
+ const CONTAINER_ISOLATED_GIT = [
247
+ 'w=$1; shift',
248
+ 'd=$(mktemp -d) || exit 1',
249
+ 'mkdir -p "$d/git/objects" "$d/git/refs" && printf \'ref: refs/heads/main\\n\' > "$d/git/HEAD" && cat > "$d/patch.diff"'
250
+ + ' || { rm -rf "$d"; exit 1; }',
251
+ `unset ${[...GIT_REPOSITORY_ENV, ...GIT_CONFIG_ENV].join(' ')}`,
252
+ 'export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_ATTR_NOSYSTEM=1 HOME="$d" XDG_CONFIG_HOME="$d"'
253
+ + ' GIT_DIR="$d/git" GIT_WORK_TREE="$w"',
254
+ ].join('\n');
255
+ function containerPatchHost(docker) {
256
+ const run = async (argv, input) => {
257
+ try {
258
+ return (await runInContainer(docker, argv, input === undefined ? {} : { input })).stdout;
65
259
  }
66
260
  catch (error) {
67
- const message = error instanceof Error ? error.message : String(error);
68
- throw new Error(`apply_patch failed: ${message}`);
261
+ if (error instanceof DockerCommandError && error.exitCode !== null)
262
+ return null;
263
+ throw error;
69
264
  }
70
- },
71
- };
265
+ };
266
+ let tree;
267
+ const workTree = () => tree ??= (async () => {
268
+ const cdup = await run(['git', 'rev-parse', '--show-cdup']);
269
+ const root = cdup === null ? docker.workdir : posix.resolve(docker.workdir, cdup.replace(/\n$/, '') || '.');
270
+ return { root, cwd: docker.workdir, spelled: docker.workdir };
271
+ })();
272
+ return {
273
+ files: containerFiles(docker),
274
+ resolveFrom: (base, path) => posix.resolve(base, path),
275
+ workTree,
276
+ spell: (_tree, path) => path,
277
+ git: async (args, diff) => run(['sh', '-c', `${CONTAINER_ISOLATED_GIT}\ngit "$@" "$d/patch.diff"; s=$?; rm -rf "$d"; exit $s`,
278
+ 'sh', (await workTree()).root, ...args], diff),
279
+ apply: async (diff, pinned) => runInContainer(docker, ['sh', '-c', `${CONTAINER_ISOLATED_GIT}\n`
280
+ + '{ git apply --whitespace=nowarn "$@" "$d/patch.diff" || git apply --whitespace=nowarn "$@" --recount --unidiff-zero'
281
+ + ' "$d/patch.diff"; }; s=$?; rm -rf "$d"; exit $s', 'sh', (await workTree()).root, ...pinned], { input: diff }),
282
+ };
283
+ }
72
284
  /**
73
285
  * A unified diff wrapped in the structured format's "*** Begin Patch" / "*** End Patch" markers, with no structured
74
286
  * operations inside: models mix the two, and the structured parser found nothing to apply (2026-10-27). Returns the
@@ -85,42 +297,347 @@ function wrappedUnifiedDiff(patch) {
85
297
  return null;
86
298
  return body.join('\n') + '\n';
87
299
  }
88
- async function gitApplyOnHost(patch, cwd, subprocessEnv) {
89
- const dir = await mkdtemp(join(tmpdir(), 'ztc-apply-patch-'));
90
- const patchPath = join(dir, 'patch.diff');
91
- try {
92
- await writeFileAtomic(patchPath, patch);
93
- const apply = (extra) => execFileAsync('git', ['apply', '--whitespace=nowarn', ...extra, patchPath], { cwd, env: buildUserSubprocessEnv(subprocessEnv), maxBuffer: 10 * 1024 * 1024 });
94
- try {
95
- return await apply([]);
96
- }
97
- catch (strict) {
98
- // Models often write hunks git apply refuses although every context line matches: no trailing context, which
99
- // git anchors to the end of the file, or headers that miscount their lines, which it reads as corrupt
100
- // (2026-10-27). --recount and --unidiff-zero drop only those checks; context must still match, and a patch
101
- // that fails both ways reports the strict error.
102
- try {
103
- return await apply(['--recount', '--unidiff-zero']);
300
+ /**
301
+ * Pin git's path depth for a diff with a `diff --git` header: -p1 is git's default, but a plain ---/+++ section
302
+ * earlier in the same diff can make git guess another depth for the rest. Pinned, the header names below are read
303
+ * exactly as git reads them.
304
+ */
305
+ function gitApplyPathArgs(diff) {
306
+ return /^diff --git /m.test(diff) ? ['-p1'] : [];
307
+ }
308
+ /**
309
+ * The paths git apply will touch, read by git itself: `--numstat` names the file each section writes (after git
310
+ * strips, unquotes and places names by its own rules, and skips what it would skip), once as apply_patch's strict
311
+ * attempt parses the diff and once as its --recount --unidiff-zero fallback does, and both again reversed, which
312
+ * names a rename's or copy's source. --numstat names one file per section, and in a repository subdirectory git
313
+ * decides whether to apply a section by its new name alone, so the old name of a section it applies (a rename's or
314
+ * copy's source, or the file a `deleted file mode` section removes) can lie outside the working directory while the
315
+ * reversed reading skips the section: the names of every `diff --git` section git applies are read here as well,
316
+ * and those of a section it skips are not, since git touches nothing for it.
317
+ */
318
+ async function unifiedTargets(diff, host) {
319
+ const pinned = gitApplyPathArgs(diff);
320
+ const sections = gitSections(diff);
321
+ const [strict, strictReversed, recount, recountReversed] = await Promise.all([[], ['--recount', '--unidiff-zero']].flatMap(mode => [[], ['-R']].map(direction => (host.git(['apply', '--numstat', '-z', '--whitespace=nowarn', ...pinned, ...mode, ...direction], diff)))));
322
+ const tree = await host.workTree();
323
+ // git's prefix in a repository subdirectory. A section whose tested name is outside it is skipped (use_patch),
324
+ // unless git itself lists that name as applied, which only a mistaken prefix would explain.
325
+ const prefix = tree.root !== tree.cwd ? `${relativeName(tree)}/` : '';
326
+ const applied = new Set([strict, recount].flatMap(listed => numstatNames(listed ?? '')));
327
+ const skipped = sections.filter(section => prefix !== '' && section.tested !== null && !applied.has(section.tested)
328
+ && !(section.tested.startsWith(prefix) && section.tested.length > prefix.length));
329
+ if (skipped.length > 0 && applied.size === 0 && (strict !== null || recount !== null)) {
330
+ throw new Error(`apply_patch: git would apply nothing in this diff: in a repository subdirectory git reads a git diff's`
331
+ + ` names from the repository root, ${tree.root}, and skips a section whose name is outside this working directory,`
332
+ + ` where a name starts with ${relativeName(tree)}/ (${skipped.map(section => section.tested).join(', ')} in the diff)`);
333
+ }
334
+ const names = new Set(sections.filter(section => !skipped.includes(section)).flatMap(section => section.names));
335
+ for (const listed of [strict, strictReversed, recount, recountReversed]) {
336
+ for (const name of numstatNames(listed ?? ''))
337
+ names.add(name);
338
+ }
339
+ // In a repository subdirectory a git diff names files from the repository root: say so when one is refused.
340
+ const where = tree.root !== tree.cwd && pinned.length > 0
341
+ ? ` (git reads a git diff's names from the repository root, ${tree.root}, so a name in this working directory`
342
+ + ` starts with ${relativeName(tree)}/)`
343
+ : '';
344
+ return [...names].map(name => ({ path: host.spell(tree, host.resolveFrom(tree.root, name)), label: `${name} in the diff${where}` }));
345
+ }
346
+ /** The working directory's name from the work tree's root, with / separators, as a git diff names it. */
347
+ function relativeName(tree) {
348
+ return tree.cwd.slice(tree.root.length).replace(/^[\\/]+/, '').split(sep).join('/');
349
+ }
350
+ /** The names in `git apply --numstat -z` output: "added\tdeleted\tname\0" per file, "-" counts for a binary one. */
351
+ function numstatNames(listed) {
352
+ return listed.split('\0').filter(Boolean).map(record => {
353
+ const match = /^(?:\d+|-)\t(?:\d+|-)\t([\s\S]+)$/.exec(record);
354
+ if (!match)
355
+ throw new Error(`apply_patch: cannot read git's list of the files this patch changes: ${JSON.stringify(record)}`);
356
+ return match[1];
357
+ });
358
+ }
359
+ // git's apply.c reads a `diff --git` header with parse_git_diff_header, git_header_name and find_name; the functions
360
+ // below follow them for -p1, which apply_patch pins for any diff that has such a header.
361
+ const GIT_HEADER_LINES = ['--- ', '+++ ', 'old mode ', 'new mode ', 'deleted file mode ', 'new file mode ', 'copy from ',
362
+ 'copy to ', 'rename old ', 'rename new ', 'rename from ', 'rename to ', 'similarity index ', 'dissimilarity index ', 'index '];
363
+ /**
364
+ * Each `diff --git` section's names, as parse_git_diff_header reads them for -p1. A ---/+++ line names its side
365
+ * unless `new file mode` (for ---) or `deleted file mode` (for +++) came first, and then git expects /dev/null:
366
+ * otherwise `/dev/null` is the file dev/null. `deleted file mode` makes the old name, and `new file mode` the new
367
+ * one, the name the `diff --git` line gives both sides, whatever the ---/+++ lines said; a rename or copy line
368
+ * replaces its side; and a section that names neither side takes the `diff --git` line's name for both.
369
+ *
370
+ * A `diff --git` line with no header line after it is refused: git keeps its name for the next section it finds,
371
+ * and a plain ---/+++ section there then takes it as its new name, reads its own names from the repository root,
372
+ * and passes git's subdirectory test on the borrowed name while removing a file outside. git itself never writes
373
+ * such a header.
374
+ */
375
+ function gitSections(diff) {
376
+ const lines = diff.split('\n');
377
+ const sections = [];
378
+ // git reads only lines that end in a newline, so the text after the last one is never a header.
379
+ for (let index = 0; index < lines.length - 1; index += 1) {
380
+ const header = lines[index];
381
+ if (!header.startsWith('diff --git '))
382
+ continue;
383
+ const named = gitHeaderName(1, header.slice('diff --git '.length));
384
+ let oldName = null;
385
+ let newName = null;
386
+ let isNew = false;
387
+ let isDelete = false;
388
+ const given = [];
389
+ const give = (name) => {
390
+ if (name !== null)
391
+ given.push(name);
392
+ return name;
393
+ };
394
+ let next = index + 1;
395
+ for (; next < lines.length - 1; next += 1) {
396
+ // '@@ -' and any line git does not recognize end the header.
397
+ const prefix = GIT_HEADER_LINES.find(candidate => lines[next].startsWith(candidate));
398
+ if (!prefix)
399
+ break;
400
+ const rest = lines[next].slice(prefix.length);
401
+ if (prefix === '--- ' || prefix === '+++ ') {
402
+ const emptied = prefix === '--- ' ? isNew : isDelete;
403
+ if (emptied && isDevNull(rest))
404
+ continue;
405
+ const name = give(findName(rest, 1, true));
406
+ if (prefix === '--- ' && oldName === null && !isNew)
407
+ oldName = name;
408
+ if (prefix === '+++ ' && newName === null && !isDelete)
409
+ newName = name;
104
410
  }
105
- catch {
106
- throw strict;
411
+ else if (prefix === 'deleted file mode ') {
412
+ isDelete = true;
413
+ oldName = named;
414
+ }
415
+ else if (prefix === 'new file mode ') {
416
+ isNew = true;
417
+ newName = named;
418
+ }
419
+ else if (prefix === 'copy from ' || prefix === 'rename old ' || prefix === 'rename from ') {
420
+ oldName = give(findName(rest, 0, false));
421
+ }
422
+ else if (prefix === 'copy to ' || prefix === 'rename new ' || prefix === 'rename to ') {
423
+ newName = give(findName(rest, 0, false));
107
424
  }
108
425
  }
426
+ if (next === index + 1 && next < lines.length - 1) {
427
+ throw new Error(`apply_patch: refusing ${JSON.stringify(header)}: a \`diff --git\` line needs its header lines`
428
+ + ` (---/+++, a mode, rename or copy line) right after it, and git would lend its name to the next section`);
429
+ }
430
+ if (oldName === null && newName === null)
431
+ oldName = newName = named;
432
+ const names = [...new Set([oldName, newName, ...given].filter((name) => name !== null))];
433
+ for (const name of names) {
434
+ if (name.includes('\0'))
435
+ throw new Error(`apply_patch: refusing ${JSON.stringify(name)}: a path cannot contain a NUL byte`);
436
+ }
437
+ sections.push({ names, tested: newName ?? oldName });
109
438
  }
110
- finally {
111
- await rm(dir, { recursive: true, force: true });
439
+ return sections;
440
+ }
441
+ /** git's is_dev_null: /dev/null, then one of git's own isspace() bytes (the line's newline ends it here). */
442
+ function isDevNull(name) {
443
+ return name === '/dev/null' || /^\/dev\/null[ \t\r]/.test(name);
444
+ }
445
+ /**
446
+ * git's git_header_name: the name both sides of a `diff --git` line give, with `strip` components removed, or null
447
+ * when they differ (a rename), or when git cannot tell them apart. A quoted name that decodes to a NUL byte refuses
448
+ * the patch (unquoteCStyle), since git reads names as NUL-terminated C strings and its consumers disagree about what
449
+ * comes after one.
450
+ */
451
+ function gitHeaderName(strip, line) {
452
+ if (line.startsWith('"')) {
453
+ const first = unquoteCStyle(line);
454
+ if (first === null)
455
+ return null;
456
+ const cut = skipTreePrefix(strip, first.value);
457
+ if (cut === null)
458
+ return null;
459
+ const name = first.value.slice(cut);
460
+ const second = line.slice(first.end).replace(/^[ \t\r]+/, '');
461
+ if (second.startsWith('"')) {
462
+ const other = unquoteCStyle(second);
463
+ if (other === null)
464
+ return null;
465
+ const otherCut = skipTreePrefix(strip, other.value);
466
+ return otherCut !== null && other.value.slice(otherCut) === name ? name : null;
467
+ }
468
+ // An unquoted second name: git compares the stripped first name against the rest of the line from the second
469
+ // name's stripped start through the line's own newline (git_header_name's `line + llen - cp != first.len ||
470
+ // memcmp(...)`, where `line + llen` is past the newline). gitSections split the diff on '\n', so that newline is
471
+ // implicit here and restored for the comparison: a first name ending in an escaped newline can match.
472
+ const otherCut = skipTreePrefix(strip, second);
473
+ return otherCut !== null && `${second.slice(otherCut)}\n` === name ? name : null;
112
474
  }
475
+ const nameStart = skipTreePrefix(strip, line);
476
+ if (nameStart === null)
477
+ return null;
478
+ const name = line.slice(nameStart);
479
+ const quote = name.indexOf('"');
480
+ if (quote >= 0) {
481
+ // A quoted second name: the first, unquoted, is the same name followed by a space.
482
+ const other = unquoteCStyle(name.slice(quote));
483
+ if (other === null)
484
+ return null;
485
+ const otherCut = skipTreePrefix(strip, other.value);
486
+ if (otherCut === null)
487
+ return null;
488
+ const tail = other.value.slice(otherCut);
489
+ return tail.length < quote && name.startsWith(tail) && /[ \t\r]/.test(name[tail.length] ?? '') ? tail : null;
490
+ }
491
+ // Without quotes, a name counts only when it shows up twice, exactly the same, around one space or tab.
492
+ for (let length = 0; length < name.length; length += 1) {
493
+ if (name[length] !== ' ' && name[length] !== '\t')
494
+ continue;
495
+ const rest = name.slice(length + 1);
496
+ const restCut = skipTreePrefix(strip, rest);
497
+ if (restCut === null)
498
+ return null;
499
+ if (rest.slice(restCut) === name.slice(0, length))
500
+ return name.slice(0, length);
501
+ }
502
+ return null;
503
+ }
504
+ /** git's skip_tree_prefix: the index after the first `strip` components, or null. */
505
+ function skipTreePrefix(strip, name) {
506
+ if (strip === 0)
507
+ return name.startsWith('/') ? null : 0;
508
+ let left = strip;
509
+ for (let index = 0; index < name.length; index += 1) {
510
+ if (name[index] === '/') {
511
+ left -= 1;
512
+ if (left <= 0)
513
+ return index === 0 ? null : index + 1;
514
+ }
515
+ }
516
+ return null;
517
+ }
518
+ /**
519
+ * git's find_name: a C-quoted name, or one that ends at a tab (when asked) or at \r, the only other byte git's own
520
+ * isspace() table holds that a line can (it holds no \v or \f); -p strips components.
521
+ */
522
+ function findName(text, strip, endsAtTab) {
523
+ if (text.startsWith('"')) {
524
+ const quoted = unquoteCStyle(text);
525
+ if (quoted !== null) {
526
+ let name = quoted.value;
527
+ for (let left = strip; left > 0 && name !== null; left -= 1) {
528
+ const slash = name.indexOf('/');
529
+ name = slash < 0 ? null : name.slice(slash + 1);
530
+ }
531
+ if (name !== null)
532
+ return name ? squashSlash(name) : null;
533
+ }
534
+ }
535
+ let start = strip === 0 ? 0 : null;
536
+ let left = strip;
537
+ let end = text.length;
538
+ for (let index = 0; index < text.length; index += 1) {
539
+ const ch = text[index];
540
+ if (ch === '\t' ? endsAtTab : ch === '\r') {
541
+ end = index;
542
+ break;
543
+ }
544
+ if (ch === '/') {
545
+ left -= 1;
546
+ if (left === 0)
547
+ start = index + 1;
548
+ }
549
+ }
550
+ if (start === null || start >= end)
551
+ return null;
552
+ return squashSlash(text.slice(start, end));
553
+ }
554
+ function squashSlash(name) {
555
+ return name.replace(/\/{2,}/g, '/');
556
+ }
557
+ const C_ESCAPES = { a: 7, b: 8, f: 12, n: 10, r: 13, t: 9, v: 11, '\\': 92, '"': 34 };
558
+ /**
559
+ * git's unquote_c_style for a name that starts with '"': the bytes it spells, decoded as UTF-8, and the index after
560
+ * its closing quote; null for an escape git does not accept. git reads past the end of the line for the closing
561
+ * quote, so a quote that does not close on its line refuses the patch rather than guess. A name that decodes to a
562
+ * NUL byte, from an escape (\000) or a literal NUL inside the quotes, refuses the patch too: git reads a name as a
563
+ * NUL-terminated C string, and its consumers read what comes after the NUL inconsistently (strcmp/strncmp/strchr
564
+ * stop at it, skip_tree_prefix scans across it), so the admission cannot model which bytes git keeps. git's own
565
+ * diff never writes a NUL in a path.
566
+ */
567
+ function unquoteCStyle(text) {
568
+ const bytes = [];
569
+ let index = 1;
570
+ while (index < text.length) {
571
+ const ch = text[index];
572
+ if (ch === '"') {
573
+ if (bytes.includes(0)) {
574
+ throw new Error(`apply_patch: refusing ${JSON.stringify(text.slice(0, index + 1))}: a path cannot contain a NUL byte`);
575
+ }
576
+ return { value: Buffer.from(bytes).toString('utf8'), end: index + 1 };
577
+ }
578
+ if (ch !== '\\') {
579
+ const point = text.codePointAt(index);
580
+ const char = String.fromCodePoint(point);
581
+ bytes.push(...Buffer.from(char, 'utf8'));
582
+ index += char.length;
583
+ continue;
584
+ }
585
+ const escaped = text[index + 1];
586
+ if (escaped !== undefined && Object.hasOwn(C_ESCAPES, escaped)) {
587
+ bytes.push(C_ESCAPES[escaped]);
588
+ index += 2;
589
+ continue;
590
+ }
591
+ const octal = text.slice(index + 1, index + 4);
592
+ if (!/^[0-3][0-7][0-7]$/.test(octal))
593
+ return null;
594
+ bytes.push(parseInt(octal, 8));
595
+ index += 4;
596
+ }
597
+ throw new Error(`apply_patch: a quoted path in the diff does not close on its line: ${JSON.stringify(text)}`);
113
598
  }
114
599
  function patchedFile(path, before, after) {
115
600
  if (after === null)
116
601
  return { path, change: 'deleted' };
117
- if (before === null)
118
- return { path, change: 'added', lines: fileLines(after).length };
119
- const view = describeEdit(before, after);
602
+ const change = before === null ? 'added' : 'updated';
603
+ if (after.kind === 'link')
604
+ return { path, change, link: after.target };
605
+ if (after.kind === 'other')
606
+ return { path, change };
607
+ if (before === null || before.kind !== 'file')
608
+ return { path, change, lines: fileLines(after.text).length };
609
+ const view = describeEdit(before.text, after.text);
120
610
  return { path, change: 'updated', ...(view === null ? {} : { view }) };
121
611
  }
122
- async function readIfPresent(files, path) {
123
- return await files.exists(path) ? files.read(path) : null;
612
+ /**
613
+ * The host side of PatchFiles.inspect: opened without following a final symlink and without blocking (a FIFO with
614
+ * no writer would wait forever), and read only when it is a regular file.
615
+ */
616
+ async function inspectHostPath(path) {
617
+ let handle;
618
+ try {
619
+ handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
620
+ }
621
+ catch (error) {
622
+ const code = error.code;
623
+ if (code === 'ENOENT' || code === 'ENOTDIR')
624
+ return null;
625
+ const info = await lstat(path).catch(() => null);
626
+ if (info === null)
627
+ throw error;
628
+ if (info.isSymbolicLink())
629
+ return { kind: 'link', target: await readlink(path) };
630
+ if (!info.isFile())
631
+ return { kind: 'other' };
632
+ throw error;
633
+ }
634
+ try {
635
+ const info = await handle.stat();
636
+ return info.isFile() ? { kind: 'file', text: await handle.readFile('utf8') } : { kind: 'other' };
637
+ }
638
+ finally {
639
+ await handle.close();
640
+ }
124
641
  }
125
642
  function hostFiles(cwd) {
126
643
  return {
@@ -136,12 +653,24 @@ function hostFiles(cwd) {
136
653
  return false;
137
654
  }
138
655
  },
656
+ inspect: inspectHostPath,
139
657
  read: path => readFile(path, 'utf-8'),
140
658
  write: async (path, content) => {
141
659
  await mkdir(dirname(path), { recursive: true });
142
660
  await writeFileAtomic(path, content);
143
661
  },
144
662
  remove: path => unlink(path),
663
+ sameFile: async (a, b) => {
664
+ if (a === b)
665
+ return true;
666
+ try {
667
+ const [first, second] = await Promise.all([lstat(a), lstat(b)]);
668
+ return first.dev === second.dev && first.ino === second.ino;
669
+ }
670
+ catch {
671
+ return false;
672
+ }
673
+ },
145
674
  };
146
675
  }
147
676
  function containerFiles(docker) {
@@ -152,46 +681,61 @@ function containerFiles(docker) {
152
681
  return false;
153
682
  throw error;
154
683
  }),
684
+ inspect: async (path) => {
685
+ const { stdout } = await runInContainer(docker, ['sh', '-c', 'if [ -L "$1" ]; then printf L; readlink "$1";'
686
+ + ' elif [ -f "$1" ]; then printf F; cat "$1"; elif [ -e "$1" ]; then printf O; else printf N; fi', 'sh', path]);
687
+ const rest = stdout.slice(1);
688
+ if (stdout.startsWith('L'))
689
+ return { kind: 'link', target: rest.replace(/\n$/, '') };
690
+ if (stdout.startsWith('F'))
691
+ return { kind: 'file', text: rest };
692
+ return stdout.startsWith('O') ? { kind: 'other' } : null;
693
+ },
155
694
  read: async (path) => (await runInContainer(docker, ['cat', '--', path])).stdout,
156
695
  write: (path, content) => writeContainerFile(docker, path, content),
157
696
  remove: async (path) => { await runInContainer(docker, ['rm', '--', path]); },
697
+ sameFile: (a, b) => a === b ? Promise.resolve(true)
698
+ : runInContainer(docker, ['sh', '-c', '[ "$1" -ef "$2" ]', 'sh', a, b]).then(() => true, (error) => {
699
+ if (error instanceof DockerCommandError && error.exitCode === 1)
700
+ return false;
701
+ throw error;
702
+ }),
158
703
  };
159
704
  }
160
- async function applyStructuredPatch(patch, files) {
161
- const operations = parseStructuredPatch(patch);
162
- const changed = new Set();
163
- const patched = [];
164
- // Whether any operation changed bytes. An identity hunk (`-x` then `+x`) is a
165
- // silent no-op that used to report success identically to a real edit.
166
- let contentChanged = false;
167
- for (const operation of operations) {
168
- if (operation.kind === 'add') {
169
- const target = files.resolve(operation.path);
170
- // Match git-apply semantics: 'Add File' must not clobber an existing file.
171
- if (await files.exists(target)) {
172
- throw new Error(`apply_patch: cannot Add File ${operation.path}: already exists (use Update File)`);
705
+ async function applyStructuredPatch(operations, files, targets, admit) {
706
+ // Read-modify-write under the per-path locks of every file the patch names, write atomically, verify: a sibling
707
+ // tool call in the same response must not interleave between a read and its write.
708
+ return withPathLocks(targets.map(target => target.path), async () => {
709
+ await admit();
710
+ const changed = new Set();
711
+ const patched = [];
712
+ // Whether any operation changed bytes. An identity hunk (`-x` then `+x`) is a
713
+ // silent no-op that used to report success identically to a real edit.
714
+ let contentChanged = false;
715
+ for (const operation of operations) {
716
+ if (operation.kind === 'add') {
717
+ const target = files.resolve(operation.path);
718
+ // Match git-apply semantics: 'Add File' must not clobber an existing file.
719
+ if (await files.exists(target)) {
720
+ throw new Error(`apply_patch: cannot Add File ${operation.path}: already exists (use Update File)`);
721
+ }
722
+ const content = `${operation.lines.join('\n')}${operation.lines.length ? '\n' : ''}`;
723
+ await files.write(target, content);
724
+ contentChanged = true;
725
+ changed.add(operation.path);
726
+ patched.push(patchedFile(target, null, { kind: 'file', text: content }));
727
+ continue;
173
728
  }
174
- const content = `${operation.lines.join('\n')}${operation.lines.length ? '\n' : ''}`;
175
- await withPathLock(target, () => files.write(target, content));
176
- contentChanged = true;
177
- changed.add(operation.path);
178
- patched.push(patchedFile(target, null, content));
179
- continue;
180
- }
181
- if (operation.kind === 'delete') {
182
- const target = files.resolve(operation.path);
183
- await withPathLock(target, () => files.remove(target));
184
- contentChanged = true;
185
- changed.add(operation.path);
186
- patched.push(patchedFile(target, '', null));
187
- continue;
188
- }
189
- const sourcePath = files.resolve(operation.path);
190
- const targetPath = operation.moveTo ? files.resolve(operation.moveTo) : sourcePath;
191
- // Read-modify-write under the per-path lock, write atomically, verify: a
192
- // sibling tool call in the same response must not interleave between the
193
- // read and the write.
194
- await withPathLock(sourcePath, async () => {
729
+ if (operation.kind === 'delete') {
730
+ const target = files.resolve(operation.path);
731
+ await files.remove(target);
732
+ contentChanged = true;
733
+ changed.add(operation.path);
734
+ patched.push(patchedFile(target, { kind: 'file', text: '' }, null));
735
+ continue;
736
+ }
737
+ const sourcePath = files.resolve(operation.path);
738
+ const targetPath = operation.moveTo ? files.resolve(operation.moveTo) : sourcePath;
195
739
  const original = await files.read(sourcePath);
196
740
  const next = applyStructuredHunks(original, operation.hunks);
197
741
  await files.write(targetPath, next);
@@ -201,24 +745,39 @@ async function applyStructuredPatch(patch, files) {
201
745
  }
202
746
  if (onDisk !== original)
203
747
  contentChanged = true;
204
- patched.push(patchedFile(targetPath, original, next));
205
- });
206
- if (operation.moveTo) {
207
- await files.remove(sourcePath).catch(() => undefined);
208
- changed.add(operation.moveTo);
748
+ patched.push(patchedFile(targetPath, { kind: 'file', text: original }, { kind: 'file', text: next }));
749
+ // A move onto the source's own file (./a.txt, or A.txt where names ignore case) leaves nothing to remove.
750
+ if (operation.moveTo && !(await files.sameFile(sourcePath, targetPath))) {
751
+ await files.remove(sourcePath).catch(() => undefined);
752
+ }
753
+ if (operation.moveTo)
754
+ changed.add(operation.moveTo);
755
+ changed.add(operation.path);
209
756
  }
210
- changed.add(operation.path);
757
+ const paths = [...changed].map(path => files.resolve(path));
758
+ return {
759
+ path: paths[0] || files.resolve('.'),
760
+ paths,
761
+ action: 'patched',
762
+ changed: contentChanged,
763
+ stdout: '',
764
+ stderr: '',
765
+ files: patched,
766
+ };
767
+ });
768
+ }
769
+ /**
770
+ * A header's path, refused when it cannot name a file: empty, or holding a NUL byte, which no file name holds (a
771
+ * component like `a\0` only disappears when a later `..` removes it). A backslash is an ordinary character on POSIX,
772
+ * where `..\x` is one file of that name, and a separator on Windows; admission and the write resolve it alike.
773
+ */
774
+ function headerPath(header, path) {
775
+ if (!path)
776
+ throw new Error(`apply_patch: *** ${header}: needs a path`);
777
+ if (path.includes('\0')) {
778
+ throw new Error(`apply_patch: refusing *** ${header}: ${JSON.stringify(path)}: a path cannot contain a NUL byte`);
211
779
  }
212
- const paths = [...changed].map(path => files.resolve(path));
213
- return {
214
- path: paths[0] || files.resolve('.'),
215
- paths,
216
- action: 'patched',
217
- changed: contentChanged,
218
- stdout: '',
219
- stderr: '',
220
- files: patched,
221
- };
780
+ return path;
222
781
  }
223
782
  function parseStructuredPatch(patch) {
224
783
  const lines = patch.split(/\r?\n/);
@@ -227,7 +786,7 @@ function parseStructuredPatch(patch) {
227
786
  while (i < lines.length) {
228
787
  const line = lines[i];
229
788
  if (line.startsWith('*** Add File: ')) {
230
- const path = line.slice('*** Add File: '.length).trim();
789
+ const path = headerPath('Add File', line.slice('*** Add File: '.length).trim());
231
790
  i += 1;
232
791
  const body = [];
233
792
  while (i < lines.length && !lines[i].startsWith('*** ') && !lines[i].startsWith('@@')) {
@@ -240,19 +799,21 @@ function parseStructuredPatch(patch) {
240
799
  continue;
241
800
  }
242
801
  if (line.startsWith('*** Delete File: ')) {
243
- operations.push({ kind: 'delete', path: line.slice('*** Delete File: '.length).trim() });
802
+ operations.push({ kind: 'delete', path: headerPath('Delete File', line.slice('*** Delete File: '.length).trim()) });
244
803
  i += 1;
245
804
  continue;
246
805
  }
247
806
  if (line.startsWith('*** Update File: ')) {
248
- const path = line.slice('*** Update File: '.length).trim();
807
+ const path = headerPath('Update File', line.slice('*** Update File: '.length).trim());
249
808
  i += 1;
250
809
  let moveTo;
251
810
  const hunks = [];
252
811
  let current = [];
253
812
  while (i < lines.length && !lines[i].startsWith('*** Add File: ') && !lines[i].startsWith('*** Delete File: ') && !lines[i].startsWith('*** Update File: ') && !lines[i].startsWith('*** End Patch')) {
254
813
  if (lines[i].startsWith('*** Move to: ')) {
255
- moveTo = lines[i].slice('*** Move to: '.length).trim();
814
+ moveTo = lines[i].slice('*** Move to: '.length).trim() || undefined;
815
+ if (moveTo !== undefined)
816
+ headerPath('Move to', moveTo);
256
817
  }
257
818
  else if (lines[i].startsWith('@@')) {
258
819
  if (current.length > 0) {
@@ -345,17 +906,3 @@ function findLineSequence(lines, needle, start) {
345
906
  }
346
907
  return -1;
347
908
  }
348
- function extractPatchedPaths(patch) {
349
- const paths = new Set();
350
- for (const line of patch.split('\n')) {
351
- if (!line.startsWith('+++ ') && !line.startsWith('--- ')) {
352
- continue;
353
- }
354
- const raw = line.slice(4).trim().split('\t')[0];
355
- if (raw === '/dev/null') {
356
- continue;
357
- }
358
- paths.add(raw.replace(/^[ab]\//, ''));
359
- }
360
- return [...paths];
361
- }