Elffuss BraidHub

utopia-ia/elffuss-braid public

Git import never takes a braid branch backwards

Importing again pointed every braid ref named like a git branch or tag
at git's commit, without looking at what braid had. After agents had
landed work in braid, a second import moved main back to git's commit:
nothing was lost from the store, and undo reverted it, but the branch
lost its head.

An import now moves a braid ref only when it does not exist yet, or
when git's commit descends from it. A ref where braid is ahead, where
the two have diverged, whose target is not a changeset, or that moved
while the import ran, stays where it is. The report lists it under
`kept`, with the reason. The git map still records every imported
object. Found by the claims review of the project site.
Changesetbceec3f3d91e76d7f355fdbf0ecab4e82449d52c03b36147d98d305cb0bee5d0
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 11:44 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 11:44 +02:00
Parents4fb2400e6864

Browse the files at this changeset

4 files changed

modified crates/cli/src/main.rs +20 −0
@@ -1057,6 +1057,12 @@
10571057 "blobs": report.blobs,
10581058 "tags": report.tags,
10591059 "refs": refs,
1060+ "kept": import.kept.iter().map(|k| json!({
1061+ "name": k.name,
1062+ "braid": k.braid.to_hex(),
1063+ "git": k.git.to_hex(),
1064+ "reason": k.reason.code(),
1065+ })).collect::<Vec<_>>(),
10601066 "operation": import.operation.as_ref().map(|op| op.seq),
10611067 }))?;
10621068 } else {
@@ -1068,6 +1074,20 @@
10681074 report.tags,
10691075 report.refs.len()
10701076 );
1077+ for kept in &import.kept {
1078+ let why = match kept.reason {
1079+ braid_repo::KeptReason::Ahead => "braid has work git does not have",
1080+ braid_repo::KeptReason::Diverged => "braid and git have each moved on",
1081+ braid_repo::KeptReason::NotAChangeset => "one side is not a changeset",
1082+ braid_repo::KeptReason::Moved => "it moved while the import ran",
1083+ };
1084+ println!(
1085+ "Kept {} at {}: {why} (git is at {}).",
1086+ kept.name,
1087+ kept.braid.short(),
1088+ kept.git.short()
1089+ );
1090+ }
10711091 if import.operation.is_none() {
10721092 println!("Nothing changed.");
10731093 }
modified crates/cli/tests/cli.rs +73 −0
@@ -471,3 +471,76 @@
471471 assert!(refs["refs"].as_object().unwrap().is_empty());
472472 assert_eq!(run_json(braid_in(&repo).arg("fsck"))["clean"], true);
473473 }
474+
475+#[test]
476+fn importing_again_never_takes_a_braid_branch_backwards() {
477+ let work = tempfile::tempdir().unwrap();
478+ let src = work.path().join("src");
479+ std::fs::create_dir(&src).unwrap();
480+ git(&src, &["init", "-q", "-b", "main"]);
481+ std::fs::write(src.join("a.txt"), "a\n").unwrap();
482+ git(&src, &["add", "a.txt"]);
483+ git(&src, &["commit", "-q", "-m", "A"]);
484+ git(&src, &["branch", "feature"]);
485+
486+ let repo = work.path().join("braid");
487+ assert!(
488+ braid()
489+ .arg("init")
490+ .arg(&repo)
491+ .output()
492+ .unwrap()
493+ .status
494+ .success()
495+ );
496+ run_json(braid_in(&repo).args(["git", "import"]).arg(&src));
497+ let imported = run_json(braid_in(&repo).arg("refs"))["refs"]["main"]
498+ .as_str()
499+ .unwrap()
500+ .to_owned();
501+
502+ // A change lands on main in braid, without a working copy.
503+ let file = work.path().join("b.txt");
504+ std::fs::write(&file, "b\n").unwrap();
505+ let set = format!("b.txt=@{}", file.display());
506+ run_json(
507+ braid_in(&repo)
508+ .env("BRAID_AUTHOR", "Ada <ada@example.org>")
509+ .args([
510+ "change", "create", "--base", "main", "--set", &set, "-m", "B", "--land", "main",
511+ ]),
512+ );
513+ let ahead = run_json(braid_in(&repo).arg("refs"))["refs"]["main"]
514+ .as_str()
515+ .unwrap()
516+ .to_owned();
517+ assert_ne!(ahead, imported);
518+
519+ // Importing again with nothing new in git keeps braid's main where it is.
520+ let again = run_json(braid_in(&repo).args(["git", "import"]).arg(&src));
521+ assert_eq!(again["kept"][0]["name"], "main");
522+ assert_eq!(again["kept"][0]["reason"], "ahead");
523+ assert_eq!(
524+ run_json(braid_in(&repo).arg("refs"))["refs"]["main"],
525+ ahead.as_str()
526+ );
527+
528+ // Git moves on too: main diverges and stays in braid, feature only moved
529+ // forward and follows git.
530+ std::fs::write(src.join("c.txt"), "c\n").unwrap();
531+ git(&src, &["add", "c.txt"]);
532+ git(&src, &["commit", "-q", "-m", "C"]);
533+ git(&src, &["checkout", "-q", "feature"]);
534+ std::fs::write(src.join("d.txt"), "d\n").unwrap();
535+ git(&src, &["add", "d.txt"]);
536+ git(&src, &["commit", "-q", "-m", "D"]);
537+ let third = run_json(braid_in(&repo).args(["git", "import"]).arg(&src));
538+ let kept = third["kept"].as_array().unwrap();
539+ assert_eq!(kept.len(), 1, "{third}");
540+ assert_eq!(kept[0]["name"], "main");
541+ assert_eq!(kept[0]["reason"], "diverged");
542+ let refs = run_json(braid_in(&repo).arg("refs"));
543+ assert_eq!(refs["refs"]["main"], ahead.as_str());
544+ assert_ne!(refs["refs"]["feature"], imported.as_str());
545+ assert_eq!(run_json(braid_in(&repo).arg("fsck"))["clean"], true);
546+}
modified crates/repo/src/git.rs +109 −10
@@ -87,6 +87,47 @@
8787 pub report: ImportReport,
8888 /// The operation that moved the refs, or `None` when nothing changed.
8989 pub operation: Option<Operation>,
90+ /// Braid refs the import left where they were, because moving them would
91+ /// have dropped work braid has and git has not.
92+ pub kept: Vec<KeptRef>,
93+}
94+
95+/// A braid ref that an import did not move, and why.
96+#[derive(Clone, Debug, PartialEq, Eq)]
97+pub struct KeptRef {
98+ /// The braid ref.
99+ pub name: String,
100+ /// Where it stays.
101+ pub braid: ObjectId,
102+ /// What git's ref points to, as a braid object.
103+ pub git: ObjectId,
104+ /// Why it was not moved.
105+ pub reason: KeptReason,
106+}
107+
108+/// Why an import did not move a braid ref.
109+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110+pub enum KeptReason {
111+ /// Braid's ref already contains git's commit: braid is ahead.
112+ Ahead,
113+ /// Each side has work the other does not.
114+ Diverged,
115+ /// One side is not a changeset, for example a tag that moved in git.
116+ NotAChangeset,
117+ /// The ref moved while the import ran.
118+ Moved,
119+}
120+
121+impl KeptReason {
122+ /// The name used in JSON output.
123+ pub fn code(self) -> &'static str {
124+ match self {
125+ KeptReason::Ahead => "ahead",
126+ KeptReason::Diverged => "diverged",
127+ KeptReason::NotAChangeset => "not_a_changeset",
128+ KeptReason::Moved => "moved",
129+ }
130+ }
90131 }
91132
92133 fn store_error(err: TransactError<Infallible>) -> Error {
@@ -265,33 +306,91 @@
265306 .collect();
266307 wanted.push((MAP_REF.to_owned(), map_id));
267308
309+ // Decide which refs may move before taking the op log lock: a ref that
310+ // does not exist yet, or one git's commit descends from. A braid ref
311+ // with work git does not have stays where it is, so an import never
312+ // takes a branch backwards or sideways.
268313 let current = self.store.refs()?;
269- if wanted
270- .iter()
271- .all(|(name, id)| current.get(name) == Some(*id))
272- {
314+ let mut moves: Vec<(String, Option<ObjectId>, ObjectId)> = Vec::new();
315+ let mut kept = Vec::new();
316+ for (name, id) in &wanted {
317+ let now = current.get(name);
318+ if now == Some(*id) {
319+ continue;
320+ }
321+ match now {
322+ Some(now) if name != MAP_REF => match self.import_may_move(now, *id)? {
323+ None => moves.push((name.clone(), Some(now), *id)),
324+ Some(reason) => kept.push(KeptRef {
325+ name: name.clone(),
326+ braid: now,
327+ git: *id,
328+ reason,
329+ }),
330+ },
331+ _ => moves.push((name.clone(), now, *id)),
332+ }
333+ }
334+ if moves.is_empty() {
273335 return Ok(GitImport {
274336 report,
275337 operation: None,
338+ kept,
276339 });
277340 }
278- let description = format!("git import of {} refs", wanted.len() - 1);
341+ let moved = moves.iter().filter(|(name, ..)| name != MAP_REF).count();
342+ let description = if kept.is_empty() {
343+ format!("git import of {moved} refs")
344+ } else {
345+ format!("git import of {moved} refs, {} kept", kept.len())
346+ };
347+ let mut moved_meanwhile = Vec::new();
279348 let operation = self
280349 .store
281350 .transact(agent, &description, |refs| {
282- Ok(wanted
283- .iter()
284- .filter(|(name, id)| refs.get(name) != Some(*id))
285- .map(|(name, id)| RefUpdate::new(name.clone(), refs.get(name), Some(*id)))
286- .collect())
351+ let mut updates = Vec::with_capacity(moves.len());
352+ for (name, old, new) in &moves {
353+ let now = refs.get(name);
354+ if now == *old || name == MAP_REF {
355+ updates.push(RefUpdate::new(name.clone(), now, Some(*new)));
356+ } else if let Some(now) = now {
357+ moved_meanwhile.push(KeptRef {
358+ name: name.clone(),
359+ braid: now,
360+ git: *new,
361+ reason: KeptReason::Moved,
362+ });
363+ }
364+ }
365+ Ok(updates)
287366 })
288367 .map_err(store_error)?;
368+ kept.extend(moved_meanwhile);
289369 Ok(GitImport {
290370 report,
291371 operation: Some(operation),
372+ kept,
292373 })
293374 }
294375
376+ /// Whether an import may move a braid ref from `braid` to `git`: `None`
377+ /// when git's commit descends from braid's, otherwise why it may not.
378+ fn import_may_move(&self, braid: ObjectId, git: ObjectId) -> Result<Option<KeptReason>, Error> {
379+ let changeset = |id: &ObjectId| -> Result<bool, Error> {
380+ Ok(matches!(self.store.stat(id)?, Some((Kind::Changeset, _))))
381+ };
382+ if !changeset(&braid)? || !changeset(&git)? {
383+ return Ok(Some(KeptReason::NotAChangeset));
384+ }
385+ if braid_engine::is_ancestor(&self.store, braid, git)? {
386+ return Ok(None);
387+ }
388+ if braid_engine::is_ancestor(&self.store, git, braid)? {
389+ return Ok(Some(KeptReason::Ahead));
390+ }
391+ Ok(Some(KeptReason::Diverged))
392+ }
393+
295394 /// Writes the given braid refs (all of them when `names` is empty) into
296395 /// the git repository at `git_repo`, which must exist. Existing git refs
297396 /// of the same names are overwritten.
modified crates/repo/src/lib.rs +2 −2
@@ -44,8 +44,8 @@
4444 pub use clock::{local_now, signature_now};
4545 pub use config::{CONFIG_FILE, Config};
4646 pub use git::{
47- GIT_EXPORT_AGENT, GitImport, MAP_REF, REMOTE_PREFIX, braid_ref_for_git, git_ref_for_braid,
48- remote_ref,
47+ GIT_EXPORT_AGENT, GitImport, KeptReason, KeptRef, MAP_REF, REMOTE_PREFIX, braid_ref_for_git,
48+ git_ref_for_braid, remote_ref,
4949 };
5050 pub use history::{RepoHistory, StoreIndex};
5151 pub use link::{Location, WORKSPACES_DIR, WorkspaceLink, locate};