xonecas.io
64875
Mc

mini-coder / commit 3964cc6

refactor: simplify undo to remove only conversation turns

xonecas2026-03-15 3964cc6e41ce3af17e2715028c503818de404864 parent f90f6b5

14 files changed

.agents/skills/mini-coder/SKILL.md+2−2
@@ -88,7 +88,7 @@ Inside `mc`, the user can run slash commands such as:
8888 - `/context prune <off|balanced|aggressive>` — set pruning strategy
8989 - `/context cap <off|bytes|kb>` — cap tool payload size
9090 - `/cache <on|off>` — toggle prompt caching
91-- `/undo` — revert the last turn
91+- `/undo` — remove the last conversation turn (does not revert filesystem changes)
9292 - `/new` — start a fresh session
9393 - `/mcp list` — list configured MCP servers
9494 - `/mcp add <name> http <url>` — add an HTTP MCP server
@@ -141,7 +141,7 @@ mini-coder stores app data in:
141141 ~/.config/mini-coder/
142142 ```
143143
144-This includes session history and related local state.
144+This includes session history, MCP server config, and related local metadata.
145145
146146 ## How to help users effectively
147147
README.md+3−3
@@ -45,7 +45,7 @@ Need more firepower? I also connect to **MCP servers** over HTTP or stdio — at
4545 - **Built-in web search** — set `EXA_API_KEY` and I expose `webSearch` + `webContent` tools.
4646 - **Session memory** — conversations are saved in a local SQLite database. Resume where you left off with `-c` or pick a specific session with `-r <id>`.
4747 - **Shell integration** — prefix with `!` to run shell commands inline. Use `@` to reference files in your prompt (with Tab completion).
48-- **Slash commands** — `/model` or `/models` to list/switch models, `/model effort <low|medium|high|xhigh|off>` for reasoning effort, `/reasoning [on|off]` to toggle reasoning display, `/context` to inspect or tune pruning/tool-result caps, `/cache` to configure prompt caching, `/review` for a code review (global custom command, auto-created at `~/.agents/commands/review.md`), `/agent [name]` to set or clear an active primary agent, `/undo` to roll back a turn, `/new` for a clean session, `/mc …
48+- **Slash commands** — `/model` or `/models` to list/switch models, `/model effort <low|medium|high|xhigh|off>` for reasoning effort, `/reasoning [on|off]` to toggle reasoning display, `/context` to inspect or tune pruning/tool-result caps, `/cache` to configure prompt caching, `/review` for a code review (global custom command, auto-created at `~/.agents/commands/review.md`), `/agent [name]` to set or clear an active primary agent, `/undo` to remove the last conversation turn (it does not rev …
4949
5050 - **Custom commands** — drop a `.md` file in `.agents/commands/` and it becomes a `/command`. Claude-compatible `.claude/commands/` works too. Supports argument placeholders (`$ARGUMENTS`, `$1`…`$9`) and shell interpolation (`` !`cmd` ``). Global commands live in `~/.agents/commands/` and `~/.claude/commands/`. Custom commands take precedence over built-ins. → [docs/custom-commands.md](docs/custom-commands.md)
5151 - **Custom agents** — drop a `.md` file in `.agents/agents/` or `.claude/agents/` (or `~/.agents/agents/` / `~/.claude/agents/` globally) and activate it with `/agent [name]`. Agent definitions are also exposed to subagent delegation unless `mode: primary`. → [docs/custom-agents.md](docs/custom-agents.md)
@@ -136,7 +136,7 @@ mc -h # show help
136136
137137 Everything I remember lives in `~/.config/mini-coder/` — here's what I'm holding onto:
138138
139-- `sessions.db` — your full session history, `/undo` data, MCP server config, and model metadata, all in one tidy SQLite file
139+- `sessions.db` — your full session history, MCP server config, and model metadata, all in one tidy SQLite file
140140 - `api.log` — a request/response log for every provider call this run, if you want to peek under the hood
141141 - `errors.log` — anything that went sideways, caught and written down so you can actually debug it
142142
@@ -160,7 +160,7 @@ src/
160160 cli/ # Input, output, slash commands, markdown rendering
161161 llm-api/ # Provider factory + streaming turn logic
162162 tools/ # shell, subagent, skill tools
163- # + webSearch, webContent, undo support
163+ # + webSearch, webContent
164164 internal/ # shared internals, including the mc-edit helper implementation
165165 mcp/ # MCP server connections
166166 session/ # SQLite-backed session & history management
docs/file-helper-plan.md+25−25
@@ -13,9 +13,9 @@ The branch has already moved mini-coder toward the intended shell-first model:
1313 - model-facing local file tools have been removed or are in the process of being fully deleted from the old path
1414 - hook support has been removed as part of the same cleanup
1515
16-The main work still left is **undo**.
16+The undo cleanup has now landed too.
1717
18-`/undo` is still implemented around the old tool-managed snapshot model, while real edits now happen through shell commands that invoke `mc-edit`. Until that is redesigned, the architecture is not fully aligned.
18+`/undo` is now a conversation-turn undo only. It no longer tries to restore filesystem state, which keeps the architecture honest with the real shell + `mc-edit` edit path.
1919
2020 ---
2121
@@ -130,7 +130,7 @@ This cleanup is part of the refactor because hooks were tied to the old, heavier
130130
131131 ### 7. CLI and docs cleanup has started
132132
133-Prompt text, tool rendering, help text, and docs have already been pushed toward the shell-first model, but this part still needs a final consistency pass after undo is redesigned.
133+Prompt text, tool rendering, help text, and docs have already been pushed toward the shell-first model, but this part still needs a final consistency pass now that undo is settled.
134134
135135 ---
136136
@@ -172,12 +172,12 @@ The correct choice here is deletion, not redesign.
172172
173173 If hooks ever come back, that should happen as a separate effort with a clear use case.
174174
175-### 6. `/undo` must follow the real edit path
175+### 6. `/undo` should stay aligned with the real edit path
176176
177177 The old snapshot model was built around tool-managed writes.
178178 That no longer matches reality.
179179
180-If `/undo` is kept, it should primarily guarantee restoration for edits that went through `mc-edit`, not arbitrary raw shell file operations.
180+The correct result for this refactor is to keep `/undo` as conversation history undo only, not a filesystem restoration feature for shell-driven edits.
181181
182182 ### 7. MCP descriptions matter more now
183183
@@ -188,36 +188,34 @@ Their names and descriptions should stay concise and easy to distinguish from sh
188188
189189 ## What is left to do
190190
191-### 1. Redesign `/undo` around `mc-edit`
191+### 1. Redesign `/undo`
192192
193-This is the main unfinished work.
193+This work is done.
194194
195-### Current state
195+### What changed
196196
197-Undo still depends on the old snapshot path:
197+Undo no longer depends on the old snapshot path.
198+The snapshot-specific pieces were removed, including:
198199
199200 - `src/tools/snapshot.ts`
200201 - `src/agent/undo-snapshot.ts`
201-- `src/agent/session-runner.ts`
202202 - `src/session/db/snapshot-repo.ts`
203203
204-That design assumes the agent knows when file writes happen through local tools.
205-But the new edit path is shell-driven, so that assumption is no longer valid.
204+`/undo` now removes only the most recent conversation turn from session history.
205+It does not try to infer or restore filesystem state from shell-driven edits.
206206
207-### Recommended decision
207+### Result
208208
209-Keep `/undo` and a conversation turn undo only. Remove snapshotting and file changes tracking. Reflect this in the repor documentation as well.
210-
211-### Done when
212-
213-- /undo doesn't manage filesystem changes
214-- snapshotting is completly removed
209+- `/undo` doesn't manage filesystem changes
210+- snapshotting is removed from runtime code and docs
215211
216212 ---
217213
218214 ### 2. Finish the docs and help-text consistency pass
219215
220-The repo is already telling the new story in several places, but not yet from one consistent source of truth.
216+This is partially done.
217+
218+The repo is already telling the new story in several places, and the `/undo` wording has now been updated in the core help/manpage/README surfaces, but there is still not one fully consistent source of truth yet.
221219
222220 ### Sweep targets
223221
@@ -238,19 +236,20 @@ The repo is already telling the new story in several places, but not yet from on
238236 - `mc-edit` is clearly named as the targeted edit path
239237 - removed local file tools are not described as active runtime tools
240238 - removed hook support is not described anywhere
241-- `/undo` wording matches the redesigned guarantee once that work lands
239+- `/undo` wording matches the redesigned guarantee everywhere it is documented
242240
243241 ### Done when
244242
245243 - docs match implementation
246244 - examples reinforce shell + `mc-edit`
247245 - there are no stale references to removed tools or hooks
246+- `/undo` is consistently described as conversation-history undo only
248247
249248 ---
250249
251250 ### 3. Final prompt, CLI, and rendering polish
252251
253-Most of this is already moving in the right direction, but it still needs a final pass once undo is settled.
252+Most of this is already moving in the right direction, and the undo-specific wording cleanup is now done, but it still needs a final pass for overall consistency.
254253
255254 ### Areas to review
256255
@@ -296,6 +295,8 @@ Run:
296295 bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun run test
297296 ```
298297
298+Status on this branch: this command passes after the undo cleanup.
299+
299300 ---
300301
301302 ## Completion checklist
@@ -306,7 +307,7 @@ This refactor is complete when all of the following are true:
306307 - `mc-edit` is the clear targeted edit path
307308 - the old hashline edit path is fully gone
308309 - hooks are fully gone from runtime, UI, and docs
309-- `/undo` is aligned with shell + `mc-edit`
310+- `/undo` is aligned with the shell-first architecture by only undoing conversation history
310311 - prompt, CLI, and docs all describe the same architecture
311312 - bundled commands/skills/examples reinforce the shell-first workflow
312313
@@ -330,8 +331,7 @@ Compared to `main`, the branch has already done the hard architectural shift: `m
330331
331332 What remains is mostly about making the new architecture complete and honest:
332333
333-- finish `/undo`
334-- finish the docs/help/prompt consistency pass
334+- finish the remaining docs/help/prompt consistency pass
335335 - do one final MCP/CLI polish sweep
336336 - verify no stale code or messaging remains
337337
docs/mini-coder.1.md+3−3
@@ -62,7 +62,7 @@ Inside the interactive session, the following slash commands are available:
6262 : Attach Google Gemini cached content.
6363
6464 **/undo**
65-: Revert the last turn.
65+: Remove the last conversation turn. This does not revert filesystem changes.
6666
6767 **/new**
6868 : Clear context and start a fresh session.
@@ -130,7 +130,7 @@ The agent has access to the following tools:
130130
131131 ## FILES & DIRECTORIES
132132 **~/.config/mini-coder/**
133-: Application data directory. Contains `sessions.db` (SQLite database for session history, `/undo` data, MCP server configs, and model metadata), `api.log`, and `errors.log`.
133+: Application data directory. Contains `sessions.db` (SQLite database for session history, MCP server configs, and model metadata), `api.log`, and `errors.log`.
134134
135135 **.agents/ or .claude/ (Local or Global in ~/)**
136136 : Configuration directories for advanced features:
@@ -147,6 +147,6 @@ The agent has access to the following tools:
147147 * **Subagent Delegation**: Includes a tool to spawn parallel instances of itself to tackle independent subtasks simultaneously (up to 10 levels deep).
148148 * **Model Context Protocol (MCP)**: Native support for connecting external tools via MCP servers over HTTP or stdio.
149149 * **Prompt Caching**: Configurable caching behaviors for supported providers (OpenAI, Gemini).
150-* **Undo Functionality**: Roll back the last conversation turn and restore tracked local state.
150+* **Undo Functionality**: Remove the last conversation turn from the current session history. It does not restore filesystem changes.
151151
152152
src/agent/session-runner.ts+2−16
@@ -6,11 +6,7 @@ import { resolveModel } from "../llm-api/providers.ts";
66 import type { ContextPruningMode, CoreMessage } from "../llm-api/turn.ts";
77 import { runTurn } from "../llm-api/turn.ts";
88 import type { ToolDef } from "../llm-api/types.ts";
9-import {
10- deleteAllSnapshots,
11- getMaxTurnIndex,
12- saveMessages,
13-} from "../session/db/index.ts";
9+import { getMaxTurnIndex, saveMessages } from "../session/db/index.ts";
1410 import type { ActiveSession } from "../session/manager.ts";
1511 import {
1612 newSession,
@@ -24,7 +20,7 @@ import {
2420 } from "./agent-helpers.ts";
2521 import type { AgentReporter } from "./reporter.ts";
2622 import { buildSystemPrompt } from "./system-prompt.ts";
27-import { undoLastTurn } from "./undo-snapshot.ts";
23+import { undoLastTurn } from "./undo-turn.ts";
2824
2925 interface SessionRunnerOptions {
3026 cwd: string;
@@ -75,7 +71,6 @@ export class SessionRunner {
7571 private sessionTimeAnchor!: string;
7672 private coreHistory!: CoreMessage[];
7773 private turnIndex = 1;
78- private snapshotStack: Array<number | null> = [];
7974 private totalIn = 0;
8075 private totalOut = 0;
8176 private lastContextTokens = 0;
@@ -133,7 +128,6 @@ export class SessionRunner {
133128 }
134129 this.session = resumed;
135130 this.currentModel = this.session.model;
136- deleteAllSnapshots(this.session.id);
137131 this.reporter.info(
138132 `Resumed session ${this.session.id} (${c.cyan(this.currentModel)})`,
139133 );
@@ -147,7 +141,6 @@ export class SessionRunner {
147141 }
148142
149143 public startNewSession() {
150- deleteAllSnapshots(this.session.id);
151144 this.session = newSession(this.currentModel, this.cwd);
152145 this.coreHistory.length = 0;
153146 this.turnIndex = 1;
@@ -156,7 +149,6 @@ export class SessionRunner {
156149 this.lastContextTokens = 0;
157150 this.sessionTimeAnchor = new Date(this.session.createdAt).toISOString();
158151 this.rebuildSystemPrompt();
159- this.snapshotStack.length = 0;
160152 }
161153
162154 public addShellContext(command: string, output: string): void {
@@ -168,20 +160,15 @@ export class SessionRunner {
168160 this.session.messages.push(msg);
169161 saveMessages(this.session.id, [msg], thisTurn);
170162 this.coreHistory.push(msg);
171- this.snapshotStack.push(null);
172163 }
173164
174165 public async undoLastTurn(): Promise<boolean> {
175166 return undoLastTurn({
176167 session: this.session,
177168 coreHistory: this.coreHistory,
178- snapshotStack: this.snapshotStack,
179- getTurnIndex: () => this.turnIndex,
180169 setTurnIndex: (idx) => {
181170 this.turnIndex = idx;
182171 },
183- cwd: this.cwd,
184- reporter: this.reporter,
185172 });
186173 }
187174
@@ -228,7 +215,6 @@ export class SessionRunner {
228215 let lastAssistantText = "";
229216
230217 try {
231- this.snapshotStack.push(thisTurn);
232218 this.reporter.startSpinner("thinking");
233219 const events = runTurn({
234220 model: llm,
src/agent/undo-snapshot.ts+0−57
@@ -1,57 +0,0 @@
1-import type { CoreMessage } from "../llm-api/turn.ts";
2-import { deleteLastTurn, loadMessages } from "../session/db/index.ts";
3-import type { ActiveSession } from "../session/manager.ts";
4-import {
5- restoreSnapshot,
6- type SnapshotRestoreResult,
7-} from "../tools/snapshot.ts";
8-import type { AgentReporter } from "./reporter.ts";
9-
10-interface UndoContext {
11- session: ActiveSession;
12- coreHistory: CoreMessage[];
13- snapshotStack: Array<number | null>;
14- getTurnIndex: () => number;
15- setTurnIndex: (idx: number) => void;
16- cwd: string;
17- reporter: AgentReporter;
18-}
19-
20-export async function undoLastTurn(ctx: UndoContext): Promise<boolean> {
21- const { session, coreHistory, snapshotStack, cwd, reporter } = ctx;
22- const turnIndex = ctx.getTurnIndex();
23-
24- // Nothing to undo if there are no messages
25- if (session.messages.length === 0) return false;
26-
27- // Delete from DB and decrement turn counter
28- const deleted = deleteLastTurn(session.id);
29- if (!deleted) return false;
30-
31- const poppedTurn = snapshotStack.pop() ?? null;
32- if (turnIndex > 0) ctx.setTurnIndex(turnIndex - 1);
33-
34- // Sync in-memory history reliably with DB state
35- const remaining = loadMessages(session.id);
36- session.messages.length = 0;
37- session.messages.push(...remaining);
38-
39- coreHistory.length = 0;
40- coreHistory.push(...remaining);
41-
42- // Restore files from the SQLite snapshot for the turn being undone
43- if (poppedTurn !== null) {
44- const restoreResult: SnapshotRestoreResult = await restoreSnapshot(
45- cwd,
46- session.id,
47- poppedTurn,
48- );
49- if (restoreResult.restored === false && restoreResult.reason === "error") {
50- reporter.error(
51- "snapshot restore failed — some files may not have been reverted",
52- );
53- }
54- }
55-
56- return deleted;
57-}
src/agent/undo-turn.ts+32−0
@@ -0,0 +1,32 @@
1+import type { CoreMessage } from "../llm-api/turn.ts";
2+import {
3+ deleteLastTurn,
4+ getMaxTurnIndex,
5+ loadMessages,
6+} from "../session/db/index.ts";
7+import type { ActiveSession } from "../session/manager.ts";
8+
9+interface UndoContext {
10+ session: ActiveSession;
11+ coreHistory: CoreMessage[];
12+ setTurnIndex: (idx: number) => void;
13+}
14+
15+export async function undoLastTurn(ctx: UndoContext): Promise<boolean> {
16+ const { session, coreHistory } = ctx;
17+
18+ if (session.messages.length === 0) return false;
19+
20+ const deleted = deleteLastTurn(session.id);
21+ if (!deleted) return false;
22+
23+ const remaining = loadMessages(session.id);
24+ session.messages.length = 0;
25+ session.messages.push(...remaining);
26+
27+ coreHistory.length = 0;
28+ coreHistory.push(...remaining);
29+
30+ ctx.setTurnIndex(getMaxTurnIndex(session.id) + 1);
31+ return true;
32+}
src/cli/commands-help.ts+1−1
@@ -13,7 +13,7 @@ export function renderHelpCommand(
1313
1414 const cmds: [string, string][] = [
1515 ["/model [id]", "list or switch models (fetches live list)"],
16- ["/undo", "revert the last turn"],
16+ ["/undo", "remove the last conversation turn"],
1717 ["/reasoning [on|off]", "toggle display of model reasoning output"],
1818 ["/context [prune|cap]", "configure context pruning and tool-result caps"],
1919 [
src/cli/commands.ts+2−2
@@ -31,11 +31,11 @@ type CommandResult =
3131 // ─── Command handlers ─────────────────────────────────────────────────────────
3232
3333 async function handleUndo(ctx: CommandContext): Promise<void> {
34- ctx.startSpinner("undoing last turn");
34+ ctx.startSpinner("removing last turn");
3535 try {
3636 const ok = await ctx.undoLastTurn();
3737 if (ok) {
38- writeln(`${PREFIX.success} ${c.dim("last turn undone")}`);
38+ writeln(`${PREFIX.success} ${c.dim("last conversation turn removed")}`);
3939 } else {
4040 writeln(`${PREFIX.info} ${c.dim("nothing to undo")}`);
4141 }
src/session/db/connection.ts+1−15
@@ -92,20 +92,6 @@ const SCHEMA = `
9292 key TEXT PRIMARY KEY,
9393 value TEXT NOT NULL
9494 );
95-
96-
97-
98- CREATE TABLE IF NOT EXISTS snapshots (
99- id INTEGER PRIMARY KEY AUTOINCREMENT,
100- session_id TEXT NOT NULL,
101- turn_index INTEGER NOT NULL,
102- path TEXT NOT NULL,
103- content BLOB,
104- existed INTEGER NOT NULL
105- );
106-
107- CREATE INDEX IF NOT EXISTS idx_snapshots_turn
108- ON snapshots(session_id, turn_index);
10995 `;
11096
11197 let _db: Database | null = null;
@@ -162,7 +148,7 @@ export function getDb(): Database {
162148 return _db;
163149 }
164150
165-/** Keep only this many most-recent sessions (messages/snapshots cascade). */
151+/** Keep only this many most-recent sessions. */
166152 const MAX_SESSIONS = 100;
167153 /** Keep only this many most-recent prompt_history entries. */
168154 const MAX_PROMPT_HISTORY = 500;
src/session/db/index.ts+0−1
@@ -4,4 +4,3 @@ export * from "./message-repo.ts";
44 export * from "./model-info-repo.ts";
55 export * from "./session-repo.ts";
66 export * from "./settings-repo.ts";
7-export * from "./snapshot-repo.ts";
src/session/db/snapshot-repo.ts+0−65
@@ -1,65 +0,0 @@
1-import { getDb } from "./connection.ts";
2-
3-interface SnapshotFile {
4- /** Path relative to the project cwd */
5- path: string;
6- /** Raw file contents, or null if the file did not exist before the turn */
7- content: Uint8Array | null;
8- /** True if the file existed before the turn; false if the agent created it */
9- existed: boolean;
10-}
11-
12-export function saveSnapshot(
13- sessionId: string,
14- turnIndex: number,
15- files: SnapshotFile[],
16-): void {
17- const db = getDb();
18- const stmt = db.prepare(
19- `INSERT INTO snapshots (session_id, turn_index, path, content, existed)
20- VALUES (?, ?, ?, ?, ?)`,
21- );
22- const insert = db.transaction(() => {
23- for (const f of files) {
24- stmt.run(
25- sessionId,
26- turnIndex,
27- f.path,
28- f.content ?? null,
29- f.existed ? 1 : 0,
30- );
31- }
32- });
33- insert();
34-}
35-
36-export function loadSnapshot(
37- sessionId: string,
38- turnIndex: number,
39-): SnapshotFile[] {
40- const rows = getDb()
41- .query<
42- { path: string; content: Uint8Array | null; existed: number },
43- [string, number]
44- >(
45- "SELECT path, content, existed FROM snapshots WHERE session_id = ? AND turn_index = ?",
46- )
47- .all(sessionId, turnIndex);
48- return rows.map((r) => ({
49- path: r.path,
50- content: r.content ?? null,
51- existed: r.existed === 1,
52- }));
53-}
54-
55-export function deleteSnapshot(sessionId: string, turnIndex: number): void {
56- getDb().run("DELETE FROM snapshots WHERE session_id = ? AND turn_index = ?", [
57- sessionId,
58- turnIndex,
59- ]);
60-}
61-
62-/** Delete all snapshot rows for a session (e.g. on session reset). */
63-export function deleteAllSnapshots(sessionId: string): void {
64- getDb().run("DELETE FROM snapshots WHERE session_id = ?", [sessionId]);
65-}
src/tools/snapshot.test.ts+0−238
@@ -1,238 +0,0 @@
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 {
6- deleteSnapshot,
7- loadSnapshot,
8- saveSnapshot,
9-} from "../session/db/index.ts";
10-import { restoreSnapshot, snapshotBeforeEdit } from "./snapshot.ts";
11-
12-// ─── Helpers ──────────────────────────────────────────────────────────────────
13-
14-function spawnSync(args: string[], cwd: string): void {
15- const proc = Bun.spawnSync(args, { cwd, stdout: "pipe", stderr: "pipe" });
16- if (proc.exitCode !== 0) {
17- throw new Error(
18- `Command failed: ${args.join(" ")}\n${proc.stderr.toString()}`,
19- );
20- }
21-}
22-
23-/** Create a minimal git repo in a temp directory and return its path. */
24-function makeRepo(): string {
25- const dir = join(
26- tmpdir(),
27- `mc-snap-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
28- );
29- mkdirSync(dir, { recursive: true });
30- spawnSync(["git", "init"], dir);
31- spawnSync(["git", "config", "user.email", "test@example.com"], dir);
32- spawnSync(["git", "config", "user.name", "Test"], dir);
33- // Initial commit so HEAD exists
34- writeFileSync(join(dir, "README.md"), "hello\n");
35- spawnSync(["git", "add", "README.md"], dir);
36- spawnSync(["git", "commit", "-m", "init"], dir);
37- return dir;
38-}
39-
40-function cleanRepo(dir: string): void {
41- rmSync(dir, { recursive: true, force: true });
42-}
43-
44-function useTestRepo() {
45- const state = { repoDir: "", sessionId: crypto.randomUUID() };
46- beforeEach(() => {
47- state.repoDir = makeRepo();
48- });
49- afterEach(() => {
50- cleanRepo(state.repoDir);
51- });
52- return state;
53-}
54-
55-// ─── db helpers ───────────────────────────────────────────────────────────────
56-
57-describe("saveSnapshot / loadSnapshot / deleteSnapshot", () => {
58- test("round-trips file entries", () => {
59- const sessionId = crypto.randomUUID();
60- const turnIndex = 42;
61- const content = new TextEncoder().encode("hello world");
62-
63- saveSnapshot(sessionId, turnIndex, [
64- { path: "src/foo.ts", content, existed: true },
65- { path: "src/new.ts", content: null, existed: false },
66- ]);
67-
68- const rows = loadSnapshot(sessionId, turnIndex);
69- expect(rows).toHaveLength(2);
70-
71- const foo = rows.find((r) => r.path === "src/foo.ts");
72- expect(foo?.existed).toBe(true);
73- expect(foo?.content).toEqual(content);
74-
75- const newFile = rows.find((r) => r.path === "src/new.ts");
76- expect(newFile?.existed).toBe(false);
77- expect(newFile?.content).toBeNull();
78-
79- // Cleanup
80- deleteSnapshot(sessionId, turnIndex);
81- expect(loadSnapshot(sessionId, turnIndex)).toHaveLength(0);
82- });
83-});
84-
85-// ─── snapshotBeforeEdit ───────────────────────────────────────────────────────
86-
87-describe("snapshotBeforeEdit", () => {
88- const state = useTestRepo();
89-
90- test("snapshots a modified tracked file before edit", async () => {
91- const filePath = join(state.repoDir, "README.md");
92- const snappedPaths = new Set<string>();
93-
94- await snapshotBeforeEdit(
95- state.repoDir,
96- state.sessionId,
97- 3,
98- filePath,
99- snappedPaths,
100- );
101-
102- const rows = loadSnapshot(state.sessionId, 3);
103- const readme = rows.find((r) => r.path === "README.md");
104- expect(readme).toBeDefined();
105- expect(readme?.existed).toBe(true);
106- expect(new TextDecoder().decode(readme?.content ?? undefined)).toBe(
107- "hello\n",
108- );
109- expect(snappedPaths.has("README.md")).toBe(true);
110-
111- deleteSnapshot(state.sessionId, 3);
112- });
113-
114- test("snapshots an untracked new file with existed=false", async () => {
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- );
125-
126- const rows = loadSnapshot(state.sessionId, 4);
127- const f = rows.find((r) => r.path === "untracked.txt");
128- expect(f).toBeDefined();
129- // File didn't exist before edit
130- expect(f?.existed).toBe(false);
131- expect(f?.content).toBeNull();
132-
133- deleteSnapshot(state.sessionId, 4);
134- });
135-
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- );
147-
148- // Change the file
149- writeFileSync(filePath, "changed\n");
150-
151- // Second call should be a no-op
152- await snapshotBeforeEdit(
153- state.repoDir,
154- state.sessionId,
155- 5,
156- filePath,
157- snappedPaths,
158- );
159-
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- );
165-
166- deleteSnapshot(state.sessionId, 5);
167- });
168-});
169-
170-// ─── restoreSnapshot ──────────────────────────────────────────────────────────
171-
172-describe("restoreSnapshot", () => {
173- const state = useTestRepo();
174-
175- test("returns not-found when no snapshot exists", async () => {
176- const result = await restoreSnapshot(state.repoDir, state.sessionId, 99);
177- expect(result.restored).toBe(false);
178- if (!result.restored) expect(result.reason).toBe("not-found");
179- });
180-
181- test("restores a modified file to its pre-turn content", async () => {
182- const filePath = join(state.repoDir, "README.md");
183- const originalContent = "hello\n";
184- saveSnapshot(state.sessionId, 10, [
185- {
186- path: "README.md",
187- content: new TextEncoder().encode(originalContent),
188- existed: true,
189- },
190- ]);
191-
192- writeFileSync(filePath, "agent changed this\n");
193-
194- const result = await restoreSnapshot(state.repoDir, state.sessionId, 10);
195- expect(result.restored).toBe(true);
196-
197- const restoredContent = await Bun.file(filePath).text();
198- expect(restoredContent).toBe(originalContent);
199-
200- expect(loadSnapshot(state.sessionId, 10)).toHaveLength(0);
201- });
202-
203- test("deletes a file that was created by the agent (existed=false)", async () => {
204- const newFile = join(state.repoDir, "agent-created.ts");
205- writeFileSync(newFile, "export const x = 1;\n");
206-
207- saveSnapshot(state.sessionId, 11, [
208- { path: "agent-created.ts", content: null, existed: false },
209- ]);
210-
211- const result = await restoreSnapshot(state.repoDir, state.sessionId, 11);
212- expect(result.restored).toBe(true);
213-
214- const exists = await Bun.file(newFile).exists();
215- expect(exists).toBe(false);
216-
217- expect(loadSnapshot(state.sessionId, 11)).toHaveLength(0);
218- });
219-
220- test("end-to-end: snapshotBeforeEdit then agent creates file, restoreSnapshot deletes it", async () => {
221- const agentFile = join(state.repoDir, "generated.ts");
222- const snappedPaths = new Set<string>();
223-
224- await snapshotBeforeEdit(
225- state.repoDir,
226- state.sessionId,
227- 13,
228- agentFile,
229- snappedPaths,
230- );
231-
232- writeFileSync(agentFile, "export const y = 2;\n");
233-
234- const result = await restoreSnapshot(state.repoDir, state.sessionId, 13);
235- expect(result.restored).toBe(true);
236- expect(await Bun.file(agentFile).exists()).toBe(false);
237- });
238-});
src/tools/snapshot.ts+0−111
@@ -1,111 +0,0 @@
1-/**
2- * SQLite-based turn snapshots for /undo.
3- *
4- * Before an agent makes a tool-managed file modification, we snapshot the
5- * exact state of that file on disk.
6- *
7- * On /undo, we restore those files from the DB and clean up the snapshot rows.
8- */
9-
10-import { unlinkSync } from "node:fs";
11-import { isAbsolute, join, relative } from "node:path";
12-import {
13- deleteSnapshot,
14- loadSnapshot,
15- saveSnapshot,
16-} from "../session/db/index.ts";
17-
18-// ─── Types ────────────────────────────────────────────────────────────────────
19-
20-export type SnapshotRestoreResult =
21- | { restored: true }
22- | { restored: false; reason: "not-found" | "error" };
23-
24-// ─── Public API ───────────────────────────────────────────────────────────────
25-
26-/**
27- * Snapshot a file's state before editing it, if it hasn't been snapshotted this turn.
28- * Does not throw.
29- */
30-export async function snapshotBeforeEdit(
31- cwd: string,
32- sessionId: string,
33- turnIndex: number,
34- filePath: string,
35- snappedPaths: Set<string>,
36-): Promise<void> {
37- try {
38- const absPath = isAbsolute(filePath) ? filePath : join(cwd, filePath);
39- const relPath = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;
40-
41- if (snappedPaths.has(relPath)) return;
42- snappedPaths.add(relPath);
43-
44- let existed = false;
45- let content: Uint8Array | null = null;
46-
47- const file = Bun.file(absPath);
48- if (await file.exists()) {
49- existed = true;
50- content = new Uint8Array(await file.arrayBuffer());
51- }
52-
53- saveSnapshot(sessionId, turnIndex, [{ path: relPath, content, existed }]);
54- } catch {
55- // Ignore errors — undo is a best-effort mechanism
56- }
57-}
58-
59-/**
60- * Restore files from the snapshot for the given turn and remove the snapshot.
61- * Returns whether files were restored.
62- */
63-export async function restoreSnapshot(
64- cwd: string,
65- sessionId: string,
66- turnIndex: number,
67-): Promise<SnapshotRestoreResult> {
68- try {
69- const files = loadSnapshot(sessionId, turnIndex);
70-
71- if (files.length === 0) return { restored: false, reason: "not-found" };
72-
73- let anyFailed = false;
74-
75- for (const file of files) {
76- const absPath = join(cwd, file.path);
77-
78- if (!file.existed) {
79- // File was created by the agent (or is a rename destination) — delete it
80- try {
81- if (await Bun.file(absPath).exists()) {
82- unlinkSync(absPath);
83- }
84- } catch {
85- anyFailed = true;
86- }
87- continue;
88- }
89-
90- // File existed before — restore its content
91- if (file.content !== null) {
92- try {
93- await Bun.write(absPath, file.content);
94- } catch {
95- anyFailed = true;
96- }
97- }
98- }
99-
100- // Only delete the snapshot when all files were restored successfully.
101- // If any write failed, keep the snapshot so a retry is possible.
102- if (!anyFailed) {
103- deleteSnapshot(sessionId, turnIndex);
104- }
105- return anyFailed
106- ? { restored: false, reason: "error" }
107- : { restored: true };
108- } catch {
109- return { restored: false, reason: "error" };
110- }
111-}