From bbd92b21e1e80135c258e139676de3575f2f0188 Mon Sep 17 00:00:00 2001 From: Vincent Date: Fri, 24 Jul 2026 13:20:13 -0400 Subject: [PATCH 1/3] chore(cli): remove data-loss surface and refuse destructive moves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stop-the-bleeding for verified data-loss paths (deeper behavior fixes for revise rollback and stash deletion capture are tracked separately): - move --force removed: disk rename ran before the tracking update, which always fails on a tracked destination — the destination file was deleted from disk, unrecoverable for add-only/untracked targets. - move now refuses ANY existing file at the resolved destination, tracked or untracked — fs::rename replaced it silently with exit 0. Moving into an existing directory still works (the check runs on the resolved / path). Run-level regression tests cover the untracked-destination, tracked-destination, and move-into-directory cases. - stash --include-untracked/-u removed: copied untracked files into the stash sidecar but never cleaned them from the working copy, while printing 'restored to clean state'. Untracked files are now simply left alone (suite 06 pins the behavior and rejects the removed flag). - memory new --id errors when the id already exists instead of silently replacing a possibly-attested memory; regression test asserts the original content survives. Follow-up: fold the existence check into the vault_store transaction to close the check-then-write window. Verified kept: view switch --stash works end-to-end for modified files; it inherits stash's missing deletion capture (behavior-fix PR). --- atomic-cli/src/commands/memory/new.rs | 72 ++++++++++++ atomic-cli/src/commands/mv.rs | 151 ++++++++++++++++++------- atomic-cli/src/commands/stash.rs | 78 ++----------- atomic-cli/src/commands/view/switch.rs | 2 +- tests/harness/06_tags_and_stash.sh | 21 ++-- 5 files changed, 206 insertions(+), 118 deletions(-) diff --git a/atomic-cli/src/commands/memory/new.rs b/atomic-cli/src/commands/memory/new.rs index edc5f135..017873f0 100644 --- a/atomic-cli/src/commands/memory/new.rs +++ b/atomic-cli/src/commands/memory/new.rs @@ -105,6 +105,21 @@ impl Command for MemoryNew { let id = self.id.clone().unwrap_or_else(generate_ulid_lowercased); let vault_path = bridge::normalize_memory_path(&id); + // Refuse to overwrite an existing memory: the entry may be attested, + // and vault_store would silently replace it while the old attestation + // keeps signing the previous content. + if repo + .vault_retrieve(&vault_path) + .map_err(CliError::Repository)? + .is_some() + { + return Err(CliError::InvalidArgument { + message: format!( + "memory '{id}' already exists at .vault/{vault_path}; choose a different --id" + ), + }); + } + // Build the frontmatter SPINE as FLAT SCALAR/array fields only (so it // survives yaml_frontmatter_to_json round-trip). Do NOT write // attributedTo/proof/contentHash — attest fills those. createdAt is @@ -304,4 +319,61 @@ mod tests { assert_eq!(node.derived_from[0], "urn:atomic:intent:demo-1"); assert!(node.text.contains("health-check timeout")); } + + #[test] + #[serial_test::serial] + fn test_new_refuses_duplicate_id() { + struct DirGuard { + original: std::path::PathBuf, + } + impl DirGuard { + fn new() -> Self { + Self { + original: std::env::current_dir() + .unwrap_or_else(|_| std::path::PathBuf::from("/")), + } + } + } + impl Drop for DirGuard { + fn drop(&mut self) { + let _ = std::env::set_current_dir(&self.original); + } + } + + let _guard = DirGuard::new(); + let dir = tempdir().unwrap(); + { + let repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + } + std::env::set_current_dir(dir.path()).unwrap(); + + let first = MemoryNew { + kind: "constraint".into(), + about: vec![], + derived_from: vec![], + text: Some("original fact".into()), + id: Some("dup01".into()), + status: "active".into(), + }; + first.run().expect("first create succeeds"); + + let overwrite = MemoryNew { + kind: "preference".into(), + about: vec![], + derived_from: vec![], + text: Some("REPLACED".into()), + id: Some("dup01".into()), + status: "active".into(), + }; + let err = overwrite.run().expect_err("duplicate id must be rejected"); + assert!( + err.to_string().contains("already exists"), + "unexpected error: {err}" + ); + + let on_disk = std::fs::read_to_string(dir.path().join(".vault/memory/dup01.md")).unwrap(); + assert!(on_disk.contains("original fact")); + assert!(!on_disk.contains("REPLACED")); + } } diff --git a/atomic-cli/src/commands/mv.rs b/atomic-cli/src/commands/mv.rs index a403b995..69711ff6 100644 --- a/atomic-cli/src/commands/mv.rs +++ b/atomic-cli/src/commands/mv.rs @@ -15,7 +15,6 @@ //! //! Options: //! -n, --dry-run Show what would be moved without doing it -//! -f, --force Force move even if destination exists //! -h, --help Print help information //! ``` //! @@ -75,7 +74,6 @@ use crate::output::{print_hint, print_success, print_warning}; /// # Options /// /// - `--dry-run` / `-n`: Preview what would be moved -/// - `--force` / `-f`: Force move even if destination exists (overwrite tracking) #[derive(Parser, Debug, Clone)] #[command(name = "move")] #[derive(Default)] @@ -98,14 +96,6 @@ pub struct Move { /// modify the repository or filesystem. #[arg(short = 'n', long = "dry-run")] pub dry_run: bool, - - /// Force move even if destination tracking exists. - /// - /// This will overwrite the destination's tracking entry if it exists. - /// The destination file on disk is NOT overwritten unless you explicitly - /// remove it first. - #[arg(short = 'f', long = "force")] - pub force: bool, } impl Move { @@ -115,7 +105,6 @@ impl Move { source: source.into(), destination: destination.into(), dry_run: false, - force: false, } } @@ -125,12 +114,6 @@ impl Move { self } - /// Builder: set the force flag. - pub fn with_force(mut self, force: bool) -> Self { - self.force = force; - self - } - /// Normalize a path relative to the repository root. fn normalize_path(&self, repo_root: &Path, path: &str) -> CliResult { let p = Path::new(path); @@ -217,17 +200,32 @@ impl Command for Move { return Err(CliError::FileNotFound { path: source_path }); } - // Check if destination is already tracked (unless force) - if !self.force - && repo - .is_tracked(&destination) - .map_err(CliError::Repository)? + // A tracked destination is always an error: the tracking layer + // rejects it anyway, and forcing past it destroyed the destination + // file on disk (the old --force flag was removed for that reason). + if repo + .is_tracked(&destination) + .map_err(CliError::Repository)? { return Err(CliError::FileAlreadyTracked { path: PathBuf::from(&destination), }); } + // Refuse to overwrite ANY existing file at the resolved destination, + // tracked or not — fs::rename replaces it silently and the previous + // content is unrecoverable. (Moving INTO an existing directory is + // fine: resolve_destination already appended the source filename.) + let destination_disk = repo_root.join(&destination); + if destination_disk.exists() { + return Err(CliError::InvalidArgument { + message: format!( + "destination '{}' already exists on disk; move it away or choose another name", + destination + ), + }); + } + // Dry run mode if self.dry_run { println!("Would move: {} → {}", source, destination); @@ -286,7 +284,6 @@ mod tests { assert_eq!(cmd.source, "old.rs"); assert_eq!(cmd.destination, "new.rs"); assert!(!cmd.dry_run); - assert!(!cmd.force); } #[test] @@ -295,7 +292,6 @@ mod tests { assert!(cmd.source.is_empty()); assert!(cmd.destination.is_empty()); assert!(!cmd.dry_run); - assert!(!cmd.force); } #[test] @@ -304,22 +300,13 @@ mod tests { assert!(cmd.dry_run); } - #[test] - fn test_move_with_force() { - let cmd = Move::new("old.rs", "new.rs").with_force(true); - assert!(cmd.force); - } - #[test] fn test_move_builder_chain() { - let cmd = Move::new("src/old.rs", "src/new.rs") - .with_dry_run(true) - .with_force(true); + let cmd = Move::new("src/old.rs", "src/new.rs").with_dry_run(true); assert_eq!(cmd.source, "src/old.rs"); assert_eq!(cmd.destination, "src/new.rs"); assert!(cmd.dry_run); - assert!(cmd.force); } // Path Resolution Tests @@ -370,15 +357,12 @@ mod tests { #[test] fn test_move_clone() { - let cmd = Move::new("old.rs", "new.rs") - .with_dry_run(true) - .with_force(true); + let cmd = Move::new("old.rs", "new.rs").with_dry_run(true); let cloned = cmd.clone(); assert_eq!(cloned.source, cmd.source); assert_eq!(cloned.destination, cmd.destination); assert_eq!(cloned.dry_run, cmd.dry_run); - assert_eq!(cloned.force, cmd.force); } // Normalize Path Tests @@ -409,4 +393,95 @@ mod tests { let result = cmd.normalize_path(temp.path(), "/completely/different/path.rs"); assert!(result.is_err()); } + + // Run-level Data-Safety Tests + + struct DirGuard { + original: PathBuf, + } + + impl DirGuard { + fn new() -> Self { + Self { + original: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")), + } + } + } + + impl Drop for DirGuard { + fn drop(&mut self) { + let _ = std::env::set_current_dir(&self.original); + } + } + + fn init_repo_with_tracked(files: &[(&str, &str)]) -> tempfile::TempDir { + let temp = tempfile::tempdir().unwrap(); + { + let _repo = atomic_repository::Repository::init(temp.path()).unwrap(); + } + for (name, content) in files { + std::fs::write(temp.path().join(name), content).unwrap(); + } + std::env::set_current_dir(temp.path()).unwrap(); + let add = crate::commands::add::Add::new() + .with_files(files.iter().map(|(n, _)| n.to_string()).collect::>()); + add.run().unwrap(); + temp + } + + #[test] + #[serial_test::serial] + fn test_move_refuses_existing_untracked_destination() { + let _guard = DirGuard::new(); + let temp = init_repo_with_tracked(&[("src.txt", "SOURCE")]); + std::fs::write(temp.path().join("dest.txt"), "PRECIOUS-UNTRACKED").unwrap(); + + let result = Move::new("src.txt", "dest.txt").run(); + + assert!(result.is_err(), "move onto an existing file must fail"); + let dest = std::fs::read_to_string(temp.path().join("dest.txt")).unwrap(); + assert_eq!(dest, "PRECIOUS-UNTRACKED", "destination must be untouched"); + let src = std::fs::read_to_string(temp.path().join("src.txt")).unwrap(); + assert_eq!(src, "SOURCE", "source must still exist"); + } + + #[test] + #[serial_test::serial] + fn test_move_refuses_tracked_destination() { + let _guard = DirGuard::new(); + let temp = init_repo_with_tracked(&[("a.txt", "A"), ("b.txt", "TRACKED-B")]); + + let result = Move::new("a.txt", "b.txt").run(); + + assert!(result.is_err(), "move onto a tracked file must fail"); + assert_eq!( + std::fs::read_to_string(temp.path().join("b.txt")).unwrap(), + "TRACKED-B" + ); + assert_eq!( + std::fs::read_to_string(temp.path().join("a.txt")).unwrap(), + "A" + ); + } + + #[test] + #[serial_test::serial] + fn test_move_into_existing_directory_works() { + let _guard = DirGuard::new(); + let temp = init_repo_with_tracked(&[("file.txt", "CONTENT")]); + std::fs::create_dir(temp.path().join("sub")).unwrap(); + + let result = Move::new("file.txt", "sub").run(); + + assert!( + result.is_ok(), + "move into a directory failed: {:?}", + result.err() + ); + assert_eq!( + std::fs::read_to_string(temp.path().join("sub/file.txt")).unwrap(), + "CONTENT" + ); + assert!(!temp.path().join("file.txt").exists()); + } } diff --git a/atomic-cli/src/commands/stash.rs b/atomic-cli/src/commands/stash.rs index 51df971b..ff55e2aa 100644 --- a/atomic-cli/src/commands/stash.rs +++ b/atomic-cli/src/commands/stash.rs @@ -113,10 +113,6 @@ pub struct Stash { #[arg(short, long, global = true)] pub message: Option, - /// Include untracked files in the stash. - #[arg(short = 'u', long, global = true)] - pub include_untracked: bool, - /// Keep the changes in the working copy after stashing. /// /// By default, stash restores the working copy to clean state. @@ -135,10 +131,6 @@ pub enum StashSubcommand { #[arg(short, long)] message: Option, - /// Include untracked files in the stash. - #[arg(short = 'u', long)] - include_untracked: bool, - /// Keep the changes in the working copy after stashing. #[arg(short, long)] keep: bool, @@ -240,7 +232,6 @@ impl Stash { Self { command: None, message: None, - include_untracked: false, keep: false, } } @@ -251,24 +242,12 @@ impl Stash { self } - /// Builder: set the include-untracked flag. - pub fn with_include_untracked(mut self, include: bool) -> Self { - self.include_untracked = include; - self - } - /// Builder: set the keep flag. pub fn with_keep(mut self, keep: bool) -> Self { self.keep = keep; self } - /// Builder: set the --all subcommand behavior (alias for include_untracked). - pub fn with_all(mut self, all: bool) -> Self { - self.include_untracked = all; - self - } - /// Builder: set the subcommand to apply with dependencies. pub fn with_dependencies(mut self, _deps: bool) -> Self { // Dependencies flag is handled at the subcommand level; @@ -385,10 +364,9 @@ impl Stash { &self, repo: &mut Repository, message: Option, - include_untracked: bool, keep: bool, ) -> CliResult<()> { - self.run_push(repo, message, include_untracked, keep) + self.run_push(repo, message, keep) } /// Execute stash push (save changes). @@ -396,7 +374,6 @@ impl Stash { &self, repo: &mut Repository, message: Option, - include_untracked: bool, keep: bool, ) -> CliResult<()> { // Check for uncommitted changes @@ -484,23 +461,6 @@ impl Stash { } } - if include_untracked || self.include_untracked { - for entry in status.untracked() { - let p = entry.path().to_string_lossy().to_string(); - let abs = repo.root().join(&p); - if abs.is_file() { - let rel_dir = stash_dir.join( - std::path::Path::new(&p) - .parent() - .unwrap_or(std::path::Path::new("")), - ); - let _ = std::fs::create_dir_all(&rel_dir); - let _ = std::fs::copy(&abs, stash_dir.join(&p)); - stashed_paths.push(p); - } - } - } - // Write a manifest so we know which files were stashed let manifest_path = stash_dir.join("MANIFEST"); let manifest_content = stashed_paths.join("\n"); @@ -720,13 +680,11 @@ impl Command for Stash { match &self.command { None => { // Default action: push - self.run_push(&mut repo, None, self.include_untracked, self.keep) + self.run_push(&mut repo, None, self.keep) + } + Some(StashSubcommand::Push { message, keep }) => { + self.run_push(&mut repo, message.clone(), *keep) } - Some(StashSubcommand::Push { - message, - include_untracked, - keep, - }) => self.run_push(&mut repo, message.clone(), *include_untracked, *keep), Some(StashSubcommand::Pop { stash }) => self.run_pop(&mut repo, stash.as_deref()), Some(StashSubcommand::Apply { stash }) => self.run_apply(&mut repo, stash.as_deref()), Some(StashSubcommand::List) => self.run_list(&repo), @@ -750,7 +708,6 @@ mod tests { let cmd = Stash::new(); assert!(cmd.command.is_none()); assert!(cmd.message.is_none()); - assert!(!cmd.include_untracked); assert!(!cmd.keep); } @@ -767,12 +724,6 @@ mod tests { assert_eq!(cmd.message, Some("WIP auth".to_string())); } - #[test] - fn test_stash_with_include_untracked() { - let cmd = Stash::new().with_include_untracked(true); - assert!(cmd.include_untracked); - } - #[test] fn test_stash_with_keep() { let cmd = Stash::new().with_keep(true); @@ -781,13 +732,9 @@ mod tests { #[test] fn test_stash_builder_chain() { - let cmd = Stash::new() - .with_message("test") - .with_include_untracked(true) - .with_keep(true); + let cmd = Stash::new().with_message("test").with_keep(true); assert_eq!(cmd.message, Some("test".to_string())); - assert!(cmd.include_untracked); assert!(cmd.keep); } @@ -851,14 +798,11 @@ mod tests { #[test] fn test_stash_clone() { - let cmd = Stash::new() - .with_message("test") - .with_include_untracked(true); + let cmd = Stash::new().with_message("test"); let cloned = cmd.clone(); assert_eq!(cloned.message, cmd.message); - assert_eq!(cloned.include_untracked, cmd.include_untracked); assert_eq!(cloned.keep, cmd.keep); } @@ -868,18 +812,12 @@ mod tests { fn test_subcommand_push() { let subcmd = StashSubcommand::Push { message: Some("test".to_string()), - include_untracked: true, keep: false, }; match subcmd { - StashSubcommand::Push { - message, - include_untracked, - keep, - } => { + StashSubcommand::Push { message, keep } => { assert_eq!(message, Some("test".to_string())); - assert!(include_untracked); assert!(!keep); } _ => panic!("Expected Push"), diff --git a/atomic-cli/src/commands/view/switch.rs b/atomic-cli/src/commands/view/switch.rs index 925fff0d..a8a8f3df 100644 --- a/atomic-cli/src/commands/view/switch.rs +++ b/atomic-cli/src/commands/view/switch.rs @@ -134,7 +134,7 @@ impl Command for Switch { // Auto-stash: save changes before switching let stash_cmd = crate::commands::stash::Stash::new() .with_message(format!("Auto-stash before switching to {}", name)); - stash_cmd.run_push_on(&mut repo, None, false, false)?; + stash_cmd.run_push_on(&mut repo, None, false)?; } else { let dirty: Vec = status .entries() diff --git a/tests/harness/06_tags_and_stash.sh b/tests/harness/06_tags_and_stash.sh index 0ae94538..8f8d2a86 100755 --- a/tests/harness/06_tags_and_stash.sh +++ b/tests/harness/06_tags_and_stash.sh @@ -554,8 +554,12 @@ else fi # ═══════════════════════════════════════════════════════════════════════════ -begin_section "Stash: Stash with new untracked files (--include-untracked)" +begin_section "Stash: Untracked files are left in place" # ═══════════════════════════════════════════════════════════════════════════ +# +# The --include-untracked flag was removed: it copied untracked files into +# the stash sidecar but never cleaned them from the working copy, while +# still printing "clean". Untracked files now simply stay untouched. make_temp_repo "stash-untracked" init_repo @@ -568,20 +572,19 @@ record_change "base" >/dev/null 2>&1 || true create_file "newfile.txt" "I am new" overwrite_file "tracked.txt" "modified tracked" -# Stash with --include-untracked -stash_iu="$(atomic stash push --include-untracked 2>&1)" -if echo "$stash_iu" | grep -qiE "saved|stash"; then - _pass "stash with --include-untracked succeeds" -else - _pass "stash with --include-untracked completed" -fi +# The removed flag must stay removed +assert_failure "stash rejects removed --include-untracked flag" \ + atomic stash push --include-untracked -# tracked.txt should be restored +# Plain stash: tracked change saved, untracked file left alone +assert_success "stash saves tracked changes" atomic stash push assert_file_content "tracked.txt restored" "tracked.txt" "tracked" +assert_file_exists "untracked file left in working copy" "newfile.txt" # Pop and verify atomic stash pop >/dev/null 2>&1 || true assert_file_content "tracked.txt modified after pop" "tracked.txt" "modified tracked" +assert_file_content "untracked file untouched by pop" "newfile.txt" "I am new" # ═══════════════════════════════════════════════════════════════════════════ begin_section "Stash: Stash with custom message" From c2563722f8c47b8d6335c5f4adc51f021df1c464 Mon Sep 17 00:00:00 2001 From: Vincent Date: Fri, 24 Jul 2026 15:09:10 -0400 Subject: [PATCH 2/3] fix(cli): close two holes in the move destination guard The guard added alongside the --force removal used Path::exists(), which is wrong in two directions. Case-only rename regressed. On case-insensitive filesystems (APFS, NTFS) 'file.txt' exists whenever 'File.txt' does, so 'atomic move File.txt file.txt' returned exit 2. It worked before this stack -- is_tracked is case-sensitive and rename(2) handles case-only renames -- and --force was removed in the same commit, leaving no way through. Canonicalize both sides and allow the move when they resolve to the same entry. Dangling symlinks were still clobbered. exists() follows the link and reports false for a broken one, so rename destroyed it -- contradicting the guard's own 'refuse ANY existing file' comment. Use symlink_metadata. Both reproduced against the built binary before and after. Regression tests added for each; the untracked- and tracked-destination guards are unchanged and still refuse (exit 2, contents intact). --- atomic-cli/src/commands/mv.rs | 78 ++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 2 deletions(-) diff --git a/atomic-cli/src/commands/mv.rs b/atomic-cli/src/commands/mv.rs index 69711ff6..53318535 100644 --- a/atomic-cli/src/commands/mv.rs +++ b/atomic-cli/src/commands/mv.rs @@ -212,12 +212,18 @@ impl Command for Move { }); } - // Refuse to overwrite ANY existing file at the resolved destination, + // Refuse to overwrite ANY existing entry at the resolved destination, // tracked or not — fs::rename replaces it silently and the previous // content is unrecoverable. (Moving INTO an existing directory is // fine: resolve_destination already appended the source filename.) + // + // symlink_metadata rather than Path::exists(): exists() follows the + // link and reports false for a dangling symlink, which let rename + // destroy it. A case-only rename is exempt — see is_same_file. let destination_disk = repo_root.join(&destination); - if destination_disk.exists() { + if std::fs::symlink_metadata(&destination_disk).is_ok() + && !is_same_file(&source_path, &destination_disk) + { return Err(CliError::InvalidArgument { message: format!( "destination '{}' already exists on disk; move it away or choose another name", @@ -270,6 +276,26 @@ impl Command for Move { } } +/// Whether two paths that both exist refer to the same entry on disk. +/// +/// On case-insensitive filesystems (APFS, NTFS) a case-only rename such as +/// `atomic move File.txt file.txt` has a destination that "already exists" — +/// it *is* the source. Canonicalizing both sides resolves the real casing so +/// that rename is allowed through, while any genuinely distinct destination +/// still gets refused. +/// +/// Fails closed: if either side cannot be canonicalized the paths are treated +/// as distinct, so the caller refuses the move rather than overwriting. +fn is_same_file(source: &Path, destination: &Path) -> bool { + match ( + std::fs::canonicalize(source), + std::fs::canonicalize(destination), + ) { + (Ok(source), Ok(destination)) => source == destination, + _ => false, + } +} + // Tests #[cfg(test)] @@ -484,4 +510,52 @@ mod tests { ); assert!(!temp.path().join("file.txt").exists()); } + + #[test] + #[serial_test::serial] + fn test_move_allows_case_only_rename() { + let _guard = DirGuard::new(); + let temp = init_repo_with_tracked(&[("File.txt", "CONTENT")]); + + // On a case-insensitive filesystem the destination "already exists" + // because it is the source. The guard must not block that. + let result = Move::new("File.txt", "file.txt").run(); + + assert!( + result.is_ok(), + "case-only rename must be allowed: {:?}", + result.err() + ); + assert_eq!( + std::fs::read_to_string(temp.path().join("file.txt")).unwrap(), + "CONTENT" + ); + } + + #[test] + #[serial_test::serial] + #[cfg(unix)] + fn test_move_refuses_dangling_symlink_destination() { + let _guard = DirGuard::new(); + let temp = init_repo_with_tracked(&[("src.txt", "SOURCE")]); + let dangling = temp.path().join("dangling.txt"); + std::os::unix::fs::symlink(temp.path().join("no-such-target"), &dangling).unwrap(); + + let result = Move::new("src.txt", "dangling.txt").run(); + + assert!( + result.is_err(), + "move onto a dangling symlink must fail — Path::exists() reports \ + false for it, which let rename destroy the link" + ); + assert!( + std::fs::symlink_metadata(&dangling).unwrap().is_symlink(), + "the symlink must survive" + ); + assert_eq!( + std::fs::read_to_string(temp.path().join("src.txt")).unwrap(), + "SOURCE", + "source must still exist" + ); + } } From 1288b9b0587a4ff2ea1a1043e9d8a6501b72f870 Mon Sep 17 00:00:00 2001 From: Vincent Date: Mon, 27 Jul 2026 10:47:12 -0400 Subject: [PATCH 3/3] docs(cli): simplify safety comments --- atomic-cli/src/commands/memory/new.rs | 4 +--- atomic-cli/src/commands/mv.rs | 28 ++++++--------------------- 2 files changed, 7 insertions(+), 25 deletions(-) diff --git a/atomic-cli/src/commands/memory/new.rs b/atomic-cli/src/commands/memory/new.rs index 017873f0..cf2a49f4 100644 --- a/atomic-cli/src/commands/memory/new.rs +++ b/atomic-cli/src/commands/memory/new.rs @@ -105,9 +105,7 @@ impl Command for MemoryNew { let id = self.id.clone().unwrap_or_else(generate_ulid_lowercased); let vault_path = bridge::normalize_memory_path(&id); - // Refuse to overwrite an existing memory: the entry may be attested, - // and vault_store would silently replace it while the old attestation - // keeps signing the previous content. + // Do not overwrite a memory or invalidate its attestation. if repo .vault_retrieve(&vault_path) .map_err(CliError::Repository)? diff --git a/atomic-cli/src/commands/mv.rs b/atomic-cli/src/commands/mv.rs index 53318535..d0ba480e 100644 --- a/atomic-cli/src/commands/mv.rs +++ b/atomic-cli/src/commands/mv.rs @@ -200,9 +200,7 @@ impl Command for Move { return Err(CliError::FileNotFound { path: source_path }); } - // A tracked destination is always an error: the tracking layer - // rejects it anyway, and forcing past it destroyed the destination - // file on disk (the old --force flag was removed for that reason). + // The repository cannot move onto an already tracked path. if repo .is_tracked(&destination) .map_err(CliError::Repository)? @@ -212,14 +210,8 @@ impl Command for Move { }); } - // Refuse to overwrite ANY existing entry at the resolved destination, - // tracked or not — fs::rename replaces it silently and the previous - // content is unrecoverable. (Moving INTO an existing directory is - // fine: resolve_destination already appended the source filename.) - // - // symlink_metadata rather than Path::exists(): exists() follows the - // link and reports false for a dangling symlink, which let rename - // destroy it. A case-only rename is exempt — see is_same_file. + // `rename` overwrites existing files, so reject any destination entry. + // `symlink_metadata` also detects dangling symlinks. let destination_disk = repo_root.join(&destination); if std::fs::symlink_metadata(&destination_disk).is_ok() && !is_same_file(&source_path, &destination_disk) @@ -276,16 +268,9 @@ impl Command for Move { } } -/// Whether two paths that both exist refer to the same entry on disk. +/// Returns true when both paths resolve to the same entry. /// -/// On case-insensitive filesystems (APFS, NTFS) a case-only rename such as -/// `atomic move File.txt file.txt` has a destination that "already exists" — -/// it *is* the source. Canonicalizing both sides resolves the real casing so -/// that rename is allowed through, while any genuinely distinct destination -/// still gets refused. -/// -/// Fails closed: if either side cannot be canonicalized the paths are treated -/// as distinct, so the caller refuses the move rather than overwriting. +/// This allows case-only renames. Errors return false so moves fail safely. fn is_same_file(source: &Path, destination: &Path) -> bool { match ( std::fs::canonicalize(source), @@ -517,8 +502,7 @@ mod tests { let _guard = DirGuard::new(); let temp = init_repo_with_tracked(&[("File.txt", "CONTENT")]); - // On a case-insensitive filesystem the destination "already exists" - // because it is the source. The guard must not block that. + // The destination is the source on case-insensitive filesystems. let result = Move::new("File.txt", "file.txt").run(); assert!(