xonecas.io
64875
Mc

mini-coder / commit cb62267

feat: git-based file undo for /undo command

Before each agent turn, stash the working tree with a labelled message
(mini-coder:turn:N). On /undo, pop the stash for that specific turn so
files are restored alongside conversation history.

- gitStashTurn: runs before saveMessages; uses exit code (not stdout
  parsing) to detect whether a stash was created
- gitStashPop: matches stash by exact turn index to avoid popping the
  wrong stash in multi-turn sessions; returns a typed result so merge
  conflicts surface as a renderError instead of silent failure
- lastStash tracks whether a stash was created per-turn; cleared on
  new session and after each undo
- startNewSession clears lastStash to prevent stale stash pops

xonecas2026-02-21 cb62267116769cbd87dccc694aace9e881d1aa62 parent 1cf85eb

3 files changed

src/agent/agent.ts+30−1
@@ -20,6 +20,11 @@ import { getContextWindow, resolveModel } from "../llm-api/providers.ts";
2020 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";
23+import {
24+ type GitStashPopResult,
25+ gitStashPop,
26+ gitStashTurn,
27+} from "../tools/git-stash.ts";
2328
2429 import {
2530 deleteLastTurn,
@@ -286,7 +291,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
286291 cwd,
287292 runSubagent: (prompt) => runSubagent(prompt),
288293
289- undoLastTurn: () => {
294+ undoLastTurn: async () => {
290295 // Nothing to undo if there are no messages
291296 if (session.messages.length === 0) return false;
292297
@@ -315,7 +320,20 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
315320
316321 // Delete from DB and decrement turn counter
317322 const deleted = deleteLastTurn(session.id);
323+ const poppedTurn = lastStash;
318324 if (turnIndex > 0) turnIndex--;
325+ lastStash = null;
326+
327+ // Restore files via git stash pop for the specific turn being undone
328+ if (poppedTurn !== null) {
329+ const popResult: GitStashPopResult = await gitStashPop(cwd, poppedTurn);
330+ if (popResult.restored === false && popResult.conflict) {
331+ renderError(
332+ "git stash pop conflict — your working tree may need manual resolution",
333+ );
334+ }
335+ }
336+
319337 return deleted;
320338 },
321339 connectMcpServer: connectAndAddMcp,
@@ -326,12 +344,15 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
326344 totalIn = 0;
327345 totalOut = 0;
328346 lastContextTokens = 0;
347+ lastStash = null;
329348 },
330349 };
331350 const spinner = new Spinner();
332351 let totalIn = 0;
333352 let totalOut = 0;
334353 let lastContextTokens = 0;
354+ // turnIndex of the last stash created, or null if no stash was made
355+ let lastStash: number | null = null;
335356
336357 // ── Handle initial prompt (non-interactive) ────────────────────────────────
337358 if (opts.initialPrompt) {
@@ -401,6 +422,11 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
401422 // Capture turn index for this turn (user + response share the same index)
402423 const thisTurn = turnIndex++;
403424
425+ // 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);
429+
404430 const coreContent = planMode
405431 ? `${resolvedText}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
406432 : resolvedText;
@@ -416,6 +442,9 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
416442 const onSigInt = () => abortController.abort();
417443 process.once("SIGINT", onSigInt);
418444
445+ // Store stash metadata so undoLastTurn can pop the right stash
446+ lastStash = stashed ? thisTurn : null;
447+
419448 spinner.start("thinking");
420449
421450 const events = runTurn({
src/cli/commands.ts+7−5
@@ -18,7 +18,7 @@ export interface CommandContext {
1818 setModel: (model: string) => void;
1919 planMode: boolean;
2020 setPlanMode: (enabled: boolean) => void;
21- undoLastTurn: () => boolean;
21+ undoLastTurn: () => Promise<boolean>;
2222 startNewSession: () => void;
2323
2424 connectMcpServer: (name: string) => Promise<void>;
@@ -123,10 +123,12 @@ function handlePlan(ctx: CommandContext): void {
123123 }
124124 }
125125
126-function handleUndo(ctx: CommandContext): void {
127- const ok = ctx.undoLastTurn();
126+async function handleUndo(ctx: CommandContext): Promise<void> {
127+ const ok = await ctx.undoLastTurn();
128128 if (ok) {
129- writeln(`${PREFIX.success} ${c.dim("last turn removed from history")}`);
129+ writeln(
130+ `${PREFIX.success} ${c.dim("last turn undone — history and files restored")}`,
131+ );
130132 } else {
131133 writeln(`${PREFIX.info} ${c.dim("nothing to undo")}`);
132134 }
@@ -351,7 +353,7 @@ export async function handleCommand(
351353 return { type: "handled" };
352354
353355 case "undo":
354- handleUndo(ctx);
356+ await handleUndo(ctx);
355357 return { type: "handled" };
356358
357359 case "plan":
src/tools/git-stash.ts+93−0
@@ -0,0 +1,93 @@
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+}