chatccc 0.2.230 → 0.2.232

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.
@@ -1,10 +1,12 @@
1
- import { mkdtemp, readFile } from "node:fs/promises";
1
+ import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
 
5
5
  import { describe, expect, it } from "vitest";
6
6
 
7
7
  import {
8
+ buildPersistedAssistantMessage,
9
+ buildSummaryPrompt,
8
10
  BuiltinContextManager,
9
11
  estimateBuiltinContextTokens,
10
12
  listBuiltinContextSessions,
@@ -13,6 +15,43 @@ import {
13
15
  } from "../builtin/context.ts";
14
16
 
15
17
  describe("BuiltinContextManager", () => {
18
+ it("keeps recent messages within the token budget instead of a fixed count", () => {
19
+ const context = new BuiltinContextManager({
20
+ compactAtTokens: 300,
21
+ keepRecentMessages: 16,
22
+ persist: false,
23
+ });
24
+ for (let index = 0; index < 8; index += 1) {
25
+ context.appendMessage({
26
+ role: index % 2 === 0 ? "user" : "assistant",
27
+ content: `${index}:` + "x".repeat(400),
28
+ });
29
+ }
30
+
31
+ const plan = context.planCompaction();
32
+
33
+ expect(plan).not.toBeNull();
34
+ expect(plan!.recentMessages.length).toBeLessThan(8);
35
+ expect(plan!.recentMessages.at(-1)?.content).toContain("7:");
36
+ expect(estimateBuiltinContextTokens("", plan!.recentMessages)).toBeLessThanOrEqual(300);
37
+ });
38
+
39
+ it("bounds oversized source material sent to the compaction model", () => {
40
+ const context = new BuiltinContextManager({
41
+ compactAtTokens: 100,
42
+ keepRecentMessages: 1,
43
+ persist: false,
44
+ });
45
+ context.setSummary("previous ".repeat(30_000));
46
+ context.appendMessage({ role: "assistant", content: "a".repeat(200_000) });
47
+ context.appendMessage({ role: "user", content: "latest request" });
48
+
49
+ const prompt = buildSummaryPrompt(context.planCompaction()!);
50
+
51
+ expect(prompt.length).toBeLessThan(90_000);
52
+ expect(prompt).toContain("truncated for compaction");
53
+ });
54
+
16
55
  it("persists and restores summary, messages, and total message count", async () => {
17
56
  const dir = await mkdtemp(join(tmpdir(), "chatccc-builtin-context-"));
18
57
 
@@ -42,10 +81,11 @@ describe("BuiltinContextManager", () => {
42
81
 
43
82
  it("selects only older messages for compaction and keeps recent messages raw", () => {
44
83
  const context = new BuiltinContextManager({
45
- compactAtTokens: 1,
84
+ compactAtTokens: 100,
46
85
  keepRecentMessages: 2,
47
86
  persist: false,
48
87
  });
88
+ context.setSummary("x".repeat(500));
49
89
  context.appendMessage({ role: "user", content: "旧用户消息" });
50
90
  context.appendMessage({ role: "assistant", content: "旧助手回复" });
51
91
  context.appendMessage({ role: "user", content: "近期用户消息" });
@@ -88,6 +128,122 @@ describe("BuiltinContextManager", () => {
88
128
  ]);
89
129
  });
90
130
 
131
+ it("persists structured tool calls and restores them", async () => {
132
+ const dir = await mkdtemp(join(tmpdir(), "chatccc-builtin-context-tools-"));
133
+
134
+ const first = new BuiltinContextManager({
135
+ persist: true,
136
+ contextDir: dir,
137
+ sessionId: "tool-persisted",
138
+ });
139
+ first.appendMessage({
140
+ role: "assistant",
141
+ content: "回复\n\n[Tool transcript]\ntool_call run_command: {}\ntool_result run_command: {}",
142
+ toolCalls: [
143
+ { name: "run_command", input: "{\"command\":\"npm test\"}", output: "{\"exitCode\":0}" },
144
+ { name: "read_file", input: "{\"path\":\"a.ts\"}", output: "...", is_error: true },
145
+ ],
146
+ });
147
+ first.save();
148
+
149
+ const restored = new BuiltinContextManager({
150
+ persist: true,
151
+ contextDir: dir,
152
+ sessionId: "tool-persisted",
153
+ });
154
+
155
+ expect(restored.messages[0].toolCalls).toEqual([
156
+ { name: "run_command", input: "{\"command\":\"npm test\"}", output: "{\"exitCode\":0}" },
157
+ { name: "read_file", input: "{\"path\":\"a.ts\"}", output: "...", is_error: true },
158
+ ]);
159
+ });
160
+
161
+ it("loads legacy context files without toolCalls and filters malformed entries", async () => {
162
+ const dir = await mkdtemp(join(tmpdir(), "chatccc-builtin-context-legacy-"));
163
+ const state = {
164
+ version: 1,
165
+ createdAt: 1,
166
+ updatedAt: 2,
167
+ sessionId: "legacy",
168
+ summary: "",
169
+ totalMessages: 2,
170
+ compactedMessages: 0,
171
+ messages: [
172
+ { role: "assistant", content: "老消息" },
173
+ {
174
+ role: "assistant",
175
+ content: "带 toolCalls",
176
+ toolCalls: [
177
+ { name: "ok", input: "{\"a\":1}" },
178
+ { name: "" }, // 非法:空 name 应被过滤
179
+ { input: "no-name" }, // 非法:缺 name 应被过滤
180
+ { name: "bad-type", input: 42 }, // 非法:input 非 string 应被忽略字段
181
+ ],
182
+ },
183
+ ],
184
+ };
185
+ await mkdir(join(dir, "legacy"));
186
+ await writeFile(join(dir, "legacy", "context.json"), JSON.stringify(state), "utf8");
187
+
188
+ const restored = new BuiltinContextManager({
189
+ persist: true,
190
+ contextDir: dir,
191
+ sessionId: "legacy",
192
+ });
193
+
194
+ expect(restored.messages[0].toolCalls).toBeUndefined();
195
+ expect(restored.messages[1].toolCalls).toEqual([
196
+ { name: "ok", input: "{\"a\":1}" },
197
+ { name: "bad-type" },
198
+ ]);
199
+ expect(restored.totalMessages).toBe(2);
200
+ });
201
+
202
+ it("builds a persisted assistant message with transcript text plus structured tool calls", () => {
203
+ const message = buildPersistedAssistantMessage({
204
+ fullText: "回复正文",
205
+ transcriptLines: [
206
+ "tool_call run_command: {\"command\":\"npm test\"}",
207
+ "tool_result run_command: {\"exitCode\":0}",
208
+ ],
209
+ toolCalls: [
210
+ { name: "run_command", input: "{\"command\":\"npm test\"}", output: "{\"exitCode\":0}" },
211
+ ],
212
+ });
213
+
214
+ expect(message.role).toBe("assistant");
215
+ expect(message.content).toContain("回复正文");
216
+ expect(message.content).toContain("[Tool transcript]");
217
+ expect(message.content).toContain("tool_call run_command");
218
+ expect(message.toolCalls).toEqual([
219
+ { name: "run_command", input: "{\"command\":\"npm test\"}", output: "{\"exitCode\":0}" },
220
+ ]);
221
+ });
222
+
223
+ it("builds a plain assistant message without tool transcript when no tools ran", () => {
224
+ const message = buildPersistedAssistantMessage({
225
+ fullText: "纯文本回复",
226
+ transcriptLines: [],
227
+ });
228
+
229
+ expect(message.content).toBe("纯文本回复");
230
+ expect(message.content).not.toContain("[Tool transcript]");
231
+ expect(message.toolCalls).toBeUndefined();
232
+ });
233
+
234
+ it("caps both assistant text and tool transcript in persisted messages", () => {
235
+ const message = buildPersistedAssistantMessage({
236
+ fullText: "a".repeat(10_000),
237
+ transcriptLines: Array.from({ length: 12 }, () => "x".repeat(8_000)),
238
+ maxAssistantChars: 2_000,
239
+ maxTranscriptChars: 4_000,
240
+ });
241
+
242
+ expect(message.content.length).toBeLessThan(7_000);
243
+ expect(message.content).toContain("assistant response truncated");
244
+ expect(message.content).toContain("tool transcript truncated");
245
+ });
246
+
91
247
  it("reset clears memory and the persisted context file", async () => {
92
248
  const dir = await mkdtemp(join(tmpdir(), "chatccc-builtin-context-reset-"));
93
249
  const context = new BuiltinContextManager({
@@ -1,240 +1,240 @@
1
- import { execFile } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
4
- import { homedir, tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { promisify } from "node:util";
7
-
8
- import { afterEach, describe, expect, it } from "vitest";
9
-
10
- import {
11
- applyPatchForTool,
12
- createFileForTool,
13
- deleteFileForTool,
14
- editFileForTool,
15
- expandHomePath,
16
- listDirForTool,
17
- moveFileForTool,
18
- readFileForTool,
19
- runCommandForTool,
20
- searchCodeForTool,
21
- } from "../builtin/file-tools.ts";
22
-
23
- const execFileAsync = promisify(execFile);
24
- const tempDirs: string[] = [];
25
-
26
- async function makeTempDir(): Promise<string> {
27
- const dir = await mkdtemp(join(tmpdir(), "deepccc-tools-"));
28
- tempDirs.push(dir);
29
- return dir;
30
- }
31
-
32
- describe("expandHomePath", () => {
33
- it("expands ~ and ~/ (both separators) to the user home directory", () => {
34
- const home = homedir();
35
- expect(expandHomePath("~")).toBe(home);
36
- expect(expandHomePath("~/x/y.txt")).toBe(join(home, "x", "y.txt"));
37
- expect(expandHomePath("~\\x\\y.txt")).toBe(join(home, "x", "y.txt"));
38
- });
39
-
40
- it("leaves absolute paths and other inputs unchanged", () => {
41
- expect(expandHomePath("C:/a/b")).toBe("C:/a/b");
42
- expect(expandHomePath("~other/x")).toBe("~other/x");
43
- expect(expandHomePath("")).toBe("");
44
- });
45
- });
46
-
47
- async function hasRg(): Promise<boolean> {
48
- try {
49
- await execFileAsync("rg", ["--version"]);
50
- return true;
51
- } catch {
52
- return false;
53
- }
54
- }
55
-
56
- function sha256(text: string): string {
57
- return createHash("sha256").update(text).digest("hex");
58
- }
59
-
60
- afterEach(async () => {
61
- await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
62
- });
63
-
64
- describe("DeepCCC file tools", () => {
65
- it("reads a text file with line ranges", async () => {
66
- const dir = await makeTempDir();
67
- await writeFile(join(dir, ".secret.txt"), "one\ntwo\nthree\n", "utf8");
68
-
69
- const result = await readFileForTool(dir, { path: ".secret.txt", startLine: 2, endLine: 3 });
70
-
71
- expect(result).toEqual(expect.objectContaining({
72
- sha256: sha256("one\ntwo\nthree\n"),
73
- isBinary: false,
74
- content: "two\nthree",
75
- startLine: 2,
76
- endLine: 3,
77
- totalLines: 4,
78
- }));
79
- expect(result.path).toContain(".secret.txt");
80
- });
81
-
82
- it("lists directory entries including hidden files", async () => {
83
- const dir = await makeTempDir();
84
- await writeFile(join(dir, ".env"), "TOKEN=x", "utf8");
85
-
86
- const result = await listDirForTool(dir);
87
-
88
- expect(result.entries).toContainEqual(expect.objectContaining({
89
- name: ".env",
90
- type: "file",
91
- }));
92
- });
93
-
94
- it("searches code with rg without using a shell", async () => {
95
- if (!await hasRg()) return;
96
-
97
- const dir = await makeTempDir();
98
- await writeFile(join(dir, "a.ts"), "const marker = 1;\n", "utf8");
99
-
100
- const result = await searchCodeForTool(dir, { query: "marker", glob: "*.ts" });
101
-
102
- expect(result.matches).toEqual([
103
- expect.objectContaining({
104
- line: 1,
105
- text: "const marker = 1;",
106
- }),
107
- ]);
108
- });
109
-
110
- it("runs non-interactive shell commands in the requested cwd", async () => {
111
- const dir = await makeTempDir();
112
-
113
- const result = await runCommandForTool(dir, {
114
- command: "node -e \"process.stdout.write(process.cwd())\"",
115
- timeoutMs: 5_000,
116
- });
117
-
118
- expect(result.exitCode).toBe(0);
119
- expect(result.timedOut).toBe(false);
120
- expect(result.stdout.toLowerCase()).toBe(dir.toLowerCase());
121
- expect(result.stderr).toBe("");
122
- });
123
-
124
- it("returns non-zero command exits without throwing", async () => {
125
- const dir = await makeTempDir();
126
-
127
- const result = await runCommandForTool(dir, {
128
- command: "node -e \"process.stderr.write('failed'); process.exit(7)\"",
129
- timeoutMs: 5_000,
130
- });
131
-
132
- expect(result.exitCode).toBe(7);
133
- expect(result.stderr).toBe("failed");
134
- expect(result.timedOut).toBe(false);
135
- });
136
-
137
- it("edits a file with exact replacements and a SHA-256 precondition", async () => {
138
- const dir = await makeTempDir();
139
- const file = join(dir, "edit.txt");
140
- await writeFile(file, "alpha\nbeta\ngamma\n", "utf8");
141
-
142
- const result = await editFileForTool(dir, {
143
- path: "edit.txt",
144
- expectedSha256: sha256("alpha\nbeta\ngamma\n"),
145
- edits: [{ oldText: "beta", newText: "BETA" }],
146
- });
147
-
148
- expect(result).toEqual(expect.objectContaining({
149
- changed: true,
150
- editsApplied: 1,
151
- beforeSha256: sha256("alpha\nbeta\ngamma\n"),
152
- afterSha256: sha256("alpha\nBETA\ngamma\n"),
153
- }));
154
- await expect(readFile(file, "utf8")).resolves.toBe("alpha\nBETA\ngamma\n");
155
- });
156
-
157
- it("rejects edits when the SHA-256 precondition does not match", async () => {
158
- const dir = await makeTempDir();
159
- await writeFile(join(dir, "edit.txt"), "current\n", "utf8");
160
-
161
- await expect(editFileForTool(dir, {
162
- path: "edit.txt",
163
- expectedSha256: sha256("stale\n"),
164
- edits: [{ oldText: "current", newText: "next" }],
165
- })).rejects.toThrow("SHA-256 mismatch");
166
- });
167
-
168
- it("creates and deletes files", async () => {
169
- const dir = await makeTempDir();
170
-
171
- const created = await createFileForTool(dir, {
172
- path: "created.txt",
173
- content: "created\n",
174
- });
175
- expect(created).toEqual(expect.objectContaining({
176
- changed: true,
177
- afterSha256: sha256("created\n"),
178
- }));
179
- await expect(readFile(join(dir, "created.txt"), "utf8")).resolves.toBe("created\n");
180
-
181
- const deleted = await deleteFileForTool(dir, {
182
- path: "created.txt",
183
- expectedSha256: sha256("created\n"),
184
- });
185
- expect(deleted).toEqual(expect.objectContaining({
186
- deleted: true,
187
- beforeSha256: sha256("created\n"),
188
- }));
189
- await expect(stat(join(dir, "created.txt"))).rejects.toThrow();
190
- });
191
-
192
- it("moves files and creates the destination directory", async () => {
193
- const dir = await makeTempDir();
194
- await writeFile(join(dir, "old.txt"), "move me\n", "utf8");
195
-
196
- const result = await moveFileForTool(dir, {
197
- sourcePath: "old.txt",
198
- destinationPath: "nested/new.txt",
199
- expectedSourceSha256: sha256("move me\n"),
200
- });
201
-
202
- expect(result).toEqual(expect.objectContaining({
203
- moved: true,
204
- sourceSha256: sha256("move me\n"),
205
- }));
206
- await expect(stat(join(dir, "old.txt"))).rejects.toThrow();
207
- await expect(readFile(join(dir, "nested", "new.txt"), "utf8")).resolves.toBe("move me\n");
208
- });
209
-
210
- it("applies a unified diff patch", async () => {
211
- const dir = await makeTempDir();
212
- await writeFile(join(dir, "patch.txt"), "one\ntwo\nthree\n", "utf8");
213
-
214
- const result = await applyPatchForTool(dir, {
215
- patch: [
216
- "--- a/patch.txt",
217
- "+++ b/patch.txt",
218
- "@@ -1,4 +1,4 @@",
219
- " one",
220
- "-two",
221
- "+TWO",
222
- " three",
223
- " ",
224
- "",
225
- ].join("\n"),
226
- expectedSha256ByPath: {
227
- "patch.txt": sha256("one\ntwo\nthree\n"),
228
- },
229
- });
230
-
231
- expect(result.changedFiles).toEqual([
232
- expect.objectContaining({
233
- action: "edit",
234
- beforeSha256: sha256("one\ntwo\nthree\n"),
235
- afterSha256: sha256("one\nTWO\nthree\n"),
236
- }),
237
- ]);
238
- await expect(readFile(join(dir, "patch.txt"), "utf8")).resolves.toBe("one\nTWO\nthree\n");
239
- });
240
- });
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { promisify } from "node:util";
7
+
8
+ import { afterEach, describe, expect, it } from "vitest";
9
+
10
+ import {
11
+ applyPatchForTool,
12
+ createFileForTool,
13
+ deleteFileForTool,
14
+ editFileForTool,
15
+ expandHomePath,
16
+ listDirForTool,
17
+ moveFileForTool,
18
+ readFileForTool,
19
+ runCommandForTool,
20
+ searchCodeForTool,
21
+ } from "../builtin/file-tools.ts";
22
+
23
+ const execFileAsync = promisify(execFile);
24
+ const tempDirs: string[] = [];
25
+
26
+ async function makeTempDir(): Promise<string> {
27
+ const dir = await mkdtemp(join(tmpdir(), "deepccc-tools-"));
28
+ tempDirs.push(dir);
29
+ return dir;
30
+ }
31
+
32
+ describe("expandHomePath", () => {
33
+ it("expands ~ and ~/ (both separators) to the user home directory", () => {
34
+ const home = homedir();
35
+ expect(expandHomePath("~")).toBe(home);
36
+ expect(expandHomePath("~/x/y.txt")).toBe(join(home, "x", "y.txt"));
37
+ expect(expandHomePath("~\\x\\y.txt")).toBe(join(home, "x", "y.txt"));
38
+ });
39
+
40
+ it("leaves absolute paths and other inputs unchanged", () => {
41
+ expect(expandHomePath("C:/a/b")).toBe("C:/a/b");
42
+ expect(expandHomePath("~other/x")).toBe("~other/x");
43
+ expect(expandHomePath("")).toBe("");
44
+ });
45
+ });
46
+
47
+ async function hasRg(): Promise<boolean> {
48
+ try {
49
+ await execFileAsync("rg", ["--version"]);
50
+ return true;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ function sha256(text: string): string {
57
+ return createHash("sha256").update(text).digest("hex");
58
+ }
59
+
60
+ afterEach(async () => {
61
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
62
+ });
63
+
64
+ describe("DeepCCC file tools", () => {
65
+ it("reads a text file with line ranges", async () => {
66
+ const dir = await makeTempDir();
67
+ await writeFile(join(dir, ".secret.txt"), "one\ntwo\nthree\n", "utf8");
68
+
69
+ const result = await readFileForTool(dir, { path: ".secret.txt", startLine: 2, endLine: 3 });
70
+
71
+ expect(result).toEqual(expect.objectContaining({
72
+ sha256: sha256("one\ntwo\nthree\n"),
73
+ isBinary: false,
74
+ content: "two\nthree",
75
+ startLine: 2,
76
+ endLine: 3,
77
+ totalLines: 4,
78
+ }));
79
+ expect(result.path).toContain(".secret.txt");
80
+ });
81
+
82
+ it("lists directory entries including hidden files", async () => {
83
+ const dir = await makeTempDir();
84
+ await writeFile(join(dir, ".env"), "TOKEN=x", "utf8");
85
+
86
+ const result = await listDirForTool(dir);
87
+
88
+ expect(result.entries).toContainEqual(expect.objectContaining({
89
+ name: ".env",
90
+ type: "file",
91
+ }));
92
+ });
93
+
94
+ it("searches code with rg without using a shell", async () => {
95
+ if (!await hasRg()) return;
96
+
97
+ const dir = await makeTempDir();
98
+ await writeFile(join(dir, "a.ts"), "const marker = 1;\n", "utf8");
99
+
100
+ const result = await searchCodeForTool(dir, { query: "marker", glob: "*.ts" });
101
+
102
+ expect(result.matches).toEqual([
103
+ expect.objectContaining({
104
+ line: 1,
105
+ text: "const marker = 1;",
106
+ }),
107
+ ]);
108
+ });
109
+
110
+ it("runs non-interactive shell commands in the requested cwd", async () => {
111
+ const dir = await makeTempDir();
112
+
113
+ const result = await runCommandForTool(dir, {
114
+ command: "node -e \"process.stdout.write(process.cwd())\"",
115
+ timeoutMs: 5_000,
116
+ });
117
+
118
+ expect(result.exitCode).toBe(0);
119
+ expect(result.timedOut).toBe(false);
120
+ expect(result.stdout.toLowerCase()).toBe(dir.toLowerCase());
121
+ expect(result.stderr).toBe("");
122
+ });
123
+
124
+ it("returns non-zero command exits without throwing", async () => {
125
+ const dir = await makeTempDir();
126
+
127
+ const result = await runCommandForTool(dir, {
128
+ command: "node -e \"process.stderr.write('failed'); process.exit(7)\"",
129
+ timeoutMs: 5_000,
130
+ });
131
+
132
+ expect(result.exitCode).toBe(7);
133
+ expect(result.stderr).toBe("failed");
134
+ expect(result.timedOut).toBe(false);
135
+ });
136
+
137
+ it("edits a file with exact replacements and a SHA-256 precondition", async () => {
138
+ const dir = await makeTempDir();
139
+ const file = join(dir, "edit.txt");
140
+ await writeFile(file, "alpha\nbeta\ngamma\n", "utf8");
141
+
142
+ const result = await editFileForTool(dir, {
143
+ path: "edit.txt",
144
+ expectedSha256: sha256("alpha\nbeta\ngamma\n"),
145
+ edits: [{ oldText: "beta", newText: "BETA" }],
146
+ });
147
+
148
+ expect(result).toEqual(expect.objectContaining({
149
+ changed: true,
150
+ editsApplied: 1,
151
+ beforeSha256: sha256("alpha\nbeta\ngamma\n"),
152
+ afterSha256: sha256("alpha\nBETA\ngamma\n"),
153
+ }));
154
+ await expect(readFile(file, "utf8")).resolves.toBe("alpha\nBETA\ngamma\n");
155
+ });
156
+
157
+ it("rejects edits when the SHA-256 precondition does not match", async () => {
158
+ const dir = await makeTempDir();
159
+ await writeFile(join(dir, "edit.txt"), "current\n", "utf8");
160
+
161
+ await expect(editFileForTool(dir, {
162
+ path: "edit.txt",
163
+ expectedSha256: sha256("stale\n"),
164
+ edits: [{ oldText: "current", newText: "next" }],
165
+ })).rejects.toThrow("SHA-256 mismatch");
166
+ });
167
+
168
+ it("creates and deletes files", async () => {
169
+ const dir = await makeTempDir();
170
+
171
+ const created = await createFileForTool(dir, {
172
+ path: "created.txt",
173
+ content: "created\n",
174
+ });
175
+ expect(created).toEqual(expect.objectContaining({
176
+ changed: true,
177
+ afterSha256: sha256("created\n"),
178
+ }));
179
+ await expect(readFile(join(dir, "created.txt"), "utf8")).resolves.toBe("created\n");
180
+
181
+ const deleted = await deleteFileForTool(dir, {
182
+ path: "created.txt",
183
+ expectedSha256: sha256("created\n"),
184
+ });
185
+ expect(deleted).toEqual(expect.objectContaining({
186
+ deleted: true,
187
+ beforeSha256: sha256("created\n"),
188
+ }));
189
+ await expect(stat(join(dir, "created.txt"))).rejects.toThrow();
190
+ });
191
+
192
+ it("moves files and creates the destination directory", async () => {
193
+ const dir = await makeTempDir();
194
+ await writeFile(join(dir, "old.txt"), "move me\n", "utf8");
195
+
196
+ const result = await moveFileForTool(dir, {
197
+ sourcePath: "old.txt",
198
+ destinationPath: "nested/new.txt",
199
+ expectedSourceSha256: sha256("move me\n"),
200
+ });
201
+
202
+ expect(result).toEqual(expect.objectContaining({
203
+ moved: true,
204
+ sourceSha256: sha256("move me\n"),
205
+ }));
206
+ await expect(stat(join(dir, "old.txt"))).rejects.toThrow();
207
+ await expect(readFile(join(dir, "nested", "new.txt"), "utf8")).resolves.toBe("move me\n");
208
+ });
209
+
210
+ it("applies a unified diff patch", async () => {
211
+ const dir = await makeTempDir();
212
+ await writeFile(join(dir, "patch.txt"), "one\ntwo\nthree\n", "utf8");
213
+
214
+ const result = await applyPatchForTool(dir, {
215
+ patch: [
216
+ "--- a/patch.txt",
217
+ "+++ b/patch.txt",
218
+ "@@ -1,4 +1,4 @@",
219
+ " one",
220
+ "-two",
221
+ "+TWO",
222
+ " three",
223
+ " ",
224
+ "",
225
+ ].join("\n"),
226
+ expectedSha256ByPath: {
227
+ "patch.txt": sha256("one\ntwo\nthree\n"),
228
+ },
229
+ });
230
+
231
+ expect(result.changedFiles).toEqual([
232
+ expect.objectContaining({
233
+ action: "edit",
234
+ beforeSha256: sha256("one\ntwo\nthree\n"),
235
+ afterSha256: sha256("one\nTWO\nthree\n"),
236
+ }),
237
+ ]);
238
+ await expect(readFile(join(dir, "patch.txt"), "utf8")).resolves.toBe("one\nTWO\nthree\n");
239
+ });
240
+ });