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
3 changes: 3 additions & 0 deletions .claude/skills/sc-cli-reference/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ cargo run --bin sc -- merge <public-branch> --identity <key> # ON a private br
# public branch IN (keeps an embargo current); the
# reverse (merge/cherry-pick/rebase FROM a private
# branch) is refused — publish first
cargo run --bin sc -- merge --abort --identity <key> # ON a private branch: abort a stopped merge
# (restores the private tip's checkout; the key is
# required, a keyless abort refuses and leaves the stop)
cargo run --bin sc -- merge <ref> [--identity <key>] # three-way merge (ff when possible; exits
# 1 on conflicts; --identity only needed when a
# protected path diverged in content on both sides)
Expand Down
7 changes: 6 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,11 @@ transport-adjacent. The rest, imperatively:
disk (out of view, or protected and skipped) instead of carrying the prior
tip, and under a sparse spec set on the public branch its conflict stop lays
out in-view files only and refuses an out-of-view conflict before any write (#240; no decided root, it would be unsealed).
A stopped private merge records `.sc/CONFLICT_PLAINTEXT` and
`.sc/CONFLICT_SIDECARS` like the public stop (completion leaves sidecars out of
the sealed tree and removes them), and `merge --abort` needs `--identity` (a
keyless or non-recipient abort refuses, leaving the stop intact) and restores
the private tip's checkout (#246).
`sc branch revoke` rotates the KEK but a recipient who already fetched keeps
the old manifest (rotation ≠ erasure). **Keep identity files outside the
working tree** — a key committed under a private branch is sealed in and
Expand Down Expand Up @@ -284,7 +289,7 @@ transport-adjacent. The rest, imperatively:
the view.
- **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. Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded.
away and retry. Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded (except that a private stop refuses a `.theirs` sidecar that would land on an existing file).
- **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. A push into a repo with a stopped op is
Expand Down
4 changes: 3 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,9 @@ across every phase.
branch remain individually sealed under a branch KEK. Grant is O(1), revoke
rotates the KEK, and publish atomically replays scanner-gated public history.
A conflicted merge of a public branch into a private one under a sparse spec honors the view and decides
out-of-view paths by the merge, not the prior tip (#240). (ADR-0044.)
out-of-view paths by the merge, not the prior tip (#240). A stopped merge into
a private branch aborts with `--identity` and records its `.theirs` sidecars
and plaintext like the public stop (#246). (ADR-0044.)
- **Phase 35 — Native desktop browser.** A bundled Tauri v2 application opens
`.sc` repositories through the Rust crates and renders local/remote refs, the
all-parent snapshot DAG, provenance, public files, and first-parent diffs.
Expand Down
14 changes: 11 additions & 3 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,17 @@ enum Cmd {
/// Branch to merge in.
branch: Option<String>,
/// Abandon an in-progress merge and restore the working tree. When given,
/// the BRANCH argument is ignored.
/// the BRANCH argument is ignored. On a private branch it needs
/// `--identity` (the tip is sealed).
#[arg(long)]
abort: bool,
/// Author recorded on the merge snapshot (default: $SC_AUTHOR, then the
/// OS username).
#[arg(long)]
author: Option<String>,
/// Identity key to decrypt protected paths that diverged in content on
/// both sides (ciphertext-id fast paths need no identity at all).
/// both sides (ciphertext-id fast paths need no identity at all), and
/// to open a private branch.
#[arg(long)]
identity: Option<PathBuf>,
},
Expand Down Expand Up @@ -2179,7 +2181,13 @@ fn run_merge(
) -> Result<()> {
let repo = open_repo()?;
if abort {
let skipped = repo.merge_abort()?;
// Only a private branch needs the key to restore its checkout.
let sk = if repo.head_private()?.is_some() {
resolve_identity_opt(identity)?
} else {
None
};
let skipped = repo.merge_abort_with_identity(sk.as_ref())?;
println!("merge aborted; working tree restored");
for path in &skipped {
eprintln!("skipped (no key): {path}");
Expand Down
59 changes: 59 additions & 0 deletions crates/cli/tests/merge_exit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,62 @@ fn merge_with_conflicts_exits_nonzero_and_abort_exits_zero() {

std::fs::remove_dir_all(&root).unwrap();
}

#[test]
fn abort_on_a_private_branch_needs_the_identity() {
let root = tmp("private");
let keys = tmp("private-keys");
let id = keys.join("alice.id");
let id_arg = id.to_str().unwrap();
assert!(sc(&keys, &["keygen", "--out", id_arg]).status.success());

assert!(sc(&root, &["init"]).status.success());
std::fs::write(root.join("file.txt"), "base\n").unwrap();
assert!(sc(&root, &["commit", "-m", "base"]).status.success());
let ok = |args: &[&str]| {
let out = sc(&root, args);
assert!(
out.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
};
ok(&["branch", "fix", "--private", "--identity", id_arg]);
ok(&["switch", "fix", "--identity", id_arg]);
std::fs::write(root.join("file.txt"), "private\n").unwrap();
ok(&["commit", "-m", "private", "--identity", id_arg]);
ok(&["switch", "main", "--identity", id_arg]);
std::fs::write(root.join("file.txt"), "public\n").unwrap();
ok(&["commit", "-m", "public"]);
ok(&["switch", "fix", "--identity", id_arg]);

let out = sc(&root, &["merge", "main", "--identity", id_arg]);
assert_eq!(out.status.code(), Some(1), "conflicted merge must exit 1");

// No key: refused, and the stop is still there to abort.
let mut keyless = Command::new(env!("CARGO_BIN_EXE_sc"));
keyless
.args(["merge", "--abort"])
.current_dir(&root)
.env("SC_IDENTITY", keys.join("absent"));
assert!(!keyless.output().unwrap().status.success());
assert!(std::fs::read_to_string(root.join("file.txt"))
.unwrap()
.contains("<<<<<<<"));

let abort = sc(&root, &["merge", "--abort", "--identity", id_arg]);
assert!(
abort.status.success(),
"abort: {}",
String::from_utf8_lossy(&abort.stderr)
);
assert_eq!(
std::fs::read_to_string(root.join("file.txt")).unwrap(),
"private\n"
);
assert!(!root.join(".sc/MERGE_HEAD").exists());

std::fs::remove_dir_all(&root).unwrap();
std::fs::remove_dir_all(&keys).unwrap();
assert!(!root.exists() && !keys.exists(), "test dir left behind");
}
2 changes: 2 additions & 0 deletions crates/repo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ mod partial_walks;
pub mod pick_state;
pub mod private;
#[cfg(test)]
mod private_abort;
#[cfg(test)]
mod private_sparse;
pub mod promisor;
pub mod protect;
Expand Down
129 changes: 125 additions & 4 deletions crates/repo/src/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl PrivateCtx {
/// The inner (plaintext-id) tip snapshot id. At branch creation this is
/// the public base itself; after the first private commit it is a private
/// inner id resolvable only through the index.
fn inner_tip(&self) -> Result<ObjectId> {
pub(crate) fn inner_tip(&self) -> Result<ObjectId> {
self.index
.inner_tip
.ok_or_else(|| Error::BadRef("private branch manifest has no inner tip".into()))
Expand Down Expand Up @@ -183,7 +183,7 @@ impl Repo {
}
}

fn get_inner_snapshot(
pub(crate) fn get_inner_snapshot(
&self,
store: &mut Store,
ctx: &PrivateCtx,
Expand Down Expand Up @@ -706,6 +706,30 @@ impl Repo {
tracked.extend(d.keys().cloned());
}
let files = worktree::read_worktree(&self.layout, &tracked)?;
// A sidecar the stop wrote is working-tree scratch: it reaches neither
// the scanner nor the sealed tree, unless the merge's outcome tracks
// that name (then it is the user's own file).
let (files, sidecars) = if merge_head.is_some() {
let scratch = crate::conflict_plaintext::read_sidecars(&self.layout)?;
let source = decided.as_ref().unwrap_or(&prior);
let is_scratch = |p: &str| scratch.contains(p) && !source.contains_key(p);
(
files
.into_iter()
.filter(|(p, _, _)| !is_scratch(p))
.collect(),
scratch,
)
} else {
(files, Default::default())
};
// Paths the stop wrote in plaintext. One now absent from disk was
// deleted by the user: it must not be carried back from the merge.
let conflict_plaintext = if merge_head.is_some() {
crate::conflict_plaintext::read(&self.layout)?
} else {
Default::default()
};

// Scanner gate on the plaintext partition (protected-prefix files are
// sealed at publish, exempt here exactly as in a public commit).
Expand Down Expand Up @@ -759,7 +783,10 @@ impl Repo {
// recorded: a decided tree cannot sit in unsealed `.sc/` state.
let source = decided.as_ref().unwrap_or(&prior);
for (path, e) in source {
if entries.contains_key(path) || disk_paths.contains(path) {
if entries.contains_key(path)
|| disk_paths.contains(path)
|| conflict_plaintext.contains(path)
{
continue;
}
if !sparse.matches(path) || e.2 & PROTECTED != 0 {
Expand Down Expand Up @@ -789,6 +816,7 @@ impl Repo {
Some(mh) => vec![inner_tip, mh],
};
let mut index = ctx.index.clone();
let committed_paths: BTreeSet<String> = entries.keys().cloned().collect();
let new_tip = self.seal_commit(
&mut store, &ctx, &mut index, &carried, entries, new_blobs, parents, secrets,
protection, author, message,
Expand All @@ -807,6 +835,12 @@ impl Repo {
};
let new_mid = store.put(Object::Manifest(new_manifest))?;
drop(store);
// The sidecars were left out of the sealed tree; remove them before
// the ref moves, or the next commit would take them. A failure here
// fails this commit with nothing moved and the record intact.
if !sidecars.is_empty() {
self.remove_conflict_sidecars_unless(&mut |p| committed_paths.contains(p))?;
}
refs::write_branch_tip(&self.layout, &branch, &new_mid)?;
crate::merge_state::clear(&self.layout)?;
let label = if merge_head.is_some() {
Expand All @@ -825,6 +859,51 @@ impl Repo {
Ok(new_tip)
}

/// Abandon a stopped merge into the private branch at HEAD: put the
/// private tip back on disk and clear the merge state. The ref never moved
/// during the stop and nothing was stored outside the sealed manifest, so
/// 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>> {
let (branch, mid, manifest) = self
.head_private()?
.ok_or_else(|| Error::NotPrivateBranch("HEAD".into()))?;
let ctx = self.open_private(&branch, mid, manifest, identity)?;
let sk = identity.expect("open_private succeeded");
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 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));
let skipped = self.materialize_private(
"merge --abort",
&mut store,
&ctx,
ours.root,
&written,
&ours.protection,
sk,
)?;
drop(store);
// 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)
}

/// Build inner trees + snapshot from a decided file map, seal everything
/// genuinely new (not in the index, not in `carried`), record the new
/// DEKs in `index`, and return the new inner tip id. The shared tail of
Expand Down Expand Up @@ -1390,6 +1469,26 @@ impl Repo {
plaintext.insert(&f.path, None);
}
drop(store);
// A sidecar lands beside its conflicted file and is removed again
// at completion or abort, so it must not stand on a file either
// side tracks or on one the user owns (the public stop's rule).
let merged_paths: BTreeSet<String> = fm.files.iter().map(|f| f.path.clone()).collect();
for (name, _) in &fm.sidecars {
if prior_paths.contains(name) || merged_paths.contains(name) {
return Err(Error::InvalidArgument(format!(
"merge has conflicts, and its sidecar {name} would overwrite a tracked \
file; rename or remove that file, then retry"
)));
}
let full = worktree::safe_join(&self.layout.root, name)?;
if full.symlink_metadata().is_ok() {
return Err(Error::InvalidArgument(format!(
"merge has conflicts, and writing {name} would overwrite an untracked \
or ignored file or directory (possibly a sidecar left by an earlier \
stop); move it away, then retry"
)));
}
}
// Removals first: a failed one must fail the stop before any
// other write, or completion would commit the stale plaintext.
for (path, pt) in &plaintext {
Expand All @@ -1402,6 +1501,29 @@ impl Repo {
}
}
}
// 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
// only paths the checkout already holds.
crate::conflict_plaintext::write(
&self.layout,
&fm.files
.iter()
.filter(|f| {
sparse.matches(&f.path)
&& (f.needs_encrypt
|| matches!(plaintext.get(f.path.as_str()), Some(Some(_))))
})
.map(|f| f.path.clone())
.collect::<Vec<_>>(),
)?;
crate::conflict_plaintext::write_sidecars(
&self.layout,
&fm.sidecars
.iter()
.map(|(n, _)| n.clone())
.collect::<Vec<_>>(),
)?;
for f in fm.files.iter().filter(|f| sparse.matches(&f.path)) {
let full = worktree::safe_join(&self.layout.root, &f.path)?;
if matches!(plaintext.get(f.path.as_str()), Some(None)) {
Expand All @@ -1420,7 +1542,6 @@ impl Repo {
let full = worktree::safe_join(&self.layout.root, name)?;
std::fs::write(&full, bytes)?;
}
let merged_paths: BTreeSet<String> = fm.files.iter().map(|f| f.path.clone()).collect();
for p in prior_paths.difference(&merged_paths) {
if !sparse.matches(p) {
continue;
Expand Down
Loading
Loading