xonecas.io
64875
Mc

mini-coder / commit 0c73914

refactor: optimize snapshotting and file edits

This commit improves performance by removing the expensive git status --porcelain spawn before every turn. It introduces snapshotting via interception of file writes (create, insert, replace) using applyFileEdit and withCwdDefault.

Note: There are known edge cases with this new approach. Subagents operate on transient session IDs and bypass parent session snapshots. Shell and custom hooks also bypass the tool-level write interception.

xonecas2026-03-12 0c73914fc7f7627a087e30e46345f6276912e610 parent 740db9b

11 files changed

TODO.md+3−0
@@ -1,5 +1,8 @@
11 # TODO
22
3+- Newline missing after spinner, new content is appended starting on the same line as the spinner line.
4+- ESC doesn't interrupt subagents created by custom commands, example: can't interrupt a review agent
5+
36 ---
47
58 ## LSP Diagnostics (not very important, with tool-hooks and strong linting, this is not as necessary, but we should implement asap)
src/agent/agent.ts+7−1
@@ -58,6 +58,7 @@ export async function initAgent(opts: AgentOptions): Promise<{
5858 const cwd = opts.cwd;
5959 let currentModel = opts.model;
6060
61+ let currentRunner: SessionRunner | null = null;
6162 const { runSubagent, killAll } = createSubagentRunner(
6263 cwd,
6364 () => currentModel,
@@ -68,8 +69,12 @@ export async function initAgent(opts: AgentOptions): Promise<{
6869 runSubagent,
6970 onHook: (tool, path, ok) => opts.reporter.renderHook(tool, path, ok),
7071 availableAgents: subagentAgents(agents),
72+ snapshotCallback: async (filePath) => {
73+ if (currentRunner) {
74+ await currentRunner.snapshotCallback(filePath);
75+ }
76+ },
7177 });
72-
7378 const mcpTools: ToolDef[] = [];
7479
7580 async function connectAndAddMcp(name: string): Promise<void> {
@@ -116,6 +121,7 @@ export async function initAgent(opts: AgentOptions): Promise<{
116121 isSubagent: opts.headless,
117122 killSubprocesses: killAll,
118123 });
124+ currentRunner = runner;
119125
120126 // Active primary agent state — name only; the system prompt is stored on runner.
121127 let activeAgentName: string | null = getPreferredActiveAgent();
src/agent/session-runner.ts+20−6
@@ -17,7 +17,7 @@ import {
1717 resumeSession,
1818 touchActiveSession,
1919 } from "../session/manager.ts";
20-import { takeSnapshot } from "../tools/snapshot.ts";
20+import { snapshotBeforeEdit } from "../tools/snapshot.ts";
2121 import { extractAssistantText, makeInterruptMessage } from "./agent-helpers.ts";
2222 import type { AgentReporter } from "./reporter.ts";
2323 import { buildSystemPrompt } from "./system-prompt.ts";
@@ -61,6 +61,20 @@ export class SessionRunner {
6161 public coreHistory!: CoreMessage[];
6262 public turnIndex = 1;
6363 public snapshotStack: Array<number | null> = [];
64+ public currentSnappedPaths: Set<string> | null = null;
65+ public currentTurn: number | null = null;
66+
67+ public async snapshotCallback(filePath: string) {
68+ if (this.currentTurn !== null && this.currentSnappedPaths !== null) {
69+ await snapshotBeforeEdit(
70+ this.cwd,
71+ this.session.id,
72+ this.currentTurn,
73+ filePath,
74+ this.currentSnappedPaths,
75+ );
76+ }
77+ }
6478
6579 public planMode = false;
6680 public ralphMode = false;
@@ -145,8 +159,8 @@ export class SessionRunner {
145159 const allImages = [...pastedImages];
146160 const thisTurn = this.turnIndex++;
147161
148- const snapped = await takeSnapshot(this.cwd, this.session.id, thisTurn);
149-
162+ this.currentTurn = thisTurn;
163+ this.currentSnappedPaths = new Set<string>();
150164 const coreContent = this.planMode
151165 ? `${text}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
152166 : text;
@@ -181,8 +195,7 @@ export class SessionRunner {
181195 let lastAssistantText = "";
182196
183197 try {
184- this.snapshotStack.push(snapped ? thisTurn : null);
185-
198+ this.snapshotStack.push(thisTurn);
186199 this.reporter.startSpinner("thinking");
187200 const events = runTurn({
188201 model: llm,
@@ -232,9 +245,10 @@ export class SessionRunner {
232245 saveMessages(this.session.id, [stubMsg], thisTurn);
233246 throw err;
234247 } finally {
248+ this.currentTurn = null;
249+ this.currentSnappedPaths = null;
235250 stopWatcher();
236251 }
237-
238252 return lastAssistantText;
239253 }
240254 }
src/agent/tools.ts+22−13
@@ -36,13 +36,18 @@ import {
3636 /**
3737 * Inject a default cwd if not provided by the LLM.
3838 */
39-function withCwdDefault(tool: ToolDef, cwd: string): ToolDef {
39+function withCwdDefault(
40+ tool: ToolDef,
41+ cwd: string,
42+ snapshotCallback?: (filePath: string) => Promise<void>,
43+): ToolDef {
4044 const originalExecute = tool.execute;
4145 return {
4246 ...tool,
4347 execute: async (input: unknown) => {
4448 const withDefault = {
4549 cwd,
50+ ...(snapshotCallback ? { snapshotCallback } : {}),
4651 ...(typeof input === "object" && input ? input : {}),
4752 };
4853 return originalExecute(withDefault);
@@ -123,6 +128,7 @@ export function buildToolSet(opts: {
123128
124129 onHook: (toolName: string, scriptPath: string, success: boolean) => void;
125130 availableAgents: ReadonlyMap<string, { description: string }>;
131+ snapshotCallback?: (filePath: string) => Promise<void>;
126132 }): ToolDef[] {
127133 const { cwd, onHook } = opts;
128134 const lookupHook = createHookCache(HOOKABLE_TOOLS, cwd);
@@ -161,10 +167,11 @@ export function buildToolSet(opts: {
161167 ) as ToolDef,
162168 // Write: create/overwrite, replace/delete, insert
163169 withHooks(
164- withCwdDefault(createTool as ToolDef, cwd) as ToolDef<
165- { cwd?: string },
166- CreateToolOutput
167- >,
170+ withCwdDefault(
171+ createTool as ToolDef,
172+ cwd,
173+ opts.snapshotCallback,
174+ ) as ToolDef<{ cwd?: string }, CreateToolOutput>,
168175 lookupHook,
169176 cwd,
170177 (result) => hookEnvForCreate(result, cwd),
@@ -172,10 +179,11 @@ export function buildToolSet(opts: {
172179 finalizeWriteResult,
173180 ) as ToolDef,
174181 withHooks(
175- withCwdDefault(replaceTool as ToolDef, cwd) as ToolDef<
176- { cwd?: string },
177- ReplaceToolOutput
178- >,
182+ withCwdDefault(
183+ replaceTool as ToolDef,
184+ cwd,
185+ opts.snapshotCallback,
186+ ) as ToolDef<{ cwd?: string }, ReplaceToolOutput>,
179187 lookupHook,
180188 cwd,
181189 (result) => hookEnvForReplace(result, cwd),
@@ -183,10 +191,11 @@ export function buildToolSet(opts: {
183191 finalizeWriteResult,
184192 ) as ToolDef,
185193 withHooks(
186- withCwdDefault(insertTool as ToolDef, cwd) as ToolDef<
187- { cwd?: string },
188- InsertToolOutput
189- >,
194+ withCwdDefault(
195+ insertTool as ToolDef,
196+ cwd,
197+ opts.snapshotCallback,
198+ ) as ToolDef<{ cwd?: string }, InsertToolOutput>,
190199 lookupHook,
191200 cwd,
192201 (result) => hookEnvForInsert(result, cwd),
src/session/db/snapshot-repo.ts+1−1
@@ -1,6 +1,6 @@
11 import { getDb } from "./connection.ts";
22
3-export interface SnapshotFile {
3+interface SnapshotFile {
44 /** Path relative to the project cwd */
55 path: string;
66 /** Raw file contents, or null if the file did not exist before the turn */
src/tools/create.ts+5−1
@@ -11,7 +11,10 @@ const CreateSchema = z.object({
1111 content: z.string().describe("Full content to write to the file"),
1212 });
1313
14-type CreateInput = z.infer<typeof CreateSchema> & { cwd?: string };
14+type CreateInput = z.infer<typeof CreateSchema> & {
15+ cwd?: string;
16+ snapshotCallback?: (filePath: string) => Promise<void>;
17+};
1518
1619 interface CreateOutput {
1720 path: string;
@@ -37,6 +40,7 @@ export const createTool: ToolDef<CreateInput, CreateToolOutput> = {
3740 const created = !(await file.exists());
3841 const before = created ? "" : await file.text();
3942
43+ await input.snapshotCallback?.(filePath);
4044 await Bun.write(filePath, input.content);
4145
4246 const diff = generateDiff(relPath, before, input.content);
src/tools/insert.ts+12−12
@@ -1,8 +1,7 @@
11 import { z } from "zod";
22 import type { ToolDef } from "../llm-api/types.ts";
3-import { generateDiff } from "./diff.ts";
43 import { findLineByHash } from "./hashline.ts";
5-import { parseAnchor, resolveExistingFile } from "./shared.ts";
4+import { applyFileEdit, parseAnchor, resolveExistingFile } from "./shared.ts";
65 import type { WriteResultMeta } from "./write-result.ts";
76
87 const InsertSchema = z.object({
@@ -16,7 +15,10 @@ const InsertSchema = z.object({
1615 content: z.string().describe("Text to insert"),
1716 });
1817
19-type InsertInput = z.infer<typeof InsertSchema> & { cwd?: string };
18+type InsertInput = z.infer<typeof InsertSchema> & {
19+ cwd?: string;
20+ snapshotCallback?: (filePath: string) => Promise<void>;
21+};
2022
2123 interface InsertOutput {
2224 path: string;
@@ -60,14 +62,12 @@ export const insertTool: ToolDef<InsertInput, InsertToolOutput> = {
6062 ];
6163
6264 const updated = updatedLines.join("\n");
63- await Bun.write(filePath, updated);
64-
65- const diff = generateDiff(relPath, original, updated);
66- return {
67- path: relPath,
68- diff,
69- _filePath: filePath,
70- _before: original,
71- };
65+ return applyFileEdit(
66+ input.snapshotCallback,
67+ filePath,
68+ relPath,
69+ original,
70+ updated,
71+ );
7272 },
7373 };
src/tools/replace.ts+13−10
@@ -1,8 +1,7 @@
11 import { z } from "zod";
22 import type { ToolDef } from "../llm-api/types.ts";
3-import { generateDiff } from "./diff.ts";
43 import { findLineByHash } from "./hashline.ts";
5-import { parseAnchor, resolveExistingFile } from "./shared.ts";
4+import { applyFileEdit, parseAnchor, resolveExistingFile } from "./shared.ts";
65 import type { WriteResultMeta } from "./write-result.ts";
76
87 const ReplaceSchema = z.object({
@@ -24,7 +23,10 @@ const ReplaceSchema = z.object({
2423 ),
2524 });
2625
27-type ReplaceInput = z.infer<typeof ReplaceSchema> & { cwd?: string };
26+type ReplaceInput = z.infer<typeof ReplaceSchema> & {
27+ cwd?: string;
28+ snapshotCallback?: (filePath: string) => Promise<void>;
29+};
2830
2931 interface ReplaceOutput {
3032 path: string;
@@ -90,15 +92,16 @@ export const replaceTool: ToolDef<ReplaceInput, ReplaceToolOutput> = {
9092 ];
9193
9294 const updated = updatedLines.join("\n");
93- await Bun.write(filePath, updated);
94-
95- const diff = generateDiff(relPath, original, updated);
95+ const editResult = await applyFileEdit(
96+ input.snapshotCallback,
97+ filePath,
98+ relPath,
99+ original,
100+ updated,
101+ );
96102 return {
97- path: relPath,
98- diff,
103+ ...editResult,
99104 deleted: replacement.length === 0,
100- _filePath: filePath,
101- _before: original,
102105 };
103106 },
104107 };
src/tools/shared.ts+19−0
@@ -1,4 +1,5 @@
11 import { join, relative } from "node:path";
2+import { generateDiff } from "./diff.ts";
23
34 export function resolvePath(cwdInput: string | undefined, pathInput: string) {
45 const cwd = cwdInput ?? process.cwd();
@@ -51,3 +52,21 @@ export function parseAnchor(value: string, name = "anchor"): ParsedAnchor {
5152
5253 return { line, hash: hash.toLowerCase() };
5354 }
55+
56+export async function applyFileEdit(
57+ snapshotCallback: ((filePath: string) => Promise<void>) | undefined,
58+ filePath: string,
59+ relPath: string,
60+ original: string,
61+ updated: string,
62+) {
63+ await snapshotCallback?.(filePath);
64+ await Bun.write(filePath, updated);
65+
66+ return {
67+ path: relPath,
68+ diff: generateDiff(relPath, original, updated),
69+ _filePath: filePath,
70+ _before: original,
71+ };
72+}
src/tools/snapshot.test.ts+64−108
@@ -7,7 +7,7 @@ import {
77 loadSnapshot,
88 saveSnapshot,
99 } from "../session/db/index.ts";
10-import { restoreSnapshot, takeSnapshot } from "./snapshot.ts";
10+import { restoreSnapshot, snapshotBeforeEdit } from "./snapshot.ts";
1111
1212 // ─── Helpers ──────────────────────────────────────────────────────────────────
1313
@@ -82,121 +82,86 @@ describe("saveSnapshot / loadSnapshot / deleteSnapshot", () => {
8282 });
8383 });
8484
85-// ─── takeSnapshot ─────────────────────────────────────────────────────────────
85+// ─── snapshotBeforeEdit ───────────────────────────────────────────────────────
8686
87-describe("takeSnapshot", () => {
87+describe("snapshotBeforeEdit", () => {
8888 const state = useTestRepo();
8989
90- test("returns false on a clean working tree", async () => {
91- const result = await takeSnapshot(state.repoDir, state.sessionId, 1);
92- expect(result).toBe(false);
93- });
94-
95- test("returns false for a non-git directory", async () => {
96- const nonGit = join(tmpdir(), `mc-nongit-${Date.now()}`);
97- mkdirSync(nonGit, { recursive: true });
98- try {
99- const result = await takeSnapshot(nonGit, state.sessionId, 2);
100- expect(result).toBe(false);
101- } finally {
102- rmSync(nonGit, { recursive: true, force: true });
103- }
104- });
105-
106- test("snapshots a modified tracked file", async () => {
90+ test("snapshots a modified tracked file before edit", async () => {
10791 const filePath = join(state.repoDir, "README.md");
108- writeFileSync(filePath, "modified content\n");
109-
110- const result = await takeSnapshot(state.repoDir, state.sessionId, 3);
111- expect(result).toBe(true);
92+ const snappedPaths = new Set<string>();
93+
94+ await snapshotBeforeEdit(
95+ state.repoDir,
96+ state.sessionId,
97+ 3,
98+ filePath,
99+ snappedPaths,
100+ );
112101
113102 const rows = loadSnapshot(state.sessionId, 3);
114103 const readme = rows.find((r) => r.path === "README.md");
115104 expect(readme).toBeDefined();
116105 expect(readme?.existed).toBe(true);
117106 expect(new TextDecoder().decode(readme?.content ?? undefined)).toBe(
118- "modified content\n",
107+ "hello\n",
119108 );
109+ expect(snappedPaths.has("README.md")).toBe(true);
120110
121111 deleteSnapshot(state.sessionId, 3);
122112 });
123113
124114 test("snapshots an untracked new file with existed=false", async () => {
125- writeFileSync(join(state.repoDir, "untracked.txt"), "brand new\n");
126-
127- const result = await takeSnapshot(state.repoDir, state.sessionId, 4);
128- expect(result).toBe(true);
115+ const filePath = join(state.repoDir, "untracked.txt");
116+ const snappedPaths = new Set<string>();
117+
118+ await snapshotBeforeEdit(
119+ state.repoDir,
120+ state.sessionId,
121+ 4,
122+ filePath,
123+ snappedPaths,
124+ );
129125
130126 const rows = loadSnapshot(state.sessionId, 4);
131127 const f = rows.find((r) => r.path === "untracked.txt");
132128 expect(f).toBeDefined();
133- // Untracked files are new — on undo they should be deleted, not written back
129+ // File didn't exist before edit
134130 expect(f?.existed).toBe(false);
131+ expect(f?.content).toBeNull();
135132
136133 deleteSnapshot(state.sessionId, 4);
137134 });
138135
139- test("snapshots files inside a new untracked directory", async () => {
140- // Without -u, git collapses new dirs to a single "?? dir/" entry.
141- // With -u, each file inside is listed individually.
142- mkdirSync(join(state.repoDir, "src"), { recursive: true });
143- writeFileSync(join(state.repoDir, "src", "a.ts"), "export const a = 1;\n");
144- writeFileSync(join(state.repoDir, "src", "b.ts"), "export const b = 2;\n");
145-
146- const result = await takeSnapshot(state.repoDir, state.sessionId, 5);
147- expect(result).toBe(true);
148-
149- const rows = loadSnapshot(state.sessionId, 5);
150- const a = rows.find((r) => r.path === "src/a.ts");
151- const b = rows.find((r) => r.path === "src/b.ts");
152- expect(a).toBeDefined();
153- expect(b).toBeDefined();
154- expect(a?.existed).toBe(false);
155- expect(b?.existed).toBe(false);
156-
157- deleteSnapshot(state.sessionId, 5);
158- });
159-
160- test("snapshots a renamed file correctly", async () => {
161- // Commit a file so it's tracked, then rename it
162- writeFileSync(join(state.repoDir, "old-name.ts"), "export const x = 1;\n");
163- spawnSync(["git", "add", "old-name.ts"], state.repoDir);
164- spawnSync(["git", "commit", "-m", "add file"], state.repoDir);
165-
166- // Rename tracked file
167- spawnSync(["git", "mv", "old-name.ts", "new-name.ts"], state.repoDir);
168-
169- const result = await takeSnapshot(state.repoDir, state.sessionId, 6);
170- expect(result).toBe(true);
171-
172- const rows = loadSnapshot(state.sessionId, 6);
173- // Old path: was deleted — should have existed=true with content
174- const oldEntry = rows.find((r) => r.path === "old-name.ts");
175- expect(oldEntry).toBeDefined();
176- expect(oldEntry?.existed).toBe(true);
177- expect(oldEntry?.content).not.toBeNull();
178-
179- // New path: brand new on disk — should have existed=false
180- const newEntry = rows.find((r) => r.path === "new-name.ts");
181- expect(newEntry).toBeDefined();
182- expect(newEntry?.existed).toBe(false);
183-
184- deleteSnapshot(state.sessionId, 6);
185- });
136+ test("does not snapshot the same file twice in one turn", async () => {
137+ const filePath = join(state.repoDir, "README.md");
138+ const snappedPaths = new Set<string>();
139+
140+ await snapshotBeforeEdit(
141+ state.repoDir,
142+ state.sessionId,
143+ 5,
144+ filePath,
145+ snappedPaths,
146+ );
186147
187- test("does not affect git status after snapshotting", async () => {
188- writeFileSync(join(state.repoDir, "README.md"), "changed\n");
148+ // Change the file
149+ writeFileSync(filePath, "changed\n");
189150
190- await takeSnapshot(state.repoDir, state.sessionId, 5);
151+ // Second call should be a no-op
152+ await snapshotBeforeEdit(
153+ state.repoDir,
154+ state.sessionId,
155+ 5,
156+ filePath,
157+ snappedPaths,
158+ );
191159
192- // git status should still show the modification — nothing was stashed
193- const proc = Bun.spawnSync(["git", "status", "--porcelain"], {
194- cwd: state.repoDir,
195- stdout: "pipe",
196- stderr: "pipe",
197- });
198- const statusOut = proc.stdout.toString();
199- expect(statusOut).toContain("README.md");
160+ const rows = loadSnapshot(state.sessionId, 5);
161+ const readme = rows.find((r) => r.path === "README.md");
162+ expect(new TextDecoder().decode(readme?.content ?? undefined)).toBe(
163+ "hello\n",
164+ );
200165
201166 deleteSnapshot(state.sessionId, 5);
202167 });
@@ -216,7 +181,6 @@ describe("restoreSnapshot", () => {
216181 test("restores a modified file to its pre-turn content", async () => {
217182 const filePath = join(state.repoDir, "README.md");
218183 const originalContent = "hello\n";
219- // File was already "hello\n" from makeRepo; now simulate a pre-turn snapshot
220184 saveSnapshot(state.sessionId, 10, [
221185 {
222186 path: "README.md",
@@ -225,17 +189,14 @@ describe("restoreSnapshot", () => {
225189 },
226190 ]);
227191
228- // Agent modifies the file
229192 writeFileSync(filePath, "agent changed this\n");
230193
231- // Undo: restore
232194 const result = await restoreSnapshot(state.repoDir, state.sessionId, 10);
233195 expect(result.restored).toBe(true);
234196
235197 const restoredContent = await Bun.file(filePath).text();
236198 expect(restoredContent).toBe(originalContent);
237199
238- // Snapshot should be cleaned up
239200 expect(loadSnapshot(state.sessionId, 10)).toHaveLength(0);
240201 });
241202
@@ -243,7 +204,6 @@ describe("restoreSnapshot", () => {
243204 const newFile = join(state.repoDir, "agent-created.ts");
244205 writeFileSync(newFile, "export const x = 1;\n");
245206
246- // Snapshot says this file did NOT exist before the turn
247207 saveSnapshot(state.sessionId, 11, [
248208 { path: "agent-created.ts", content: null, existed: false },
249209 ]);
@@ -257,24 +217,20 @@ describe("restoreSnapshot", () => {
257217 expect(loadSnapshot(state.sessionId, 11)).toHaveLength(0);
258218 });
259219
260- test("end-to-end: takeSnapshot then agent creates file, restoreSnapshot deletes it", async () => {
261- // Working tree is clean before the turn — nothing to snapshot
262- const snapped = await takeSnapshot(state.repoDir, state.sessionId, 12);
263- expect(snapped).toBe(false);
264-
265- // Agent creates a new file mid-turn
220+ test("end-to-end: snapshotBeforeEdit then agent creates file, restoreSnapshot deletes it", async () => {
266221 const agentFile = join(state.repoDir, "generated.ts");
267- writeFileSync(agentFile, "export const y = 2;\n");
268-
269- // Now snapshot captures the untracked file with existed=false
270- const snapped2 = await takeSnapshot(state.repoDir, state.sessionId, 13);
271- expect(snapped2).toBe(true);
222+ const snappedPaths = new Set<string>();
223+
224+ await snapshotBeforeEdit(
225+ state.repoDir,
226+ state.sessionId,
227+ 13,
228+ agentFile,
229+ snappedPaths,
230+ );
272231
273- const rows = loadSnapshot(state.sessionId, 13);
274- const entry = rows.find((r) => r.path === "generated.ts");
275- expect(entry?.existed).toBe(false);
232+ writeFileSync(agentFile, "export const y = 2;\n");
276233
277- // Restore: should delete the agent-created file
278234 const result = await restoreSnapshot(state.repoDir, state.sessionId, 13);
279235 expect(result.restored).toBe(true);
280236 expect(await Bun.file(agentFile).exists()).toBe(false);
src/tools/snapshot.ts+24−224
@@ -1,26 +1,17 @@
11 /**
22 * SQLite-based turn snapshots for /undo.
33 *
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).
4+ * Before an agent makes a file modification (create, replace, insert),
5+ * we hook in to snapshot the exact state of that file on disk.
76 *
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.
7+ * On /undo, we restore those files from the DB and clean up the snapshot rows.
168 */
179
18-import { readFileSync, unlinkSync } from "node:fs";
19-import { join } from "node:path";
10+import { unlinkSync } from "node:fs";
11+import { isAbsolute, join, relative } from "node:path";
2012 import {
2113 deleteSnapshot,
2214 loadSnapshot,
23- type SnapshotFile,
2415 saveSnapshot,
2516 } from "../session/db/index.ts";
2617
@@ -30,225 +21,38 @@ export type SnapshotRestoreResult =
3021 | { restored: true }
3122 | { restored: false; reason: "not-found" | "error" };
3223
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-
17024 // ─── Public API ───────────────────────────────────────────────────────────────
17125
17226 /**
173- * Snapshot the current working tree state before a turn.
174- * Returns true if a snapshot was created (there were dirty files), false otherwise.
27+ * Snapshot a file's state before editing it, if it hasn't been snapshotted this turn.
28+ * Does not throw.
17529 */
176-export async function takeSnapshot(
30+export async function snapshotBeforeEdit(
17731 cwd: string,
17832 sessionId: string,
17933 turnIndex: number,
180-): Promise<boolean> {
34+ filePath: string,
35+ snappedPaths: Set<string>,
36+): Promise<void> {
18137 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;
38+ const absPath = isAbsolute(filePath) ? filePath : join(cwd, filePath);
39+ const relPath = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;
19240
193- const files: SnapshotFile[] = [];
41+ if (snappedPaths.has(relPath)) return;
42+ snappedPaths.add(relPath);
19443
195- for (const entry of entries) {
196- const absPath = join(repoRoot, entry.path);
44+ let existed = false;
45+ let content: Uint8Array | null = null;
19746
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- }
47+ const file = Bun.file(absPath);
48+ if (await file.exists()) {
49+ existed = true;
50+ content = new Uint8Array(await file.arrayBuffer());
24451 }
24552
246- if (files.length === 0) return false;
247-
248- saveSnapshot(sessionId, turnIndex, files);
249- return true;
53+ saveSnapshot(sessionId, turnIndex, [{ path: relPath, content, existed }]);
25054 } catch {
251- return false;
55+ // Ignore errors — undo is a best-effort mechanism
25256 }
25357 }
25458
@@ -263,17 +67,13 @@ export async function restoreSnapshot(
26367 ): Promise<SnapshotRestoreResult> {
26468 try {
26569 const files = loadSnapshot(sessionId, turnIndex);
266- const repoRoot = await getRepoRoot(cwd);
26770
26871 if (files.length === 0) return { restored: false, reason: "not-found" };
26972
270- // We need the repo root to resolve paths; fall back to cwd if unavailable
271- const root = repoRoot ?? cwd;
272-
27373 let anyFailed = false;
27474
27575 for (const file of files) {
276- const absPath = join(root, file.path);
76+ const absPath = join(cwd, file.path);
27777
27878 if (!file.existed) {
27979 // File was created by the agent (or is a rename destination) — delete it