From 20ae84b3aaa2b3d848acaa90b12c639ebff9c14f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 07:49:46 +0300 Subject: [PATCH 1/6] fix(repo): sweep .theirs sidecars only for non-text conflicts A text conflict writes no sidecar, so an untracked user file named .theirs was deleted by merge/cherry-pick/rebase abort and by rebase --continue whenever the parent tree did not track it. The sweep now skips text conflicts and any path whose kind cannot be derived. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 11 +++--- crates/repo/src/replay.rs | 77 +++++++++++++++++++++++++++++++++++++++ crates/repo/src/repo.rs | 15 +++++++- 3 files changed, 95 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6589dfb0..3373dfcb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -720,12 +720,11 @@ scale-&-reach horizon): limitation across different Git repos). - **Richer trust models** beyond trusted-key lists (delegation, expiry) — P22 ships the key-list model. -- **Sidecar-cleanup footgun in `rebase_continue` — half fixed (P37c).** - `remove_conflict_sidecars` now skips paths the completion's parent tree - tracks, but it still has no non-text-kind gate: a text conflict writes no - `.theirs` sidecar, so an untracked user file named `foo.txt.theirs` is - still deleted when the stop's conflict path is `foo.txt`. Pass the conflict - kind (or the written sidecar list) to the sweep to close it. +- **Sidecar-cleanup footgun in `rebase_continue` — fixed.** + `remove_conflict_sidecars` (merge/pick/rebase abort and `rebase --continue`) + unlinks `{path}.theirs` only for a non-text conflict whose sidecar the + completion's parent tree does not track, so an untracked user file of that + name survives; a kind that cannot be derived leaves the file. - **In-progress guard for the RECEIVING repo on push.** `LocalTransport::update_ref` moves a branch tip with only a CAS/ff gate and no in-progress check on the receiving side — a push into a repo diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 53438b0d..689ed830 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -2905,6 +2905,83 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// Two branches that conflict as text on `x.txt`, `main` checked out, with + /// an untracked user file `x.txt.theirs` beside it. A text conflict writes + /// no sidecar, so no sweep may touch that file. + fn text_conflict_with_user_theirs_file(name: &str) -> (std::path::PathBuf, Repo) { + let root = tmp_root(name); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("x.txt"), b"a\nb\nc\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("x.txt"), b"a\nMAIN\nc\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("x.txt"), b"a\nWORK\nc\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + std::fs::write(root.join("x.txt.theirs"), b"mine\n").unwrap(); + (root, repo) + } + + fn assert_user_theirs_file_survives(root: &std::path::Path) { + assert_eq!( + std::fs::read(root.join("x.txt.theirs")).unwrap(), + b"mine\n", + "an untracked x.txt.theirs beside a text conflict is the user's" + ); + } + + #[test] + fn merge_abort_keeps_a_user_theirs_file_beside_a_text_conflict() { + let (root, repo) = text_conflict_with_user_theirs_file("sweep-merge-abort"); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + repo.merge_abort().unwrap(); + assert_user_theirs_file_survives(&root); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + #[test] + fn cherry_pick_abort_keeps_a_user_theirs_file_beside_a_text_conflict() { + let (root, repo) = text_conflict_with_user_theirs_file("sweep-pick-abort"); + assert!(matches!( + repo.cherry_pick("work", "me", None, None).unwrap_err(), + Error::PickConflicts(_) + )); + assert!(repo.pick_in_progress()); + repo.cherry_pick_abort().unwrap(); + assert_user_theirs_file_survives(&root); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + #[test] + fn rebase_abort_and_continue_keep_a_user_theirs_file_beside_a_text_conflict() { + // work is rebased onto main: x.txt conflicts as text. + let (root, repo) = text_conflict_with_user_theirs_file("sweep-rebase"); + repo.switch("work").unwrap(); + assert!(matches!( + repo.rebase("main", "me", None).unwrap(), + RebaseResult::Stopped { .. } + )); + repo.rebase_abort().unwrap(); + assert_user_theirs_file_survives(&root); + + assert!(matches!( + repo.rebase("main", "me", None).unwrap(), + RebaseResult::Stopped { .. } + )); + std::fs::write(root.join("x.txt"), b"a\nresolved\nc\n").unwrap(); + repo.rebase_continue("me", None).unwrap(); + assert_user_theirs_file_survives(&root); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + /// A file where a parent directory of a plaintext path must be fails the /// write halfway; the stop refuses before writing anything instead. #[test] diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index f9169047..15daabef 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1928,7 +1928,7 @@ impl Repo { } /// Remove the `.theirs` sidecars a stopped merge, pick or rebase - /// wrote for `paths`, except a file any of `roots` tracks: that one is the + /// wrote for `paths` (only non-text conflicts write one), 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 /// stray sidecar is harmless, deleting a tracked file is not. Call it after /// the restore, so a restore that fails leaves the sidecars to retry. @@ -1938,9 +1938,20 @@ impl Repo { roots: &[ObjectId], ) -> Result<()> { let partial = self.promisor()?.is_some(); + // Only a non-text conflict writes a sidecar; a `.theirs` file beside + // a text conflict is the user's own. A kind that cannot be derived + // (a gap, a corrupt record) leaves the file: a stray sidecar is + // harmless. Computed before the store lock is taken. + let wrote_sidecar: Vec<&String> = paths + .iter() + .filter(|p| { + self.conflict_kind(p) + .is_ok_and(|k| k != crate::conflicts::ConflictKind::Text) + }) + .collect(); let store_arc = self.vfs.store(); let mut store = store_arc.lock().unwrap(); - for path in paths { + for path in wrote_sidecar { let sidecar = format!("{path}.theirs"); let tracked = roots.iter().any(|root| { worktree::tree_entry_at(&mut store, *root, &sidecar, partial) From 25f340e521f4e5a91fc182d1599974eacefbf307 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 07:55:20 +0300 Subject: [PATCH 2/6] fix(repo): sweep only the sidecars a stop recorded writing Conflict kind does not say whether a .theirs sidecar was written: a protected UTF-8 conflict and a binary delete/modify write none. The stop now records the sidecars it writes in .sc/CONFLICT_SIDECARS (kept apart from CONFLICT_PLAINTEXT, which completion counts as tracked), and abort, rebase --continue and sc resolve remove only those. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 5 +- ROADMAP.md | 10 +-- crates/repo/src/conflict_plaintext.rs | 51 ++++++++++++- crates/repo/src/conflicts.rs | 42 ++++------- crates/repo/src/replay.rs | 102 +++++++++++++++++++++++--- crates/repo/src/repo.rs | 45 +++++------- 6 files changed, 181 insertions(+), 74 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 77385f62..0c47796b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -241,7 +241,10 @@ transport-adjacent. The rest, imperatively: - **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. + and abort removes listed paths the restored tree does not track as plain files. The `.theirs` + sidecars it wrote are listed apart in `.sc/CONFLICT_SIDECARS`; abort, `rebase + --continue` and `sc resolve` remove only those, never a `.theirs` file the stop + did not write. - **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/ROADMAP.md b/ROADMAP.md index 3373dfcb..b6df1614 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -720,11 +720,11 @@ scale-&-reach horizon): limitation across different Git repos). - **Richer trust models** beyond trusted-key lists (delegation, expiry) — P22 ships the key-list model. -- **Sidecar-cleanup footgun in `rebase_continue` — fixed.** - `remove_conflict_sidecars` (merge/pick/rebase abort and `rebase --continue`) - unlinks `{path}.theirs` only for a non-text conflict whose sidecar the - completion's parent tree does not track, so an untracked user file of that - name survives; a kind that cannot be derived leaves the file. +- **Sidecar-cleanup footgun in `rebase_continue` — fixed.** A stop records the + `.theirs` sidecars it actually wrote in `.sc/CONFLICT_SIDECARS`; merge/pick/ + rebase abort, `rebase --continue` and `sc resolve` unlink only those (and + never a path the restored tree tracks), so an untracked user `foo.txt.theirs` + survives whatever the conflict kind. - **In-progress guard for the RECEIVING repo on push.** `LocalTransport::update_ref` moves a branch tip with only a CAS/ff gate and no in-progress check on the receiving side — a push into a repo diff --git a/crates/repo/src/conflict_plaintext.rs b/crates/repo/src/conflict_plaintext.rs index de052a70..8e5abc8c 100644 --- a/crates/repo/src/conflict_plaintext.rs +++ b/crates/repo/src/conflict_plaintext.rs @@ -48,15 +48,53 @@ pub(crate) fn read(layout: &Layout) -> Result> { } } -/// Drop the record. +/// Drop both records. pub(crate) fn clear(layout: &Layout) -> Result<()> { - match std::fs::remove_file(path(layout)) { + remove_if_present(&path(layout))?; + remove_if_present(&sidecar_path(layout)) +} + +fn remove_if_present(p: &std::path::Path) -> Result<()> { + match std::fs::remove_file(p) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(e.into()), } } +fn sidecar_path(layout: &Layout) -> std::path::PathBuf { + layout.dot_sc.join("CONFLICT_SIDECARS") +} + +/// Record the `.theirs` sidecars a stop wrote, by full path. They are +/// kept apart from the plaintext list because completion counts a plaintext +/// path as tracked, and a sidecar must never be committed. An empty list +/// removes the record. +pub(crate) fn write_sidecars(layout: &Layout, paths: &[String]) -> Result<()> { + if paths.is_empty() { + return remove_if_present(&sidecar_path(layout)); + } + let tmp = layout.dot_sc.join("CONFLICT_SIDECARS.tmp"); + std::fs::write(&tmp, paths.join("\0"))?; + std::fs::rename(&tmp, sidecar_path(layout))?; + Ok(()) +} + +/// The recorded sidecar paths, empty when there is no record. Only the +/// sidecars a stop actually wrote are listed: a `.theirs` file beside a +/// conflict that wrote none is the user's own. +pub(crate) fn read_sidecars(layout: &Layout) -> Result> { + match std::fs::read_to_string(sidecar_path(layout)) { + 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()), + } +} + #[cfg(test)] mod tests { use super::*; @@ -83,8 +121,17 @@ mod tests { write(&layout, &[]).unwrap(); assert!(read(&layout).unwrap().is_empty(), "an empty list clears"); write(&layout, &["x".into()]).unwrap(); + write_sidecars(&layout, &["x.theirs".into()]).unwrap(); + assert_eq!( + read_sidecars(&layout) + .unwrap() + .into_iter() + .collect::>(), + vec!["x.theirs"] + ); clear(&layout).unwrap(); assert!(read(&layout).unwrap().is_empty()); + assert!(read_sidecars(&layout).unwrap().is_empty()); std::fs::remove_dir_all(&root).unwrap(); } } diff --git a/crates/repo/src/conflicts.rs b/crates/repo/src/conflicts.rs index 5b807d01..7d6cb43b 100644 --- a/crates/repo/src/conflicts.rs +++ b/crates/repo/src/conflicts.rs @@ -292,33 +292,21 @@ impl Repo { }, } - // Drop the `.theirs` sidecar this system may have written — the only - // sidecar extension ever written (`.base` and `.ours` are never - // produced, so removing them was both dead code and a footgun: a - // repo can legitimately track a real file named - // `foo.txt.base`/`foo.txt.ours`, and blind-unlinking it would - // silently destroy user data). `.theirs` is written only for - // BINARY/PROTECTED-with-binary-content conflicts (merge.rs writes - // `{path}.theirs` in the binary-conflict arm) — a TEXT conflict - // never writes one, so a `.theirs`-named file sitting untracked next - // to a text conflict is not this system's scratch, it's the user's; - // removing it there would silently and unrecoverably delete - // untracked data. So only consider removal when the conflict kind is - // NOT Text (`!= Text`, not `== Binary`: a protected binary conflict - // still writes a plaintext `.theirs` sidecar and classifies as - // Protected, so it must still be cleaned up). And even then, only - // remove it when it is NOT a tracked path — a genuine sidecar is - // untracked scratch by construction, so a tracked `{path}.theirs` - // must be a user's real file and is left alone. - if kind != ConflictKind::Text { - let theirs_sidecar_path = format!("{path}.theirs"); - if !self.tracked_paths()?.contains(&theirs_sidecar_path) { - let sidecar = safe_join(&self.layout.root, &theirs_sidecar_path)?; - match std::fs::remove_file(&sidecar) { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(e.into()), - } + // Drop the `.theirs` sidecar the stop recorded writing for this path. + // Only a recorded sidecar is ours: the kind of conflict does not say + // whether one was written (a protected UTF-8 conflict and a binary + // delete/modify write none), and a `.theirs` file the stop did not + // write is the user's, as is a tracked `{path}.theirs` (a repo can + // legitimately track `foo.txt.theirs`, `.base` or `.ours`). + let theirs_sidecar_path = format!("{path}.theirs"); + if crate::conflict_plaintext::read_sidecars(&self.layout)?.contains(&theirs_sidecar_path) + && !self.tracked_paths()?.contains(&theirs_sidecar_path) + { + let sidecar = safe_join(&self.layout.root, &theirs_sidecar_path)?; + match std::fs::remove_file(&sidecar) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), } } diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 689ed830..bcaac55f 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -660,10 +660,7 @@ impl Repo { 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, - )?; + self.remove_conflict_sidecars(&sidecar_roots)?; crate::pick_state::clear(&self.layout)?; Ok(skipped) } @@ -1219,10 +1216,7 @@ impl Repo { // user's own): see `remove_conflict_sidecars`. // Not a file the completion's parent tracks (that one is the // user's own): see `remove_conflict_sidecars`. - self.remove_conflict_sidecars( - &crate::rebase_state::read_conflicts(&self.layout)?, - &[self.snapshot(&st.acc_tip)?.root], - )?; + self.remove_conflict_sidecars(&[self.snapshot(&st.acc_tip)?.root])?; // Advance state BEFORE attempting the fold, so an error from the // fold below (on a later commit) leaves a retryable, idempotent // `--continue` rather than losing resumability. `rebase_abort` @@ -1308,10 +1302,7 @@ impl Repo { )? }; self.remove_conflict_plaintext(snap.root)?; - self.remove_conflict_sidecars( - &crate::rebase_state::read_conflicts(&self.layout)?, - &[snap.root], - )?; + self.remove_conflict_sidecars(&[snap.root])?; crate::rebase_state::clear(&self.layout)?; Ok(skipped) } @@ -2932,6 +2923,93 @@ mod tests { ); } + /// Binary delete/modify writes no sidecar: `ours` deletes, `work` edits. + #[test] + fn abort_keeps_a_user_theirs_file_beside_a_binary_delete_modify_conflict() { + let root = tmp_root("sweep-bin-delmod"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\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("bin.dat")).unwrap(); + repo.commit("me", "main deletes").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeWORK\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch("main").unwrap(); + std::fs::write(root.join("bin.dat.theirs"), b"mine\n").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + repo.merge_abort().unwrap(); + assert_eq!( + std::fs::read(root.join("bin.dat.theirs")).unwrap(), + b"mine\n" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// A protected UTF-8 conflict writes markers, not a sidecar. + #[test] + fn abort_and_resolve_keep_a_user_theirs_file_beside_a_protected_text_conflict() { + let root = tmp_root("sweep-protected-text"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"l1\nl2\nl3\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("secret/a.txt"), b"MAIN\nl2\nl3\n").unwrap(); + repo.commit("me", "main edits").unwrap(); + repo.switch_with_identity("work", Some(&alice_sk)).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"WORK\nl2\nl3\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + std::fs::write(root.join("secret/a.txt.theirs"), b"mine\n").unwrap(); + let mine = || std::fs::read(root.join("secret/a.txt.theirs")).unwrap(); + + let err = repo + .cherry_pick("work", "me", Some(&alice_sk), None) + .unwrap_err(); + assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); + repo.resolve_path("secret/a.txt", crate::ResolveSide::Ours, Some(&alice_sk)) + .unwrap(); + assert_eq!(mine(), b"mine\n", "resolve must keep the user's file"); + repo.cherry_pick_abort().unwrap(); + assert_eq!(mine(), b"mine\n", "abort must keep the user's file"); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// The control: a binary conflict's own sidecar is still cleaned up. + #[test] + fn abort_still_removes_the_sidecar_a_binary_conflict_wrote() { + let root = tmp_root("sweep-bin-own"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + assert!(root.join("bin.dat.theirs").exists()); + repo.merge_abort().unwrap(); + assert!(!root.join("bin.dat.theirs").exists()); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + #[test] fn merge_abort_keeps_a_user_theirs_file_beside_a_text_conflict() { let (root, repo) = text_conflict_with_user_theirs_file("sweep-merge-abort"); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 15daabef..5a387630 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1877,6 +1877,10 @@ impl Repo { .map(|(p, ..)| p.clone()) .collect::>(), )?; + crate::conflict_plaintext::write_sidecars( + &self.layout, + &sidecars.iter().map(|(r, _)| r.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() { @@ -1927,32 +1931,22 @@ impl Repo { Ok(()) } - /// Remove the `.theirs` sidecars a stopped merge, pick or rebase - /// wrote for `paths` (only non-text conflicts write one), 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 - /// stray sidecar is harmless, deleting a tracked file is not. Call it after - /// the restore, so a restore that fails leaves the sidecars to retry. - pub(crate) fn remove_conflict_sidecars( - &self, - paths: &[String], - roots: &[ObjectId], - ) -> Result<()> { + /// Remove the `.theirs` sidecars the stop recorded writing + /// (`conflict_plaintext::read_sidecars`), except a file any of `roots` + /// tracks: that one is the user's own and was just restored. A `.theirs` + /// file the stop did not write is the user's, whatever kind of conflict + /// sits beside it. A failed lookup counts as tracked: a stray sidecar is + /// harmless, deleting a tracked file is not. Call it after the restore, so + /// a restore that fails leaves the sidecars to retry. + pub(crate) fn remove_conflict_sidecars(&self, roots: &[ObjectId]) -> Result<()> { + let sidecars = crate::conflict_plaintext::read_sidecars(&self.layout)?; + if sidecars.is_empty() { + return Ok(()); + } let partial = self.promisor()?.is_some(); - // Only a non-text conflict writes a sidecar; a `.theirs` file beside - // a text conflict is the user's own. A kind that cannot be derived - // (a gap, a corrupt record) leaves the file: a stray sidecar is - // harmless. Computed before the store lock is taken. - let wrote_sidecar: Vec<&String> = paths - .iter() - .filter(|p| { - self.conflict_kind(p) - .is_ok_and(|k| k != crate::conflicts::ConflictKind::Text) - }) - .collect(); let store_arc = self.vfs.store(); let mut store = store_arc.lock().unwrap(); - for path in wrote_sidecar { - let sidecar = format!("{path}.theirs"); + for sidecar in sidecars { let tracked = roots.iter().any(|root| { worktree::tree_entry_at(&mut store, *root, &sidecar, partial) .map_or(true, |e| e.is_some()) @@ -2018,10 +2012,7 @@ impl Repo { 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, - )?; + self.remove_conflict_sidecars(&sidecar_roots)?; crate::merge_state::clear(&self.layout)?; Ok(skipped) } From 0e14b25ae1457c81b38b5865b01b426aeb152c6d Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 08:02:02 +0300 Subject: [PATCH 3/6] fix(repo): retire a sidecar from the record once resolve removes it A later user file at the same path would otherwise be swept by abort or rebase --continue. The new sidecar tests also assert their repository directory is gone. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/conflict_plaintext.rs | 25 ++++++++++++++ crates/repo/src/conflicts.rs | 1 + crates/repo/src/replay.rs | 50 +++++++++++++++++++++++---- 3 files changed, 70 insertions(+), 6 deletions(-) diff --git a/crates/repo/src/conflict_plaintext.rs b/crates/repo/src/conflict_plaintext.rs index 8e5abc8c..bdc6b2c4 100644 --- a/crates/repo/src/conflict_plaintext.rs +++ b/crates/repo/src/conflict_plaintext.rs @@ -80,6 +80,16 @@ pub(crate) fn write_sidecars(layout: &Layout, paths: &[String]) -> Result<()> { Ok(()) } +/// Drop one sidecar from the record once it has been dealt with, so a file +/// the user later creates at that path is not mistaken for ours. +pub(crate) fn retire_sidecar(layout: &Layout, sidecar: &str) -> Result<()> { + let mut paths = read_sidecars(layout)?; + if paths.remove(sidecar) { + write_sidecars(layout, &paths.into_iter().collect::>())?; + } + Ok(()) +} + /// The recorded sidecar paths, empty when there is no record. Only the /// sidecars a stop actually wrote are listed: a `.theirs` file beside a /// conflict that wrote none is the user's own. @@ -129,6 +139,21 @@ mod tests { .collect::>(), vec!["x.theirs"] ); + write_sidecars(&layout, &["x.theirs".into(), "y.theirs".into()]).unwrap(); + retire_sidecar(&layout, "x.theirs").unwrap(); + assert_eq!( + read_sidecars(&layout) + .unwrap() + .into_iter() + .collect::>(), + vec!["y.theirs"] + ); + retire_sidecar(&layout, "y.theirs").unwrap(); + assert!( + read_sidecars(&layout).unwrap().is_empty(), + "last one removes the file" + ); + write_sidecars(&layout, &["x.theirs".into()]).unwrap(); clear(&layout).unwrap(); assert!(read(&layout).unwrap().is_empty()); assert!(read_sidecars(&layout).unwrap().is_empty()); diff --git a/crates/repo/src/conflicts.rs b/crates/repo/src/conflicts.rs index 7d6cb43b..2a286750 100644 --- a/crates/repo/src/conflicts.rs +++ b/crates/repo/src/conflicts.rs @@ -308,6 +308,7 @@ impl Repo { Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(e.into()), } + crate::conflict_plaintext::retire_sidecar(&self.layout, &theirs_sidecar_path)?; } let remaining: Vec = conflicts.into_iter().filter(|p| p != path).collect(); diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index bcaac55f..12a1861a 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -2896,6 +2896,12 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// Remove a test repository and assert it is gone. + fn remove_root(root: &std::path::Path) { + std::fs::remove_dir_all(root).unwrap(); + assert!(!root.exists(), "test repository must leave no residue"); + } + /// Two branches that conflict as text on `x.txt`, `main` checked out, with /// an untracked user file `x.txt.theirs` beside it. A text conflict writes /// no sidecar, so no sweep may touch that file. @@ -2949,7 +2955,7 @@ mod tests { b"mine\n" ); drop(repo); - std::fs::remove_dir_all(&root).ok(); + remove_root(&root); } /// A protected UTF-8 conflict writes markers, not a sidecar. @@ -2982,7 +2988,7 @@ mod tests { repo.cherry_pick_abort().unwrap(); assert_eq!(mine(), b"mine\n", "abort must keep the user's file"); drop(repo); - std::fs::remove_dir_all(&root).ok(); + remove_root(&root); } /// The control: a binary conflict's own sidecar is still cleaned up. @@ -3007,7 +3013,39 @@ mod tests { repo.merge_abort().unwrap(); assert!(!root.join("bin.dat.theirs").exists()); drop(repo); - std::fs::remove_dir_all(&root).ok(); + remove_root(&root); + } + + /// `sc resolve` removes the sidecar it recorded; a file the user later + /// creates at that path must survive a later abort. + #[test] + fn abort_keeps_a_user_file_created_at_a_sidecar_path_after_resolve() { + let root = tmp_root("sweep-after-resolve"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + repo.resolve_path("bin.dat", crate::ResolveSide::Ours, None) + .unwrap(); + assert!(!root.join("bin.dat.theirs").exists()); + std::fs::write(root.join("bin.dat.theirs"), b"mine\n").unwrap(); + repo.merge_abort().unwrap(); + assert_eq!( + std::fs::read(root.join("bin.dat.theirs")).unwrap(), + b"mine\n" + ); + drop(repo); + remove_root(&root); } #[test] @@ -3020,7 +3058,7 @@ mod tests { repo.merge_abort().unwrap(); assert_user_theirs_file_survives(&root); drop(repo); - std::fs::remove_dir_all(&root).ok(); + remove_root(&root); } #[test] @@ -3034,7 +3072,7 @@ mod tests { repo.cherry_pick_abort().unwrap(); assert_user_theirs_file_survives(&root); drop(repo); - std::fs::remove_dir_all(&root).ok(); + remove_root(&root); } #[test] @@ -3057,7 +3095,7 @@ mod tests { repo.rebase_continue("me", None).unwrap(); assert_user_theirs_file_survives(&root); drop(repo); - std::fs::remove_dir_all(&root).ok(); + remove_root(&root); } /// A file where a parent directory of a plaintext path must be fails the From 05c7a53b2285ecfde3ac9e7e15c911bdfdeb7eed Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 08:13:30 +0300 Subject: [PATCH 4/6] fix(repo): retire the sidecar record once swept A retried rebase --continue could otherwise remove a file the user made at a sidecar path after the first sweep. Records the separate gap that completion commits a leftover sidecar. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 6 ++++++ crates/repo/src/replay.rs | 37 +++++++++++++++++++++++++++++++++++++ crates/repo/src/repo.rs | 8 ++++++-- 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b6df1614..318fc337 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -725,6 +725,12 @@ scale-&-reach horizon): rebase abort, `rebase --continue` and `sc resolve` unlink only those (and never a path the restored tree tracks), so an untracked user `foo.txt.theirs` survives whatever the conflict kind. +- **Completion commits a leftover `.theirs` sidecar.** A binary conflict's + `.theirs` is working-tree scratch, but if the user resolves by editing + `` (not `sc resolve`) and leaves the sidecar, the completing `sc commit` + or `rebase --continue` snapshots it as a tracked file (reproduced on main with + a merge). Exclude recorded sidecars (`.sc/CONFLICT_SIDECARS`) that no input + root tracks from the completion snapshot. - **In-progress guard for the RECEIVING repo on push.** `LocalTransport::update_ref` moves a branch tip with only a CAS/ff gate and no in-progress check on the receiving side — a push into a repo diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 12a1861a..7e63d5ec 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -3048,6 +3048,43 @@ mod tests { remove_root(&root); } + /// A sweep retires the record: a retried `--continue` (or any second + /// sweep) must not remove a file the user creates at that path meanwhile. + #[test] + fn a_swept_sidecar_is_retired_from_the_record() { + let root = tmp_root("sweep-retired"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + let ours = repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + let ours_root = repo.snapshot(&ours).unwrap().root; + repo.remove_conflict_sidecars(&[ours_root]).unwrap(); + assert!( + !root.join("bin.dat.theirs").exists(), + "first sweep removes it" + ); + + std::fs::write(root.join("bin.dat.theirs"), b"mine\n").unwrap(); + repo.remove_conflict_sidecars(&[ours_root]).unwrap(); + assert_eq!( + std::fs::read(root.join("bin.dat.theirs")).unwrap(), + b"mine\n", + "second sweep must not touch a file made after the first" + ); + drop(repo); + remove_root(&root); + } + #[test] fn merge_abort_keeps_a_user_theirs_file_beside_a_text_conflict() { let (root, repo) = text_conflict_with_user_theirs_file("sweep-merge-abort"); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 5a387630..13f8226b 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1937,7 +1937,8 @@ impl Repo { /// file the stop did not write is the user's, whatever kind of conflict /// sits beside it. A failed lookup counts as tracked: a stray sidecar is /// harmless, deleting a tracked file is not. Call it after the restore, so - /// a restore that fails leaves the sidecars to retry. + /// a restore that fails leaves the sidecars to retry. The record is retired + /// once swept. pub(crate) fn remove_conflict_sidecars(&self, roots: &[ObjectId]) -> Result<()> { let sidecars = crate::conflict_plaintext::read_sidecars(&self.layout)?; if sidecars.is_empty() { @@ -1955,7 +1956,10 @@ impl Repo { let _ = std::fs::remove_file(self.layout.root.join(sidecar)); } } - Ok(()) + // Handled: retire the record, so a retry (a `--continue` whose fold + // fails later) cannot sweep a file the user creates at that path. + drop(store); + crate::conflict_plaintext::write_sidecars(&self.layout, &[]) } /// Abandon an in-progress merge: restore the working tree to the current tip From f59d156ce9eb5e75f43e2036609187100d4bc069 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 08:22:23 +0300 Subject: [PATCH 5/6] fix(repo): retire each swept sidecar after its removal succeeds A removal failure other than NotFound now stops the sweep with the record intact, so a retry can finish it, instead of being ignored. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/replay.rs | 38 ++++++++++++++++++++++++++++++++++++++ crates/repo/src/repo.rs | 16 +++++++++++----- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 7e63d5ec..6d236d1f 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -3085,6 +3085,44 @@ mod tests { remove_root(&root); } + /// A sweep that cannot remove a sidecar fails with the record intact, so a + /// retry can finish the job. + #[test] + fn a_failed_sidecar_removal_keeps_the_record_for_a_retry() { + let root = tmp_root("sweep-remove-fails"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + let ours = repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + repo.merge("work", "me").unwrap_err(); + let ours_root = repo.snapshot(&ours).unwrap().root; + // Replace the sidecar with a directory: `remove_file` cannot unlink it. + std::fs::remove_file(root.join("bin.dat.theirs")).unwrap(); + std::fs::create_dir(root.join("bin.dat.theirs")).unwrap(); + repo.remove_conflict_sidecars(&[ours_root]).unwrap_err(); + assert!( + crate::conflict_plaintext::read_sidecars(&repo.layout) + .unwrap() + .contains("bin.dat.theirs"), + "the record survives a failed removal" + ); + std::fs::remove_dir(root.join("bin.dat.theirs")).unwrap(); + std::fs::write(root.join("bin.dat.theirs"), b"x\n").unwrap(); + repo.remove_conflict_sidecars(&[ours_root]).unwrap(); + assert!( + !root.join("bin.dat.theirs").exists(), + "the retry finishes it" + ); + drop(repo); + remove_root(&root); + } + #[test] fn merge_abort_keeps_a_user_theirs_file_beside_a_text_conflict() { let (root, repo) = text_conflict_with_user_theirs_file("sweep-merge-abort"); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 13f8226b..41c52e68 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1953,13 +1953,19 @@ impl Repo { .map_or(true, |e| e.is_some()) }); if !tracked { - let _ = std::fs::remove_file(self.layout.root.join(sidecar)); + // Only an already-absent file is fine: any other failure stops + // the sweep with the record intact, so a retry can finish it. + match std::fs::remove_file(worktree::safe_join(&self.layout.root, &sidecar)?) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), + } } + // Handled: retire it, so a retry (a `--continue` whose fold fails + // later) cannot sweep a file the user creates at that path. + crate::conflict_plaintext::retire_sidecar(&self.layout, &sidecar)?; } - // Handled: retire the record, so a retry (a `--continue` whose fold - // fails later) cannot sweep a file the user creates at that path. - drop(store); - crate::conflict_plaintext::write_sidecars(&self.layout, &[]) + Ok(()) } /// Abandon an in-progress merge: restore the working tree to the current tip From 74736d06cc64d6e1663ecdef5a3cccd3a74afc5f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Mon, 19 Oct 2026 08:30:17 +0300 Subject: [PATCH 6/6] fix(repo): retire sidecar records before unlinking, in one write A crash after the unlink left a record naming a path the user could then recreate. The sweep now clears the record once up front and restores the failed and unprocessed paths on a removal error; resolve retires first and restores on a failed unlink. This also drops the per-entry rewrite. Co-Authored-By: Claude Sonnet 5.5 --- crates/repo/src/conflicts.rs | 15 +++++++++++++-- crates/repo/src/repo.rs | 33 +++++++++++++++++++++------------ 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/crates/repo/src/conflicts.rs b/crates/repo/src/conflicts.rs index 2a286750..7f0cf705 100644 --- a/crates/repo/src/conflicts.rs +++ b/crates/repo/src/conflicts.rs @@ -303,12 +303,23 @@ impl Repo { && !self.tracked_paths()?.contains(&theirs_sidecar_path) { let sidecar = safe_join(&self.layout.root, &theirs_sidecar_path)?; + // Retire first: a crash after the unlink must not leave a record + // that names a path the user may recreate. A failed unlink puts + // the entry back. + crate::conflict_plaintext::retire_sidecar(&self.layout, &theirs_sidecar_path)?; match std::fs::remove_file(&sidecar) { Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(e.into()), + Err(e) => { + let mut paths = crate::conflict_plaintext::read_sidecars(&self.layout)?; + paths.insert(theirs_sidecar_path); + let _ = crate::conflict_plaintext::write_sidecars( + &self.layout, + &paths.into_iter().collect::>(), + ); + return Err(e.into()); + } } - crate::conflict_plaintext::retire_sidecar(&self.layout, &theirs_sidecar_path)?; } let remaining: Vec = conflicts.into_iter().filter(|p| p != path).collect(); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 41c52e68..d76bdcd8 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1944,26 +1944,35 @@ impl Repo { if sidecars.is_empty() { return Ok(()); } + // Retire the whole record before unlinking anything, in one write: a + // crash then leaves harmless residue, never a record naming a path the + // user may recreate before the retry. A removal that fails puts the + // failed and unprocessed paths back so the retry can finish the job. + crate::conflict_plaintext::write_sidecars(&self.layout, &[])?; let partial = self.promisor()?.is_some(); let store_arc = self.vfs.store(); let mut store = store_arc.lock().unwrap(); - for sidecar in sidecars { + let sidecars: Vec = sidecars.into_iter().collect(); + for (i, sidecar) in sidecars.iter().enumerate() { let tracked = roots.iter().any(|root| { - worktree::tree_entry_at(&mut store, *root, &sidecar, partial) + worktree::tree_entry_at(&mut store, *root, sidecar, partial) .map_or(true, |e| e.is_some()) }); - if !tracked { - // Only an already-absent file is fine: any other failure stops - // the sweep with the record intact, so a retry can finish it. - match std::fs::remove_file(worktree::safe_join(&self.layout.root, &sidecar)?) { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(e.into()), + if tracked { + continue; + } + let removed = worktree::safe_join(&self.layout.root, sidecar).and_then(|full| { + match std::fs::remove_file(full) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), } + }); + if let Err(e) = removed { + // Best effort: the removal error is the one worth reporting. + let _ = crate::conflict_plaintext::write_sidecars(&self.layout, &sidecars[i..]); + return Err(e); } - // Handled: retire it, so a retry (a `--continue` whose fold fails - // later) cannot sweep a file the user creates at that path. - crate::conflict_plaintext::retire_sidecar(&self.layout, &sidecar)?; } Ok(()) }