| 1 | //! Git-based `/undo` and `/redo` for agent file changes. |
| 2 | //! |
| 3 | //! The agent can change files through tools *and* shell commands, so the only |
| 4 | //! reliable way to reverse a whole response is git. Before each agent run we |
| 5 | //! snapshot the entire working tree (tracked files, modifications, deletions |
| 6 | //! and untracked non-ignored files) into a throwaway commit object created |
| 7 | //! with `git commit-tree`. Because the snapshot is just an object — never a |
| 8 | //! branch or a ref — HEAD and the user's history are never touched. |
| 9 | //! |
| 10 | //! `/undo` restores that pre-run snapshot; `/redo` re-applies the state that |
| 11 | //! was undone. Restoring uses `git read-tree` + `git checkout-index` + |
| 12 | //! `git clean`, which rewrites the working tree *without* moving HEAD. |
| 13 | //! |
| 14 | //! All git commands run against the repository root (found via |
| 15 | //! `git rev-parse --show-toplevel`), so changes made anywhere in the repo are |
| 16 | //! captured even when wynba was started from a subdirectory. The snapshot |
| 17 | //! index is a throwaway file in the OS temp dir, so the real index is never |
| 18 | //! touched. |
| 19 | //! |
| 20 | //! If the current directory is not inside a git repository the snapshots are |
| 21 | //! skipped and `/undo` / `/redo` report that they have nothing to work with. |
| 22 | |
| 23 | use std::path:: |
| 24 | use std::process:: |
| 25 | |
| 26 | use anyhow::{Context |
| 27 | use rusqlite::Connection |
| 28 | |
| 29 | use crate::db; |
| 30 | |
| 31 | /// settings keys (scoped per session) holding the pending undo/redo snapshot |
| 32 | /// hashes. An empty value means "not set". |
| 33 | fn before_key(session_id: |
| 34 | format!("git_undo_before:{session_id |
| 35 | } |
| 36 | fn after_key(session_id: |
| 37 | format!("git_undo_after:{session_id |
| 38 | } |
| 39 | |
| 40 | /// Run `git` in `dir` with `args` and return trimmed stdout. Errors if git is |
| 41 | /// missing or the command fails. |
| 42 | fn git_in(dir: |
| 43 | git_env_in(dir, args |
| 44 | } |
| 45 | |
| 46 | /// Like [`git_in`] but with extra environment variables (used to point git at |
| 47 | /// a throwaway index so the real index and working tree stay untouched). |
| 48 | fn git_env_in(dir: |
| 49 | let mut cmd |
| 50 | cmd.args(args |
| 51 | for (k, v |
| 52 | cmd.env(k |
| 53 | } |
| 54 | let out = |
| 55 | if !out.status. |
| 56 | let stderr = |
| 57 | return Err(anyhow |
| 58 | "git {} failed: {}", |
| 59 | args.join(" |
| 60 | stderr.trim() |
| 61 | )); |
| 62 | } |
| 63 | Ok(String |
| 64 | } |
| 65 | |
| 66 | /// The repository root of the current working directory, or `None` when we are |
| 67 | /// not inside a git work tree. |
| 68 | fn repo_root() -> Option |
| 69 | let out = |
| 70 | .args(["rev-parse", |
| 71 | .output() |
| 72 | .ok()?; |
| 73 | if !out.status. |
| 74 | return None; |
| 75 | } |
| 76 | let root = |
| 77 | if root.is_empty() |
| 78 | None |
| 79 | } else { |
| 80 | Some(PathBuf |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// Does the commit object still exist in the object store? (It could have been |
| 85 | /// pruned by `git gc`.) |
| 86 | fn commit_exists_in(root: |
| 87 | Command::new( |
| 88 | .args(["cat-file", |
| 89 | .current_dir(root) |
| 90 | .output() |
| 91 | .map(|o| |
| 92 | .unwrap_or(false) |
| 93 | } |
| 94 | |
| 95 | /// Capture the whole working tree of `root` as an unreferenced commit object. |
| 96 | /// Returns the hash. Never touches HEAD, the real index, or the working tree. |
| 97 | fn snapshot_in(root: |
| 98 | let tmp_idx = |
| 99 | std::env::temp_dir |
| 100 | let idx_env = |
| 101 | let run = |
| 102 | let result = |
| 103 | run(&["read-tree" |
| 104 | run(&["add" |
| 105 | let tree = |
| 106 | // Parent the snapshot on HEAD when it exists so the object stays |
| 107 | // reachable-ish (and so `git diff HEAD <snapshot>` reads naturally); |
| 108 | // on a repo with no commits yet it becomes a root commit. |
| 109 | match git_in(root, |
| 110 | Ok(head) |
| 111 | run(&["commit-tree" |
| 112 | } |
| 113 | _ => run( |
| 114 | } |
| 115 | })(); |
| 116 | let _ = |
| 117 | result |
| 118 | } |
| 119 | |
| 120 | /// Number of paths whose content differs between two commits/trees — a rough |
| 121 | /// "files changed" count for the undo/redo summary message. |
| 122 | fn diff_count(root: |
| 123 | match git_in(root, |
| 124 | Ok(out) |
| 125 | Err(_) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// Rewrite the working tree of `root` to match `target`, leaving HEAD/branch |
| 130 | /// untouched. `diff_against` is only used to count the files the operation |
| 131 | /// touches. Returns the number of changed files. |
| 132 | fn restore_in(root: |
| 133 | let changed = |
| 134 | // Put the target tree into the index (index only — HEAD doesn't move). |
| 135 | git_in(root, & |
| 136 | // Copy every indexed path into the working tree, overwriting what's there |
| 137 | // and recreating anything that was deleted. |
| 138 | git_in(root, & |
| 139 | // Drop untracked files the run created that aren't in the snapshot. No |
| 140 | // `-x`: ignored files (node_modules, .env, build output…) are left alone. |
| 141 | let _ = |
| 142 | // Unstage so pre-existing untracked files are untracked again, matching |
| 143 | // the pre-run state. Best-effort: on an unborn-HEAD repo this is a no-op. |
| 144 | let _ = |
| 145 | Ok(changed) |
| 146 | } |
| 147 | |
| 148 | /// Call right before an agent run starts: snapshot the pre-run working tree so |
| 149 | /// `/undo` can restore it, and clear any pending redo (a new run invalidates |
| 150 | /// the previous undo). |
| 151 | pub fn on_run_start(conn |
| 152 | let after = |
| 153 | if db::get_setting( |
| 154 | db::set_setting(conn |
| 155 | } |
| 156 | let before = |
| 157 | match repo_root() { |
| 158 | Some(root) |
| 159 | Ok(hash) |
| 160 | // git exists but the snapshot failed (e.g. a broken repo); fall |
| 161 | // back to "no undo" for this run rather than crashing the agent. |
| 162 | Err(_) |
| 163 | }, |
| 164 | // Not a git repo: undo can't work for this session, but don't leave a |
| 165 | // stale snapshot around. |
| 166 | None => db |
| 167 | } |
| 168 | Ok(()) |
| 169 | } |
| 170 | |
| 171 | /// `/undo`: restore the working tree to the state captured before the last |
| 172 | /// agent run. Returns a human-readable result, or `None` when there is |
| 173 | /// nothing to undo. |
| 174 | pub fn undo(conn |
| 175 | let before = |
| 176 | let Some( |
| 177 | return Ok(None |
| 178 | }; |
| 179 | let Some( |
| 180 | db::set_setting(conn |
| 181 | return Ok(Some |
| 182 | }; |
| 183 | if !commit_exists_in(&root |
| 184 | db::set_setting(conn |
| 185 | return Ok(Some |
| 186 | "Nothing to undo: the pre-run snapshot was pruned by `git gc`.".into(), |
| 187 | )); |
| 188 | } |
| 189 | // Snapshot the current state so /redo can bring it back. |
| 190 | let after = |
| 191 | let changed = |
| 192 | db::set_setting(conn |
| 193 | db::set_setting(conn |
| 194 | Ok(Some |
| 195 | "Undid the last agent response — restored {changed} changed file(s) to \ |
| 196 | their pre-run state (via git). Use /redo to re-apply it." |
| 197 | ))) |
| 198 | } |
| 199 | |
| 200 | /// `/redo` (git half): re-apply the changes that `/undo` just took back. |
| 201 | /// Returns `None` when there is no pending git redo. |
| 202 | pub fn redo(conn |
| 203 | let after = |
| 204 | let Some( |
| 205 | return Ok(None |
| 206 | }; |
| 207 | let Some( |
| 208 | db::set_setting(conn |
| 209 | return Ok(Some |
| 210 | }; |
| 211 | if !commit_exists_in(&root |
| 212 | db::set_setting(conn |
| 213 | return Ok(Some |
| 214 | "Nothing to redo: the undone snapshot was pruned by `git gc`.".into(), |
| 215 | )); |
| 216 | } |
| 217 | let cur = |
| 218 | let changed = |
| 219 | db::set_setting(conn |
| 220 | Ok(Some |
| 221 | "Redid the undo — re-applied {changed} file(s) from the agent's last \ |
| 222 | response (via git)." |
| 223 | ))) |
| 224 | } |
| 225 | |
| 226 | #[cfg(test)] |
| 227 | mod tests { |
| 228 | use super::*; |
| 229 | use std::fs; |
| 230 | |
| 231 | /// Create a throwaway git repo at a fresh temp path and return its root. |
| 232 | /// Uses `git -C` so the process CWD is never touched; snapshots are taken |
| 233 | /// with the module's repo-root helpers pointing at the returned path. |
| 234 | fn make_repo() -> |
| 235 | let dir = |
| 236 | "wynba-gitundo-test-{}-{}", |
| 237 | std::process::id |
| 238 | uuid::Uuid::now_v7 |
| 239 | )); |
| 240 | let _ = |
| 241 | fs::create_dir_all(&dir |
| 242 | let run = |
| 243 | Command::new( |
| 244 | .args(args) |
| 245 | .current_dir(&dir) |
| 246 | .output() |
| 247 | .unwrap() |
| 248 | }; |
| 249 | assert!(run(& |
| 250 | assert!(run(& |
| 251 | assert!(run(& |
| 252 | fs::write(dir |
| 253 | fs::write(dir |
| 254 | assert!(run(& |
| 255 | assert!(run(& |
| 256 | dir |
| 257 | } |
| 258 | |
| 259 | fn head(root: |
| 260 | git_in(root, & |
| 261 | } |
| 262 | |
| 263 | #[test] |
| 264 | fn undo_and_redo_roundtrip_via_git() { |
| 265 | let root = |
| 266 | let head_before = |
| 267 | |
| 268 | let before = |
| 269 | |
| 270 | // Simulate an agent response: edit a tracked file, delete one, create |
| 271 | // untracked ones (including nested) and delete an untracked one. |
| 272 | fs::write(root |
| 273 | fs::remove_file(root |
| 274 | fs::write(root |
| 275 | fs::create_dir_all(root |
| 276 | fs::write(root |
| 277 | |
| 278 | let after = |
| 279 | assert_ne!(before, |
| 280 | |
| 281 | // ---- undo ---- |
| 282 | let changed = |
| 283 | assert!(changed >= |
| 284 | assert_eq!(fs:: |
| 285 | assert!(!root. |
| 286 | assert!(!root. |
| 287 | assert_eq!( |
| 288 | fs::read_to_string(root |
| 289 | "keep\n" |
| 290 | ); |
| 291 | assert_eq!(head(& |
| 292 | // The index was reset: a.txt is unmodified, existing_untracked is |
| 293 | // untracked again (exactly the pre-run state). |
| 294 | let status = |
| 295 | assert_eq!(status.trim |
| 296 | |
| 297 | // ---- redo ---- |
| 298 | let cur = |
| 299 | let changed = |
| 300 | assert!(changed >= |
| 301 | assert_eq!( |
| 302 | fs::read_to_string(root |
| 303 | "line2-modified\n" |
| 304 | ); |
| 305 | assert!(root.join |
| 306 | assert!(root.join |
| 307 | assert!(!root. |
| 308 | assert_eq!(head(& |
| 309 | |
| 310 | fs::remove_dir_all(root |
| 311 | } |
| 312 | |
| 313 | #[test] |
| 314 | fn snapshot_parents_on_head_without_moving_it() { |
| 315 | let root = |
| 316 | let head_before = |
| 317 | let snap = |
| 318 | assert_eq!(head(& |
| 319 | // `snap^` is the original HEAD: the snapshot commit is a child of it. |
| 320 | let parent = |
| 321 | assert_eq!(parent, |
| 322 | fs::remove_dir_all(root |
| 323 | } |
| 324 | } |