diff --git a/atomic-cli/src/commands/memory/new.rs b/atomic-cli/src/commands/memory/new.rs index edc5f135..cf2a49f4 100644 --- a/atomic-cli/src/commands/memory/new.rs +++ b/atomic-cli/src/commands/memory/new.rs @@ -105,6 +105,19 @@ impl Command for MemoryNew { let id = self.id.clone().unwrap_or_else(generate_ulid_lowercased); let vault_path = bridge::normalize_memory_path(&id); + // Do not overwrite a memory or invalidate its attestation. + 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 +317,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..d0ba480e 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,30 @@ 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)? + // The repository cannot move onto an already tracked path. + if repo + .is_tracked(&destination) + .map_err(CliError::Repository)? { return Err(CliError::FileAlreadyTracked { path: PathBuf::from(&destination), }); } + // `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) + { + 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); @@ -272,6 +268,19 @@ impl Command for Move { } } +/// Returns true when both paths resolve to the same entry. +/// +/// 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), + std::fs::canonicalize(destination), + ) { + (Ok(source), Ok(destination)) => source == destination, + _ => false, + } +} + // Tests #[cfg(test)] @@ -286,7 +295,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 +303,6 @@ mod tests { assert!(cmd.source.is_empty()); assert!(cmd.destination.is_empty()); assert!(!cmd.dry_run); - assert!(!cmd.force); } #[test] @@ -304,22 +311,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 +368,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 +404,142 @@ 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()); + } + + #[test] + #[serial_test::serial] + fn test_move_allows_case_only_rename() { + let _guard = DirGuard::new(); + let temp = init_repo_with_tracked(&[("File.txt", "CONTENT")]); + + // The destination is the source on case-insensitive filesystems. + 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" + ); + } } 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"