Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,19 @@ transport-adjacent. The rest, imperatively:
`.sc/sparse-widen` (local-only like the rest, removed with the spec write or
the op); abort and completion delete what an interrupted widen laid outside
the view.
- **`materialize` deletes or overwrites a path only if it is the stop's own
file (ADR-0034 refinement 8, #255, #256).** A file the replaced tree tracks goes
only when the disk copy is a regular file with exactly the tracked bytes (an
edit, a replacement or a symlink survives); a path outside the sparse view is
never reported, since nothing is laid there and a copy is the user's. An
abort (`merge_abort`, `cherry_pick_abort`, `rebase_abort`; they return an
`AbortReport`) finishes anyway: it removes what the stop laid, leaves the
rest and lists it in `kept` (`sc` prints `left in place (changed since the
stop)`), and overwrites a file only if it is still the stopped tree's bytes or
the stop owns it (recorded plaintext, a conflicted path). Recorded plaintext (`CONFLICT_PLAINTEXT`, which now includes the
carried protected files a stop decrypted) and sidecars are removed whatever
their bytes, since an edit of them is the discarded resolution. Merge abort
compares against the decided root, not theirs' tree.
- **A merge, switch, cherry-pick, rebase, undo or sparse-spec change refuses, before any write, to lay a file or
directory onto an untracked or ignored one** (`refuse_untracked_overwrite`); move it
away and retry. A directory holding only tracked files is not such a case: a file/directory change at one path crosses switch, undo, abort and `--continue`, and the emptied directories are cleared (#247). `materialize` checks every such directory before its first removal, so a refusal changes nothing and an abort stays retryable; a forward op also refuses a user's empty directory there (it cannot tell it from a husk), while `materialize` itself prunes empty ones. (On a case-insensitive checkout, replacing `foo/a` with a file `Foo` is refused: the check does not follow the case alias. Fail-closed.) On a sparse checkout the same holds for a path the result adds
Expand All @@ -331,7 +344,7 @@ truth — do not re-list items here); entries that name an issue mirror the open
GitHub issues. Standing entries: `sc ws` workspace refresh (#215),
a limit-aware `sc fetch` and an object-count clone limit (#217 remainder), the non-unix
`.sc/local-key` ACL (#214), and the open
sparse, private-branch and abort edge cases (#241, #246, #247, #248).
sparse guard and user-file safety limits (#241, ADR-0034 refinement 8).

## Agent skills

Expand Down
16 changes: 9 additions & 7 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -784,13 +784,15 @@ P28 review follow-ons, the port de-flake, the clippy allow-list) are recorded in
agent may have open. Abandon and re-fork covers it meanwhile.
- **Sparse untracked-file guard edge cases.** #241: on a case-insensitive
filesystem the untracked-file guard can alias an old-view path with a newly
in-view one. #248: an untracked file at an out-of-view path that the other side adds wins
over the merge result at completion.
- **Abort and private-merge stop bugs.** #246: `--abort` of a merge stopped on a
private branch fails with `WrongKind`, and a binary conflict's `.theirs`
sidecar is committed into the sealed tree. #247: `--abort` of a stopped
merge, pick or rebase fails with `IsADirectory` when the decided root replaced
a file with a directory.
in-view one.
- **User-file safety limits (ADR-0034 refinement 8, ADR-0044).** A file whose
bytes equal the tracked or laid ones cannot be told from the stop's own
write, so it is removed. `merge --abort` of a private-branch merge, which
keeps no decided root, restores the tip over every path it tracks (a
post-stop edit of one, or a user file at a path the stop removed, is lost)
and treats a conflicted path as the stop's whatever its bytes. An abort with
no decided root (residue) removes nothing and does not say so. Private forward operations (switch, fast-forward, clean merge)
remove in-view paths on the dirty check alone, without a byte comparison.
- **Network-Git same-remote edge cases** (ADR-0018's re-synthesis
limitation across different Git repos).
- **Richer signer trust models** beyond trusted-key lists (delegation, expiry)
Expand Down
29 changes: 17 additions & 12 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2220,6 +2220,17 @@ fn run_status(json: bool, identity: Option<PathBuf>) -> Result<()> {
Ok(())
}

/// Say what an abort did not restore: protected paths it has no key for, and
/// files it left because they are no longer what the stop laid (#255).
fn print_abort_report(report: &scl_repo::AbortReport) {
for path in &report.skipped {
eprintln!("skipped (no key): {path}");
}
for path in &report.kept {
eprintln!("left in place (changed since the stop): {path}");
}
}

fn run_merge(
branch: Option<String>,
abort: bool,
Expand All @@ -2234,11 +2245,9 @@ fn run_merge(
} else {
None
};
let skipped = repo.merge_abort_with_identity(sk.as_ref())?;
let report = repo.merge_abort_with_identity(sk.as_ref())?;
println!("merge aborted; working tree restored");
for path in &skipped {
eprintln!("skipped (no key): {path}");
}
print_abort_report(&report);
return Ok(());
}
let branch = branch.ok_or_else(|| anyhow::anyhow!("merge: provide a branch or --abort"))?;
Expand Down Expand Up @@ -2279,11 +2288,9 @@ fn run_cherry_pick(
) -> Result<()> {
let repo = open_repo()?;
if abort {
let skipped = repo.cherry_pick_abort()?;
let report = repo.cherry_pick_abort()?;
println!("cherry-pick aborted; working tree restored");
for path in &skipped {
eprintln!("skipped (no key): {path}");
}
print_abort_report(&report);
return Ok(());
}
let refname = refname.ok_or_else(|| anyhow::anyhow!("cherry-pick needs a ref or --abort"))?;
Expand Down Expand Up @@ -2323,11 +2330,9 @@ fn run_rebase(
) -> Result<()> {
let repo = open_repo()?;
if abort {
let skipped = repo.rebase_abort()?;
let report = repo.rebase_abort()?;
println!("rebase aborted; working tree restored");
for path in &skipped {
eprintln!("skipped (no key): {path}");
}
print_abort_report(&report);
return Ok(());
}
// Soft-resolve like `run_merge`/`run_cherry_pick`: a missing identity file
Expand Down
28 changes: 28 additions & 0 deletions crates/core/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,26 @@ impl Object {
Object::Blob(Arc::from(bytes.into().into_boxed_slice()))
}

/// The id a blob with the bytes read from `reader` would have, computed
/// in fixed-size chunks so a big file is never held in memory. Equal to
/// `Object::blob(bytes).id()` (pinned by a test).
pub fn blob_id_of_reader(mut reader: impl std::io::Read) -> std::io::Result<ObjectId> {
let mut hasher = blake3::Hasher::new();
hasher.update(&[TAG_BLOB]);
let mut buf = [0_u8; 64 * 1024];
loop {
match reader.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
hasher.update(&buf[..n]);
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(ObjectId::from_bytes(*hasher.finalize().as_bytes()))
}

/// Bytes counted against the store's blob budget (0 for small resident
/// kinds). Sealed payloads are blob-sized ciphertext and get the same
/// budget/eviction treatment as plaintext blobs.
Expand Down Expand Up @@ -798,6 +818,14 @@ impl<'a> Reader<'a> {
mod tests {
use super::*;

#[test]
fn blob_id_of_reader_matches_the_blob_id() {
for bytes in [vec![], b"hello".to_vec(), vec![7_u8; 200_000]] {
let streamed = Object::blob_id_of_reader(&bytes[..]).unwrap();
assert_eq!(streamed, Object::blob(bytes).id());
}
}

#[test]
fn blob_roundtrip_and_dedup() {
let a = Object::blob(b"hello".to_vec());
Expand Down
4 changes: 3 additions & 1 deletion crates/repo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ pub mod textdiff;
pub mod tls_pins;
pub mod transcripts;
pub mod transport;
#[cfg(test)]
mod user_file_safety;
pub mod walfmt;
pub mod wire;
pub mod workspace;
Expand All @@ -79,7 +81,7 @@ pub use promisor::{PackFilter, Promisor, Scope};
pub use protect_ops::PrefixRecipient;
pub use remote::{RemoteConfig, RemoteKind};
pub use replay::{PickResult, RebaseResult};
pub use repo::{Repo, Status};
pub use repo::{AbortReport, Repo, Status};
pub use rewrap::RewrapReport;
pub use scanner::ScanReport;
pub use secrets::SecretInfo;
Expand Down
5 changes: 3 additions & 2 deletions crates/repo/src/partial_walks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -673,7 +673,8 @@ fn every_materializer_call_site_fills_or_is_exempt() {
continue;
}
let call = t.contains("worktree::materialize(")
|| t.contains("worktree::materialize_with_old_view(");
|| t.contains("worktree::materialize_with_old_view(")
|| t.contains("worktree::materialize_restore(");
if !call {
continue;
}
Expand All @@ -686,7 +687,7 @@ fn every_materializer_call_site_fills_or_is_exempt() {
);
}
}
assert!(checked >= 15, "the scan found only {checked} call sites");
assert!(checked >= 14, "the scan found only {checked} call sites");
}

/// A private branch cannot be checked out on a partial clone (sealing and
Expand Down
98 changes: 80 additions & 18 deletions crates/repo/src/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,10 +394,25 @@ impl Repo {
&target.keys().cloned().collect(),
)?;
}
// A path outside the view is never laid out, so a copy on disk is the
// user's own (#256). A failed removal is an error: the file may be
// decrypted plaintext that must not linger.
worktree::refuse_blocked_parents(
&self.layout.root,
target.keys().filter(|p| sparse.matches(p)),
&|c| old_paths.contains(c) && !target.contains_key(c),
)?;
for p in old_paths {
if !target.contains_key(p) || !sparse.matches(p) {
if !target.contains_key(p)
&& sparse.matches(p)
&& !worktree::under_symlink(&self.layout.root, p)
{
let full = worktree::safe_join(&self.layout.root, p)?;
let _ = std::fs::remove_file(full);
match std::fs::remove_file(full) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
}
let mut skipped = Vec::new();
Expand Down Expand Up @@ -880,7 +895,10 @@ impl Repo {
/// only the checkout needs restoring. It needs the identity (the tip is a
/// manifest); a caller who cannot open the branch is refused before any
/// write, leaving the stop intact for someone who can.
pub(crate) fn merge_abort_private(&self, identity: Option<&SecretKey>) -> Result<Vec<String>> {
pub(crate) fn merge_abort_private(
&self,
identity: Option<&SecretKey>,
) -> Result<crate::repo::AbortReport> {
let (branch, mid, manifest) = self
.head_private()?
.ok_or_else(|| Error::NotPrivateBranch("HEAD".into()))?;
Expand All @@ -889,20 +907,56 @@ impl Repo {
let theirs_id = crate::merge_state::read_merge_head(&self.layout)?
.expect("in_progress is true but MERGE_HEAD is absent");
let sparse = self.sparse_spec()?;
let plaintext = crate::conflict_plaintext::read(&self.layout)?;
let conflicted: BTreeSet<String> = crate::merge_state::read_conflicts(&self.layout)?
.into_iter()
.collect();

let store_arc = self.vfs.store();
let mut store = store_arc.lock().unwrap();
let inner_tip = ctx.inner_tip()?;
let ours = self.get_inner_snapshot(&mut store, &ctx, &inner_tip)?;
let theirs = store.get_snapshot(&theirs_id)?;
let prior = self.inner_tree_files(&mut store, &ctx, ours.root)?;
// The stop wrote files from ours and from theirs, in view only; theirs'
// adds are not in the restored tree, so the removal pass must know
// them (as the public abort does by passing theirs' root).
let mut written: BTreeSet<String> = prior.keys().cloned().collect();
written
.extend(worktree::tree_file_entries_with_perms(&mut store, theirs.root)?.into_keys());
written.retain(|p| sparse.matches(p));
// The stop wrote files from theirs, in view only; those the restored
// tip does not track must go, but only the stop's own: a conflicted
// path or recorded plaintext, or a file that is still theirs' bytes.
// A stop keeps no decided root for a private branch (it would be
// unsealed), so a conflicted path cannot be compared by content.
// Anything else at such a path is the user's and is reported (#255).
let mut written: BTreeSet<String> = prior
.keys()
.filter(|p| sparse.matches(p))
.cloned()
.collect();
Comment on lines +927 to +931

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve clean private-merge edits on abort

When a user edits an ordinary, non-conflicted private-tip path after a private merge stops, adding every prior path to written causes materialize_private to overwrite that edit unconditionally with the tip version. Unlike the public abort path, this never compares the file with the stopped or restored tree and never adds it to AbortReport::kept, so aborting a private merge silently loses unrelated post-stop work; apply the same ownership comparison before restoring target paths.

AGENTS.md reference: AGENTS.md:L3-L5

Useful? React with 👍 / 👎.

let mut kept = Vec::new();
for (p, (blob_id, _, perms)) in
worktree::tree_file_entries_with_perms(&mut store, theirs.root)?
{
if prior.contains_key(&p) || !sparse.matches(&p) {
continue;
}
let full = worktree::safe_join(&self.layout.root, &p)?;
// Not knowing what stands there must stop the abort before it
// clears the stop's records (decrypted text could linger).
let Some(meta) = worktree::lstat(&full)? else {
continue;
};
let recorded = plaintext.contains(&p);
// The stop wrote regular files: a symlink there is the user's.
let ours = meta.is_file()
&& !worktree::under_symlink(&self.layout.root, &p)
&& if perms & PROTECTED != 0 {
recorded
} else {
recorded || conflicted.contains(&p) || worktree::disk_is_blob(&full, &blob_id)
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if ours {
written.insert(p);
} else {
kept.push(p);
}
}
let skipped = self.materialize_private(
"merge --abort",
&mut store,
Expand All @@ -917,7 +971,7 @@ impl Repo {
// After the restore, so a failed restore leaves the sidecars to retry.
self.remove_conflict_sidecars_unless(&mut |p| prior.contains_key(p))?;
crate::merge_state::clear(&self.layout)?;
Ok(skipped)
Ok(crate::repo::AbortReport { skipped, kept })
}

/// Build inner trees + snapshot from a decided file map, seal everything
Expand Down Expand Up @@ -1522,6 +1576,21 @@ impl Repo {
}
}
}
// Drop the prior-tip paths the merge deleted, with the removals
// above and before any conflict output is written: a failure here
// then leaves no markers without a merge state, and is never
// swallowed (completion would resurrect the file from disk).
for p in prior_paths.difference(&merged_paths) {
if !sparse.matches(p) {
continue;
}
let full = worktree::safe_join(&self.layout.root, p)?;
match std::fs::remove_file(full) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
Comment on lines +1587 to +1591

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make private-merge deletion failures atomic

When a conflicted private merge deletes multiple prior-tip paths and a later unlink fails, this loop has already removed earlier paths but merge_state::write has not yet run, so there is no abort state and retrying the merge is rejected by the dirty-tree guard. Fresh evidence in the final code is that deletion errors are now propagated before conflict output, but successful earlier unlinks are not rolled back; preflight or stage all deletions before mutating the checkout.

AGENTS.md reference: AGENTS.md:L11-L13

Useful? React with 👍 / 👎.

}
}
// Record what is about to land on disk in plaintext, and the
// sidecars, before writing it: completion and abort need both
// (see `conflict_plaintext`). Nothing here is sealed, and it names
Expand Down Expand Up @@ -1563,13 +1632,6 @@ impl Repo {
let full = worktree::safe_join(&self.layout.root, name)?;
std::fs::write(&full, bytes)?;
}
for p in prior_paths.difference(&merged_paths) {
if !sparse.matches(p) {
continue;
}
let full = worktree::safe_join(&self.layout.root, p)?;
let _ = std::fs::remove_file(full);
}
crate::merge_state::write(&self.layout, &theirs, &fm.conflicts, None)?;
return Err(Error::MergeConflicts(fm.conflicts.len()));
}
Expand Down
18 changes: 18 additions & 0 deletions crates/repo/src/private_abort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,24 @@ fn abort_after_a_text_conflict_restores_the_private_tip() {
f.finish();
}

#[test]
fn abort_keeps_a_file_of_theirs_the_user_changed_after_the_stop() {
// `m.txt` is theirs' add, laid by the stop. The user's edit of it is not
// the stop's file any more, and abort says it left it (#255).
let f = fixture("kept", true, false, false);
assert!(matches!(
f.repo.merge_into_private("main", "alice", f.id()),
Err(Error::MergeConflicts(1))
));
put(&f.root, "m.txt", b"mine\n");
let report = f.repo.merge_abort_with_identity(f.id()).unwrap();
f.assert_no_state();
assert_eq!(report.kept, vec!["m.txt".to_string()]);
assert_eq!(read(&f.root, "m.txt"), "mine\n");
assert_eq!(read(&f.root, "a.txt"), "private edit\n");
f.finish();
}

#[test]
fn abort_after_a_binary_conflict_removes_the_sidecar() {
let f = fixture("bin", false, true, false);
Expand Down
Loading
Loading