返回 CodeWhale
repo.rs
根目录 / crates / snapshot / src / repo.rs
1 //! Side-git repository wrapper for workspace snapshots.
2 //!
3 //! `SnapshotRepo` shells out to the system `git` binary (we deliberately
4 //! avoid `git2` to dodge its LGPL surface). The two paths that matter:
5 //!
6 //! - `git_dir` → `<snapshot state dir>/<project_hash>/<worktree_hash>/.git`
7 //! - `work_tree` → the user's actual workspace
8 //!
9 //! Every git invocation passes both `--git-dir` AND `--work-tree`. That is
10 //! the single biggest safety mechanism: it guarantees we never accidentally
11 //! mutate the user's own `.git` directory. If git can't find the side
12 //! repo, the command fails fast instead of falling back to "current
13 //! directory".
14
15 use std::cell::RefCell;
16 use std::collections::{HashMap, HashSet};
17 use std::io;
18 use std::path::{Component, Path, PathBuf};
19 use std::process::Output;
20 use std::time::{Duration, SystemTime, UNIX_EPOCH};
21
22 use codewhale_dependencies::{ExternalTool, run_bounded_git_with_timeout};
23
24 use super::paths::{ensure_snapshot_dir, snapshot_git_dir};
25
26 /// Identifier for a snapshot — the underlying git commit id.
27 ///
28 /// The field is private: [`SnapshotId::parse`] is the only way to build one,
29 /// so every value handed to `git` as a revision is a full SHA-1 or SHA-256
30 /// hex object id and can never be read as an option or a revision expression.
31 #[derive(Debug, Clone, PartialEq, Eq)]
32 pub struct SnapshotId(String);
33
34 impl SnapshotId {
35 /// Accept exactly a full hex object id: 40 (SHA-1) or 64 (SHA-256)
36 /// ASCII hex digits. Anything else is `InvalidInput`.
37 pub fn parse(id: &str) -> io::Result<Self> {
38 if Self::is_well_formed(id) {
39 Ok(Self(id.to_string()))
40 } else {
41 Err(io::Error::new(
42 io::ErrorKind::InvalidInput,
43 "snapshot id must be a full hexadecimal commit id",
44 ))
45 }
46 }
47
48 /// Whether `id` would be accepted by [`SnapshotId::parse`].
49 pub fn is_well_formed(id: &str) -> bool {
50 matches!(id.len(), 40 | 64) && id.bytes().all(|b| b.is_ascii_hexdigit())
51 }
52
53 /// Take the id string out.
54 pub fn into_string(self) -> String {
55 self.0
56 }
57
58 /// Borrow the SHA as a string slice.
59 pub fn as_str(&self) -> &str {
60 &self.0
61 }
62 }
63
64 /// A single snapshot record (one row in `git log`).
65 #[derive(Debug, Clone)]
66 pub struct Snapshot {
67 /// Commit SHA inside the side repo.
68 pub id: SnapshotId,
69 /// Subject line — the label passed to [`SnapshotRepo::snapshot`].
70 pub label: String,
71 /// Root tree of the snapshot commit. Unlike [`Self::id`] it survives the
72 /// survivor-chain rebuild every prune performs (the rebuild re-commits
73 /// the same tree under a new commit id), so it is the durable identity a
74 /// recorded restore point is resolved by.
75 pub tree: SnapshotId,
76 /// Author timestamp (Unix seconds).
77 pub timestamp: i64,
78 /// Session this snapshot belongs to, when recorded (encoded as a
79 /// `[sid=...] ` label prefix). `None` for legacy snapshots taken
80 /// before session tagging existed.
81 pub session_id: Option<String>,
82 }
83
84 /// One path that differs between two snapshots
85 /// ([`SnapshotRepo::path_changes_between`]).
86 #[derive(Debug, Clone, PartialEq, Eq)]
87 pub struct SnapshotPathChange {
88 /// Workspace-relative path, as git names it.
89 pub path: String,
90 /// git's status letter: `A` added, `D` deleted, `M` modified, `T` type
91 /// changed.
92 pub status: char,
93 /// Lines added and removed; `None` for a binary file.
94 pub added: Option<u64>,
95 pub removed: Option<u64>,
96 }
97
98 /// What the work tree holds now that a snapshot did not
99 /// ([`SnapshotRepo::work_tree_changes_since`]), as `git diff` writes it.
100 #[derive(Debug, Clone, PartialEq, Eq)]
101 pub struct WorkTreeChanges {
102 /// One changed path per line, as `git diff --name-only` writes them.
103 pub names: String,
104 /// `git diff --stat`.
105 pub stat: String,
106 /// The unified patch, cut at the caller's bound on a char boundary; empty
107 /// when more than [`WORK_TREE_PATCH_MAX_LINES`] lines changed.
108 pub patch: String,
109 /// Whether the patch was cut or left out.
110 pub patch_truncated: bool,
111 }
112
113 /// Changed lines past which [`SnapshotRepo::work_tree_changes_since`] does
114 /// not read the patch at all: git's whole output is buffered before it can be
115 /// cut, so a generated multi-gigabyte file must not be diffed into memory.
116 pub const WORK_TREE_PATCH_MAX_LINES: u64 = 200_000;
117
118 /// What a file-scoped restore did to one path, relative to the working tree
119 /// it was applied to.
120 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
121 pub enum PathRestoreAction {
122 /// Both the snapshot and the working tree had the path; its content came
123 /// back from the snapshot.
124 Modified,
125 /// The snapshot had the path and the working tree no longer did, so the
126 /// restore recreated the file.
127 Recreated,
128 /// The working tree had the path and the snapshot did not, so the restore
129 /// removed the file.
130 Removed,
131 }
132
133 impl PathRestoreAction {
134 /// Stable wire name, also used by the runtime API response.
135 pub fn as_str(self) -> &'static str {
136 match self {
137 Self::Modified => "modified",
138 Self::Recreated => "recreated",
139 Self::Removed => "removed",
140 }
141 }
142 }
143
144 /// Report of what `SnapshotRepo::restore_paths` did to one path.
145 #[derive(Debug, Clone)]
146 pub struct PathRestoreOutcome {
147 /// Workspace-relative path that was restored.
148 pub path: PathBuf,
149 /// How the working tree changed.
150 pub action: PathRestoreAction,
151 }
152
153 /// A snapshot as it was just written: its commit and the root tree it holds.
154 ///
155 /// The commit id can be rewritten by the prune that follows every snapshot
156 /// once the repo holds more than [`crate::DEFAULT_MAX_SNAPSHOTS`]
157 /// (see `rebuild_survivor_chain`); the tree id cannot, because a tree is
158 /// content-addressed and the rebuild re-commits the same tree.
159 #[derive(Debug, Clone, PartialEq, Eq)]
160 pub struct TakenSnapshot {
161 pub id: SnapshotId,
162 pub tree: SnapshotId,
163 }
164
165 /// Wrapper around the per-workspace side-git repo.
166 pub struct SnapshotRepo {
167 git_dir: PathBuf,
168 work_tree: PathBuf,
169 }
170
171 const STALE_TMP_PACK_AGE: Duration = Duration::from_secs(60 * 60);
172
173 /// Advisory lock file inside the side repo's `.git`. Every session, turn and
174 /// sub-agent working in one workspace shares one side repo, and its index,
175 /// HEAD and object store are only consistent when snapshot, restore, prune
176 /// and gc run one at a time: a gc in one session otherwise deleted another
177 /// session's new, not yet referenced commit and left HEAD on a missing
178 /// object.
179 const SNAPSHOT_LOCK_FILE: &str = "codewhale-snapshot.lock";
180
181 /// Longest a snapshot, restore or prune waits for another writer's lock
182 /// before failing (the turn then shows the snapshot-failure notice).
183 const SNAPSHOT_LOCK_WAIT: Duration = Duration::from_secs(30);
184
185 /// How often a waiting writer retries the lock.
186 const SNAPSHOT_LOCK_POLL: Duration = Duration::from_millis(5);
187
188 const SNAPSHOT_LOCK_REACQUIRE_DELAY: Duration = Duration::from_millis(50);
189
190 thread_local! {
191 /// Side repos whose write lock this thread already holds, so a locked
192 /// operation that calls another (restore takes a safety snapshot, a
193 /// snapshot runs the size prune) does not wait on its own lock.
194 static HELD_SNAPSHOT_LOCKS: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
195 }
196
197 static SNAPSHOT_LOCK_RELEASED_AT: std::sync::OnceLock<
198 std::sync::Mutex<HashMap<PathBuf, std::time::Instant>>,
199 > = std::sync::OnceLock::new();
200
201 fn snapshot_lock_released_at() -> &'static std::sync::Mutex<HashMap<PathBuf, std::time::Instant>> {
202 SNAPSHOT_LOCK_RELEASED_AT.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
203 }
204
205 /// Maximum total snapshot storage in megabytes before pruning kicks in at
206 /// snapshot time. Keeps the side repo from blowing up the user's disk during
207 /// long-running or high-churn sessions (#1112).
208 const MAX_SNAPSHOT_SIZE_MB: u64 = 500;
209
210 const BYTES_PER_MB: u64 = 1024 * 1024;
211
212 /// Grace margin below `MAX_SNAPSHOT_SIZE_MB` used as the prune target
213 /// so the repo doesn't hit the limit again one snapshot later.
214 const PRUNE_TARGET_MB: u64 = 400;
215
216 /// Hard cap on the number of file entries the bounded size estimator
217 /// will inspect before declaring the workspace "too large". Protects
218 /// against a workspace with millions of tiny files (no individual
219 /// file is large, but `git add -A` would still take forever).
220 pub const SIZE_WALK_MAX_ENTRIES: usize = 200_000;
221
222 /// Which snapshot gate refused a workspace. The recovery differs per gate —
223 /// raising `[snapshots] max_workspace_gb` lifts only [`WorkspaceGate::TooLarge`]
224 /// — so callers must not offer one gate's remedy for another's failure.
225 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
226 pub enum WorkspaceGate {
227 /// Snapshot-eligible content exceeds the configured byte cap.
228 TooLarge,
229 /// The bounded walk hit [`SIZE_WALK_MAX_ENTRIES`]. This bound is
230 /// independent of the byte cap: `max_workspace_gb = 0` does not lift it.
231 TooManyEntries,
232 }
233
234 /// Leading text of the `io::Error` each gate produces. `core::turn` matches on
235 /// these to pick the right consequence/recovery notice, so they are one
236 /// declaration shared by producer and matcher rather than two literals.
237 pub const GATE_TOO_LARGE_MARKER: &str = "workspace too large for snapshots";
238 pub const GATE_TOO_MANY_ENTRIES_MARKER: &str = "workspace has too many files for snapshots";
239 pub const GATE_UNSAFE_LOCATION_MARKER: &str = "workspace snapshots are disabled";
240
241 /// Display a workspace path in gate diagnostics. The diagnostic names the
242 /// path the caller passed in — canonicalization is for filesystem and
243 /// security logic, not for the message. On Windows `Path::canonicalize`
244 /// rewrites more than the verbatim (`\\?\`) prefix (case, 8.3 names), so a
245 /// canonical spelling can never be relied on to match what users name; the
246 /// verbatim prefix is still stripped when present for readability.
247 fn display_workspace_for_gate(workspace: &Path) -> String {
248 let raw = workspace.display().to_string();
249 raw.strip_prefix(r"\\?\")
250 .or_else(|| raw.strip_prefix("//?/"))
251 .unwrap_or(&raw)
252 .to_string()
253 }
254
255 impl WorkspaceGate {
256 /// One-line English diagnostic for logs, `/undo`, and the gate matcher.
257 /// The user-facing consequence and recovery are localized by the notice
258 /// surfaces; this string must not restate them.
259 fn describe(self, cap_bytes: u64, workspace: &Path) -> String {
260 let workspace = display_workspace_for_gate(workspace);
261 match self {
262 Self::TooLarge => format!(
263 "{GATE_TOO_LARGE_MARKER}: over {} bytes of snapshot-eligible content in {workspace}",
264 cap_bytes,
265 ),
266 Self::TooManyEntries => format!(
267 "{GATE_TOO_MANY_ENTRIES_MARKER}: over {SIZE_WALK_MAX_ENTRIES} snapshot-eligible entries in {workspace}"
268 ),
269 }
270 }
271 }
272
273 /// Top-level directory and extension patterns that the snapshot path
274 /// already excludes via `BUILTIN_EXCLUDES`. The estimator skips these
275 /// up front so the size walk reflects what would actually land in the
276 /// snapshot commit. Kept narrow to common build-output dirs — anything
277 /// else falls back to the `.gitignore` filter.
278 const SIZE_WALK_SKIP_DIRS: &[&str] = &[
279 "node_modules",
280 "target",
281 "dist",
282 "build",
283 ".build",
284 ".next",
285 ".nuxt",
286 ".svelte-kit",
287 ".turbo",
288 ".parcel-cache",
289 "vendor",
290 ".cargo",
291 ".rustup",
292 ".npm",
293 ".bun",
294 ".yarn",
295 ".pnpm-store",
296 ".cache",
297 ".venv",
298 "venv",
299 ".tox",
300 "__pycache__",
301 ".mypy_cache",
302 ".pytest_cache",
303 ".ruff_cache",
304 ".gradle",
305 ".m2",
306 ".local",
307 ".git",
308 ];
309
310 const BUILTIN_EXCLUDES: &str = "\
311 # CodeWhale built-in snapshot exclusions
312 node_modules/
313 target/
314 dist/
315 build/
316 .build/
317 .next/
318 .nuxt/
319 .svelte-kit/
320 .turbo/
321 .parcel-cache/
322 vendor/
323 .cargo/
324 .rustup/
325 .npm/
326 .bun/
327 .yarn/
328 .pnpm-store/
329 .cache/
330 .venv/
331 venv/
332 .tox/
333 __pycache__/
334 *.pyc
335 .mypy_cache/
336 .pytest_cache/
337 .ruff_cache/
338 .gradle/
339 .m2/
340 .local/
341 .DS_Store
342
343 # Binary and generated artifacts. Snapshots are source rollback checkpoints,
344 # not a full binary backup; keeping these out avoids side-repo bloat.
345 *.exe
346 *.dll
347 *.so
348 *.dylib
349 *.wasm
350 *.o
351 *.obj
352 *.class
353 *.pdb
354 *.dSYM
355 *.zip
356 *.tar
357 *.tar.gz
358 *.tgz
359 *.tar.bz2
360 *.tar.xz
361 *.7z
362 *.rar
363 *.iso
364 *.dmg
365 *.bin
366 *.mp4
367 *.mov
368 *.mkv
369 *.avi
370 *.webm
371 *.mp3
372 *.wav
373 *.flac
374 *.aac
375 ";
376
377 impl SnapshotRepo {
378 /// Open an existing snapshot repo for `workspace` without creating or
379 /// initializing anything on disk.
380 ///
381 /// This is useful for read-only UI surfaces that want to report checkpoint
382 /// availability without paying the first-init size walk or surprising the
383 /// user by creating a side repo from a view action.
384 pub fn open_existing(workspace: &Path) -> io::Result<Option<Self>> {
385 let work_tree = workspace
386 .canonicalize()
387 .unwrap_or_else(|_| workspace.to_path_buf());
388 let git_dir = snapshot_git_dir(&work_tree)?;
389 if !git_dir.exists() || !git_dir.join("HEAD").exists() {
390 return Ok(None);
391 }
392 Ok(Some(Self { git_dir, work_tree }))
393 }
394
395 /// Open or initialize the snapshot repo for `workspace`.
396 ///
397 /// On first use this:
398 /// 1. Creates the `.git` dir under the resolved snapshot store.
399 /// 2. Runs `git init --bare=false --quiet`.
400 /// 3. Sets a fixed `user.name` / `user.email` so commits don't pick up
401 /// the user's global git identity (we don't want our snapshots to
402 /// look like they came from the user).
403 pub fn open_or_init(workspace: &Path) -> io::Result<Self> {
404 Self::open_or_init_with_cap(
405 workspace,
406 codewhale_config::DEFAULT_MAX_WORKSPACE_BYTES_FOR_SNAPSHOT,
407 )
408 }
409
410 /// Variant of [`Self::open_or_init`] that accepts an explicit
411 /// workspace-size cap. `cap_bytes = 0` disables the cap entirely
412 /// (always snapshot, regardless of size).
413 ///
414 /// When the workspace exceeds the cap and the side repo hasn't
415 /// been initialized yet, returns `Err(InvalidInput)` with a
416 /// "workspace too large" reason. Subsequent calls (after the user
417 /// shrinks the workspace or raises the cap via config) succeed.
418 pub fn open_or_init_with_cap(workspace: &Path, cap_bytes: u64) -> io::Result<Self> {
419 let work_tree = workspace
420 .canonicalize()
421 .unwrap_or_else(|_| workspace.to_path_buf());
422 if let Some(reason) =
423 unsafe_workspace_snapshot_reason(&work_tree, codewhale_paths::user_home().as_deref())
424 {
425 return Err(io::Error::new(
426 io::ErrorKind::InvalidInput,
427 format!(
428 "{GATE_UNSAFE_LOCATION_MARKER} for {reason}: {}",
429 display_workspace_for_gate(workspace)
430 ),
431 ));
432 }
433
434 let git_dir = ensure_snapshot_dir(&work_tree)?.join(".git");
435
436 // A `.git` without HEAD is an init that never finished (or only a
437 // peer's lock file): initialize it rather than use it half-made.
438 let needs_init = !git_dir.join("HEAD").exists();
439 if needs_init {
440 // First-init size guard. Skipping this on subsequent opens
441 // is intentional: paying a workspace walk on every snapshot
442 // would defeat the purpose of the cap, and a workspace
443 // that fit on first init is allowed to grow within the
444 // existing repo's `MAX_SNAPSHOT_SIZE_MB` budget. Users on
445 // workspaces that grew past the cap mid-session get the
446 // existing aggressive-pruning path in `snapshot()`.
447 if let Err(gate) =
448 estimate_workspace_size_bounded(&work_tree, cap_bytes, SIZE_WALK_MAX_ENTRIES)
449 {
450 return Err(io::Error::new(
451 io::ErrorKind::InvalidInput,
452 gate.describe(cap_bytes, workspace),
453 ));
454 }
455 // The lock file lives in `.git`, so create it first; `git init`
456 // accepts an existing `.git` directory.
457 std::fs::create_dir_all(&git_dir)?;
458 }
459 let repo = Self { git_dir, work_tree };
460 if needs_init {
461 // Two sessions opening a new workspace at once must not both run
462 // `git init` and the identity config: a config write that loses
463 // git's own config lock is ignored, and a snapshot committed
464 // before the identity lands would carry the user's.
465 repo.with_write_lock(|| {
466 if repo.git_dir.join("HEAD").exists() {
467 return Ok(());
468 }
469 repo.init_side_repo()
470 })?;
471 }
472
473 write_builtin_excludes(&repo.git_dir)?;
474 if let Err(err) = cleanup_stale_pack_temps(&repo.git_dir, STALE_TMP_PACK_AGE) {
475 tracing::debug!(
476 target: "snapshot",
477 "failed to clean stale snapshot tmp_pack files: {err}"
478 );
479 }
480 Ok(repo)
481 }
482
483 /// `git init` the side repo and pin its config. Runs under the write lock.
484 fn init_side_repo(&self) -> io::Result<()> {
485 let (git_dir, work_tree) = (&self.git_dir, &self.work_tree);
486 let parent = git_dir.parent().ok_or_else(|| {
487 io::Error::new(io::ErrorKind::InvalidInput, "snapshot dir has no parent")
488 })?;
489 // `git init` here uses the parent directory as the work tree
490 // and stores metadata in `.git`. We then continue to use
491 // explicit `--git-dir` / `--work-tree` flags for every other
492 // command so behaviour is invariant of cwd.
493 let mut git = codewhale_dependencies::Git::command()
494 .ok_or_else(|| io_other("git not found on PATH"))?;
495 let init = git.arg("init").arg("--quiet").arg(parent);
496 let init = run_bounded_git(init, "init")
497 .map_err(|e| io_other(format!("failed to run git init: {e}")))?;
498 if !init.status.success() {
499 return Err(io_other(format!(
500 "git init failed: {}",
501 String::from_utf8_lossy(&init.stderr).trim()
502 )));
503 }
504
505 for (key, value) in [
506 ("user.name", "deepseek-snapshots"),
507 ("user.email", "snapshots@codewhale.local"),
508 ("gc.auto", "0"),
509 ("core.autocrlf", "false"),
510 ] {
511 let configured = run_git(git_dir, work_tree, &["config", key, value])?;
512 if !configured.status.success() {
513 return Err(io_other(format!(
514 "git config {key} failed: {}",
515 String::from_utf8_lossy(&configured.stderr).trim()
516 )));
517 }
518 }
519 Ok(())
520 }
521
522 /// Take a snapshot of the current working tree.
523 ///
524 /// Internally: `git add -A`, `git write-tree`, `git commit-tree`, then
525 /// `git update-ref HEAD <commit>`.
526 /// `git add -A` honours the user's workspace ignore rules while staging
527 /// into the side repo's index.
528 ///
529 /// Before committing, checks whether the snapshot directory exceeds
530 /// `MAX_SNAPSHOT_SIZE_MB` and prunes the oldest snapshots if it does.
531 ///
532 /// Returns the snapshot's commit SHA.
533 pub fn snapshot(&self, label: &str) -> io::Result<SnapshotId> {
534 self.snapshot_with_session(label, None)
535 }
536
537 /// Take a snapshot, tagging it with the owning session id.
538 ///
539 /// The session id is encoded into the commit message as a `[sid=...] `
540 /// label prefix. [`Self::list`] decodes it back into
541 /// [`Snapshot::session_id`] and strips the prefix from the visible
542 /// label, so existing listing surfaces keep showing the plain label.
543 /// Legacy snapshots taken through [`Self::snapshot`] carry no prefix
544 /// and decode with `session_id == None`.
545 pub fn snapshot_with_session(
546 &self,
547 label: &str,
548 session_id: Option<&str>,
549 ) -> io::Result<SnapshotId> {
550 self.take_snapshot(label, session_id).map(|taken| taken.id)
551 }
552
553 /// [`Self::snapshot_with_session`], also reporting the root tree the
554 /// snapshot holds — the identity a recorded restore point keeps.
555 pub fn take_snapshot(
556 &self,
557 label: &str,
558 session_id: Option<&str>,
559 ) -> io::Result<TakenSnapshot> {
560 self.with_write_lock(|| self.take_snapshot_locked(label, session_id))
561 }
562
563 fn take_snapshot_locked(
564 &self,
565 label: &str,
566 session_id: Option<&str>,
567 ) -> io::Result<TakenSnapshot> {
568 // Guard against disk blowup (#1112): if the snapshot directory has
569 // grown beyond the limit, prune aggressively before adding more.
570 if let Ok(removed) = self.prune_size_pressure(
571 MAX_SNAPSHOT_SIZE_MB * BYTES_PER_MB,
572 PRUNE_TARGET_MB * BYTES_PER_MB,
573 ) && removed > 0
574 {
575 notify_snapshot_history_pruned_once(&self.work_tree, removed);
576 }
577 // A HEAD that names a missing commit would make every `commit-tree
578 // -p` below fail ("is not a valid object"), silently ending undo.
579 self.repair_broken_head()?;
580 let parent = run_git(
581 &self.git_dir,
582 &self.work_tree,
583 &["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
584 )?;
585 let parent = parent
586 .status
587 .success()
588 .then(|| String::from_utf8_lossy(&parent.stdout).trim().to_string())
589 .filter(|s| !s.is_empty());
590
591 self.stage_work_tree()?;
592 let (tree, sha) = match self.commit_staged_tree(parent.as_deref(), label, session_id) {
593 Ok(done) => done,
594 Err(first) => {
595 // An index naming objects that no longer exist (left by an
596 // interrupted or racing gc) breaks every later snapshot:
597 // `add -A` does not rehash files whose stat data is
598 // unchanged, and `write-tree` hands back the index's cached
599 // tree id even when that tree is gone, so `commit-tree` then
600 // fails. Rebuild the index from the work tree once.
601 let reset = run_git(&self.git_dir, &self.work_tree, &["read-tree", "--empty"])?;
602 if !reset.status.success() {
603 return Err(first);
604 }
605 self.stage_work_tree()?;
606 self.commit_staged_tree(parent.as_deref(), label, session_id)?
607 }
608 };
609
610 self.move_head(Some(&sha), parent.as_deref())?;
611
612 let id = SnapshotId::parse(&sha).map_err(|_| {
613 io_other(format!(
614 "git commit-tree returned a malformed commit id: {sha:?}"
615 ))
616 })?;
617 let tree = SnapshotId::parse(&tree).map_err(|_| {
618 io_other(format!(
619 "git write-tree returned a malformed tree id: {tree:?}"
620 ))
621 })?;
622 Ok(TakenSnapshot { id, tree })
623 }
624
625 /// `write-tree` the staged index and `commit-tree` it onto `parent`,
626 /// returning the tree and commit ids.
627 fn commit_staged_tree(
628 &self,
629 parent: Option<&str>,
630 label: &str,
631 session_id: Option<&str>,
632 ) -> io::Result<(String, String)> {
633 let tree = run_git(&self.git_dir, &self.work_tree, &["write-tree"])?;
634 if !tree.status.success() {
635 return Err(io_other(format!(
636 "git write-tree failed: {}",
637 String::from_utf8_lossy(&tree.stderr).trim()
638 )));
639 }
640 let tree = String::from_utf8_lossy(&tree.stdout).trim().to_string();
641
642 let mut args = vec!["commit-tree".to_string(), tree.clone()];
643 if let Some(parent) = parent {
644 args.push("-p".to_string());
645 args.push(parent.to_string());
646 }
647 args.push("-m".to_string());
648 args.push(Self::encode_session_label(label, session_id));
649 let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
650
651 // `commit-tree` creates marker commits even when the tree matches its
652 // parent, and it does not run user/global commit hooks.
653 let commit = run_git(&self.git_dir, &self.work_tree, &arg_refs)?;
654 if !commit.status.success() {
655 return Err(io_other(format!(
656 "git commit-tree failed: {}",
657 String::from_utf8_lossy(&commit.stderr).trim()
658 )));
659 }
660 let sha = String::from_utf8_lossy(&commit.stdout).trim().to_string();
661 Ok((tree, sha))
662 }
663
664 /// Repair a side repo whose HEAD names a commit that no longer exists
665 /// (an interrupted gc or prune, a copied or partially deleted
666 /// `~/.codewhale/snapshots` directory). Left alone, every later snapshot
667 /// fails on `commit-tree -p <missing>` and /undo is dead without a word.
668 ///
669 /// The broken ref is deleted so the next snapshot starts a fresh history.
670 /// Restore points before the break cannot be recovered; the caller tells
671 /// the user. Returns `true` when a repair happened.
672 pub fn repair_broken_head(&self) -> io::Result<bool> {
673 self.with_write_lock(|| self.repair_broken_head_locked())
674 }
675
676 fn repair_broken_head_locked(&self) -> io::Result<bool> {
677 let commit = run_git(
678 &self.git_dir,
679 &self.work_tree,
680 &["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
681 )?;
682 if commit.status.success() {
683 return Ok(false);
684 }
685 // An unborn branch (fresh repo) names nothing: nothing to repair.
686 let named = run_git(
687 &self.git_dir,
688 &self.work_tree,
689 &["rev-parse", "--verify", "--quiet", "HEAD"],
690 )?;
691 if !named.status.success() {
692 return Ok(false);
693 }
694 let missing = String::from_utf8_lossy(&named.stdout).trim().to_string();
695 // A lookup can fail for a moment while another session sharing this
696 // repo runs gc or repack. Only a commit that is really absent
697 // justifies touching HEAD: deleting it discards every restore point.
698 if self.is_commit(&missing)? {
699 return Ok(false);
700 }
701 self.reset_missing_head(&missing)
702 }
703
704 /// Move HEAD off `missing`, a commit id it named when this repair looked.
705 /// Both moves are compare-and-swap against `missing`: a writer that does
706 /// not take the snapshot lock (an older build) may have published a valid
707 /// snapshot since, and neither the reflog reset nor the delete may then
708 /// overwrite it. A refused reset is reported, never followed by a delete.
709 fn reset_missing_head(&self, missing: &str) -> io::Result<bool> {
710 // The newest reflog entry that still names a commit keeps the
711 // restore points before the break.
712 if let Some(recovered) = self.newest_reflog_commit(missing)? {
713 self.move_head(Some(&recovered), Some(missing))
714 .map_err(|error| {
715 io_other(format!(
716 "snapshot history HEAD pointed at missing commit {missing} and was not reset to {recovered}: {error}"
717 ))
718 })?;
719 tracing::warn!(
720 target: "snapshot",
721 "snapshot history HEAD pointed at missing commit {missing}; reset to {recovered} from the reflog"
722 );
723 return Ok(false);
724 }
725 self.move_head(None, Some(missing)).map_err(|error| {
726 io_other(format!(
727 "snapshot history HEAD points at missing commit {missing} and could not be reset: {error}"
728 ))
729 })?;
730 tracing::warn!(
731 target: "snapshot",
732 "snapshot history HEAD pointed at missing commit {missing}; started a fresh history"
733 );
734 Ok(true)
735 }
736
737 fn is_commit(&self, oid: &str) -> io::Result<bool> {
738 let object = format!("{oid}^{{commit}}");
739 Ok(
740 run_git(&self.git_dir, &self.work_tree, &["cat-file", "-e", &object])?
741 .status
742 .success(),
743 )
744 }
745
746 /// The newest commit recorded in HEAD's reflogs (its branch's, then
747 /// HEAD's own) that still exists, skipping `missing`.
748 fn newest_reflog_commit(&self, missing: &str) -> io::Result<Option<String>> {
749 let branch = run_git(&self.git_dir, &self.work_tree, &["symbolic-ref", "HEAD"])?;
750 let mut logs = Vec::new();
751 if branch.status.success() {
752 let name = String::from_utf8_lossy(&branch.stdout).trim().to_string();
753 logs.push(self.git_dir.join("logs").join(name));
754 }
755 logs.push(self.git_dir.join("logs").join("HEAD"));
756 for log in logs {
757 let Ok(text) = std::fs::read_to_string(&log) else {
758 continue;
759 };
760 // Each line is `<old> <new> <who> <when>\t<message>`.
761 for line in text.lines().rev() {
762 let mut fields = line.split(' ');
763 let (Some(old), Some(new)) = (fields.next(), fields.next()) else {
764 continue;
765 };
766 for oid in [new, old] {
767 if oid.len() >= 40
768 && oid != missing
769 && oid.bytes().any(|b| b != b'0')
770 && self.is_commit(oid)?
771 {
772 return Ok(Some(oid.to_string()));
773 }
774 }
775 }
776 }
777 Ok(None)
778 }
779
780 /// Point the side repo's HEAD branch at a commit id that does not exist.
781 #[cfg(any(test, feature = "test-support"))]
782 pub fn point_head_at_missing_commit_for_test(&self) {
783 let branch = run_git(&self.git_dir, &self.work_tree, &["symbolic-ref", "HEAD"])
784 .expect("symbolic-ref");
785 let branch = String::from_utf8_lossy(&branch.stdout).trim().to_string();
786 let path = self.git_dir.join(&branch);
787 std::fs::create_dir_all(path.parent().expect("ref parent")).expect("ref dir");
788 std::fs::write(path, "1111111111111111111111111111111111111111\n").expect("write ref");
789 }
790
791 /// Prefix a snapshot label with its owning session id, if any.
792 fn encode_session_label(label: &str, session_id: Option<&str>) -> String {
793 match session_id {
794 Some(sid) if !sid.is_empty() => format!("[sid={sid}] {label}"),
795 _ => label.to_string(),
796 }
797 }
798
799 /// Split a possibly session-tagged label back into `(session_id, label)`.
800 ///
801 /// Returns `(None, label)` for untagged labels. The decoded label is
802 /// the original one without the `[sid=...] ` prefix, so consumers that
803 /// match on `pre-turn:`/`tool:`/`redo:` prefixes keep working unchanged.
804 fn decode_session_label(label: &str) -> (Option<String>, String) {
805 let Some(rest) = label.strip_prefix("[sid=") else {
806 return (None, label.to_string());
807 };
808 let Some(end) = rest.find("] ") else {
809 return (None, label.to_string());
810 };
811 let sid = &rest[..end];
812 let plain = &rest[end + 2..];
813 if sid.is_empty() || plain.is_empty() {
814 return (None, label.to_string());
815 }
816 (Some(sid.to_string()), plain.to_string())
817 }
818 /// Size-pressure prune (#1112): if the side repo exceeds `max_bytes`,
819 /// drop the oldest half of the snapshots, repeatedly, until the store is
820 /// at or under `target_bytes` or only the protected restore points are
821 /// left. Returns the number of snapshots destroyed, so the caller can
822 /// tell the user their undo history shrank (S5).
823 ///
824 /// The prune goes oldest first by count and always keeps the newest
825 /// snapshot plus each session's newest `pre-turn:` and `post-turn:`
826 /// boundaries, so every session's running turn (and the one before it)
827 /// stays restorable. It used to
828 /// prune by age starting at one second, which on the first pass dropped
829 /// every snapshot older than a second and then wiped the rest: a workspace
830 /// whose side repo sat above the cap lost all undo history on every
831 /// snapshot.
832 fn prune_size_pressure(&self, max_bytes: u64, target_bytes: u64) -> io::Result<usize> {
833 self.with_write_lock(|| {
834 let current_bytes = dir_size_bytes(&self.git_dir)?;
835 if current_bytes <= max_bytes {
836 return Ok(0);
837 }
838 tracing::warn!(
839 target: "snapshot",
840 current_mb = current_bytes / BYTES_PER_MB,
841 limit_mb = max_bytes / BYTES_PER_MB,
842 "snapshot storage over limit — pruning the oldest snapshots"
843 );
844 let mut removed_total: usize = 0;
845 loop {
846 let snapshots = self.list(usize::MAX)?;
847 let mut survivors = size_pressure_survivors(&snapshots, snapshots.len() / 2);
848 if survivors.len() >= snapshots.len() {
849 // Halving kept only protected points: cut to those alone.
850 survivors = size_pressure_survivors(&snapshots, 0);
851 }
852 if survivors.is_empty() || survivors.len() >= snapshots.len() {
853 break;
854 }
855 self.rebuild_survivor_chain(&survivors, &snapshots[0].id)?;
856 self.reclaim_unreachable();
857 removed_total = removed_total.saturating_add(snapshots.len() - survivors.len());
858 let new_size = dir_size_bytes(&self.git_dir)?;
859 if new_size <= target_bytes {
860 tracing::info!(
861 target: "snapshot",
862 new_size_mb = new_size / BYTES_PER_MB,
863 "pruned snapshot storage back under limit"
864 );
865 break;
866 }
867 }
868 Ok(removed_total)
869 })
870 }
871
872 /// Restore the workspace to the state at `id`.
873 ///
874 /// Requires a durable safety snapshot before changing files. A failed
875 /// restore attempts to put those files back; if that also fails, the
876 /// error identifies the retained safety snapshot for recovery. This is
877 /// not atomic against an external editor changing the live workspace.
878 /// File/directory transitions are refused before checkout because the
879 /// replaced directory may contain files excluded from the backup.
880 /// We never touch the user's own `.git`.
881 pub fn restore(&self, id: &SnapshotId) -> io::Result<()> {
882 self.with_write_lock(|| self.restore_locked(id))
883 }
884
885 fn restore_locked(&self, id: &SnapshotId) -> io::Result<()> {
886 // The backup label is deliberately not an undo/revert-turn candidate.
887 let target_short = &id.as_str()[..id.as_str().len().min(12)];
888 let backup = self
889 .snapshot_with_session(&format!("pre-restore:{target_short}"), None)
890 .map_err(|error| {
891 io_other(format!(
892 "pre-restore safety snapshot failed; no workspace files were changed: {error}"
893 ))
894 })?;
895 let current_paths = self.tree_paths(backup.as_str())?;
896 let target_paths = self.tree_paths(id.as_str())?;
897 for rel in &target_paths {
898 match std::fs::symlink_metadata(self.work_tree.join(rel)) {
899 Ok(metadata) if metadata.is_dir() => {
900 return Err(io_other(format!(
901 "'{}' requires a file/directory transition; nothing was restored",
902 rel.display()
903 )));
904 }
905 Ok(_) if !current_paths.contains(rel) => {
906 return Err(io_other(format!(
907 "'{}' was excluded from the safety snapshot; nothing was restored",
908 rel.display()
909 )));
910 }
911 // Unix reports a path under a live file as NotADirectory;
912 // Windows reports NotFound, so look for the file itself.
913 Err(error)
914 if error.kind() == io::ErrorKind::NotADirectory
915 || (error.kind() == io::ErrorKind::NotFound
916 && ancestor_is_not_a_directory(&self.work_tree, rel)) =>
917 {
918 return Err(io_other(format!(
919 "'{}' requires a file/directory transition; nothing was restored",
920 rel.display()
921 )));
922 }
923 Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
924 _ => {}
925 }
926 }
927 if let Err(error) = self.restore_tree(id, &current_paths, &target_paths) {
928 let recovery = match self.restore_tree(&backup, &target_paths, &current_paths) {
929 Ok(()) => "previous snapshot files were restored".to_string(),
930 Err(rollback) => format!("rollback also failed: {rollback}"),
931 };
932 return Err(io_other(format!(
933 "restore failed: {error}; {recovery}; safety snapshot {} retains the previous files",
934 backup.as_str()
935 )));
936 }
937 Ok(())
938 }
939
940 fn restore_tree(
941 &self,
942 id: &SnapshotId,
943 current_paths: &HashSet<PathBuf>,
944 target_paths: &HashSet<PathBuf>,
945 ) -> io::Result<()> {
946 // An empty target (the first snapshot of an empty directory) has no
947 // path for `:/` to match, and git refuses the checkout outright; there
948 // is nothing to write back, only the later files to remove.
949 if !target_paths.is_empty() {
950 let checkout = run_git(
951 &self.git_dir,
952 &self.work_tree,
953 &["checkout", id.as_str(), "--", ":/"],
954 )?;
955 if !checkout.status.success() {
956 return Err(io_other(format!(
957 "git checkout failed: {}",
958 String::from_utf8_lossy(&checkout.stderr).trim()
959 )));
960 }
961 }
962 self.remove_paths_missing_from_target(current_paths, target_paths)
963 }
964
965 /// File restore never traverses symlinks, directories, or Git metadata.
966 /// Validate every existing component before reading, backing up or writing.
967 pub fn validate_restore_file(&self, rel: &Path) -> io::Result<bool> {
968 if !is_safe_relative_path(rel)
969 || rel
970 .components()
971 .any(|part| codewhale_util::git_metadata::is_git_metadata_name(part.as_os_str()))
972 {
973 return Err(io::Error::new(
974 io::ErrorKind::InvalidInput,
975 format!(
976 "refusing to restore unsafe path '{}': restore requires a regular workspace file",
977 rel.display()
978 ),
979 ));
980 }
981 let mut path = self.work_tree.clone();
982 for part in rel.components() {
983 path.push(part);
984 match std::fs::symlink_metadata(&path) {
985 Ok(meta)
986 if meta.file_type().is_symlink()
987 || (path == self.work_tree.join(rel) && !meta.is_file())
988 || (path != self.work_tree.join(rel) && !meta.is_dir()) =>
989 {
990 return Err(io::Error::new(
991 io::ErrorKind::InvalidInput,
992 "restore refuses directories, symlinks and non-regular files",
993 ));
994 }
995 Ok(_) => {}
996 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
997 Err(error) => return Err(error),
998 }
999 }
1000 Ok(true)
1001 }
1002
1003 fn snapshot_contains_regular_file(&self, id: &SnapshotId, rel: &Path) -> io::Result<bool> {
1004 self.snapshot_file_blob(id, rel).map(|blob| blob.is_some())
1005 }
1006
1007 /// The blob id `rel` holds in snapshot (commit or tree) `id`, or `None`
1008 /// when the snapshot does not contain it. Anything other than a regular
1009 /// file is `InvalidInput`: file-scoped restores never write symlinks or
1010 /// directories.
1011 fn snapshot_file_blob(&self, id: &SnapshotId, rel: &Path) -> io::Result<Option<String>> {
1012 let entry = run_git(
1013 &self.git_dir,
1014 &self.work_tree,
1015 &[
1016 "--literal-pathspecs",
1017 "ls-tree",
1018 "-z",
1019 "--end-of-options",
1020 id.as_str(),
1021 "--",
1022 rel.to_str()
1023 .ok_or_else(|| io_other("restore path must be UTF-8"))?,
1024 ],
1025 )?;
1026 if !entry.status.success() {
1027 return Err(io_other(format!(
1028 "Failed to inspect snapshot file: {}",
1029 String::from_utf8_lossy(&entry.stderr).trim()
1030 )));
1031 }
1032 if entry.stdout.is_empty() {
1033 return Ok(None);
1034 }
1035 let line = String::from_utf8_lossy(&entry.stdout);
1036 let blob = line
1037 .strip_prefix("100644 blob ")
1038 .or_else(|| line.strip_prefix("100755 blob "))
1039 .and_then(|rest| rest.split('\t').next())
1040 .filter(|sha| SnapshotId::is_well_formed(sha))
1041 .ok_or_else(|| {
1042 io::Error::new(
1043 io::ErrorKind::InvalidInput,
1044 "snapshot path is not a regular file",
1045 )
1046 })?;
1047 Ok(Some(blob.to_string()))
1048 }
1049
1050 /// Whether the working-tree bytes of `rel` are exactly what snapshot `id`
1051 /// holds for it (both absent counts as a match).
1052 ///
1053 /// Compares content hashes directly instead of `git diff <id>`: the side
1054 /// repo's index only lists paths present at the last snapshot, and a diff
1055 /// against a commit reports a path the index lost as deleted even when
1056 /// the file is on disk.
1057 pub fn path_matches_snapshot(&self, id: &SnapshotId, rel: &Path) -> io::Result<bool> {
1058 let in_work = self.validate_restore_file(rel)?;
1059 match (self.snapshot_file_blob(id, rel)?, in_work) {
1060 (None, false) => Ok(true),
1061 (None, true) | (Some(_), false) => Ok(false),
1062 (Some(blob), true) => {
1063 let rel_str = rel
1064 .to_str()
1065 .ok_or_else(|| io_other("restore path must be UTF-8"))?;
1066 let abs = self.work_tree.join(rel);
1067 let abs = abs
1068 .to_str()
1069 .ok_or_else(|| io_other("restore path must be UTF-8"))?;
1070 // Git for Windows cannot open the `\\?\` verbatim form that
1071 // `canonicalize` gives the work tree.
1072 let abs = match abs.strip_prefix(r"\\?\") {
1073 Some(rest) => match rest.strip_prefix(r"UNC\") {
1074 Some(unc) => format!(r"\\{unc}"),
1075 None => rest.to_string(),
1076 },
1077 None => abs.to_string(),
1078 };
1079 let hashed = run_git(
1080 &self.git_dir,
1081 &self.work_tree,
1082 &["hash-object", &format!("--path={rel_str}"), "--", &abs],
1083 )?;
1084 if !hashed.status.success() {
1085 return Err(io_other(format!(
1086 "git hash-object failed: {}",
1087 String::from_utf8_lossy(&hashed.stderr).trim()
1088 )));
1089 }
1090 Ok(String::from_utf8_lossy(&hashed.stdout).trim() == blob)
1091 }
1092 }
1093 }
1094
1095 /// Paths whose content differs between snapshots `from` and `to` (commit
1096 /// or tree ids), with renames reported as a delete plus an add so each
1097 /// side's path is restorable on its own.
1098 pub fn changed_paths_between(
1099 &self,
1100 from: &SnapshotId,
1101 to: &SnapshotId,
1102 ) -> io::Result<Vec<PathBuf>> {
1103 let diff = run_git(
1104 &self.git_dir,
1105 &self.work_tree,
1106 &[
1107 "diff",
1108 "--no-renames",
1109 "--name-only",
1110 "-z",
1111 "--end-of-options",
1112 from.as_str(),
1113 to.as_str(),
1114 "--",
1115 ],
1116 )?;
1117 if !diff.status.success() {
1118 return Err(io_other(format!(
1119 "git diff --name-only failed: {}",
1120 String::from_utf8_lossy(&diff.stderr).trim()
1121 )));
1122 }
1123 let mut paths: Vec<PathBuf> = parse_nul_paths(&diff.stdout).into_iter().collect();
1124 paths.sort();
1125 Ok(paths)
1126 }
1127
1128 /// Whether `rel` has the same content (or is absent) in both snapshots.
1129 pub fn path_same_in_snapshots(
1130 &self,
1131 a: &SnapshotId,
1132 b: &SnapshotId,
1133 rel: &Path,
1134 ) -> io::Result<bool> {
1135 Ok(self.snapshot_file_blob(a, rel)? == self.snapshot_file_blob(b, rel)?)
1136 }
1137
1138 /// Return whether `rel` differs between snapshot `id` and the current
1139 /// working tree.
1140 ///
1141 /// This is the single-path counterpart of
1142 /// [`Self::work_tree_matches_snapshot`]: it answers "would restoring just
1143 /// this file change anything?", which is what file-scoped revert
1144 /// cursoring needs. A path that exists in neither the snapshot nor the
1145 /// working tree does not differ.
1146 pub fn path_differs_from_snapshot(&self, id: &SnapshotId, rel: &Path) -> io::Result<bool> {
1147 let in_work = self.validate_restore_file(rel)?;
1148 let in_target = self.snapshot_contains_regular_file(id, rel)?;
1149 match (in_target, in_work) {
1150 // Neither side has it: nothing to restore and nothing to remove.
1151 (false, false) => Ok(false),
1152 // The snapshot has it and the working tree lost it.
1153 (true, false) => Ok(true),
1154 // The path was created after the snapshot.
1155 (false, true) => Ok(true),
1156 (true, true) => {
1157 let rel = rel.to_string_lossy().into_owned();
1158 let diff = run_git(
1159 &self.git_dir,
1160 &self.work_tree,
1161 &[
1162 "--literal-pathspecs",
1163 "diff",
1164 "--quiet",
1165 "--end-of-options",
1166 id.as_str(),
1167 "--",
1168 rel.as_str(),
1169 ],
1170 )?;
1171 git_diff_matches(diff).map(|matches| !matches)
1172 }
1173 }
1174 }
1175
1176 /// Restore only `rel_paths` from snapshot `id`.
1177 ///
1178 /// This is the file-scoped counterpart of [`Self::restore`]. The
1179 /// difference that matters: the whole-tree `git checkout <sha> -- :/` is
1180 /// replaced by a pathspec-limited checkout, so a working-tree path outside
1181 /// `rel_paths` is never written or deleted. The safety backup reads the workspace.
1182 ///
1183 /// A path the snapshot does not track is removed from the working tree
1184 /// (that is how a file created after the snapshot is reverted), and a path
1185 /// the snapshot tracks but the working tree lost is recreated. A path that
1186 /// exists in neither side produces no outcome at all, rather than a
1187 /// report claiming a change that did not happen.
1188 #[cfg(test)]
1189 pub fn restore_paths(
1190 &self,
1191 id: &SnapshotId,
1192 rel_paths: &[PathBuf],
1193 ) -> io::Result<Vec<PathRestoreOutcome>> {
1194 self.restore_paths_checked(id, rel_paths, || Ok(()))
1195 }
1196
1197 pub fn restore_file_if_unchanged(
1198 &self,
1199 id: &SnapshotId,
1200 rel: &Path,
1201 expected_hash: &str,
1202 ) -> io::Result<Vec<PathRestoreOutcome>> {
1203 let verify = || {
1204 let actual = if self.validate_restore_file(rel)? {
1205 format!(
1206 "sha256:{}",
1207 hash_regular_file_nofollow(&self.work_tree.join(rel))?
1208 )
1209 } else {
1210 "absent".to_string()
1211 };
1212 if actual != expected_hash {
1213 return Err(io::Error::new(
1214 io::ErrorKind::WouldBlock,
1215 "The file changed after the selected change record. Refresh and review it before restoring; nothing was changed.",
1216 ));
1217 }
1218 Ok(())
1219 };
1220 verify()?;
1221 self.restore_paths_checked(id, &[rel.to_path_buf()], verify)
1222 }
1223
1224 fn restore_paths_checked(
1225 &self,
1226 id: &SnapshotId,
1227 rel_paths: &[PathBuf],
1228 preflight: impl FnOnce() -> io::Result<()>,
1229 ) -> io::Result<Vec<PathRestoreOutcome>> {
1230 let target_short = &id.as_str()[..id.as_str().len().min(12)];
1231 let plan: Vec<(PathBuf, SnapshotId)> = rel_paths
1232 .iter()
1233 .map(|rel| (rel.clone(), id.clone()))
1234 .collect();
1235 self.restore_path_plan(
1236 &plan,
1237 &format!("pre-restore:{target_short}"),
1238 false,
1239 preflight,
1240 )
1241 }
1242
1243 /// Restore each `(path, source)` pair of `plan` from its own snapshot
1244 /// (commit or tree id), and nothing else.
1245 ///
1246 /// The whole plan is validated, then one mandatory `backup_label` safety
1247 /// snapshot is written, then `preflight` runs immediately before the
1248 /// first mutation. A path its source does not hold is removed; with
1249 /// `prune_emptied_dirs` the directories that removal leaves empty go too
1250 /// (a turn-scoped undo removes the directories a dropped turn created),
1251 /// otherwise they stay (a file-scoped revert names a file, not a tree).
1252 pub fn restore_path_plan(
1253 &self,
1254 plan: &[(PathBuf, SnapshotId)],
1255 backup_label: &str,
1256 prune_emptied_dirs: bool,
1257 preflight: impl FnOnce() -> io::Result<()>,
1258 ) -> io::Result<Vec<PathRestoreOutcome>> {
1259 self.with_write_lock(|| {
1260 self.restore_path_plan_locked(plan, backup_label, prune_emptied_dirs, preflight)
1261 })
1262 }
1263
1264 fn restore_path_plan_locked(
1265 &self,
1266 plan: &[(PathBuf, SnapshotId)],
1267 backup_label: &str,
1268 prune_emptied_dirs: bool,
1269 preflight: impl FnOnce() -> io::Result<()>,
1270 ) -> io::Result<Vec<PathRestoreOutcome>> {
1271 if plan.is_empty() {
1272 return Ok(Vec::new());
1273 }
1274 // Validate the entire request before any mutation or backup. A snapshot
1275 // directory entry must not turn a file action into recursive checkout.
1276 let mut pre_state = Vec::with_capacity(plan.len());
1277 for (rel, id) in plan {
1278 let in_work = self.validate_restore_file(rel)?;
1279 let in_target = self.snapshot_contains_regular_file(id, rel)?;
1280 pre_state.push((rel.clone(), id.clone(), in_target, in_work));
1281 }
1282
1283 // A durable backup is required for this destructive API. Ignored
1284 // files cannot be removed/overwritten if the snapshot cannot retain them.
1285 let backup = self.snapshot_with_session(backup_label, None)?;
1286 for (rel, _, _, in_work) in &pre_state {
1287 let in_backup = self.snapshot_contains_regular_file(&backup, rel)?;
1288 if *in_work && !in_backup {
1289 return Err(io_other(
1290 "File was excluded from the safety snapshot; nothing was restored",
1291 ));
1292 }
1293 if self.validate_restore_file(rel)? != *in_work || in_backup != *in_work {
1294 return Err(io::Error::new(
1295 io::ErrorKind::WouldBlock,
1296 format!(
1297 "'{}' changed while the restore was being prepared; nothing was changed.",
1298 rel.display()
1299 ),
1300 ));
1301 }
1302 }
1303
1304 // Recheck after the potentially slow safety snapshot, immediately
1305 // before checkout/removal. New editor work is retained in the backup.
1306 preflight()?;
1307
1308 // One pathspec-limited checkout per source snapshot, in plan order.
1309 let mut sources: Vec<&SnapshotId> = Vec::new();
1310 for (_, id, in_target, _) in &pre_state {
1311 if *in_target && !sources.contains(&id) {
1312 sources.push(id);
1313 }
1314 }
1315
1316 let mut rollback_plan = Vec::new();
1317 let restore = (|| -> io::Result<_> {
1318 for source in sources {
1319 let batch = pre_state
1320 .iter()
1321 .filter(|(_, id, in_target, _)| *in_target && id == source);
1322 let mut tracked = Vec::new();
1323 for (rel, _, _, in_work) in batch.clone() {
1324 if self.validate_restore_file(rel)? != *in_work {
1325 return Err(io_other(format!(
1326 "'{}' changed before checkout",
1327 rel.display()
1328 )));
1329 }
1330 tracked.push(rel.as_path());
1331 }
1332 rollback_plan.extend(
1333 batch.map(|(rel, _, _, in_work)| (rel.as_path(), Some(source), *in_work)),
1334 );
1335 self.checkout_snapshot_paths(source, &tracked)?;
1336 }
1337
1338 let mut outcomes = Vec::new();
1339 for (rel, _, in_target, was_in_work) in &pre_state {
1340 let action = match (in_target, was_in_work) {
1341 (true, true) => PathRestoreAction::Modified,
1342 (true, false) => PathRestoreAction::Recreated,
1343 (false, true) => {
1344 self.remove_restore_file(rel)?;
1345 rollback_plan.push((rel.as_path(), None, true));
1346 PathRestoreAction::Removed
1347 }
1348 (false, false) => continue,
1349 };
1350 outcomes.push(PathRestoreOutcome {
1351 path: rel.clone(),
1352 action,
1353 });
1354 }
1355 Ok(outcomes)
1356 })();
1357 let outcomes = match restore {
1358 Ok(outcomes) => outcomes,
1359 Err(error) => {
1360 let attempted_changes = !rollback_plan.is_empty();
1361 let failures: Vec<_> = rollback_plan
1362 .into_iter()
1363 .rev()
1364 .filter_map(|(rel, source, was_in_work)| {
1365 self.rollback_restored_path(&backup, rel, source, was_in_work)
1366 .err()
1367 .map(|error| format!("'{}': {error}", rel.display()))
1368 })
1369 .collect();
1370 let recovery = if !attempted_changes {
1371 "no file changes were applied".to_string()
1372 } else if failures.is_empty() {
1373 "applied file changes were rolled back".to_string()
1374 } else {
1375 format!("rollback incomplete: {}", failures.join("; "))
1376 };
1377 return Err(io_other(format!(
1378 "scoped restore failed: {error}; {recovery}; safety snapshot {} retains the previous files",
1379 backup.as_str()
1380 )));
1381 }
1382 };
1383 if prune_emptied_dirs {
1384 for outcome in &outcomes {
1385 if outcome.action == PathRestoreAction::Removed
1386 && self.removal_parent_is_real(&outcome.path).unwrap_or(false)
1387 {
1388 self.prune_empty_parent_dirs(self.work_tree.join(&outcome.path).parent());
1389 }
1390 }
1391 }
1392 Ok(outcomes)
1393 }
1394
1395 fn checkout_snapshot_paths(&self, id: &SnapshotId, paths: &[&Path]) -> io::Result<()> {
1396 let mut args = vec!["--literal-pathspecs", "checkout", id.as_str(), "--"];
1397 for rel in paths {
1398 args.push(
1399 rel.to_str()
1400 .ok_or_else(|| io_other("restore path must be UTF-8"))?,
1401 );
1402 }
1403 let checkout = run_git(&self.git_dir, &self.work_tree, &args)?;
1404 if !checkout.status.success() {
1405 return Err(io_other(format!(
1406 "git checkout failed: {}",
1407 String::from_utf8_lossy(&checkout.stderr).trim()
1408 )));
1409 }
1410 Ok(())
1411 }
1412
1413 fn remove_restore_file(&self, rel: &Path) -> io::Result<()> {
1414 self.validate_restore_file(rel)
1415 .and_then(|_| std::fs::remove_file(self.work_tree.join(rel)))
1416 .map_err(|error| io_other(format!("removing '{}' failed: {error}", rel.display())))
1417 }
1418
1419 fn rollback_restored_path(
1420 &self,
1421 backup: &SnapshotId,
1422 rel: &Path,
1423 source: Option<&SnapshotId>,
1424 was_in_work: bool,
1425 ) -> io::Result<()> {
1426 let exists = self.validate_restore_file(rel)?;
1427 if exists {
1428 let matches_checkout = match source {
1429 Some(source) => self.path_matches_snapshot(source, rel)?,
1430 None => false,
1431 };
1432 if !matches_checkout {
1433 if self.path_matches_snapshot(backup, rel)? {
1434 return Ok(());
1435 }
1436 return Err(io_other("file changed during restore"));
1437 }
1438 }
1439 if was_in_work {
1440 self.checkout_snapshot_paths(backup, &[rel])?;
1441 } else if exists {
1442 self.remove_restore_file(rel)?;
1443 }
1444 Ok(())
1445 }
1446
1447 /// Return whether the current workspace matches the given snapshot's
1448 /// tracked file content.
1449 ///
1450 /// This is intentionally narrower than a full "workspace identical"
1451 /// claim: it compares the current working tree against the snapshot's
1452 /// tracked paths via git's diff machinery. That is sufficient for
1453 /// `/undo` cursoring — if the diff is empty, restoring this snapshot
1454 /// again would be a no-op, so the caller should continue scanning
1455 /// older snapshots.
1456 pub fn work_tree_matches_snapshot(&self, id: &SnapshotId) -> io::Result<bool> {
1457 let diff = run_git(
1458 &self.git_dir,
1459 &self.work_tree,
1460 &[
1461 "diff",
1462 "--quiet",
1463 "--end-of-options",
1464 id.as_str(),
1465 "--",
1466 ":/",
1467 ],
1468 )?;
1469 git_diff_matches(diff)
1470 }
1471
1472 /// Everything in the work tree that differs from snapshot `from`: files
1473 /// changed, deleted, and created since, including ones no snapshot has
1474 /// recorded yet. New ignored paths stay out, as they stay out of a
1475 /// snapshot; a path `from` holds is compared even if it is ignored now,
1476 /// as the next snapshot would still record it.
1477 ///
1478 /// Read-only for the user and for the snapshot history: the work tree is
1479 /// compared through a throwaway index, seeded with `from`'s paths and
1480 /// then given every other path as "intent to add" (name and stat data, no
1481 /// content), so the side repo's index is not written, no file content is
1482 /// stored, and no snapshot is taken. (Git stores the empty blob those
1483 /// entries name.) Renames are not detected, matching
1484 /// [`Self::patch_between`]. The patch is cut at `max_patch_bytes`, and
1485 /// left out past [`WORK_TREE_PATCH_MAX_LINES`] changed lines.
1486 pub fn work_tree_changes_since(
1487 &self,
1488 from: &SnapshotId,
1489 max_patch_bytes: usize,
1490 ) -> io::Result<WorkTreeChanges> {
1491 let scratch = tempfile::tempdir()?;
1492 let index = scratch.path().join("index");
1493 let run = |args: &[&str]| -> io::Result<String> {
1494 let subcommand = args.first().copied().unwrap_or("git");
1495 let mut cmd = codewhale_dependencies::Git::command()
1496 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "git not found on PATH"))?;
1497 cmd.env("GIT_INDEX_FILE", &index)
1498 .arg("--git-dir")
1499 .arg(&self.git_dir)
1500 .arg("--work-tree")
1501 .arg(&self.work_tree)
1502 .args(["-c", "core.quotePath=false"])
1503 .args(args);
1504 let output = run_bounded_git(&mut cmd, subcommand)?;
1505 if !output.status.success() {
1506 return Err(io_other(format!(
1507 "git {subcommand} failed: {}",
1508 String::from_utf8_lossy(&output.stderr).trim()
1509 )));
1510 }
1511 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
1512 };
1513 // Seed with `from` first: on an empty index a file the snapshot holds
1514 // but a later `.gitignore` covers would be skipped by `add` and read
1515 // as deleted while it is still on disk.
1516 run(&["read-tree", from.as_str()])?;
1517 run(&["add", "--intent-to-add", "--", ":/"])?;
1518 let diff = |format: &str| {
1519 run(&[
1520 "diff",
1521 "--no-renames",
1522 "--no-color",
1523 "--no-ext-diff",
1524 "--no-textconv",
1525 format,
1526 "--end-of-options",
1527 from.as_str(),
1528 "--",
1529 ":/",
1530 ])
1531 };
1532 // `--numstat`: `added\tremoved\tpath` per line, `-` for a binary side.
1533 let numstat = diff("--numstat")?;
1534 let mut names = String::new();
1535 let mut changed_lines = 0_u64;
1536 for record in numstat.lines() {
1537 let mut fields = record.splitn(3, '\t');
1538 let (Some(added), Some(removed), Some(path)) =
1539 (fields.next(), fields.next(), fields.next())
1540 else {
1541 continue;
1542 };
1543 for count in [added, removed] {
1544 changed_lines = changed_lines.saturating_add(count.parse().unwrap_or(0));
1545 }
1546 names.push_str(path);
1547 names.push('\n');
1548 }
1549 let stat = diff("--stat")?;
1550 let (patch, patch_truncated) = if changed_lines > WORK_TREE_PATCH_MAX_LINES {
1551 (String::new(), true)
1552 } else {
1553 truncate_at_char_boundary(&diff("--unified=3")?, max_patch_bytes)
1554 };
1555 Ok(WorkTreeChanges {
1556 names,
1557 stat,
1558 patch,
1559 patch_truncated,
1560 })
1561 }
1562
1563 /// Paths that differ between snapshots `from` and `to`, in git's order,
1564 /// one [`SnapshotPathChange`] each: its `status` is git's `A`/`M`/`D`/`T`
1565 /// letter and its line counts are `None` for a binary file. Paths come
1566 /// back as git stores them (`-z`), control characters included, so a
1567 /// caller that prints one must escape it. Both trees are read from the side repo; neither the
1568 /// work tree nor the index is touched. At most `limit` paths are
1569 /// returned; the flag says whether more differed.
1570 pub fn path_changes_between(
1571 &self,
1572 from: &SnapshotId,
1573 to: &SnapshotId,
1574 limit: usize,
1575 ) -> io::Result<(Vec<SnapshotPathChange>, bool)> {
1576 let run = |format: &str| -> io::Result<String> {
1577 let output = run_git(
1578 &self.git_dir,
1579 &self.work_tree,
1580 &[
1581 "diff",
1582 "--no-renames",
1583 "--no-ext-diff",
1584 "--no-textconv",
1585 format,
1586 "-z",
1587 "--end-of-options",
1588 from.as_str(),
1589 to.as_str(),
1590 ],
1591 )?;
1592 if !output.status.success() {
1593 return Err(io_other(format!(
1594 "git diff {format} failed: {}",
1595 String::from_utf8_lossy(&output.stderr).trim()
1596 )));
1597 }
1598 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
1599 };
1600 // `--numstat -z`: `added\tremoved\tpath\0`, `-` for a binary side.
1601 let numstat = run("--numstat")?;
1602 let mut counts: HashMap<String, (Option<u64>, Option<u64>)> = HashMap::new();
1603 for record in numstat.split('\0').filter(|record| !record.is_empty()) {
1604 let mut fields = record.splitn(3, '\t');
1605 let (Some(added), Some(removed), Some(path)) =
1606 (fields.next(), fields.next(), fields.next())
1607 else {
1608 continue;
1609 };
1610 counts.insert(path.to_string(), (added.parse().ok(), removed.parse().ok()));
1611 }
1612 // `--name-status -z`: `status\0path\0` pairs.
1613 let name_status = run("--name-status")?;
1614 let mut fields = name_status.split('\0').filter(|field| !field.is_empty());
1615 let mut changes = Vec::new();
1616 let mut truncated = false;
1617 while let (Some(status), Some(path)) = (fields.next(), fields.next()) {
1618 if changes.len() == limit {
1619 truncated = true;
1620 break;
1621 }
1622 let (added, removed) = counts.get(path).copied().unwrap_or((None, None));
1623 changes.push(SnapshotPathChange {
1624 path: path.to_string(),
1625 status: status.chars().next().unwrap_or('M'),
1626 added,
1627 removed,
1628 });
1629 }
1630 Ok((changes, truncated))
1631 }
1632
1633 /// Whether a tree is still in this repo.
1634 ///
1635 /// The side repo keeps only the newest snapshots, while the receipt that
1636 /// names one is durable in the turn record: a restore point can outlive
1637 /// the object it names. A caller about to diff two trees asks this first,
1638 /// so "these restore points are gone" is answered with the pruning it is
1639 /// rather than as a git failure over an object nobody can bring back.
1640 /// IO and repository failures remain errors rather than evidence of pruning.
1641 pub fn has_tree(&self, id: &SnapshotId) -> io::Result<bool> {
1642 let spec = format!("{}^{{tree}}", id.as_str());
1643 let output = run_git(
1644 &self.git_dir,
1645 &self.work_tree,
1646 &[
1647 "rev-parse",
1648 "--verify",
1649 "--quiet",
1650 "--end-of-options",
1651 &spec,
1652 ],
1653 )?;
1654 match output.status.code() {
1655 Some(0) => Ok(true),
1656 Some(1) => Ok(false),
1657 _ => Err(io_other(format!(
1658 "git tree lookup failed: {}",
1659 String::from_utf8_lossy(&output.stderr).trim()
1660 ))),
1661 }
1662 }
1663
1664 /// The unified diff of one path between snapshots `from` and `to`, as
1665 /// `git diff` writes it — the patch behind the [`SnapshotPathChange`]
1666 /// [`Self::path_changes_between`] counts for the same two trees.
1667 ///
1668 /// Both trees are read from the side repo: neither the work tree nor the
1669 /// index is touched. The path is taken literally, so a name holding glob
1670 /// characters is one path rather than a pattern. Renames are not
1671 /// detected, matching `path_changes_between`, so a moved file reads as a
1672 /// deletion plus an addition.
1673 ///
1674 /// The text is cut at `max_bytes` on a char boundary; the flag says
1675 /// whether anything was dropped. A binary path yields git's own binary
1676 /// notice, and a path that does not differ yields an empty string: the
1677 /// caller reports what git wrote rather than inventing a patch.
1678 pub fn patch_between(
1679 &self,
1680 from: &SnapshotId,
1681 to: &SnapshotId,
1682 path: &str,
1683 max_bytes: usize,
1684 ) -> io::Result<(String, bool)> {
1685 let output = run_git(
1686 &self.git_dir,
1687 &self.work_tree,
1688 &[
1689 "--literal-pathspecs",
1690 "diff",
1691 "--no-renames",
1692 "--no-color",
1693 "--no-ext-diff",
1694 "--no-textconv",
1695 "--unified=3",
1696 "--end-of-options",
1697 from.as_str(),
1698 to.as_str(),
1699 "--",
1700 path,
1701 ],
1702 )?;
1703 if !output.status.success() {
1704 return Err(io_other(format!(
1705 "git diff failed: {}",
1706 String::from_utf8_lossy(&output.stderr).trim()
1707 )));
1708 }
1709 Ok(truncate_at_char_boundary(
1710 &String::from_utf8_lossy(&output.stdout),
1711 max_bytes,
1712 ))
1713 }
1714
1715 fn tree_paths(&self, treeish: &str) -> io::Result<HashSet<PathBuf>> {
1716 let ls = run_git(
1717 &self.git_dir,
1718 &self.work_tree,
1719 &[
1720 "ls-tree",
1721 "-r",
1722 "-z",
1723 "--name-only",
1724 "--end-of-options",
1725 treeish,
1726 ],
1727 )?;
1728 if !ls.status.success() {
1729 return Err(io_other(format!(
1730 "git ls-tree failed: {}",
1731 String::from_utf8_lossy(&ls.stderr).trim()
1732 )));
1733 }
1734 Ok(parse_nul_paths(&ls.stdout))
1735 }
1736
1737 fn remove_paths_missing_from_target(
1738 &self,
1739 current_paths: &HashSet<PathBuf>,
1740 target_paths: &HashSet<PathBuf>,
1741 ) -> io::Result<()> {
1742 let removals: Vec<&PathBuf> = current_paths
1743 .difference(target_paths)
1744 .filter(|rel| is_safe_relative_path(rel))
1745 .collect();
1746 // The removal list comes from the side repo, not the live tree. A
1747 // directory may have been replaced by a symlink since the backup, and
1748 // `remove_file` would follow it and delete outside the workspace.
1749 // Refuse the whole removal before deleting anything.
1750 for rel in &removals {
1751 self.removal_parent_is_real(rel)?;
1752 }
1753 for rel in removals {
1754 // Checked again next to the delete: the tree is live.
1755 if !self.removal_parent_is_real(rel)? {
1756 continue;
1757 }
1758 let path = self.work_tree.join(rel);
1759 let metadata = match std::fs::symlink_metadata(&path) {
1760 Ok(metadata) => metadata,
1761 Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
1762 Err(error) => return Err(error),
1763 };
1764 if metadata.file_type().is_dir() {
1765 // A file-to-directory transition can make this path a
1766 // required parent of files just restored from the target.
1767 if target_paths.iter().any(|target| target.starts_with(rel)) {
1768 continue;
1769 }
1770 std::fs::remove_dir(&path)?;
1771 } else {
1772 std::fs::remove_file(&path)?;
1773 }
1774 self.prune_empty_parent_dirs(path.parent());
1775 }
1776 Ok(())
1777 }
1778
1779 /// Whether every directory between the work tree and `rel` is a real
1780 /// directory. `Ok(false)`: one is missing, so `rel` is gone too. An
1781 /// ancestor that is a symlink or a file is an `InvalidInput` refusal.
1782 fn removal_parent_is_real(&self, rel: &Path) -> io::Result<bool> {
1783 let mut dir = self.work_tree.clone();
1784 for part in rel.parent().into_iter().flat_map(Path::components) {
1785 dir.push(part);
1786 match std::fs::symlink_metadata(&dir) {
1787 Ok(meta) if meta.file_type().is_dir() => {}
1788 Ok(_) => {
1789 return Err(io::Error::new(
1790 io::ErrorKind::InvalidInput,
1791 format!(
1792 "restore refuses to remove '{}': '{}' is no longer a directory (a symlink could lead outside the workspace)",
1793 rel.display(),
1794 dir.strip_prefix(&self.work_tree).unwrap_or(&dir).display()
1795 ),
1796 ));
1797 }
1798 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
1799 Err(error) => return Err(error),
1800 }
1801 }
1802 Ok(true)
1803 }
1804
1805 fn prune_empty_parent_dirs(&self, mut dir: Option<&Path>) {
1806 while let Some(path) = dir {
1807 if path == self.work_tree {
1808 break;
1809 }
1810 if std::fs::remove_dir(path).is_err() {
1811 break;
1812 }
1813 dir = path.parent();
1814 }
1815 }
1816
1817 /// List up to `limit` most-recent snapshots, newest first.
1818 pub fn list(&self, limit: usize) -> io::Result<Vec<Snapshot>> {
1819 // `git log -<n>` is the short form of `--max-count=<n>`; if `limit`
1820 // is `usize::MAX` (caller asked for "everything") we pass an empty
1821 // count so git defaults to no upper bound.
1822 let mut args: Vec<String> = vec!["log".to_string()];
1823 if limit < usize::MAX {
1824 args.push(format!("--max-count={limit}"));
1825 }
1826 args.push("--pretty=format:%H%x09%T%x09%at%x09%s".to_string());
1827 args.push("--no-color".to_string());
1828 let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
1829 let log = run_git(&self.git_dir, &self.work_tree, &arg_refs)?;
1830 if !log.status.success() {
1831 let head = run_git(
1832 &self.git_dir,
1833 &self.work_tree,
1834 &["symbolic-ref", "-q", "HEAD"],
1835 )?;
1836 if head.status.success() {
1837 let reference = String::from_utf8_lossy(&head.stdout);
1838 let exists = run_git(
1839 &self.git_dir,
1840 &self.work_tree,
1841 &["show-ref", "--verify", "--quiet", reference.trim()],
1842 )?;
1843 if exists.status.code() == Some(1) {
1844 return Ok(Vec::new());
1845 }
1846 }
1847 return Err(io_other(format!(
1848 "git log failed: {}",
1849 String::from_utf8_lossy(&log.stderr).trim()
1850 )));
1851 }
1852 let stdout = String::from_utf8_lossy(&log.stdout);
1853 let mut out = Vec::new();
1854 for line in stdout.lines() {
1855 let mut parts = line.splitn(4, '\t');
1856 let sha = parts.next().unwrap_or("").to_string();
1857 let tree = parts.next().unwrap_or("").to_string();
1858 let ts = parts
1859 .next()
1860 .and_then(|s| s.parse::<i64>().ok())
1861 .unwrap_or(0);
1862 let subject = parts.next().unwrap_or("").to_string();
1863 // `git log --pretty=format:%H` only emits full hex ids; skip anything
1864 // else rather than let it become a revision argument later.
1865 let (Ok(id), Ok(tree)) = (SnapshotId::parse(&sha), SnapshotId::parse(&tree)) else {
1866 continue;
1867 };
1868 let (session_id, label) = Self::decode_session_label(&subject);
1869 out.push(Snapshot {
1870 id,
1871 tree,
1872 label,
1873 timestamp: ts,
1874 session_id,
1875 });
1876 }
1877 Ok(out)
1878 }
1879
1880 /// Drop snapshots older than `max_age`, returning the count removed.
1881 ///
1882 /// Strategy: identify keepable commits (younger than the cutoff),
1883 /// reset HEAD to the oldest survivor, then `git reflog expire` +
1884 /// `git gc --prune=now` to actually reclaim space. Cheap and avoids
1885 /// rewriting history when nothing has aged out.
1886 pub fn prune_older_than(&self, max_age: Duration) -> io::Result<usize> {
1887 self.with_write_lock(|| self.prune_older_than_locked(max_age))
1888 }
1889
1890 fn prune_older_than_locked(&self, max_age: Duration) -> io::Result<usize> {
1891 self.repair_broken_head()?;
1892 let now = SystemTime::now()
1893 .duration_since(UNIX_EPOCH)
1894 .map_err(|e| io_other(format!("clock error: {e}")))?
1895 .as_secs() as i64;
1896 let cutoff = now.saturating_sub(i64::try_from(max_age.as_secs()).unwrap_or(i64::MAX));
1897
1898 let snapshots = self.list(usize::MAX)?;
1899 if snapshots.is_empty() {
1900 return Ok(0);
1901 }
1902
1903 // Snapshots are newest-first. Find the index of the first one
1904 // at-or-older than the cutoff — every entry from that index
1905 // onward is a candidate for removal. We use `<=` so a 0-second
1906 // retention drops same-second commits (otherwise tests calling
1907 // `prune_older_than(Duration::ZERO)` immediately after creating
1908 // a snapshot would never prune anything).
1909 let cut_index = snapshots.iter().position(|s| s.timestamp <= cutoff);
1910 let Some(cut) = cut_index else {
1911 return Ok(0);
1912 };
1913 let removed = snapshots.len() - cut;
1914 if removed == 0 {
1915 return Ok(0);
1916 }
1917
1918 if cut == 0 {
1919 // Every snapshot is older than the cutoff: unset HEAD so the next
1920 // snapshot starts a fresh history and gc reclaims the old one.
1921 self.move_head(None, Some(snapshots[0].id.as_str()))?;
1922 } else {
1923 // Keep the newest `cut` snapshots (indices [0..cut], newest-first)
1924 // and drop the older tail. This MUST rebuild the survivors as a
1925 // fresh orphan chain, not `update-ref HEAD <oldest survivor>`:
1926 // the snapshots are a parent-linked commit chain with the newest
1927 // at HEAD, so pointing HEAD at the oldest survivor orphaned every
1928 // NEWER snapshot (gc then destroyed them) while keeping the very
1929 // snapshots we meant to remove as its ancestors — the exact
1930 // inverse of the intent (2026-08-04 review, reproduced).
1931 self.rebuild_survivor_chain(&snapshots[..cut], &snapshots[0].id)?;
1932 }
1933
1934 self.reclaim_unreachable();
1935 Ok(removed)
1936 }
1937
1938 /// Expire the reflog and gc every unreachable object now, reclaiming the
1939 /// space of the snapshots a prune dropped. Runs only under the snapshot
1940 /// write lock: an immediate prune is safe because no other writer that
1941 /// takes the lock can hold a new, not yet referenced object meanwhile.
1942 fn reclaim_unreachable(&self) {
1943 let _ = run_git(
1944 &self.git_dir,
1945 &self.work_tree,
1946 &["reflog", "expire", "--expire=now", "--all"],
1947 );
1948 let _ = run_git(
1949 &self.git_dir,
1950 &self.work_tree,
1951 &["gc", "--prune=now", "--quiet"],
1952 );
1953 }
1954
1955 /// Run `op` holding the side repo's cross-process write lock (see
1956 /// [`SNAPSHOT_LOCK_FILE`]). Reentrant on one thread, so a locked
1957 /// operation may call another.
1958 fn with_write_lock<T>(&self, op: impl FnOnce() -> io::Result<T>) -> io::Result<T> {
1959 self.with_write_lock_within(SNAPSHOT_LOCK_WAIT, op)
1960 }
1961
1962 /// [`Self::with_write_lock`] with an explicit bound on the wait. The
1963 /// snapshot runs on the turn and tool path, so a peer's long gc (or a
1964 /// stopped process holding the lock) must fail this snapshot, not stall
1965 /// the turn and pin a blocking thread indefinitely.
1966 fn with_write_lock_within<T>(
1967 &self,
1968 wait: Duration,
1969 op: impl FnOnce() -> io::Result<T>,
1970 ) -> io::Result<T> {
1971 let held = HELD_SNAPSHOT_LOCKS.with(|held| held.borrow().contains(&self.git_dir));
1972 if held {
1973 return op();
1974 }
1975 let reacquire_delay = snapshot_lock_released_at()
1976 .lock()
1977 .ok()
1978 .and_then(|released| released.get(&self.git_dir).copied())
1979 .and_then(|at| SNAPSHOT_LOCK_REACQUIRE_DELAY.checked_sub(at.elapsed()));
1980 if let Some(remaining) = reacquire_delay {
1981 std::thread::sleep(remaining);
1982 }
1983 let file = open_snapshot_lock_file(&self.git_dir.join(SNAPSHOT_LOCK_FILE))?;
1984 let mut lock = fd_lock::RwLock::new(file);
1985 let deadline = std::time::Instant::now() + wait;
1986 let _guard = loop {
1987 match lock.try_write() {
1988 Ok(guard) => break guard,
1989 Err(err) if std::time::Instant::now() >= deadline => {
1990 return Err(io::Error::new(
1991 io::ErrorKind::TimedOut,
1992 format!(
1993 "snapshot side repo is busy: another session held its lock for over {}s ({err})",
1994 wait.as_secs()
1995 ),
1996 ));
1997 }
1998 Err(_) => std::thread::sleep(SNAPSHOT_LOCK_POLL),
1999 }
2000 };
2001 // Declared after the guard, so it is dropped (and the thread's claim
2002 // released) before the file lock is.
2003 let _held = HeldSnapshotLock::claim(&self.git_dir);
2004 let result = op();
2005 drop(_held);
2006 drop(_guard);
2007 if let Ok(mut released) = snapshot_lock_released_at().lock() {
2008 released.insert(self.git_dir.clone(), std::time::Instant::now());
2009 }
2010 result
2011 }
2012
2013 /// Stage every tracked and untracked path the workspace exposes.
2014 /// `--all` means `add` + `update` + `remove`, the set `git status` shows.
2015 fn stage_work_tree(&self) -> io::Result<()> {
2016 let add = run_git(&self.git_dir, &self.work_tree, &["add", "-A"])?;
2017 if !add.status.success() {
2018 return Err(io_other(format!(
2019 "git add -A failed: {}",
2020 String::from_utf8_lossy(&add.stderr).trim()
2021 )));
2022 }
2023 Ok(())
2024 }
2025
2026 /// Rebuild `survivors` (newest-first) as a fresh orphan commit chain and
2027 /// point HEAD at its tip, so every snapshot NOT in `survivors` becomes
2028 /// unreachable for gc to reclaim. Each survivor's tree, label, session
2029 /// id, and author/committer timestamp are preserved, so ages do not lie
2030 /// after a prune (finding: `prune_keep_last_n` previously reset them to
2031 /// "now"). Assumes `survivors` is non-empty.
2032 ///
2033 /// `listed_head` is the HEAD the survivors were chosen from; if another
2034 /// writer moved HEAD since, the rebuild fails rather than orphan that
2035 /// writer's snapshot.
2036 fn rebuild_survivor_chain(
2037 &self,
2038 survivors: &[Snapshot],
2039 listed_head: &SnapshotId,
2040 ) -> io::Result<()> {
2041 let mut prev_sha: Option<String> = None;
2042 for s in survivors.iter().rev() {
2043 let tree_hash = s.tree.as_str().to_string();
2044
2045 let mut args = vec![
2046 "commit-tree".to_string(),
2047 "-m".to_string(),
2048 Self::encode_session_label(&s.label, s.session_id.as_deref()),
2049 tree_hash,
2050 ];
2051 if let Some(ref p) = prev_sha {
2052 args.push("-p".to_string());
2053 args.push(p.clone());
2054 }
2055 let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
2056 let new_sha = self.commit_tree_preserving_date(&arg_refs, s.timestamp)?;
2057 prev_sha = Some(new_sha);
2058 }
2059
2060 if let Some(final_sha) = prev_sha {
2061 self.move_head(Some(&final_sha), Some(listed_head.as_str()))?;
2062 }
2063 Ok(())
2064 }
2065
2066 /// Point HEAD at `new` (or delete it when `None`), only if it still names
2067 /// `expected` (`None`: HEAD must not exist yet). The compare-and-swap
2068 /// means a writer that does not take the snapshot lock, such as an older
2069 /// build, is never silently orphaned: the move fails instead.
2070 fn move_head(&self, new: Option<&str>, expected: Option<&str>) -> io::Result<()> {
2071 let expected = expected.unwrap_or("");
2072 let args = match new {
2073 Some(new) => ["update-ref", "HEAD", new, expected],
2074 None => ["update-ref", "-d", "HEAD", expected],
2075 };
2076 let update = run_git(&self.git_dir, &self.work_tree, &args)?;
2077 if !update.status.success() {
2078 return Err(io_other(format!(
2079 "git update-ref HEAD failed: {}",
2080 String::from_utf8_lossy(&update.stderr).trim()
2081 )));
2082 }
2083 Ok(())
2084 }
2085
2086 /// Run a `commit-tree` invocation with the author/committer dates pinned
2087 /// to `timestamp` (Unix seconds), so a rebuilt survivor keeps its real
2088 /// age instead of stamping "now".
2089 fn commit_tree_preserving_date(&self, args: &[&str], timestamp: i64) -> io::Result<String> {
2090 let date = format!("{timestamp} +0000");
2091 let mut command = codewhale_dependencies::Git::command()
2092 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "git not found on PATH"))?;
2093 command
2094 .arg("--git-dir")
2095 .arg(&self.git_dir)
2096 .arg("--work-tree")
2097 .arg(&self.work_tree)
2098 .env("GIT_AUTHOR_DATE", &date)
2099 .env("GIT_COMMITTER_DATE", &date)
2100 .args(args);
2101 let out = run_bounded_git(&mut command, args.first().copied().unwrap_or("git"))?;
2102 if !out.status.success() {
2103 return Err(io_other(format!(
2104 "commit-tree failed: {}",
2105 String::from_utf8_lossy(&out.stderr).trim()
2106 )));
2107 }
2108 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
2109 }
2110
2111 /// Prune by count: keep the newest `max_count` snapshots, plus the newest
2112 /// `max_count` turn boundaries (`pre-turn:` / `post-turn:`), and drop the
2113 /// rest.
2114 ///
2115 /// Turn boundaries are the restore points turn-scoped undo resolves, and
2116 /// every other kind (`tool:`, `post-tool:`, `pre-restore:`) can arrive in
2117 /// bursts: one turn with more file-modifying tool calls than `max_count`,
2118 /// or several threads sharing the workspace, would otherwise push out the
2119 /// running turn's own `pre-turn:` snapshot before its `post-turn:` one is
2120 /// taken. So the boundaries are retained by their own count, and at most
2121 /// `2 * max_count` snapshots survive.
2122 ///
2123 /// The survivors are rebuilt as a fresh orphan chain; each keeps its
2124 /// tree, label, session id and timestamp, and the dropped ones become
2125 /// unreachable for gc to reclaim.
2126 #[cfg(any(test, feature = "test-support"))]
2127 pub fn prune_keep_last_n(&self, max_count: usize) -> io::Result<usize> {
2128 self.with_write_lock(|| self.prune_keep_last_n_locked(max_count, 1))
2129 }
2130
2131 /// `Self::prune_keep_last_n` for the prune that follows every snapshot:
2132 /// it waits until half a window of snapshots is due to go and drops them
2133 /// together. Rebuilding the survivor chain costs two git processes per
2134 /// survivor, and doing that after every snapshot past the cap put seconds
2135 /// in front of every later turn's provider request. The store then holds
2136 /// at most half a window more than `Self::prune_keep_last_n` would keep.
2137 pub fn prune_keep_last_n_batched(&self, max_count: usize) -> io::Result<usize> {
2138 self.with_write_lock(|| self.prune_keep_last_n_locked(max_count, (max_count / 2).max(1)))
2139 }
2140
2141 fn prune_keep_last_n_locked(&self, max_count: usize, min_removed: usize) -> io::Result<usize> {
2142 let snapshots = self.list(usize::MAX)?;
2143 if snapshots.len() <= max_count {
2144 return Ok(0);
2145 }
2146 // Newest first: keep the first `max_count` of every kind, and the
2147 // first `max_count` turn boundaries wherever they sit.
2148 let mut boundaries_kept = 0usize;
2149 let survivors: Vec<Snapshot> = snapshots
2150 .iter()
2151 .enumerate()
2152 .filter(|(index, snapshot)| {
2153 let boundary = is_turn_boundary_label(&snapshot.label);
2154 let keep = *index < max_count || (boundary && boundaries_kept < max_count);
2155 if keep && boundary {
2156 boundaries_kept += 1;
2157 }
2158 keep
2159 })
2160 .map(|(_, snapshot)| snapshot.clone())
2161 .collect();
2162 let removed = snapshots.len() - survivors.len();
2163 if removed < min_removed || survivors.is_empty() {
2164 return Ok(0);
2165 }
2166 self.rebuild_survivor_chain(&survivors, &snapshots[0].id)?;
2167 self.reclaim_unreachable();
2168 Ok(removed)
2169 }
2170
2171 /// Whether a snapshot of the workspace would leave `rel` out: it is
2172 /// excluded by the workspace's `.gitignore` files or the built-in
2173 /// snapshot exclusions and not already tracked. Such a path is never in
2174 /// any snapshot, so no restore can put it back.
2175 pub fn path_is_excluded(&self, rel: &Path) -> io::Result<bool> {
2176 let rel_str = rel
2177 .to_str()
2178 .ok_or_else(|| io_other("snapshot path must be UTF-8"))?;
2179 let out = run_git(
2180 &self.git_dir,
2181 &self.work_tree,
2182 &["check-ignore", "--quiet", "--", rel_str],
2183 )?;
2184 match out.status.code() {
2185 Some(0) => Ok(true),
2186 Some(1) => Ok(false),
2187 _ => Err(io_other(format!(
2188 "git check-ignore failed: {}",
2189 String::from_utf8_lossy(&out.stderr).trim()
2190 ))),
2191 }
2192 }
2193
2194 /// Drop unreachable loose objects left behind by interrupted or
2195 /// orphaned side-repo operations.
2196 pub fn prune_unreachable_objects(&self) -> io::Result<()> {
2197 self.with_write_lock(|| {
2198 let prune = run_git(&self.git_dir, &self.work_tree, &["prune", "--expire=now"])?;
2199 if !prune.status.success() {
2200 return Err(io_other(format!(
2201 "git prune failed: {}",
2202 String::from_utf8_lossy(&prune.stderr).trim()
2203 )));
2204 }
2205 Ok(())
2206 })
2207 }
2208
2209 /// Return the side-repo's `.git` directory.
2210 pub fn git_dir(&self) -> &Path {
2211 &self.git_dir
2212 }
2213
2214 /// Return the work tree path.
2215 pub fn work_tree(&self) -> &Path {
2216 &self.work_tree
2217 }
2218 }
2219
2220 /// Whether `label` marks a turn boundary (`pre-turn:` / `post-turn:`), the
2221 /// restore points [`SnapshotRepo::prune_keep_last_n`] retains by their own
2222 /// count.
2223 fn is_turn_boundary_label(label: &str) -> bool {
2224 label.starts_with("pre-turn:") || label.starts_with("post-turn:")
2225 }
2226
2227 /// Which snapshots a size-pressure prune keeps (newest first): the newest
2228 /// `keep`, plus the newest snapshot and, for every session, its newest
2229 /// `pre-turn:` and `post-turn:` boundaries wherever they sit. Sessions and
2230 /// sub-agents share the side repo, so protecting only the globally newest
2231 /// boundaries let one session's snapshots push out another's running turn;
2232 /// each session's current turn and the one before it stay restorable
2233 /// however hard the prune has to cut.
2234 fn size_pressure_survivors(snapshots: &[Snapshot], keep: usize) -> Vec<Snapshot> {
2235 let mut boundaries_seen: HashSet<(Option<&str>, bool)> = HashSet::new();
2236 snapshots
2237 .iter()
2238 .enumerate()
2239 .filter(|(index, snapshot)| {
2240 let kind = if snapshot.label.starts_with("pre-turn:") {
2241 Some(true)
2242 } else if snapshot.label.starts_with("post-turn:") {
2243 Some(false)
2244 } else {
2245 None
2246 };
2247 let newest_boundary = kind
2248 .is_some_and(|pre| boundaries_seen.insert((snapshot.session_id.as_deref(), pre)));
2249 *index == 0 || *index < keep || newest_boundary
2250 })
2251 .map(|(_, snapshot)| snapshot.clone())
2252 .collect()
2253 }
2254
2255 /// This thread's claim on a side repo's write lock, released on drop.
2256 struct HeldSnapshotLock(PathBuf);
2257
2258 impl HeldSnapshotLock {
2259 fn claim(git_dir: &Path) -> Self {
2260 HELD_SNAPSHOT_LOCKS.with(|held| held.borrow_mut().push(git_dir.to_path_buf()));
2261 Self(git_dir.to_path_buf())
2262 }
2263 }
2264
2265 impl Drop for HeldSnapshotLock {
2266 fn drop(&mut self) {
2267 HELD_SNAPSHOT_LOCKS.with(|held| {
2268 let mut held = held.borrow_mut();
2269 if let Some(index) = held.iter().rposition(|path| path == &self.0) {
2270 held.remove(index);
2271 }
2272 });
2273 }
2274 }
2275
2276 /// Open (creating if needed) the side repo's lock file without following a
2277 /// symlink planted in its place.
2278 fn open_snapshot_lock_file(path: &Path) -> io::Result<std::fs::File> {
2279 let mut options = std::fs::OpenOptions::new();
2280 options.create(true).truncate(false).read(true).write(true);
2281 #[cfg(unix)]
2282 {
2283 use std::os::unix::fs::OpenOptionsExt;
2284 options
2285 .mode(0o600)
2286 .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
2287 }
2288 options.open(path)
2289 }
2290
2291 fn hash_regular_file_nofollow(path: &Path) -> io::Result<String> {
2292 use sha2::{Digest, Sha256};
2293 use std::io::Read;
2294
2295 let mut options = std::fs::OpenOptions::new();
2296 options.read(true);
2297 #[cfg(unix)]
2298 {
2299 use std::os::unix::fs::OpenOptionsExt;
2300 options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
2301 }
2302 let mut file = options.open(path)?;
2303 if !file.metadata()?.is_file() {
2304 return Err(io::Error::new(
2305 io::ErrorKind::InvalidInput,
2306 "restore refuses directories, symlinks and non-regular files",
2307 ));
2308 }
2309 let mut hasher = Sha256::new();
2310 let mut buffer = [0_u8; 64 * 1024];
2311 loop {
2312 let read = file.read(&mut buffer)?;
2313 if read == 0 {
2314 break;
2315 }
2316 hasher.update(&buffer[..read]);
2317 }
2318 Ok(codewhale_runtime::hashing::hex_bytes(hasher.finalize()))
2319 }
2320
2321 /// Keep the side repo's `info/exclude` at [`BUILTIN_EXCLUDES`]. Every open
2322 /// runs this without the write lock, while another session may be inside
2323 /// `git add -A` reading the file, so it is left alone when already current
2324 /// and otherwise replaced by rename: a truncate-then-write let that reader
2325 /// see an empty exclude list and stage `node_modules/`, `target/` and the
2326 /// like into the shared side repo.
2327 fn write_builtin_excludes(git_dir: &Path) -> io::Result<()> {
2328 let info_dir = git_dir.join("info");
2329 let exclude = info_dir.join("exclude");
2330 if std::fs::read(&exclude).is_ok_and(|current| current == BUILTIN_EXCLUDES.as_bytes()) {
2331 return Ok(());
2332 }
2333 std::fs::create_dir_all(&info_dir)?;
2334 codewhale_util::utils::write_atomic(&exclude, BUILTIN_EXCLUDES.as_bytes())
2335 }
2336
2337 /// Recursively compute the total size of a directory in bytes.
2338 fn dir_size_bytes(root: &Path) -> io::Result<u64> {
2339 fn walk(dir: &Path, total: &mut u64) -> io::Result<()> {
2340 if !dir.is_dir() {
2341 return Ok(());
2342 }
2343 for entry in std::fs::read_dir(dir)? {
2344 let entry = entry?;
2345 let path = entry.path();
2346 let ft = entry.file_type()?;
2347 if ft.is_symlink() {
2348 continue;
2349 }
2350 if ft.is_dir() {
2351 walk(&path, total)?;
2352 } else if ft.is_file() {
2353 *total = total.saturating_add(entry.metadata().map(|m| m.len()).unwrap_or(0));
2354 }
2355 }
2356 Ok(())
2357 }
2358 let mut total: u64 = 0;
2359 walk(root, &mut total)?;
2360 Ok(total)
2361 }
2362
2363 /// Log once per workspace per process when the size-pressure prune destroys
2364 /// restore points.
2365 fn notify_snapshot_history_pruned_once(workspace: &Path, removed: usize) {
2366 use std::collections::HashSet;
2367 use std::sync::{Mutex, OnceLock};
2368 static NOTIFIED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
2369 let key = workspace.to_string_lossy().into_owned();
2370 let set = NOTIFIED.get_or_init(|| Mutex::new(HashSet::new()));
2371 let Ok(mut guard) = set.lock() else {
2372 return;
2373 };
2374 if !guard.insert(key) {
2375 return;
2376 }
2377 drop(guard);
2378 tracing::warn!(
2379 target: "snapshot",
2380 workspace = %workspace.display(),
2381 removed,
2382 cap_mb = MAX_SNAPSHOT_SIZE_MB,
2383 "{}",
2384 snapshot_history_pruned_message(workspace, removed).trim_end()
2385 );
2386 }
2387
2388 /// Build the user-visible notice for a size-pressure prune. Kept pure and
2389 /// separate from the emit/dedup shell so the content is unit-testable.
2390 fn snapshot_history_pruned_message(workspace: &Path, removed: usize) -> String {
2391 format!(
2392 "warning: snapshot/undo history for {} was pruned to stay under the {} MB snapshot storage cap.
2393 {} snapshot(s) were removed and can no longer be restored.
2394 The cap bounds the undo side-repo's disk use; high-churn or large workspaces hit it sooner.
2395 ",
2396 workspace.display(),
2397 MAX_SNAPSHOT_SIZE_MB,
2398 removed
2399 )
2400 }
2401
2402 fn cleanup_stale_pack_temps(git_dir: &Path, stale_age: Duration) -> io::Result<usize> {
2403 let pack_dir = git_dir.join("objects").join("pack");
2404 if !pack_dir.exists() {
2405 return Ok(0);
2406 }
2407 cleanup_stale_pack_temps_in(&pack_dir, stale_age, SystemTime::now())
2408 }
2409
2410 fn cleanup_stale_pack_temps_in(
2411 pack_dir: &Path,
2412 stale_age: Duration,
2413 now: SystemTime,
2414 ) -> io::Result<usize> {
2415 let mut removed = 0;
2416 for entry in std::fs::read_dir(pack_dir)? {
2417 let entry = entry?;
2418 let name = entry.file_name();
2419 let Some(name) = name.to_str() else {
2420 continue;
2421 };
2422 if !name.starts_with("tmp_pack_") {
2423 continue;
2424 }
2425 if !entry.file_type()?.is_file() {
2426 continue;
2427 }
2428
2429 let metadata = entry.metadata()?;
2430 let Ok(modified) = metadata.modified() else {
2431 continue;
2432 };
2433 let Ok(age) = now.duration_since(modified) else {
2434 continue;
2435 };
2436 if age < stale_age {
2437 continue;
2438 }
2439
2440 match std::fs::remove_file(entry.path()) {
2441 Ok(()) => removed += 1,
2442 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
2443 Err(err) => return Err(err),
2444 }
2445 }
2446 Ok(removed)
2447 }
2448
2449 // Generous budget: `git add -A` on a large workspace is legitimately slow,
2450 // but a wedged git (stalled NFS/FUSE, hung hook) must not block the turn
2451 // pipeline forever — every caller treats a snapshot error as
2452 // snapshot-disabled-with-warning and proceeds without the git data. Tests
2453 // use a tighter budget so a regression that deadlocks a child on its own
2454 // output fails in seconds instead of hanging for the full window.
2455 #[cfg(not(any(test, feature = "test-support")))]
2456 pub(crate) const GIT_COMMAND_TIMEOUT: Duration = Duration::from_secs(300);
2457 #[cfg(any(test, feature = "test-support"))]
2458 pub(crate) const GIT_COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
2459
2460 /// Run a pre-configured git command under [`GIT_COMMAND_TIMEOUT`] with both
2461 /// pipes drained while the child runs (the same concurrent drain
2462 /// `Command::output` performs). Every git invocation in this module goes
2463 /// through here, so a wedged git — stalled NFS/FUSE, hung hook — degrades
2464 /// the snapshot with an error instead of hanging the turn pipeline.
2465 ///
2466 /// The timeout path kills the child and reaps it on a detached thread: on a
2467 /// hard-wedged mount git can sit in uninterruptible kernel I/O where even
2468 /// SIGKILL is deferred, and a blocking `wait()` would hang the pipeline
2469 /// exactly like the wedged git would. Killing without git's own cleanup can
2470 /// leave a fresh `index.lock` behind; later snapshots then fail fast on the
2471 /// lock with an error naming it.
2472 fn run_bounded_git(cmd: &mut std::process::Command, subcommand: &str) -> io::Result<Output> {
2473 run_bounded_git_with_timeout(cmd, subcommand, GIT_COMMAND_TIMEOUT)
2474 }
2475
2476 fn run_git(git_dir: &Path, work_tree: &Path, args: &[&str]) -> io::Result<Output> {
2477 let mut cmd = codewhale_dependencies::Git::command()
2478 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "git not found on PATH"))?;
2479 cmd.arg("--git-dir")
2480 .arg(git_dir)
2481 .arg("--work-tree")
2482 .arg(work_tree)
2483 .args(args);
2484 run_bounded_git(&mut cmd, args.first().copied().unwrap_or("git"))
2485 }
2486
2487 fn git_diff_matches(output: Output) -> io::Result<bool> {
2488 match output.status.code() {
2489 Some(0) => Ok(true),
2490 Some(1) => Ok(false),
2491 _ => Err(io_other(format!(
2492 "git diff failed: {}",
2493 String::from_utf8_lossy(&output.stderr).trim()
2494 ))),
2495 }
2496 }
2497
2498 fn io_other(msg: impl Into<String>) -> io::Error {
2499 io::Error::other(msg.into())
2500 }
2501
2502 /// `text` whole, or the longest prefix that fits in `max_bytes` and ends on a
2503 /// char boundary; the flag says which of the two the caller got.
2504 pub fn truncate_at_char_boundary(text: &str, max_bytes: usize) -> (String, bool) {
2505 if text.len() <= max_bytes {
2506 return (text.to_string(), false);
2507 }
2508 let mut end = max_bytes;
2509 while !text.is_char_boundary(end) {
2510 end -= 1;
2511 }
2512 (text[..end].to_string(), true)
2513 }
2514
2515 /// Walk `workspace` and accumulate file sizes, returning `Ok(total)`
2516 /// when the workspace fits under `cap_bytes` and `Err(gate)` naming the
2517 /// bound that tripped. Honors `.gitignore` — whether or not the
2518 /// workspace is itself a git repo, matching the `git add -A` that the
2519 /// snapshot commit actually runs against this work tree — and the
2520 /// snapshot-specific skip list above, so the measured size reflects
2521 /// what would land in a snapshot commit rather than the raw `du -sh`
2522 /// total.
2523 ///
2524 /// The walk is bounded by both `cap_bytes` and `max_entries`, and the
2525 /// two bounds are reported separately because they have different
2526 /// recoveries. A `cap_bytes` of `0` disables the byte cap entirely (so
2527 /// config can opt out) but not the entry bound.
2528 ///
2529 /// Production passes [`SIZE_WALK_MAX_ENTRIES`] for `max_entries`; it is
2530 /// a parameter only so the entry bound is reachable in a test without
2531 /// creating 200,000 inodes. It must not be threaded up through
2532 /// [`SnapshotRepo::open_or_init_with_cap`]: `WorkspaceGate::describe`
2533 /// interpolates the constant into the user-facing message, so a weaker
2534 /// injected bound would report a number that did not trip.
2535 pub fn estimate_workspace_size_bounded(
2536 workspace: &Path,
2537 cap_bytes: u64,
2538 max_entries: usize,
2539 ) -> Result<u64, WorkspaceGate> {
2540 use ignore::WalkBuilder;
2541 let mut total: u64 = 0;
2542 let mut entries: usize = 0;
2543 let skip: HashSet<&'static str> = SIZE_WALK_SKIP_DIRS.iter().copied().collect();
2544 let walker = WalkBuilder::new(workspace)
2545 .hidden(false)
2546 // `ignore` defaults to `require_git(true)`, which silently disables
2547 // every gitignore rule when the workspace is not inside a git repo.
2548 // The snapshot's own `git add -A` honors `.gitignore` regardless, so
2549 // without this the estimator over-counts a non-git workspace and can
2550 // refuse it while offering a `.gitignore` remedy that cannot work.
2551 .require_git(false)
2552 .follow_links(false)
2553 .filter_entry(move |entry| {
2554 // Skip the well-known build-output directories at any depth.
2555 // The `ignore` crate calls `filter_entry` once per dir/file;
2556 // returning `false` here prunes the whole subtree.
2557 entry
2558 .file_name()
2559 .to_str()
2560 .is_none_or(|name| !skip.contains(name))
2561 })
2562 .build();
2563 for entry in walker.flatten() {
2564 entries += 1;
2565 if entries > max_entries {
2566 return Err(WorkspaceGate::TooManyEntries);
2567 }
2568 if let Ok(meta) = entry.metadata()
2569 && meta.is_file()
2570 {
2571 total = total.saturating_add(meta.len());
2572 if cap_bytes > 0 && total > cap_bytes {
2573 return Err(WorkspaceGate::TooLarge);
2574 }
2575 }
2576 }
2577 Ok(total)
2578 }
2579
2580 pub fn unsafe_workspace_snapshot_reason(
2581 workspace: &Path,
2582 home: Option<&Path>,
2583 ) -> Option<&'static str> {
2584 let workspace = normalize_path_for_safety(workspace);
2585 if is_filesystem_root(&workspace) {
2586 return Some("filesystem root");
2587 }
2588
2589 if is_home_directory(&workspace, home) {
2590 return Some("home directory");
2591 }
2592
2593 let home = home.map(normalize_path_for_safety)?;
2594 if workspace.parent() == Some(home.as_path()) {
2595 let name = workspace.file_name().and_then(|name| name.to_str());
2596 if matches!(
2597 name,
2598 Some(
2599 "Desktop" | "Documents" | "Downloads" | "Library" | "Movies" | "Music" | "Pictures"
2600 )
2601 ) {
2602 return Some("home collection directory");
2603 }
2604 }
2605
2606 None
2607 }
2608
2609 fn normalize_path_for_safety(path: &Path) -> PathBuf {
2610 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
2611 }
2612
2613 fn is_filesystem_root(path: &Path) -> bool {
2614 path.parent().is_none()
2615 }
2616
2617 fn is_home_directory(work_tree: &Path, home: Option<&Path>) -> bool {
2618 let Some(home) = home else {
2619 return false;
2620 };
2621
2622 let home_canonical = home.canonicalize().unwrap_or_else(|_| home.to_path_buf());
2623 work_tree == home_canonical
2624 }
2625
2626 fn parse_nul_paths(bytes: &[u8]) -> HashSet<PathBuf> {
2627 bytes
2628 .split(|b| *b == 0)
2629 .filter(|chunk| !chunk.is_empty())
2630 .map(|chunk| PathBuf::from(String::from_utf8_lossy(chunk).into_owned()))
2631 .collect()
2632 }
2633
2634 fn is_safe_relative_path(path: &Path) -> bool {
2635 !path.as_os_str().is_empty()
2636 && path
2637 .components()
2638 .all(|component| matches!(component, Component::Normal(_)))
2639 }
2640
2641 /// Normalize a caller-supplied path into a safe workspace-relative path.
2642 ///
2643 /// Accepts either a workspace-relative path or an absolute path inside
2644 /// `workspace`. Returns `None` when the result is not a plain relative path —
2645 /// absolute, empty, containing `..`, or pointing outside the workspace. Every
2646 /// file-scoped restore path passes through here, so a caller never gets to
2647 /// name a path the snapshot repo would resolve outside the work tree.
2648 ///
2649 /// The name is literal: leading or trailing spaces, brackets and glob
2650 /// characters are filename bytes, never trimmed and never patterns. Git is
2651 /// invoked with `--literal-pathspecs` for every file-scoped operation.
2652 pub fn workspace_relative_path(workspace: &Path, raw: &str) -> Option<PathBuf> {
2653 if raw.is_empty() {
2654 return None;
2655 }
2656 let candidate = Path::new(raw);
2657 let rel = if candidate.is_absolute() {
2658 strip_workspace_prefix(candidate, workspace, cfg!(windows))?
2659 } else {
2660 candidate.to_path_buf()
2661 };
2662 is_safe_relative_path(&rel).then_some(rel)
2663 }
2664
2665 fn strip_workspace_prefix(
2666 candidate: &Path,
2667 workspace: &Path,
2668 case_insensitive: bool,
2669 ) -> Option<PathBuf> {
2670 if let Ok(rel) = candidate.strip_prefix(workspace) {
2671 return Some(rel.to_path_buf());
2672 }
2673 if !case_insensitive {
2674 return None;
2675 }
2676 let mut remaining = candidate.components();
2677 for expected in workspace.components() {
2678 if !workspace_components_match(&remaining.next()?, &expected) {
2679 return None;
2680 }
2681 }
2682 Some(remaining.as_path().to_path_buf())
2683 }
2684
2685 fn workspace_components_match(
2686 left: &std::path::Component<'_>,
2687 right: &std::path::Component<'_>,
2688 ) -> bool {
2689 use std::path::{Component, Prefix};
2690 match (left, right) {
2691 (Component::Prefix(left), Component::Prefix(right)) => match (left.kind(), right.kind()) {
2692 (
2693 Prefix::Disk(left) | Prefix::VerbatimDisk(left),
2694 Prefix::Disk(right) | Prefix::VerbatimDisk(right),
2695 ) => left.eq_ignore_ascii_case(&right),
2696 _ => left
2697 .as_os_str()
2698 .to_string_lossy()
2699 .eq_ignore_ascii_case(&right.as_os_str().to_string_lossy()),
2700 },
2701 _ => left
2702 .as_os_str()
2703 .to_string_lossy()
2704 .eq_ignore_ascii_case(&right.as_os_str().to_string_lossy()),
2705 }
2706 }
2707
2708 /// Whether some existing ancestor of `rel` (within `root`) is not a
2709 /// directory: restoring `rel` would then turn a file into a directory.
2710 fn ancestor_is_not_a_directory(root: &Path, rel: &Path) -> bool {
2711 rel.ancestors()
2712 .skip(1)
2713 .filter(|ancestor| !ancestor.as_os_str().is_empty())
2714 .any(|ancestor| {
2715 std::fs::symlink_metadata(root.join(ancestor)).is_ok_and(|metadata| !metadata.is_dir())
2716 })
2717 }
2718
2719 #[cfg(test)]
2720 mod tests {
2721 use super::*;
2722 use codewhale_runtime::test_support::lock_test_env;
2723 use std::fs::{File, FileTimes};
2724 use tempfile::tempdir;
2725
2726 #[test]
2727 fn git_metadata_name_covers_case_and_windows_aliases() {
2728 for windows in [false, true] {
2729 for name in [".git", ".GIT", ".Git", ".gIt"] {
2730 assert!(
2731 codewhale_util::git_metadata::git_metadata_name(name, windows),
2732 "{name} windows={windows}"
2733 );
2734 }
2735 for name in [
2736 ".github",
2737 ".gitignore",
2738 "a.git",
2739 "git",
2740 "",
2741 "git~",
2742 "GIT~1a",
2743 ] {
2744 assert!(
2745 !codewhale_util::git_metadata::git_metadata_name(name, windows),
2746 "{name} windows={windows}"
2747 );
2748 }
2749 }
2750 // Windows drops trailing dots/spaces and `:stream` suffixes, and
2751 // `GIT~N` is the 8.3 short name of `.git`; elsewhere these are
2752 // ordinary names.
2753 for name in [
2754 ".git.",
2755 ".git ",
2756 ".GIT. .",
2757 ".git::$INDEX_ALLOCATION",
2758 ".git:stream",
2759 "GIT~1",
2760 "git~12",
2761 ] {
2762 assert!(
2763 codewhale_util::git_metadata::git_metadata_name(name, true),
2764 "{name}"
2765 );
2766 assert!(
2767 !codewhale_util::git_metadata::git_metadata_name(name, false),
2768 "{name}"
2769 );
2770 }
2771 }
2772
2773 #[test]
2774 fn snapshot_id_parse_accepts_only_full_hex_object_ids() {
2775 let sha1 = "0123456789abcdefABCDEF0123456789abcdef01";
2776 let sha256 = "a".repeat(64);
2777 assert_eq!(SnapshotId::parse(sha1).expect("sha1").as_str(), sha1);
2778 assert!(SnapshotId::parse(&sha256).is_ok());
2779 for bad in [
2780 "",
2781 "HEAD",
2782 "abc123",
2783 "--output=/tmp/x",
2784 "-0123456789abcdef0123456789abcdef0123456",
2785 "0123456789abcdef0123456789abcdef0123456g",
2786 "0123456789abcdef0123456789abcdef01234567~1",
2787 "0123456789abcdef0123456789abcdef012345678",
2788 ] {
2789 let err = SnapshotId::parse(bad).expect_err(bad);
2790 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
2791 }
2792 }
2793
2794 /// Holds the home directory pinned to a tempdir for the lifetime of a test. Also
2795 /// owns the process-wide env-var mutex so tests across modules
2796 /// don't trample each other's home env vars.
2797 pub(super) struct ScopedHome {
2798 _vars: Vec<codewhale_runtime::test_support::EnvVarGuard>,
2799 _guard: codewhale_runtime::test_support::TestEnvLock,
2800 }
2801 pub(super) fn scoped_home(home: &Path) -> ScopedHome {
2802 use codewhale_runtime::test_support::EnvVarGuard;
2803 let guard = lock_test_env();
2804 ScopedHome {
2805 _vars: vec![
2806 EnvVarGuard::set("HOME", home),
2807 EnvVarGuard::set("USERPROFILE", home),
2808 EnvVarGuard::remove("HOMEDRIVE"),
2809 EnvVarGuard::remove("HOMEPATH"),
2810 EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")),
2811 ],
2812 _guard: guard,
2813 }
2814 }
2815
2816 /// Build a side-repo inside the test's selected profile. Return its
2817 /// environment guard so reads and writes stay isolated for the whole test.
2818 fn make_repo(tmp: &Path) -> (SnapshotRepo, ScopedHome) {
2819 let workspace = tmp.join("workspace");
2820 std::fs::create_dir_all(&workspace).unwrap();
2821 let guard = scoped_home(tmp);
2822 let repo = SnapshotRepo::open_or_init(&workspace).expect("open_or_init");
2823 (repo, guard)
2824 }
2825
2826 #[test]
2827 fn snapshot_creates_commit_in_side_repo_only() {
2828 let tmp = tempdir().unwrap();
2829 let (repo, _home) = make_repo(tmp.path());
2830 std::fs::write(repo.work_tree().join("a.txt"), b"alpha").unwrap();
2831
2832 let id = repo.snapshot("pre-turn:1").expect("snapshot");
2833 assert_eq!(id.as_str().len(), 40);
2834
2835 let list = repo.list(10).expect("list");
2836 assert_eq!(list.len(), 1);
2837 assert_eq!(list[0].label, "pre-turn:1");
2838
2839 // The user's workspace must NOT have a real `.git` because we
2840 // never created one in their workspace — only in the side dir.
2841 assert!(!repo.work_tree().join(".git").exists());
2842 }
2843
2844 /// B2: a side repo whose HEAD names a missing commit made every snapshot
2845 /// fail on `commit-tree -p` ("is not a valid object"), so /undo died
2846 /// silently. The broken ref is reset and snapshots resume.
2847 #[test]
2848 fn broken_head_is_repaired_and_snapshots_resume() {
2849 let tmp = tempdir().unwrap();
2850 let (repo, _home) = make_repo(tmp.path());
2851 std::fs::write(repo.work_tree().join("a.txt"), b"alpha").unwrap();
2852 repo.snapshot("pre-turn:1").expect("first snapshot");
2853 assert!(!repo.repair_broken_head().expect("healthy head"));
2854
2855 repo.point_head_at_missing_commit_for_test();
2856 assert!(
2857 repo.list(10).is_err() || repo.list(10).unwrap().is_empty(),
2858 "a broken head cannot list its history"
2859 );
2860
2861 // With a reflog, the last commit that still exists is restored and
2862 // the restore points before the break survive.
2863 assert!(
2864 !repo.repair_broken_head().expect("recover"),
2865 "recovered from the reflog, not restarted"
2866 );
2867 let list = repo.list(10).expect("list after recovery");
2868 assert_eq!(list.len(), 1, "{list:?}");
2869 assert_eq!(list[0].label, "pre-turn:1");
2870
2871 // Without one, the broken ref is deleted and history restarts.
2872 repo.point_head_at_missing_commit_for_test();
2873 std::fs::remove_dir_all(repo.git_dir.join("logs")).expect("drop reflogs");
2874 assert!(repo.repair_broken_head().expect("repair"), "repaired once");
2875 assert!(!repo.repair_broken_head().expect("idempotent"));
2876 std::fs::write(repo.work_tree().join("a.txt"), b"beta").unwrap();
2877 repo.snapshot("pre-turn:2").expect("snapshots resume");
2878 let list = repo.list(10).expect("list after repair");
2879 assert_eq!(list.len(), 1, "history restarts at the repair: {list:?}");
2880 assert_eq!(list[0].label, "pre-turn:2");
2881
2882 // The snapshot path repairs on its own too, for callers that never
2883 // asked.
2884 repo.point_head_at_missing_commit_for_test();
2885 repo.snapshot("pre-turn:3")
2886 .expect("snapshot repairs on its own");
2887 }
2888
2889 #[test]
2890 fn open_existing_is_read_only_and_does_not_initialize() {
2891 let tmp = tempdir().unwrap();
2892 let workspace = tmp.path().join("workspace");
2893 std::fs::create_dir_all(&workspace).unwrap();
2894 let _home = scoped_home(tmp.path());
2895
2896 let before = SnapshotRepo::open_existing(&workspace).expect("open existing");
2897 assert!(before.is_none());
2898 assert!(
2899 !snapshot_git_dir(&workspace)
2900 .expect("snapshot path")
2901 .exists(),
2902 "read-only open must not create the side repo"
2903 );
2904
2905 let repo = SnapshotRepo::open_or_init(&workspace).expect("open_or_init");
2906 std::fs::write(repo.work_tree().join("a.txt"), b"alpha").unwrap();
2907 repo.snapshot("pre-turn:1").expect("snapshot");
2908
2909 let after = SnapshotRepo::open_existing(&workspace).expect("open existing");
2910 assert!(after.is_some());
2911 }
2912
2913 #[test]
2914 fn restore_reverts_workspace_files() {
2915 let tmp = tempdir().unwrap();
2916 let (repo, _home) = make_repo(tmp.path());
2917 let f = repo.work_tree().join("file.txt");
2918
2919 std::fs::write(&f, b"original").unwrap();
2920 let id = repo.snapshot("pre-turn:1").expect("snapshot");
2921
2922 std::fs::write(&f, b"clobbered").unwrap();
2923 repo.snapshot("post-turn:1").expect("snapshot 2");
2924
2925 repo.restore(&id).expect("restore");
2926 let after = std::fs::read_to_string(&f).unwrap();
2927 assert_eq!(after, "original");
2928 }
2929
2930 #[test]
2931 fn restore_removes_files_added_after_target_snapshot() {
2932 let tmp = tempdir().unwrap();
2933 let (repo, _home) = make_repo(tmp.path());
2934 let original = repo.work_tree().join("original.txt");
2935 let added = repo.work_tree().join("added.txt");
2936
2937 std::fs::write(&original, b"original").unwrap();
2938 let id = repo.snapshot("pre-turn:1").expect("snapshot");
2939
2940 std::fs::write(&added, b"new file").unwrap();
2941 repo.snapshot("post-turn:1").expect("snapshot 2");
2942
2943 repo.restore(&id).expect("restore");
2944 assert!(original.exists());
2945 assert!(!added.exists(), "restore must remove tracked added files");
2946 }
2947
2948 /// The first snapshot of an empty project holds the empty tree. Restoring
2949 /// it used to fail (`pathspec ':/' did not match`) before removing
2950 /// anything, so every file created since stayed.
2951 #[test]
2952 fn restore_to_an_empty_snapshot_removes_the_files_created_since() {
2953 let tmp = tempdir().unwrap();
2954 let (repo, _home) = make_repo(tmp.path());
2955 let empty = repo.snapshot("pre-turn:1").expect("empty snapshot");
2956 let created = repo.work_tree().join("src").join("main.rs");
2957 std::fs::create_dir_all(created.parent().unwrap()).unwrap();
2958 std::fs::write(&created, b"fn main() {}").unwrap();
2959 std::fs::write(repo.work_tree().join("notes.txt"), b"notes").unwrap();
2960 repo.snapshot("post-turn:1").expect("snapshot 2");
2961
2962 repo.restore(&empty).expect("restore to the empty tree");
2963 assert!(!created.exists(), "restore must remove files created since");
2964 assert!(!repo.work_tree().join("notes.txt").exists());
2965 assert!(
2966 !repo.work_tree().join("src").exists(),
2967 "directories the removal emptied go too"
2968 );
2969 }
2970
2971 #[test]
2972 fn restore_keeps_current_files_when_safety_snapshot_fails() {
2973 let tmp = tempdir().unwrap();
2974 let (repo, _home) = make_repo(tmp.path());
2975 let empty = repo.snapshot("pre-turn:1").unwrap();
2976 let file = repo.work_tree().join("new-work.txt");
2977 std::fs::write(&file, b"only copy of new work").unwrap();
2978 repo.snapshot("post-turn:1").unwrap();
2979 std::fs::write(repo.git_dir().join("index.lock"), b"").unwrap();
2980
2981 let error = repo.restore(&empty).expect_err("backup is mandatory");
2982 assert!(
2983 error.to_string().contains("safety snapshot failed"),
2984 "{error}"
2985 );
2986 assert_eq!(std::fs::read(&file).unwrap(), b"only copy of new work");
2987 }
2988
2989 #[test]
2990 fn restore_rolls_back_files_after_a_partial_checkout_error() {
2991 let tmp = tempdir().unwrap();
2992 let (repo, _home) = make_repo(tmp.path());
2993 let first = repo.work_tree().join("a.txt");
2994 let last_dir = repo.work_tree().join("z");
2995 let last = last_dir.join("last.txt");
2996 std::fs::create_dir(&last_dir).unwrap();
2997 std::fs::write(&first, b"old first").unwrap();
2998 std::fs::write(&last, b"old last").unwrap();
2999 let target = repo.snapshot("pre-turn:1").unwrap();
3000 let object = run_git(
3001 repo.git_dir(),
3002 repo.work_tree(),
3003 &["rev-parse", &format!("{}:z/last.txt", target.as_str())],
3004 )
3005 .unwrap();
3006 assert!(object.status.success());
3007 let object = String::from_utf8(object.stdout).unwrap();
3008 let object = object.trim();
3009 std::fs::write(&first, b"new first").unwrap();
3010 std::fs::remove_file(&last).unwrap();
3011 let before = repo.snapshot("before-restore-proof").unwrap();
3012 // A missing target-only blob makes Git fail after it writes a.txt.
3013 // The backup needs neither that blob nor z/last.txt for recovery.
3014 std::fs::remove_file(
3015 repo.git_dir()
3016 .join("objects")
3017 .join(&object[..2])
3018 .join(&object[2..]),
3019 )
3020 .unwrap();
3021
3022 // Prove the failure fixture really permits a partial overwrite.
3023 let partial = run_git(
3024 repo.git_dir(),
3025 repo.work_tree(),
3026 &["checkout", target.as_str(), "--", ":/"],
3027 )
3028 .unwrap();
3029 assert!(!partial.status.success());
3030 assert_eq!(std::fs::read(&first).unwrap(), b"old first");
3031 let reset = run_git(
3032 repo.git_dir(),
3033 repo.work_tree(),
3034 &["checkout", before.as_str(), "--", ":/"],
3035 )
3036 .unwrap();
3037 assert!(reset.status.success());
3038 assert_eq!(std::fs::read(&first).unwrap(), b"new first");
3039
3040 let error = repo.restore(&target).expect_err("target blob is missing");
3041 assert!(error.to_string().contains("unable to read"), "{error}");
3042 assert!(
3043 error
3044 .to_string()
3045 .contains("previous snapshot files were restored"),
3046 "{error}"
3047 );
3048 assert!(error.to_string().contains("safety snapshot"), "{error}");
3049 assert_eq!(std::fs::read(&first).unwrap(), b"new first");
3050 assert!(!last.exists());
3051 }
3052
3053 #[test]
3054 fn restore_refuses_file_directory_transitions_without_changing_files() {
3055 for target_is_dir in [false, true] {
3056 let tmp = tempdir().unwrap();
3057 let (repo, _home) = make_repo(tmp.path());
3058 let path = repo.work_tree().join("a");
3059 let child = path.join("child");
3060 if target_is_dir {
3061 std::fs::create_dir(&path).unwrap();
3062 std::fs::write(&child, b"old child").unwrap();
3063 } else {
3064 std::fs::write(&path, b"old file").unwrap();
3065 }
3066 let target = repo.snapshot("pre-turn:1").unwrap();
3067 if target_is_dir {
3068 std::fs::remove_file(&child).unwrap();
3069 std::fs::remove_dir(&path).unwrap();
3070 std::fs::write(&path, b"new file").unwrap();
3071 } else {
3072 std::fs::remove_file(&path).unwrap();
3073 std::fs::create_dir(&path).unwrap();
3074 std::fs::write(&child, b"new child").unwrap();
3075 }
3076
3077 let error = repo
3078 .restore(&target)
3079 .expect_err("type transition is refused");
3080 assert!(
3081 error.to_string().contains("file/directory transition"),
3082 "{error}"
3083 );
3084 if target_is_dir {
3085 assert_eq!(std::fs::read(&path).unwrap(), b"new file");
3086 } else {
3087 assert_eq!(std::fs::read(&child).unwrap(), b"new child");
3088 }
3089 }
3090 }
3091
3092 #[test]
3093 fn a_path_under_a_live_file_needs_a_transition() {
3094 let tmp = tempdir().unwrap();
3095 std::fs::write(tmp.path().join("a"), b"file").unwrap();
3096 std::fs::create_dir(tmp.path().join("d")).unwrap();
3097 assert!(super::ancestor_is_not_a_directory(
3098 tmp.path(),
3099 Path::new("a/child")
3100 ));
3101 assert!(!super::ancestor_is_not_a_directory(
3102 tmp.path(),
3103 Path::new("d/child")
3104 ));
3105 assert!(!super::ancestor_is_not_a_directory(
3106 tmp.path(),
3107 Path::new("missing/child")
3108 ));
3109 assert!(!super::ancestor_is_not_a_directory(
3110 tmp.path(),
3111 Path::new("a")
3112 ));
3113 }
3114
3115 /// A failed safety snapshot refuses before a symlinked parent could be
3116 /// followed, even when restoring to an empty target skips checkout.
3117 #[cfg(unix)]
3118 #[test]
3119 fn restore_refuses_to_remove_through_a_symlinked_parent() {
3120 let tmp = tempdir().unwrap();
3121 let (repo, _home) = make_repo(tmp.path());
3122 let empty = repo.snapshot("pre-turn:1").expect("empty snapshot");
3123 let src = repo.work_tree().join("src");
3124 std::fs::create_dir_all(&src).unwrap();
3125 std::fs::write(src.join("victim"), b"inside").unwrap();
3126 repo.snapshot("post-turn:1")
3127 .expect("snapshot holding src/victim");
3128
3129 let outside = tempdir().unwrap();
3130 let sentinel = outside.path().join("victim");
3131 std::fs::write(&sentinel, b"outside").unwrap();
3132 std::fs::remove_dir_all(&src).unwrap();
3133 std::os::unix::fs::symlink(outside.path(), &src).unwrap();
3134 // A stale index lock makes the mandatory safety snapshot fail.
3135 std::fs::write(repo.git_dir().join("index.lock"), b"").unwrap();
3136
3137 let err = repo
3138 .restore(&empty)
3139 .expect_err("a removal through a symlinked parent is refused");
3140 assert!(err.to_string().contains("safety snapshot failed"), "{err}");
3141 assert_eq!(
3142 std::fs::read(&sentinel).unwrap(),
3143 b"outside",
3144 "the file outside the workspace survives"
3145 );
3146 assert!(
3147 std::fs::symlink_metadata(&src)
3148 .unwrap()
3149 .file_type()
3150 .is_symlink()
3151 );
3152 }
3153
3154 /// Every session, turn and sub-agent in a workspace shares its side repo.
3155 /// A snapshot must wait while another writer holds the repo's write lock
3156 /// instead of racing its index, HEAD and gc.
3157 #[test]
3158 fn snapshot_waits_for_the_side_repo_write_lock() {
3159 let tmp = tempdir().unwrap();
3160 let (repo, _home) = make_repo(tmp.path());
3161 std::fs::write(repo.work_tree().join("f.txt"), b"v0").unwrap();
3162 repo.snapshot("pre-turn:1").expect("first snapshot");
3163
3164 let lock_path = repo.git_dir().join(SNAPSHOT_LOCK_FILE);
3165 let mut peer = fd_lock::RwLock::new(open_snapshot_lock_file(&lock_path).unwrap());
3166 let held = peer.write().expect("peer holds the write lock");
3167
3168 let (done_tx, done_rx) = std::sync::mpsc::channel();
3169 let git_dir = repo.git_dir().to_path_buf();
3170 let work_tree = repo.work_tree().to_path_buf();
3171 let writer = std::thread::spawn(move || {
3172 let repo = SnapshotRepo { git_dir, work_tree };
3173 std::fs::write(repo.work_tree().join("f.txt"), b"v1").unwrap();
3174 let taken = repo.snapshot("post-turn:1");
3175 let _ = done_tx.send(());
3176 taken
3177 });
3178 assert!(
3179 done_rx.recv_timeout(Duration::from_millis(400)).is_err(),
3180 "a snapshot must not run while another writer holds the lock"
3181 );
3182 drop(held);
3183 done_rx
3184 .recv_timeout(Duration::from_secs(30))
3185 .expect("snapshot proceeds once the lock is released");
3186 writer
3187 .join()
3188 .expect("writer thread")
3189 .expect("snapshot after release");
3190 assert_eq!(repo.list(usize::MAX).unwrap().len(), 2);
3191 }
3192
3193 /// Two writers sharing one side repo, each snapshotting and pruning, must
3194 /// all succeed and leave a history whose every snapshot still restores.
3195 #[test]
3196 fn concurrent_snapshot_and_prune_keep_the_side_repo_consistent() {
3197 fn eventually<T>(mut op: impl FnMut() -> io::Result<T>) -> io::Result<T> {
3198 let mut attempts = 0;
3199 loop {
3200 match op() {
3201 Err(err) if err.kind() == io::ErrorKind::TimedOut && attempts < 5 => {
3202 attempts += 1;
3203 }
3204 other => return other,
3205 }
3206 }
3207 }
3208 let tmp = tempdir().unwrap();
3209 let (repo, _home) = make_repo(tmp.path());
3210 std::fs::write(repo.work_tree().join("seed.txt"), b"seed").unwrap();
3211 repo.snapshot("pre-turn:0").expect("seed snapshot");
3212 let git_dir = repo.git_dir().to_path_buf();
3213 let work_tree = repo.work_tree().to_path_buf();
3214 let writers: Vec<_> = (0..2)
3215 .map(|writer| {
3216 let git_dir = git_dir.clone();
3217 let work_tree = work_tree.clone();
3218 std::thread::spawn(move || -> io::Result<()> {
3219 let repo = SnapshotRepo { git_dir, work_tree };
3220 for turn in 0..6 {
3221 std::fs::write(
3222 repo.work_tree().join(format!("w{writer}.txt")),
3223 format!("{writer}-{turn}"),
3224 )?;
3225 eventually(|| repo.snapshot(&format!("post-turn:{writer}-{turn}")))?;
3226 eventually(|| repo.prune_keep_last_n(2))?;
3227 }
3228 Ok(())
3229 })
3230 })
3231 .collect();
3232 for writer in writers {
3233 writer
3234 .join()
3235 .expect("writer thread")
3236 .expect("writer ran clean");
3237 }
3238 assert!(!repo.repair_broken_head().expect("head check"));
3239 let history = repo.list(usize::MAX).expect("history lists");
3240 assert!(!history.is_empty());
3241 for snapshot in &history {
3242 assert!(
3243 repo.is_commit(snapshot.id.as_str()).unwrap(),
3244 "listed snapshot {} must exist",
3245 snapshot.id.as_str()
3246 );
3247 }
3248 }
3249
3250 /// A peer stuck holding the lock (a long gc, a stopped process) used to
3251 /// block the snapshot, and the turn waiting on it, with no end. The wait
3252 /// is bounded and ends in an error the turn reports.
3253 #[test]
3254 fn side_repo_lock_wait_is_bounded() {
3255 let tmp = tempdir().unwrap();
3256 let (repo, _home) = make_repo(tmp.path());
3257 let lock_path = repo.git_dir().join(SNAPSHOT_LOCK_FILE);
3258 let mut peer = fd_lock::RwLock::new(open_snapshot_lock_file(&lock_path).unwrap());
3259 let _held = peer.write().expect("peer holds the write lock");
3260
3261 let started = std::time::Instant::now();
3262 let err = repo
3263 .with_write_lock_within(Duration::from_millis(200), || Ok(()))
3264 .expect_err("a held lock times out");
3265 assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}");
3266 assert!(err.to_string().contains("busy"), "{err}");
3267 assert!(
3268 started.elapsed() < Duration::from_secs(10),
3269 "the wait ends near its bound"
3270 );
3271 }
3272
3273 #[test]
3274 fn side_repo_lock_reacquire_waits_out_the_courtesy_delay() {
3275 let tmp = tempdir().unwrap();
3276 let (repo, _home) = make_repo(tmp.path());
3277 repo.with_write_lock(|| Ok(())).unwrap();
3278 let started = std::time::Instant::now();
3279 for _ in 0..3 {
3280 repo.with_write_lock(|| Ok(())).unwrap();
3281 }
3282 assert!(
3283 started.elapsed() >= SNAPSHOT_LOCK_REACQUIRE_DELAY,
3284 "an immediate reacquire yields a poll window to a waiting writer"
3285 );
3286 }
3287
3288 /// First-time init (git init plus the pinned identity) runs under the
3289 /// write lock, so two sessions opening a new workspace do not race it; a
3290 /// `.git` holding only a peer's lock file is initialized, not trusted.
3291 #[test]
3292 fn first_init_waits_for_the_side_repo_write_lock() {
3293 let tmp = tempdir().unwrap();
3294 let (repo, _home) = make_repo(tmp.path());
3295 let git_dir = repo.git_dir().to_path_buf();
3296 let workspace = repo.work_tree().to_path_buf();
3297 drop(repo);
3298 std::fs::remove_dir_all(&git_dir).unwrap();
3299 std::fs::create_dir_all(&git_dir).unwrap();
3300 let mut peer = fd_lock::RwLock::new(
3301 open_snapshot_lock_file(&git_dir.join(SNAPSHOT_LOCK_FILE)).unwrap(),
3302 );
3303 let held = peer.write().expect("peer holds the write lock");
3304
3305 let (done_tx, done_rx) = std::sync::mpsc::channel();
3306 let env_ticket = codewhale_runtime::test_support::env_scope_ticket();
3307 let opener = std::thread::spawn(move || {
3308 let _membership = codewhale_runtime::test_support::join_env_scope(env_ticket);
3309 let opened = SnapshotRepo::open_or_init(&workspace);
3310 let _ = done_tx.send(());
3311 opened
3312 });
3313 assert!(
3314 done_rx.recv_timeout(Duration::from_millis(400)).is_err(),
3315 "init must not run while another writer holds the lock"
3316 );
3317 drop(held);
3318 done_rx
3319 .recv_timeout(Duration::from_secs(30))
3320 .expect("init proceeds once the lock is released");
3321 let repo = opener.join().expect("opener thread").expect("open_or_init");
3322 assert!(
3323 repo.git_dir().join("HEAD").exists(),
3324 "the repo was initialized"
3325 );
3326 std::fs::write(repo.work_tree().join("f.txt"), b"v").unwrap();
3327 repo.snapshot("pre-turn:1").expect("the new repo snapshots");
3328 }
3329
3330 /// Opening runs on every snapshot without the write lock while a peer may
3331 /// be staging. It used to truncate and rewrite `info/exclude` each time,
3332 /// so the peer's `git add -A` could read an empty exclude list.
3333 #[test]
3334 fn opening_leaves_a_current_exclude_file_untouched() {
3335 let tmp = tempdir().unwrap();
3336 let (repo, _home) = make_repo(tmp.path());
3337 let exclude = repo.git_dir().join("info").join("exclude");
3338 let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
3339 File::options()
3340 .write(true)
3341 .open(&exclude)
3342 .unwrap()
3343 .set_times(FileTimes::new().set_modified(old))
3344 .unwrap();
3345
3346 SnapshotRepo::open_or_init(repo.work_tree()).expect("reopen");
3347 assert_eq!(
3348 std::fs::metadata(&exclude).unwrap().modified().unwrap(),
3349 old,
3350 "a current exclude file is not rewritten"
3351 );
3352
3353 std::fs::write(&exclude, b"stale\n").unwrap();
3354 SnapshotRepo::open_or_init(repo.work_tree()).expect("reopen");
3355 assert_eq!(
3356 std::fs::read_to_string(&exclude).unwrap(),
3357 BUILTIN_EXCLUDES,
3358 "a stale exclude file is replaced"
3359 );
3360 }
3361
3362 /// HEAD moves only from the value the writer read. A writer that does not
3363 /// take the lock (an older build) must not be orphaned by a later move.
3364 #[test]
3365 fn head_moves_only_from_the_expected_commit() {
3366 let tmp = tempdir().unwrap();
3367 let (repo, _home) = make_repo(tmp.path());
3368 std::fs::write(repo.work_tree().join("f.txt"), b"v1").unwrap();
3369 let first = repo.snapshot("pre-turn:1").expect("snapshot 1");
3370 std::fs::write(repo.work_tree().join("f.txt"), b"v2").unwrap();
3371 let second = repo.snapshot("post-turn:1").expect("snapshot 2");
3372
3373 repo.move_head(Some(first.as_str()), Some(first.as_str()))
3374 .expect_err("HEAD no longer names the expected commit");
3375 repo.move_head(Some(first.as_str()), None)
3376 .expect_err("HEAD exists, so an unborn expectation fails");
3377 repo.move_head(None, Some(first.as_str()))
3378 .expect_err("deleting HEAD also checks the expected commit");
3379 assert_eq!(repo.list(1).unwrap()[0].id, second, "HEAD is unchanged");
3380
3381 repo.move_head(Some(first.as_str()), Some(second.as_str()))
3382 .expect("the expected commit moves");
3383 assert_eq!(repo.list(1).unwrap()[0].id, first);
3384 }
3385
3386 /// HEAD repair looks up a missing commit, then moves HEAD off it. A peer
3387 /// that published a snapshot in between used to be overwritten by the
3388 /// reflog reset or deleted by the fresh-history fallback; both moves now
3389 /// require HEAD to still name the missing commit.
3390 #[test]
3391 fn head_repair_leaves_a_peers_new_snapshot_alone() {
3392 let tmp = tempdir().unwrap();
3393 let (repo, _home) = make_repo(tmp.path());
3394 std::fs::write(repo.work_tree().join("f.txt"), b"v1").unwrap();
3395 repo.snapshot("pre-turn:1").expect("snapshot 1");
3396 std::fs::write(repo.work_tree().join("f.txt"), b"v2").unwrap();
3397 let peer = repo.snapshot("post-turn:peer").expect("peer snapshot");
3398 let missing = "1111111111111111111111111111111111111111";
3399
3400 repo.reset_missing_head(missing)
3401 .expect_err("the reflog reset checks HEAD still names the missing commit");
3402 assert_eq!(repo.list(1).unwrap()[0].id, peer, "HEAD is unchanged");
3403
3404 std::fs::remove_dir_all(repo.git_dir().join("logs")).unwrap();
3405 repo.reset_missing_head(missing)
3406 .expect_err("the fresh-history delete checks it too");
3407 assert_eq!(
3408 repo.list(1).unwrap()[0].id,
3409 peer,
3410 "the peer's snapshot stays"
3411 );
3412 }
3413
3414 /// A prune rebuilds the survivors it listed. If another writer committed
3415 /// after that listing, the rebuild used to overwrite HEAD and orphan the
3416 /// new snapshot for gc; now it fails and the snapshot stays.
3417 #[test]
3418 fn survivor_rebuild_refuses_when_another_writer_moved_head() {
3419 let tmp = tempdir().unwrap();
3420 let (repo, _home) = make_repo(tmp.path());
3421 for i in 0..3 {
3422 std::fs::write(repo.work_tree().join("f.txt"), format!("v{i}")).unwrap();
3423 repo.snapshot(&format!("tool:{i}")).expect("snapshot");
3424 }
3425 let listed = repo.list(usize::MAX).unwrap();
3426 std::fs::write(repo.work_tree().join("f.txt"), b"peer").unwrap();
3427 let peer = repo.snapshot("post-turn:peer").expect("peer snapshot");
3428
3429 repo.rebuild_survivor_chain(&listed[..1], &listed[0].id)
3430 .expect_err("HEAD moved since the listing");
3431 let history = repo.list(usize::MAX).unwrap();
3432 assert_eq!(history.len(), 4, "nothing was dropped");
3433 assert_eq!(history[0].id, peer, "the peer's snapshot is still HEAD");
3434 }
3435
3436 /// An index naming objects that no longer exist (an interrupted or racing
3437 /// gc) failed every later `write-tree`, because `add -A` does not rehash
3438 /// files whose stat data is unchanged. The index is rebuilt once instead.
3439 #[test]
3440 fn snapshot_rebuilds_an_index_naming_missing_objects() {
3441 let tmp = tempdir().unwrap();
3442 let (repo, _home) = make_repo(tmp.path());
3443 let file = repo.work_tree().join("f.txt");
3444 std::fs::write(&file, b"content").unwrap();
3445 // An mtime well before the index keeps git from treating the entry as
3446 // racily clean and rehashing it, which would hide the broken index.
3447 File::options()
3448 .write(true)
3449 .open(&file)
3450 .unwrap()
3451 .set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(3600)))
3452 .unwrap();
3453 let taken = repo
3454 .take_snapshot("pre-turn:1", None)
3455 .expect("first snapshot");
3456 let blob = git_output(&repo, &["rev-parse", "HEAD:f.txt"]);
3457 for oid in [blob.as_str(), taken.tree.as_str()] {
3458 let object = repo
3459 .git_dir()
3460 .join("objects")
3461 .join(&oid[..2])
3462 .join(&oid[2..]);
3463 std::fs::remove_file(&object).expect("loose object removed");
3464 }
3465
3466 let again = repo
3467 .take_snapshot("post-turn:1", None)
3468 .expect("the snapshot rebuilds the index and succeeds");
3469 assert_eq!(
3470 git_output(
3471 &repo,
3472 &["cat-file", "-p", &format!("{}:f.txt", again.id.as_str())]
3473 ),
3474 "content"
3475 );
3476 }
3477
3478 fn git_output(repo: &SnapshotRepo, args: &[&str]) -> String {
3479 let out = run_git(repo.git_dir(), repo.work_tree(), args).unwrap();
3480 assert!(
3481 out.status.success(),
3482 "git {args:?}: {}",
3483 String::from_utf8_lossy(&out.stderr)
3484 );
3485 String::from_utf8_lossy(&out.stdout).trim().to_string()
3486 }
3487
3488 #[test]
3489 fn restore_path_plan_rolls_back_partial_file_changes() {
3490 let tmp = tempdir().unwrap();
3491 let (repo, _home) = make_repo(tmp.path());
3492 let work = repo.work_tree();
3493 let modified = work.join("modified.txt");
3494 let recreated = work.join("recreated.txt");
3495 let removed = work.join("new/removed.txt");
3496 let blocked = work.join("blocked.txt");
3497 let unrelated = work.join("unrelated.txt");
3498 std::fs::write(&modified, b"before turn").unwrap();
3499 std::fs::write(&recreated, b"before deletion").unwrap();
3500 std::fs::write(&unrelated, b"before edit").unwrap();
3501 let target = repo.snapshot("pre-turn:1").unwrap();
3502
3503 std::fs::write(&modified, b"after turn").unwrap();
3504 std::fs::remove_file(&recreated).unwrap();
3505 std::fs::create_dir(removed.parent().unwrap()).unwrap();
3506 std::fs::write(&removed, b"new file").unwrap();
3507 std::fs::write(&blocked, b"file to remove").unwrap();
3508 let plan = [
3509 "modified.txt",
3510 "recreated.txt",
3511 "new/removed.txt",
3512 "blocked.txt",
3513 ]
3514 .map(|rel| (PathBuf::from(rel), target.clone()));
3515 let error = repo
3516 .restore_path_plan(&plan, "pre-restore:rollback-test", true, || {
3517 std::fs::write(&unrelated, b"new editor work")?;
3518 std::fs::remove_file(&blocked)?;
3519 std::fs::create_dir(&blocked)?;
3520 std::fs::write(blocked.join("keep.txt"), b"new work in directory")
3521 })
3522 .expect_err("the final removal must fail");
3523
3524 assert_eq!(std::fs::read(&modified).unwrap(), b"after turn");
3525 assert!(!recreated.exists());
3526 assert_eq!(std::fs::read(&removed).unwrap(), b"new file");
3527 assert_eq!(std::fs::read(&unrelated).unwrap(), b"new editor work");
3528 assert_eq!(
3529 std::fs::read(blocked.join("keep.txt")).unwrap(),
3530 b"new work in directory"
3531 );
3532 let message = error.to_string();
3533 assert!(message.contains("blocked.txt"), "{message}");
3534 assert!(
3535 message.contains("applied file changes were rolled back"),
3536 "{message}"
3537 );
3538 let backup = repo.list(1).unwrap().pop().unwrap();
3539 assert_eq!(backup.label, "pre-restore:rollback-test");
3540 assert!(message.contains(backup.id.as_str()), "{message}");
3541
3542 std::fs::write(&recreated, b"replacement file").unwrap();
3543 let blob = repo
3544 .snapshot_file_blob(&target, Path::new("recreated.txt"))
3545 .unwrap()
3546 .unwrap();
3547 std::fs::remove_file(
3548 repo.git_dir()
3549 .join("objects")
3550 .join(&blob[..2])
3551 .join(&blob[2..]),
3552 )
3553 .unwrap();
3554 let error = repo
3555 .restore_path_plan(&plan[..2], "pre-restore:checkout-test", true, || Ok(()))
3556 .expect_err("checkout of the missing target blob must fail");
3557 let message = error.to_string();
3558 assert!(message.contains("git checkout failed"), "{message}");
3559 assert!(
3560 message.contains("applied file changes were rolled back"),
3561 "{message}"
3562 );
3563 assert_eq!(std::fs::read(&modified).unwrap(), b"after turn");
3564 assert_eq!(std::fs::read(&recreated).unwrap(), b"replacement file");
3565 }
3566
3567 #[test]
3568 fn restore_paths_leaves_unrelated_files_alone() {
3569 let tmp = tempdir().unwrap();
3570 let (repo, _home) = make_repo(tmp.path());
3571 let wanted = repo.work_tree().join("wanted.txt");
3572 let unrelated = repo.work_tree().join("unrelated.txt");
3573
3574 std::fs::write(&wanted, b"original").unwrap();
3575 std::fs::write(&unrelated, b"original").unwrap();
3576 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3577
3578 std::fs::write(&wanted, b"clobbered").unwrap();
3579 std::fs::write(&unrelated, b"also clobbered").unwrap();
3580 repo.snapshot("post-turn:1").expect("snapshot 2");
3581
3582 let outcomes = repo
3583 .restore_paths(&id, &[PathBuf::from("wanted.txt")])
3584 .expect("scoped restore");
3585
3586 assert_eq!(std::fs::read_to_string(&wanted).unwrap(), "original");
3587 assert_eq!(
3588 std::fs::read_to_string(&unrelated).unwrap(),
3589 "also clobbered",
3590 "a file-scoped restore must not touch a path it was not given"
3591 );
3592 assert_eq!(outcomes.len(), 1);
3593 assert_eq!(outcomes[0].path, PathBuf::from("wanted.txt"));
3594 assert_eq!(outcomes[0].action, PathRestoreAction::Modified);
3595 }
3596
3597 #[test]
3598 fn only_restore_paths_is_safe_for_a_single_file_action() {
3599 // Characterizes the difference the per-file Revert control depends on.
3600 // `restore()` is what the TUI's `patch_undo()` and the runtime's
3601 // `patch-undo` endpoint both call. It is scoped in *snapshot selection*
3602 // (it picks a recent `tool:` snapshot) but not in *effect*: it checks
3603 // out the whole tree, so it also rolls back a working-tree path that no
3604 // tool touched. That is the data loss #2 removed the control over, and
3605 // it is why a per-file action cannot be built on top of it.
3606 let tmp = tempdir().unwrap();
3607 let (repo, _home) = make_repo(tmp.path());
3608 let touched = repo.work_tree().join("touched.txt");
3609 let unrelated = repo.work_tree().join("unrelated.txt");
3610
3611 std::fs::write(&touched, b"v1").unwrap();
3612 std::fs::write(&unrelated, b"snapshot-time").unwrap();
3613 let id = repo.snapshot("tool:call-1").expect("snapshot");
3614
3615 // The tool edits one file; something else — the user, another editor —
3616 // changes the other one after the snapshot was taken.
3617 std::fs::write(&touched, b"v2").unwrap();
3618 std::fs::write(&unrelated, b"user-work-in-progress").unwrap();
3619
3620 repo.restore(&id).expect("whole-tree restore");
3621 assert_eq!(std::fs::read_to_string(&touched).unwrap(), "v1");
3622 assert_eq!(
3623 std::fs::read_to_string(&unrelated).unwrap(),
3624 "snapshot-time",
3625 "whole-tree restore rolls back a file no tool touched"
3626 );
3627
3628 // Same situation again, but through the file-scoped path the
3629 // `file-revert` endpoint uses.
3630 std::fs::write(&touched, b"v1").unwrap();
3631 std::fs::write(&unrelated, b"snapshot-time").unwrap();
3632 let id2 = repo.snapshot("tool:call-2").expect("snapshot 2");
3633 std::fs::write(&touched, b"v2").unwrap();
3634 std::fs::write(&unrelated, b"user-work-in-progress").unwrap();
3635
3636 repo.restore_paths(&id2, &[PathBuf::from("touched.txt")])
3637 .expect("scoped restore");
3638 assert_eq!(std::fs::read_to_string(&touched).unwrap(), "v1");
3639 assert_eq!(
3640 std::fs::read_to_string(&unrelated).unwrap(),
3641 "user-work-in-progress",
3642 "the scoped restore must leave the unrelated edit alone"
3643 );
3644 }
3645
3646 #[test]
3647 fn restore_paths_removes_a_file_created_after_the_snapshot() {
3648 let tmp = tempdir().unwrap();
3649 let (repo, _home) = make_repo(tmp.path());
3650 let kept = repo.work_tree().join("kept.txt");
3651 let created = repo.work_tree().join("created.txt");
3652
3653 std::fs::write(&kept, b"kept").unwrap();
3654 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3655
3656 std::fs::write(&created, b"new file").unwrap();
3657 repo.snapshot("post-turn:1").expect("snapshot 2");
3658
3659 let outcomes = repo
3660 .restore_paths(&id, &[PathBuf::from("created.txt")])
3661 .expect("scoped restore");
3662
3663 assert!(
3664 !created.exists(),
3665 "a created file must be removed by revert"
3666 );
3667 assert!(kept.exists(), "the untouched file must survive");
3668 assert_eq!(outcomes[0].action, PathRestoreAction::Removed);
3669 }
3670
3671 #[test]
3672 fn restore_paths_recreates_a_file_deleted_after_the_snapshot() {
3673 let tmp = tempdir().unwrap();
3674 let (repo, _home) = make_repo(tmp.path());
3675 let deleted = repo.work_tree().join("deleted.txt");
3676
3677 std::fs::write(&deleted, b"content").unwrap();
3678 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3679
3680 std::fs::remove_file(&deleted).unwrap();
3681 repo.snapshot("post-turn:1").expect("snapshot 2");
3682
3683 let outcomes = repo
3684 .restore_paths(&id, &[PathBuf::from("deleted.txt")])
3685 .expect("scoped restore");
3686
3687 assert_eq!(std::fs::read_to_string(&deleted).unwrap(), "content");
3688 assert_eq!(outcomes[0].action, PathRestoreAction::Recreated);
3689 }
3690
3691 #[test]
3692 fn restore_paths_rejects_parent_traversal() {
3693 let tmp = tempdir().unwrap();
3694 let (repo, _home) = make_repo(tmp.path());
3695 std::fs::write(repo.work_tree().join("a.txt"), b"a").unwrap();
3696 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3697
3698 let err = repo
3699 .restore_paths(&id, &[PathBuf::from("../escape.txt")])
3700 .expect_err("traversal must be refused");
3701 assert!(err.to_string().contains("unsafe path"), "got: {err}");
3702 }
3703
3704 #[test]
3705 fn path_differs_from_snapshot_is_scoped_to_the_named_path() {
3706 let tmp = tempdir().unwrap();
3707 let (repo, _home) = make_repo(tmp.path());
3708 let touched = repo.work_tree().join("touched.txt");
3709 let untouched = repo.work_tree().join("untouched.txt");
3710
3711 std::fs::write(&touched, b"v1").unwrap();
3712 std::fs::write(&untouched, b"v1").unwrap();
3713 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3714
3715 std::fs::write(&touched, b"v2").unwrap();
3716
3717 assert!(
3718 repo.path_differs_from_snapshot(&id, Path::new("touched.txt"))
3719 .expect("differs")
3720 );
3721 assert!(
3722 !repo
3723 .path_differs_from_snapshot(&id, Path::new("untouched.txt"))
3724 .expect("differs")
3725 );
3726 }
3727
3728 #[test]
3729 fn workspace_relative_path_accepts_inside_paths_and_refuses_outside_ones() {
3730 // A real absolute temp path so the fixture is absolute on Windows too
3731 // (`/tmp/ws` is a relative path with a root-dir component there).
3732 let temp = std::env::temp_dir();
3733 let workspace = temp.join("ws");
3734 let other = temp.join("other");
3735
3736 assert_eq!(
3737 workspace_relative_path(&workspace, "src/lib.rs"),
3738 Some(PathBuf::from("src/lib.rs"))
3739 );
3740 let inside = workspace.join("src").join("lib.rs");
3741 assert_eq!(
3742 workspace_relative_path(&workspace, &inside.to_string_lossy()),
3743 Some(PathBuf::from("src").join("lib.rs"))
3744 );
3745 let outside = other.join("lib.rs");
3746 assert_eq!(
3747 workspace_relative_path(&workspace, &outside.to_string_lossy()),
3748 None
3749 );
3750 assert_eq!(workspace_relative_path(&workspace, "../escape"), None);
3751 assert_eq!(
3752 workspace_relative_path(&workspace, "src/../../escape"),
3753 None
3754 );
3755 assert_eq!(workspace_relative_path(&workspace, ""), None);
3756 // Whitespace and glob characters are literal filename bytes.
3757 assert_eq!(
3758 workspace_relative_path(&workspace, " padded.txt "),
3759 Some(PathBuf::from(" padded.txt "))
3760 );
3761 assert_eq!(
3762 workspace_relative_path(&workspace, "file[12].txt"),
3763 Some(PathBuf::from("file[12].txt"))
3764 );
3765 }
3766
3767 fn sha256_hash(path: &Path) -> String {
3768 format!(
3769 "sha256:{}",
3770 codewhale_runtime::hashing::sha256_hex(std::fs::read(path).unwrap())
3771 )
3772 }
3773
3774 /// The Git primitive treats `[12]` as a pattern even after `--`; the
3775 /// file-scoped restore must not. `file[12].txt` and `file1.txt` both exist
3776 /// in the snapshot, so only literal pathspecs keep the second one intact.
3777 #[test]
3778 fn restore_file_if_unchanged_treats_glob_characters_literally() {
3779 let tmp = tempdir().unwrap();
3780 let (repo, _home) = make_repo(tmp.path());
3781 let literal = repo.work_tree().join("file[12].txt");
3782 let sibling = repo.work_tree().join("file1.txt");
3783 std::fs::write(&literal, b"literal-before").unwrap();
3784 std::fs::write(&sibling, b"sibling-before").unwrap();
3785 let id = repo.snapshot("tool:call-1").expect("snapshot");
3786 std::fs::write(&literal, b"literal-after").unwrap();
3787 std::fs::write(&sibling, b"sibling-after").unwrap();
3788
3789 assert!(
3790 repo.path_differs_from_snapshot(&id, Path::new("file[12].txt"))
3791 .unwrap()
3792 );
3793 let outcomes = repo
3794 .restore_file_if_unchanged(&id, Path::new("file[12].txt"), &sha256_hash(&literal))
3795 .expect("literal restore");
3796 assert_eq!(outcomes.len(), 1);
3797 assert_eq!(outcomes[0].action, PathRestoreAction::Modified);
3798 assert_eq!(std::fs::read_to_string(&literal).unwrap(), "literal-before");
3799 assert_eq!(
3800 std::fs::read_to_string(&sibling).unwrap(),
3801 "sibling-after",
3802 "a bracketed filename must never restore its glob siblings"
3803 );
3804 }
3805
3806 #[test]
3807 fn restore_file_if_unchanged_refuses_when_the_reviewed_bytes_changed() {
3808 let tmp = tempdir().unwrap();
3809 let (repo, _home) = make_repo(tmp.path());
3810 let file = repo.work_tree().join("a.txt");
3811 std::fs::write(&file, b"v1").unwrap();
3812 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3813 std::fs::write(&file, b"v2").unwrap();
3814 let reviewed = sha256_hash(&file);
3815 // The user edits again after the client captured its change record.
3816 std::fs::write(&file, b"v3-user-edit").unwrap();
3817
3818 let err = repo
3819 .restore_file_if_unchanged(&id, Path::new("a.txt"), &reviewed)
3820 .expect_err("stale hash must refuse");
3821 assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
3822 assert_eq!(std::fs::read_to_string(&file).unwrap(), "v3-user-edit");
3823 // `absent` is only valid for a file the client saw as deleted.
3824 let err = repo
3825 .restore_file_if_unchanged(&id, Path::new("a.txt"), "absent")
3826 .expect_err("absent must not match an existing file");
3827 assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
3828 // The exact current bytes restore.
3829 let outcomes = repo
3830 .restore_file_if_unchanged(&id, Path::new("a.txt"), &sha256_hash(&file))
3831 .expect("current hash restores");
3832 assert_eq!(outcomes[0].action, PathRestoreAction::Modified);
3833 assert_eq!(std::fs::read_to_string(&file).unwrap(), "v1");
3834 }
3835
3836 #[test]
3837 fn restore_file_if_unchanged_handles_deleted_and_created_files() {
3838 let tmp = tempdir().unwrap();
3839 let (repo, _home) = make_repo(tmp.path());
3840 let deleted = repo.work_tree().join("deleted.txt");
3841 std::fs::write(&deleted, b"content").unwrap();
3842 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3843 std::fs::remove_file(&deleted).unwrap();
3844 let created = repo.work_tree().join("created.txt");
3845 std::fs::write(&created, b"new").unwrap();
3846
3847 let outcomes = repo
3848 .restore_file_if_unchanged(&id, Path::new("deleted.txt"), "absent")
3849 .expect("recreate");
3850 assert_eq!(outcomes[0].action, PathRestoreAction::Recreated);
3851 assert_eq!(std::fs::read_to_string(&deleted).unwrap(), "content");
3852
3853 let outcomes = repo
3854 .restore_file_if_unchanged(&id, Path::new("created.txt"), &sha256_hash(&created))
3855 .expect("remove");
3856 assert_eq!(outcomes[0].action, PathRestoreAction::Removed);
3857 assert!(!created.exists());
3858 // A created file inside a new directory is removed alone; the
3859 // directory the user made stays.
3860 let nested_dir = repo.work_tree().join("newdir");
3861 std::fs::create_dir_all(&nested_dir).unwrap();
3862 let nested = nested_dir.join("only.txt");
3863 std::fs::write(&nested, b"n").unwrap();
3864 let outcomes = repo
3865 .restore_file_if_unchanged(&id, Path::new("newdir/only.txt"), &sha256_hash(&nested))
3866 .expect("remove nested");
3867 assert_eq!(outcomes[0].action, PathRestoreAction::Removed);
3868 assert!(!nested.exists());
3869 assert!(nested_dir.is_dir(), "the parent directory is not pruned");
3870 // A path missing on both sides is not a change and reports nothing.
3871 assert!(
3872 !repo
3873 .path_differs_from_snapshot(&id, Path::new("never.txt"))
3874 .unwrap()
3875 );
3876 }
3877
3878 #[test]
3879 fn restore_file_if_unchanged_refuses_directories_git_metadata_and_ignored_files() {
3880 let tmp = tempdir().unwrap();
3881 let (repo, _home) = make_repo(tmp.path());
3882 let dir = repo.work_tree().join("src");
3883 std::fs::create_dir_all(&dir).unwrap();
3884 std::fs::write(dir.join("lib.rs"), b"fn a() {}").unwrap();
3885 std::fs::write(
3886 repo.work_tree().join(".gitignore"),
3887 "ignored.txt
3888 ",
3889 )
3890 .unwrap();
3891 std::fs::write(repo.work_tree().join("ignored.txt"), b"secret").unwrap();
3892 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3893 std::fs::write(dir.join("lib.rs"), b"fn b() {}").unwrap();
3894
3895 let mut refused = vec!["src", ".git/config", "src/.GIT/x", ".git"];
3896 if cfg!(windows) {
3897 refused.extend([".git./config", ".git /config", "GIT~1/config"]);
3898 }
3899 for rel in refused {
3900 let err = repo.validate_restore_file(Path::new(rel)).expect_err(rel);
3901 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{rel}");
3902 }
3903 let err = repo
3904 .restore_file_if_unchanged(&id, Path::new("src"), "absent")
3905 .expect_err("directories are refused");
3906 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
3907 assert_eq!(
3908 std::fs::read_to_string(dir.join("lib.rs")).unwrap(),
3909 "fn b() {}"
3910 );
3911
3912 // A gitignored file is excluded from the safety backup, so removing
3913 // it would be unrecoverable: refuse and leave it in place.
3914 let ignored = repo.work_tree().join("ignored.txt");
3915 let err = repo
3916 .restore_file_if_unchanged(&id, Path::new("ignored.txt"), &sha256_hash(&ignored))
3917 .expect_err("ignored files are refused");
3918 assert!(err.to_string().contains("safety snapshot"), "got: {err}");
3919 assert_eq!(std::fs::read_to_string(&ignored).unwrap(), "secret");
3920 }
3921
3922 #[cfg(unix)]
3923 #[test]
3924 fn restore_file_if_unchanged_refuses_symlinks_anywhere_in_the_path() {
3925 let tmp = tempdir().unwrap();
3926 let (repo, _home) = make_repo(tmp.path());
3927 let outside = tmp.path().join("outside");
3928 std::fs::create_dir_all(&outside).unwrap();
3929 std::fs::write(outside.join("target.txt"), b"outside").unwrap();
3930 std::fs::write(repo.work_tree().join("real.txt"), b"real").unwrap();
3931 std::os::unix::fs::symlink(&outside, repo.work_tree().join("linkdir")).unwrap();
3932 std::os::unix::fs::symlink(
3933 outside.join("target.txt"),
3934 repo.work_tree().join("link.txt"),
3935 )
3936 .unwrap();
3937 let id = repo.snapshot("pre-turn:1").expect("snapshot");
3938
3939 for rel in ["link.txt", "linkdir/target.txt"] {
3940 let err = repo
3941 .restore_file_if_unchanged(&id, Path::new(rel), "absent")
3942 .expect_err(rel);
3943 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{rel}");
3944 }
3945 assert_eq!(
3946 std::fs::read_to_string(outside.join("target.txt")).unwrap(),
3947 "outside"
3948 );
3949 // The snapshot side is checked too: a symlink entry in the tree is
3950 // not a regular file even when the work tree copy is gone.
3951 std::fs::remove_file(repo.work_tree().join("link.txt")).unwrap();
3952 let err = repo
3953 .restore_file_if_unchanged(&id, Path::new("link.txt"), "absent")
3954 .expect_err("snapshot symlink entry");
3955 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
3956 assert!(!repo.work_tree().join("link.txt").exists());
3957 }
3958
3959 #[test]
3960 fn list_distinguishes_an_unborn_head_from_broken_history() {
3961 let tmp = tempdir().unwrap();
3962 let (repo, _home) = make_repo(tmp.path());
3963 assert!(repo.list(10).expect("unborn HEAD lists nothing").is_empty());
3964
3965 std::fs::write(repo.work_tree().join("a.txt"), b"a").unwrap();
3966 repo.snapshot("pre-turn:1").expect("snapshot");
3967 assert_eq!(repo.list(10).unwrap().len(), 1);
3968
3969 // Point the branch at an object that does not exist: the history is
3970 // now broken, which must surface as an error rather than "no
3971 // snapshots" (an empty list would let patch-undo drop a turn).
3972 let head = String::from_utf8(
3973 run_git(repo.git_dir(), repo.work_tree(), &["symbolic-ref", "HEAD"])
3974 .unwrap()
3975 .stdout,
3976 )
3977 .unwrap();
3978 std::fs::write(
3979 repo.git_dir().join(head.trim()),
3980 "0123456789abcdef0123456789abcdef01234567\n",
3981 )
3982 .unwrap();
3983 let err = repo.list(10).expect_err("broken history must error");
3984 assert!(err.to_string().contains("git log failed"), "got: {err}");
3985 }
3986
3987 #[test]
3988 fn restore_takes_a_pre_restore_safety_snapshot_that_round_trips() {
3989 let tmp = tempdir().unwrap();
3990 let (repo, _home) = make_repo(tmp.path());
3991 let f = repo.work_tree().join("file.txt");
3992
3993 std::fs::write(&f, b"v1").unwrap();
3994 let id1 = repo.snapshot("pre-turn:1").expect("snapshot v1");
3995
3996 std::fs::write(&f, b"v2").unwrap();
3997 repo.snapshot("post-turn:1").expect("snapshot v2");
3998
3999 repo.restore(&id1).expect("restore to v1");
4000 assert_eq!(std::fs::read_to_string(&f).unwrap(), "v1");
4001
4002 // The restore must have captured the pre-restore state (v2) under a
4003 // `pre-restore:` label naming its target, so the destructive op is
4004 // itself reversible (2026-08-04 snapshot hunt).
4005 let snapshots = repo.list(usize::MAX).expect("list");
4006 let safety = snapshots
4007 .iter()
4008 .find(|s| s.label.starts_with("pre-restore:"))
4009 .expect("a pre-restore safety snapshot must exist");
4010 assert!(
4011 safety.label.ends_with(&id1.as_str()[..12]),
4012 "safety label should name the restore target: {}",
4013 safety.label
4014 );
4015
4016 repo.restore(&safety.id)
4017 .expect("restore the safety snapshot");
4018 assert_eq!(
4019 std::fs::read_to_string(&f).unwrap(),
4020 "v2",
4021 "the safety snapshot must bring back the pre-restore state"
4022 );
4023 }
4024
4025 #[test]
4026 fn snapshot_and_restore_do_not_move_user_git_head() {
4027 let tmp = tempdir().unwrap();
4028 let workspace = tmp.path().join("workspace");
4029 std::fs::create_dir_all(&workspace).unwrap();
4030 codewhale_dependencies::Git::command()
4031 .expect("git not found")
4032 .arg("-C")
4033 .arg(&workspace)
4034 .arg("init")
4035 .arg("--quiet")
4036 .status()
4037 .unwrap();
4038 std::fs::write(workspace.join("tracked.txt"), b"committed").unwrap();
4039 codewhale_dependencies::Git::command()
4040 .expect("git not found")
4041 .arg("-C")
4042 .arg(&workspace)
4043 .arg("add")
4044 .arg("tracked.txt")
4045 .status()
4046 .unwrap();
4047 codewhale_dependencies::Git::command()
4048 .expect("git not found")
4049 .arg("-C")
4050 .arg(&workspace)
4051 .arg("-c")
4052 .arg("user.name=user")
4053 .arg("-c")
4054 .arg("user.email=user@example.test")
4055 .arg("commit")
4056 .arg("--quiet")
4057 .arg("-m")
4058 .arg("init")
4059 .status()
4060 .unwrap();
4061 let user_head_before = codewhale_dependencies::Git::command()
4062 .expect("git not found")
4063 .arg("-C")
4064 .arg(&workspace)
4065 .args(["rev-parse", "HEAD"])
4066 .output()
4067 .unwrap()
4068 .stdout;
4069
4070 let _home = scoped_home(tmp.path());
4071 let repo = SnapshotRepo::open_or_init(&workspace).unwrap();
4072 std::fs::write(workspace.join("tracked.txt"), b"dirty-before").unwrap();
4073 let id = repo.snapshot("pre-turn:1").unwrap();
4074 std::fs::write(workspace.join("tracked.txt"), b"dirty-after").unwrap();
4075 repo.snapshot("post-turn:1").unwrap();
4076 repo.restore(&id).unwrap();
4077
4078 let user_head_after = codewhale_dependencies::Git::command()
4079 .expect("git not found")
4080 .arg("-C")
4081 .arg(&workspace)
4082 .args(["rev-parse", "HEAD"])
4083 .output()
4084 .unwrap()
4085 .stdout;
4086 assert_eq!(user_head_after, user_head_before);
4087 assert_eq!(
4088 std::fs::read_to_string(workspace.join("tracked.txt")).unwrap(),
4089 "dirty-before"
4090 );
4091 }
4092
4093 #[test]
4094 fn list_respects_limit() {
4095 let tmp = tempdir().unwrap();
4096 let (repo, _home) = make_repo(tmp.path());
4097 for i in 0..5 {
4098 std::fs::write(repo.work_tree().join("f.txt"), format!("v{i}")).unwrap();
4099 repo.snapshot(&format!("turn:{i}")).unwrap();
4100 }
4101 let three = repo.list(3).unwrap();
4102 assert_eq!(three.len(), 3);
4103 // Newest first.
4104 assert_eq!(three[0].label, "turn:4");
4105 }
4106
4107 #[test]
4108 fn prune_drops_snapshots_older_than_threshold() {
4109 let tmp = tempdir().unwrap();
4110 let (repo, _home) = make_repo(tmp.path());
4111 std::fs::write(repo.work_tree().join("f.txt"), "v0").unwrap();
4112 repo.snapshot("turn:0").unwrap();
4113
4114 // Wait one second so the snapshot's commit timestamp is strictly
4115 // in the past relative to the prune call's "now" — otherwise
4116 // same-second comparisons make the assertion flaky.
4117 std::thread::sleep(Duration::from_millis(1100));
4118
4119 let removed = repo.prune_older_than(Duration::from_secs(0)).unwrap();
4120 assert!(removed >= 1, "expected at least 1 pruned, got {removed}");
4121
4122 // After pruning everything, the next snapshot should start a
4123 // fresh history.
4124 std::fs::write(repo.work_tree().join("f.txt"), "v1").unwrap();
4125 repo.snapshot("turn:1").unwrap();
4126 let list = repo.list(10).unwrap();
4127 assert_eq!(list.len(), 1);
4128 assert_eq!(list[0].label, "turn:1");
4129 }
4130
4131 #[test]
4132 fn prune_with_an_age_beyond_i64_keeps_every_snapshot() {
4133 let tmp = tempdir().unwrap();
4134 let (repo, _home) = make_repo(tmp.path());
4135 std::fs::write(repo.work_tree().join("f.txt"), "v0").unwrap();
4136 repo.snapshot("turn:0").unwrap();
4137 std::thread::sleep(Duration::from_millis(1100));
4138
4139 let removed = repo
4140 .prune_older_than(Duration::from_secs(u64::MAX))
4141 .unwrap();
4142
4143 assert_eq!(removed, 0);
4144 assert_eq!(repo.list(10).unwrap().len(), 1);
4145 }
4146
4147 /// The 2026-08-04 regression: with a cut in the MIDDLE of history,
4148 /// `prune_older_than` used to `update-ref HEAD <oldest survivor>`, which
4149 /// orphaned (and gc destroyed) the NEWEST snapshots while keeping the
4150 /// old ones as ancestors — the inverse of the intent, firing on every
4151 /// boot. This pins the correct partial-cut behavior.
4152 #[test]
4153 fn prune_older_than_keeps_the_newest_and_drops_only_the_old_tail() {
4154 let tmp = tempdir().unwrap();
4155 let (repo, _home) = make_repo(tmp.path());
4156
4157 // Two "old" snapshots, then a pause, then two "new" ones.
4158 for i in 0..2 {
4159 std::fs::write(repo.work_tree().join("f.txt"), format!("old{i}")).unwrap();
4160 repo.snapshot(&format!("old:{i}")).unwrap();
4161 std::thread::sleep(Duration::from_millis(1100));
4162 }
4163 // A wide gap so git's whole-second commit timestamps land the cut
4164 // unambiguously between the old and new pairs. The margins are
4165 // deliberately generous: this test runs under full-suite parallelism
4166 // where a sleep can overrun, and the cut is wall-clock. At prune time
4167 // the newest pair is ~0-1.2s old against a 6s cutoff, and the old
4168 // pair is ~9s old — ~5s of slack in both directions.
4169 std::thread::sleep(Duration::from_secs(8));
4170 for i in 0..2 {
4171 std::fs::write(repo.work_tree().join("f.txt"), format!("new{i}")).unwrap();
4172 repo.snapshot(&format!("new:{i}")).unwrap();
4173 if i == 0 {
4174 std::thread::sleep(Duration::from_millis(1100));
4175 }
4176 }
4177 let before = repo.list(usize::MAX).unwrap();
4178 assert_eq!(before.len(), 4);
4179 // Derive the cut from the timestamps actually recorded rather than a
4180 // fixed 6s. A fixed cut assumes `repo.snapshot()` is fast: `new:0` is
4181 // only ~1.2s plus one git subprocess older than prune time, so on a
4182 // loaded Windows runner that subprocess alone pushed it past 6s and
4183 // three snapshots were pruned instead of two. (The old fixture guard
4184 // could not catch it either — it checked `before[0]` and `before[2]`,
4185 // and `before[1]` is the entry that drifts.)
4186 let now = std::time::SystemTime::now()
4187 .duration_since(std::time::UNIX_EPOCH)
4188 .unwrap()
4189 .as_secs() as i64;
4190 // Newest-first: [new:1, new:0, old:1, old:0]. The cut must land
4191 // strictly between the pairs, so aim at the midpoint of the 8s gap —
4192 // that leaves ~4s of slack against clock drift and a slow runner in
4193 // both directions.
4194 let survivor = before[1].timestamp;
4195 let victim = before[2].timestamp;
4196 assert!(
4197 survivor - victim >= 8,
4198 "fixture needs an 8s gap between the pairs (survivor {survivor}, victim {victim})"
4199 );
4200 let midpoint = victim + (survivor - victim) / 2;
4201 assert!(
4202 now > midpoint,
4203 "fixture cutoff is not before the current time"
4204 );
4205 let max_age = Duration::from_secs((now - midpoint) as u64);
4206
4207 // The two old snapshots drop, the two new ones survive.
4208 let removed = repo.prune_older_than(max_age).unwrap();
4209 assert_eq!(removed, 2, "only the old tail should be removed");
4210
4211 let remaining = repo.list(usize::MAX).unwrap();
4212 assert_eq!(remaining.len(), 2, "the two newest must survive");
4213 assert_eq!(
4214 remaining[0].label, "new:1",
4215 "newest survives (was destroyed before)"
4216 );
4217 assert_eq!(remaining[1].label, "new:0");
4218 assert!(
4219 !remaining.iter().any(|s| s.label.starts_with("old:")),
4220 "old snapshots must be gone, not kept as ancestors: {:?}",
4221 remaining.iter().map(|s| &s.label).collect::<Vec<_>>()
4222 );
4223
4224 // The survivors' contents are intact and restorable.
4225 repo.restore(&remaining[0].id).unwrap();
4226 assert_eq!(
4227 std::fs::read_to_string(repo.work_tree().join("f.txt")).unwrap(),
4228 "new1"
4229 );
4230 }
4231
4232 #[test]
4233 fn prune_keep_last_n_keeps_latest_and_gc_reclaims_rest() {
4234 let tmp = tempdir().unwrap();
4235 let (repo, _home) = make_repo(tmp.path());
4236
4237 for i in 0..3 {
4238 std::fs::write(repo.work_tree().join("f.txt"), format!("v{i}")).unwrap();
4239 repo.snapshot(&format!("turn:{i}")).unwrap();
4240 std::thread::sleep(Duration::from_millis(1100));
4241 }
4242
4243 assert_eq!(repo.list(usize::MAX).unwrap().len(), 3);
4244
4245 let removed = repo.prune_keep_last_n(1).unwrap();
4246 assert_eq!(removed, 2);
4247
4248 let remaining = repo.list(usize::MAX).unwrap();
4249 assert_eq!(remaining.len(), 1);
4250 assert_eq!(remaining[0].label, "turn:2");
4251
4252 // New snapshot starts a clean chain (not appending to old).
4253 std::fs::write(repo.work_tree().join("f.txt"), "fresh").unwrap();
4254 repo.snapshot("turn:new").unwrap();
4255 assert_eq!(repo.list(usize::MAX).unwrap().len(), 2);
4256 }
4257
4258 /// The per-snapshot prune drops half a window at once instead of
4259 /// rebuilding the chain for every snapshot past the cap.
4260 #[test]
4261 fn batched_prune_waits_for_half_a_window_then_drops_it_together() {
4262 let tmp = tempdir().unwrap();
4263 let (repo, _home) = make_repo(tmp.path());
4264 let max = 4;
4265 for n in 0..max + 1 {
4266 std::fs::write(repo.work_tree().join("f.txt"), format!("{n}")).unwrap();
4267 repo.snapshot(&format!("tool:{n}")).unwrap();
4268 }
4269 // One over the cap: the plain prune would rebuild now, the batched
4270 // one waits.
4271 assert_eq!(repo.prune_keep_last_n_batched(max).unwrap(), 0);
4272 assert_eq!(repo.list(usize::MAX).unwrap().len(), max + 1);
4273
4274 std::fs::write(repo.work_tree().join("f.txt"), "last").unwrap();
4275 repo.snapshot("tool:last").unwrap();
4276 assert_eq!(repo.prune_keep_last_n_batched(max).unwrap(), 2);
4277 let kept = repo.list(usize::MAX).unwrap();
4278 assert_eq!(kept.len(), max);
4279 assert_eq!(kept[0].label, "tool:last", "the newest snapshots survive");
4280 }
4281
4282 #[test]
4283 fn prune_keep_last_n_preserves_multiple_snapshots_in_order() {
4284 let tmp = tempdir().unwrap();
4285 let (repo, _home) = make_repo(tmp.path());
4286
4287 for i in 0..4 {
4288 std::fs::write(repo.work_tree().join("f.txt"), format!("v{i}")).unwrap();
4289 repo.snapshot(&format!("turn:{i}")).unwrap();
4290 std::thread::sleep(Duration::from_millis(1100));
4291 }
4292
4293 assert_eq!(repo.list(usize::MAX).unwrap().len(), 4);
4294
4295 let removed = repo.prune_keep_last_n(2).unwrap();
4296 assert_eq!(removed, 2);
4297
4298 let remaining = repo.list(usize::MAX).unwrap();
4299 assert_eq!(remaining.len(), 2);
4300 // Should be newest-first: turn:3 (newest), turn:2 (second newest)
4301 assert_eq!(remaining[0].label, "turn:3");
4302 assert_eq!(remaining[1].label, "turn:2");
4303
4304 // New snapshot continues the chain.
4305 std::fs::write(repo.work_tree().join("f.txt"), "fresh").unwrap();
4306 repo.snapshot("turn:new").unwrap();
4307 let after = repo.list(usize::MAX).unwrap();
4308 assert_eq!(after.len(), 3);
4309 assert_eq!(after[0].label, "turn:new");
4310 }
4311
4312 #[test]
4313 fn open_or_init_removes_stale_tmp_pack_files_only() {
4314 let tmp = tempdir().unwrap();
4315 let (repo, _home) = make_repo(tmp.path());
4316 let workspace = repo.work_tree().to_path_buf();
4317 let pack_dir = repo.git_dir().join("objects").join("pack");
4318 std::fs::create_dir_all(&pack_dir).unwrap();
4319
4320 let stale = pack_dir.join("tmp_pack_stale");
4321 let fresh = pack_dir.join("tmp_pack_fresh");
4322 let ordinary_pack = pack_dir.join("pack-kept.pack");
4323 std::fs::write(&stale, b"stale").unwrap();
4324 std::fs::write(&fresh, b"fresh").unwrap();
4325 std::fs::write(&ordinary_pack, b"pack").unwrap();
4326
4327 let old_time = SystemTime::now() - STALE_TMP_PACK_AGE - Duration::from_secs(60);
4328 {
4329 let file = File::options().write(true).open(&stale).unwrap();
4330 file.set_times(FileTimes::new().set_modified(old_time))
4331 .unwrap();
4332 }
4333
4334 SnapshotRepo::open_or_init(&workspace).unwrap();
4335
4336 assert!(!stale.exists(), "stale tmp_pack file should be removed");
4337 assert!(fresh.exists(), "fresh tmp_pack file should be kept");
4338 assert!(ordinary_pack.exists(), "non-temp pack file should be kept");
4339 }
4340
4341 #[test]
4342 fn snapshot_respects_workspace_gitignore() {
4343 let tmp = tempdir().unwrap();
4344 let (repo, _home) = make_repo(tmp.path());
4345 std::fs::write(repo.work_tree().join(".gitignore"), "ignored.txt\n").unwrap();
4346 std::fs::write(repo.work_tree().join("ignored.txt"), b"secret").unwrap();
4347 std::fs::write(repo.work_tree().join("kept.txt"), b"public").unwrap();
4348
4349 let id = repo.snapshot("pre-turn:1").expect("snapshot");
4350
4351 // `git ls-tree` against the snapshot's commit shouldn't list ignored.txt.
4352 let ls = run_git(
4353 repo.git_dir(),
4354 repo.work_tree(),
4355 &["ls-tree", "-r", "--name-only", id.as_str()],
4356 )
4357 .expect("ls-tree");
4358 let names = String::from_utf8_lossy(&ls.stdout);
4359 assert!(names.contains("kept.txt"), "kept.txt missing: {names}");
4360 assert!(
4361 !names.contains("ignored.txt"),
4362 "ignored.txt should not be in snapshot: {names}",
4363 );
4364 }
4365
4366 #[test]
4367 fn unsafe_workspace_rejects_home_directory_workspace() {
4368 let tmp = tempdir().unwrap();
4369 let home = tmp.path();
4370
4371 assert_eq!(
4372 unsafe_workspace_snapshot_reason(home, Some(home)),
4373 Some("home directory")
4374 );
4375 }
4376
4377 #[test]
4378 fn unsafe_workspace_rejects_home_collection_directories() {
4379 let tmp = tempdir().unwrap();
4380 let home = tmp.path();
4381 let desktop = tmp.path().join("Desktop");
4382 std::fs::create_dir_all(&desktop).unwrap();
4383
4384 assert_eq!(
4385 unsafe_workspace_snapshot_reason(&desktop, Some(home)),
4386 Some("home collection directory")
4387 );
4388 }
4389
4390 #[test]
4391 fn unsafe_workspace_allows_project_directories_under_home() {
4392 let tmp = tempdir().unwrap();
4393 let home = tmp.path();
4394 let workspace = tmp.path().join("code").join("project");
4395 std::fs::create_dir_all(&workspace).unwrap();
4396
4397 assert_eq!(
4398 unsafe_workspace_snapshot_reason(&workspace, Some(home)),
4399 None
4400 );
4401 }
4402
4403 #[test]
4404 fn snapshot_respects_builtin_excludes() {
4405 let tmp = tempdir().unwrap();
4406 let (repo, _home) = make_repo(tmp.path());
4407 std::fs::create_dir_all(repo.work_tree().join("node_modules/pkg")).unwrap();
4408 std::fs::create_dir_all(repo.work_tree().join(".next/cache")).unwrap();
4409 std::fs::create_dir_all(repo.work_tree().join("src")).unwrap();
4410 std::fs::write(
4411 repo.work_tree().join("node_modules/pkg/index.js"),
4412 b"generated",
4413 )
4414 .unwrap();
4415 std::fs::write(repo.work_tree().join(".next/cache/chunk.bin"), b"generated").unwrap();
4416 std::fs::write(repo.work_tree().join("debug.wasm"), b"binary").unwrap();
4417 std::fs::write(repo.work_tree().join("src/main.rs"), b"fn main() {}").unwrap();
4418
4419 let excludes = std::fs::read_to_string(repo.git_dir().join("info/exclude")).unwrap();
4420 assert!(excludes.contains("node_modules/"));
4421 assert!(excludes.contains(".next/"));
4422 assert!(excludes.contains("*.wasm"));
4423
4424 let id = repo.snapshot("pre-turn:1").expect("snapshot");
4425 let ls = run_git(
4426 repo.git_dir(),
4427 repo.work_tree(),
4428 &["ls-tree", "-r", "--name-only", id.as_str()],
4429 )
4430 .expect("ls-tree");
4431 let names = String::from_utf8_lossy(&ls.stdout);
4432 assert!(
4433 names.contains("src/main.rs"),
4434 "src/main.rs missing: {names}"
4435 );
4436 assert!(
4437 !names.contains("node_modules"),
4438 "node_modules should not be in snapshot: {names}",
4439 );
4440 assert!(
4441 !names.contains(".next"),
4442 ".next should not be in snapshot: {names}",
4443 );
4444 assert!(
4445 !names.contains("debug.wasm"),
4446 "binary artifacts should not be in snapshot: {names}",
4447 );
4448 }
4449
4450 #[test]
4451 fn open_or_init_is_idempotent() {
4452 let tmp = tempdir().unwrap();
4453 let (_r, _h) = make_repo(tmp.path());
4454 // Second open should not panic and should reuse the existing
4455 // `.git`. We re-open via the public API rather than make_repo to
4456 // avoid double-acquiring HOME (the guard would deadlock).
4457 drop((_r, _h));
4458 let (_r2, _h2) = make_repo(tmp.path());
4459 }
4460
4461 #[test]
4462 fn home_directory_guard_matches_canonical_paths() {
4463 let tmp = tempdir().unwrap();
4464 let home = tmp.path();
4465 let home_canonical = home.canonicalize().unwrap();
4466 let workspace = home.join("workspace");
4467 std::fs::create_dir_all(&workspace).unwrap();
4468 let workspace_canonical = workspace.canonicalize().unwrap();
4469
4470 assert!(is_home_directory(&home_canonical, Some(home)));
4471 assert!(!is_home_directory(&workspace_canonical, Some(home)));
4472 assert!(!is_home_directory(&home_canonical, None));
4473 }
4474
4475 #[test]
4476 fn dir_size_bytes_measures_directory_bytes() {
4477 let tmp = tempdir().unwrap();
4478 let dir = tmp.path().join("sizedir");
4479 std::fs::create_dir_all(dir.join("sub")).unwrap();
4480 // 3 bytes per file.
4481 std::fs::write(dir.join("a.txt"), b"abc").unwrap();
4482 std::fs::write(dir.join("sub/b.txt"), b"xyz").unwrap();
4483
4484 let size = dir_size_bytes(&dir).expect("dir_size_bytes");
4485 assert_eq!(size, 6, "two 3-byte files should measure 6 bytes");
4486
4487 // Write 2 MB of data.
4488 let big = dir.join("big.bin");
4489 std::fs::write(&big, vec![0u8; 2 * 1024 * 1024]).unwrap();
4490 let size = dir_size_bytes(&dir).expect("dir_size_bytes after big write");
4491 assert_eq!(
4492 size,
4493 2 * 1024 * 1024 + 6,
4494 "expected 2 MB + 6 bytes after writing a 2 MB file"
4495 );
4496 }
4497
4498 /// Regression: snapshot size cap (#1112). When the snapshot dir grows,
4499 /// `snapshot()` must prune old snapshots to stay under the limit.
4500 /// This test uses the real size constants, which are 500/400 MB —
4501 /// we can't easily blow up a temp dir to 500 MB in a unit test.
4502 /// Instead we verify the guard logic doesn't panic or error on a
4503 /// small repo (well under the cap), and that `snapshot()` still works.
4504 #[test]
4505 fn snapshot_succeeds_when_under_size_cap() {
4506 let tmp = tempdir().unwrap();
4507 let (repo, _home) = make_repo(tmp.path());
4508 // The side repo is tiny — well under 500 MB. Snapshot should work.
4509 std::fs::write(repo.work_tree().join("f.txt"), b"hello").unwrap();
4510 let id = repo.snapshot("pre-turn:1").expect("snapshot under cap");
4511 assert_eq!(id.as_str().len(), 40);
4512 }
4513
4514 /// Sessions and sub-agents share one side repo. The size-pressure prune
4515 /// used to protect only the globally newest turn boundaries, so another
4516 /// session's snapshots pushed a running turn's `pre-turn:` out and its
4517 /// undo had nothing to restore.
4518 #[test]
4519 fn prune_size_pressure_keeps_every_sessions_turn_boundaries() {
4520 let tmp = tempdir().unwrap();
4521 let (repo, _home) = make_repo(tmp.path());
4522 for (i, (label, sid)) in [
4523 ("pre-turn:5", "A"),
4524 ("tool:a", "A"),
4525 ("pre-turn:1", "B"),
4526 ("tool:b", "B"),
4527 ("post-turn:1", "B"),
4528 ("pre-turn:2", "B"),
4529 ("tool:c", "B"),
4530 ]
4531 .into_iter()
4532 .enumerate()
4533 {
4534 std::fs::write(repo.work_tree().join("f.txt"), format!("v{i}")).unwrap();
4535 repo.snapshot_with_session(label, Some(sid))
4536 .expect("snapshot");
4537 }
4538 repo.prune_size_pressure(0, 0).expect("prune_size_pressure");
4539 let kept: Vec<(String, Option<String>)> = repo
4540 .list(usize::MAX)
4541 .unwrap()
4542 .into_iter()
4543 .map(|s| (s.label, s.session_id))
4544 .collect();
4545 let kept_a_pre = kept
4546 .iter()
4547 .any(|(label, sid)| label == "pre-turn:5" && sid.as_deref() == Some("A"));
4548 assert!(
4549 kept_a_pre,
4550 "session A's running turn stays restorable: {kept:?}"
4551 );
4552 assert_eq!(
4553 kept.iter()
4554 .map(|(label, _)| label.as_str())
4555 .collect::<Vec<_>>(),
4556 ["tool:c", "pre-turn:2", "post-turn:1", "pre-turn:5"],
4557 "only boundaries and the newest snapshot survive a full cut"
4558 );
4559 }
4560
4561 /// The size-pressure prune drops the oldest snapshots first and keeps the
4562 /// newest one plus the newest turn boundaries. It used to prune by age
4563 /// from one second down, which wiped every restore point, the running
4564 /// turn's own `pre-turn:` included, on each snapshot of a side repo over
4565 /// the cap.
4566 #[test]
4567 fn prune_size_pressure_drops_oldest_first_and_keeps_turn_boundaries() {
4568 let tmp = tempdir().unwrap();
4569 let (repo, _home) = make_repo(tmp.path());
4570 for (i, label) in [
4571 "pre-turn:1",
4572 "tool:a",
4573 "post-turn:1",
4574 "pre-turn:2",
4575 "tool:b",
4576 "tool:c",
4577 ]
4578 .into_iter()
4579 .enumerate()
4580 {
4581 std::fs::write(repo.work_tree().join("f.txt"), format!("v{i}")).unwrap();
4582 repo.snapshot(label).expect("snapshot");
4583 }
4584 // A zero byte limit makes any non-empty side repo "over limit", so the
4585 // prune cuts as far as it may and reports exactly what it destroyed;
4586 // the count is what the user-visible notice is built from.
4587 let removed = repo.prune_size_pressure(0, 0).expect("prune_size_pressure");
4588 let labels: Vec<String> = repo
4589 .list(usize::MAX)
4590 .unwrap()
4591 .into_iter()
4592 .map(|s| s.label)
4593 .collect();
4594 assert_eq!(
4595 labels,
4596 ["tool:c", "pre-turn:2", "post-turn:1"],
4597 "the newest snapshot and the newest turn boundaries survive"
4598 );
4599 assert_eq!(removed, 3, "every dropped snapshot is reported");
4600 // The survivors still restore: the running turn can be undone.
4601 let pre = repo.list(usize::MAX).unwrap()[1].id.clone();
4602 repo.restore(&pre)
4603 .expect("restore the running turn's boundary");
4604 assert_eq!(
4605 std::fs::read_to_string(repo.work_tree().join("f.txt")).unwrap(),
4606 "v3"
4607 );
4608 }
4609
4610 #[test]
4611 fn prune_size_pressure_is_a_noop_under_the_limit() {
4612 let tmp = tempdir().unwrap();
4613 let (repo, _home) = make_repo(tmp.path());
4614 std::fs::write(repo.work_tree().join("f.txt"), b"v0").unwrap();
4615 repo.snapshot("pre-turn:0").expect("snapshot");
4616 let removed = repo
4617 .prune_size_pressure(u64::MAX, u64::MAX)
4618 .expect("prune_size_pressure");
4619 assert_eq!(removed, 0, "under the limit nothing may be removed");
4620 assert_eq!(repo.list(usize::MAX).unwrap().len(), 1);
4621 }
4622
4623 #[test]
4624 fn snapshot_history_pruned_message_names_workspace_count_and_cap() {
4625 let msg = snapshot_history_pruned_message(Path::new("/tmp/ws"), 7);
4626 assert!(msg.contains("/tmp/ws"), "message must name the workspace");
4627 assert!(msg.contains("7"), "message must state the removed count");
4628 assert!(
4629 msg.contains(&MAX_SNAPSHOT_SIZE_MB.to_string()),
4630 "message must state the storage cap"
4631 );
4632 }
4633
4634 #[test]
4635 fn estimate_workspace_size_bounded_returns_total_when_under_cap() {
4636 let tmp = tempdir().unwrap();
4637 let workspace = tmp.path().join("workspace");
4638 std::fs::create_dir_all(&workspace).unwrap();
4639 std::fs::write(workspace.join("a.txt"), vec![b'a'; 100]).unwrap();
4640 std::fs::write(workspace.join("b.txt"), vec![b'b'; 50]).unwrap();
4641 let total = estimate_workspace_size_bounded(&workspace, 10_000, SIZE_WALK_MAX_ENTRIES)
4642 .expect("under-cap walk must return a total");
4643 assert!(
4644 total >= 150,
4645 "total ({total}) must include both files (≥150 bytes)"
4646 );
4647 }
4648
4649 #[test]
4650 fn estimate_workspace_size_bounded_reports_the_size_gate_when_over_cap() {
4651 let tmp = tempdir().unwrap();
4652 let workspace = tmp.path().join("workspace");
4653 std::fs::create_dir_all(&workspace).unwrap();
4654 // Two 1 KB files, cap at 1 KB — second file should trip the cap.
4655 std::fs::write(workspace.join("a.bin"), vec![b'a'; 1024]).unwrap();
4656 std::fs::write(workspace.join("b.bin"), vec![b'b'; 1024]).unwrap();
4657 assert_eq!(
4658 estimate_workspace_size_bounded(&workspace, 1024, SIZE_WALK_MAX_ENTRIES),
4659 Err(WorkspaceGate::TooLarge),
4660 "over-cap walk must name the size gate for early bailout"
4661 );
4662 }
4663
4664 #[test]
4665 fn oversize_gate_message_states_the_byte_cap_without_a_remedy() {
4666 // The remedy is localized by the notice surfaces; repeating it here is
4667 // what produced the doubled warning.
4668 let message =
4669 WorkspaceGate::TooLarge.describe(2 * 1024 * 1024 * 1024, Path::new("/tmp/ws"));
4670 assert!(message.starts_with(GATE_TOO_LARGE_MARKER));
4671 assert!(message.contains("/tmp/ws"));
4672 assert!(!message.contains("max_workspace_gb"));
4673 assert_eq!(message.lines().count(), 1, "the gate message is one line");
4674 }
4675
4676 #[test]
4677 fn entry_gate_message_is_distinct_and_never_blames_the_size_cap() {
4678 let message = WorkspaceGate::TooManyEntries.describe(0, Path::new("/tmp/ws"));
4679 assert!(message.starts_with(GATE_TOO_MANY_ENTRIES_MARKER));
4680 assert!(
4681 !message.contains(GATE_TOO_LARGE_MARKER),
4682 "the entry gate must not be reported as a size trip"
4683 );
4684 assert!(message.contains(&SIZE_WALK_MAX_ENTRIES.to_string()));
4685 assert!(!message.contains("max_workspace_gb"));
4686 }
4687
4688 #[test]
4689 fn estimate_workspace_size_bounded_skips_builtin_excluded_dirs() {
4690 let tmp = tempdir().unwrap();
4691 let workspace = tmp.path().join("workspace");
4692 std::fs::create_dir_all(workspace.join("node_modules")).unwrap();
4693 std::fs::create_dir_all(workspace.join("target")).unwrap();
4694 std::fs::create_dir_all(workspace.join("src")).unwrap();
4695 // 2 MB of "build output" in excluded dirs — must not count toward
4696 // the cap.
4697 std::fs::write(workspace.join("node_modules/big.bin"), vec![0u8; 1_000_000]).unwrap();
4698 std::fs::write(workspace.join("target/big.bin"), vec![0u8; 1_000_000]).unwrap();
4699 std::fs::write(workspace.join("src/lib.rs"), b"// real source").unwrap();
4700 let total = estimate_workspace_size_bounded(&workspace, 500_000, SIZE_WALK_MAX_ENTRIES)
4701 .expect("walk must succeed since real source is tiny");
4702 assert!(
4703 total < 1_000,
4704 "total ({total}) must reflect only src/, not node_modules/ or target/"
4705 );
4706 }
4707
4708 #[test]
4709 fn estimate_workspace_size_bounded_cap_zero_disables_cap() {
4710 let tmp = tempdir().unwrap();
4711 let workspace = tmp.path().join("workspace");
4712 std::fs::create_dir_all(&workspace).unwrap();
4713 // 10 KB file — would trip a 1 KB cap, but cap=0 means no cap.
4714 std::fs::write(workspace.join("big.bin"), vec![0u8; 10 * 1024]).unwrap();
4715 let total = estimate_workspace_size_bounded(&workspace, 0, SIZE_WALK_MAX_ENTRIES)
4716 .expect("cap=0 must always return a total");
4717 assert!(
4718 total >= 10 * 1024,
4719 "total ({total}) must include the 10 KB file when cap is disabled"
4720 );
4721 }
4722
4723 /// The entry ceiling is the bound that no test could reach before
4724 /// `max_entries` became a parameter: 200,000 inodes per run is not a
4725 /// price a unit test should pay. A byte-cheap workspace must still be
4726 /// refused, and refused as the *entry* gate — reporting `TooLarge` here
4727 /// would offer `max_workspace_gb` as a remedy that cannot lift it.
4728 #[test]
4729 fn entry_ceiling_refuses_a_byte_cheap_workspace_with_too_many_entries() {
4730 let tmp = tempdir().unwrap();
4731 let workspace = tmp.path().join("workspace");
4732 std::fs::create_dir_all(&workspace).unwrap();
4733 for i in 0..10 {
4734 std::fs::write(workspace.join(format!("f{i}.txt")), b"x").unwrap();
4735 }
4736 assert_eq!(
4737 estimate_workspace_size_bounded(&workspace, 10_000_000, 3),
4738 Err(WorkspaceGate::TooManyEntries),
4739 "ten tiny files under a 10 MB cap must trip the entry bound, not the byte cap"
4740 );
4741 }
4742
4743 /// The invariant documented on `WorkspaceGate::TooManyEntries` and on the
4744 /// estimator: `max_workspace_gb = 0` opts out of the byte cap only. A
4745 /// future "if `cap_bytes == 0`, skip the walk" shortcut would satisfy
4746 /// every other test here and silently delete the ceiling that exists to
4747 /// stop a multi-minute `git add -A`.
4748 #[test]
4749 fn cap_zero_does_not_lift_the_entry_ceiling() {
4750 let tmp = tempdir().unwrap();
4751 let workspace = tmp.path().join("workspace");
4752 std::fs::create_dir_all(&workspace).unwrap();
4753 for i in 0..10 {
4754 std::fs::write(workspace.join(format!("f{i}.txt")), b"x").unwrap();
4755 }
4756 assert_eq!(
4757 estimate_workspace_size_bounded(&workspace, 0, 3),
4758 Err(WorkspaceGate::TooManyEntries),
4759 "cap_bytes = 0 disables the byte cap, never the entry ceiling"
4760 );
4761 }
4762
4763 /// `ignore` disables gitignore matching entirely when no ancestor holds a
4764 /// `.git` (`require_git` defaults to true), but the snapshot's own
4765 /// `git add -A --work-tree <workspace>` reads `.gitignore` either way. A
4766 /// non-git workspace was therefore measured on content that would never
4767 /// be staged — and then told to fix it by editing `.gitignore`.
4768 ///
4769 /// Deliberately creates no `.git`: the point is the non-repo case.
4770 #[test]
4771 fn gitignored_content_is_excluded_outside_a_git_repo() {
4772 let tmp = tempdir().unwrap();
4773 let workspace = tmp.path().join("workspace");
4774 std::fs::create_dir_all(workspace.join("src")).unwrap();
4775 std::fs::write(workspace.join(".gitignore"), "big.bin\n").unwrap();
4776 std::fs::write(workspace.join("big.bin"), vec![0u8; 1_000_000]).unwrap();
4777 std::fs::write(workspace.join("src/lib.rs"), b"// real source").unwrap();
4778 assert!(
4779 !workspace.join(".git").exists(),
4780 "this test is only meaningful outside a git repo"
4781 );
4782 let total = estimate_workspace_size_bounded(&workspace, 500_000, SIZE_WALK_MAX_ENTRIES)
4783 .expect("the only large file is gitignored, so the walk must fit under the cap");
4784 assert!(
4785 total < 1_000,
4786 "total ({total}) must exclude the gitignored 1 MB file"
4787 );
4788 }
4789
4790 #[test]
4791 fn open_or_init_with_cap_rejects_oversized_workspace() {
4792 let tmp = tempdir().unwrap();
4793 let workspace = tmp.path().join("workspace");
4794 std::fs::create_dir_all(&workspace).unwrap();
4795 let _home = scoped_home(tmp.path());
4796 // Drop a 4 KB file under a 1 KB cap.
4797 std::fs::write(workspace.join("big.bin"), vec![0u8; 4096]).unwrap();
4798 let outcome = SnapshotRepo::open_or_init_with_cap(&workspace, 1024);
4799 let err = match outcome {
4800 Ok(_) => panic!("oversized workspace must fail open_or_init_with_cap"),
4801 Err(e) => e,
4802 };
4803 let msg = err.to_string();
4804 assert!(
4805 msg.contains(GATE_TOO_LARGE_MARKER),
4806 "error must call out the size cap; got: {msg}"
4807 );
4808 let named_owned = workspace.display().to_string();
4809 let named = named_owned
4810 .strip_prefix(r"\\?\")
4811 .or_else(|| named_owned.strip_prefix("//?/"))
4812 .unwrap_or(named_owned.as_str());
4813 assert!(
4814 msg.contains(named),
4815 "error must name the workspace it refused; got: {msg}"
4816 );
4817 // The remedy belongs to the localized notice. Repeating it here is
4818 // what produced the doubled, three-line warning users saw.
4819 assert!(
4820 !msg.contains("max_workspace_gb"),
4821 "gate error must not carry its own remedy copy; got: {msg}"
4822 );
4823 }
4824
4825 #[test]
4826 fn open_or_init_with_cap_zero_disables_size_check() {
4827 let tmp = tempdir().unwrap();
4828 let workspace = tmp.path().join("workspace");
4829 std::fs::create_dir_all(&workspace).unwrap();
4830 let _home = scoped_home(tmp.path());
4831 // 4 KB file but cap=0 → should still succeed.
4832 std::fs::write(workspace.join("big.bin"), vec![0u8; 4096]).unwrap();
4833 let repo = SnapshotRepo::open_or_init_with_cap(&workspace, 0)
4834 .expect("cap=0 must skip the size check");
4835 let id = repo
4836 .snapshot("pre-turn:1")
4837 .expect("snapshot under disabled cap");
4838 assert_eq!(id.as_str().len(), 40);
4839 }
4840
4841 #[test]
4842 fn session_tagged_snapshot_round_trips_through_list() {
4843 let tmp = tempdir().unwrap();
4844 let (repo, _home) = make_repo(tmp.path());
4845 std::fs::write(repo.work_tree().join("a.txt"), b"x").unwrap();
4846
4847 repo.snapshot_with_session("pre-turn:1", Some("sess-42"))
4848 .expect("snapshot with session");
4849
4850 let list = repo.list(10).expect("list");
4851 assert_eq!(list.len(), 1);
4852 // The visible label stays clean; the session id is decoded separately.
4853 assert_eq!(list[0].label, "pre-turn:1");
4854 assert_eq!(list[0].session_id.as_deref(), Some("sess-42"));
4855 }
4856
4857 #[test]
4858 fn untagged_snapshot_decodes_without_session() {
4859 let tmp = tempdir().unwrap();
4860 let (repo, _home) = make_repo(tmp.path());
4861 std::fs::write(repo.work_tree().join("a.txt"), b"x").unwrap();
4862
4863 repo.snapshot("pre-turn:1").expect("snapshot");
4864
4865 let list = repo.list(10).expect("list");
4866 assert_eq!(list.len(), 1);
4867 assert_eq!(list[0].label, "pre-turn:1");
4868 assert_eq!(list[0].session_id, None);
4869 }
4870
4871 /// A burst of per-tool snapshots larger than the count cap never pushes
4872 /// out the turn boundaries: the running turn's `pre-turn:` restore point
4873 /// survives its own 50-write turn and another thread's burst.
4874 #[test]
4875 fn prune_keep_last_n_retains_turn_boundaries_through_a_tool_burst() {
4876 let tmp = tempdir().unwrap();
4877 let (repo, _home) = make_repo(tmp.path());
4878 let file = repo.work_tree().join("a.txt");
4879 std::fs::write(&file, "v0").unwrap();
4880 let older_post = repo
4881 .take_snapshot("post-turn:0", Some("thr_a"))
4882 .expect("snapshot");
4883 let pre = repo
4884 .take_snapshot("pre-turn:1", Some("thr_a"))
4885 .expect("snapshot");
4886 for i in 0..6 {
4887 std::fs::write(&file, format!("v{}", i + 1)).unwrap();
4888 repo.take_snapshot(&format!("tool:call-{i}"), Some("thr_a"))
4889 .expect("snapshot");
4890 repo.take_snapshot(&format!("post-tool:call-{i}"), Some("thr_a"))
4891 .expect("snapshot");
4892 }
4893 // 14 snapshots, cap 3: the newest three plus the (two) boundaries.
4894 let removed = repo.prune_keep_last_n(3).expect("prune");
4895 assert_eq!(removed, 9);
4896 let labels: Vec<String> = repo
4897 .list(usize::MAX)
4898 .unwrap()
4899 .into_iter()
4900 .map(|snapshot| snapshot.label)
4901 .collect();
4902 assert_eq!(
4903 labels,
4904 [
4905 "post-tool:call-5",
4906 "tool:call-5",
4907 "post-tool:call-4",
4908 "pre-turn:1",
4909 "post-turn:0",
4910 ]
4911 );
4912 let trees: Vec<SnapshotId> = repo
4913 .list(usize::MAX)
4914 .unwrap()
4915 .into_iter()
4916 .map(|snapshot| snapshot.tree)
4917 .collect();
4918 assert!(trees.contains(&pre.tree) && trees.contains(&older_post.tree));
4919
4920 // Boundaries are themselves capped at the same count.
4921 for i in 2..6 {
4922 repo.take_snapshot(&format!("pre-turn:{i}"), Some("thr_a"))
4923 .expect("snapshot");
4924 }
4925 repo.prune_keep_last_n(3).expect("prune");
4926 let boundaries = repo
4927 .list(usize::MAX)
4928 .unwrap()
4929 .into_iter()
4930 .filter(|snapshot| is_turn_boundary_label(&snapshot.label))
4931 .count();
4932 assert_eq!(boundaries, 3);
4933 }
4934
4935 #[test]
4936 fn prune_keep_last_n_preserves_session_tags() {
4937 let tmp = tempdir().unwrap();
4938 let (repo, _home) = make_repo(tmp.path());
4939 let file = repo.work_tree().join("a.txt");
4940
4941 // More snapshots than DEFAULT_MAX_SNAPSHOTS (50) so the survivor
4942 // chain is rebuilt as orphan commits — the path that previously
4943 // dropped the [sid=...] label prefix and turned every surviving
4944 // snapshot into a "legacy" (untagged) one.
4945 for i in 0..55 {
4946 std::fs::write(&file, format!("v{i}")).unwrap();
4947 repo.snapshot_with_session(&format!("pre-turn:{i}"), Some("sess-p"))
4948 .expect("tagged snapshot");
4949 }
4950
4951 let removed = repo.prune_keep_last_n(50).expect("prune");
4952 assert!(removed > 0, "expected prune to drop older snapshots");
4953
4954 let list = repo.list(usize::MAX).expect("list");
4955 assert_eq!(list.len(), 50);
4956 assert!(
4957 list.iter()
4958 .all(|s| s.session_id.as_deref() == Some("sess-p")),
4959 "prune must preserve [sid=...] prefixes; got untagged survivors"
4960 );
4961 }
4962
4963 #[test]
4964 fn tagged_and_untagged_snapshots_coexist_in_one_chain() {
4965 let tmp = tempdir().unwrap();
4966 let (repo, _home) = make_repo(tmp.path());
4967 std::fs::write(repo.work_tree().join("a.txt"), b"v1").unwrap();
4968
4969 // Legacy untagged snapshot, then a session-tagged one.
4970 repo.snapshot("pre-turn:1").expect("legacy snapshot");
4971 std::fs::write(repo.work_tree().join("a.txt"), b"v2").unwrap();
4972 repo.snapshot_with_session("pre-turn:1", Some("sess-a"))
4973 .expect("tagged snapshot");
4974
4975 let list = repo.list(10).expect("list");
4976 assert_eq!(list.len(), 2);
4977 // Newest first.
4978 assert_eq!(list[0].session_id.as_deref(), Some("sess-a"));
4979 assert_eq!(list[1].session_id, None);
4980 assert_eq!(list[1].label, "pre-turn:1");
4981 }
4982
4983 /// The patch a per-call change record shows comes from the side repo's
4984 /// own two trees, names one path, and names it literally: a bracketed
4985 /// filename must not drag its glob sibling into the diff.
4986 #[test]
4987 fn patch_between_diffs_one_literal_path_between_two_snapshots() {
4988 let tmp = tempdir().unwrap();
4989 let (repo, _home) = make_repo(tmp.path());
4990 std::fs::write(repo.work_tree().join("a.txt"), b"alpha\n").unwrap();
4991 std::fs::write(repo.work_tree().join("b.txt"), b"keep\n").unwrap();
4992 std::fs::write(repo.work_tree().join("file[12].txt"), b"literal-before\n").unwrap();
4993 std::fs::write(repo.work_tree().join("file1.txt"), b"sibling-before\n").unwrap();
4994 let before = repo.snapshot("tool:call-1").expect("snapshot");
4995 std::fs::write(repo.work_tree().join("a.txt"), b"alpha\nbeta\n").unwrap();
4996 std::fs::write(repo.work_tree().join("b.txt"), b"changed\n").unwrap();
4997 std::fs::write(repo.work_tree().join("file[12].txt"), b"literal-after\n").unwrap();
4998 let after = repo.snapshot("post-tool:call-1").expect("snapshot");
4999
5000 let (patch, truncated) = repo
5001 .patch_between(&before, &after, "a.txt", 1 << 20)
5002 .expect("patch");
5003 assert!(!truncated);
5004 assert!(patch.contains("+beta"), "{patch}");
5005 assert!(
5006 !patch.contains("b.txt"),
5007 "only the named path belongs in this patch: {patch}"
5008 );
5009
5010 let (literal, _) = repo
5011 .patch_between(&before, &after, "file[12].txt", 1 << 20)
5012 .expect("patch");
5013 assert!(literal.contains("+literal-after"), "{literal}");
5014 assert!(
5015 !literal.contains("file1.txt"),
5016 "a bracketed filename must not diff its glob sibling: {literal}"
5017 );
5018
5019 // A path that does not differ writes nothing rather than an empty
5020 // hunk the caller would have to interpret.
5021 let unchanged = repo
5022 .patch_between(&before, &before, "a.txt", 1 << 20)
5023 .expect("patch");
5024 assert!(unchanged.0.is_empty(), "{unchanged:?}");
5025 assert!(!unchanged.1);
5026 }
5027
5028 /// The work tree is compared as it is now, not as the newest snapshot
5029 /// left it: a file created since, which no snapshot or index holds, is in
5030 /// the diff with its content, and reading it moves neither the repo's
5031 /// HEAD nor its index.
5032 #[test]
5033 fn work_tree_changes_since_sees_edits_deletions_and_unrecorded_new_files() {
5034 let tmp = tempdir().unwrap();
5035 let (repo, _home) = make_repo(tmp.path());
5036 let ws = repo.work_tree().to_path_buf();
5037 std::fs::write(ws.join(".gitignore"), b"ignored/\n").unwrap();
5038 std::fs::write(ws.join("keep.txt"), b"same\n").unwrap();
5039 std::fs::write(ws.join("edit.txt"), b"one\ntwo\n").unwrap();
5040 std::fs::write(ws.join("gone.txt"), b"bye\n").unwrap();
5041 std::fs::write(ws.join("late.txt"), b"still here\n").unwrap();
5042 let before = repo.snapshot("pre-turn:1").expect("snapshot");
5043 let head = git_output(&repo, &["rev-parse", "HEAD"]);
5044 let index = git_output(&repo, &["ls-files", "--stage"]);
5045
5046 std::fs::write(ws.join("edit.txt"), b"one\nTWO\n").unwrap();
5047 std::fs::remove_file(ws.join("gone.txt")).unwrap();
5048 std::fs::write(ws.join("new file.txt"), b"fresh\n").unwrap();
5049 std::fs::create_dir_all(ws.join("ignored")).unwrap();
5050 std::fs::write(ws.join("ignored/skip.txt"), b"skip\n").unwrap();
5051 // Ignored only after the snapshot recorded it, and untouched: it is
5052 // not a deletion.
5053 std::fs::write(ws.join(".gitignore"), b"ignored/\nlate.txt\n").unwrap();
5054
5055 let changes = repo
5056 .work_tree_changes_since(&before, 1 << 20)
5057 .expect("changes");
5058 let mut names: Vec<&str> = changes.names.lines().collect();
5059 names.sort_unstable();
5060 assert_eq!(
5061 names,
5062 [".gitignore", "edit.txt", "gone.txt", "new file.txt"]
5063 );
5064 assert!(!changes.patch.contains("still here"), "{}", changes.patch);
5065 assert!(changes.stat.contains("edit.txt"), "{}", changes.stat);
5066 assert!(!changes.patch_truncated);
5067 for expected in ["-two", "+TWO", "-bye", "+fresh"] {
5068 assert!(changes.patch.contains(expected), "{}", changes.patch);
5069 }
5070 assert!(!changes.patch.contains("skip"), "{}", changes.patch);
5071 assert_eq!(git_output(&repo, &["rev-parse", "HEAD"]), head);
5072 assert_eq!(git_output(&repo, &["ls-files", "--stage"]), index);
5073
5074 let cut = repo.work_tree_changes_since(&before, 40).expect("changes");
5075 assert!(cut.patch_truncated);
5076 assert!(cut.patch.len() <= 40);
5077 assert_eq!(cut.names, changes.names);
5078
5079 // Back at the snapshot: nothing differs, and nothing is invented.
5080 std::fs::write(ws.join(".gitignore"), b"ignored/\n").unwrap();
5081 std::fs::write(ws.join("edit.txt"), b"one\ntwo\n").unwrap();
5082 std::fs::write(ws.join("gone.txt"), b"bye\n").unwrap();
5083 std::fs::remove_file(ws.join("new file.txt")).unwrap();
5084 let none = repo
5085 .work_tree_changes_since(&before, 1 << 20)
5086 .expect("changes");
5087 assert_eq!(none.names, "");
5088 assert_eq!(none.patch, "");
5089 }
5090
5091 #[test]
5092 fn work_tree_changes_since_names_non_ascii_paths_as_written() {
5093 let tmp = tempdir().unwrap();
5094 let (repo, _home) = make_repo(tmp.path());
5095 let ws = repo.work_tree().to_path_buf();
5096 std::fs::write(ws.join("笔记 📝.md"), b"old\n").unwrap();
5097 let before = repo.snapshot("pre-turn:1").expect("snapshot");
5098 git_output(&repo, &["config", "core.quotePath", "true"]);
5099 std::fs::write(ws.join("笔记 📝.md"), b"new\n").unwrap();
5100
5101 let changes = repo
5102 .work_tree_changes_since(&before, 1 << 20)
5103 .expect("changes");
5104 assert_eq!(changes.names, "笔记 📝.md\n");
5105 assert!(changes.stat.contains("笔记 📝.md"), "{}", changes.stat);
5106 assert!(changes.patch.contains("b/笔记 📝.md"), "{}", changes.patch);
5107 }
5108
5109 /// A tree the repo no longer holds — the receipt outlived the object —
5110 /// is reported as absent rather than as a diff failure, so a caller can
5111 /// tell pruning from a broken repo without reading git's stderr.
5112 #[test]
5113 fn has_tree_separates_a_pruned_object_from_a_present_one() {
5114 let tmp = tempdir().unwrap();
5115 let (repo, _home) = make_repo(tmp.path());
5116 std::fs::write(repo.work_tree().join("a.txt"), b"alpha").unwrap();
5117 let taken = repo.take_snapshot("tool:call-1", None).expect("snapshot");
5118
5119 assert!(
5120 repo.has_tree(&taken.tree).expect("tree lookup"),
5121 "the snapshot's own tree resolves"
5122 );
5123 // Valid hex, never written: exactly what a pruned receipt names.
5124 let pruned = SnapshotId::parse(&"deadbeef".repeat(5)).unwrap();
5125 assert!(!repo.has_tree(&pruned).expect("missing tree lookup"));
5126 }
5127
5128 #[test]
5129 fn has_tree_reports_broken_repository_metadata_as_an_error() {
5130 let tmp = tempdir().unwrap();
5131 let (repo, _home) = make_repo(tmp.path());
5132 std::fs::write(repo.work_tree().join("a.txt"), b"alpha").unwrap();
5133 let taken = repo.take_snapshot("tool:call-1", None).expect("snapshot");
5134 std::fs::write(
5135 repo.git_dir().join("HEAD"),
5136 b"invalid snapshot repository metadata\n",
5137 )
5138 .unwrap();
5139 let error = repo
5140 .has_tree(&taken.tree)
5141 .expect_err("broken repo is not pruning");
5142 assert_eq!(error.kind(), io::ErrorKind::Other);
5143 }
5144
5145 /// A patch larger than the caller's bound is cut on a char boundary and
5146 /// reported as cut, so a client never receives half a character.
5147 #[test]
5148 fn patch_between_cuts_an_over_long_patch_on_a_char_boundary() {
5149 let tmp = tempdir().unwrap();
5150 let (repo, _home) = make_repo(tmp.path());
5151 std::fs::write(repo.work_tree().join("d.txt"), "start\n").unwrap();
5152 let before = repo.snapshot("tool:call-1").expect("snapshot");
5153 let long = format!("{}\n", "汉字宽字符行".repeat(400));
5154 std::fs::write(repo.work_tree().join("d.txt"), long).unwrap();
5155 let after = repo.snapshot("post-tool:call-1").expect("snapshot");
5156
5157 let (patch, truncated) = repo
5158 .patch_between(&before, &after, "d.txt", 64)
5159 .expect("patch");
5160 assert!(truncated, "a 64-byte bound must cut this patch");
5161 assert!(patch.len() <= 64, "{} bytes kept", patch.len());
5162 assert!(patch.is_char_boundary(patch.len()));
5163
5164 let (whole, not_truncated) = repo
5165 .patch_between(&before, &after, "d.txt", 1 << 20)
5166 .expect("patch");
5167 assert!(!not_truncated);
5168 assert!(whole.contains("汉字宽字符行"), "{whole}");
5169 }
5170
5171 #[test]
5172 fn run_git_drains_output_larger_than_the_pipe_buffer() {
5173 let tmp = tempdir().unwrap();
5174 let (repo, _home) = make_repo(tmp.path());
5175 // ~5000 paths is well past the 64 KiB OS pipe buffer: output of this
5176 // size is only reachable when the pipes are drained while the child
5177 // runs. A bounded read that only starts after the child exits would
5178 // deadlock the child on its own output and die at the command
5179 // timeout instead of returning the tree listing.
5180 for i in 0..5000 {
5181 std::fs::write(repo.work_tree().join(format!("file_{i:05}.txt")), b"x").unwrap();
5182 }
5183 let id = repo.snapshot("large-output").expect("snapshot");
5184 let paths = repo
5185 .tree_paths(id.as_str())
5186 .expect("tree_paths must drain output instead of timing out");
5187 assert!(
5188 paths.len() >= 5000,
5189 "expected every file in the tree listing, got {}",
5190 paths.len()
5191 );
5192 }
5193 }
5194
5195 /// The bounded-git tests drive the core with real children, so they need a
5196 /// POSIX shell; the timeout pin also depends on wall-clock behavior.
5197 #[cfg(all(test, unix))]
5198 mod bounded_git_tests {
5199 use super::*;
5200
5201 #[test]
5202 fn bounded_git_times_out_a_wedged_child_and_reports_timed_out() {
5203 // A child that never exits stands in for a wedged git (stalled
5204 // mount, hung hook): the call must come back with a TimedOut error
5205 // promptly instead of blocking the turn pipeline forever.
5206 let started = std::time::Instant::now();
5207 let mut wedged = std::process::Command::new("sh");
5208 wedged.arg("-c").arg("sleep 30");
5209 let err = run_bounded_git_with_timeout(&mut wedged, "sleep", Duration::from_millis(250))
5210 .expect_err("a wedged child must hit the bound");
5211 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
5212 assert!(
5213 err.to_string().contains("timed out after"),
5214 "the error must report the bound; got {err}"
5215 );
5216 let elapsed = started.elapsed();
5217 assert!(
5218 elapsed < Duration::from_secs(15),
5219 "the bound must be enforced promptly; took {elapsed:?}"
5220 );
5221 }
5222
5223 #[test]
5224 fn bounded_git_returns_promptly_when_a_grandchild_holds_the_pipes() {
5225 // The direct child (sh) exits after the echo; the backgrounded
5226 // sleep inherits both pipes and holds them for 30s. The call must
5227 // still return promptly with the output captured before the grace,
5228 // annotated on stderr — not wait out the grandchild.
5229 let started = std::time::Instant::now();
5230 let mut sh = std::process::Command::new("sh");
5231 sh.arg("-c").arg("echo bounded-git-grandchild; sleep 30 &");
5232 let output = run_bounded_git(&mut sh, "sh").expect("sh must succeed");
5233 let elapsed = started.elapsed();
5234 assert!(output.status.success());
5235 assert!(
5236 String::from_utf8_lossy(&output.stdout).contains("bounded-git-grandchild"),
5237 "output captured before the grace must survive: {:?}",
5238 output.stdout
5239 );
5240 assert!(
5241 String::from_utf8_lossy(&output.stderr)
5242 .contains("git output pipes did not close after git exited"),
5243 "the partial-output note must explain the early return: {:?}",
5244 output.stderr
5245 );
5246 assert!(
5247 elapsed < Duration::from_secs(15),
5248 "a pipe-holding grandchild must not hold the call past the grace; took {elapsed:?}"
5249 );
5250 }
5251
5252 #[test]
5253 fn hash_regular_file_nofollow_matches_sha256_and_refuses_symlinks() {
5254 let tmp = tempfile::tempdir().unwrap();
5255 let file = tmp.path().join("payload.bin");
5256 let payload = vec![0x5a_u8; 131_072 + 17];
5257 std::fs::write(&file, &payload).unwrap();
5258 assert_eq!(
5259 hash_regular_file_nofollow(&file).unwrap(),
5260 codewhale_runtime::hashing::sha256_hex(&payload)
5261 );
5262 #[cfg(unix)]
5263 {
5264 let link = tmp.path().join("link.bin");
5265 std::os::unix::fs::symlink(&file, &link).unwrap();
5266 assert!(hash_regular_file_nofollow(&link).is_err());
5267 }
5268 }
5269 }
5270
5270 lines RUST