@@ -0,0 +1,285 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { deleteSnapshot, loadSnapshot, saveSnapshot } from "../session/db.ts";
6+import { restoreSnapshot, takeSnapshot } from "./snapshot.ts";
7+
8+// ─── Helpers ──────────────────────────────────────────────────────────────────
9+
10+function spawnSync(args: string[], cwd: string): void {
11+ const proc = Bun.spawnSync(args, { cwd, stdout: "pipe", stderr: "pipe" });
12+ if (proc.exitCode !== 0) {
13+ throw new Error(
14+ `Command failed: ${args.join(" ")}\n${proc.stderr.toString()}`,
15+ );
16+ }
17+}
18+
19+/** Create a minimal git repo in a temp directory and return its path. */
20+function makeRepo(): string {
21+ const dir = join(
22+ tmpdir(),
23+ `mc-snap-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
24+ );
25+ mkdirSync(dir, { recursive: true });
26+ spawnSync(["git", "init"], dir);
27+ spawnSync(["git", "config", "user.email", "test@example.com"], dir);
28+ spawnSync(["git", "config", "user.name", "Test"], dir);
29+ // Initial commit so HEAD exists
30+ writeFileSync(join(dir, "README.md"), "hello\n");
31+ spawnSync(["git", "add", "README.md"], dir);
32+ spawnSync(["git", "commit", "-m", "init"], dir);
33+ return dir;
34+}
35+
36+function cleanRepo(dir: string): void {
37+ rmSync(dir, { recursive: true, force: true });
38+}
39+
40+// ─── db helpers ───────────────────────────────────────────────────────────────
41+
42+describe("saveSnapshot / loadSnapshot / deleteSnapshot", () => {
43+ test("round-trips file entries", () => {
44+ const sessionId = crypto.randomUUID();
45+ const turnIndex = 42;
46+ const content = new TextEncoder().encode("hello world");
47+
48+ saveSnapshot(sessionId, turnIndex, [
49+ { path: "src/foo.ts", content, existed: true },
50+ { path: "src/new.ts", content: null, existed: false },
51+ ]);
52+
53+ const rows = loadSnapshot(sessionId, turnIndex);
54+ expect(rows).toHaveLength(2);
55+
56+ const foo = rows.find((r) => r.path === "src/foo.ts");
57+ expect(foo?.existed).toBe(true);
58+ expect(foo?.content).toEqual(content);
59+
60+ const newFile = rows.find((r) => r.path === "src/new.ts");
61+ expect(newFile?.existed).toBe(false);
62+ expect(newFile?.content).toBeNull();
63+
64+ // Cleanup
65+ deleteSnapshot(sessionId, turnIndex);
66+ expect(loadSnapshot(sessionId, turnIndex)).toHaveLength(0);
67+ });
68+});
69+
70+// ─── takeSnapshot ─────────────────────────────────────────────────────────────
71+
72+describe("takeSnapshot", () => {
73+ let repoDir: string;
74+ const sessionId = crypto.randomUUID();
75+
76+ beforeEach(() => {
77+ repoDir = makeRepo();
78+ });
79+
80+ afterEach(() => {
81+ cleanRepo(repoDir);
82+ });
83+
84+ test("returns false on a clean working tree", async () => {
85+ const result = await takeSnapshot(repoDir, sessionId, 1);
86+ expect(result).toBe(false);
87+ });
88+
89+ test("returns false for a non-git directory", async () => {
90+ const nonGit = join(tmpdir(), `mc-nongit-${Date.now()}`);
91+ mkdirSync(nonGit, { recursive: true });
92+ try {
93+ const result = await takeSnapshot(nonGit, sessionId, 2);
94+ expect(result).toBe(false);
95+ } finally {
96+ rmSync(nonGit, { recursive: true, force: true });
97+ }
98+ });
99+
100+ test("snapshots a modified tracked file", async () => {
101+ const filePath = join(repoDir, "README.md");
102+ writeFileSync(filePath, "modified content\n");
103+
104+ const result = await takeSnapshot(repoDir, sessionId, 3);
105+ expect(result).toBe(true);
106+
107+ const rows = loadSnapshot(sessionId, 3);
108+ const readme = rows.find((r) => r.path === "README.md");
109+ expect(readme).toBeDefined();
110+ expect(readme?.existed).toBe(true);
111+ expect(new TextDecoder().decode(readme?.content ?? undefined)).toBe(
112+ "modified content\n",
113+ );
114+
115+ deleteSnapshot(sessionId, 3);
116+ });
117+
118+ test("snapshots an untracked new file with existed=false", async () => {
119+ writeFileSync(join(repoDir, "untracked.txt"), "brand new\n");
120+
121+ const result = await takeSnapshot(repoDir, sessionId, 4);
122+ expect(result).toBe(true);
123+
124+ const rows = loadSnapshot(sessionId, 4);
125+ const f = rows.find((r) => r.path === "untracked.txt");
126+ expect(f).toBeDefined();
127+ // Untracked files are new — on undo they should be deleted, not written back
128+ expect(f?.existed).toBe(false);
129+
130+ deleteSnapshot(sessionId, 4);
131+ });
132+
133+ test("snapshots files inside a new untracked directory", async () => {
134+ // Without -u, git collapses new dirs to a single "?? dir/" entry.
135+ // With -u, each file inside is listed individually.
136+ mkdirSync(join(repoDir, "src"), { recursive: true });
137+ writeFileSync(join(repoDir, "src", "a.ts"), "export const a = 1;\n");
138+ writeFileSync(join(repoDir, "src", "b.ts"), "export const b = 2;\n");
139+
140+ const result = await takeSnapshot(repoDir, sessionId, 5);
141+ expect(result).toBe(true);
142+
143+ const rows = loadSnapshot(sessionId, 5);
144+ const a = rows.find((r) => r.path === "src/a.ts");
145+ const b = rows.find((r) => r.path === "src/b.ts");
146+ expect(a).toBeDefined();
147+ expect(b).toBeDefined();
148+ expect(a?.existed).toBe(false);
149+ expect(b?.existed).toBe(false);
150+
151+ deleteSnapshot(sessionId, 5);
152+ });
153+
154+ test("snapshots a renamed file correctly", async () => {
155+ // Commit a file so it's tracked, then rename it
156+ writeFileSync(join(repoDir, "old-name.ts"), "export const x = 1;\n");
157+ spawnSync(["git", "add", "old-name.ts"], repoDir);
158+ spawnSync(["git", "commit", "-m", "add file"], repoDir);
159+
160+ // Rename tracked file
161+ spawnSync(["git", "mv", "old-name.ts", "new-name.ts"], repoDir);
162+
163+ const result = await takeSnapshot(repoDir, sessionId, 6);
164+ expect(result).toBe(true);
165+
166+ const rows = loadSnapshot(sessionId, 6);
167+ // Old path: was deleted — should have existed=true with content
168+ const oldEntry = rows.find((r) => r.path === "old-name.ts");
169+ expect(oldEntry).toBeDefined();
170+ expect(oldEntry?.existed).toBe(true);
171+ expect(oldEntry?.content).not.toBeNull();
172+
173+ // New path: brand new on disk — should have existed=false
174+ const newEntry = rows.find((r) => r.path === "new-name.ts");
175+ expect(newEntry).toBeDefined();
176+ expect(newEntry?.existed).toBe(false);
177+
178+ deleteSnapshot(sessionId, 6);
179+ });
180+
181+ test("does not affect git status after snapshotting", async () => {
182+ writeFileSync(join(repoDir, "README.md"), "changed\n");
183+
184+ await takeSnapshot(repoDir, sessionId, 5);
185+
186+ // git status should still show the modification — nothing was stashed
187+ const proc = Bun.spawnSync(["git", "status", "--porcelain"], {
188+ cwd: repoDir,
189+ stdout: "pipe",
190+ stderr: "pipe",
191+ });
192+ const statusOut = proc.stdout.toString();
193+ expect(statusOut).toContain("README.md");
194+
195+ deleteSnapshot(sessionId, 5);
196+ });
197+});
198+
199+// ─── restoreSnapshot ──────────────────────────────────────────────────────────
200+
201+describe("restoreSnapshot", () => {
202+ let repoDir: string;
203+ const sessionId = crypto.randomUUID();
204+
205+ beforeEach(() => {
206+ repoDir = makeRepo();
207+ });
208+
209+ afterEach(() => {
210+ cleanRepo(repoDir);
211+ });
212+
213+ test("returns not-found when no snapshot exists", async () => {
214+ const result = await restoreSnapshot(repoDir, sessionId, 99);
215+ expect(result.restored).toBe(false);
216+ if (!result.restored) expect(result.reason).toBe("not-found");
217+ });
218+
219+ test("restores a modified file to its pre-turn content", async () => {
220+ const filePath = join(repoDir, "README.md");
221+ const originalContent = "hello\n";
222+ // File was already "hello\n" from makeRepo; now simulate a pre-turn snapshot
223+ saveSnapshot(sessionId, 10, [
224+ {
225+ path: "README.md",
226+ content: new TextEncoder().encode(originalContent),
227+ existed: true,
228+ },
229+ ]);
230+
231+ // Agent modifies the file
232+ writeFileSync(filePath, "agent changed this\n");
233+
234+ // Undo: restore
235+ const result = await restoreSnapshot(repoDir, sessionId, 10);
236+ expect(result.restored).toBe(true);
237+
238+ const restoredContent = await Bun.file(filePath).text();
239+ expect(restoredContent).toBe(originalContent);
240+
241+ // Snapshot should be cleaned up
242+ expect(loadSnapshot(sessionId, 10)).toHaveLength(0);
243+ });
244+
245+ test("deletes a file that was created by the agent (existed=false)", async () => {
246+ const newFile = join(repoDir, "agent-created.ts");
247+ writeFileSync(newFile, "export const x = 1;\n");
248+
249+ // Snapshot says this file did NOT exist before the turn
250+ saveSnapshot(sessionId, 11, [
251+ { path: "agent-created.ts", content: null, existed: false },
252+ ]);
253+
254+ const result = await restoreSnapshot(repoDir, sessionId, 11);
255+ expect(result.restored).toBe(true);
256+
257+ const exists = await Bun.file(newFile).exists();
258+ expect(exists).toBe(false);
259+
260+ expect(loadSnapshot(sessionId, 11)).toHaveLength(0);
261+ });
262+
263+ test("end-to-end: takeSnapshot then agent creates file, restoreSnapshot deletes it", async () => {
264+ // Working tree is clean before the turn — nothing to snapshot
265+ const snapped = await takeSnapshot(repoDir, sessionId, 12);
266+ expect(snapped).toBe(false);
267+
268+ // Agent creates a new file mid-turn
269+ const agentFile = join(repoDir, "generated.ts");
270+ writeFileSync(agentFile, "export const y = 2;\n");
271+
272+ // Now snapshot captures the untracked file with existed=false
273+ const snapped2 = await takeSnapshot(repoDir, sessionId, 13);
274+ expect(snapped2).toBe(true);
275+
276+ const rows = loadSnapshot(sessionId, 13);
277+ const entry = rows.find((r) => r.path === "generated.ts");
278+ expect(entry?.existed).toBe(false);
279+
280+ // Restore: should delete the agent-created file
281+ const result = await restoreSnapshot(repoDir, sessionId, 13);
282+ expect(result.restored).toBe(true);
283+ expect(await Bun.file(agentFile).exists()).toBe(false);
284+ });
285+});