xonecas.io
64875
Mc

mini-coder / commit 389da5a

feat: replace git stash snapshots with SQLite-based file snapshots for /undo

Snapshots now store dirty file contents in the app's SQLite database instead
of using git stash. This makes the snapshot mechanism completely invisible to
the user — no stash entries appear in git stash list, git status is never
disturbed, and the user's working tree is untouched between turns.

Key changes:
- Add snapshots table (DB_VERSION 3) with saveSnapshot/loadSnapshot/deleteAllSnapshots helpers
- New src/tools/snapshot.ts: takeSnapshot reads dirty files via git status --porcelain -z -u
  (handling modified, deleted, renamed, untracked, and new directories), restoreSnapshot
  writes them back atomically and only deletes rows on full success
- snapshotStack (Array<number|null>) replaces single lastStash variable, keeping a 1:1
  alignment with turns so multi-level /undo correctly restores the right snapshot each time
- Orphaned snapshot rows cleaned up on session resume and startNewSession
- Delete git-stash.ts

xonecas2026-02-21 389da5aae12c20ad80229356254896166dec5520 parent a7328d1

6 files changed

package.json+1−1
@@ -1,6 +1,6 @@
11 {
22 "name": "mini-coder",
3- "version": "0.0.1",
3+ "version": "0.0.3",
44 "description": "A small, fast CLI coding agent",
55 "module": "src/index.ts",
66 "type": "module",
src/agent/agent.ts+33−18
@@ -21,12 +21,13 @@ import { type CoreMessage, runTurn } from "../llm-api/turn.ts";
2121 import type { ToolDef } from "../llm-api/types.ts";
2222 import { connectMcpServer } from "../mcp/client.ts";
2323 import {
24- type GitStashPopResult,
25- gitStashPop,
26- gitStashTurn,
27-} from "../tools/git-stash.ts";
24+ type SnapshotRestoreResult,
25+ restoreSnapshot,
26+ takeSnapshot,
27+} from "../tools/snapshot.ts";
2828
2929 import {
30+ deleteAllSnapshots,
3031 deleteLastTurn,
3132 getConfigDir,
3233 getMaxTurnIndex,
@@ -159,6 +160,9 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
159160 }
160161 session = resumed;
161162 currentModel = session.model;
163+ // Orphaned snapshot rows from a previous run can never be reached by the
164+ // fresh in-memory snapshotStack — delete them so they don't accumulate.
165+ deleteAllSnapshots(session.id);
162166 renderInfo(`Resumed session ${session.id} (${c.cyan(currentModel)})`);
163167 } else {
164168 session = newSession(currentModel, cwd);
@@ -320,16 +324,22 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
320324
321325 // Delete from DB and decrement turn counter
322326 const deleted = deleteLastTurn(session.id);
323- const poppedTurn = lastStash;
327+ const poppedTurn = snapshotStack.pop() ?? null;
324328 if (turnIndex > 0) turnIndex--;
325- lastStash = null;
326329
327- // Restore files via git stash pop for the specific turn being undone
330+ // Restore files from the SQLite snapshot for the turn being undone
328331 if (poppedTurn !== null) {
329- const popResult: GitStashPopResult = await gitStashPop(cwd, poppedTurn);
330- if (popResult.restored === false && popResult.conflict) {
332+ const restoreResult: SnapshotRestoreResult = await restoreSnapshot(
333+ cwd,
334+ session.id,
335+ poppedTurn,
336+ );
337+ if (
338+ restoreResult.restored === false &&
339+ restoreResult.reason === "error"
340+ ) {
331341 renderError(
332- "git stash pop conflict — your working tree may need manual resolution",
342+ "snapshot restore failed — some files may not have been reverted",
333343 );
334344 }
335345 }
@@ -338,21 +348,24 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
338348 },
339349 connectMcpServer: connectAndAddMcp,
340350 startNewSession: () => {
351+ deleteAllSnapshots(session.id);
341352 session = newSession(currentModel, cwd);
342353 coreHistory.length = 0;
343354 turnIndex = 1;
344355 totalIn = 0;
345356 totalOut = 0;
346357 lastContextTokens = 0;
347- lastStash = null;
358+ snapshotStack.length = 0;
348359 },
349360 };
350361 const spinner = new Spinner();
351362 let totalIn = 0;
352363 let totalOut = 0;
353364 let lastContextTokens = 0;
354- // turnIndex of the last stash created, or null if no stash was made
355- let lastStash: number | null = null;
365+ // Stack aligned 1:1 with turns. Each processUserInput pushes the turn index
366+ // when a snapshot was created, or null when the tree was clean. Each
367+ // undoLastTurn pops the top so the indices always correspond to the right turn.
368+ const snapshotStack: Array<number | null> = [];
356369
357370 // ── Handle initial prompt (non-interactive) ────────────────────────────────
358371 if (opts.initialPrompt) {
@@ -423,9 +436,9 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
423436 const thisTurn = turnIndex++;
424437
425438 // Snapshot working tree before anything is persisted or sent to the LLM.
426- // If stashing fails (not a git repo, clean tree) stashed=false and /undo
427- // will only roll back conversation history, not files — which is fine.
428- const stashed = await gitStashTurn(cwd, thisTurn);
439+ // Saves dirty file contents to SQLite so /undo can restore them without
440+ // touching git stash or the user's working tree state.
441+ const snapped = await takeSnapshot(cwd, session.id, thisTurn);
429442
430443 const coreContent = planMode
431444 ? `${resolvedText}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
@@ -442,8 +455,10 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
442455 const onSigInt = () => abortController.abort();
443456 process.once("SIGINT", onSigInt);
444457
445- // Store stash metadata so undoLastTurn can pop the right stash
446- lastStash = stashed ? thisTurn : null;
458+ // Always push so the stack stays aligned 1:1 with turns. A null entry means
459+ // the tree was clean at snapshot time — /undo will roll back conversation
460+ // history but skip file restoration for that turn.
461+ snapshotStack.push(snapped ? thisTurn : null);
447462
448463 spinner.start("thinking");
449464
src/session/db.ts+79−1
@@ -18,7 +18,7 @@ function getDbPath(): string {
1818
1919 // ─── Schema ───────────────────────────────────────────────────────────────────
2020
21-const DB_VERSION = 2;
21+const DB_VERSION = 3;
2222
2323 const SCHEMA = `
2424 CREATE TABLE IF NOT EXISTS sessions (
@@ -67,6 +67,18 @@ const SCHEMA = `
6767 key TEXT PRIMARY KEY,
6868 value TEXT NOT NULL
6969 );
70+
71+ CREATE TABLE IF NOT EXISTS snapshots (
72+ id INTEGER PRIMARY KEY AUTOINCREMENT,
73+ session_id TEXT NOT NULL,
74+ turn_index INTEGER NOT NULL,
75+ path TEXT NOT NULL,
76+ content BLOB,
77+ existed INTEGER NOT NULL
78+ );
79+
80+ CREATE INDEX IF NOT EXISTS idx_snapshots_turn
81+ ON snapshots(session_id, turn_index);
7082 `;
7183
7284 // ─── Types ────────────────────────────────────────────────────────────────────
@@ -332,6 +344,72 @@ export function setPreferredModel(model: string): void {
332344 setSetting("preferred_model", model);
333345 }
334346
347+// ─── Snapshots ────────────────────────────────────────────────────────────────
348+
349+export interface SnapshotFile {
350+ /** Path relative to the project cwd */
351+ path: string;
352+ /** Raw file contents, or null if the file did not exist before the turn */
353+ content: Uint8Array | null;
354+ /** True if the file existed before the turn; false if the agent created it */
355+ existed: boolean;
356+}
357+
358+export function saveSnapshot(
359+ sessionId: string,
360+ turnIndex: number,
361+ files: SnapshotFile[],
362+): void {
363+ const db = getDb();
364+ const stmt = db.prepare(
365+ `INSERT INTO snapshots (session_id, turn_index, path, content, existed)
366+ VALUES (?, ?, ?, ?, ?)`,
367+ );
368+ const insert = db.transaction(() => {
369+ for (const f of files) {
370+ stmt.run(
371+ sessionId,
372+ turnIndex,
373+ f.path,
374+ f.content ?? null,
375+ f.existed ? 1 : 0,
376+ );
377+ }
378+ });
379+ insert();
380+}
381+
382+export function loadSnapshot(
383+ sessionId: string,
384+ turnIndex: number,
385+): SnapshotFile[] {
386+ const rows = getDb()
387+ .query<
388+ { path: string; content: Uint8Array | null; existed: number },
389+ [string, number]
390+ >(
391+ "SELECT path, content, existed FROM snapshots WHERE session_id = ? AND turn_index = ?",
392+ )
393+ .all(sessionId, turnIndex);
394+ return rows.map((r) => ({
395+ path: r.path,
396+ content: r.content ?? null,
397+ existed: r.existed === 1,
398+ }));
399+}
400+
401+export function deleteSnapshot(sessionId: string, turnIndex: number): void {
402+ getDb().run("DELETE FROM snapshots WHERE session_id = ? AND turn_index = ?", [
403+ sessionId,
404+ turnIndex,
405+ ]);
406+}
407+
408+/** Delete all snapshot rows for a session (e.g. on session reset). */
409+export function deleteAllSnapshots(sessionId: string): void {
410+ getDb().run("DELETE FROM snapshots WHERE session_id = ?", [sessionId]);
411+}
412+
335413 // ─── ID generation ────────────────────────────────────────────────────────────
336414
337415 /** Generate a short session ID: timestamp + random suffix */
src/tools/git-stash.ts+0−93
@@ -1,93 +0,0 @@
1-/**
2- * Git-based turn snapshots for /undo.
3- *
4- * Before each agent turn we stash any dirty working tree so that /undo can
5- * restore files to exactly the state they were in before the agent ran.
6- *
7- * Both functions are silent no-ops when the cwd is not inside a git repository
8- * or the working tree is already clean. They never throw.
9- */
10-
11-/** Stash the current working tree before a turn. Returns true if a stash was created. */
12-export async function gitStashTurn(
13- cwd: string,
14- turnIndex: number,
15-): Promise<boolean> {
16- try {
17- const proc = Bun.spawn(
18- [
19- "git",
20- "stash",
21- "push",
22- "--include-untracked",
23- "--message",
24- `mini-coder:turn:${turnIndex}`,
25- ],
26- { cwd, stdout: "pipe", stderr: "pipe" },
27- );
28- // Drain both streams so the process doesn't hang
29- await Promise.all([
30- new Response(proc.stdout).text(),
31- new Response(proc.stderr).text(),
32- ]);
33- const code = await proc.exited;
34- // Exit 0 = stash created; exit 1 = "nothing to stash" (also fine)
35- // Any other code means git isn't available or cwd is not a repo
36- return code === 0;
37- } catch {
38- return false;
39- }
40-}
41-
42-export type GitStashPopResult =
43- | { restored: true }
44- | { restored: false; conflict: boolean };
45-
46-/**
47- * Pop the mini-coder stash for a specific turn.
48- * Returns whether files were restored and whether a merge conflict occurred.
49- */
50-export async function gitStashPop(
51- cwd: string,
52- turnIndex: number,
53-): Promise<GitStashPopResult> {
54- const noRestore: GitStashPopResult = { restored: false, conflict: false };
55- try {
56- // Find the stash for this specific turn
57- const listProc = Bun.spawn(["git", "stash", "list"], {
58- cwd,
59- stdout: "pipe",
60- stderr: "pipe",
61- });
62- const listOut = await new Response(listProc.stdout).text();
63- await new Response(listProc.stderr).text();
64- await listProc.exited;
65-
66- const pattern = new RegExp(
67- `^(stash@\\{\\d+\\}):.*mini-coder:turn:${turnIndex}$`,
68- "m",
69- );
70- const match = pattern.exec(listOut);
71- if (!match) return noRestore;
72-
73- const ref = match[1];
74- if (!ref) return noRestore;
75-
76- const popProc = Bun.spawn(["git", "stash", "pop", ref], {
77- cwd,
78- stdout: "pipe",
79- stderr: "pipe",
80- });
81- await Promise.all([
82- new Response(popProc.stdout).text(),
83- new Response(popProc.stderr).text(),
84- ]);
85- const code = await popProc.exited;
86-
87- if (code === 0) return { restored: true };
88- // Non-zero exit from stash pop typically means a merge conflict
89- return { restored: false, conflict: true };
90- } catch {
91- return noRestore;
92- }
93-}
src/tools/snapshot.test.ts+285−0
@@ -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+});
src/tools/snapshot.ts+311−0
@@ -0,0 +1,311 @@
1+/**
2+ * SQLite-based turn snapshots for /undo.
3+ *
4+ * Before each agent turn we inspect the git working tree (via `git status`) and
5+ * store the contents of every dirty file in the SQLite database. On /undo we
6+ * restore those files from the DB and clean up the snapshot row(s).
7+ *
8+ * This approach is completely invisible to the user: no stash entries, no
9+ * commits, no impact on `git status` / `git log` / `git add`.
10+ *
11+ * Snapshotting is skipped silently when:
12+ * - the cwd is not inside a git repository, or
13+ * - the working tree is already clean (nothing to snapshot).
14+ *
15+ * Both functions never throw.
16+ */
17+
18+import { readFileSync, unlinkSync } from "node:fs";
19+import { join } from "node:path";
20+import {
21+ type SnapshotFile,
22+ deleteSnapshot,
23+ loadSnapshot,
24+ saveSnapshot,
25+} from "../session/db.ts";
26+
27+// ─── Types ────────────────────────────────────────────────────────────────────
28+
29+export type SnapshotRestoreResult =
30+ | { restored: true }
31+ | { restored: false; reason: "not-found" | "error" };
32+
33+// ─── Helpers ──────────────────────────────────────────────────────────────────
34+
35+/** Run a git command and return { stdout as raw bytes, code }. Never throws. */
36+async function gitBytes(
37+ args: string[],
38+ cwd: string,
39+): Promise<{ bytes: Uint8Array; code: number }> {
40+ try {
41+ const proc = Bun.spawn(["git", ...args], {
42+ cwd,
43+ stdout: "pipe",
44+ stderr: "pipe",
45+ });
46+ const [bytes] = await Promise.all([
47+ new Response(proc.stdout).bytes(),
48+ new Response(proc.stderr).bytes(),
49+ ]);
50+ const code = await proc.exited;
51+ return { bytes, code };
52+ } catch {
53+ return { bytes: new Uint8Array(), code: -1 };
54+ }
55+}
56+
57+/** Run a git command and return { stdout as text, code }. Never throws. */
58+async function git(
59+ args: string[],
60+ cwd: string,
61+): Promise<{ stdout: string; code: number }> {
62+ const { bytes, code } = await gitBytes(args, cwd);
63+ return { stdout: new TextDecoder().decode(bytes), code };
64+}
65+
66+/**
67+ * Parse `git status --porcelain -z` output into a list of affected relative paths.
68+ * Returns null when git is unavailable or cwd is not a repo.
69+ *
70+ * With -z, the format is NUL-delimited entries: "XY PATH" for normal entries,
71+ * and "R NEW\0OLD" (or "C NEW\0OLD") for renames/copies — meaning the new
72+ * (destination) path is in the entry itself, and the old (source) path follows
73+ * as the next NUL-delimited token.
74+ *
75+ * Status codes we care about:
76+ * M modified (tracked)
77+ * A added to index (tracked but new)
78+ * D deleted (tracked)
79+ * R renamed — snapshot old (source) path content; new path is untracked-style
80+ * C copied — snapshot the new path
81+ * ? untracked
82+ */
83+interface StatusEntry {
84+ /** Path relative to repo root */
85+ path: string;
86+ /** True if the file currently exists on disk */
87+ existsOnDisk: boolean;
88+ /** True if the file is brand-new and not in HEAD (untracked, not yet committed) */
89+ isNew: boolean;
90+}
91+
92+/**
93+ * Parse `git status` for the given repo root.
94+ * Assumes the caller has already verified we're inside a git repo.
95+ */
96+async function getStatusEntries(
97+ repoRoot: string,
98+): Promise<StatusEntry[] | null> {
99+ // -u / --untracked-files=all enumerates individual files inside new directories
100+ // rather than collapsing them to a single "?? dir/" entry.
101+ const status = await git(["status", "--porcelain", "-z", "-u"], repoRoot);
102+ if (status.code !== 0) return null;
103+
104+ const raw = status.stdout;
105+ if (raw === "") return []; // clean tree
106+
107+ const entries: StatusEntry[] = [];
108+ const parts = raw.split("\0");
109+ let i = 0;
110+ while (i < parts.length) {
111+ const entry = parts[i];
112+ i++;
113+ if (!entry || entry.length < 4) continue;
114+
115+ const xy = entry.slice(0, 2);
116+ const filePath = entry.slice(3); // for renames: this is the NEW (destination) path
117+ const x = xy[0] ?? " "; // index status
118+ const y = xy[1] ?? " "; // worktree status
119+
120+ if (x === "R" || x === "C") {
121+ // With --porcelain -z: entry contains NEW path; next token is OLD (source) path.
122+ const oldPath = parts[i];
123+ i++;
124+ // Old/source path: deleted from working tree — existed in HEAD, capture content
125+ if (oldPath) {
126+ entries.push({ path: oldPath, existsOnDisk: false, isNew: false });
127+ }
128+ // New/destination path: exists on disk, not in HEAD yet
129+ if (filePath) {
130+ entries.push({ path: filePath, existsOnDisk: true, isNew: true });
131+ }
132+ continue;
133+ }
134+
135+ if (x === "D" || y === "D") {
136+ // Deleted — file no longer exists on disk but was in HEAD
137+ if (filePath)
138+ entries.push({ path: filePath, existsOnDisk: false, isNew: false });
139+ continue;
140+ }
141+
142+ if (x === "?" && y === "?") {
143+ // Untracked — file exists on disk and is brand-new (not in HEAD)
144+ if (filePath)
145+ entries.push({ path: filePath, existsOnDisk: true, isNew: true });
146+ continue;
147+ }
148+
149+ // All other cases (M, A, U, etc.) — file exists on disk and was in HEAD
150+ if (filePath)
151+ entries.push({ path: filePath, existsOnDisk: true, isNew: false });
152+ }
153+
154+ // Deduplicate by path (renames can produce duplicates)
155+ const seen = new Set<string>();
156+ return entries.filter((e) => {
157+ if (seen.has(e.path)) return false;
158+ seen.add(e.path);
159+ return true;
160+ });
161+}
162+
163+/** Get the repo root so we can resolve paths relative to cwd correctly. */
164+async function getRepoRoot(cwd: string): Promise<string | null> {
165+ const result = await git(["rev-parse", "--show-toplevel"], cwd);
166+ if (result.code !== 0) return null;
167+ return result.stdout.trim();
168+}
169+
170+// ─── Public API ───────────────────────────────────────────────────────────────
171+
172+/**
173+ * Snapshot the current working tree state before a turn.
174+ * Returns true if a snapshot was created (there were dirty files), false otherwise.
175+ */
176+export async function takeSnapshot(
177+ cwd: string,
178+ sessionId: string,
179+ turnIndex: number,
180+): Promise<boolean> {
181+ try {
182+ // A single rev-parse establishes both "are we in a repo" and the root path.
183+ const repoRoot = await getRepoRoot(cwd);
184+ if (repoRoot === null) return false;
185+
186+ const entries = await getStatusEntries(repoRoot);
187+
188+ // git status failed
189+ if (entries === null) return false;
190+ // Clean working tree — nothing to snapshot
191+ if (entries.length === 0) return false;
192+
193+ const files: SnapshotFile[] = [];
194+
195+ for (const entry of entries) {
196+ const absPath = join(repoRoot, entry.path);
197+
198+ if (!entry.existsOnDisk) {
199+ // File was deleted before this turn — retrieve its content from HEAD
200+ // so we can restore it on undo. Binary-safe: read as raw bytes.
201+ const { bytes, code } = await gitBytes(
202+ ["show", `HEAD:${entry.path}`],
203+ repoRoot,
204+ );
205+ if (code === 0) {
206+ files.push({
207+ path: entry.path,
208+ content: bytes,
209+ existed: true,
210+ });
211+ }
212+ continue;
213+ }
214+
215+ if (entry.isNew) {
216+ // File exists on disk but is not in HEAD (untracked or rename destination).
217+ // On undo we should delete it, not restore content — mark existed=false.
218+ // We still read the content so it can be re-created if needed in future,
219+ // but the restore logic uses existed to decide delete vs. overwrite.
220+ try {
221+ const content = readFileSync(absPath);
222+ files.push({
223+ path: entry.path,
224+ content: new Uint8Array(content),
225+ existed: false,
226+ });
227+ } catch {
228+ // Race condition: file removed after status. Skip it.
229+ }
230+ continue;
231+ }
232+
233+ // File exists on disk and was in HEAD — read its current content
234+ try {
235+ const content = readFileSync(absPath);
236+ files.push({
237+ path: entry.path,
238+ content: new Uint8Array(content),
239+ existed: true,
240+ });
241+ } catch {
242+ // Race condition: file removed after status. Skip it.
243+ }
244+ }
245+
246+ if (files.length === 0) return false;
247+
248+ saveSnapshot(sessionId, turnIndex, files);
249+ return true;
250+ } catch {
251+ return false;
252+ }
253+}
254+
255+/**
256+ * Restore files from the snapshot for the given turn and remove the snapshot.
257+ * Returns whether files were restored.
258+ */
259+export async function restoreSnapshot(
260+ cwd: string,
261+ sessionId: string,
262+ turnIndex: number,
263+): Promise<SnapshotRestoreResult> {
264+ try {
265+ const files = loadSnapshot(sessionId, turnIndex);
266+ const repoRoot = await getRepoRoot(cwd);
267+
268+ if (files.length === 0) return { restored: false, reason: "not-found" };
269+
270+ // We need the repo root to resolve paths; fall back to cwd if unavailable
271+ const root = repoRoot ?? cwd;
272+
273+ let anyFailed = false;
274+
275+ for (const file of files) {
276+ const absPath = join(root, file.path);
277+
278+ if (!file.existed) {
279+ // File was created by the agent (or is a rename destination) — delete it
280+ try {
281+ if (await Bun.file(absPath).exists()) {
282+ unlinkSync(absPath);
283+ }
284+ } catch {
285+ anyFailed = true;
286+ }
287+ continue;
288+ }
289+
290+ // File existed before — restore its content
291+ if (file.content !== null) {
292+ try {
293+ await Bun.write(absPath, file.content);
294+ } catch {
295+ anyFailed = true;
296+ }
297+ }
298+ }
299+
300+ // Only delete the snapshot when all files were restored successfully.
301+ // If any write failed, keep the snapshot so a retry is possible.
302+ if (!anyFailed) {
303+ deleteSnapshot(sessionId, turnIndex);
304+ }
305+ return anyFailed
306+ ? { restored: false, reason: "error" }
307+ : { restored: true };
308+ } catch {
309+ return { restored: false, reason: "error" };
310+ }
311+}