Elffuss BraidHub

utopia-ia/elffuss-braid public

braid revert: undo a changeset with a new one, and land it

A revert of C is a changeset on C whose changes are the diff from C's tree
back to its first parent's, with a reverts field naming C. It lands as any
change does: rebased onto a head that moved on, path by path with C as the
base, and stopping with conflicts, exit status 2, when later work touched
the same lines. Roots are refused, and merges unless --mainline 1. In a
repository linked to a hub the revert lands on the hub.
Changeset8f30159883ea823578c84da4e4e70d404eaf2fc6b988960a19879be6644f0aa4
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 11:41 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 11:41 +02:00
Parents4042011ee701

Browse the files at this changeset

13 files changed

modified crates/cli/src/agents.rs +1 −1
@@ -464,7 +464,7 @@
464464
465465 /// The repository's main branch among its branches `names`: `main`,
466466 /// `master`, or its only branch.
467-fn main_branch(names: &[&str]) -> Result<String> {
467+pub(crate) fn main_branch(names: &[&str]) -> Result<String> {
468468 if let Some(preferred) = ["main", "master"]
469469 .into_iter()
470470 .find(|preferred| names.contains(preferred))
modified crates/cli/src/hub/land.rs +61 −8
@@ -186,7 +186,8 @@
186186
187187 /// Lands one changeset, made without a working copy, on `branch` of the
188188 /// hub, then fetches. Every error names the changeset, and whether it
189-/// landed.
189+/// landed; when the answer was lost, it says to run `again`, the command
190+/// that made the changeset, once more.
190191 pub(crate) fn land_change(
191192 repo: &Repo,
192193 remote: &impl Remote,
@@ -194,6 +195,7 @@
194195 branch: &str,
195196 change: ObjectId,
196197 agent: &str,
198+ again: &str,
197199 ) -> Result<LandResponse> {
198200 let store = repo.store();
199201 let base = read_changeset(store, change)?.parents.first().copied();
@@ -207,13 +209,8 @@
207209 mode: LandMode::Rebase,
208210 agent: Some(agent.to_owned()),
209211 };
210- let response = land(store, remote, &request, OffBranch::Change { base }).map_err(|err| {
211- not_landed(
212- err,
213- &format!("its {branch} (changeset {change})"),
214- "braid change create",
215- )
216- })?;
212+ let response = land(store, remote, &request, OffBranch::Change { base })
213+ .map_err(|err| not_landed(err, &format!("its {branch} (changeset {change})"), again))?;
217214 let landed = match response.outcome.as_str() {
218215 "fast-forward" | "rebased" | "already-applied" => true,
219216 "conflicts" => false,
@@ -655,6 +652,7 @@
655652 "main",
656653 change,
657654 "agent-1",
655+ "braid change create",
658656 )
659657 .unwrap_err();
660658 let local = braid_engine::Error::BaseNotOnBranch {
@@ -676,10 +674,65 @@
676674 "main",
677675 change,
678676 "agent-1",
677+ "braid change create",
679678 )
680679 .unwrap();
681680 assert_eq!(response.outcome, "fast-forward");
682681 assert_eq!(s.hub_main(), Some(change));
683682 assert_eq!(s.local_main(), Some(change));
684683 }
684+
685+ #[test]
686+ fn a_revert_lands_on_the_hub_rebased_over_later_work() {
687+ let s = Setup::new();
688+ let base = s.local_main().unwrap();
689+ let culprit = ada_change(&s.local.repo, Some(base), &[("b.txt", "bad\n")]);
690+ let later = ada_change(&s.local.repo, Some(culprit), &[("c.txt", "c\n")]);
691+ for change in [culprit, later] {
692+ let response = land_change(
693+ &s.local.repo,
694+ &s.hub,
695+ &s.local.link,
696+ "main",
697+ change,
698+ "agent-1",
699+ "braid change create",
700+ )
701+ .unwrap();
702+ assert_eq!(response.outcome, "fast-forward");
703+ }
704+ let revert = braid_wc::create_revert(
705+ s.local.repo.store(),
706+ &braid_wc::RevertRequest {
707+ culprit,
708+ allow_merge: false,
709+ author: ada(),
710+ agent: "verifier".to_owned(),
711+ },
712+ )
713+ .unwrap();
714+ let response = land_change(
715+ &s.local.repo,
716+ &s.hub,
717+ &s.local.link,
718+ "main",
719+ revert,
720+ "verifier",
721+ "braid revert",
722+ )
723+ .unwrap();
724+ assert_eq!(response.outcome, "rebased");
725+ let head = s.hub_main().unwrap();
726+ assert_eq!(s.local_main(), Some(head));
727+ let store = s.local.repo.store();
728+ let root = braid_engine::read_changeset(store, head).unwrap().root;
729+ let file = |path: &str| match braid_engine::entry_at(store, root, path.as_bytes()) {
730+ Ok(Some(braid_format::EntryKind::File { blob, .. })) => {
731+ braid_engine::read_blob(store, blob).unwrap()
732+ }
733+ other => panic!("{path}: {other:?}"),
734+ };
735+ assert_eq!(file("b.txt"), b"b\n");
736+ assert_eq!(file("c.txt"), b"c\n");
737+ }
685738 }
modified crates/cli/src/hub/resilience_tests.rs +2 −1
@@ -726,7 +726,8 @@
726726 &s.local.link,
727727 "main",
728728 change,
729- "agent-1"
729+ "agent-1",
730+ "braid change create"
730731 )
731732 .unwrap_err()
732733 );
modified crates/cli/src/main.rs +6 −0
@@ -6,6 +6,7 @@
66 mod agents;
77 mod history;
88 mod hub;
9+mod revert;
910 mod sync;
1011 mod work;
1112
@@ -313,6 +314,10 @@
313314 #[command(subcommand)]
314315 action: work::ChangeAction,
315316 },
317+ /// Undo a changeset with a new one, and land it (exit status 2 on
318+ /// conflicts).
319+ #[command(long_about = revert::REVERT_HELP)]
320+ Revert(revert::RevertArgs),
316321 }
317322
318323 #[derive(Debug, Subcommand)]
@@ -515,6 +520,7 @@
515520 Command::Resolve { paths } => work::resolve(cli, paths),
516521 Command::Track { paths } => work::track(cli, paths),
517522 Command::Change { action } => work::change(cli, action),
523+ Command::Revert(args) => revert::revert(cli, args),
518524 }
519525 }
520526
added crates/cli/src/revert.rs +183 −0
@@ -0,0 +1,183 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! `revert`: undo a changeset that landed with a new changeset, and land
5+//! that.
6+
7+use std::process::ExitCode;
8+
9+use anyhow::{Result, bail};
10+use braid_format::ObjectId;
11+use braid_repo::Repo;
12+use braid_wc::{Identity, RevertRequest};
13+use clap::Args;
14+use serde_json::json;
15+
16+use crate::hub::{self, link::Link};
17+use crate::work::{IdentityArgs, Report, branches, identity, print_conflicts};
18+use crate::{Cli, open_repo, print_json, resolve_changeset};
19+
20+/// The long help of `revert`.
21+pub(crate) const REVERT_HELP: &str =
22+ "Undo a changeset that landed on a branch: make a new changeset on it
23+whose changes put every file back as its first parent had it, modes,
24+symlinks and submodules included, and land that on the branch. The message
25+is `Revert \"<subject>\"`, and the changeset has a `reverts` field naming
26+the one it undoes.
27+
28+Landing works as for any change: when the branch has moved on since, the
29+revert is rebased onto its head path by path, so later changes to other
30+lines and files stay. When a later change touched the same lines, the
31+landing stops with conflicts, the branch does not move and the exit status
32+is 2: undo the change by hand in a workspace instead.
33+
34+A changeset without parents cannot be reverted, nor a merge unless
35+--mainline 1 says to undo what it brought in against its first parent.
36+--no-land only makes the changeset and prints its id. In a repository
37+linked to a hub, the revert lands on the hub, then fetches; --local, or
38+BRAID_HUB=off, lands here.
39+
40+With --json it prints revert, the new changeset's id; reverts, the one it
41+undoes; branch; and land, the report of the landing as `braid land --help`
42+describes it, or null with --no-land.";
43+
44+#[derive(Debug, Args)]
45+pub(crate) struct RevertArgs {
46+ /// The changeset to undo: a ref, an id, or a short id (6 hex digits or
47+ /// more).
48+ revision: String,
49+ /// The branch to land the revert on (default: main, master, or the
50+ /// repository's only branch).
51+ #[arg(long, value_name = "BRANCH")]
52+ branch: Option<String>,
53+ /// Only make the revert and print its id; do not land it.
54+ #[arg(long)]
55+ no_land: bool,
56+ /// Revert a merge against this parent: only 1, the first, is supported.
57+ #[arg(long, value_name = "PARENT", value_parser = clap::value_parser!(u8).range(1..=1))]
58+ mainline: Option<u8>,
59+ #[command(flatten)]
60+ identity: IdentityArgs,
61+ /// Land in this repository even if it is linked to a hub.
62+ #[arg(long)]
63+ local: bool,
64+}
65+
66+/// The branch a command acts on: the one given, or else the repository's
67+/// main branch: `main`, `master`, or its only branch.
68+pub(crate) fn branch_or_main(repo: &Repo, given: Option<&str>) -> Result<String> {
69+ match given {
70+ Some(branch) => Ok(branch.to_owned()),
71+ None => crate::agents::main_branch(&branches(&repo.store().refs()?)),
72+ }
73+}
74+
75+/// Refuses to revert `culprit` on `branch` unless it is on the branch's
76+/// first-parent chain, as landing requires: anything else would be stored
77+/// first and refused after.
78+pub(crate) fn check_on_branch(repo: &Repo, branch: &str, culprit: ObjectId) -> Result<()> {
79+ let Some(head) = repo.store().refs()?.get(branch) else {
80+ bail!("there is no branch {branch:?} to land the revert on");
81+ };
82+ if !braid_engine::first_parent_chain_contains(repo.store(), head, culprit, usize::MAX)? {
83+ bail!(
84+ "changeset {} is not on {branch}'s first-parent chain: only what landed on {branch} can be reverted there",
85+ culprit.short()
86+ );
87+ }
88+ Ok(())
89+}
90+
91+/// Lands `change`, a revert made with [`braid_wc::create_revert`], on
92+/// `branch`: on the hub of `link`, then fetching, or in this repository.
93+pub(crate) fn land_revert(
94+ repo: &Repo,
95+ link: Option<&Link>,
96+ branch: &str,
97+ change: ObjectId,
98+ agent: &str,
99+ committer: &Identity,
100+) -> Result<Report> {
101+ Ok(match link {
102+ Some(link) => {
103+ let hub = hub::connect(link)?;
104+ let remote = hub.repo(link.repo.clone());
105+ let response =
106+ hub::land::land_change(repo, &remote, link, branch, change, agent, "braid revert")?;
107+ Report::hub(&response)
108+ }
109+ None => Report::landing(&braid_wc::land_change(
110+ repo.store(),
111+ branch,
112+ change,
113+ agent,
114+ committer,
115+ )?),
116+ })
117+}
118+
119+pub(crate) fn revert(cli: &Cli, args: &RevertArgs) -> Result<ExitCode> {
120+ let repo = open_repo(cli)?;
121+ let culprit = resolve_changeset(&repo, &args.revision)?;
122+ let branch = branch_or_main(&repo, args.branch.as_deref())?;
123+ let author = identity(&args.identity, &repo)?;
124+ let link = if args.no_land {
125+ None
126+ } else {
127+ hub::linked(&repo, args.local)?
128+ };
129+ if !args.no_land && link.is_none() {
130+ check_on_branch(&repo, &branch, culprit)?;
131+ }
132+ let change = braid_wc::create_revert(
133+ repo.store(),
134+ &RevertRequest {
135+ culprit,
136+ allow_merge: args.mainline.is_some(),
137+ author: author.clone(),
138+ agent: cli.agent.clone(),
139+ },
140+ )?;
141+ let report = if args.no_land {
142+ None
143+ } else {
144+ Some(land_revert(
145+ &repo,
146+ link.as_ref(),
147+ &branch,
148+ change,
149+ &cli.agent,
150+ &author,
151+ )?)
152+ };
153+ let code = report.as_ref().map_or(ExitCode::SUCCESS, Report::exit_code);
154+ if cli.json {
155+ print_json(&json!({
156+ "revert": change.to_hex(),
157+ "reverts": culprit.to_hex(),
158+ "branch": branch,
159+ "land": report.as_ref().map(Report::json),
160+ }))?;
161+ return Ok(code);
162+ }
163+ match &report {
164+ None => println!(
165+ "Made {}, the revert of {}; it has not landed",
166+ change.short(),
167+ culprit.short()
168+ ),
169+ Some(report) if report.conflicted() => {
170+ println!(
171+ "The revert of {} conflicts with what landed on {branch} since; {branch} did not move:",
172+ culprit.short()
173+ );
174+ print_conflicts(&report.conflicts);
175+ println!("Undo the change by hand in a workspace instead.");
176+ }
177+ Some(report) => {
178+ println!("Reverted {} with {}", culprit.short(), change.short());
179+ report.print_landing(cli);
180+ }
181+ }
182+ Ok(code)
183+}
modified crates/cli/src/work.rs +28 −20
@@ -29,7 +29,7 @@
2929 use crate::{Cli, change_json, open_repo, print_json, resolve_changeset};
3030
3131 /// Exit status of a command that stopped on conflicts.
32-const CONFLICTS: u8 = 2;
32+pub(crate) const CONFLICTS: u8 = 2;
3333
3434 /// The fields of the report `land`, `update` and `change create --land`
3535 /// print with `--json`, for their long help.
@@ -396,7 +396,7 @@
396396 )
397397 }
398398
399-fn identity(args: &IdentityArgs, repo: &Repo) -> Result<Identity> {
399+pub(crate) fn identity(args: &IdentityArgs, repo: &Repo) -> Result<Identity> {
400400 Ok(Identity::resolve(args.author.as_deref(), repo)?)
401401 }
402402
@@ -763,28 +763,29 @@
763763 })
764764 }
765765
766-/// What `land`, `update` and `change create --land` report, in one shape:
767-/// the fields their long help lists. A landing on a hub fills it from the
768-/// hub's answer, so that it prints exactly what a local landing does.
769-struct Report {
770- branch: String,
771- outcome: String,
766+/// What `land`, `update`, `change create --land` and `revert` report, in
767+/// one shape: the fields their long help lists. A landing on a hub fills it
768+/// from the hub's answer, so that it prints exactly what a local landing
769+/// does.
770+pub(crate) struct Report {
771+ pub(crate) branch: String,
772+ pub(crate) outcome: String,
772773 head_before: Option<ObjectId>,
773- head: Option<ObjectId>,
774+ pub(crate) head: Option<ObjectId>,
774775 placed: Vec<Placed>,
775776 merged_paths: Vec<String>,
776777 operation: Option<u64>,
777778 change: Option<ObjectId>,
778779 /// Each conflict as data (see [`conflict_json`]).
779- conflicts: Vec<Value>,
780- next: Option<String>,
780+ pub(crate) conflicts: Vec<Value>,
781+ pub(crate) next: Option<String>,
781782 /// For a workspace: its base afterwards, and the paths of its working
782783 /// copy written or removed.
783784 workspace: Option<(Option<ObjectId>, Vec<String>)>,
784785 }
785786
786787 impl Report {
787- fn landing(report: &LandReport) -> Report {
788+ pub(crate) fn landing(report: &LandReport) -> Report {
788789 let (outcome, change, conflicts): (_, _, &[Conflict]) = match &report.landed {
789790 Landed::Nothing => ("nothing", None, &[]),
790791 Landed::FastForward(_) => ("fast-forward", None, &[]),
@@ -809,7 +810,7 @@
809810 }
810811
811812 /// A landing as the hub answered it.
812- fn hub(response: &LandResponse) -> Report {
813+ pub(crate) fn hub(response: &LandResponse) -> Report {
813814 Report {
814815 branch: response.reference.clone(),
815816 outcome: response.outcome.clone(),
@@ -886,11 +887,11 @@
886887 }
887888 }
888889
889- fn conflicted(&self) -> bool {
890+ pub(crate) fn conflicted(&self) -> bool {
890891 self.outcome == "conflicts" || !self.conflicts.is_empty()
891892 }
892893
893- fn json(&self) -> Value {
894+ pub(crate) fn json(&self) -> Value {
894895 let mut value = json!({
895896 "branch": self.branch,
896897 "outcome": self.outcome,
@@ -913,7 +914,7 @@
913914 value
914915 }
915916
916- fn exit_code(&self) -> ExitCode {
917+ pub(crate) fn exit_code(&self) -> ExitCode {
917918 if self.conflicted() {
918919 ExitCode::from(CONFLICTS)
919920 } else {
@@ -942,7 +943,7 @@
942943 }
943944
944945 /// Prints a landing as text.
945- fn print_landing(&self, cli: &Cli) {
946+ pub(crate) fn print_landing(&self, cli: &Cli) {
946947 let branch = &self.branch;
947948 let several = self.placed.len() > 1;
948949 match self.outcome.as_str() {
@@ -1199,8 +1200,15 @@
11991200 Some(link) => {
12001201 let hub = hub::connect(&link)?;
12011202 let remote = hub.repo(link.repo.clone());
1202- let response =
1203- hub::land::land_change(&repo, &remote, &link, branch, change, &cli.agent)?;
1203+ let response = hub::land::land_change(
1204+ &repo,
1205+ &remote,
1206+ &link,
1207+ branch,
1208+ change,
1209+ &cli.agent,
1210+ "braid change create",
1211+ )?;
12041212 Report::hub(&response)
12051213 }
12061214 None => Report::landing(&braid_wc::land_change(
@@ -1313,7 +1321,7 @@
13131321 /// Prints conflicts as data ([`conflict_json`], or a hub's answer, which
13141322 /// has the same shape), one line each: the kind, the path, and the regions
13151323 /// of a content conflict, the directory removed, or the path collided with.
1316-fn print_conflicts(conflicts: &[Value]) {
1324+pub(crate) fn print_conflicts(conflicts: &[Value]) {
13171325 for conflict in conflicts {
13181326 let text = |key: &str| conflict[key].as_str().unwrap_or("");
13191327 let regions = conflict["hunks"].as_array().map_or(0, Vec::len);
added crates/cli/tests/revert.rs +244 −0
@@ -0,0 +1,244 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! `braid revert` end to end: a revert lands like any change, rebased over
5+//! later work, and stops with conflicts as `braid land` does when later
6+//! work touched the same lines.
7+
8+use std::path::{Path, PathBuf};
9+use std::process::{Command, Output};
10+
11+use serde_json::Value;
12+
13+fn braid(dir: &Path, args: &[&str]) -> Output {
14+ Command::new(env!("CARGO_BIN_EXE_braid"))
15+ .current_dir(dir)
16+ .args(args)
17+ .env("BRAID_AGENT", "tester")
18+ .env("BRAID_AUTHOR", "Ada <ada@example.org>")
19+ .env("BRAID_HUB", "off")
20+ .output()
21+ .unwrap()
22+}
23+
24+/// Runs braid with `--json`, expecting exit status `code`.
25+fn run(dir: &Path, args: &[&str], code: i32) -> Value {
26+ let mut all = args.to_vec();
27+ all.push("--json");
28+ let out = braid(dir, &all);
29+ assert_eq!(
30+ out.status.code(),
31+ Some(code),
32+ "braid {args:?}: {}{}",
33+ String::from_utf8_lossy(&out.stdout),
34+ String::from_utf8_lossy(&out.stderr)
35+ );
36+ serde_json::from_slice(&out.stdout).unwrap_or(Value::Null)
37+}
38+
39+fn id(value: &Value) -> String {
40+ value.as_str().unwrap().to_owned()
41+}
42+
43+struct Repo {
44+ _temp: tempfile::TempDir,
45+ dir: PathBuf,
46+ files: PathBuf,
47+}
48+
49+impl Repo {
50+ fn new() -> Repo {
51+ let temp = tempfile::tempdir().unwrap();
52+ let base = std::fs::canonicalize(temp.path()).unwrap();
53+ let dir = base.join("repo");
54+ let files = base.join("files");
55+ std::fs::create_dir(&files).unwrap();
56+ run(&base, &["init", dir.to_str().unwrap()], 0);
57+ Repo {
58+ _temp: temp,
59+ dir,
60+ files,
61+ }
62+ }
63+
64+ /// Lands a change on `main` that sets each path to its text, with
65+ /// `message`, and returns the changeset that holds it on `main`.
66+ fn land(&self, sets: &[(&str, &str)], message: &str) -> String {
67+ let main = self.head();
68+ let base = main.as_deref().unwrap_or("none");
69+ let mut args = vec![
70+ "change".to_owned(),
71+ "create".to_owned(),
72+ "--base".to_owned(),
73+ base.to_owned(),
74+ ];
75+ for (n, (path, text)) in sets.iter().enumerate() {
76+ let file = self.files.join(format!("{message}-{n}"));
77+ std::fs::write(&file, text).unwrap();
78+ args.push("--set".to_owned());
79+ args.push(format!("{path}=@{}", file.display()));
80+ }
81+ args.extend(["-m", message, "--land", "main"].map(str::to_owned));
82+ let args: Vec<&str> = args.iter().map(String::as_str).collect();
83+ let out = run(&self.dir, &args, 0);
84+ id(&out["land"]["head"])
85+ }
86+
87+ fn head(&self) -> Option<String> {
88+ let refs = run(&self.dir, &["refs"], 0);
89+ refs["refs"]["main"].as_str().map(str::to_owned)
90+ }
91+
92+ fn cat(&self, path: &str) -> String {
93+ let out = braid(&self.dir, &["cat-object", &format!("main:{path}")]);
94+ assert!(out.status.success(), "{path}");
95+ String::from_utf8(out.stdout).unwrap()
96+ }
97+}
98+
99+#[test]
100+fn a_revert_lands_and_puts_the_files_back() {
101+ let r = Repo::new();
102+ r.land(&[("a", "1\n2\n3\n"), ("b", "b\n")], "Seed");
103+ let culprit = r.land(&[("a", "1\nbad\n3\n"), ("new", "n\n")], "Break a\n\nbody");
104+ let out = run(&r.dir, &["revert", &culprit[..10]], 0);
105+ let revert = id(&out["revert"]);
106+ assert_eq!(out["reverts"], culprit.as_str());
107+ assert_eq!(out["branch"], "main");
108+ assert_eq!(out["land"]["outcome"], "fast-forward");
109+ assert_eq!(out["land"]["head"], revert.as_str());
110+ assert_eq!(r.cat("a"), "1\n2\n3\n");
111+ assert!(!braid(&r.dir, &["cat-object", "main:new"]).status.success());
112+
113+ let shown = run(&r.dir, &["show", &revert], 0);
114+ assert_eq!(shown["parents"][0], culprit.as_str());
115+ assert_eq!(
116+ shown["message"],
117+ format!("Revert \"Break a\"\n\nThis reverts changeset {culprit}.\n")
118+ );
119+ assert_eq!(shown["agent"], "tester");
120+ assert!(
121+ shown["extras"]
122+ .as_array()
123+ .unwrap()
124+ .contains(&serde_json::json!(["reverts", culprit]))
125+ );
126+ // A text report says what happened.
127+ let text = braid(&r.dir, &["revert", &revert]);
128+ assert!(text.status.success());
129+ let text = String::from_utf8(text.stdout).unwrap();
130+ assert!(
131+ text.starts_with(&format!("Reverted {}", &revert[..12])),
132+ "{text}"
133+ );
134+ assert_eq!(r.cat("a"), "1\nbad\n3\n");
135+}
136+
137+#[test]
138+fn a_revert_rebases_over_later_work() {
139+ let r = Repo::new();
140+ r.land(&[("a", "1\n2\n3\n4\n5\n")], "Seed");
141+ let culprit = r.land(&[("a", "1\n2\nbad\n4\n5\n")], "Break");
142+ r.land(&[("a", "one\n2\nbad\n4\n5\n"), ("c", "c\n")], "Later");
143+ let out = run(&r.dir, &["revert", &culprit, "--branch", "main"], 0);
144+ assert_eq!(out["land"]["outcome"], "rebased");
145+ assert_eq!(r.head().unwrap(), id(&out["land"]["head"]));
146+ assert_eq!(r.cat("a"), "one\n2\n3\n4\n5\n");
147+ assert_eq!(r.cat("c"), "c\n");
148+}
149+
150+#[test]
151+fn a_revert_that_conflicts_moves_nothing_and_exits_with_2() {
152+ let r = Repo::new();
153+ r.land(&[("a", "1\n2\n3\n")], "Seed");
154+ let culprit = r.land(&[("a", "1\nbad\n3\n")], "Break");
155+ let later = r.land(&[("a", "1\nworse\n3\n")], "Later");
156+ let out = run(&r.dir, &["revert", &culprit], 2);
157+ let land = &out["land"];
158+ assert_eq!(land["outcome"], "conflicts");
159+ assert_eq!(land["head"], later.as_str());
160+ assert_eq!(land["change"], out["revert"]);
161+ let conflict = &land["conflicts"][0];
162+ assert_eq!(conflict["path"], "a");
163+ assert_eq!(conflict["kind"], "CONTENT");
164+ assert_eq!(conflict["hunks"][0]["branch"]["text"], "worse\n");
165+ assert_eq!(conflict["hunks"][0]["workspace"]["text"], "2\n");
166+ assert_eq!(r.head().unwrap(), later);
167+ let text = braid(&r.dir, &["revert", &culprit]);
168+ assert_eq!(text.status.code(), Some(2));
169+ let text = String::from_utf8(text.stdout).unwrap();
170+ assert!(text.contains("did not move"), "{text}");
171+}
172+
173+#[test]
174+fn no_land_only_makes_the_revert() {
175+ let r = Repo::new();
176+ r.land(&[("a", "1\n")], "Seed");
177+ let culprit = r.land(&[("a", "2\n")], "Change");
178+ let out = run(&r.dir, &["revert", &culprit, "--no-land"], 0);
179+ assert_eq!(out["land"], Value::Null);
180+ assert_eq!(r.head().unwrap(), culprit);
181+ let revert = id(&out["revert"]);
182+ let shown = run(&r.dir, &["show", &revert], 0);
183+ assert_eq!(shown["parents"][0], culprit.as_str());
184+}
185+
186+#[test]
187+fn what_cannot_be_reverted_is_refused() {
188+ let r = Repo::new();
189+ let seed = r.land(&[("a", "1\n")], "Seed");
190+ let out = braid(&r.dir, &["revert", &seed]);
191+ assert_eq!(out.status.code(), Some(1));
192+ assert!(String::from_utf8_lossy(&out.stderr).contains("no parent"));
193+ // A changeset that is not on the branch.
194+ let off = run(
195+ &r.dir,
196+ &[
197+ "change", "create", "--base", &seed, "-m", "Off", "--delete", "a",
198+ ],
199+ 0,
200+ );
201+ let out = braid(&r.dir, &["revert", &id(&off["change"])]);
202+ assert_eq!(out.status.code(), Some(1));
203+ let err = String::from_utf8_lossy(&out.stderr);
204+ assert!(err.contains("first-parent chain"), "{err}");
205+ assert_eq!(r.head().unwrap(), seed);
206+ // Only the first parent of a merge is a mainline.
207+ let out = braid(&r.dir, &["revert", &seed, "--mainline", "2"]);
208+ assert_eq!(out.status.code(), Some(2));
209+}
210+
211+#[cfg(unix)]
212+#[test]
213+fn a_revert_puts_back_modes_and_removes_what_was_added() {
214+ use std::os::unix::fs::PermissionsExt;
215+ let r = Repo::new();
216+ r.land(&[("run.sh", "echo hi\n"), ("gone", "g\n")], "Seed");
217+ run(&r.dir, &["workspace", "add", "w"], 0);
218+ let ws = r.dir.join(".braid/work/w");
219+ std::fs::set_permissions(ws.join("run.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
220+ std::fs::remove_file(ws.join("gone")).unwrap();
221+ std::fs::write(ws.join("added"), "a\n").unwrap();
222+ run(&ws, &["commit", "-m", "Modes"], 0);
223+ let landed = run(&ws, &["land"], 0);
224+ let culprit = id(&landed["head"]);
225+ let shown = run(&r.dir, &["show", "main"], 0);
226+ assert_eq!(shown["changes"].as_array().unwrap().len(), 3);
227+
228+ run(&r.dir, &["revert", &culprit], 0);
229+ let back = run(&r.dir, &["diff", &culprit, "main"], 0);
230+ let ops: Vec<(String, String)> = back["changes"]
231+ .as_array()
232+ .unwrap()
233+ .iter()
234+ .map(|c| (id(&c["path"]), id(&c["op"])))
235+ .collect();
236+ assert_eq!(
237+ ops,
238+ [
239+ ("added".to_owned(), "delete".to_owned()),
240+ ("gone".to_owned(), "file".to_owned()),
241+ ("run.sh".to_owned(), "file".to_owned()),
242+ ]
243+ );
244+}
modified crates/engine/src/land.rs +38 −0
@@ -51,6 +51,12 @@
5151 /// field names the agent that made the change, wherever it landed.
5252 pub const AGENT: &[u8] = b"agent";
5353
54+/// The extra field a revert carries: the id, in hex, of the changeset it
55+/// undoes. A rebased revert keeps it, as it keeps every extra field but
56+/// [`REBASED_FROM`]. It says what the revert undoes; it proves nothing about
57+/// who made it.
58+pub const REVERTS: &[u8] = b"reverts";
59+
5460 /// What landing a change does to the branch.
5561 #[derive(Clone, Debug, PartialEq, Eq)]
5662 pub enum LandOutcome {
@@ -1015,6 +1021,38 @@
10151021 );
10161022 }
10171023
1024+ #[test]
1025+ fn a_rebased_revert_keeps_what_it_reverts() {
1026+ // A revert of `culprit` is a changeset on it whose changes are the
1027+ // diff back to its parent. Rebased onto a head that moved, the merge
1028+ // takes base = culprit, ours = head, theirs = the culprit's parent.
1029+ let repo = Repo::new();
1030+ let base = repo.commit(
1031+ &[],
1032+ vec![repo.set("f", "1\n2\n3\n4\n5\n"), repo.set("g", "1")],
1033+ );
1034+ let culprit = repo.commit(&[base], vec![repo.set("f", "1\n2\nbad\n4\n5\n")]);
1035+ let head = repo.commit(&[culprit], vec![repo.set("f", "one\n2\nbad\n4\n5\n")]);
1036+ let back = diff(&repo.objects, repo.root(culprit), repo.root(base)).unwrap();
1037+ let extras = vec![
1038+ (AGENT.to_vec(), b"verifier".to_vec()),
1039+ (REVERTS.to_vec(), culprit.to_hex().into_bytes()),
1040+ ];
1041+ let revert = commit_with_extras(&repo, vec![culprit], back, extras.clone());
1042+ let outcome = land(&repo.objects, Some(head), revert, signature("x")).unwrap();
1043+ let LandOutcome::Rebased { changeset, .. } = outcome else {
1044+ panic!("expected a rebase, got {outcome:?}");
1045+ };
1046+ let new = read_changeset(&repo.objects, changeset).unwrap();
1047+ assert_eq!(
1048+ repo.files(new.root),
1049+ text_map(&[("f", "one\n2\n3\n4\n5\n"), ("g", "1")])
1050+ );
1051+ let mut expected = extras;
1052+ expected.push((REBASED_FROM.to_vec(), revert.to_hex().into_bytes()));
1053+ assert_eq!(new.extras, expected);
1054+ }
1055+
10181056 fn commit_with_extras(
10191057 repo: &Repo,
10201058 parents: Vec<ObjectId>,
modified crates/engine/src/lib.rs +1 −1
@@ -89,7 +89,7 @@
8989 pub use diff::diff;
9090 pub use error::{ApplyProblem, Error, StoreError};
9191 pub use history::{DeriveReport, History};
92-pub use land::{AGENT, Conflict, ConflictKind, LandOutcome, REBASED_FROM, land};
92+pub use land::{AGENT, Conflict, ConflictKind, LandOutcome, REBASED_FROM, REVERTS, land};
9393 pub use merge::{BINARY_SNIFF_BYTES, ConflictHunk, HunkSide, MergeResult, is_binary, merge3};
9494 pub use path::MAX_PATH_DEPTH;
9595 pub use reach::{Reach, Reached, reachable};
modified crates/wc/src/change.rs +80 −2
@@ -1,14 +1,15 @@
11 // SPDX-License-Identifier: Apache-2.0
22 // Copyright (c) 2026 UtopiaIA
33
4-//! Making a changeset without a working copy, and landing one.
4+//! Making a changeset without a working copy, reverting one, and landing
5+//! one.
56 //!
67 //! An agent that knows which files it wants to change does not need a
78 //! checkout: it names the base, the new contents and the deletions, and can
89 //! state what it expects the base to hold at each path, so that it never
910 //! overwrites an edit it did not see.
1011
11-use braid_engine::{EMPTY_TREE, LandOutcome, entry_at, land, read_changeset};
12+use braid_engine::{EMPTY_TREE, LandOutcome, REVERTS, diff, entry_at, land, read_changeset};
1213 use braid_format::{Change, ChangeOp, EntryKind, Kind, ObjectId, Objects, validate_path};
1314 use braid_store::{RefUpdate, Store, TransactError};
1415
@@ -127,6 +128,81 @@
127128 Ok(id)
128129 }
129130
131+/// A revert to make: a changeset that undoes another.
132+#[derive(Clone, Debug)]
133+pub struct RevertRequest {
134+ /// The changeset to undo.
135+ pub culprit: ObjectId,
136+ /// Whether a merge may be reverted. Its revert undoes what it brought
137+ /// in against its first parent.
138+ pub allow_merge: bool,
139+ /// The author, who also commits it.
140+ pub author: Identity,
141+ /// The label of the agent making it, recorded as its
142+ /// [`AGENT`](braid_engine::AGENT) field.
143+ pub agent: String,
144+}
145+
146+/// Makes the revert of `request.culprit` (C), and returns its id: a
147+/// changeset whose only parent is C, whose changes turn C's tree back into
148+/// its first parent's, modes, symlinks and gitlinks included, with the
149+/// message `Revert "<C's subject>"` and a [`REVERTS`] field naming C.
150+///
151+/// It is stored but not landed. [`land_change`] lands it like any change:
152+/// on a branch that moved past C, the rebase merges each path with C as the
153+/// base, the head as ours and C's parent as theirs, which is what undoing C
154+/// on top of later work means; a later change to the same lines is a
155+/// conflict.
156+///
157+/// A changeset without parents, one that changes nothing, and a merge
158+/// unless [`RevertRequest::allow_merge`] says so, are refused.
159+pub fn create_revert(store: &Store, request: &RevertRequest) -> Result<ObjectId, Error> {
160+ let culprit = request.culprit;
161+ let changeset = read_changeset(store, culprit)?;
162+ let parent = match changeset.parents.as_slice() {
163+ [] => return Err(Error::RevertRoot(culprit)),
164+ [parent] => *parent,
165+ [parent, ..] if request.allow_merge => *parent,
166+ parents => {
167+ return Err(Error::RevertMerge {
168+ changeset: culprit,
169+ parents: parents.len(),
170+ });
171+ }
172+ };
173+ let parent_root = read_changeset(store, parent)?.root;
174+ let changes = diff(store, changeset.root, parent_root)?;
175+ if changes.is_empty() {
176+ return Err(Error::NothingToRevert(culprit));
177+ }
178+ let mut message = format!("Revert \"{}\"", subject(&changeset.message)).into_bytes();
179+ message.extend_from_slice(format!("\n\nThis reverts changeset {culprit}.\n").as_bytes());
180+ let mut extras = crate::rebase::agent_extras(&request.agent);
181+ extras.push((REVERTS.to_vec(), culprit.to_hex().into_bytes()));
182+ let signature = request.author.now();
183+ let id = braid_engine::commit(
184+ store,
185+ vec![culprit],
186+ changes,
187+ signature.clone(),
188+ signature,
189+ message,
190+ extras,
191+ )?;
192+ store.sync()?;
193+ Ok(id)
194+}
195+
196+/// The first line of a message that is not blank, trimmed.
197+fn subject(message: &[u8]) -> String {
198+ String::from_utf8_lossy(message)
199+ .lines()
200+ .map(str::trim)
201+ .find(|line| !line.is_empty())
202+ .unwrap_or("")
203+ .to_owned()
204+}
205+
130206 fn describe(entry: Option<&EntryKind>) -> String {
131207 match entry {
132208 None => "absent".to_owned(),
@@ -219,6 +295,8 @@
219295 #[test]
220296 fn describing_entries() {
221297 assert_eq!(describe(None), "absent");
298+ assert_eq!(subject(b"\n Fix the parser \nmore\n"), "Fix the parser");
299+ assert_eq!(subject(b""), "");
222300 let blob = ObjectId::hash(Kind::Blob, b"x");
223301 assert_eq!(
224302 describe(Some(&EntryKind::File { blob, size: 1 })),
modified crates/wc/src/error.rs +21 −0
@@ -233,6 +233,27 @@
233233 index: usize,
234234 },
235235
236+ /// A changeset without parents cannot be reverted: there is nothing to
237+ /// go back to.
238+ #[error("changeset {} has no parent, so there is nothing to revert it to", .0.short())]
239+ RevertRoot(ObjectId),
240+
241+ /// A merge is reverted only on request, against its first parent.
242+ #[error(
243+ "changeset {} is a merge of {parents} parents: pass --mainline 1 to undo what it brought in against its first parent",
244+ .changeset.short()
245+ )]
246+ RevertMerge {
247+ /// The merge.
248+ changeset: ObjectId,
249+ /// How many parents it has.
250+ parents: usize,
251+ },
252+
253+ /// The changeset changes no file, so its revert would change none.
254+ #[error("changeset {} changes no file against its first parent: there is nothing to revert", .0.short())]
255+ NothingToRevert(ObjectId),
256+
236257 /// The workspace's base changed while its changesets were landing
237258 /// somewhere else.
238259 #[error(
modified crates/wc/src/lib.rs +4 −3
@@ -40,8 +40,9 @@
4040 //! - [`Workspace::update`] brings the workspace onto the branch's head,
4141 //! rebasing its own changesets; conflicts are written with markers.
4242 //! - [`create_change`] and [`land_change`] make and land a changeset
43-//! without any working copy; [`land_stack`] lands a stack of them made
44-//! elsewhere, as a hub does.
43+//! without any working copy; [`create_revert`] makes one that undoes
44+//! another; [`land_stack`] lands a stack of them made elsewhere, as a hub
45+//! does.
4546 //! - [`Workspace::stack`] and [`Workspace::adopt`] split a landing in two,
4647 //! for a repository whose branches live on a hub: what to land there,
4748 //! and moving onto the head that holds it afterwards.
@@ -83,7 +84,7 @@
8384 mod workspace;
8485
8586 pub use blocker::Blocker;
86-pub use change::{ChangeRequest, Expect, create_change, land_change};
87+pub use change::{ChangeRequest, Expect, RevertRequest, create_change, create_revert, land_change};
8788 pub use error::Error;
8889 pub use fsprobe::FileSystem;
8990 pub use identity::Identity;
added crates/wc/tests/revert.rs +188 −0
@@ -0,0 +1,188 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Reverting a changeset: the revert undoes it whole, modes and links
5+//! included, and lands like any change, rebased onto a head that moved on,
6+//! with conflicts where later work touched the same lines.
7+
8+mod common;
9+
10+use braid_engine::{AGENT, REBASED_FROM, REVERTS, read_changeset};
11+use braid_format::{ChangeOp, GitId, ObjectId};
12+use braid_wc::{Error, Landed, RevertRequest, create_revert, land_change};
13+use common::{Fixture, ada};
14+
15+fn revert(f: &Fixture, culprit: ObjectId, allow_merge: bool) -> Result<ObjectId, Error> {
16+ create_revert(
17+ f.repo.store(),
18+ &RevertRequest {
19+ culprit,
20+ allow_merge,
21+ author: ada(),
22+ agent: "reverter".to_owned(),
23+ },
24+ )
25+}
26+
27+fn land(f: &Fixture, change: ObjectId) -> Landed {
28+ land_change(f.repo.store(), "main", change, "reverter", &ada())
29+ .unwrap()
30+ .landed
31+}
32+
33+fn root(f: &Fixture, id: ObjectId) -> ObjectId {
34+ read_changeset(f.repo.store(), id).unwrap().root
35+}
36+
37+fn gitlink(byte: u8) -> ChangeOp {
38+ ChangeOp::Gitlink {
39+ commit: GitId::Sha1([byte; 20]),
40+ }
41+}
42+
43+#[test]
44+fn a_revert_undoes_adds_edits_deletes_and_modes() {
45+ let f = Fixture::new();
46+ let base = f.commit(
47+ &[],
48+ vec![
49+ ("edit", f.file("1\n2\n")),
50+ ("gone", f.file("bye\n")),
51+ ("run", f.file("echo\n")),
52+ ("link", f.symlink(b"edit")),
53+ ("sub", gitlink(1)),
54+ ("dir/file", f.file("d\n")),
55+ ],
56+ );
57+ f.set_branch("main", base);
58+ let culprit = f.commit(
59+ &[base],
60+ vec![
61+ ("dir", f.file("now a file\n")),
62+ ("dir/file", ChangeOp::Delete),
63+ ("edit", f.file("1\nbad\n")),
64+ ("gone", ChangeOp::Delete),
65+ ("link", f.symlink(b"run")),
66+ ("new/deep", f.file("added\n")),
67+ ("run", f.exec("echo\n")),
68+ ("sub", gitlink(2)),
69+ ],
70+ );
71+ assert!(matches!(land(&f, culprit), Landed::FastForward(_)));
72+
73+ let id = revert(&f, culprit, false).unwrap();
74+ let made = read_changeset(f.repo.store(), id).unwrap();
75+ assert_eq!(made.parents, [culprit]);
76+ assert_eq!(made.root, root(&f, base));
77+ assert_eq!(
78+ String::from_utf8(made.message).unwrap(),
79+ format!("Revert \"test change\"\n\nThis reverts changeset {culprit}.\n")
80+ );
81+ assert_eq!(
82+ made.extras,
83+ [
84+ (AGENT.to_vec(), b"reverter".to_vec()),
85+ (REVERTS.to_vec(), culprit.to_hex().into_bytes()),
86+ ]
87+ );
88+ // Built on the head: the branch fast-forwards to it.
89+ assert_eq!(land(&f, id), Landed::FastForward(id));
90+ assert_eq!(root(&f, f.head("main").unwrap()), root(&f, base));
91+}
92+
93+#[test]
94+fn a_revert_rebases_over_later_unrelated_work() {
95+ let f = Fixture::new();
96+ let base = f.commit(
97+ &[],
98+ vec![("a", f.file("1\n2\n3\n4\n5\n")), ("b", f.file("b\n"))],
99+ );
100+ let culprit = f.commit(&[base], vec![("a", f.file("1\n2\nbad\n4\n5\n"))]);
101+ let later = f.commit(
102+ &[culprit],
103+ vec![("a", f.file("one\n2\nbad\n4\n5\n")), ("c", f.file("c\n"))],
104+ );
105+ f.set_branch("main", later);
106+
107+ let id = revert(&f, culprit, false).unwrap();
108+ let Landed::Rebased(landed) = land(&f, id) else {
109+ panic!("expected a rebase");
110+ };
111+ assert_eq!(f.head("main"), Some(landed));
112+ let expected = f.commit(&[later], vec![("a", f.file("one\n2\n3\n4\n5\n"))]);
113+ assert_eq!(root(&f, landed), root(&f, expected));
114+ // The rebased revert still says what it reverts, and where it came from.
115+ let extras = read_changeset(f.repo.store(), landed).unwrap().extras;
116+ assert_eq!(
117+ extras,
118+ [
119+ (AGENT.to_vec(), b"reverter".to_vec()),
120+ (REVERTS.to_vec(), culprit.to_hex().into_bytes()),
121+ (REBASED_FROM.to_vec(), id.to_hex().into_bytes()),
122+ ]
123+ );
124+}
125+
126+#[test]
127+fn a_revert_that_later_work_conflicts_with_does_not_move_the_branch() {
128+ let f = Fixture::new();
129+ let base = f.commit(&[], vec![("a", f.file("1\n2\n3\n"))]);
130+ let culprit = f.commit(&[base], vec![("a", f.file("1\nbad\n3\n"))]);
131+ let later = f.commit(&[culprit], vec![("a", f.file("1\nworse\n3\n"))]);
132+ f.set_branch("main", later);
133+
134+ let id = revert(&f, culprit, false).unwrap();
135+ let Landed::Conflicts { change, conflicts } = land(&f, id) else {
136+ panic!("expected conflicts");
137+ };
138+ assert_eq!(change, id);
139+ assert_eq!(conflicts.len(), 1);
140+ assert_eq!(conflicts[0].path, b"a");
141+ assert_eq!(conflicts[0].kind.code(), "CONTENT");
142+ assert_eq!(f.head("main"), Some(later));
143+}
144+
145+#[test]
146+fn the_reverted_change_landed_again_is_already_applied() {
147+ // As the simulation's regression test has it: a change that landed
148+ // once never lands a second time over its revert.
149+ let f = Fixture::new();
150+ let base = f.commit(&[], vec![("f", f.file("1\n")), ("g", f.file("1\n"))]);
151+ let ours = f.commit(&[base], vec![("g", f.file("2\n"))]);
152+ let theirs = f.commit(&[base], vec![("f", f.file("2\n"))]);
153+ f.set_branch("main", ours);
154+ let Landed::Rebased(rebased) = land(&f, theirs) else {
155+ panic!("expected a rebase");
156+ };
157+ let id = revert(&f, rebased, false).unwrap();
158+ assert_eq!(land(&f, id), Landed::FastForward(id));
159+ assert_eq!(land(&f, theirs), Landed::AlreadyApplied);
160+ assert_eq!(land(&f, rebased), Landed::AlreadyApplied);
161+ assert_eq!(f.head("main"), Some(id));
162+ // And reverting the revert puts the change back.
163+ let again = revert(&f, id, false).unwrap();
164+ assert_eq!(land(&f, again), Landed::FastForward(again));
165+ assert_eq!(root(&f, again), root(&f, rebased));
166+}
167+
168+#[test]
169+fn roots_empty_changes_and_merges_are_refused() {
170+ let f = Fixture::new();
171+ let base = f.commit(&[], vec![("a", f.file("a\n"))]);
172+ assert!(matches!(revert(&f, base, false), Err(Error::RevertRoot(id)) if id == base));
173+ let empty = f.commit(&[base], Vec::new());
174+ assert!(matches!(
175+ revert(&f, empty, false),
176+ Err(Error::NothingToRevert(id)) if id == empty
177+ ));
178+ let side = f.commit(&[base], vec![("s", f.file("s\n"))]);
179+ let merge = f.commit(&[base, side], vec![("s", f.file("s\n"))]);
180+ assert!(matches!(
181+ revert(&f, merge, false),
182+ Err(Error::RevertMerge { parents: 2, .. })
183+ ));
184+ // Asked for, it undoes what the merge brought in against its first
185+ // parent.
186+ let id = revert(&f, merge, true).unwrap();
187+ assert_eq!(root(&f, id), root(&f, base));
188+}