From e2c935fd46410e2ae73daa5a0a0b002858c559eb Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Sun, 18 Oct 2026 17:23:13 +0300 Subject: [PATCH 1/3] fix(repo): honor deletions and clean up plaintext in stopped merges, picks and rebases A stopped merge, pick or rebase now records the paths it wrote to disk in plaintext (.sc/CONFLICT_PLAINTEXT). Completion no longer carries such a path back from a parent when the user deleted it, abort removes the ones the restored tree does not track as plain files, and completion reads the working tree with the decided root's paths counted as tracked so an ignore rule cannot hide a file the operation added. Resolves ADR-0049 open questions 16, 18 and 19, all reproducible on full clones. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 4 + crates/repo/src/conflict_plaintext.rs | 79 +++++++++++ crates/repo/src/lib.rs | 1 + crates/repo/src/merge_state.rs | 1 + crates/repo/src/pick_state.rs | 1 + crates/repo/src/rebase_state.rs | 1 + crates/repo/src/replay.rs | 159 +++++++++++++++++++++++ crates/repo/src/repo.rs | 78 ++++++++++- docs/adr/0049-merge-on-partial-clones.md | 6 +- 9 files changed, 324 insertions(+), 6 deletions(-) create mode 100644 crates/repo/src/conflict_plaintext.rs diff --git a/CLAUDE.md b/CLAUDE.md index ea399b18..77385f62 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -238,6 +238,10 @@ transport-adjacent. The rest, imperatively: - **`sc ws harvest` lands on the currently-checked-out branch** (default the session's base; `--into` must also be checked out) — it refuses with a `sc switch` hint otherwise. +- **A stopped merge/pick/rebase lists the paths it wrote as plaintext in + `.sc/CONFLICT_PLAINTEXT`.** Protected conflict text never enters the CAS, so no + tree records it; completion treats a listed path absent from disk as deleted, + and abort removes listed paths the restored tree does not track as plain files. - **Every ref-moving or commit-creating op (including all secret/protect policy ops) is guarded against an in-progress merge/pick/rebase** — finish or abort the in-progress op first. diff --git a/crates/repo/src/conflict_plaintext.rs b/crates/repo/src/conflict_plaintext.rs new file mode 100644 index 00000000..f2b38855 --- /dev/null +++ b/crates/repo/src/conflict_plaintext.rs @@ -0,0 +1,79 @@ +//! The paths a stopped merge, cherry-pick or rebase wrote to the working tree +//! as plaintext (`.sc/CONFLICT_PLAINTEXT`, one path per line). +//! +//! A protected path's conflict text, or a clean content merge of one, is never +//! put in the CAS (ADR-0025), so no tree records that the file was written. +//! Two things need to know: completion, which would otherwise read a path the +//! user deleted from disk as "absent because the committer cannot read it" and +//! carry the parent's ciphertext back, and abort, whose removal walk only sees +//! the trees and would leave the decrypted text behind (ADR-0049 q16, q18). +//! +//! One file serves all three operations because only one can be in progress. +//! It is replaced at every stop and cleared with the operation's own state. +//! Read it only while an operation is in progress: residue from a crash is +//! otherwise inert. + +use std::collections::BTreeSet; + +use crate::error::Result; +use crate::layout::Layout; + +fn path(layout: &Layout) -> std::path::PathBuf { + layout.dot_sc.join("CONFLICT_PLAINTEXT") +} + +/// Record `paths` as written to the working tree in plaintext. An empty list +/// removes the record. +pub(crate) fn write(layout: &Layout, paths: &[String]) -> Result<()> { + if paths.is_empty() { + return clear(layout); + } + let tmp = layout.dot_sc.join("CONFLICT_PLAINTEXT.tmp"); + std::fs::write(&tmp, paths.join("\n") + "\n")?; + std::fs::rename(&tmp, path(layout))?; + Ok(()) +} + +/// The recorded paths, empty when there is no record. +pub(crate) fn read(layout: &Layout) -> Result> { + match std::fs::read_to_string(path(layout)) { + Ok(text) => Ok(text.lines().map(str::to_string).collect()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()), + Err(e) => Err(e.into()), + } +} + +/// Drop the record. +pub(crate) fn clear(layout: &Layout) -> Result<()> { + match std::fs::remove_file(path(layout)) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn write_read_clear_roundtrip() { + let root = + std::env::temp_dir().join(format!("scl-conflict-plaintext-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let layout = Layout::at(&root); + std::fs::create_dir_all(&layout.dot_sc).unwrap(); + assert!(read(&layout).unwrap().is_empty()); + write(&layout, &["a/b.txt".into(), "c.txt".into()]).unwrap(); + assert_eq!( + read(&layout).unwrap().into_iter().collect::>(), + vec!["a/b.txt", "c.txt"] + ); + write(&layout, &[]).unwrap(); + assert!(read(&layout).unwrap().is_empty(), "an empty list clears"); + write(&layout, &["x".into()]).unwrap(); + clear(&layout).unwrap(); + assert!(read(&layout).unwrap().is_empty()); + std::fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/crates/repo/src/lib.rs b/crates/repo/src/lib.rs index 42861884..b400514d 100644 --- a/crates/repo/src/lib.rs +++ b/crates/repo/src/lib.rs @@ -3,6 +3,7 @@ pub mod bucket_transport; pub(crate) mod cache; +pub(crate) mod conflict_plaintext; pub(crate) mod conflicts; pub mod diff3; pub mod error; diff --git a/crates/repo/src/merge_state.rs b/crates/repo/src/merge_state.rs index 5c997399..4f1cc033 100644 --- a/crates/repo/src/merge_state.rs +++ b/crates/repo/src/merge_state.rs @@ -110,6 +110,7 @@ pub fn clear(layout: &Layout) -> Result<()> { remove_if_exists(&merge_head_path(layout))?; remove_if_exists(&merge_conflicts_path(layout))?; remove_if_exists(&decided_root_path(layout))?; + crate::conflict_plaintext::clear(layout)?; Ok(()) } diff --git a/crates/repo/src/pick_state.rs b/crates/repo/src/pick_state.rs index f9b2f705..f5081ecf 100644 --- a/crates/repo/src/pick_state.rs +++ b/crates/repo/src/pick_state.rs @@ -147,6 +147,7 @@ pub fn clear(layout: &Layout) -> Result<()> { remove_if_exists(&pick_conflicts_path(layout))?; remove_if_exists(&decided_root_path(layout))?; remove_if_exists(&mainline_base_path(layout))?; + crate::conflict_plaintext::clear(layout)?; Ok(()) } diff --git a/crates/repo/src/rebase_state.rs b/crates/repo/src/rebase_state.rs index 9015f38f..97d1aa5e 100644 --- a/crates/repo/src/rebase_state.rs +++ b/crates/repo/src/rebase_state.rs @@ -230,6 +230,7 @@ pub fn clear(layout: &Layout) -> Result<()> { remove_if_exists(&state_path(layout))?; remove_if_exists(&conflicts_path(layout))?; remove_if_exists(&decided_root_path(layout))?; + crate::conflict_plaintext::clear(layout)?; Ok(()) } diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index fc99c775..32504ba0 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -657,6 +657,9 @@ impl Repo { None, )?; } + if let Some(root) = sidecar_roots.first() { + self.remove_conflict_plaintext(*root)?; + } self.remove_conflict_sidecars( &crate::pick_state::read_conflicts(&self.layout)?, &sidecar_roots, @@ -1304,6 +1307,7 @@ impl Repo { None, )? }; + self.remove_conflict_plaintext(snap.root)?; self.remove_conflict_sidecars( &crate::rebase_state::read_conflicts(&self.layout)?, &[snap.root], @@ -2486,6 +2490,161 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// Base has a plain `secret/a.txt`. `main` then protects `secret/` (so the + /// file becomes ciphertext) while `work` deletes the plain file. Picking + /// `work` onto `main` is a delete-versus-modify conflict on a protected + /// path. Returns the repo, its root, the recipient key and `main`'s tip. + fn protected_delete_modify_pick( + tag: &str, + ) -> (Repo, std::path::PathBuf, scl_crypto::SecretKey) { + let root = tmp_root(tag); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"l1\nl2\nl3\n").unwrap(); + std::fs::write(root.join("keep.txt"), b"k\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + repo.switch("work").unwrap(); + std::fs::remove_file(root.join("secret/a.txt")).unwrap(); + repo.commit("me", "work deletes").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + let err = repo + .cherry_pick("work", "me", Some(&alice_sk), None) + .unwrap_err(); + assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); + assert!( + root.join("secret/a.txt").exists(), + "plaintext surviving side" + ); + (repo, root, alice_sk) + } + + /// ADR-0049 q16: such a conflict resolved by deleting the file stays + /// deleted at completion. The plaintext conflict path is not in the decided + /// root, so the absent-protected carry used to bring the parent's + /// ciphertext back. + #[test] + fn resolving_a_protected_delete_modify_conflict_to_deletion_sticks() { + let (repo, root, alice_sk) = protected_delete_modify_pick("cp-prot-delete"); + repo.resolve_path( + "secret/a.txt", + crate::conflicts::ResolveSide::Theirs, + Some(&alice_sk), + ) + .unwrap(); + assert!(!root.join("secret/a.txt").exists()); + let id = repo.commit("me", "pick: delete").unwrap(); + let snap = repo.snapshot(&id).unwrap(); + let arc = repo.vfs().store(); + let mut store = arc.lock().unwrap(); + let entries = worktree::tree_file_entries_with_perms(&mut store, snap.root).unwrap(); + assert!( + !entries.contains_key("secret/a.txt"), + "the deletion must stick, got {:?}", + entries.keys().collect::>() + ); + assert!(entries.contains_key("keep.txt")); + drop(store); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// ADR-0049 q18: aborting that pick removes the decrypted conflict text it + /// wrote. Abort has no identity, so the restored protected file is skipped, + /// and materialize neither writes nor deletes a skipped path. + #[test] + fn aborting_a_protected_conflict_leaves_no_plaintext_on_disk() { + let (repo, root, _sk) = protected_delete_modify_pick("cp-prot-abort"); + repo.cherry_pick_abort().unwrap(); + assert!(!repo.pick_in_progress()); + assert!( + !root.join("secret/a.txt").exists(), + "decrypted conflict text must not outlive the abort" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// ADR-0049 q18, the variant where the conflict text lives in neither the + /// original nor the decided root: base has a plain `secret/a.txt`, `main` + /// deletes it, `work` protects `secret/` and edits it. The pick stops on a + /// delete-versus-modify conflict and writes the decrypted text to disk; + /// abort must remove it. + #[test] + fn aborting_a_conflict_whose_text_is_in_no_root_leaves_no_plaintext() { + let root = tmp_root("cp-prot-abort2"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"l1\nl2\nl3\n").unwrap(); + std::fs::write(root.join("keep.txt"), b"k\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::remove_file(root.join("secret/a.txt")).unwrap(); + repo.commit("me", "main deletes").unwrap(); + repo.switch("work").unwrap(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"EDITED\nl2\nl3\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + let err = repo + .cherry_pick("work", "me", Some(&alice_sk), None) + .unwrap_err(); + assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); + assert!(root.join("secret/a.txt").exists(), "plaintext on disk"); + + repo.cherry_pick_abort().unwrap(); + assert!( + !root.join("secret/a.txt").exists(), + "decrypted conflict text must not outlive the abort" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// ADR-0049 q19: a file the picked commit adds that the completion parent's + /// `.scignore` covers is part of the pick's outcome, so completing the pick + /// keeps it. Ignore rules hide untracked files only, and the decided root + /// says the file is tracked. + #[test] + fn completing_a_conflicted_pick_keeps_an_added_file_the_parent_ignores() { + let root = tmp_root("cp-ignored-added"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("a.txt"), b"l1\nl2\nl3\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join(".scignore"), b"gen/\n").unwrap(); + std::fs::write(root.join("a.txt"), b"OURS\nl2\nl3\n").unwrap(); + repo.commit("me", "main ignores gen and edits").unwrap(); + repo.switch("work").unwrap(); + std::fs::create_dir_all(root.join("gen")).unwrap(); + std::fs::write(root.join("gen/x.txt"), b"generated\n").unwrap(); + std::fs::write(root.join("a.txt"), b"THEIRS\nl2\nl3\n").unwrap(); + repo.commit("me", "work adds gen and edits").unwrap(); + repo.switch("main").unwrap(); + + let err = repo.cherry_pick("work", "me", None, None).unwrap_err(); + assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); + assert!(root.join("gen/x.txt").exists(), "the pick laid it out"); + repo.resolve_path("a.txt", crate::conflicts::ResolveSide::Ours, None) + .unwrap(); + let id = repo.commit("me", "pick").unwrap(); + let snap = repo.snapshot(&id).unwrap(); + let arc = repo.vfs().store(); + let mut store = arc.lock().unwrap(); + let entries = worktree::tree_file_entries_with_perms(&mut store, snap.root).unwrap(); + assert!( + entries.contains_key("gen/x.txt"), + "the added file must be kept, got {:?}", + entries.keys().collect::>() + ); + drop(store); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + #[test] fn cherry_pick_protected_conflict_writes_plaintext_markers_worktree_only() { // Same-line edits of secret/a.txt on both sides: the pick conflicts. diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index f9b501da..446e7473 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -180,6 +180,28 @@ impl Repo { } } + /// `tracked`, plus the paths a stopped operation's decided root holds. A + /// file that root holds is part of the outcome, so an ignore rule must not + /// hide it from the completion's working-tree read (ADR-0049 q19). + fn with_decided_paths( + &self, + mut tracked: std::collections::BTreeSet, + decided_root: Option, + ) -> Result> { + let Some(root) = decided_root else { + return Ok(tracked); + }; + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + let ids = if self.promisor()?.is_some() { + worktree::tree_file_ids_sparse(&mut store, root, &self.sparse_spec()?)? + } else { + worktree::tree_file_ids(&mut store, root)? + }; + tracked.extend(ids.into_keys()); + Ok(tracked) + } + /// The pick/rebase-completion snapshot assembly, extracted from /// `commit`'s pick-completion arm (P19 Task 2 groundwork) so /// `Repo::rebase_continue` can reuse it verbatim: read the resolved @@ -212,7 +234,9 @@ impl Repo { // filled (a rebase accumulator that carried it): fill it before the // tracked paths are read from it (lazy partial clones only). self.ensure_view(self.snapshot(&parent)?.root, &self.sparse_spec()?)?; - let files = worktree::read_worktree(&self.layout, &self.tracked_paths_at(Some(parent))?)?; + let tracked = + self.with_decided_paths(self.tracked_paths_at(Some(parent))?, decided_root)?; + let files = worktree::read_worktree(&self.layout, &tracked)?; // Pick/rebase completion opens its own main cache. It saves right // after `snapshot_files` (before the caller moves the ref): the sealed // blobs are already in the store via `write_tree_with_perms`, so a @@ -636,9 +660,18 @@ impl Repo { sources.push(entries); } + // Paths the stopped operation wrote in plaintext. One of them that + // is absent from disk now was deleted by the user (resolving a + // delete-versus-modify conflict to the deleted side): it must not + // be carried back from a parent (ADR-0049 q16). + let conflict_plaintext = if merge_head.is_some() || pick_head.is_some() { + crate::conflict_plaintext::read(&self.layout)? + } else { + Default::default() + }; for entries in sources { for (path, (blob_id, mode, perms)) in entries { - if on_disk.contains(&path) { + if on_disk.contains(&path) || conflict_plaintext.contains(&path) { continue; } let still_protected = perms & scl_core::PROTECTED != 0 @@ -842,7 +875,8 @@ impl Repo { message, )?, _ => { - let files = worktree::read_worktree(&self.layout, &self.tracked_paths()?)?; + let tracked = self.with_decided_paths(self.tracked_paths()?, decided_root)?; + let files = worktree::read_worktree(&self.layout, &tracked)?; let mut c = self.open_protected_cache()?; let id = self.snapshot_files( files, @@ -1788,6 +1822,15 @@ impl Repo { // so cache trouble never aborts the conflict write-out (P33 Task 7). cache.save_best_effort(); } + // Record what is about to be written in plaintext, before writing it: + // completion and abort need the list (see `conflict_plaintext`). + crate::conflict_plaintext::write( + &self.layout, + &to_encrypt + .iter() + .map(|(p, ..)| p.clone()) + .collect::>(), + )?; for (path, bytes, _mode, _recipients) in to_encrypt { let full = worktree::safe_join(&self.layout.root, path)?; if let Some(parent) = full.parent() { @@ -1805,6 +1848,32 @@ impl Repo { Ok(conflict_root) } + /// Remove the plaintext a stopped merge, pick or rebase wrote for + /// protected content (`conflict_plaintext`), except a path the restored + /// tree tracks as a plain file: that one is the user's own. Call it after + /// the restore. A lookup that fails keeps the file: it would be a path the + /// restored tree may track. + pub(crate) fn remove_conflict_plaintext(&self, restored_root: ObjectId) -> Result<()> { + let paths = crate::conflict_plaintext::read(&self.layout)?; + if paths.is_empty() { + return Ok(()); + } + let partial = self.promisor()?.is_some(); + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + for path in paths { + let remove = match worktree::tree_entry_at(&mut store, restored_root, &path, partial) { + Ok(None) => true, + Ok(Some((_, _, perms))) => perms & scl_core::PROTECTED != 0, + Err(_) => false, + }; + if remove { + let _ = std::fs::remove_file(worktree::safe_join(&self.layout.root, &path)?); + } + } + Ok(()) + } + /// Remove the `.theirs` sidecars a stopped merge, pick or rebase /// wrote for `paths`, except a file any of `roots` tracks: that one is the /// user's own and was just restored. A failed lookup counts as tracked: a @@ -1882,6 +1951,9 @@ impl Repo { None, )?; } + if let Some(root) = sidecar_roots.first() { + self.remove_conflict_plaintext(*root)?; + } self.remove_conflict_sidecars( &crate::merge_state::read_conflicts(&self.layout)?, &sidecar_roots, diff --git a/docs/adr/0049-merge-on-partial-clones.md b/docs/adr/0049-merge-on-partial-clones.md index 97443641..cefea0a6 100644 --- a/docs/adr/0049-merge-on-partial-clones.md +++ b/docs/adr/0049-merge-on-partial-clones.md @@ -178,10 +178,10 @@ Replay is a three-way merge with a different base, and `replay_commit` is the on 13. **Wrap sets differ between a clean and a conflicted completion.** A clean partial merge that carried a subtree keeps the union of ours, theirs and base wraps; a conflicted completion keeps ours and theirs, as a full clone does. No blob whose wrap exists only in base can reach the decided root, so nothing readable is lost, but the same merge can record a different `protection.wrapped` depending on whether it conflicted. A recipient revoked on both branches whose base wrap would otherwise come back is the visible case. Decide whether completion should read the merge base's wraps too. 14. **A sidecar next to an exact-file protection rule.** A protected binary conflict at `secret.bin` writes plaintext `secret.bin.theirs`; if the rule covers exactly `secret.bin`, the sidecar matches no rule and a later commit would read it back as a plain file. This predates partial clones (the scanner is the only guard). `sc resolve` removes it; a commit that leaves it behind should probably refuse. 15. **State durability.** `merge_state` renames without syncing, as the other state files do. A power loss between the decided-root write and `MERGE_HEAD` leaves a state that partial completion refuses and `merge --abort` clears. -16. **A protected delete-versus-modify conflict resolved to the absent side.** The conflict path is not in the decided root (protected conflict plaintext lives on disk), so after `sc resolve` deletes the working file, completion's absent-protected carry restores it from the first parent. The full-clone completion runs the same code (`snapshot_files`, "explicit deletion of a protected file is a future operation"), so the partial path matches it. Recording a decided deletion in the merge state would fix both. +16. **A protected delete-versus-modify conflict resolved to the absent side.** *Resolved:* a stopped merge, pick or rebase records the paths it wrote to disk in plaintext in `.sc/CONFLICT_PLAINTEXT` (`conflict_plaintext.rs`), and completion does not carry such a path back from a parent when it is absent from disk. The conflict path is not in the decided root (protected conflict plaintext lives on disk only), so before this the absent-protected carry restored it from the first parent, on full clones too. Test `resolving_a_protected_delete_modify_conflict_to_deletion_sticks`. 17. **Single-tip graft keeps what the built side decided.** `graft_out_of_sparse` carries an out-of-view file standing where the view expects a directory, unless the built side already holds that name (a file replaced by a directory in an ordinary commit). -18. **Abort can leave decrypted conflict plaintext behind.** A protected delete-versus-modify conflict (base plain `src/x`, ours deleted it, theirs edits and protects it) writes the decrypted conflict text straight to disk. Neither the original root nor the decided root contains the path, so the abort's removal walk misses it and clears the state. This is the full-clone behaviour; decision 10 does not change it. -19. **Completion can drop a newly tracked ignored file.** The ignore exemptions come from the completion parent's tracked paths. A picked commit that adds a plain in-view file the parent's `.scignore` covers, and also conflicts elsewhere, loses that file at completion. Also the full-clone behaviour. +18. **Abort can leave decrypted conflict plaintext behind.** *Resolved:* abort removes every recorded plaintext path the restored tree does not track as a plain file. The case was a protected delete-versus-modify conflict whose text is in neither the original nor the decided root, so the abort's removal walk never saw it. Test `aborting_a_conflict_whose_text_is_in_no_root_leaves_no_plaintext`. +19. **Completion can drop a newly tracked ignored file.** *Resolved:* completion reads the working tree with the decided root's paths counted as tracked, so an ignore rule cannot hide a file the operation itself added. Test `completing_a_conflicted_pick_keeps_an_added_file_the_parent_ignores`. 20. **A stopped pick or rebase without its decided root.** `PICK_DECIDED_ROOT` and `REBASE_DECIDED_ROOT` are written before the state's in-progress signal, so the state cannot normally be missing. If it is (a lost file, a power loss before the data reached disk), a partial clone's completion refuses, because grafting from the tip would keep the old out-of-view content; `--abort` still works. ## Alternatives considered From 8fa13eb341175ac28d457809955567c72ff2a1d3 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Sun, 18 Oct 2026 17:31:14 +0300 Subject: [PATCH 2/3] fix(repo): harden the conflict-plaintext record - abort propagates a failure to remove a recorded plaintext file instead of discarding it, so the stopped operation stays retryable - completion counts recorded plaintext paths as tracked, so a user's resolution of a plaintext-only conflict path survives an ignore rule - the record is NUL-separated so a filename with a newline round-trips Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/conflict_plaintext.rs | 17 ++++- crates/repo/src/replay.rs | 96 ++++++++++++++++----------- crates/repo/src/repo.rs | 13 +++- 3 files changed, 85 insertions(+), 41 deletions(-) diff --git a/crates/repo/src/conflict_plaintext.rs b/crates/repo/src/conflict_plaintext.rs index f2b38855..de052a70 100644 --- a/crates/repo/src/conflict_plaintext.rs +++ b/crates/repo/src/conflict_plaintext.rs @@ -1,5 +1,6 @@ //! The paths a stopped merge, cherry-pick or rebase wrote to the working tree -//! as plaintext (`.sc/CONFLICT_PLAINTEXT`, one path per line). +//! as plaintext (`.sc/CONFLICT_PLAINTEXT`, NUL-separated: a path can hold a +//! newline but never a NUL). //! //! A protected path's conflict text, or a clean content merge of one, is never //! put in the CAS (ADR-0025), so no tree records that the file was written. @@ -29,7 +30,7 @@ pub(crate) fn write(layout: &Layout, paths: &[String]) -> Result<()> { return clear(layout); } let tmp = layout.dot_sc.join("CONFLICT_PLAINTEXT.tmp"); - std::fs::write(&tmp, paths.join("\n") + "\n")?; + std::fs::write(&tmp, paths.join("\0"))?; std::fs::rename(&tmp, path(layout))?; Ok(()) } @@ -37,7 +38,11 @@ pub(crate) fn write(layout: &Layout, paths: &[String]) -> Result<()> { /// The recorded paths, empty when there is no record. pub(crate) fn read(layout: &Layout) -> Result> { match std::fs::read_to_string(path(layout)) { - Ok(text) => Ok(text.lines().map(str::to_string).collect()), + Ok(text) => Ok(text + .split('\0') + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()), Err(e) => Err(e.into()), } @@ -69,6 +74,12 @@ mod tests { read(&layout).unwrap().into_iter().collect::>(), vec!["a/b.txt", "c.txt"] ); + write(&layout, &["odd\nname.txt".into()]).unwrap(); + assert_eq!( + read(&layout).unwrap().into_iter().collect::>(), + vec!["odd\nname.txt"], + "a newline in a path survives" + ); write(&layout, &[]).unwrap(); assert!(read(&layout).unwrap().is_empty(), "an empty list clears"); write(&layout, &["x".into()]).unwrap(); diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 32504ba0..8b524a61 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -2567,14 +2567,15 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } - /// ADR-0049 q18, the variant where the conflict text lives in neither the - /// original nor the decided root: base has a plain `secret/a.txt`, `main` - /// deletes it, `work` protects `secret/` and edits it. The pick stops on a - /// delete-versus-modify conflict and writes the decrypted text to disk; - /// abort must remove it. - #[test] - fn aborting_a_conflict_whose_text_is_in_no_root_leaves_no_plaintext() { - let root = tmp_root("cp-prot-abort2"); + /// Base has a plain `secret/a.txt`, `main` deletes it, `work` protects + /// `secret/` and edits it. Picking `work` stops on a delete-versus-modify + /// conflict whose decrypted text lives in neither the original nor the + /// decided root. With `ignore`, `main` also ignores `secret/`. + fn delete_vs_protected_edit_pick( + tag: &str, + ignore: bool, + ) -> (Repo, std::path::PathBuf, scl_crypto::SecretKey) { + let root = tmp_root(tag); let repo = Repo::init(&root).unwrap(); let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); std::fs::create_dir_all(root.join("secret")).unwrap(); @@ -2583,6 +2584,9 @@ mod tests { repo.commit("me", "base").unwrap(); repo.branch("work").unwrap(); std::fs::remove_file(root.join("secret/a.txt")).unwrap(); + if ignore { + std::fs::write(root.join(".scignore"), b"secret/\n").unwrap(); + } repo.commit("me", "main deletes").unwrap(); repo.switch("work").unwrap(); repo.protect("secret/", &[alice_pk], None).unwrap(); @@ -2594,7 +2598,13 @@ mod tests { .unwrap_err(); assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); assert!(root.join("secret/a.txt").exists(), "plaintext on disk"); + (repo, root, alice_sk) + } + /// ADR-0049 q18: abort removes that decrypted text. + #[test] + fn aborting_a_conflict_whose_text_is_in_no_root_leaves_no_plaintext() { + let (repo, root, _sk) = delete_vs_protected_edit_pick("cp-prot-abort2", false); repo.cherry_pick_abort().unwrap(); assert!( !root.join("secret/a.txt").exists(), @@ -2604,42 +2614,54 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } - /// ADR-0049 q19: a file the picked commit adds that the completion parent's - /// `.scignore` covers is part of the pick's outcome, so completing the pick - /// keeps it. Ignore rules hide untracked files only, and the decided root - /// says the file is tracked. + /// An abort that cannot remove the plaintext keeps the stopped pick, so the + /// text is not left behind with nothing to retry. + #[cfg(unix)] #[test] - fn completing_a_conflicted_pick_keeps_an_added_file_the_parent_ignores() { - let root = tmp_root("cp-ignored-added"); - let repo = Repo::init(&root).unwrap(); - std::fs::write(root.join("a.txt"), b"l1\nl2\nl3\n").unwrap(); - repo.commit("me", "base").unwrap(); - repo.branch("work").unwrap(); - std::fs::write(root.join(".scignore"), b"gen/\n").unwrap(); - std::fs::write(root.join("a.txt"), b"OURS\nl2\nl3\n").unwrap(); - repo.commit("me", "main ignores gen and edits").unwrap(); - repo.switch("work").unwrap(); - std::fs::create_dir_all(root.join("gen")).unwrap(); - std::fs::write(root.join("gen/x.txt"), b"generated\n").unwrap(); - std::fs::write(root.join("a.txt"), b"THEIRS\nl2\nl3\n").unwrap(); - repo.commit("me", "work adds gen and edits").unwrap(); - repo.switch("main").unwrap(); + fn an_abort_that_cannot_remove_the_plaintext_keeps_the_state() { + use std::os::unix::fs::PermissionsExt; + let (repo, root, _sk) = delete_vs_protected_edit_pick("cp-prot-abort-fail", false); + let dir = root.join("secret"); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap(); + // Running as a user that ignores directory permissions: nothing to test. + let can_write = std::fs::File::create(dir.join("probe")).is_ok(); + if can_write { + std::fs::remove_file(dir.join("probe")).ok(); + } else { + assert!(repo.cherry_pick_abort().is_err()); + assert!(repo.pick_in_progress(), "the state is kept for a retry"); + assert!(root.join("secret/a.txt").exists()); + } + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + if !can_write { + repo.cherry_pick_abort().unwrap(); + assert!(!root.join("secret/a.txt").exists()); + } + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } - let err = repo.cherry_pick("work", "me", None, None).unwrap_err(); - assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); - assert!(root.join("gen/x.txt").exists(), "the pick laid it out"); - repo.resolve_path("a.txt", crate::conflicts::ResolveSide::Ours, None) - .unwrap(); + /// The user's resolution of a plaintext-only conflict path is read even + /// when an ignore rule covers it: it is part of the outcome. + #[test] + fn a_resolved_plaintext_only_conflict_path_survives_an_ignore_rule() { + let (repo, root, alice_sk) = delete_vs_protected_edit_pick("cp-prot-ignored", true); + repo.resolve_path( + "secret/a.txt", + crate::conflicts::ResolveSide::Theirs, + Some(&alice_sk), + ) + .unwrap(); + assert!(root.join("secret/a.txt").exists()); let id = repo.commit("me", "pick").unwrap(); let snap = repo.snapshot(&id).unwrap(); let arc = repo.vfs().store(); let mut store = arc.lock().unwrap(); let entries = worktree::tree_file_entries_with_perms(&mut store, snap.root).unwrap(); - assert!( - entries.contains_key("gen/x.txt"), - "the added file must be kept, got {:?}", - entries.keys().collect::>() - ); + let (_, _, perms) = entries + .get("secret/a.txt") + .expect("the resolved file must be committed"); + assert_ne!(perms & scl_core::PROTECTED, 0, "sealed"); drop(store); drop(repo); std::fs::remove_dir_all(&root).ok(); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 446e7473..b59e846e 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -191,6 +191,10 @@ impl Repo { let Some(root) = decided_root else { return Ok(tracked); }; + // A path the operation wrote in plaintext is part of the outcome too, + // though no tree holds it: the user's resolution of it is read even + // under an ignore rule. An absent one stays absent. + tracked.extend(crate::conflict_plaintext::read(&self.layout)?); let store_arc = self.vfs.store(); let mut store = store_arc.lock().unwrap(); let ids = if self.promisor()?.is_some() { @@ -1868,7 +1872,14 @@ impl Repo { Err(_) => false, }; if remove { - let _ = std::fs::remove_file(worktree::safe_join(&self.layout.root, &path)?); + // Only an already-absent file is fine: any other failure must + // stop the abort before its state is cleared, or the decrypted + // text stays on disk with nothing left to retry. + match std::fs::remove_file(worktree::safe_join(&self.layout.root, &path)?) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), + } } } Ok(()) From 32bd6801bb48bdf1c74e00dec03d74eb296f843c Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Sun, 18 Oct 2026 17:35:36 +0300 Subject: [PATCH 3/3] test(repo): cover merge completion and abort with recorded plaintext Merge flavours of the protected delete-versus-modify tests (ignored resolution kept, deletion sticks, abort leaves no plaintext) and a check that an ordinary conflict records nothing. ADR-0049 q21 notes that a conflict stop overwrites an ignored or untracked file at a plaintext path. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/replay.rs | 112 +++++++++++++++++++++++ docs/adr/0049-merge-on-partial-clones.md | 2 + 2 files changed, 114 insertions(+) diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 8b524a61..b92f4c8a 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -2667,6 +2667,118 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// The merge flavour of `delete_vs_protected_edit_pick`: same history, but + /// `main` merges `work` and stops on the delete-versus-modify conflict. + fn delete_vs_protected_edit_merge( + tag: &str, + ignore: bool, + ) -> (Repo, std::path::PathBuf, scl_crypto::SecretKey) { + let root = tmp_root(tag); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"l1\nl2\nl3\n").unwrap(); + std::fs::write(root.join("keep.txt"), b"k\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::remove_file(root.join("secret/a.txt")).unwrap(); + if ignore { + std::fs::write(root.join(".scignore"), b"secret/\n").unwrap(); + } + repo.commit("me", "main deletes").unwrap(); + repo.switch("work").unwrap(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"EDITED\nl2\nl3\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + let err = repo + .merge_with_identity("work", "me", Some(&alice_sk)) + .unwrap_err(); + assert!(matches!(err, Error::MergeConflicts(1)), "got {err:?}"); + assert!(root.join("secret/a.txt").exists(), "plaintext on disk"); + (repo, root, alice_sk) + } + + /// A merge completion keeps the user's resolution of a plaintext-only + /// conflict path under an ignore rule, sealed and with both parents. + #[test] + fn a_merge_completion_keeps_a_resolved_plaintext_only_path_under_an_ignore_rule() { + let (repo, root, sk) = delete_vs_protected_edit_merge("mg-prot-ignored", true); + repo.resolve_path( + "secret/a.txt", + crate::conflicts::ResolveSide::Theirs, + Some(&sk), + ) + .unwrap(); + let id = repo.commit("me", "merge").unwrap(); + let snap = repo.snapshot(&id).unwrap(); + assert_eq!(snap.parents.len(), 2); + let arc = repo.vfs().store(); + let mut store = arc.lock().unwrap(); + let entries = worktree::tree_file_entries_with_perms(&mut store, snap.root).unwrap(); + let (_, _, perms) = entries + .get("secret/a.txt") + .expect("the resolved file must be committed"); + assert_ne!(perms & scl_core::PROTECTED, 0, "sealed"); + drop(store); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// Deleting the file while resolving that merge conflict sticks. + #[test] + fn a_merge_conflict_on_a_protected_path_honors_deletion() { + let (repo, root, _sk) = delete_vs_protected_edit_merge("mg-prot-delete", false); + std::fs::remove_file(root.join("secret/a.txt")).unwrap(); + let id = repo.commit("me", "merge").unwrap(); + let snap = repo.snapshot(&id).unwrap(); + let arc = repo.vfs().store(); + let mut store = arc.lock().unwrap(); + let entries = worktree::tree_file_entries_with_perms(&mut store, snap.root).unwrap(); + assert!(!entries.contains_key("secret/a.txt"), "the deletion sticks"); + drop(store); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// Aborting a merge removes the decrypted conflict text. + #[test] + fn aborting_a_merge_conflict_on_a_protected_path_leaves_no_plaintext() { + let (repo, root, _sk) = delete_vs_protected_edit_merge("mg-prot-abort", false); + repo.merge_abort().unwrap(); + assert!(!repo.merge_in_progress()); + assert!( + !root.join("secret/a.txt").exists(), + "decrypted conflict text must not outlive the abort" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// An ordinary conflict, with nothing protected, records no plaintext. + #[test] + fn an_unprotected_conflict_records_no_plaintext() { + let root = tmp_root("mg-plain-no-record"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("a.txt"), b"l1\nl2\nl3\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("a.txt"), b"OURS\nl2\nl3\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("a.txt"), b"THEIRS\nl2\nl3\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(1) + )); + assert!(!root.join(".sc/CONFLICT_PLAINTEXT").exists()); + repo.merge_abort().unwrap(); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + #[test] fn cherry_pick_protected_conflict_writes_plaintext_markers_worktree_only() { // Same-line edits of secret/a.txt on both sides: the pick conflicts. diff --git a/docs/adr/0049-merge-on-partial-clones.md b/docs/adr/0049-merge-on-partial-clones.md index cefea0a6..eee13650 100644 --- a/docs/adr/0049-merge-on-partial-clones.md +++ b/docs/adr/0049-merge-on-partial-clones.md @@ -184,6 +184,8 @@ Replay is a three-way merge with a different base, and `replay_commit` is the on 19. **Completion can drop a newly tracked ignored file.** *Resolved:* completion reads the working tree with the decided root's paths counted as tracked, so an ignore rule cannot hide a file the operation itself added. Test `completing_a_conflicted_pick_keeps_an_added_file_the_parent_ignores`. 20. **A stopped pick or rebase without its decided root.** `PICK_DECIDED_ROOT` and `REBASE_DECIDED_ROOT` are written before the state's in-progress signal, so the state cannot normally be missing. If it is (a lost file, a power loss before the data reached disk), a partial clone's completion refuses, because grafting from the tip would keep the old out-of-view content; `--abort` still works. +21. **A conflict stop overwrites an ignored or untracked file at a plaintext path.** The stop writes the decrypted text with a plain write, so a local copy the user kept at that path (the usual "stop tracking, keep it ignored" move) is replaced, and abort now removes the path. The loss happens at the stop and predates the record; refusing the stop when an untracked file sits at a plaintext path would close it. + ## Alternatives considered - **Fetch everything a merge might need first (`backfill --all`, then merge).** Correct and simple, and what the refusal message says today. It defeats the partial clone.